Search is not available for this dataset
text string | meta dict |
|---|---|
/*
ODE: a program to get optime Runge-Kutta and multi-steps methods.
Copyright 2011-2019, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file rk_5_4.c
* \brief Source file to optimize Runge-Kutta 5 steps 4th order methods.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2011-2019.
*/
#define _GNU_SOURCE
#include <string.h>
#include <math.h>
#include <libxml/parser.h>
#include <glib.h>
#include <libintl.h>
#include <gsl/gsl_rng.h>
#include "config.h"
#include "utils.h"
#include "optimize.h"
#include "rk.h"
#include "rk_5_4.h"
#define DEBUG_RK_5_4 0 ///< macro to debug.
/**
* Function to obtain the coefficients of a 5 steps 4th order Runge-Kutta
* method.
*/
int
rk_tb_5_4 (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *tb, *r;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t5 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
b21 (tb) = r[2];
t3 (tb) = r[3];
b31 (tb) = r[4];
b32 (tb) = r[5];
t4 (tb) = r[6];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = t4 (tb);
E[0] = 0.5L;
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = D[0] * t4 (tb);
E[1] = 1.L / 3.L;
A[2] = A[1] * t1 (tb);
B[2] = B[1] * t2 (tb);
C[2] = C[1] * t3 (tb);
D[2] = D[1] * t4 (tb);
E[2] = 0.25L;
A[3] = D[3] = 0.L;
B[3] = b21 (tb) * t1 (tb) * (t2 (tb) - t4 (tb));
C[3] = (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb)) * (t3 (tb) - t4 (tb));
E[3] = 0.125L - 1.L / 6.L * t4 (tb);
solve_4 (A, B, C, D, E);
if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))
return 0;
b54 (tb) = E[3];
b53 (tb) = E[2];
b52 (tb) = E[1];
b51 (tb) = E[0];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = 1.L / 6.L - b52 (tb) * b21 (tb) * t1 (tb)
- b53 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb));
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = 1.L / 12.L - b52 (tb) * b21 (tb) * sqr (t1 (tb))
- b53 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)));
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = 1.L / 24.L - b53 (tb) * b32 (tb) * b21 (tb) * t1 (tb);
solve_3 (A, B, C, D);
b43 (tb) = D[2] / b54 (tb);
if (isnan (b43 (tb)))
return 0;
b42 (tb) = D[1] / b54 (tb);
if (isnan (b42 (tb)))
return 0;
b41 (tb) = D[0] / b54 (tb);
if (isnan (b41 (tb)))
return 0;
rk_b_5 (tb);
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 5 steps 4th order, 5th order in
* equations depending only on time, Runge-Kutta method.
*/
int
rk_tb_5_4t (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *tb, *r;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4t: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t5 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
t3 (tb) = r[2];
t4 (tb) = r[3];
b31 (tb) = r[4];
b21 (tb) = r[5];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = t4 (tb);
E[0] = 0.5L;
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = D[0] * t4 (tb);
E[1] = 1.L / 3.L;
A[2] = A[1] * t1 (tb);
B[2] = B[1] * t2 (tb);
C[2] = C[1] * t3 (tb);
D[2] = D[1] * t4 (tb);
E[2] = 0.25L;
A[3] = A[2] * t1 (tb);
B[3] = B[2] * t2 (tb);
C[3] = C[2] * t3 (tb);
D[3] = D[2] * t4 (tb);
E[3] = 0.2L;
solve_4 (A, B, C, D, E);
if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))
return 0;
b54 (tb) = E[3];
b53 (tb) = E[2];
b52 (tb) = E[1];
b51 (tb) = E[0];
b32 (tb) = (1.L / 6.L * t4 (tb) - 0.125L
- t1 (tb) * (b52 (tb) * b21 (tb) * (t4 (tb) - t2 (tb))
+ b53 (tb) * b31 (tb) * (t4 (tb) - t3 (tb))))
/ (b53 (tb) * t2 (tb) * (t4 (tb) - t3 (tb)));
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = 1.L / 6.L - b52 (tb) * b21 (tb) * t1 (tb)
- b53 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb));
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = 1.L / 12.L - b52 (tb) * b21 (tb) * sqr (t1 (tb))
- b53 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)));
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = 1.L / 24.L - b53 (tb) * b32 (tb) * b21 (tb) * t1 (tb);
solve_3 (A, B, C, D);
b43 (tb) = D[2] / b54 (tb);
if (isnan (b43 (tb)))
return 0;
b42 (tb) = D[1] / b54 (tb);
if (isnan (b42 (tb)))
return 0;
b41 (tb) = D[0] / b54 (tb);
if (isnan (b41 (tb)))
return 0;
rk_b_5 (tb);
#if DEBUG_RK_5_4
rk_print_tb (optimize, "rk_tb_5_4t", stderr);
fprintf (stderr, "rk_tb_5_4t: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 5 steps 3rd-4th order Runge-Kutta
* pair.
*/
int
rk_tb_5_4p (Optimize * optimize) ///< Optimize struct.
{
long double A[3], B[3], C[3], D[3];
long double *tb;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4p: start\n");
#endif
if (!rk_tb_5_4 (optimize))
return 0;
tb = optimize->coefficient;
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = 0.5L;
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = 1.L / 3.L;
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = 1.L / 6.L;
solve_3 (A, B, C, D);
if (isnan (D[0]) || isnan (D[1]) || isnan (D[2]))
return 0;
e53 (tb) = D[2];
e52 (tb) = D[1];
e51 (tb) = D[0];
rk_e_5 (tb);
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4p: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 5 steps 3th-4th order, 4th-5th order
* in equations depending only on time, Runge-Kutta pair.
*/
int
rk_tb_5_4tp (Optimize * optimize) ///< Optimize struct.
{
long double A[4], B[4], C[4], D[4], E[4];
long double *tb, *r;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_tb_5_4tp: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t5 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
t3 (tb) = r[2];
t4 (tb) = r[3];
b31 (tb) = r[4];
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = t4 (tb);
E[0] = 0.5L;
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = D[0] * t4 (tb);
E[1] = 1.L / 3.L;
A[2] = A[1] * t1 (tb);
B[2] = B[1] * t2 (tb);
C[2] = C[1] * t3 (tb);
D[2] = D[1] * t4 (tb);
E[2] = 0.25L;
A[3] = A[2] * t1 (tb);
B[3] = B[2] * t2 (tb);
C[3] = C[2] * t3 (tb);
D[3] = D[2] * t4 (tb);
E[3] = 0.2L;
solve_4 (A, B, C, D, E);
if (isnan (E[0]) || isnan (E[1]) || isnan (E[2]) || isnan (E[3]))
return 0;
b54 (tb) = E[3];
b53 (tb) = E[2];
b52 (tb) = E[1];
b51 (tb) = E[0];
e53 (tb) = (0.25L - 1.L / 3.L * t1 (tb)
- (1.L / 3.L - 0.5L * t1 (tb)) * t2 (tb))
/ (t3 (tb) * (t3 (tb) - t2 (tb)) * (t3 (tb) - t1 (tb)));
if (isnan (e53 (tb)))
return 0;
e52 (tb) = (1.L / 3.L - 0.5L * t1 (tb)
- t3 (tb) * (t3 (tb) - t1 (tb)) * e53 (tb))
/ (t2 (tb) * (t2 (tb) - t1 (tb)));
if (isnan (e52 (tb)))
return 0;
e51 (tb) = (0.5L - t2 (tb) * e52 (tb) - t3 (tb) * e53 (tb)) / t1 (tb);
if (isnan (e51 (tb)))
return 0;
b21 (tb) = (1.L / 6.L * b53 (tb) * (t4 (tb) - t3 (tb))
+ e53 (tb) * (0.125L - 1.L / 6.L * t4 (tb)))
/ (t1 (tb) * (e52 (tb) * b53 (tb) * (t4 (tb) - t3 (tb))
- e53 (tb) * b52 (tb) * (t4 (tb) - t2 (tb))));
if (isnan (b21 (tb)))
return 0;
b32 (tb) = (1.L / 6.L * t4 (tb) - 0.125L
- t1 (tb) * (b52 (tb) * b21 (tb) * (t4 (tb) - t2 (tb))
+ b53 (tb) * b31 (tb) * (t4 (tb) - t3 (tb))))
/ (b53 (tb) * t2 (tb) * (t4 (tb) - t3 (tb)));
if (isnan (b32 (tb)))
return 0;
A[0] = t1 (tb);
B[0] = t2 (tb);
C[0] = t3 (tb);
D[0] = 1.L / 6.L - b52 (tb) * b21 (tb) * t1 (tb)
- b53 (tb) * (b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb));
A[1] = A[0] * t1 (tb);
B[1] = B[0] * t2 (tb);
C[1] = C[0] * t3 (tb);
D[1] = 1.L / 12.L - b52 (tb) * b21 (tb) * sqr (t1 (tb))
- b53 (tb) * (b31 (tb) * sqr (t1 (tb)) + b32 (tb) * sqr (t2 (tb)));
A[2] = 0.L;
B[2] = b21 (tb) * t1 (tb);
C[2] = b31 (tb) * t1 (tb) + b32 (tb) * t2 (tb);
D[2] = 1.L / 24.L - b53 (tb) * b32 (tb) * b21 (tb) * t1 (tb);
solve_3 (A, B, C, D);
b43 (tb) = D[2] / b54 (tb);
if (isnan (b43 (tb)))
return 0;
b42 (tb) = D[1] / b54 (tb);
if (isnan (b42 (tb)))
return 0;
b41 (tb) = D[0] / b54 (tb);
if (isnan (b41 (tb)))
return 0;
rk_b_5 (tb);
rk_e_5 (tb);
#if DEBUG_RK_5_4
rk_print_tb (optimize, "rk_tb_5_4tp", stderr);
fprintf (stderr, "rk_tb_5_4tp: end\n");
#endif
return 1;
}
/**
* Function to calculate the objective function of a 5 steps 4th order
* Runge-Kutta method.
*
* \return objective function value.
*/
long double
rk_objective_tb_5_4 (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4: start\n");
#endif
tb = rk->tb->coefficient;
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (b43 (tb) < 0.L)
o += b43 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b54 (tb) < 0.L)
o += b54 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_5_4: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 5 steps 4th order, 5th
* order in equations depending only on time, Runge-Kutta method.
*
* \return objective function value.
*/
long double
rk_objective_tb_5_4t (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4t: start\n");
#endif
tb = rk->tb->coefficient;
#if DEBUG_RK_5_4
rk_print_tb (optimize, "rk_objective_tb_5_4t", stderr);
#endif
o = fminl (0.L, b20 (tb));
if (b21 (tb) < 0.L)
o += b21 (tb);
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b32 (tb) < 0.L)
o += b32 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (b43 (tb) < 0.L)
o += b43 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b54 (tb) < 0.L)
o += b54 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4t: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_5_4t: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 5 steps 3rd-4th order
* Runge-Kutta pair.
*
* \return objective function value.
*/
long double
rk_objective_tb_5_4p (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4p: start\n");
#endif
tb = rk->tb->coefficient;
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (b43 (tb) < 0.L)
o += b43 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b54 (tb) < 0.L)
o += b54 (tb);
if (e50 (tb) < 0.L)
o += e50 (tb);
if (e51 (tb) < 0.L)
o += e51 (tb);
if (e52 (tb) < 0.L)
o += e52 (tb);
if (e53 (tb) < 0.L)
o += e53 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4p: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_5_4p: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 5 steps 3th-4th order,
* 4th-5th order in equations depending only on time, Runge-Kutta pair.
*
* \return objective function value.
*/
long double
rk_objective_tb_5_4tp (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4t: start\n");
#endif
tb = rk->tb->coefficient;
#if DEBUG_RK_5_4
rk_print_tb (optimize, "rk_objective_tb_5_4tp", stderr);
#endif
o = fminl (0.L, b20 (tb));
if (b21 (tb) < 0.L)
o += b21 (tb);
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b32 (tb) < 0.L)
o += b32 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b41 (tb) < 0.L)
o += b41 (tb);
if (b42 (tb) < 0.L)
o += b42 (tb);
if (b43 (tb) < 0.L)
o += b43 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b51 (tb) < 0.L)
o += b51 (tb);
if (b52 (tb) < 0.L)
o += b52 (tb);
if (b53 (tb) < 0.L)
o += b53 (tb);
if (b54 (tb) < 0.L)
o += b54 (tb);
if (e50 (tb) < 0.L)
o += e50 (tb);
if (e51 (tb) < 0.L)
o += e51 (tb);
if (e52 (tb) < 0.L)
o += e52 (tb);
if (e53 (tb) < 0.L)
o += e53 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L, fmaxl (t1 (tb), fmaxl (t2 (tb), fmaxl (t3 (tb), t4 (tb)))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_5_4
fprintf (stderr, "rk_objective_tb_5_4tp: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_5_4tp: end\n");
#endif
return o;
}
| {
"alphanum_fraction": 0.506816,
"avg_line_length": 25.6147540984,
"ext": "c",
"hexsha": "d604974d932739a3c5852cbd6c5cccf605a863ab",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/ode",
"max_forks_repo_path": "rk_5_4.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/ode",
"max_issues_repo_path": "rk_5_4.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/ode",
"max_stars_repo_path": "rk_5_4.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7059,
"size": 15625
} |
///
/// @file
///
/// @author Mirko Myllykoski (mirkom@cs.umu.se), Umeå University
///
/// @internal LICENSE
///
/// Copyright (c) 2019-2020, Umeå Universitet
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
///
/// 2. Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// 3. Neither the name of the copyright holder nor the names of its
/// contributors may be used to endorse or promote products derived from this
/// software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///
#include <starneig_test_config.h>
#include <starneig/configuration.h>
#include "solvers.h"
#include "../common/common.h"
#include "../common/parse.h"
#include "../common/local_pencil.h"
#ifdef STARNEIG_ENABLE_MPI
#include "../common/starneig_pencil.h"
#endif
#include "../common/threads.h"
#include <starneig/starneig.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cblas.h>
#include <omp.h>
#ifdef MAGMA_FOUND
#include <cuda_runtime_api.h>
#include <cuda.h>
#include <magma_auxiliary.h>
#include <magma_d.h>
#endif
static hook_solver_state_t lapack_prepare(
int argc, char * const *argv, struct hook_data_env *env)
{
return (hook_solver_state_t) env->data;
}
static int lapack_finalize(hook_solver_state_t state, struct hook_data_env *env)
{
return 0;
}
static int lapack_run(hook_solver_state_t state)
{
pencil_t data = (pencil_t) state;
extern void dgehrd_(
int const *, // the order of the matrix A
int const *, // left bound
int const *, // right bound
double *, // input/output matrix
int const *, // input/output matrix leading dimension
double *, // tau (scalar factors)
double *, // work space
int const *, // work space size
int *); // info
extern void dormhr_(
char const *, // side
char const *, // transpose
int const *, // row count
int const *, // column count
int const *, // left bound
int const *, // right bound
double const *, // elementary reflectors
int const *, // elementary reflector leading dimension
double const *, // scalar factors (tau)
double *, // input/output matrix
int const *, // input/output matrix leading dimension
double *, // work space
int const *, // work space size
int *); // info
extern void dgeqrf_(int const *, int const *, double *, int const *,
double *, double *, int const *, int *);
extern void dormqr_(char const *, char const *, int const *, int const *,
int const *, double const *, int const *, double const *, double *,
int const *, double*, const int *, int *);
extern void dgghd3_(char const *, char const *, int const *, int const *,
int const *, double *, int const *, double *, int const *, double *,
int const *, double *, int const *, double *, int const *, int *);
int n = LOCAL_MATRIX_N(data->mat_a);
double *A = LOCAL_MATRIX_PTR(data->mat_a);
int ldA = LOCAL_MATRIX_LD(data->mat_a);
double *Q = LOCAL_MATRIX_PTR(data->mat_q);
int ldQ = LOCAL_MATRIX_LD(data->mat_q);
double *B = NULL;
int ldB = 0;
double *Z = NULL;
int ldZ = 0;
double *tau = NULL;
double *work = NULL;
int info, ilo = 1, ihi = n;
threads_set_mode(THREADS_MODE_LAPACK);
if (data->mat_b != NULL) {
B = LOCAL_MATRIX_PTR(data->mat_b);
ldB = LOCAL_MATRIX_LD(data->mat_b);
Z = LOCAL_MATRIX_PTR(data->mat_z);
ldZ = LOCAL_MATRIX_LD(data->mat_z);
//
// allocate workspace
//
int lwork = 0;
{
int _lwork = -1;
double dlwork;
dgeqrf_(&n, &n, B, &ldB, tau, &dlwork, &_lwork, &info);
if (info != 0)
goto cleanup;
lwork = MAX(lwork, dlwork);
}
{
int _lwork = -1;
double dlwork;
dormqr_("L", "T", &n, &n, &n,
B, &ldB, tau, A, &ldA, &dlwork, &_lwork, &info);
if (info != 0)
goto cleanup;
lwork = MAX(lwork, dlwork);
}
{
int _lwork = -1;
double dlwork;
dormqr_("R", "N", &n, &n, &n,
B, &ldB, tau, Q, &ldQ, &dlwork, &_lwork, &info);
if (info != 0)
goto cleanup;
lwork = MAX(lwork, dlwork);
}
{
int _lwork = -1;
double dlwork;
dgghd3_("V", "V", &n, &ilo, &ihi,
A, &ldA, B, &ldB, Q, &ldQ, Z, &ldZ, &dlwork, &_lwork, &info);
if (info != 0)
goto cleanup;
lwork = MAX(lwork, dlwork);
}
tau = malloc(n*sizeof(double));
work = malloc(lwork*sizeof(double));
//
// reduce
//
// form B = ~Q * R
dgeqrf_(&n, &n, B, &ldB, tau, work, &lwork, &info);
if (info != 0)
goto cleanup;
// A <- ~Q^T * A
dormqr_("L", "T", &n, &n, &n, B, &ldB, tau, A, &ldA, work, &lwork,
&info);
if (info != 0)
goto cleanup;
// Q <- Q * ~Q
dormqr_("R", "N", &n, &n, &n, B, &ldB, tau, Q, &ldQ, work, &lwork,
&info);
if (info != 0)
goto cleanup;
// clean B (B <- R)
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
B[(size_t)i*ldB+j] = 0.0;
// reduce (A,B) to Hessenberg-triangular form
dgghd3_("V", "V", &n, &ilo, &ihi,
A, &ldA, B, &ldB, Q, &ldQ, Z, &ldZ, work, &lwork, &info);
if (info != 0)
goto cleanup;
}
else {
int lwork = -1;
double dlwork;
// request optimal work space size
dgehrd_(&n, &ilo, &ihi, A, &ldA,
tau, &dlwork, &lwork, &info);
if (info != 0)
goto cleanup;
lwork = dlwork;
work = malloc(lwork*sizeof(double));
tau = malloc(n*sizeof(double));
// reduce
dgehrd_(&n, &ilo, &ihi, A, &ldA,
tau, work, &lwork, &info);
if (info != 0)
goto cleanup;
free(work);
work = NULL;
// request optimal work space size
lwork = -1;
dormhr_("Right", "No transpose", &n, &n, &ilo, &ihi, A, &ldA, tau,
Q, &ldQ, &dlwork, &lwork, &info);
if (info != 0)
goto cleanup;
lwork = dlwork;
work = malloc(lwork*sizeof(double));
// form Q
dormhr_("Right", "No transpose", &n, &n, &ilo, &ihi, A, &ldA, tau,
Q, &ldQ, work, &lwork, &info);
if (info != 0)
goto cleanup;
for (int i = 0; i < n; i++)
for (int j = i+2; j < n; j++)
A[i*ldA+j] = 0.0;
}
cleanup:
threads_set_mode(THREADS_MODE_DEFAULT);
free(work);
free(tau);
return info;
}
const struct hook_solver hessenberg_lapack_solver = {
.name = "lapack",
.desc = "LAPACK's dgehrd/dgghrd subroutine",
.formats = (hook_data_format_t[]) { HOOK_DATA_FORMAT_PENCIL_LOCAL, 0 },
.prepare = &lapack_prepare,
.finalize = &lapack_finalize,
.run = &lapack_run
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#if defined(PDGEHRD_FOUND) && defined(PDORMHR_FOUND) && defined(PDLASET_FOUND)
static hook_solver_state_t scalapack_prepare(
int argc, char * const *argv, struct hook_data_env *env)
{
return env;
}
static int scalapack_finalize(
hook_solver_state_t state, struct hook_data_env *env)
{
return 0;
}
static int has_valid_descr(
int matrix_size, int section_size, const starneig_blacs_descr_t *descr)
{
if (descr->m != matrix_size || descr->n != matrix_size)
return 0;
if (descr->sm != section_size || descr->sn != section_size)
return 0;
return 1;
}
static int scalapack_run(hook_solver_state_t state)
{
extern void pdgehrd_(int const *, int const *, int const *, double *,
int const *, int const *, const starneig_blacs_descr_t *, double *,
double *, int const *, int *);
extern void pdormhr_(char const *, char const *, int const *, int const *,
int const *, int const *, double *, int const *, int const *,
const starneig_blacs_descr_t *, double *, double *, int const *,
int const *, const starneig_blacs_descr_t *, double *, int const *,
int *);
extern void pdlaset_(char const *, int const *, int const *,
double const *, double const *, double *, int const *, int const *,
const starneig_blacs_descr_t *);
threads_set_mode(THREADS_MODE_SCALAPACK);
struct hook_data_env *env = state;
pencil_t pencil = (pencil_t) env->data;
if (pencil->mat_a == NULL) {
fprintf(stderr, "Missing matrix A.\n");
return -1;
}
if (pencil->mat_b != NULL) {
fprintf(stderr, "Solver does not support generalized cases.\n");
return -1;
}
int n = STARNEIG_MATRIX_N(pencil->mat_a);
int sn = STARNEIG_MATRIX_BN(pencil->mat_a);
starneig_distr_t distr = STARNEIG_MATRIX_DISTR(pencil->mat_a);
starneig_blacs_context_t context = starneig_distr_to_blacs_context(distr);
starneig_blacs_descr_t desc_a, desc_q;
double *local_a, *local_q;
STARNEIG_BLACS_MATRIX_DESCR_LOCAL(
pencil->mat_a, context, &desc_a, (void **)&local_a);
STARNEIG_BLACS_MATRIX_DESCR_LOCAL(
pencil->mat_q, context, &desc_q, (void **)&local_q);
if (!has_valid_descr(n, sn, &desc_a)) {
fprintf(stderr, "Matrix A has invalid dimensions.\n");
return -1;
}
if (pencil->mat_q != NULL && !has_valid_descr(n, sn, &desc_q)) {
fprintf(stderr, "Matrix Q has invalid dimension.\n");
return -1;
}
int ilo = 1, ihi = n, ia = 1, ja = 1, ic = 1, jc = 1, lwork, info;
double *work = NULL, *tau = NULL, _work;
lwork = -1;
pdgehrd_(&n, &ilo, &ihi, NULL, &ia, &ja, &desc_a, NULL,
&_work, &lwork, &info);
if (info)
goto cleanup;
lwork = _work;
work = malloc(lwork*sizeof(double));
tau = malloc(n*sizeof(double));
pdgehrd_(&n, &ilo, &ihi, local_a, &ia, &ja, &desc_a, tau,
work, &lwork, &info);
if (info)
goto cleanup;
lwork = -1;
pdormhr_("Right", "No transpose", &n, &n, &ilo, &ihi, NULL,
&ia, &ja, &desc_a, NULL, NULL, &ic, &jc,
&desc_q, &_work, &lwork, &info);
if (info)
goto cleanup;
free(work);
lwork = _work;
work = malloc(lwork*sizeof(double));
pdormhr_("Right", "No transpose", &n, &n, &ilo, &ihi, local_a,
&ia, &ja, &desc_a, tau, local_q, &ic, &jc,
&desc_q, work, &lwork, &info);
{
int nm1 = n-2, one = 1, three = 3;
double dzero = 0.0;
pdlaset_("Lower", &nm1, &nm1, &dzero, &dzero, local_a, &three,
&one, &desc_a);
}
cleanup:
threads_set_mode(THREADS_MODE_DEFAULT);
starneig_blacs_gridexit(context);
free(work);
free(tau);
return info;
}
const struct hook_solver hessenberg_scalapack_solver = {
.name = "scalapack",
.desc = "pdgehrd subroutine from scaLAPACK",
.formats = (hook_data_format_t[]) {
#ifdef STARNEIG_ENABLE_BLACS
HOOK_DATA_FORMAT_PENCIL_BLACS,
#endif
0 },
.prepare = &scalapack_prepare,
.finalize = &scalapack_finalize,
.run = &scalapack_run
};
#endif // PDGEHRD_FOUND
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
struct starpu_state {
int argc;
char * const *argv;
struct hook_data_env *env;
};
static void starpu_print_usage(int argc, char * const *argv)
{
printf(
" --cores [default,(num)} -- Number of CPU cores\n"
" --gpus [default,(num)} -- Number of GPUS\n"
" --tile-size [default,(num)] -- tile size\n"
" --panel-width [default,(num)] -- Panel width\n"
);
}
static int starpu_check_args(int argc, char * const *argv, int *argr)
{
struct multiarg_t arg_cores = read_multiarg(
"--cores", argc, argv, argr, "default", NULL);
struct multiarg_t arg_gpus = read_multiarg(
"--gpus", argc, argv, argr, "default", NULL);
struct multiarg_t tile_size = read_multiarg(
"--tile-size", argc, argv, argr, "default", NULL);
struct multiarg_t panel_width = read_multiarg(
"--panel-width", argc, argv, argr, "default", NULL);
if (arg_cores.type == MULTIARG_INVALID)
return -1;
if (arg_gpus.type == MULTIARG_INVALID)
return -1;
if (tile_size.type == MULTIARG_INVALID ||
(tile_size.type == MULTIARG_INT && tile_size.int_value < 1)) {
fprintf(stderr, "Invalid tile size.\n");
return -1;
}
if (panel_width.type == MULTIARG_INVALID ||
(panel_width.type == MULTIARG_INT && panel_width.int_value < 1)) {
fprintf(stderr, "Invalid panel width.\n");
return -1;
}
return 0;
}
static void starpu_print_args(int argc, char * const *argv)
{
print_multiarg("--cores", argc, argv, "default", NULL);
print_multiarg("--gpus", argc, argv, "default", NULL);
print_multiarg("--tile-size", argc, argv, "default", NULL);
print_multiarg("--panel-width", argc, argv, "default", NULL);
}
static hook_solver_state_t starpu_prepare(
int argc, char * const *argv, struct hook_data_env *env)
{
struct starpu_state *state = malloc(sizeof(struct starpu_state));
state->argc = argc;
state->argv = argv;
state->env = env;
struct multiarg_t arg_cores = read_multiarg(
"--cores", argc, argv, NULL, "default", NULL);
struct multiarg_t arg_gpus = read_multiarg(
"--gpus", argc, argv, NULL, "default", NULL);
int cores = STARNEIG_USE_ALL;
if (arg_cores.type == MULTIARG_INT)
cores = arg_cores.int_value;
int gpus = STARNEIG_USE_ALL;
if (arg_gpus.type == MULTIARG_INT)
gpus = arg_gpus.int_value;
#ifdef STARNEIG_ENABLE_MPI
if (env->format == HOOK_DATA_FORMAT_PENCIL_STARNEIG ||
env->format == HOOK_DATA_FORMAT_PENCIL_BLACS)
starneig_node_init(cores, gpus, STARNEIG_FAST_DM);
else
#endif
starneig_node_init(
cores, gpus, STARNEIG_HINT_SM | STARNEIG_AWAKE_WORKERS);
return state;
}
static int starpu_finalize(hook_solver_state_t state, struct hook_data_env *env)
{
if (state == NULL)
return 0;
starneig_node_finalize();
free(state);
return 0;
}
static int starpu_run(hook_solver_state_t state)
{
int argc = ((struct starpu_state *) state)->argc;
char * const *argv = ((struct starpu_state *) state)->argv;
struct hook_data_env *env = ((struct starpu_state *) state)->env;
struct starneig_hessenberg_conf conf;
starneig_hessenberg_init_conf(&conf);
struct multiarg_t tile_size = read_multiarg(
"--tile-size", argc, argv, NULL, "default", NULL);
struct multiarg_t panel_width = read_multiarg(
"--panel-width", argc, argv, NULL, "default", NULL);
if (tile_size.type == MULTIARG_INT)
conf.tile_size = tile_size.int_value;
if (panel_width.type == MULTIARG_INT)
conf.panel_width = panel_width.int_value;
int ret = 0;
if (env->format == HOOK_DATA_FORMAT_PENCIL_LOCAL) {
pencil_t pencil = (pencil_t) env->data;
if (pencil->mat_b != NULL) {
ret = starneig_GEP_SM_HessenbergTriangular(
LOCAL_MATRIX_N(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_b), LOCAL_MATRIX_LD(pencil->mat_b),
LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q),
LOCAL_MATRIX_PTR(pencil->mat_z), LOCAL_MATRIX_LD(pencil->mat_z)
);
}
else {
ret = starneig_SEP_SM_Hessenberg_expert(&conf,
LOCAL_MATRIX_N(pencil->mat_a), 0, LOCAL_MATRIX_N(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q)
);
}
}
#ifdef STARNEIG_ENABLE_MPI
if (env->format == HOOK_DATA_FORMAT_PENCIL_BLACS) {
pencil_t pencil = (pencil_t) env->data;
if (pencil->mat_b != NULL) {
#ifdef STARNEIG_GEP_DM_HESSENBERGTRIANGULAR
ret = starneig_GEP_DM_HessenbergTriangular(
STARNEIG_MATRIX_HANDLE(pencil->mat_a),
STARNEIG_MATRIX_HANDLE(pencil->mat_b),
STARNEIG_MATRIX_HANDLE(pencil->mat_q),
STARNEIG_MATRIX_HANDLE(pencil->mat_z));
#else
fprintf(stderr,
"Solver does not support generalized cases in distributed "
"memory.\n");
return -1;
#endif
}
else {
ret = starneig_SEP_DM_Hessenberg(
STARNEIG_MATRIX_HANDLE(pencil->mat_a),
STARNEIG_MATRIX_HANDLE(pencil->mat_q));
}
}
#endif
return ret;
}
const struct hook_solver hessenberg_starpu_solver = {
.name = "starneig",
.desc = "StarPU based subroutine",
.formats = (hook_data_format_t[]) {
HOOK_DATA_FORMAT_PENCIL_LOCAL,
#ifdef STARNEIG_ENABLE_BLACS
HOOK_DATA_FORMAT_PENCIL_BLACS,
#endif
0 },
.print_usage = &starpu_print_usage,
.print_args = &starpu_print_args,
.check_args = &starpu_check_args,
.prepare = &starpu_prepare,
.finalize = &starpu_finalize,
.run = &starpu_run
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
static void starpu_simple_print_usage(int argc, char * const *argv)
{
printf(
" --cores [default,(num)} -- Number of CPU cores\n"
" --gpus [default,(num)} -- Number of GPUS\n"
);
}
static void starpu_simple_print_args(int argc, char * const *argv)
{
print_multiarg("--cores", argc, argv, "default", NULL);
print_multiarg("--gpus", argc, argv, "default", NULL);
}
static int starpu_simple_check_args(int argc, char * const *argv, int *argr)
{
struct multiarg_t arg_cores = read_multiarg(
"--cores", argc, argv, argr, "default", NULL);
struct multiarg_t arg_gpus = read_multiarg(
"--gpus", argc, argv, argr, "default", NULL);
if (arg_cores.type == MULTIARG_INVALID)
return -1;
if (arg_gpus.type == MULTIARG_INVALID)
return -1;
return 0;
}
static hook_solver_state_t starpu_simple_prepare(
int argc, char * const *argv, struct hook_data_env *env)
{
struct starpu_state *state = malloc(sizeof(struct starpu_state));
state->argc = argc;
state->argv = argv;
state->env = env;
struct multiarg_t arg_cores = read_multiarg(
"--cores", argc, argv, NULL, "default", NULL);
struct multiarg_t arg_gpus = read_multiarg(
"--gpus", argc, argv, NULL, "default", NULL);
int cores = STARNEIG_USE_ALL;
if (arg_cores.type == MULTIARG_INT)
cores = arg_cores.int_value;
int gpus = STARNEIG_USE_ALL;
if (arg_gpus.type == MULTIARG_INT)
gpus = arg_gpus.int_value;
#ifdef STARNEIG_ENABLE_MPI
if (env->format == HOOK_DATA_FORMAT_PENCIL_STARNEIG ||
env->format == HOOK_DATA_FORMAT_PENCIL_BLACS)
starneig_node_init(cores, gpus, STARNEIG_FAST_DM);
else
#endif
starneig_node_init(
cores, gpus, STARNEIG_HINT_SM | STARNEIG_AWAKE_WORKERS);
return state;
}
static int starpu_simple_finalize(
hook_solver_state_t state, struct hook_data_env *env)
{
if (state == NULL)
return 0;
starneig_node_finalize();
free(state);
return 0;
}
static int starpu_simple_run(hook_solver_state_t state)
{
struct hook_data_env *env = ((struct starpu_state *) state)->env;
int ret = 0;
if (env->format == HOOK_DATA_FORMAT_PENCIL_LOCAL) {
pencil_t pencil = (pencil_t) env->data;
if (pencil->mat_b != NULL) {
ret = starneig_GEP_SM_HessenbergTriangular(
LOCAL_MATRIX_N(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_b), LOCAL_MATRIX_LD(pencil->mat_b),
LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q),
LOCAL_MATRIX_PTR(pencil->mat_z), LOCAL_MATRIX_LD(pencil->mat_z)
);
}
else {
ret = starneig_SEP_SM_Hessenberg(LOCAL_MATRIX_N(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_a), LOCAL_MATRIX_LD(pencil->mat_a),
LOCAL_MATRIX_PTR(pencil->mat_q), LOCAL_MATRIX_LD(pencil->mat_q)
);
}
}
#ifdef STARNEIG_ENABLE_MPI
if (env->format == HOOK_DATA_FORMAT_PENCIL_BLACS) {
pencil_t pencil = (pencil_t) env->data;
if (pencil->mat_b != NULL) {
#ifdef STARNEIG_GEP_DM_HESSENBERGTRIANGULAR
ret = starneig_GEP_DM_HessenbergTriangular(
STARNEIG_MATRIX_HANDLE(pencil->mat_a),
STARNEIG_MATRIX_HANDLE(pencil->mat_b),
STARNEIG_MATRIX_HANDLE(pencil->mat_q),
STARNEIG_MATRIX_HANDLE(pencil->mat_z));
#else
fprintf(stderr,
"Solver does not support distributed memory in generalized "
"cases.\n");
return -1;
#endif
}
else {
ret = starneig_SEP_DM_Hessenberg(
STARNEIG_MATRIX_HANDLE(pencil->mat_a),
STARNEIG_MATRIX_HANDLE(pencil->mat_q));
}
}
#endif
return ret;
}
const struct hook_solver hessenberg_starpu_simple_solver = {
.name = "starneig-simple",
.desc = "StarPU based subroutine (simplified interface)",
.formats = (hook_data_format_t[]) {
HOOK_DATA_FORMAT_PENCIL_LOCAL,
#ifdef STARNEIG_ENABLE_BLACS
HOOK_DATA_FORMAT_PENCIL_BLACS,
#endif
0 },
.print_usage = &starpu_simple_print_usage,
.print_args = &starpu_simple_print_args,
.check_args = &starpu_simple_check_args,
.prepare = &starpu_simple_prepare,
.finalize = &starpu_simple_finalize,
.run = &starpu_simple_run
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#ifdef MAGMA_FOUND
static hook_solver_state_t magma_dgehrd_prepare(
int argc, char * const *argv, struct hook_data_env *env)
{
if (magma_init() != MAGMA_SUCCESS)
return NULL;
return (hook_solver_state_t) env->data;
}
static int magma_dgehrd_finalize(
hook_solver_state_t state, struct hook_data_env *env)
{
magma_finalize();
return 0;
}
static int magma_dgehrd_run(hook_solver_state_t state)
{
pencil_t data = (pencil_t) state;
int n = LOCAL_MATRIX_N(data->mat_a);
double *A = LOCAL_MATRIX_PTR(data->mat_a);
double *Q = LOCAL_MATRIX_PTR(data->mat_q);
int ldA = LOCAL_MATRIX_LD(data->mat_a);
int ldQ = LOCAL_MATRIX_LD(data->mat_q);
int info;
double *tau = NULL;
double *work = NULL;
double *dT = NULL;
threads_set_mode(THREADS_MODE_LAPACK);
// request optimal work space size
double _work;
magma_dgehrd(n, 1, n, A, ldA, tau, &_work, -1, dT, &info);
if (info != 0)
goto finalize;
tau = malloc(LOCAL_MATRIX_N(data->mat_a)*sizeof(double));
int lwork = _work;
work = malloc(lwork*sizeof(double));
int nb = magma_get_dgehrd_nb(LOCAL_MATRIX_N(data->mat_a));
cudaMalloc((void**)&dT, nb*n*sizeof(double));
// reduce
magma_dgehrd(n, 1, n, A, ldA, tau, work, lwork, dT, &info);
if (info != 0)
goto finalize;
free(work);
work = NULL;
// copy A -> Q
for (int i = 0; i < n; i++)
memcpy(Q+i*ldQ, A+i*ldA, n*sizeof(double));
// form Q
magma_dorghr(n, 1, n, Q, ldQ, tau, dT, nb, &info);
if (info != 0)
goto finalize;
// zero entries below the first sub-diagonal
for (int i = 0; i < n-1; i++)
memset(A+i*ldA+i+2, 0, (n-i-2)*sizeof(double));
finalize:
threads_set_mode(THREADS_MODE_DEFAULT);
cudaFree(dT);
free(work);
free(tau);
return info;
}
const struct hook_solver hessenberg_magma_solver = {
.name = "magma",
.desc = "MAGMA's dgehrd subroutine",
.formats = (hook_data_format_t[]) { HOOK_DATA_FORMAT_PENCIL_LOCAL, 0 },
.prepare = &magma_dgehrd_prepare,
.finalize = &magma_dgehrd_finalize,
.run = &magma_dgehrd_run
};
#endif // MAGMA_FOUND
| {
"alphanum_fraction": 0.581787904,
"avg_line_length": 29.9909194098,
"ext": "c",
"hexsha": "8dcf72c5c84ccd3cd71dceb35667771ed635a65f",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z",
"max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/StarNEig",
"max_forks_repo_path": "test/hessenberg/solvers.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/StarNEig",
"max_issues_repo_path": "test/hessenberg/solvers.c",
"max_line_length": 80,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/StarNEig",
"max_stars_repo_path": "test/hessenberg/solvers.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z",
"num_tokens": 6968,
"size": 26422
} |
/**
*
* For reference: Pearson's rho...
*
* sum( (x_i-E[x])(y_i-E[y]) )
* rho = -------------------------------------------
* sqrt( sum((x_i-E[x])^2) sum((y_i-E[y])^2) )
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <alloca.h>
#include <gsl/gsl_cdf.h>
#include "stattest.h"
#include "mix.h"
#include "bvr.h"
#include "limits.h"
struct Pair {
float cv; // Continuous Variable
unsigned int dv; // Discrete Variable
};
static int _cmp_pair( const void *pvl, const void *pvr ) {
const struct Pair *l = (const struct Pair *)pvl;
const struct Pair *r = (const struct Pair *)pvr;
const float delta = l->cv - r->cv;
if( delta == 0.0 )
return 0.0;
else
return delta < 0.0 ? -1 : +1;
}
struct MixCovars {
/**
* Maximum number of samples
*/
unsigned int SAMPLE_CAPACITY;
/**
* All category labels pushed into this accumulator must
* be in [0,category_capacity).
*/
unsigned int CATEGORY_CAPACITY;
/**
* Count of samples pushed since last cat_clear.
*/
unsigned int sample_count;
/**
* This essentially bounds the allowed category LABELS.
* Any category label push'ed in must be in [0,expected_categories).
* Only this member, NOT category_capacity, should be used to size
* counts arrays!
*/
unsigned int expected_categories;
/**
* This is an count of DISTINCT LABELS observed by push.
*/
unsigned int observed_categories;
// Calculation state ///////////////////////////////////////////////////
double mean_rank; // necessarily of both covariates
double sum_sq_dev; // used for Kruskal-Wallis and Spearman
/**
* Following struct array is ONLY for Spearman rho calculation.
* Note that the number of non-empty categories after data entry
* says NOTHING about WHICH categories (indices) are non-zero.
* An earlier implementation was assuming category_count[0,1] > 0,
* BUT THIS NEED NOT BE TRUE! Thus, all this hack...
*/
struct {
unsigned int index;
unsigned int count;
unsigned int meanRank;
} edge[2];
double sum_dev_prod; // used only for Spearman-rho
// Buffer //////////////////////////////////////////////////////////////
/**
* The TOTAL amount of malloc'ed space (for the purposes
* of fast clearing with memset).
*/
size_t SIZEOF_BUFFERS;
/**
* Two buffers
*/
struct Pair *samples;
/**
* A buffer allocated once in construction and reused for
* all subsequent analyses.
* Reallocation is not currently supported.
*/
unsigned int *category_count;
};
#ifdef _UNITTEST_MIX_
unsigned arg_min_mixb_count = 1;
#else
extern unsigned arg_min_mixb_count;
#endif
/**
* Both minCat and maxCat assume that samples is non-empty,
* but it's entirely possible that there were NO samples.
*/
static unsigned _minCat( struct MixCovars *co ) {
unsigned int i = 0;
while( i < co->expected_categories ) {
if( co->category_count[i] > 0 )
return i;
i++;
}
return INT_MAX; // just to silence compiler.
}
static unsigned _maxCat( struct MixCovars *co ) {
int i = co->expected_categories;
while( i-- > 0 ) {
if( co->category_count[i] > 0 )
return (unsigned int)i;
}
return INT_MAX; // just to silence compiler
}
/**
* Notice that all calcuations are performed without actually requiring
* an array of ranks.
*/
static unsigned int _rank_sums( struct MixCovars *co,
double *sums ) {
const unsigned int N = co->sample_count;
const bool PRECALC_SPEARMAN_PRODUCT
= co->observed_categories == 2;
const unsigned UPPER
= co->edge[1].index;
unsigned int ties = 0;
unsigned int until = 0;
float rank = 0;
double diff;
// The default pair::operator< automatically uses the first element.
qsort( co->samples, co->sample_count, sizeof(struct Pair), _cmp_pair );
for(unsigned int i = 0; i < N; i++ ) {
const unsigned int cat
= co->samples[i].dv;
// The rank of the current sample is i+1 UNLESS we're in
// the midst of a run of samples with the same value in
// which case the last computed rank (a mean) is reused.
if( ! ( i < until ) ) {
until = i + 1;
while( until < N
&& ( co->samples[i].cv == co->samples[until].cv ) ) {
ties++;
until++;
}
if( i == 0 && until == N ) {
// degenerate case: all ties.
}
// Mean of n integers starting on r:
// [ (r+0) + (r+1) + (r+2) + ... + (r+(n-1)) ] / n
// ... = \frac{nr + \sum_{i=0}^{n-1} i}{n}
// ... = r + (1/n)[ (n-1)n / 2 ]
// ... = r + (n-1)/2
rank = (1.0+i) + ((until-i)-1)/2.0;
// ...notice if the very next sample -is- different
// then rank == i+1, the trivial case.
}
/**
* Warning: If the numeric feature is constant then rank==meanRank
* and diff == 0
*/
diff = rank - co->mean_rank;
co->sum_sq_dev += ( diff * diff );
if( PRECALC_SPEARMAN_PRODUCT ) {
co->sum_dev_prod += ( diff * ( co->edge[UPPER==cat?1:0].meanRank - co->mean_rank ) );
}
sums[ cat ] += rank;
}
return ties;
}
#if defined(_UNITTEST_MIX_)
static void dbg_dump( struct MixCovars *co, FILE *fp ) {
for(unsigned int i = 0; i < co->sample_count; i++ )
fprintf( fp, "%.3f\t%d\n", co->samples[i].cv, co->samples[i].dv );
}
#endif
/***************************************************************************
* Publics
*/
void mix_destroy( void *pv ) {
if( pv ) {
struct MixCovars *co = (struct MixCovars *)pv;
if( co->samples )
free( co->samples );
free( pv );
}
}
/**
* Pre-allocate a set of working buffers large enough for all anticipated
* calculations (max feature length) and a struct to wrap them.
*/
void *mix_create( unsigned int sample_capacity, unsigned int category_capacity ) {
struct MixCovars *co
= calloc( 1, sizeof(struct MixCovars) );
if( co ) {
co->SAMPLE_CAPACITY = sample_capacity;
co->CATEGORY_CAPACITY = category_capacity;
co->SIZEOF_BUFFERS
= ( sample_capacity * sizeof(struct Pair) )
+ ( category_capacity * sizeof(unsigned int) );
// Allocate one large buffer and partition it up.
co->samples
= calloc( co->SIZEOF_BUFFERS, sizeof(char) );
co->category_count
= (unsigned int*)(co->samples
+ sample_capacity);
// If -anything- failed clean up any successes.
if( NULL == co->samples ) {
mix_destroy( co );
return NULL;
}
return co;
}
return NULL;
}
void mix_clear( void *pv, unsigned expcat ) {
struct MixCovars *co = (struct MixCovars *)pv;
assert( expcat <= co->CATEGORY_CAPACITY );
co->sample_count = 0;
co->expected_categories = expcat;
co->observed_categories = 0;
co->mean_rank = 0.0;
co->sum_sq_dev = 0.0;
co->sum_dev_prod = 0.0;
memset( co->edge, 0, sizeof(co->edge) );
co->sum_dev_prod = 0.0;
memset( co->samples, 0, co->SIZEOF_BUFFERS );
}
void mix_push( void *pv, float num, unsigned int cat ) {
struct MixCovars *co = (struct MixCovars *)pv;
assert( cat < co->expected_categories );
assert( co->sample_count < co->SAMPLE_CAPACITY );
if( 0 == co->category_count[ cat ] )
co->observed_categories++;
co->category_count[ cat ] += 1;
// Not updating edges in here because the number of conditionals
// executed for sample counts > 32 exceeds the work to find the
// edges post-sample accumulation.
co->samples[ co->sample_count ].cv = num;
co->samples[ co->sample_count ].dv = cat;
co->sample_count++;
}
size_t mix_size( void *pv ) {
struct MixCovars *co = (struct MixCovars *)pv;
return co->sample_count;
}
/**
* - Establish whether or not Spearman is even sensible (according to
* whether or not the categorical variable is binary).
* - Compute the mean rank used throughout subsequent calcs.
* - Compute the mean ranks of the categorical values assuming
* they -are- binary.
*/
bool mix_complete( void *pv ) {
struct MixCovars *co = (struct MixCovars *)pv;
if( mix_degenerate( co ) ) return false;
co->mean_rank = (1.0 + co->sample_count)/2.0;
co->edge[1].index = _maxCat( co ); // ...this is used by kruskal_wallis, but
assert( co->edge[1].index < co->expected_categories );
// ...the remainder of the edge[] struct is only used if...
if( co->observed_categories == 2 ) {
// All the following is relevant only to Spearman rho calculation.
co->edge[0].index = _minCat( co );
assert( co->edge[0].index < co->expected_categories );
co->edge[0].count = co->category_count[ co->edge[0].index ];
co->edge[0].meanRank = MEAN_RANK_OF_TIES( 0, co->edge[0].count );
co->edge[1].count = co->category_count[ co->edge[1].index ];
if( co->edge[0].count < arg_min_mixb_count ||
co->edge[1].count < arg_min_mixb_count )
return false; // another degeneracy class
co->edge[1].meanRank = MEAN_RANK_OF_TIES( co->edge[0].count, co->sample_count );
assert( (co->edge[0].count + co->edge[1].count) == co->sample_count );
}
return true;
}
bool mix_degenerate( void *pv ) {
struct MixCovars *co = (struct MixCovars *)pv;
return co->observed_categories < 2 || co->sample_count < 2;
}
bool mix_categoricalIsBinary( void *pv ) {
struct MixCovars *co = (struct MixCovars *)pv;
return co->observed_categories == 2;
}
/**
* Calculates the Kruskal-Wallis statistic and optionally a p-value.
* Importantly, it does it in a one pass iteration over the data.
*/
int mix_kruskal_wallis( void *pv, struct Statistic *result ) {
struct MixCovars *co = (struct MixCovars *)pv;
const unsigned int N
= co->sample_count ;
const size_t SIZEOF_SUMS
= co->expected_categories * sizeof(double);
double *rank_sum
= (double*)alloca( SIZEOF_SUMS );
double numerator = 0.0;
memset( rank_sum, 0, SIZEOF_SUMS );
result->extra_value[0] = _rank_sums( co, rank_sum );
for(unsigned int i = 0; i <= co->edge[1].index; i++ ) {
if( co->category_count[i] > 0 ) {
rank_sum[i] /= co->category_count[i];
double delta
= rank_sum[i] - co->mean_rank;
numerator
+= ( co->category_count[i] * delta * delta );
}
}
result->name
= "Kruskal-Wallis_K";
result->sample_count
= N;
result->value
= (N-1) * ( numerator / co->sum_sq_dev );
result->probability
= gsl_cdf_chisq_Q( result->value, co->observed_categories-1 );
return 0;
}
/**
* P-value returned is ONE-SIDED. Double it for two-sided.
*/
#ifdef HAVE_MANN_WHITNEY
int mix_mann_whitney( void *pv, struct Statistic *result ) {
struct MixCovars *co = (struct MixCovars *)pv;
const size_t SIZEOF_SUMS
= co->expected_categories * sizeof(double);
double *rank_sum
= (double*)alloca( SIZEOF_SUMS );
memset( rank_sum, 0, SIZEOF_SUMS );
ms->ties
= _rank_sums( co, rank_sum );
// TODO: If too many ties, the following method of calculating U
// becomes invalid. What to do?
const unsigned int SQ
= category_count[0]*category_count[1];
// If either group count is 0 we're done...
if( SQ ) {
const double U1
= rank_sum[0] - (category_count[0]*(category_count[0]+1.0))/2.0;
const double U2
= rank_sum[1] - (category_count[1]*(category_count[1]+1.0))/2.0;
assert( U1+U2 == SQ );
ms->U = U1 < U2 ? U1 : U2;
const double mean_U
= SQ / 2.0;
const double sigma_U
= sqrt( SQ*( category_count[0] + category_count[1] + 1.0 ) / 12.0 );
cs->P = gsl_cdf_ugaussian_P( ( ms->U - mean_U ) / sigma_U );
}
return 0;
}
#endif
/**
* This calculation depends on a quantities calculated within
* kruskal_wallis (or mann_whitney), so must be called after
* either of them.
* (This is also the only reason this method can be const.)
*/
double mix_spearman_rho( void *pv ) {
struct MixCovars *co = (struct MixCovars *)pv;
/**
* denominator requires sum of square deviation for
* the binary variables which collapses to...
*/
double SQD0 = (co->edge[0].meanRank - co->mean_rank ); SQD0 *= SQD0;
double SQD1 = (co->edge[1].meanRank - co->mean_rank ); SQD1 *= SQD1;
const double SUMSQD
= co->edge[0].count * SQD0 + co->edge[1].count * SQD1;
/**
* And the sum of squared deviation of the numeric covariate's
* ranks (sum_sq_dev) was (necessarily) calculated earlier!
*/
return co->sum_dev_prod / sqrt( co->sum_sq_dev * SUMSQD );
}
#ifdef _UNITTEST_MIX_
/**
* This is intended to be exercised with the following R script
* that generates a small table of grouped floating-point values
* executes a Kruskal-Wallis test on it, and dumps the table
* to a tab-delimited file with the test results as a comment on
* the first line.
*
* x <- data.frame(
* cat=as.integer(gl(3,4))-1,
* num=c( runif(4)*10, runif(4)*20, 10+runif(4)*10 ) );
* k <- with( x, kruskal.test( num, cat ) );
* cat( sprintf( "# K=%f p-value=%f\n", k$statistic, k$p.value ), file="foo.tab" );
* write.table( x, 'foo.tab', quote=F, sep='\t', row.names=F, col.names=F, append=TRUE );
*/
#include <err.h>
int main( int argc, char *argv[] ) {
if( argc >= 3 ) {
struct Statistic result;
const int EXPCAT
= atoi( argv[1] );
struct MixCovars *accum
= mix_create( atoi( argv[2] ), MAX_CATEGORY_COUNT );
FILE *fp
= argc > 3
? fopen( argv[3], "r" )
: stdin;
char *line = NULL;
size_t n = 0;
mix_clear( accum, EXPCAT );
while( getline( &line, &n, fp ) > 0 ) {
unsigned int cat;
float num;
if( line[0] == '#' ) {
fputs( line, stdout );
continue;
}
if( 2 == sscanf( line, "%d\t%f\n", &cat, &num ) ) {
mix_push( accum, num, cat );
} else {
fprintf( stderr, "Failure parsing line: %s", line );
}
}
free( line );
fclose( fp );
// Always calculate Kruskal-Wallis since it's valid for any groups
// count >= 2...
if( mix_complete( accum ) ) {
memset( &result, 0, sizeof(struct Statistic) );
if( mix_kruskal_wallis( accum, &result ) == 0 ) {
printf( "K=%f, p-value=%f", result.value, result.probability );
if( mix_categoricalIsBinary( accum ) )
printf( ", spearman=%f\n", mix_spearman_rho(accum) );
else
fputc( '\n', stdout );
} else {
printf( "error\n" );
}
}
#ifdef HAVE_MANN_WHITNEY
// Do a Mann-Whitney, too, if there are only 2 groups.
if( mix_categoricalIsBinary(accum) == 2 ) {
}
#endif
mix_destroy( accum );
} else
err( -1, "%s <categories> <sample count> [ <input file> ]", argv[0] );
return 0;
}
#endif
| {
"alphanum_fraction": 0.6322145766,
"avg_line_length": 24.8551483421,
"ext": "c",
"hexsha": "c6be03832df5f1284062d48677396f9094ac778e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "IlyaLab/kramtools",
"max_forks_repo_path": "pairwise/src/mix.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "IlyaLab/kramtools",
"max_issues_repo_path": "pairwise/src/mix.c",
"max_line_length": 89,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "987eb145f1f99378fcf24d4f89664e986e7c2a81",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "IlyaLab/kramtools",
"max_stars_repo_path": "pairwise/src/mix.c",
"max_stars_repo_stars_event_max_datetime": "2020-03-30T03:07:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-03-30T03:07:45.000Z",
"num_tokens": 4314,
"size": 14242
} |
/**
* Copyright 2017 BitTorrent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <okui/config.h>
#include <okui/opengl/Framebuffer.h>
#include <okui/shaders/ColorShader.h>
#include <okui/shaders/DistanceFieldShader.h>
#include <okui/shaders/TextureShader.h>
#include <okui/Application.h>
#include <okui/Color.h>
#include <okui/Point.h>
#include <okui/Rectangle.h>
#include <okui/RenderTarget.h>
#include <okui/Relation.h>
#include <okui/Responder.h>
#include <okui/ShaderCache.h>
#include <okui/TextureHandle.h>
#include <okui/TouchpadFocus.h>
#include <okui/WeakTexture.h>
#include <scraps/AbstractTaskScheduler.h>
#include <scraps/TreeNode.h>
#include <scraps/utility.h>
#include <stdts/optional.h>
#include <gsl.h>
#include <list>
#include <typeindex>
#include <unordered_map>
namespace okui {
class Application;
class BitmapFont;
class Window;
/**
* View rendering can be cached or buffered to a texture. One reason this may be done is to apply post-rendering
* effects such as tinting or reflection. When this is done, the contents of the view are clipped to its bounds.
*/
class View : public Responder, private scraps::TreeNode<View> {
public:
using Relation = okui::Relation;
View() = default;
explicit View(std::string name) : _name{std::move(name)} {}
View(const View&) = delete;
View(View&&) = delete;
View& operator=(const View&) = delete;
View& operator=(View&&) = delete;
/**
* It is an error to destroy a focused view. Remove the view first if needed.
*/
virtual ~View();
std::string name() const { return _name.empty() ? scraps::Demangle(typeid(*this).name()) : _name; }
void setName(std::string name) { _name = std::move(name); }
void addSubview(View* view);
template <typename... Views>
void addSubviews(View* view, Views&&... views) { _addSubviews(view, std::forward<Views>(views)...); }
void addHiddenSubview(View* view);
void removeSubview(View* view);
template <typename... Views>
void removeSubviews(View* view, Views&&... views) { _removeSubviews(view, std::forward<Views>(views)...); }
void removeSubviews();
Window* window() const { return _window; }
Application* application() const;
const View* superview() const { return parent(); }
View* superview() { return parent(); }
const std::list<View*>& subviews() const { return children(); }
const Rectangle<double>& bounds() const { return _bounds; }
math::Vector<double, 2> size() const { return _bounds.size(); }
Point<double> position() const { return _bounds.position(); }
double width() const { return _bounds.width; }
double height() const { return _bounds.height; }
template <typename... Args>
void setBounds(Args&&... args) { _setBounds(Rectangle<double>(std::forward<Args>(args)...)); }
void setPosition(double x, double y) { _setBounds({x, y, _bounds.width, _bounds.height}); }
void setPosition(const Point<double>& p) { setPosition(p.x, p.y); }
void setSize(double width, double height) { _setBounds({_bounds.x, _bounds.y, width, height}); }
void setSize(const math::Vector<double, 2>& s) { setSize(s.x, s.y); }
Rectangle<double> windowBounds() const;
/**
* Sets bounds as a percent of superview bounds (0-1)
*/
void setBoundsRelative(double x, double y, double width, double height);
void setInterceptsInteractions(bool intercepts);
void setInterceptsInteractions(bool intercepts, bool childrenIntercept);
void setChildrenInterceptInteractions(bool childrenIntercept);
ShaderCache* shaderCache();
void setIsVisible(bool isVisible = true);
bool isVisible() const { return _isVisible; }
void show() { setIsVisible(); }
void hide() { setIsVisible(false); }
/**
* Allows scaling of the view by a particular factor.
*/
void setScale(double scale) { setScale(scale, scale); }
void setScale(double scaleX, double scaleY);
/**
* Sets the view's background color.
*/
void setBackgroundColor(const Color& color) { _backgroundColor = color; }
const Color& backgroundColor() const { return _backgroundColor; }
/**
* Sets the view's tint. If this is anything but opaque white, this is a post-rendering effect that
* clips the view's contents.
*/
void setTintColor(const Color& color);
const Color& tintColor() const { return _tintColor; }
/**
* Sets the view's opacity. If this is anything but 1, this is a post-rendering effect that
* clips the view's contents.
*
* This effectively sets the alpha component of the view's tint color.
*/
void setOpacity(double opacity) { setTintColor(_tintColor.withAlphaF(opacity)); }
double opacity() const { return _tintColor.alphaF(); }
/**
* Returns true if the view's ancestors are visible or if the view has no ancestors.
*/
bool ancestorsAreVisible() const;
/**
* Returns true if the view and its ancestors are visible and in an open window.
*/
bool isVisibleInOpenWindow() const;
/**
* Arranges the view so it's behind all of its current siblings.
*/
void sendToBack();
/**
* Arranges the view so it's in front of all of its current siblings.
*/
void bringToFront();
/**
* Override this if the view can become focused.
*/
virtual bool canBecomeDirectFocus() { return false; }
/**
* Makes the view the current focus. If the view has a preferred focus, the preferred focus will
* become the focus instead.
*/
void focus();
/**
* Returns the view that would become focused if an attempt to give focus to this view is made.
*/
View* expectedFocus();
/**
* Sets the focus to the next ancestor that can be focused which doesn't result in this view
* retaining focus (which would otherwise happen if your ancestor's preferred focus was you)
*/
void focusAncestor();
/**
* If the view or any of its children are focused, unfocuses them.
*/
void unfocus();
/**
* If this view would receive focus and has a preferred focus, the preferred focus will become focus instead.
*/
View* preferredFocus() const { return _preferredFocus; }
void setPreferredFocus(View* view) { _preferredFocus = view; }
View* nextFocus() const { return _nextFocus; }
View* previousFocus() const { return _previousFocus; }
/**
* If the view receives an unhandled tab key down, focus will change to the given
* view (and shift+tab will do the opposite).
*/
void setNextFocus(View* view);
/**
* Returns the next available visible and focusable view if there is one.
*/
View* nextAvailableFocus();
/**
* Returns the previous available visible and focusable view.
*/
View* previousAvailableFocus();
/**
* Returns true if the view or any of its children has focus.
*/
bool isFocus() const;
TouchpadFocus& touchpadFocus() { return _touchpadFocus; }
/**
* @param rendersToTexture if true, the view is rendered to a texture, making it available via renderTexture
*/
void setRendersToTexture(bool rendersToTexture = true) { _rendersToTexture = rendersToTexture; }
/**
* If the view is set to render to a texture, this can be used to obtain said texture.
*/
std::shared_ptr<TextureInterface> renderTexture() const;
/**
* @param caches if true, the view will render to a texture and the render() method will only be called when
* the cache is invalid
*/
void setCachesRender(bool cachesRender = true) { _cachesRender = cachesRender; }
/**
* Invalidates the view's render cache.
*/
void invalidateRenderCache();
/**
* @param clipsToBounds if true, the view will not render itself or any subviews outside of its bounds
*/
void setClipsToBounds(bool clipsToBounds = true) { _clipsToBounds = clipsToBounds; }
/**
* @return if true, the view will not render itself or any subviews outside of its bounds
*/
bool clipsToBounds() const { return _clipsToBounds; }
/**
* Returns true if the mouse is hovering directly over this view.
*/
bool hasMouse() const;
shaders::ColorShader* colorShader() { return shader<shaders::ColorShader>("color shader"); }
shaders::TextureShader* textureShader() { return shader<shaders::TextureShader>("texture shader"); }
shaders::DistanceFieldShader* distanceFieldShader() { return shader<shaders::DistanceFieldShader>("distance field shader"); }
/**
* Begins loading a texture associated with the view. When the texture is loaded, the view's
* render cache will be invalidated. If the texture should not be associated with the view,
* use Window::loadTexture* instead.
*/
TextureHandle loadTextureResource(const std::string& name);
TextureHandle loadTextureFromMemory(std::shared_ptr<const std::string> data);
TextureHandle loadTextureFromURL(const std::string& url);
/**
* Get or create a shader cached via the window's shader cache.
*/
template <typename T>
T* shader(const char* identifier);
const AffineTransformation& renderTransformation() const { return _renderTransformation; }
/**
* Converts a point from local coordinates to superview coordinates.
*/
Point<double> localToSuperview(double x, double y) const { return localToAncestor(x, y, superview()); }
Point<double> localToSuperview(const Point<double>& p) const { return localToSuperview(p.x, p.y); }
/**
* Converts a point from local coordinates to the coordinates of an ancestor.
*/
Point<double> localToAncestor(double x, double y, const View* ancestor) const;
Point<double> localToAncestor(const Point<double>& p, const View* ancestor) const { return localToAncestor(p.x, p.y, ancestor); }
/**
* Converts a point from super coordinates to local coordinates.
*/
Point<double> superviewToLocal(double x, double y) const;
Point<double> superviewToLocal(const Point<double>& p) const;
/**
* Converts a point from local coordinates to window coordinates.
*/
Point<double> localToWindow(double x, double y) const;
Point<double> localToWindow(const Point<double>& p) const;
/**
* Returns true if this view has the given relation to the given view.
*
* For example, hasRelation(kDescendant, superview()) should return true.
*/
bool hasRelation(Relation relation, const View* view) const;
/**
* Returns the first view that both views have in their hierarchy, if any.
*/
const View* commonView(const View* other) const { return commonNode(other); }
using TreeNode::isDescendantOf;
using TreeNode::isAncestorOf;
/**
* Posts a message to listeners with the given relation. The view and its potential listeners must have an
* associated application for the message to be delivered.
*
* For example, post(message, Relation::kAncestor) posts the message to listeners that are ancestors of this view.
*/
template <typename T>
void post(T& message, Relation relation = Relation::kHierarchy) {
_post(std::type_index(typeid(typename std::decay_t<T>)), &message, relation);
}
template <typename T>
void post(T&& message, Relation relation = Relation::kHierarchy) {
T m = std::move(message);
_post(std::type_index(typeid(typename std::decay_t<T>)), &m, relation);
}
template <typename T>
struct ListenerAction : ListenerAction<decltype(&T::operator())> {};
template <typename C, typename R, typename... Args>
struct ListenerAction<R(C::*)(Args...) const> {
using ArgumentTuple = std::tuple<Args...>;
using ArgumentCount = std::tuple_size<ArgumentTuple>;
using MessageType = typename std::decay<typename std::tuple_element<0, ArgumentTuple>::type>::type;
};
/**
* Listens for messages from senders with the given relation.
*
* For example, listen([](const Message& message) {}, Relation::kAncestor) listens for messages from posters that
* are ancestors of this view.
*
* @param action an action that takes a constant reference to the message type to listen for and optionally a View pointer to the sender
*/
template <typename Action>
auto listen(Action&& action, Relation relation = Relation::kHierarchy) -> typename std::enable_if<ListenerAction<Action>::ArgumentCount::value == 1, void>::type {
using MessageType = typename ListenerAction<Action>::MessageType;
_listen(std::type_index(typeid(MessageType)),
[action = std::forward<Action>(action)](const void* message, View* sender) {
action(*reinterpret_cast<const MessageType*>(message));
}, relation
);
}
template <typename Action>
auto listen(Action&& action, Relation relation = Relation::kHierarchy) -> typename std::enable_if<ListenerAction<Action>::ArgumentCount::value == 2, void>::type {
using MessageType = typename ListenerAction<Action>::MessageType;
_listen(std::type_index(typeid(MessageType)),
[action = std::forward<Action>(action)](const void* message, View* sender) {
action(*reinterpret_cast<const MessageType*>(message), sender);
}, relation
);
}
/**
* Makes the given object available via get(). This can be used to store arbitrary state with the view.
*
* @param relation the object will only be available to views of the given relation
*/
template <typename T>
auto set(T&& object, Relation relation = Relation::kHierarchy) {
_provisions.emplace_front(std::forward<T>(object), relation);
return stdts::any_cast<std::decay_t<T>>(&_provisions.front().object);
}
/**
* Finds an object provided via provide. It will return a pointer to the first object it finds of the
* specified type. If more than one objects of the given type has been provided, it is undefined
* which one will be returned.
*
* @param relation only objects from views of the given relation will be returned
*/
template <typename T>
T* find(Relation relation = Relation::kHierarchy);
template <typename T>
T* get() { return find<T>(Relation::kSelf); }
template <typename T>
T* inherit() { return find<T>(Relation::kAncestor); }
/**
* Asynchronously schedules a function to be invoked using the application's task scheduler.
*
* If the view is destroyed, the invocation will be canceled.
*/
template <typename... Args>
auto async(Args&&... args) -> decltype(std::declval<scraps::AbstractTaskScheduler>().async(std::forward<Args>(args)...)) {
return _taskScheduler()->async(_taskScope, std::forward<Args>(args)...);
}
/**
* Asynchronously schedules a function to be invoked after a delay using the application's task scheduler.
*
* If the view is destroyed, the invocation will be canceled.
*/
template <typename... Args>
auto asyncAfter(Args&&... args) -> decltype(std::declval<scraps::AbstractTaskScheduler>().asyncAfter(std::forward<Args>(args)...)) {
return _taskScheduler()->asyncAfter(_taskScope, std::forward<Args>(args)...);
}
/**
* Asynchronously schedules a function to be invoked at a time using the application's task scheduler.
*
* If the view is destroyed, the invocation will be canceled.
*/
template <typename... Args>
auto asyncAt(Args&&... args) -> decltype(std::declval<scraps::AbstractTaskScheduler>().asyncAt(std::forward<Args>(args)...)) {
return _taskScheduler()->asyncAt(_taskScope, std::forward<Args>(args)...);
}
/**
* The hook provided here will be called before rendering each frame.
*/
void addUpdateHook(const std::string& handle, std::function<void()> hook);
/**
* The hook provided here will no longer be called.
*/
void removeUpdateHook(const std::string& handle);
/**
* Override this to do drawing.
*/
virtual void render() {}
virtual void render(const RenderTarget* renderTarget, const Rectangle<int>& area) { render(); }
/**
* Override this to implement custom post-render effects. For this method to be called, the view must be
* set to render to texture. The default implementation provides the built-in effects such as tint and
* opacity. If this is overridden, you will need to provide those effects in your implementation in
* order to use them.
*
* @param texture the view, rendered to a texture with premultiplied alpha
*/
virtual void postRender(std::shared_ptr<TextureInterface> texture, const AffineTransformation& transformation);
/**
* Override this to lay out subviews whenever the view is resized.
*/
virtual void layout() {}
/**
* Override this to do any sort of setup that requires the view to be attached to a window.
*/
virtual void windowChanged() {}
/**
* Override this if you want odd-shaped views to have accurate hit boxes.
*/
virtual bool hitTest(double x, double y);
bool hitTest(const Point<double>& p) { return hitTest(p.x, p.y); }
/**
* Return the most descendant visible view which intersects with (x, y)
*/
View* hitTestView(double x, double y);
View* hitTestView(const Point<double>& p) { return hitTestView(p.x, p.y); }
/**
* Override these to handle mouse events. Call the base implementation to pass on the event.
*/
virtual void mouseDown(MouseButton button, double x, double y);
virtual void mouseUp(MouseButton button, double startX, double startY, double x, double y);
virtual void mouseWheel(double xPos, double yPos, int xWheel, int yWheel);
virtual void mouseDrag(double startX, double startY, double x, double y);
virtual void mouseMovement(double x, double y);
virtual void mouseEnter() {}
virtual void mouseExit() {}
/**
* Called whenever the view or one of its subviews gains focus.
*/
virtual void focusGained() {}
/**
* Called whenever the view and its subviews lose focus.
*/
virtual void focusLost() {}
/**
* Called whenever the view or any subview gains or loses focus.
*/
virtual void focusChanged() {}
/**
* Called before the view and all of its ancestors become visible in the window.
*/
virtual void willAppear() {}
/**
* Called when the view and all of its ancestors become visible in the window.
*/
virtual void appeared() {}
/**
* Called before the view or one of its ancestors become invisible in the window.
*/
virtual void willDisappear() {}
/**
* Called when the view or one of its ancestors become invisible in the window.
*/
virtual void disappeared() {}
/**
* Renders the view and its subviews.
*
* @param area the area within the target to render to. the view will fill this area
* @param clipBounds the bounds within the target to clip rendering of the view and its children to
*/
void renderAndRenderSubviews(const RenderTarget* target, const Rectangle<int>& area, stdts::optional<Rectangle<int>> clipBounds = stdts::nullopt);
bool dispatchMouseDown(MouseButton button, double x, double y);
bool dispatchMouseUp(MouseButton button, double startX, double startY, double x, double y);
bool dispatchMouseMovement(double x, double y);
bool dispatchMouseWheel(double xPos, double yPos, int xWheel, int yWheel);
void dispatchUpdate(std::chrono::high_resolution_clock::duration elapsed);
// Responder overrides
virtual Responder* nextResponder() override;
virtual void keyDown(KeyCode key, KeyModifiers mod, bool repeat) override;
virtual void touchUp(size_t finger, Point<double> position, double pressure) override;
virtual void touchDown(size_t finger, Point<double> position, double pressure) override;
virtual void touchMovement(size_t finger, Point<double> position, Point<double> distance, double pressure) override;
private:
friend class scraps::TreeNode<View>;
friend class Window;
struct Listener {
Listener(std::type_index index, std::function<void(const void*, View*)> action, Relation relation)
: index{index}, action{std::move(action)}, relation{relation} {}
std::type_index index;
std::function<void(const void*, View*)> action;
Relation relation;
};
struct Provision {
Provision(stdts::any object, Relation relation)
: object{std::move(object)}, relation{relation} {}
stdts::any object;
Relation relation;
};
void _addSubviews() {}
template <typename... Views>
void _addSubviews(View* view, Views&&... views);
void _removeSubviews() {}
template <typename... Views>
void _removeSubviews(View* view, Views&&... views);
void _setBounds(const Rectangle<double>& bounds);
void _invalidateSuperviewRenderCache();
void _dispatchFutureVisibilityChange(bool visible);
void _dispatchVisibilityChange(bool visible);
void _dispatchWindowChange(Window* window);
void _mouseExit();
void _updateFocusableRegions(std::vector<std::tuple<View*, Rectangle<double>>>& regions);
bool _requiresTextureRendering();
void _renderAndRenderSubviews(const RenderTarget* target, const Rectangle<int>& area, bool shouldClear = false, stdts::optional<Rectangle<int>> clipBounds = stdts::nullopt);
void _post(std::type_index index, const void* ptr, Relation relation);
void _listen(std::type_index index, std::function<void(const void*, View*)> action, Relation relation);
template <typename F>
void _traverseRelation(Relation relation, F&& function);
std::vector<View*> _topViewsForRelation(Relation relation);
scraps::AbstractTaskScheduler* _taskScheduler() const;
void _updateTouchFocus(std::chrono::high_resolution_clock::duration elapsed);
void _checkUpdateSubscription();
bool _shouldSubscribeToUpdates();
std::string _name;
bool _isVisible = true;
bool _rendersToTexture = false;
bool _cachesRender = false;
bool _hasCachedRender = false;
bool _clipsToBounds = true;
bool _interceptsInteractions = true;
bool _childrenInterceptInteractions = true;
Window* _window = nullptr;
View* _subviewWithMouse = nullptr;
View* _nextFocus = nullptr;
View* _previousFocus = nullptr;
View* _preferredFocus = nullptr;
Rectangle<double> _bounds;
Point<double> _scale{1.0, 1.0};
Color _backgroundColor = Color::kTransparentBlack;
Color _tintColor = Color::kWhite;
AffineTransformation _renderTransformation;
std::unique_ptr<opengl::Framebuffer> _renderCache;
opengl::Framebuffer::Attachment* _renderCacheColorAttachment = nullptr;
std::shared_ptr<WeakTexture> _renderCacheTexture = std::make_shared<WeakTexture>();
std::list<Listener> _listeners;
std::list<Provision> _provisions;
TouchpadFocus _touchpadFocus;
std::unordered_map<size_t, std::function<void()>> _updateHooks;
scraps::AbstractTaskScheduler::TaskScope _taskScope; /* must be the last member */
};
template <typename... Views>
void View::_addSubviews(View* view, Views&&... views) {
addSubview(view);
_addSubviews(std::forward<Views>(views)...);
}
template <typename... Views>
void View::_removeSubviews(View* view, Views&&... views) {
removeSubview(view);
_removeSubviews(std::forward<Views>(views)...);
}
template <typename T>
T* View::shader(const char* identifier) {
auto s = shaderCache()->get(std::string(identifier));
if (!s) {
s = shaderCache()->add(std::make_unique<T>(), std::string(identifier), ShaderCache::Policy::kKeepForever);
}
auto ret = dynamic_cast<T*>(s->get());
ret->setTransformation(renderTransformation());
return ret;
}
template <typename T>
T* View::find(Relation relation) {
T* ret = nullptr;
_traverseRelation(relation, [&](View* view, bool* shouldContinue) {
for (auto& provision : view->_provisions) {
if (!hasRelation(provision.relation, view)) { continue; }
if (auto object = stdts::any_cast<T>(&provision.object)) {
ret = object;
*shouldContinue = false;
return 1;
}
if (auto pointer = stdts::any_cast<T*>(&provision.object)) {
ret = *pointer;
*shouldContinue = false;
return 1;
}
}
return 0;
});
if (!ret && application() && (relation == Relation::kHierarchy || relation == Relation::kAny || relation == Relation::kAncestor)) {
return application()->get<T>();
}
return ret;
}
template <typename F>
void View::_traverseRelation(Relation relation, F&& function) {
switch (relation) {
case Relation::kAny: {
bool shouldContinue = true;
for (auto& v : _topViewsForRelation(relation)) {
v->TreeNode::traverseRelation(TreeNode::Relation::kCommonRoot, function, 0, &shouldContinue);
}
break;
}
case Relation::kHierarchy: TreeNode::traverseRelation(TreeNode::Relation::kCommonRoot, function, 0); break;
case Relation::kDescendant: TreeNode::traverseRelation(TreeNode::Relation::kDescendant, function, 0); break;
case Relation::kAncestor: TreeNode::traverseRelation(TreeNode::Relation::kAncestor, function, 0); break;
case Relation::kSibling: TreeNode::traverseRelation(TreeNode::Relation::kSibling, function, 0); break;
case Relation::kSelf: TreeNode::traverseRelation(TreeNode::Relation::kSelf, function, 0); break;
}
}
} // namespace okui
| {
"alphanum_fraction": 0.6643016345,
"avg_line_length": 37.6503496503,
"ext": "h",
"hexsha": "1ebaf894681c63737a162eb666ec3bcc37d02dd3",
"lang": "C",
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2020-11-26T03:38:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-01-21T07:00:39.000Z",
"max_forks_repo_head_hexsha": "e569404b6d121e89451d57e7d321f420e5f86535",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "bittorrent/okui",
"max_forks_repo_path": "include/okui/View.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "e569404b6d121e89451d57e7d321f420e5f86535",
"max_issues_repo_issues_event_max_datetime": "2017-01-25T20:30:59.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-25T17:46:17.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "bittorrent/okui",
"max_issues_repo_path": "include/okui/View.h",
"max_line_length": 177,
"max_stars_count": 26,
"max_stars_repo_head_hexsha": "e569404b6d121e89451d57e7d321f420e5f86535",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "bittorrent/okui",
"max_stars_repo_path": "include/okui/View.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-08T10:00:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-01-20T22:14:09.000Z",
"num_tokens": 6124,
"size": 26920
} |
/*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: lymastee@hotmail.com
*
* This file is part of the gslib project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#ifndef config_27ec2780_3d0a_41f9_8a8b_0099ced77cf1_h
#define config_27ec2780_3d0a_41f9_8a8b_0099ced77cf1_h
#include <gslib/config.h>
#define __ariel_begin__ namespace gs { namespace ariel {
#define __ariel_end__ } };
#if defined(ARIEL_LIB)
#define ariel_export
#elif defined(ARIEL_DLL)
#define ariel_export __declspec(dllexport)
#else
#define ariel_export __declspec(dllimport)
#endif
enum
{
render_platform_gl_20,
render_platform_gl_30,
render_platform_d3d_9,
render_platform_d3d_11,
};
/* select render system here. */
#define select_render_platform render_platform_d3d_11
#define use_rendersys_d3d_9 (select_render_platform == render_platform_d3d_9)
#define use_rendersys_d3d_11 (select_render_platform == render_platform_d3d_11)
#define use_rendersys_gl_20 (select_render_platform == render_platform_gl_20)
#define use_rendersys_gl_30 (select_render_platform == render_platform_gl_30)
#if use_rendersys_d3d_11
#include <d3d11.h>
#include <dxgi.h>
#endif
__ariel_begin__
define_select_type(render_device);
define_select_type(render_context);
define_select_type(render_resource);
define_select_type(render_swap_chain);
define_select_type(render_target_view);
define_select_type(shader_resource_view);
define_select_type(depth_stencil_view);
define_select_type(unordered_access_view);
define_select_type(render_blob);
define_select_type(vertex_shader);
define_select_type(pixel_shader);
define_select_type(geometry_shader);
define_select_type(compute_shader);
define_select_type(hull_shader);
define_select_type(domain_shader);
define_select_type(render_include);
define_select_type(vertex_format);
define_select_type(vertex_format_desc);
define_select_type(render_vertex_buffer);
define_select_type(render_index_buffer);
define_select_type(render_constant_buffer);
define_select_type(render_texture1d);
define_select_type(render_texture2d);
define_select_type(render_texture3d);
define_select_type(render_sampler_state);
define_select_type(render_blend_state);
define_select_type(render_raster_state);
define_select_type(render_depth_state);
install_select_type(render_platform_d3d_11, render_device, ID3D11Device);
install_select_type(render_platform_d3d_11, render_context, ID3D11DeviceContext);
install_select_type(render_platform_d3d_11, render_resource, ID3D11Resource);
install_select_type(render_platform_d3d_11, render_swap_chain, IDXGISwapChain);
install_select_type(render_platform_d3d_11, render_target_view, ID3D11RenderTargetView);
install_select_type(render_platform_d3d_11, shader_resource_view, ID3D11ShaderResourceView);
install_select_type(render_platform_d3d_11, depth_stencil_view, ID3D11DepthStencilView);
install_select_type(render_platform_d3d_11, unordered_access_view, ID3D11UnorderedAccessView);
install_select_type(render_platform_d3d_11, render_blob, ID3DBlob);
install_select_type(render_platform_d3d_11, vertex_shader, ID3D11VertexShader);
install_select_type(render_platform_d3d_11, pixel_shader, ID3D11PixelShader);
install_select_type(render_platform_d3d_11, geometry_shader, ID3D11GeometryShader);
install_select_type(render_platform_d3d_11, compute_shader, ID3D11ComputeShader);
install_select_type(render_platform_d3d_11, hull_shader, ID3D11HullShader);
install_select_type(render_platform_d3d_11, domain_shader, ID3D11DomainShader);
install_select_type(render_platform_d3d_11, render_include, ID3DInclude);
install_select_type(render_platform_d3d_11, vertex_format, ID3D11InputLayout);
install_select_type(render_platform_d3d_11, vertex_format_desc, D3D11_INPUT_ELEMENT_DESC);
install_select_type(render_platform_d3d_11, render_vertex_buffer, ID3D11Buffer);
install_select_type(render_platform_d3d_11, render_index_buffer, ID3D11Buffer);
install_select_type(render_platform_d3d_11, render_constant_buffer, ID3D11Buffer);
install_select_type(render_platform_d3d_11, render_texture1d, ID3D11Texture1D);
install_select_type(render_platform_d3d_11, render_texture2d, ID3D11Texture2D);
install_select_type(render_platform_d3d_11, render_texture3d, ID3D11Texture3D);
install_select_type(render_platform_d3d_11, render_sampler_state, ID3D11SamplerState);
install_select_type(render_platform_d3d_11, render_blend_state, ID3D11BlendState);
install_select_type(render_platform_d3d_11, render_raster_state, ID3D11RasterizerState);
install_select_type(render_platform_d3d_11, render_depth_state, ID3D11DepthStencilState);
config_select_type(select_render_platform, render_device);
config_select_type(select_render_platform, render_context);
config_select_type(select_render_platform, render_resource);
config_select_type(select_render_platform, render_swap_chain);
config_select_type(select_render_platform, render_target_view);
config_select_type(select_render_platform, shader_resource_view);
config_select_type(select_render_platform, depth_stencil_view);
config_select_type(select_render_platform, unordered_access_view);
config_select_type(select_render_platform, render_blob);
config_select_type(select_render_platform, vertex_shader);
config_select_type(select_render_platform, pixel_shader);
config_select_type(select_render_platform, geometry_shader);
config_select_type(select_render_platform, compute_shader);
config_select_type(select_render_platform, hull_shader);
config_select_type(select_render_platform, domain_shader);
config_select_type(select_render_platform, render_include);
config_select_type(select_render_platform, vertex_format);
config_select_type(select_render_platform, render_vertex_buffer);
config_select_type(select_render_platform, render_index_buffer);
config_select_type(select_render_platform, render_constant_buffer);
config_select_type(select_render_platform, render_texture1d);
config_select_type(select_render_platform, render_texture2d);
config_select_type(select_render_platform, render_texture3d);
config_select_type(select_render_platform, render_sampler_state);
config_select_type(select_render_platform, render_blend_state);
config_select_type(select_render_platform, render_raster_state);
config_select_type(select_render_platform, render_depth_state);
enum render_option
{
opt_primitive_topology,
/* more to come. */
};
__ariel_end__
#endif
| {
"alphanum_fraction": 0.8418831597,
"avg_line_length": 46.237804878,
"ext": "h",
"hexsha": "0875d9cf4bed01f45e241b743ddd16d284f836fc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/ariel/config.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/ariel/config.h",
"max_line_length": 95,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/ariel/config.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z",
"num_tokens": 1700,
"size": 7583
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "core/common/logging/logging.h"
#include "core/framework/allocatormgr.h"
#include "core/framework/customregistry.h"
#include "core/framework/execution_frame.h"
#include "core/framework/op_kernel.h"
#include "core/framework/run_options.h"
#include "core/framework/session_state.h"
#include "core/framework/tensor.h"
#include "core/graph/graph_viewer.h"
#include "core/graph/model.h"
#include "core/framework/data_types.h"
#include "test/test_environment.h"
#include "test/framework/TestAllocatorManager.h"
#include "core/framework/TensorSeq.h"
#include "core/framework/session_options.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <gsl/gsl>
#include "core/util/math_cpuonly.h"
// helpers to run a function and check the status, outputting any error if it fails.
// note: wrapped in do{} while(false) so the _tmp_status variable has limited scope
#define ASSERT_STATUS_OK(function) \
do { \
auto _tmp_status = function; \
ASSERT_TRUE(_tmp_status.IsOK()) << _tmp_status; \
} while (false)
#define EXPECT_STATUS_OK(function) \
do { \
auto _tmp_status = function; \
EXPECT_TRUE(_tmp_status.IsOK()) << _tmp_status; \
} while (false)
namespace onnxruntime {
class InferenceSession;
struct SessionOptions;
namespace test {
template <typename T>
struct SeqTensors {
void AddTensor(const std::vector<int64_t>& shape0, const std::vector<T>& data0) {
tensors.push_back(Tensor<T>{shape0, data0});
}
template <typename U>
struct Tensor {
std::vector<int64_t> shape;
std::vector<U> data;
};
std::vector<Tensor<T>> tensors;
};
// unfortunately std::optional is in C++17 so use a miniversion of it
template <typename T>
class optional {
public:
optional(T v) : has_value_(true), value_(v) {}
optional() : has_value_(false) {}
bool has_value() const { return has_value_; }
const T& value() const {
ORT_ENFORCE(has_value_);
return value_;
}
private:
bool has_value_;
T value_;
};
// Function templates to translate C++ types into ONNX_NAMESPACE::TensorProto_DataTypes
template <typename T>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType();
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<float>() {
return ONNX_NAMESPACE::TensorProto_DataType_FLOAT;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<double>() {
return ONNX_NAMESPACE::TensorProto_DataType_DOUBLE;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<int32_t>() {
return ONNX_NAMESPACE::TensorProto_DataType_INT32;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<int64_t>() {
return ONNX_NAMESPACE::TensorProto_DataType_INT64;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<bool>() {
return ONNX_NAMESPACE::TensorProto_DataType_BOOL;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<int8_t>() {
return ONNX_NAMESPACE::TensorProto_DataType_INT8;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<int16_t>() {
return ONNX_NAMESPACE::TensorProto_DataType_INT16;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<uint8_t>() {
return ONNX_NAMESPACE::TensorProto_DataType_UINT8;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<uint16_t>() {
return ONNX_NAMESPACE::TensorProto_DataType_UINT16;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<uint32_t>() {
return ONNX_NAMESPACE::TensorProto_DataType_UINT32;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<uint64_t>() {
return ONNX_NAMESPACE::TensorProto_DataType_UINT64;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<std::string>() {
return ONNX_NAMESPACE::TensorProto_DataType_STRING;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<MLFloat16>() {
return ONNX_NAMESPACE::TensorProto_DataType_FLOAT16;
}
template <>
constexpr ONNX_NAMESPACE::TensorProto_DataType TypeToDataType<BFloat16>() {
return ONNX_NAMESPACE::TensorProto_DataType_BFLOAT16;
}
template <typename T>
struct TTypeProto : ONNX_NAMESPACE::TypeProto {
TTypeProto(const std::vector<int64_t>* shape = nullptr) {
mutable_tensor_type()->set_elem_type(TypeToDataType<T>());
if (shape) {
auto mutable_shape = mutable_tensor_type()->mutable_shape();
for (auto i : *shape) {
auto* mutable_dim = mutable_shape->add_dim();
if (i != -1)
mutable_dim->set_dim_value(i);
else
mutable_dim->set_dim_param("symbolic");
}
}
}
};
// Variable template for ONNX_NAMESPACE::TensorProto_DataTypes, s_type_proto<float>, etc..
template <typename T>
struct TTensorType {
static const TTypeProto<T> s_type_proto;
};
template <typename T>
const TTypeProto<T> TTensorType<T>::s_type_proto;
// TypeProto for map<TKey, TVal>
template <typename TKey, typename TVal>
struct MTypeProto : ONNX_NAMESPACE::TypeProto {
MTypeProto() {
mutable_map_type()->set_key_type(TypeToDataType<TKey>());
mutable_map_type()->mutable_value_type()->mutable_tensor_type()->set_elem_type(TypeToDataType<TVal>());
mutable_map_type()->mutable_value_type()->mutable_tensor_type()->mutable_shape()->clear_dim();
}
};
template <typename TKey, typename TVal>
struct MMapType {
static const MTypeProto<TKey, TVal> s_map_type_proto;
};
template <typename TKey, typename TVal>
const MTypeProto<TKey, TVal> MMapType<TKey, TVal>::s_map_type_proto;
// TypeProto for vector<map<TKey, TVal>>
template <typename TKey, typename TVal>
struct VectorOfMapTypeProto : ONNX_NAMESPACE::TypeProto {
VectorOfMapTypeProto() {
auto* map_type = mutable_sequence_type()->mutable_elem_type()->mutable_map_type();
map_type->set_key_type(TypeToDataType<TKey>());
map_type->mutable_value_type()->mutable_tensor_type()->set_elem_type(TypeToDataType<TVal>());
map_type->mutable_value_type()->mutable_tensor_type()->mutable_shape()->clear_dim();
}
};
template <typename TKey, typename TVal>
struct VectorOfMapType {
static const VectorOfMapTypeProto<TKey, TVal> s_vec_map_type_proto;
};
template <typename TKey, typename TVal>
const VectorOfMapTypeProto<TKey, TVal> VectorOfMapType<TKey, TVal>::s_vec_map_type_proto;
template <typename ElemType>
struct SequenceTensorTypeProto : ONNX_NAMESPACE::TypeProto {
SequenceTensorTypeProto() {
MLDataType dt = DataTypeImpl::GetTensorType<ElemType>();
const auto* elem_proto = dt->GetTypeProto();
mutable_sequence_type()->mutable_elem_type()->CopyFrom(*elem_proto);
auto* tensor_type = mutable_sequence_type()->mutable_elem_type()->mutable_tensor_type();
tensor_type->set_elem_type(TypeToDataType<ElemType>());
}
};
template <typename ElemType>
struct SequenceTensorType {
static const SequenceTensorTypeProto<ElemType> s_sequence_tensor_type_proto;
};
template <typename ElemType>
const SequenceTensorTypeProto<ElemType> SequenceTensorType<ElemType>::s_sequence_tensor_type_proto;
// To use OpTester:
// 1. Create one with the op name
// 2. Call AddAttribute with any attributes
// 3. Call AddInput for all the inputs
// 4. Call AddOutput with all expected outputs
// 5. Call Run
// Not all tensor types and output types are added, if a new input type is used, add it to the TypeToDataType list
// above for new output types, add a new specialization for Check<> See current usage for an example, should be self
// explanatory
class OpTester {
public:
// Default to the first opset that ORT was available (7).
// When operators are updated they need to explicitly add tests for the new opset version.
// This is due to the kernel matching logic. See KernelRegistry::VerifyKernelDef.
// Additionally, -1 is supported and defaults to the latest known opset.
//
// Defaulting to the latest opset version would result in existing operator implementations for non-CPU EPs to
// lose their test coverage until an implementation for the new version is added.
// e.g. there are CPU and GPU implementations for version 1 of an op. both are tested by a single OpTester test.
// opset changes from 1 to 2 and CPU implementation gets added. If 'opset_version' is 2 the kernel matching
// will find and run the CPU v2 implementation, but will not match the GPU v1 implementation.
// OpTester will say it was successful as at least one EP ran, and the GPU implementation of v1 no longer has
// test coverage.
explicit OpTester(const char* op, int opset_version = 7, const char* domain = onnxruntime::kOnnxDomain)
: op_(op), domain_(domain), opset_version_(opset_version) {
if (opset_version_ < 0) {
static int latest_onnx_version =
ONNX_NAMESPACE::OpSchemaRegistry::DomainToVersionRange().Map().at(ONNX_NAMESPACE::ONNX_DOMAIN).second;
opset_version_ = latest_onnx_version;
}
}
~OpTester();
// Set whether the NodeArg created by AddInput/AddOutput should include shape information
// for Tensor types. If not added, shape inferencing should resolve. If added, shape inferencing
// should validate. Default is to not add.
// Additionally a symbolic dimension will be added if symbolic_dim matches a dimension in the input.
OpTester& AddShapeToTensorData(bool add_shape = true, int symbolic_dim = -1) {
add_shape_to_tensor_data_ = add_shape;
add_symbolic_dim_to_tensor_data_ = symbolic_dim;
return *this;
}
// We have an initializer_list and vector version of the Add functions because std::vector is specialized for
// bool and we can't get the raw data out. So those cases must use an initializer_list
template <typename T>
void AddInput(const char* name, const std::vector<int64_t>& dims, const std::initializer_list<T>& values,
bool is_initializer = false) {
AddData(input_data_, name, dims, values.begin(), values.size(), is_initializer);
}
template <typename T>
void AddInput(const char* name, const std::vector<int64_t>& dims, const std::vector<T>& values,
bool is_initializer = false) {
AddData(input_data_, name, dims, values.data(), values.size(), is_initializer);
}
// Add other registered types, possibly experimental
template <typename T>
void AddInput(const char* name, const T& val) {
auto mltype = DataTypeImpl::GetType<T>();
ORT_ENFORCE(mltype != nullptr, "T must be a registered cpp type");
auto ptr = onnxruntime::make_unique<T>(val);
OrtValue value;
value.Init(ptr.get(), mltype, mltype->GetDeleteFunc());
ptr.release();
input_data_.push_back(Data(NodeArg(name, mltype->GetTypeProto()), std::move(value), optional<float>(),
optional<float>()));
}
template <typename T>
void AddInput(const char* name, T&& val) {
auto mltype = DataTypeImpl::GetType<T>();
ORT_ENFORCE(mltype != nullptr, "T must be a registered cpp type");
auto ptr = onnxruntime::make_unique<T>(std::move(val));
OrtValue value;
value.Init(ptr.get(), mltype, mltype->GetDeleteFunc());
ptr.release();
input_data_.push_back(Data(NodeArg(name, mltype->GetTypeProto()), std::move(value), optional<float>(),
optional<float>()));
}
template <typename T>
void AddSeqInput(const char* name, const SeqTensors<T>& seq_tensors) {
AddSeqData<T>(input_data_, name, seq_tensors);
}
template <typename T>
void AddSeqOutput(const char* name, const SeqTensors<T>& seq_tensors) {
AddSeqData<T>(output_data_, name, seq_tensors);
}
template <typename TKey, typename TVal>
void AddInput(const char* name, const std::map<TKey, TVal>& val) {
std::unique_ptr<std::map<TKey, TVal>> ptr = onnxruntime::make_unique<std::map<TKey, TVal>>(val);
OrtValue value;
value.Init(ptr.release(), DataTypeImpl::GetType<std::map<TKey, TVal>>(),
DataTypeImpl::GetType<std::map<TKey, TVal>>()->GetDeleteFunc());
input_data_.push_back(Data(NodeArg(name, &MMapType<TKey, TVal>::s_map_type_proto), std::move(value),
optional<float>(), optional<float>()));
}
template <typename T>
void AddMissingOptionalInput() {
std::string name; // empty == input doesn't exist
input_data_.push_back(Data(NodeArg(name, &TTensorType<T>::s_type_proto), OrtValue(), optional<float>(),
optional<float>()));
}
template <typename T>
void AddOutput(const char* name, const std::vector<int64_t>& dims, const std::initializer_list<T>& expected_values,
bool sort_output = false) {
AddData(output_data_, name, dims, expected_values.begin(), expected_values.size(), false, sort_output);
}
template <typename T>
void AddOutput(const char* name, const std::vector<int64_t>& dims, const std::vector<T>& expected_values,
bool sort_output = false) {
AddData(output_data_, name, dims, expected_values.data(), expected_values.size(), false, sort_output);
}
template <typename T>
void AddMissingOptionalOutput() {
std::string name; // empty == input doesn't exist
output_data_.push_back(Data(NodeArg(name, &TTensorType<T>::s_type_proto), OrtValue(), optional<float>(),
optional<float>()));
}
// Add other registered types, possibly experimental
template <typename T>
void AddOutput(const char* name, const T& val) {
auto mltype = DataTypeImpl::GetType<T>();
ORT_ENFORCE(mltype != nullptr, "T must be a registered cpp type");
auto ptr = onnxruntime::make_unique<T>(val);
OrtValue value;
value.Init(ptr.get(), mltype, mltype->GetDeleteFunc());
ptr.release();
output_data_.push_back(Data(NodeArg(name, mltype->GetTypeProto()), std::move(value), optional<float>(),
optional<float>()));
}
template <typename T>
void AddOutput(const char* name, T&& val) {
auto mltype = DataTypeImpl::GetType<T>();
ORT_ENFORCE(mltype != nullptr, "T must be a registered cpp type");
auto ptr = onnxruntime::make_unique<T>(std::move(val));
OrtValue value;
value.Init(ptr.get(), mltype, mltype->GetDeleteFunc());
ptr.release();
output_data_.push_back(Data(NodeArg(name, mltype->GetTypeProto()), std::move(value), optional<float>(),
optional<float>()));
}
// Add non tensor output
template <typename TKey, typename TVal>
void AddOutput(const char* name, const std::vector<std::map<TKey, TVal>>& val) {
auto ptr = onnxruntime::make_unique<std::vector<std::map<TKey, TVal>>>(val);
OrtValue ml_value;
ml_value.Init(ptr.release(), DataTypeImpl::GetType<std::vector<std::map<TKey, TVal>>>(),
DataTypeImpl::GetType<std::vector<std::map<TKey, TVal>>>()->GetDeleteFunc());
output_data_.push_back(Data(NodeArg(name, &VectorOfMapType<TKey, TVal>::s_vec_map_type_proto), std::move(ml_value),
optional<float>(), optional<float>()));
}
void AddCustomOpRegistry(std::shared_ptr<CustomRegistry> registry) {
custom_schema_registries_.push_back(registry->GetOpschemaRegistry());
custom_session_registries_.push_back(registry);
}
void SetOutputAbsErr(const char* name, float v);
void SetOutputRelErr(const char* name, float v);
// Number of times to call InferenceSession::Run. The same feeds are used each time.
// e.g. used to verify the generator ops behave as expected
void SetNumRunCalls(int n) {
ORT_ENFORCE(n > 0);
num_run_calls_ = n;
}
template <typename T>
void AddAttribute(std::string name, T value) {
// Generate a the proper AddAttribute call for later
add_attribute_funcs_.emplace_back([name = std::move(name), value = std::move(value)](onnxruntime::Node& node) {
node.AddAttribute(name, value);
});
}
enum class ExpectResult { kExpectSuccess,
kExpectFailure };
void Run(ExpectResult expect_result = ExpectResult::kExpectSuccess, const std::string& expected_failure_string = "",
const std::unordered_set<std::string>& excluded_provider_types = {},
const RunOptions* run_options = nullptr,
std::vector<std::unique_ptr<IExecutionProvider>>* execution_providers = nullptr,
ExecutionMode execution_mode = ExecutionMode::ORT_SEQUENTIAL);
void Run(SessionOptions session_options,
ExpectResult expect_result = ExpectResult::kExpectSuccess,
const std::string& expected_failure_string = "",
const std::unordered_set<std::string>& excluded_provider_types = {},
const RunOptions* run_options = nullptr,
std::vector<std::unique_ptr<IExecutionProvider>>* execution_providers = nullptr);
struct Data {
onnxruntime::NodeArg def_;
OrtValue data_;
optional<float> relative_error_;
optional<float> absolute_error_;
bool sort_output_;
Data(onnxruntime::NodeArg&& def, OrtValue&& data, optional<float>&& rel, optional<float>&& abs,
bool sort_output = false)
: def_(std::move(def)),
data_(std::move(data)),
relative_error_(std::move(rel)),
absolute_error_(abs),
sort_output_(sort_output) {}
Data(Data&&) = default;
Data& operator=(Data&&) = default;
};
protected:
virtual void AddNodes(onnxruntime::Graph& graph, std::vector<onnxruntime::NodeArg*>& graph_input_defs,
std::vector<onnxruntime::NodeArg*>& graph_output_defs,
std::vector<std::function<void(onnxruntime::Node& node)>>& add_attribute_funcs);
void AddInitializers(onnxruntime::Graph& graph);
void FillFeedsAndOutputNames(std::unordered_map<std::string, OrtValue>& feeds,
std::vector<std::string>& output_names);
std::unique_ptr<onnxruntime::Model> BuildGraph();
const char* op_;
#ifndef NDEBUG
bool run_called_{};
#endif
private:
template <typename T>
void AddData(std::vector<Data>& data, const char* name, const std::vector<int64_t>& dims, const T* values,
int64_t values_count, bool is_initializer = false, bool sort_output = false) {
try {
TensorShape shape{dims};
ORT_ENFORCE(shape.Size() == values_count, values_count, " input values doesn't match tensor size of ",
shape.Size());
auto allocator = test::AllocatorManager::Instance().GetAllocator(CPU);
auto p_tensor = onnxruntime::make_unique<Tensor>(DataTypeImpl::GetType<T>(), shape, allocator);
auto* data_ptr = p_tensor->template MutableData<T>();
for (int64_t i = 0; i < values_count; i++) {
data_ptr[i] = values[i];
}
std::vector<int64_t> dims_for_proto{dims};
if (add_symbolic_dim_to_tensor_data_ >= 0 &&
dims.size() > static_cast<size_t>(add_symbolic_dim_to_tensor_data_)) {
dims_for_proto[add_symbolic_dim_to_tensor_data_] = -1;
}
TTypeProto<T> type_proto(add_shape_to_tensor_data_ ? &dims_for_proto : nullptr);
OrtValue value;
value.Init(p_tensor.release(), DataTypeImpl::GetType<Tensor>(),
DataTypeImpl::GetType<Tensor>()->GetDeleteFunc());
data.push_back(Data(NodeArg(name, &type_proto), std::move(value), optional<float>(), optional<float>(), sort_output));
if (is_initializer) initializer_index_.push_back(data.size() - 1);
} catch (const std::exception& ex) {
std::cerr << "AddData for '" << name << "' threw: " << ex.what();
throw;
}
}
template <typename T>
void AddSeqData(std::vector<Data>& data, const char* name, const SeqTensors<T>& seq_tensors) {
auto num_tensors = seq_tensors.tensors.size();
std::vector<Tensor> tensors;
tensors.resize(num_tensors);
auto elem_type = DataTypeImpl::GetType<T>();
for (size_t i = 0; i < num_tensors; ++i) {
TensorShape shape{seq_tensors.tensors[i].shape};
auto values_count = static_cast<int64_t>(seq_tensors.tensors[i].data.size());
ORT_ENFORCE(shape.Size() == values_count, values_count,
" input values doesn't match tensor size of ", shape.Size());
auto allocator = test::AllocatorManager::Instance().GetAllocator(CPU);
auto& tensor = tensors[i];
tensor = Tensor(elem_type,
shape,
allocator);
auto* data_ptr = tensor.template MutableData<T>();
for (int64_t x = 0; x < values_count; ++x) {
data_ptr[x] = seq_tensors.tensors[i].data[x];
}
}
OrtValue value;
auto mltype = DataTypeImpl::GetType<TensorSeq>();
auto ptr = onnxruntime::make_unique<TensorSeq>(elem_type);
ptr->SetElements(std::move(tensors));
value.Init(ptr.get(), mltype, mltype->GetDeleteFunc());
ptr.release();
data.push_back(Data(NodeArg(name, &SequenceTensorType<T>::s_sequence_tensor_type_proto), std::move(value),
optional<float>(), optional<float>()));
}
void ExecuteModel(Model& model, InferenceSession& session_object, ExpectResult expect_result,
const std::string& expected_failure_string, const RunOptions* run_options,
std::unordered_map<std::string, OrtValue> feeds, std::vector<std::string> output_names,
const std::string& provider_type);
const char* domain_;
int opset_version_;
bool add_shape_to_tensor_data_ = true;
int add_symbolic_dim_to_tensor_data_ = -1;
int num_run_calls_ = 1;
std::vector<Data> input_data_;
std::vector<Data> output_data_;
std::vector<size_t> initializer_index_;
std::vector<std::function<void(onnxruntime::Node& node)>> add_attribute_funcs_;
IOnnxRuntimeOpSchemaRegistryList custom_schema_registries_;
std::vector<std::shared_ptr<CustomRegistry>> custom_session_registries_;
};
template <typename TException>
void ExpectThrow(OpTester& test, const std::string& error_msg) {
try {
test.Run();
// should throw and not reach this
EXPECT_TRUE(false) << "Expected Run() to throw";
} catch (TException ex) {
EXPECT_THAT(ex.what(), testing::HasSubstr(error_msg));
}
}
void DebugTrap();
void Check(const OpTester::Data& expected_data, const Tensor& output_tensor, const std::string& provider_type);
// Only used for CUDA test since no toher kernel has float 16 support
#ifdef USE_CUDA
inline void ConvertFloatToMLFloat16(const float* f_datat, MLFloat16* h_data, int input_size) {
auto in_vector = ConstEigenVectorMap<float>(f_datat, input_size);
auto output_vector = EigenVectorMap<Eigen::half>(static_cast<Eigen::half*>(static_cast<void*>(h_data)), input_size);
output_vector = in_vector.template cast<Eigen::half>();
}
#endif
inline void ConvertMLFloat16ToFloat(const MLFloat16* h_data, float* f_data, int input_size) {
auto in_vector =
ConstEigenVectorMap<Eigen::half>(static_cast<const Eigen::half*>(static_cast<const void*>(h_data)), input_size);
auto output_vector = EigenVectorMap<float>(f_data, input_size);
output_vector = in_vector.template cast<float>();
}
} // namespace test
} // namespace onnxruntime
| {
"alphanum_fraction": 0.7015180671,
"avg_line_length": 39.3025210084,
"ext": "h",
"hexsha": "36b477b5b13f055027c5968252062c4b672960a2",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T13:49:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-07-20T13:49:38.000Z",
"max_forks_repo_head_hexsha": "1d79926d273d01817ce93f001f36f417ab05f8a0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MaximKalininMS/onnxruntime",
"max_forks_repo_path": "onnxruntime/test/providers/provider_test_utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1d79926d273d01817ce93f001f36f417ab05f8a0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MaximKalininMS/onnxruntime",
"max_issues_repo_path": "onnxruntime/test/providers/provider_test_utils.h",
"max_line_length": 124,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "1d79926d273d01817ce93f001f36f417ab05f8a0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MaximKalininMS/onnxruntime",
"max_stars_repo_path": "onnxruntime/test/providers/provider_test_utils.h",
"max_stars_repo_stars_event_max_datetime": "2019-12-25T16:47:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-12-25T16:47:43.000Z",
"num_tokens": 5535,
"size": 23385
} |
#ifndef SPECTRALSUBTRACTION_H
#define SPECTRALSUBTRACTION_H
#include <stdio.h>
#include <assert.h>
#include <float.h>
#include <gsl/gsl_block.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_fft_complex.h>
#include <common/refcount.h>
#include "common/jexception.h"
#include "stream/stream.h"
#include "modulated/modulated.h"
class PSDEstimator {
public:
PSDEstimator(unsigned fftLen2);
~PSDEstimator();
bool read_estimates( const String& fn );
bool write_estimates( const String& fn );
const gsl_vector* estimate() const {
return estimates_;
}
protected:
gsl_vector* estimates_; /* estimated noise PSD */
};
typedef refcount_ptr<PSDEstimator> PSDEstimatorPtr;
/**
@class estimate the noise PSD for spectral subtraction (SS)
1. construct an object
2. add a noise sample
3. get noise estimates
*/
class AveragePSDEstimator : public PSDEstimator {
public:
/**
@brief A constructor for SS
@param unsigned fftLen2[in] the half of the FFT point
@param double alpha[in] the forgetting factor for recursive averaging.
If this is negative, the average is used
as the noise PSD estimate.
*/
AveragePSDEstimator(unsigned fftLen2, float alpha = -1.0 );
~AveragePSDEstimator();
void clear_samples();
const gsl_vector* average();
bool add_sample( const gsl_vector_complex *sample );
void clear();
protected:
float alpha_;
bool sample_added_;
list<gsl_vector *> sampleL_;
};
typedef Inherit<AveragePSDEstimator, PSDEstimatorPtr> AveragePSDEstimatorPtr;
class SpectralSubtractor : public VectorComplexFeatureStream {
public:
SpectralSubtractor(unsigned fftLen, bool halfBandShift = false, float ft=1.0, float flooringV=0.001, const String& nm = "SpectralSubtractor");
~SpectralSubtractor();
virtual const gsl_vector_complex* next(int frameX = -5);
virtual void reset();
void clear(){
for(NoisePSDIterator_ itr = noisePSDList_.begin(); itr != noisePSDList_.end(); itr++)
(*itr)->clear();
}
void set_noise_over_estimation_factor(float ft){ ft_ = ft; }
void set_channel(VectorComplexFeatureStreamPtr& chan, double alpha=-1 );
void start_training(){ training_started_ = true; }
void stop_training();
void clear_noise_samples();
void start_noise_subtraction(){ start_noise_subtraction_ = true; }
void stop_noise_subtraction(){ start_noise_subtraction_ = false; }
bool read_noise_file(const String& fn, unsigned idx=0);
bool write_noise_file(const String& fn, unsigned idx=0){ return noisePSDList_.at(idx)->write_estimates(fn); }
#ifdef ENABLE_LEGACY_BTK_API
void setNoiseOverEstimationFactor(float ft){ set_noise_over_estimation_factor(ft); }
void setChannel(VectorComplexFeatureStreamPtr& chan, double alpha=-1){ set_channel(chan, alpha); }
void startTraining(){ start_training(); }
void stopTraining(){ stop_training(); }
void clearNoiseSamples(){ clear_noise_samples(); }
void startNoiseSubtraction(){ start_noise_subtraction(); }
void stopNoiseSubtraction(){ stop_noise_subtraction(); }
bool readNoiseFile( const String& fn, unsigned idx=0 ){ return read_noise_file(fn, idx); }
bool writeNoiseFile( const String& fn, unsigned idx=0 ){ return write_noise_file(fn, idx); }
#endif
protected:
typedef list<VectorComplexFeatureStreamPtr> ChannelList_;
typedef ChannelList_::iterator ChannelIterator_;
typedef vector<AveragePSDEstimatorPtr> NoisePSDList_;
typedef NoisePSDList_::iterator NoisePSDIterator_;
ChannelList_ channelList_;
NoisePSDList_ noisePSDList_;
unsigned fftLen_;
unsigned fftLen2_;
bool halfBandShift_;
bool training_started_;
unsigned totalTrainingSampleN_;
float ft_;
float flooringV_;
bool start_noise_subtraction_;
};
typedef Inherit<SpectralSubtractor, VectorComplexFeatureStreamPtr> SpectralSubtractorPtr;
// ----- definition for class 'WienerFilter' -----
//
class WienerFilter : public VectorComplexFeatureStream {
public:
WienerFilter( VectorComplexFeatureStreamPtr &targetSignal, VectorComplexFeatureStreamPtr &noiseSignal, bool halfBandShift=false, float alpha=0.0, float flooringV=0.001, double beta=1.0, const String& nm = "WienerFilter");
~WienerFilter();
virtual const gsl_vector_complex* next(int frameX = -5);
virtual void reset();
void set_noise_amplification_factor(double beta){ beta_ = beta; }
void start_updating_noise_PSD(){ update_noise_PSD_ = true; }
void stop_updating_noise_PSD(){ update_noise_PSD_ = false; }
#ifdef ENABLE_LEGACY_BTK_API
void setNoiseAmplificationFactor(double beta){ set_noise_amplification_factor(beta); }
void startUpdatingNoisePSD(){ start_updating_noise_PSD(); }
void stopUpdatingNoisePSD(){ stop_updating_noise_PSD(); }
#endif
private:
gsl_vector *prev_PSDs_;
gsl_vector *prev_PSDn_;
VectorComplexFeatureStreamPtr target_signal_;
VectorComplexFeatureStreamPtr noise_signal_;
bool halfBandShift_;
float alpha_; // forgetting factor
float flooringV_;
float beta_; // amplification coefficient for a noise signal
bool update_noise_PSD_;
unsigned fftLen_;
unsigned fftLen2_;
};
typedef Inherit<WienerFilter, VectorComplexFeatureStreamPtr> WienerFilterPtr;
#endif
| {
"alphanum_fraction": 0.7358941371,
"avg_line_length": 34.2201257862,
"ext": "h",
"hexsha": "585034a8f3b32ff15df321c25cb4182abcc80e77",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z",
"max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "musiclvme/distant_speech_recognition",
"max_forks_repo_path": "btk20_src/postfilter/spectralsubtraction.h",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "musiclvme/distant_speech_recognition",
"max_issues_repo_path": "btk20_src/postfilter/spectralsubtraction.h",
"max_line_length": 223,
"max_stars_count": 136,
"max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "musiclvme/distant_speech_recognition",
"max_stars_repo_path": "btk20_src/postfilter/spectralsubtraction.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z",
"num_tokens": 1355,
"size": 5441
} |
#include <stdio.h>
#include <gsl/gsl_qrng.h>
int
main (void)
{
int i;
gsl_qrng * q = gsl_qrng_alloc (gsl_qrng_sobol, 2);
for (i = 0; i < 1024; i++)
{
double v[2];
gsl_qrng_get (q, v);
printf ("%.5f %.5f\n", v[0], v[1]);
}
gsl_qrng_free (q);
return 0;
}
| {
"alphanum_fraction": 0.5273972603,
"avg_line_length": 14.6,
"ext": "c",
"hexsha": "5275209a102d52232a15e5a09e63214a13bf435d",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/qrng.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/qrng.c",
"max_line_length": 52,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/qrng.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 118,
"size": 292
} |
/*
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @brief interface for TransactionReceipt
* @file TransactionReceipt.h
*/
#pragma once
#include "ProtocolTypeDef.h"
#include <bcos-crypto/interfaces/crypto/CryptoSuite.h>
#include <bcos-utilities/FixedBytes.h>
#include <gsl/span>
namespace bcos
{
namespace protocol
{
class LogEntry;
class TransactionReceipt
{
public:
using Ptr = std::shared_ptr<TransactionReceipt>;
using ConstPtr = std::shared_ptr<const TransactionReceipt>;
explicit TransactionReceipt(bcos::crypto::CryptoSuite::Ptr _cryptoSuite)
: m_cryptoSuite(_cryptoSuite)
{}
virtual ~TransactionReceipt() {}
virtual void decode(bytesConstRef _receiptData) = 0;
virtual void encode(bytes& _encodedData) const = 0;
virtual bytesConstRef encode(bool _onlyHashFieldData = false) const = 0;
virtual bcos::crypto::HashType hash() const
{
auto hashFields = encode(true);
return m_cryptoSuite->hash(hashFields);
}
virtual int32_t version() const = 0;
virtual u256 gasUsed() const = 0; // TODO: remove from hash
virtual std::string_view contractAddress() const = 0;
virtual int32_t status() const = 0;
virtual bytesConstRef output() const = 0;
virtual gsl::span<const LogEntry> logEntries() const = 0;
virtual bcos::crypto::CryptoSuite::Ptr cryptoSuite() { return m_cryptoSuite; }
virtual BlockNumber blockNumber() const = 0;
// additional information on transaction execution, no need to be involved in the hash
// calculation
virtual std::string const& message() const = 0;
virtual void setMessage(std::string const& _message) = 0;
virtual void setMessage(std::string&& _message) = 0;
protected:
bcos::crypto::CryptoSuite::Ptr m_cryptoSuite;
};
using Receipts = std::vector<TransactionReceipt::Ptr>;
using ReceiptsPtr = std::shared_ptr<Receipts>;
using ReceiptsConstPtr = std::shared_ptr<const Receipts>;
} // namespace protocol
} // namespace bcos
| {
"alphanum_fraction": 0.7223730128,
"avg_line_length": 34.3866666667,
"ext": "h",
"hexsha": "0dff070058180172ac6f8f79ade67d8db3d2c2e2",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "contropist/FISCO-BCOS",
"max_forks_repo_path": "bcos-framework/interfaces/protocol/TransactionReceipt.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "contropist/FISCO-BCOS",
"max_issues_repo_path": "bcos-framework/interfaces/protocol/TransactionReceipt.h",
"max_line_length": 90,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1605c371448b410674559bb1c9e98bab722f036b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "contropist/FISCO-BCOS",
"max_stars_repo_path": "bcos-framework/interfaces/protocol/TransactionReceipt.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 629,
"size": 2579
} |
#ifndef PFLOW_H
#define PFLOW_H
#include <petsc.h>
#define epsilon 1E-8 /**< epsilon value for finite differences */
#define MAXLINE 1000 /**< Max. number of characters in a line */
#define ISOLATED_BUS 4 /**< Isolated bus */
#define REF_BUS 3 /**< Reference bus (swing bus) */
#define PV_BUS 2 /**< PV (voltage-controlled) bus */
#define PQ_BUS 1 /**< PQ bus */
#define NGEN_AT_BUS_MAX 15 /**< Maximum number of generators allowed at a bus */
#define NLOAD_AT_BUS_MAX 10 /**< Maximum number of loads allowed at a bus */
#define NPHASE 1 /**< Per-phase analysis */
typedef void* PFLOW;
extern PetscErrorCode PFLOWCreate(MPI_Comm,PFLOW*);
extern PetscErrorCode PFLOWDestroy(PFLOW*);
extern PetscErrorCode PFLOWReadMatPowerData(PFLOW,const char[]);
extern PetscErrorCode PFLOWSolve(PFLOW);
extern PetscErrorCode PFLOWGetBusVoltage(PFLOW,PetscInt,PetscScalar*,PetscScalar*,PetscBool*);
extern PetscErrorCode PFLOWSetLoadPower(PFLOW,PetscInt,PetscScalar,PetscScalar);
#endif
| {
"alphanum_fraction": 0.7586912065,
"avg_line_length": 34.9285714286,
"ext": "h",
"hexsha": "7e71f5509a9744502e3bbf64c9c614b9b667e512",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-09-23T19:30:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-08-01T21:49:40.000Z",
"max_forks_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "GMLC-TDC/Use-Cases",
"max_forks_repo_path": "ANL-TD-Iterative-Pflow/include/pflow.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "GMLC-TDC/Use-Cases",
"max_issues_repo_path": "ANL-TD-Iterative-Pflow/include/pflow.h",
"max_line_length": 94,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "GMLC-TDC/Use-Cases",
"max_stars_repo_path": "ANL-TD-Iterative-Pflow/include/pflow.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-04T07:27:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-04T07:27:34.000Z",
"num_tokens": 244,
"size": 978
} |
/* specfunc/clausen.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_trig.h>
#include <gsl/gsl_sf_clausen.h>
#include "chebyshev.h"
#include "cheb_eval.c"
static double aclaus_data[15] = {
2.142694363766688447e+00,
0.723324281221257925e-01,
0.101642475021151164e-02,
0.3245250328531645e-04,
0.133315187571472e-05,
0.6213240591653e-07,
0.313004135337e-08,
0.16635723056e-09,
0.919659293e-11,
0.52400462e-12,
0.3058040e-13,
0.18197e-14,
0.1100e-15,
0.68e-17,
0.4e-18
};
static cheb_series aclaus_cs = {
aclaus_data,
14,
-1, 1,
8 /* FIXME: this is a guess, correct value needed here BJG */
};
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int gsl_sf_clausen_e(double x, gsl_sf_result *result)
{
const double x_cut = M_PI * GSL_SQRT_DBL_EPSILON;
double sgn = 1.0;
int status_red;
if(x < 0.0) {
x = -x;
sgn = -1.0;
}
/* Argument reduction to [0, 2pi) */
status_red = gsl_sf_angle_restrict_pos_e(&x);
/* Further reduction to [0,pi) */
if(x > M_PI) {
/* simulated extra precision: 2PI = p0 + p1 */
const double p0 = 6.28125;
const double p1 = 0.19353071795864769253e-02;
x = (p0 - x) + p1;
sgn = -sgn;
}
if(x == 0.0) {
result->val = 0.0;
result->err = 0.0;
}
else if(x < x_cut) {
result->val = x * (1.0 - log(x));
result->err = x * GSL_DBL_EPSILON;
}
else {
const double t = 2.0*(x*x / (M_PI*M_PI) - 0.5);
gsl_sf_result result_c;
cheb_eval_e(&aclaus_cs, t, &result_c);
result->val = x * (result_c.val - log(x));
result->err = x * (result_c.err + GSL_DBL_EPSILON);
}
result->val *= sgn;
return status_red;
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_clausen(const double x)
{
EVAL_RESULT(gsl_sf_clausen_e(x, &result));
}
| {
"alphanum_fraction": 0.6431701972,
"avg_line_length": 24.4464285714,
"ext": "c",
"hexsha": "ebaebbd62e2263107d1c5ed03d2a3a76585b708b",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/clausen.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/clausen.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/specfunc/clausen.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z",
"num_tokens": 961,
"size": 2738
} |
/**
*
* @file core_zlacpy_pivot.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mathieu Faverge
* @date 2013-02-01
* @precisions normal z -> c d s
*
**/
#include <lapacke.h>
#include "common.h"
#define A(m, n) BLKADDR(descA, PLASMA_Complex64_t, m, n)
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex64_t
*
* CORE_zlacpy_pivot extracts the original version of the rows selected by the
* ipiv array and copies them into a new buffer.
*
* This kernel is used by tournament pivoting algorithms, to extract the
* selected rows from the original matrix that will make it to the next level
* of the tournament.
*
*******************************************************************************
*
* @param[in] descA
* The descriptor of the matrix A in which the kernel will extract the
* original rows.
*
* @param[in] direct
* @arg PlasmaRowwise: The extracted rows are stored in column major layout.
* @arg PlasmaColumnwise: The extracted rows are store in row major layout.
*
* @param[in] k1
* The first element of IPIV for which a row interchange will
* be done.
*
* @param[in] k2
* The last element of IPIV for which a row interchange will
* be done.
*
* @param[in] ipiv
* The pivot indices; Only the element in position k1 to k2
* are accessed. The pivots should be included in the interval 1 to A.m
*
* @param[in,out] rankin
* On entry, the global indices relative to the full matrix A
* factorized, in the local sub-matrix. If init == 1, rankin is
* initialized to A.i, .. A.i+descA.m
* On exit, rows are permutted according to ipiv.
*
* @param[out] rankout
* On exit, contains the global indices of the first (k2-k1+1) rows.
*
* @param[out] A
* An lda-by-descA.n matrix. On exit, A contains the original version
* of the rows selected by the pivoting process.
*
* @param[in] lda
* The leading dimension of the array A. lda >= max(1,(k2-k1+1)).
*
* @param[in] init
* True if rankin needs to be initialized.
* False, if rankin contains already initialized data.
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if INFO = -k, the k-th argument had an illegal value
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zlacpy_pivot = PCORE_zlacpy_pivot
#define CORE_zlacpy_pivot PCORE_zlacpy_pivot
#endif
int CORE_zlacpy_pivot( const PLASMA_desc descA,
PLASMA_enum direct, int k1, int k2, const int *ipiv,
int *rankin, int *rankout,
PLASMA_Complex64_t *A, int lda,
int init)
{
int i, ip, it, ir, ld;
const int *lpiv;
int *ro = rankout;
/* Init rankin if first step */
if ( init ) {
int val = descA.i;
for(i=0; i<descA.m; i++, val++) {
rankin[i] = val;
}
}
/* Generate the rankout */
ro = rankout;
lpiv = ipiv;
for(i=k1-1; i<k2; i++, ro++, lpiv++) {
*ro = rankin[ (*lpiv) - 1 ];
rankin[ (*lpiv) - 1 ] = rankin[ i ];
}
/* Extract the rows */
if (direct == PlasmaRowwise) {
ro = rankout;
for(i=k1-1; i<k2; i++, ro++) {
ip = (*ro) - descA.i;
it = ip / descA.mb;
ir = ip % descA.mb;
ld = BLKLDD(descA, it);
cblas_zcopy(descA.n, A(it, 0) + ir, ld,
A + i, lda );
}
}
else {
ro = rankout;
for(i=k1-1; i<k2; i++, ro++) {
ip = (*ro) - descA.i;
it = ip / descA.mb;
ir = ip % descA.mb;
ld = BLKLDD(descA, it);
cblas_zcopy(descA.n, A(it, 0) + ir, ld,
A + i*lda, 1 );
}
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.5187864644,
"avg_line_length": 31.7407407407,
"ext": "c",
"hexsha": "9d8069e173b84e7d66259bffcd650f77f11d730f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas/core_zlacpy_pivot.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_zlacpy_pivot.c",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_zlacpy_pivot.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1153,
"size": 4285
} |
#pragma once
#include <imageview/IsPixelFormat.h>
#include <imageview/internal/ImageViewIterator.h>
#include <imageview/internal/ImageViewStorage.h>
#include <imageview/internal/PixelRef.h>
#include <gsl/assert>
#include <gsl/span>
#include <cstddef>
#include <stdexcept>
namespace imageview {
template <class PixelFormat, bool Mutable = false>
class ImageRowView {
public:
static_assert(IsPixelFormat<PixelFormat>::value, "Not a PixelFormat.");
using byte_type = std::conditional_t<Mutable, std::byte, const std::byte>;
using value_type = typename PixelFormat::color_type;
// TODO: consider using 'const value_type' instead of 'value_type' for immutable views.
using reference = std::conditional_t<Mutable, detail::PixelRef<PixelFormat>, value_type>;
// Constant LegacyInputIterator whose value_type is @value_type. The type satisfies all
// requirements of LegacyRandomAccessIterator except the multipass guarantee: for dereferenceable iterators a and b
// with a == b, there is no requirement that *a and *b are bound to the same object.
using const_iterator = detail::ImageViewIterator<PixelFormat, false>;
using iterator = detail::ImageViewIterator<PixelFormat, Mutable>;
// Constructs an empty view.
// This constructor is only available if PixelFormat is default-constructible.
template <class Enable = std::enable_if_t<std::is_default_constructible_v<PixelFormat>>>
constexpr ImageRowView() noexcept(noexcept(std::is_nothrow_default_constructible_v<PixelFormat>)){};
// Constructs an empty view.
// \param pixel_format - instance of PixelFormat to use.
constexpr explicit ImageRowView(const PixelFormat& pixel_format) noexcept(
noexcept(std::is_nothrow_copy_constructible_v<PixelFormat>));
// Constructs an empty view.
// \param pixel_format - instance of PixelFormat to use.
constexpr explicit ImageRowView(PixelFormat&& pixel_format) noexcept(
noexcept(std::is_nothrow_move_constructible_v<PixelFormat>));
// Constructs a flat view into the given bitmap.
// This constructor is only available if PixelFormat is default-constructible.
// \param data - bitmap data.
// \param width - the number of pixels in the bitmap.
//
// Expects(data.size() == width * PixelFormat::kBytesPerPixel)
template <class Enable = std::enable_if_t<std::is_default_constructible_v<PixelFormat>>>
constexpr ImageRowView(gsl::span<byte_type> data,
std::size_t width) noexcept(noexcept(std::is_nothrow_default_constructible_v<PixelFormat>));
// Constructs a flat view into the given bitmap.
// \param data - bitmap data.
// \param width - the number of pixels in the bitmap.
// \param pixel_format - instance of PixelFormat to use.
//
// Expects(data.size() == width * PixelFormat::kBytesPerPixel)
constexpr ImageRowView(gsl::span<byte_type> data, std::size_t width, const PixelFormat& pixel_format) noexcept(
noexcept(std::is_nothrow_copy_constructible_v<PixelFormat>));
// Constructs a flat view into the given bitmap.
// \param data - bitmap data.
// \param width - the number of pixels in the bitmap.
// \param pixel_format - instance of PixelFormat to use.
//
// Expects(data.size() == width * PixelFormat::kBytesPerPixel)
constexpr ImageRowView(gsl::span<byte_type> data, std::size_t width, PixelFormat&& pixel_format) noexcept(
noexcept(std::is_nothrow_move_constructible_v<PixelFormat>));
// Construct a read-only view from a mutable view.
template <class Enable = std::enable_if_t<!Mutable>>
constexpr ImageRowView(ImageRowView<PixelFormat, !Mutable> row_view);
// Returns the pixel format used by this image.
constexpr const PixelFormat& pixelFormat() const noexcept;
// Returns the bitmap data.
constexpr gsl::span<byte_type> data() const noexcept;
// Returns the total number of pixels in this view.
constexpr std::size_t size() const noexcept;
// Returns true if the view is empty (i.e. has 0 pixels), false otherwise.
constexpr bool empty() const noexcept;
// Returns the size of the referenced bitmap in bytes, i.e.
// size() * PixelFormat::kBytesPerPixel
constexpr std::size_t size_bytes() const noexcept;
// Returns an iterator to the first pixel.
constexpr iterator begin() const;
// Returns a const iterator to the first pixel.
constexpr const_iterator cbegin() const;
// Returns an iterator past the last pixel.
constexpr iterator end() const;
// Returns a const iterator past the last pixel.
constexpr const_iterator cend() const;
// Returns the color of the specified pixel.
// \param index - 0-based index of the pixel. No bounds checking is performed - the behavior is undefined if @index is
// outside [0; size()).
constexpr reference operator[](std::size_t index) const;
// Returns the color of the specified pixel.
// \param index - 0-based index of the pixel.
// \throw std::out_of_range if @index is outside [0; size()).
constexpr reference at(std::size_t index) const;
private:
detail::ImageViewStorage<PixelFormat, Mutable> storage_;
std::size_t width_ = 0;
};
template <class PixelFormat, bool Mutable>
constexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(const PixelFormat& pixel_format) noexcept(
noexcept(std::is_nothrow_copy_constructible_v<PixelFormat>))
: storage_(nullptr, pixel_format) {}
template <class PixelFormat, bool Mutable>
constexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(PixelFormat&& pixel_format) noexcept(
noexcept(std::is_nothrow_move_constructible_v<PixelFormat>))
: storage_(nullptr, std::move(pixel_format)) {}
template <class PixelFormat, bool Mutable>
template <class Enable>
constexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(gsl::span<byte_type> data, std::size_t width) noexcept(
noexcept(std::is_nothrow_default_constructible_v<PixelFormat>))
: storage_(data.data()), width_(width) {
Expects(data.size() == width * PixelFormat::kBytesPerPixel);
}
template <class PixelFormat, bool Mutable>
constexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(
gsl::span<byte_type> data, std::size_t width,
const PixelFormat& pixel_format) noexcept(noexcept(std::is_nothrow_copy_constructible_v<PixelFormat>))
: storage_(data.data(), pixel_format), width_(width) {
Expects(data.size() == width * PixelFormat::kBytesPerPixel);
}
template <class PixelFormat, bool Mutable>
constexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(
gsl::span<byte_type> data, std::size_t width,
PixelFormat&& pixel_format) noexcept(noexcept(std::is_nothrow_move_constructible_v<PixelFormat>))
: storage_(data.data(), std::move(pixel_format)), width_(width) {
Expects(data.size() == width * PixelFormat::kBytesPerPixel);
}
template <class PixelFormat, bool Mutable>
template <class Enable>
constexpr ImageRowView<PixelFormat, Mutable>::ImageRowView(ImageRowView<PixelFormat, !Mutable> row_view)
: ImageRowView(row_view.data(), row_view.size(), row_view.pixelFormat()) {}
template <class PixelFormat, bool Mutable>
constexpr const PixelFormat& ImageRowView<PixelFormat, Mutable>::pixelFormat() const noexcept {
return storage_.pixelFormat();
}
template <class PixelFormat, bool Mutable>
constexpr auto ImageRowView<PixelFormat, Mutable>::data() const noexcept -> gsl::span<byte_type> {
return gsl::span<byte_type>(storage_.data(), size_bytes());
}
template <class PixelFormat, bool Mutable>
constexpr std::size_t ImageRowView<PixelFormat, Mutable>::size() const noexcept {
return width_;
}
template <class PixelFormat, bool Mutable>
constexpr bool ImageRowView<PixelFormat, Mutable>::empty() const noexcept {
return width_ == 0;
}
template <class PixelFormat, bool Mutable>
constexpr std::size_t ImageRowView<PixelFormat, Mutable>::size_bytes() const noexcept {
return width_ * PixelFormat::kBytesPerPixel;
}
template <class PixelFormat, bool Mutable>
constexpr auto ImageRowView<PixelFormat, Mutable>::begin() const -> iterator {
return iterator(storage_.data_, storage_.pixelFormat());
}
template <class PixelFormat, bool Mutable>
constexpr auto ImageRowView<PixelFormat, Mutable>::cbegin() const -> const_iterator {
return const_iterator(storage_.data_, storage_.pixelFormat());
}
template <class PixelFormat, bool Mutable>
constexpr auto ImageRowView<PixelFormat, Mutable>::end() const -> iterator {
return iterator(storage_.data_ + width_ * PixelFormat::kBytesPerPixel, storage_.pixelFormat());
}
template <class PixelFormat, bool Mutable>
constexpr auto ImageRowView<PixelFormat, Mutable>::cend() const -> const_iterator {
return const_iterator(storage_.data_ + width_ * PixelFormat::kBytesPerPixel, storage_.pixelFormat());
}
template <class PixelFormat, bool Mutable>
constexpr auto ImageRowView<PixelFormat, Mutable>::operator[](std::size_t index) const -> reference {
const gsl::span<byte_type, PixelFormat::kBytesPerPixel> pixel_data(
storage_.data() + index * PixelFormat::kBytesPerPixel, PixelFormat::kBytesPerPixel);
if constexpr (Mutable) {
return detail::PixelRef<PixelFormat>(pixel_data, pixelFormat());
} else {
return pixelFormat().read(pixel_data);
}
}
template <class PixelFormat, bool Mutable>
constexpr auto ImageRowView<PixelFormat, Mutable>::at(std::size_t index) const -> reference {
if (index >= width_) {
throw std::out_of_range("ImageRowView::at(): attempting to access an element out of range.");
}
return (*this)[index];
}
} // namespace imageview
| {
"alphanum_fraction": 0.753087723,
"avg_line_length": 41.9159292035,
"ext": "h",
"hexsha": "9f907f325e53c63937e60e258efca460dc74bfac",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alexanderbelous/imageview",
"max_forks_repo_path": "include/imageview/ImageRowView.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "alexanderbelous/imageview",
"max_issues_repo_path": "include/imageview/ImageRowView.h",
"max_line_length": 120,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "817e92ac1dcbffc7fb0ebb11afe4ee9836f37df0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alexanderbelous/imageview",
"max_stars_repo_path": "include/imageview/ImageRowView.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2184,
"size": 9473
} |
#ifndef VKST_WSI_WINDOW_H
#define VKST_WSI_WINDOW_H
#include <turf/c/core.h>
#include <gsl.h>
#include <wsi/input.h>
#include <functional>
namespace wsi {
enum class window_options : uint8_t {
none = 0,
decorated = (1 << 1),
sizeable = (1 << 2),
fullscreen_windowed = (1 << 3),
}; // enum class window_options
namespace impl {
template <class D>
class window {
public:
void retitle(gsl::czstring title) noexcept {
static_cast<D*>(this)->do_retitle(title);
}
std::string title() const noexcept {
return static_cast<D const*>(this)->do_title();
}
rect2d const& topleft_size() const noexcept { return _topleft_size; }
extent2d const& size() const noexcept { return _topleft_size.extent; }
void resize(extent2d const& size) noexcept {
static_cast<D*>(this)->do_resize(size);
}
offset2d const& position() const noexcept { return _topleft_size.offset; }
void reposition(offset2d const& position) noexcept {
static_cast<D*>(this)->do_reposition(position);
}
void show() noexcept { static_cast<D*>(this)->do_show(); }
void hide() noexcept { static_cast<D*>(this)->do_hide(); }
void close() noexcept { static_cast<D*>(this)->do_close(); }
bool closed() const noexcept { return _closed; }
keyset const& keys() const noexcept { return _keys; }
buttonset const& buttons() const noexcept { return _buttons; }
int scroll() const noexcept { return _scroll; }
offset2d cursor_pos() const noexcept {
return static_cast<D const*>(this)->do_cursor_pos();
}
void poll_events() noexcept { static_cast<D*>(this)->do_poll_events(); }
using resize_delegate = std::function<void(D*, extent2d const&)>;
void on_resize(resize_delegate delegate) noexcept {
_on_resize = std::move(delegate);
}
using reposition_delegate = std::function<void(D*, offset2d const&)>;
void on_reposition(reposition_delegate delegate) noexcept {
_on_reposition = std::move(delegate);
}
using close_delegate = std::function<void(D*)>;
void on_close(close_delegate delegate) noexcept {
_on_close = std::move(delegate);
}
constexpr window() noexcept {}
constexpr window(rect2d topleft_size) noexcept
: _topleft_size{std::move(topleft_size)} {}
protected:
rect2d _topleft_size{};
bool _closed{false};
keyset _keys{};
buttonset _buttons{};
int _scroll{0};
resize_delegate _on_resize{[](auto, auto) {}};
reposition_delegate _on_reposition{[](auto, auto) {}};
close_delegate _on_close{[](D*) {}};
}; // class window
} // namespace impl
inline constexpr auto operator|(window_options a, window_options b) noexcept {
using U = std::underlying_type_t<window_options>;
return static_cast<window_options>(static_cast<U>(a) | static_cast<U>(b));
}
inline constexpr auto operator&(window_options a, window_options b) noexcept {
using U = std::underlying_type_t<window_options>;
return static_cast<window_options>(static_cast<U>(a) & static_cast<U>(b));
}
} // namespace wsi
// clang-format off
#if TURF_TARGET_WIN32
# include <wsi/window_win32.h>
#elif TURF_KERNEL_LINUX
# include <wsi/window_xlib.h>
#else
# error "Unsupported platform"
#endif
// clang-format on
#endif // VKST_WSI_WINDOW_H
| {
"alphanum_fraction": 0.7102040816,
"avg_line_length": 27.9385964912,
"ext": "h",
"hexsha": "9599355eba0a0e9b2c85bff901239340cdd9c0df",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c",
"max_forks_repo_licenses": [
"Zlib"
],
"max_forks_repo_name": "wesleygriffin/vkst",
"max_forks_repo_path": "src/wsi/window.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Zlib"
],
"max_issues_repo_name": "wesleygriffin/vkst",
"max_issues_repo_path": "src/wsi/window.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c",
"max_stars_repo_licenses": [
"Zlib"
],
"max_stars_repo_name": "wesleygriffin/vkst",
"max_stars_repo_path": "src/wsi/window.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 832,
"size": 3185
} |
#ifndef __SVM_MAIN_H__
#define __SVM_MAIN_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stdlib.h>
#include <gsl_vector.h>
#include <gsl_multimin.h>
#include "common.h"
#include "smo.h"
#include "kernels.h"
// returns vector normal to hyperplane and margin width
PyObject* __get_w_b(PyObject* elements, int k_type, double C);
input_data_t* process_input_data(PyObject* n_array, int k_type, double C);
#endif /* __SVM_MAIN_H__ */ | {
"alphanum_fraction": 0.7702702703,
"avg_line_length": 26.1176470588,
"ext": "h",
"hexsha": "5b19c449e8b50c05e8eaa310b4dbdff53a8935f0",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "HARDIntegral/ADHD_Classifier",
"max_forks_repo_path": "Source/SVM/Include/svm_main.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "HARDIntegral/ADHD_Classifier",
"max_issues_repo_path": "Source/SVM/Include/svm_main.h",
"max_line_length": 74,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "HARDIntegral/ADHD_Classifier",
"max_stars_repo_path": "Source/SVM/Include/svm_main.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 120,
"size": 444
} |
#include "imd_colrad.h"
// #include <sys/time.h>
// #include <gsl/gsl_integration.h>
// #include <gsl/gsl_errno.h>
// ***************************************************
// * TODO:
// * mpi2 und mpi3 anpassen weil energies delE und kbTe in eV
// * SPEEDUP pragma omp auch in ydot
// * floats wo möglich
// ****************************************************
#ifdef LOADBALANCE
#define node l1[i]
#define node2 l2[i]
#else
#define node l1[i][j][k]
#define node2 l2[i][j][k]
#endif
#define OMP
#define LAPACK
//#define MULTIPHOTON
// #define SPONT //<-- spontante emission, Kaum effekt
//#define STARK //<-- reabsorption via stark effect
#define DOIPD //
#define RHOMIN 50
#ifdef OMP
#include <omp.h>
#endif
#define TIMING //time-elapsed to stdout
#define MAXLEVEL 4 // bis zu welchem Ionisationsgrad?
// #ifdef USEFLOAT //Dieser Versuch ist fehlgeschlagen...
// #define EXPR(x) expf(x) //floats an wichtigen stellen erschweren
// #else //konvergenz für solver
// #define EXPR(x) exp(x)
// #endif
const int MAX_LINE_LENGTH=3000; //wird von colrad_read benuthzt
//Hängt davon ab wieviele states betrachtet werden
//sollte eigentlich besser dynamisch berechnet werden
int num_threads;
//const double EMASS=9.10938356e-31; // kg
//const double ECONST=8.854187817e-12; // As/Vm
//const double BOLTZMAN=1.38064852e-23; // J/K
//const double ECHARGE=1.60217662e-19; // C
//const double AMU=1.66053904020e-27; // atomic mass unit
const Real integ_reltol = 1e-6;
const Real integ_abstol = 1.0e-6; //1e-6;
const Real integ_abstol_ioniz= 1.0e-4; //-6;
const Real integ_abstol_recomb= 1.0e-4; //1e-6;
const int integ_meshdim =1500;
// const Real alpha_i =0.3; //0.05; //0.3;
// const Real beta_i =0.9; //4.0 ; //0.9;
const Real alpha_i =0.3; //0.05; //0.3;
const Real beta_i =0.9; //4.0 ; //0.9;
const Real ioniz_const = 1.573949440579906e+71; // konstanten zus. gefasst und aus dem doppelintegral gezogen
const Real recomb_const= 6.213703330335829e+72; // selbes für 3b-recomb.
#define muINF (50*eV2J) //ACHTUNG: Unebdingt was sinnvolleres finden (mu wird kleiner mit Te)
//wenn geschätzte max. ioniz.rate kleiner als das --> integrale garnicht erst berechnen
//Schätzungen mit Hilfe von matlab-script DESCHAUD_TEST.m
#define MINRATE 1e16 // in 1/s/m^3 --> alles unter 10 Ionisationsereignissen pro fs pro m^3 wird ignoriert
// habe ich also eine ionenkonz. von 10^26/m^3 und eine rate von 10/m^3/fs
// so ändert sich pro md-step die konz. um den Bruchteil 10/1E26 = 1E-25
// -->wayne
#define RATEIONIZMAX 1.5252e-13 // in m^3/s, das entspricht dem doppelintegral
#define RATERECOMBMAX 6e-35 //6.1052e-42 // in m^6/s, das entspricht dem doppelintegral
#define MINCONC 1e-60 //im Saha-init sollen zu kleine konzentrationen ignoriert werden
Real k_EE_MAX, k_EI_MAX, k_EE_REV_MAX, k_EI_REV_MAX; //DEBUG PURPOSE
// *********************************************************
// CVODE-STRUCT FOR SOLVER PARAMS
// *********************************************************
typedef struct {
Real It; //Intesity
Real IPD0,IPD1,IPD2,IPD3,IPD4;
Real EF;
Real P_EE,P_EI,P_MPI2,P_MPI3,P_RR;
Real P_TOTAL; //komplette colrad-Leistungsdichte, für eng-filge
Real dens; //weil cv F(dens,temp)
Real ni; //für Z=ne/ni
bool initial_equi;
Real Tinit; //initial Temp. during equi must not change!
Real Heatrate; //um temp.sprünge zu vermeiden //TEST!
} *colrad_UserData;
colrad_UserData cdata;
// *********************************************************
// MAIN
// *********************************************************
void do_colrad(double dt)
{
k_EE_MAX= k_EI_MAX= k_EE_REV_MAX= k_EI_REV_MAX=0.0;
int flag;
double t;
double tout=dt; //müssen beide double sein
int i,j,k;
N_Vector y;
Real Te0,Ti0,rho0,ni0,ne0;
colrad_ptotal=0.0;
if(myid==0 && cdata->initial_equi)
printf("COLRAD performs pre-equilibration of Saha-distribution\nfor t=%.4e s...This may take some time.\n",colrad_tequi);
#ifdef TIMING
//if(myid==0)
// {
struct timeval start, end;
gettimeofday(&start, NULL);
// }
#endif
for(i=1;i<local_fd_dim.x-1;i++)
{
#ifndef LOADBALANCE
for(j=1;j<local_fd_dim.y-1;j++)
{
for(k=1;k<local_fd_dim.z-1;k++)
{
#endif
//clear -> irgendwas stimmt nicht!
// node.ne=node2.ne=0.0;
// node.Z=node2.Z=0.0;
// node.P_EE=node2.P_EE=0.0;
// node.P_EI=node2.P_EI=0.0;
// node.P_MPI2=node2.P_MPI2=0.0;
// node.P_MPI3=node2.P_MPI3=0.0;
// node.P_RR=node2.P_RR=0.0;
if(node.natoms < fd_min_atoms || node.dens < RHOMIN) continue;
y=node.y;
Te0=node.temp*11604.5;
Ti0=node.md_temp*11604.5;
rho0=node.dens;
ni0=rho0/AMU/26.9185; //1e28; //1e26/m^3 entspricht etwa 1e-4/Angtrom^3
if(cdata->initial_equi==true)
{
Real Zmean=MeanCharge(Te0, rho0, atomic_charge, atomic_weight,i,j,k);
ne0= Zmean* node.dens / (atomic_weight * AMU);
node.ne=ne0; //Saha init greift darauf zu
colrad_Saha_init(i, j, k);
}
else //NORMAL
{
ne0=node.ne;
}
double Told=Ith(y,0); //DEBUG //letzter step, checke wie groß temp.sprung
Ith(y,0)=Told; //TEST//Te0;
cdata->Tinit=Told;
Ith(y,1)=Ti0;
Ith(y,2)=ne0;
flag = CVodeReInit(cvode_mem, 0.0, y);
if(cdata->initial_equi==true)
{
// printf("myid:%d, RUNNNING INITIAL EQUI\n",myid);
flag = CVode(cvode_mem, colrad_tequi, y, &t, CV_NORMAL);
int i_global,j_global,k_global;
#ifndef LOADBALANCE
i_global = ((i - 1) + my_coord.x * (local_fd_dim.x - 2));
j_global = ((j - 1) + my_coord.y * (local_fd_dim.y - 2));
k_global = ((k-1) + my_coord.z*(local_fd_dim.z-2));
#else
i_global = ((i - 1) + myid * (local_fd_dim.x - 2));
j_global=k_global=1;
#endif
long int nje;
long int nfe;
long int nsetups;
long int nni;
long int nst;
long int ncfn;
long int netf;
CVodeGetNumJacEvals(cvode_mem, &nje);
CVodeGetNumRhsEvals(cvode_mem, &nfe);
CVodeGetNumLinSolvSetups(cvode_mem, &nsetups);
CVodeGetNumNonlinSolvIters(cvode_mem, &nni);
CVodeGetNumSteps(cvode_mem, &nst);
CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);
CVodeGetNumErrTestFails(cvode_mem, &netf);
printf("myid:%d, COLRAD Cell %d was equilibrated, nfe:%ld, nje:%ld, nsetups:%ld, nni:%ld,nst:%ld,ncfn:%ld,netf:%ld\n",
myid,i_global, nfe,nje,nsetups,nni,nst,ncfn,netf);
} //initial equi
else //NORMAL
{
cdata->dens=node.dens;
cdata->Tinit=Te0;
// printf("myid:%d, COLRAD Cell %d begin step, Te0:%f, ne0:%.2e\n", myid,(i - 1) + myid * (local_fd_dim.x - 2),Te0, ne0);
cdata->Heatrate=(Te0-Told)/dt; //TEST
flag = CVode(cvode_mem, tout, y, &t, CV_NORMAL);
colrad_ptotal+=(fd_vol)*1e-30*cdata->P_TOTAL; // d.h. ptotal ist Gesamt-Leisung
int i_global;
#ifndef LOADBALANCE
i_global = ((i - 1) + my_coord.x * (local_fd_dim.x - 2));
#else
i_global = ((i - 1) + myid * (local_fd_dim.x - 2));
#endif
long int nje;
long int nfe;
long int nsetups;
long int nni;
long int nst;
long int ncfn;
long int netf;
CVodeGetNumJacEvals(cvode_mem, &nje);
CVodeGetNumRhsEvals(cvode_mem, &nfe);
CVodeGetNumLinSolvSetups(cvode_mem, &nsetups);
CVodeGetNumNonlinSolvIters(cvode_mem, &nni);
CVodeGetNumSteps(cvode_mem, &nst);
CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);
CVodeGetNumErrTestFails(cvode_mem, &netf);
if(myid==1 && i_global==18) //DEBUG
printf("myid:%d, COLRAD Cell %d step done,HR:%.2e, Told:%f, T0:%f, T1:%f, ne0:%.2e, ne1:%.2e, nfe:%ld, nje:%ld, nsetups:%ld, nni:%ld,nst:%ld,ncfn:%ld,netf:%ld\n",
myid,i_global, cdata->Heatrate, Told, node.temp*11604.5, Ith(y,0), node.ne, Ith(y,2),
nfe,nje,nsetups,nni,nst,ncfn,netf);
//ni0=cdata->ni;
}
//REASSIGN NEW TE AND NE
node.temp=Ith(y,0)/11604.5;
node.ne=Ith(y,2);
node.Z=node.ne/ni0;
node.P_EE=cdata->P_EE;
node.P_EI=cdata->P_EI;
node.P_MPI2=cdata->P_MPI2;
node.P_MPI3=cdata->P_MPI3;
node.P_RR=cdata->P_RR;
node2.temp=node.temp; //auch in l2 speichern! wichtig!
node2.ne=node.ne; //sonst geht alles im diffusion-step vor
node2.Z=node.Z; //ttm-writeout verloren!
node2.P_EE=node.P_EE;
node2.P_EI=node.P_EI;
node2.P_MPI2=node.P_MPI2;
node2.P_MPI3=node.P_MPI3;
node2.P_RR=node.P_RR;
if(node.temp <0 || isnan(node.temp) !=0 )
{
char errstr[255];
sprintf(errstr,"ERROR in COLRAD: Te became Nan or <0:%.4e\n",node.ne);
error(errstr);
}
if(node.ne <0 || isnan(node.ne) !=0 )
{
char errstr[255];
sprintf(errstr,"ERROR in COLRAD: ne became Nan or <0:%.4e\n",node.ne);
error(errstr);
}
#ifndef LOADBALANCE
} // for k
} //for j
#endif
}
if(cdata->initial_equi==true)
{
colrad_write(0);
cdata->initial_equi=false;
if(myid==0)
printf("Initial equi done\n");
}
else if(steps % ttm_int ==0)
{
// colrad_write(steps);
}
#ifdef TIMING
MPI_Barrier(cpugrid);
// if(myid==0)
// {
gettimeofday(&end, NULL);
Real delta = ((end.tv_sec - start.tv_sec) * 1000000u +
end.tv_usec - start.tv_usec) / 1.e6;
// if(myid==0)
printf("myid:%d, telaps:%f, COLRAD STEP DONE, kee:%.4e,keeb:%.4e, kei:%.4e, k3b:%.4e\n",
myid,delta, k_EE_MAX, k_EE_REV_MAX, k_EI_MAX, k_EI_REV_MAX);
// }
#endif
}
// *********************************************************
// INIT FUNC
// *********************************************************
void colrad_init(void)
{
//Init gsl-integration stuff
winteg_inner= gsl_integration_workspace_alloc (integ_meshdim); //Integration workspace allocation
winteg_outer= gsl_integration_workspace_alloc (integ_meshdim); //Integration workspace allocation
winteg_fermi= gsl_integration_workspace_alloc (integ_meshdim); //Integration workspace allocation
winteg_exc= gsl_integration_workspace_alloc (integ_meshdim);
winteg_rb_inner=gsl_integration_romberg_alloc(20);
winteg_rb_outer=gsl_integration_romberg_alloc(20);
HBAR=planck/2.0/pi;
LASERFREQ=LIGHTSPEED/lambda;
SUNMatrix A;
N_Vector abstol;
int i,j,k;
if(myid==0)
{
printf("*****************************************\n");
printf("* COLLISIONAL RADIATIVE MODEL *\n");
printf("*****************************************\n");
printf(" READING ENERGY LEVELS \n");
printf(" reltol:%.4e\n",colrad_reltol);
printf(" abstol:%.4e\n",colrad_abstol);
}
colrad_read_states();
if(myid==0)
{
printf(" Nr. of Equations:%d *\n",total_species+3);
}
MPI_Barrier(cpugrid);
#ifdef OMP
#pragma omp parallel
{
#pragma omp single
{
num_threads=omp_get_num_threads();
printf("myid:%d, omp threads:%d\n",myid,num_threads);
}
}
#endif
if(myid==0)
{
printf("*****************************************\n");
}
cdata=(colrad_UserData) malloc(sizeof *cdata);
cdata->initial_equi=true;
cdata->P_TOTAL=0.0;
//total_species=z0_len+z1_len; //wird bereits in read-states reduced
neq=total_species+3;
for(i=1;i<local_fd_dim.x-1;i++)
{
#ifndef LOADBALANCE
for(j=1;j<local_fd_dim.y-1;j++)
{
for(k=1;k<local_fd_dim.z-1;k++)
{
#endif
node.y=N_VNew_Serial(neq);
node.P_EE=0.0;
node.P_EI=0.0;
node.P_MPI2=0.0;
node.P_MPI3=0.0;
node.P_RR=0.0;
//l2... <--brauche nur 1 mal speicher alloc'en
//aber in DIFF-LOOP darauf achten, dass beim swappen
//l2.y immer auf l1.y zeigt und nicht ins Leere
#ifndef LOADBALANCE
}
}
#endif
}
abstol = N_VNew_Serial(neq);
N_Vector Vdummy=N_VNew_Serial(neq); //wird bei re-init ersetzt
// ************************* //
// * TOLERANCES *
// *************************
for(i=0;i<neq;i++)
{
Ith(abstol,i) = colrad_abstol;//fmax(Ith(colrad_y,i)*1e-6,10.0);
}
Ith(abstol,0)=5.0; //Temp
// ************************* //
// * SOLVER & CVODE INIT *
// *************************
cvode_mem=NULL;
cvode_mem = CVodeCreate(CV_BDF);
CVodeInit(cvode_mem, colrad_ydot, 0, Vdummy);
CVodeSetUserData(cvode_mem, cdata);
CVodeSVtolerances(cvode_mem, colrad_reltol, abstol);
SUNLinearSolver LS;
A=SUNDenseMatrix(neq, neq);
#ifdef LAPACK
LS = SUNLinSol_LapackDense(Vdummy, A);
#else
LS=SUNLinSol_Dense(Vdummy, A);
#endif
CVodeSetLinearSolver(cvode_mem, LS, A);
//////////////////////////////////////////////////////////////////////
// OPTIONAL FUNCTIONS: SIEHE S.42, TABLE 4.2
//////////////////////////////////////////////////////////////////////
//CVodeSetIterType(cvode_mem,CV_NEWTON); //ist ja eh schon gesetzt
//Keine gute idee mindt zu setzen
//CVodeSetMaxOrd(cvode_mem,12); //Bei adams default=12
//CVodeSetMaxErrTestFails(cvode_mem,7); //Default=7
//CVodeSetMaxNonlinIters(cvode_mem,3); //Default=3
//CVodeSetMaxConvFails(cvode_mem,10); //Default=10
//
//CVodeSetMaxStep(cvode_mem,1e-15);
//CVodeSetNonlinConvCoef(cvode_mem,0.01); //Default=0.1
//Max Steps muss sehr hoch sein bei großen steps,
//sonst beschwert sich newton
CVodeSetMaxNumSteps(cvode_mem,2500); //Default=500
// CVodeSetInitStep(cvode_mem,1e-17); //ACHTUNG:Wenn zu klein --> BS
//CVodeSetEpsLin(cvode_mem,0.01); //Default=0.05;
CVodeSetMaxStepsBetweenJac(cvode_mem,50); //default 50 --> guter performance boost
// CVodeSetMaxStepsBetweenJac(cvode_mem,50); //default 50 --> guter performance boost
//N_VDestroy(dummy);
/*
N_VDestroy(y);
SUNMatDestroy(A);
SUNLinSolFree(LS);
CVodeFree(&cvode_mem);
*/
//colrad_read(0);
}
void colrad_Saha_init(int i,int j,int k)
{
// int i,j,k;
// for(i=1;i<local_fd_dim.x-1;i++)
// {
// for(j=1;i<local_fd_dim.y-1;j++)
// {
// for(k=1;i<local_fd_dim.z-1;k++)
// {
Real Te0,Ti0,ne0,ni0,rho0;
N_Vector y;
y=node.y;
Te0=node.temp*11604.5;
Ti0=node.md_temp*11604.5;
rho0=node.dens; ///1e10;
ni0=rho0/AMU/26.9185; //1e28; //1e26/m^3 entspricht etwa 1e-4/Angtrom^3
ne0=node.ne;
Ith(y,0)=Te0;
Ith(y,1)=Ti0;
Ith(y,2)=ne0;
do_Saha(Te0,ni0,ne0,y);
// }
// }
// }
}
void colrad_read_states(void)
{
// **************************************************************************
// * READ STATES FILES
// **********************************************************************
int lcnt = 1;
int i, j;
Real *buf; //buffer 1d array for communication
FILE* fin = NULL;
char line[255];
if (myid == 0)
{
fin = fopen("Al0_states.txt", "r");
if (fin == NULL)
{
char errstr[255];
sprintf(errstr, "ERROR in colrad_read_states: File %s not found\n", "Al0_states.txt");
error(errstr);
}
while (1) {
if (fgets(line, MAXLINE, fin) == NULL) break;
lcnt++;
}
alloc2darr(double, STATES_z0, lcnt, 6);
lcnt = 0;
rewind(fin);
while (1)
{
if (fgets(line, MAXLINE, fin) == NULL) break;
sscanf(line, "%lf\t%lf\t%lf\t%lf\t%lf\t%lf",
&STATES_z0[lcnt][0], &STATES_z0[lcnt][1], &STATES_z0[lcnt][2],
&STATES_z0[lcnt][3], &STATES_z0[lcnt][4], &STATES_z0[lcnt][5]);
lcnt++;
}
z0_len = lcnt;
fclose(fin);
total_species += z0_len;
}
//NOW COMMUNICATE
MPI_Bcast(&z0_len, 1, MPI_INT, 0, cpugrid);
alloc1darr(Real, buf, z0_len * 6);
MPI_Barrier(cpugrid);
if (myid == 0)
{
for (i = 0; i < z0_len * 6; i += 6) //fill 1d buff-array
{
buf[i] = (Real) STATES_z0[i / 6][0];
buf[i + 1] = (Real) STATES_z0[i / 6][1];
buf[i + 2] = (Real) STATES_z0[i / 6][2];
buf[i + 3] = (Real) STATES_z0[i / 6][3];
buf[i + 4] = (Real) STATES_z0[i / 6][4];
buf[i + 5] = (Real) STATES_z0[i / 6][5];
//printf("E:%.4e,i/6:%d\n",STATES_z0[i/6][2], i/6);
}
}
MPI_Barrier(cpugrid);
MPI_Bcast(buf, z0_len * 6, REALTYPE, 0, cpugrid);
//NOW RECONSTRUCT on other procs
if (myid > 0)
{
alloc2darr(double, STATES_z0, z0_len, 6);
for (i = 0; i < z0_len * 6; i += 6)
{
STATES_z0[i / 6][0] = buf[i];
STATES_z0[i / 6][1] = buf[i + 1];
STATES_z0[i / 6][2] = buf[i + 2];
STATES_z0[i / 6][3] = buf[i + 3];
STATES_z0[i / 6][4] = buf[i + 4];
STATES_z0[i / 6][5] = buf[i + 5];
}
}
free(buf);
// ***********************************************
//Read Al, Z=+1
// **********************************************
if (myid == 0)
{
lcnt = 1;
fin = fopen("Al1_states.txt", "r");
if (fin == NULL)
{
char errstr[255];
sprintf(errstr, "ERROR in colrad_read_states: File %s not found\n", "Al1_states.txt");
error(errstr);
}
while (1) {
if (fgets(line, MAXLINE, fin) == NULL) break;
lcnt++;
}
alloc2darr(double, STATES_z1, lcnt, 6);
lcnt = 0;
rewind(fin);
while (1)
{
if (fgets(line, MAXLINE, fin) == NULL) break;
sscanf(line, "%lf\t%lf\t%lf\t%lf\t%lf\t%lf",
&STATES_z1[lcnt][0], &STATES_z1[lcnt][1], &STATES_z1[lcnt][2],
&STATES_z1[lcnt][3], &STATES_z1[lcnt][4], &STATES_z1[lcnt][5]);
lcnt++;
}
z1_len = lcnt;
fclose(fin);
total_species += z1_len;
}
//NOW COMMUNICATE
MPI_Bcast(&z1_len, 1, MPI_INT, 0, cpugrid);
alloc1darr(Real, buf, z1_len * 6);
if (myid == 0)
{
for (i = 0; i < z1_len * 6; i += 6) //fill 1d buff-array
{
buf[i] = (Real) STATES_z1[i / 6][0];
buf[i + 1] = (Real) STATES_z1[i / 6][1];
buf[i + 2] = (Real) STATES_z1[i / 6][2];
buf[i + 3] = (Real) STATES_z1[i / 6][3];
buf[i + 4] = (Real) STATES_z1[i / 6][4];
buf[i + 5] = (Real) STATES_z1[i / 6][5];
}
}
MPI_Bcast(buf, z1_len * 6, REALTYPE, 0, cpugrid);
//NOW RECONSTRUCT on other procs
if (myid > 0)
{
alloc2darr(double, STATES_z1, z1_len, 6);
for (i = 0; i < z1_len * 6; i += 6)
{
STATES_z1[i / 6][0] = buf[i];
STATES_z1[i / 6][1] = buf[i + 1];
STATES_z1[i / 6][2] = buf[i + 2];
STATES_z1[i / 6][3] = buf[i + 3];
STATES_z1[i / 6][4] = buf[i + 4];
STATES_z1[i / 6][5] = buf[i + 5];
}
}
free(buf);
// ***********************************************
//Read Al, Z=+2
// **********************************************
#if MAXLEVEL > 1
if (myid == 0)
{
lcnt = 1;
fin = fopen("Al2_states.txt", "r");
if (fin == NULL)
{
char errstr[255];
sprintf(errstr, "ERROR in colrad_read_states: File %s not found\n", "Al2_states.txt");
error(errstr);
}
while (1) {
if (fgets(line, MAXLINE, fin) == NULL) break;
lcnt++;
}
alloc2darr(double, STATES_z2, lcnt, 6);
lcnt = 0;
rewind(fin);
while (1)
{
if (fgets(line, MAXLINE, fin) == NULL) break;
sscanf(line, "%lf\t%lf\t%lf\t%lf\t%lf\t%lf",
&STATES_z2[lcnt][0], &STATES_z2[lcnt][1], &STATES_z2[lcnt][2],
&STATES_z2[lcnt][3], &STATES_z2[lcnt][4], &STATES_z2[lcnt][5]);
lcnt++;
}
z2_len = lcnt;
fclose(fin);
total_species += z2_len;
}
//NOW COMMUNICATE
MPI_Bcast(&z2_len, 1, MPI_INT, 0, cpugrid);
alloc1darr(Real, buf, z2_len * 6);
if (myid == 0)
{
for (i = 0; i < z2_len * 6; i += 6) //fill 1d buff-array
{
buf[i] = (Real) STATES_z2[i / 6][0];
buf[i + 1] = (Real) STATES_z2[i / 6][1];
buf[i + 2] = (Real) STATES_z2[i / 6][2];
buf[i + 3] = (Real) STATES_z2[i / 6][3];
buf[i + 4] = (Real) STATES_z2[i / 6][4];
buf[i + 5] = (Real) STATES_z2[i / 6][5];
}
}
MPI_Bcast(buf, z2_len * 6, REALTYPE, 0, cpugrid);
//NOW RECONSTRUCT on other procs
if (myid > 0)
{
alloc2darr(double, STATES_z2, z2_len, 6);
for (i = 0; i < z2_len * 6; i += 6)
{
STATES_z2[i / 6][0] = buf[i];
STATES_z2[i / 6][1] = buf[i + 1];
STATES_z2[i / 6][2] = buf[i + 2];
STATES_z2[i / 6][3] = buf[i + 3];
STATES_z2[i / 6][4] = buf[i + 4];
STATES_z2[i / 6][5] = buf[i + 5];
}
}
free(buf);
#endif //MAXLEVEL > 1
// ***********************************************
//Read Al, Z=+3
// **********************************************
#if MAXLEVEL > 2
if (myid == 0)
{
lcnt = 1;
fin = fopen("Al3_states.txt", "r");
if (fin == NULL)
{
char errstr[255];
sprintf(errstr, "ERROR in colrad_read_states: File %s not found\n", "Al3_states.txt");
error(errstr);
}
while (1) {
if (fgets(line, MAXLINE, fin) == NULL) break;
lcnt++;
}
alloc2darr(double, STATES_z3, lcnt, 6);
lcnt = 0;
rewind(fin);
while (1)
{
if (fgets(line, MAXLINE, fin) == NULL) break;
sscanf(line, "%lf\t%lf\t%lf\t%lf\t%lf\t%lf",
&STATES_z3[lcnt][0], &STATES_z3[lcnt][1], &STATES_z3[lcnt][2],
&STATES_z3[lcnt][3], &STATES_z3[lcnt][4], &STATES_z3[lcnt][5]);
lcnt++;
}
z3_len = lcnt;
fclose(fin);
total_species += z3_len;
}
//NOW COMMUNICATE
MPI_Bcast(&z3_len, 1, MPI_INT, 0, cpugrid);
alloc1darr(Real, buf, z3_len * 6);
if (myid == 0)
{
for (i = 0; i < z3_len * 6; i += 6) //fill 1d buff-array
{
buf[i] = (Real) STATES_z3[i / 6][0];
buf[i + 1] = (Real) STATES_z3[i / 6][1];
buf[i + 2] = (Real) STATES_z3[i / 6][2];
buf[i + 3] = (Real) STATES_z3[i / 6][3];
buf[i + 4] = (Real) STATES_z3[i / 6][4];
buf[i + 5] = (Real) STATES_z3[i / 6][5];
}
}
MPI_Bcast(buf, z3_len * 6, REALTYPE, 0, cpugrid);
//NOW RECONSTRUCT on other procs
if (myid > 0)
{
alloc2darr(double, STATES_z3, z3_len, 6);
for (i = 0; i < z3_len * 6; i += 6)
{
STATES_z3[i / 6][0] = buf[i];
STATES_z3[i / 6][1] = buf[i + 1];
STATES_z3[i / 6][2] = buf[i + 2];
STATES_z3[i / 6][3] = buf[i + 3];
STATES_z3[i / 6][4] = buf[i + 4];
STATES_z3[i / 6][5] = buf[i + 5];
}
}
free(buf);
#endif //MAXLEVEL > 2
// ***********************************************
//Read Al, Z=+4
// **********************************************
#if MAXLEVEL > 3
if (myid == 0)
{
lcnt = 1;
fin = fopen("Al4_states.txt", "r");
if (fin == NULL)
{
char errstr[255];
sprintf(errstr, "ERROR in colrad_read_states: File %s not found\n", "Al4_states.txt");
error(errstr);
}
while (1) {
if (fgets(line, MAXLINE, fin) == NULL) break;
lcnt++;
}
alloc2darr(double, STATES_z4, lcnt, 6);
lcnt = 0;
rewind(fin);
while (1)
{
if (fgets(line, MAXLINE, fin) == NULL) break;
sscanf(line, "%lf\t%lf\t%lf\t%lf\t%lf\t%lf",
&STATES_z4[lcnt][0], &STATES_z4[lcnt][1], &STATES_z4[lcnt][2],
&STATES_z4[lcnt][3], &STATES_z4[lcnt][4], &STATES_z4[lcnt][5]);
lcnt++;
}
z4_len = lcnt;
fclose(fin);
total_species += z4_len;
}
//NOW COMMUNICATE
MPI_Bcast(&z4_len, 1, MPI_INT, 0, cpugrid);
alloc1darr(Real, buf, z4_len * 6);
if (myid == 0)
{
for (i = 0; i < z4_len * 6; i += 6) //fill 1d buff-array
{
buf[i] = (Real) STATES_z4[i / 6][0];
buf[i + 1] = (Real) STATES_z4[i / 6][1];
buf[i + 2] = (Real) STATES_z4[i / 6][2];
buf[i + 3] = (Real) STATES_z4[i / 6][3];
buf[i + 4] = (Real) STATES_z4[i / 6][4];
buf[i + 5] = (Real) STATES_z4[i / 6][5];
}
}
MPI_Bcast(buf, z4_len * 6, REALTYPE, 0, cpugrid);
//NOW RECONSTRUCT on other procs
if (myid > 0)
{
alloc2darr(double, STATES_z4, z4_len, 6);
for (i = 0; i < z4_len * 6; i += 6)
{
STATES_z4[i / 6][0] = buf[i];
STATES_z4[i / 6][1] = buf[i + 1];
STATES_z4[i / 6][2] = buf[i + 2];
STATES_z4[i / 6][3] = buf[i + 3];
STATES_z4[i / 6][4] = buf[i + 4];
STATES_z4[i / 6][5] = buf[i + 5];
}
}
free(buf);
#endif //MAXLEVEL > 3
// **********************************
// * ALLOC ARRAYS
// **********************************
alloc2darr(double, k_EE_z0_z0, z0_len, z0_len);
alloc2darr(double, k_EE_z0_z0_b, z0_len, z0_len);
alloc2darr(double, k_EE_z1_z1, z1_len, z1_len);
alloc2darr(double, k_EE_z1_z1_b, z1_len, z1_len);
#if MAXLEVEL > 1
alloc2darr(double, k_EE_z2_z2, z2_len, z2_len);
alloc2darr(double, k_EE_z2_z2_b, z2_len, z2_len);
#endif
#if MAXLEVEL > 2
alloc2darr(double, k_EE_z3_z3, z3_len, z3_len);
alloc2darr(double, k_EE_z3_z3_b, z3_len, z3_len);
#endif
#if MAXLEVEL > 3
alloc2darr(double, k_EE_z4_z4, z4_len, z4_len);
alloc2darr(double, k_EE_z4_z4_b, z4_len, z4_len);
#endif
// **********************************************
// Now Thermal Ionization and Recomb. rate coeff. arrays
// z0->z1
alloc2darr(double, k_EI_z0_z1, z0_len, z1_len);
alloc2darr(double, k_EI_z1_z0, z0_len, z1_len);
#if MAXLEVEL > 1
//z1->z2
alloc2darr(double, k_EI_z1_z2, z1_len, z2_len);
alloc2darr(double, k_EI_z2_z1, z1_len, z2_len);
#endif
#if MAXLEVEL > 2
//z2->z3
alloc2darr(double, k_EI_z2_z3, z2_len, z3_len);
alloc2darr(double, k_EI_z3_z2, z2_len, z3_len);
#endif
#if MAXLEVEL > 3
//z3->z4
alloc2darr(double, k_EI_z3_z4, z3_len, z4_len);
alloc2darr(double, k_EI_z4_z3, z3_len, z4_len);
#endif
// k_MPI arrays
//z0->z1
alloc3darr(double, k_MPI_z0_z1, z0_len, z1_len, 2);
alloc3darr(double, k_MPI_z1_z0, z0_len, z1_len, 2);
//z1->z2
#if MAXLEVEL > 1
alloc3darr(double, k_MPI_z1_z2, z1_len, z2_len, 2);
alloc3darr(double, k_MPI_z2_z1, z1_len, z2_len, 2);
#endif
//z2->z3
#if MAXLEVEL > 2
alloc3darr(double, k_MPI_z2_z3, z2_len, z3_len, 2);
alloc3darr(double, k_MPI_z3_z2, z2_len, z3_len, 2);
#endif
//z3->z4
#if MAXLEVEL > 3
alloc3darr(double, k_MPI_z3_z4, z3_len, z4_len, 2);
alloc3darr(double, k_MPI_z4_z3, z3_len, z4_len, 2);
#endif
MPI_Bcast(&total_species, 1, MPI_INT, 0, cpugrid);
}
void do_Saha(Real Te,Real totalc,Real ne,N_Vector y) //Bei init
{
double tmp;
double Zav=ne/totalc;
// double Ti=Te;
double Q_z0,Q_z1,Q_z2,Q_z3,Q_z4,Q_z5; //partition functions
// double IPD_SP=0.0; //Stewart and Pyatt =(POWR(1.0+a/Debye,2.0/3.0)-1.0)/2.0/(Zav+1.0);
// double IPD_IS=0.0; //Ion-sphere model (high dens,low T) =3.0*1.0*ECHARGE*ECHARGE/2.0/a/BOLTZMAN/Te;
// double IPD_DH=0.0; //Debye-Hückel (high T,low dens) = 1.0*ECHARGE*ECHARGE/Debye/BOLTZMAN/Te;
double r10,r21,r32,r43,r54; //ratios of ion. conc.
double DeltaE;
double IPD=0.0;
double n0,n1,n2,n3,n4,n5;
double p; //probability
int i;
r10=r21=r32=r43=r54=0;
Zav=ne/totalc;
double EF=fermi_E(ne);
double mu=chempot(ne,Te);
//Debye=SQRTR(BOLTZMAN*Te/4.0/pi/ECHARGE/ECHARGE/ne/(Zav+1));
tmp=POWR(2.0*pi*EMASS*BOLTZMAN*Te,1.5)/planck/planck/planck; //ACHTUNG: Das ist wieder thermal-de brogilie Lambda
//Nutze richtiges chempot!!!!
#ifdef DOIPD
double IPD0,IPD1,IPD2,IPD3,IPD4;
double z; //DOI after ionization (e.g.=1 for Al0)
double r0; //Ion sphere radius
r0=POWR(3.0/4.0/pi/totalc,1.0/3.0);
double debye=SQRTR(BOLTZMAN*Te/4.0/pi/POWR(totalc+ne,2.0));
// Atoms, solids, and plasmas in super-intense laser fields S.220
IPD0=1.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;
IPD1=2.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;
IPD2=3.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;
IPD3=4.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;
IPD4=5.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;
#endif
//compute partition functions
Q_z0=0.0;
Q_z1=0.0;
Q_z2=0.0;
Q_z3=0.0;
Q_z4=0.0;
Q_z5=0.0;
for(i=0;i<z0_len;++i)
{
#ifdef DOIPD
IPD=IPD0;
#endif
double Ei=STATES_z0[i][2]*eV2J-IPD+mu;
double qi=STATES_z0[i][3]*exp(-(STATES_z0[i][2]-0.0)*eV2J/BOLTZMAN/Te);
if(Ei<0) //depressed state- > truncate partiation function
qi=0;
Q_z0+=qi; //Mit Energien, relativ zum Grundzustand (level=0) dieses Ions
// if(myid==0)
// printf("Z0, qi:%.4e, exp:%.4e, gi:%.4e,Q:%.4e\n", qi,
// exp(-(STATES_z0[i][2]-0.0)*eV2J/BOLTZMAN/Te),
// STATES_z0[i][3], Q_z0);
}
for(i=0;i<z1_len;++i)
{
#ifdef DOIPD
IPD=IPD0;
#endif
double Ei=STATES_z1[i][2]*eV2J-IPD+mu;
double qi=STATES_z1[i][3]*exp(-(STATES_z1[i][2]-STATES_z1[0][2])*eV2J/BOLTZMAN/Te);
if(Ei<0) qi=0;
Q_z1+=qi;
// if(myid==0)
// printf("Z1, qi:%.4e, exp:%.4e, gi:%.4e,Q:%.4e\n", qi,
// exp(-(STATES_z1[i][2]-STATES_z1[0][2])*eV2J/BOLTZMAN/Te),
// STATES_z1[i][3],Q_z1);
}
#if MAXLEVEL > 1
for(i=0;i<z2_len;++i)
{
#ifdef DOIPD
IPD=IPD1;
#endif
double Ei=STATES_z2[i][2]*eV2J-IPD+mu;
double qi=STATES_z2[i][3]*exp(-(STATES_z2[i][2]-STATES_z2[0][2])*eV2J/BOLTZMAN/Te);
if(Ei<0) qi=0;
Q_z2+=qi;
// if(myid==0)
// printf("Z2, qi:%.4e, exp:%.4e, gi:%.4e,Q:%.4e\n", qi,
// exp(-(STATES_z2[i][2]-STATES_z2[0][2])*eV2J/BOLTZMAN/Te),
// STATES_z2[i][3], Q_z2);
}
#endif
#if MAXLEVEL > 2
for(i=0;i<z3_len;++i)
{
#ifdef DOIPD
IPD=IPD2;
#endif
double Ei=STATES_z3[i][2]*eV2J-IPD+mu;
double qi=STATES_z3[i][3]*exp(-(STATES_z3[i][2]-STATES_z3[0][2])*eV2J/BOLTZMAN/Te);
if(Ei<0) qi=0;
Q_z3+=qi;
// if(myid==0)
// printf("Z3, qi:%.4e, exp:%.4e, gi:%.4e,Q:%.4e\n", qi,
// exp(-(STATES_z3[i][2]-STATES_z3[0][2])*eV2J/BOLTZMAN/Te),
// STATES_z3[i][3],Q_z3);
}
#endif
#if MAXLEVEL > 3
for(i=0;i<z4_len;++i)
{
#ifdef DOIPD
IPD=IPD3;
#endif
double Ei=STATES_z4[i][2]*eV2J-IPD+mu;
double qi=STATES_z4[i][3]*exp(-(STATES_z4[i][2]-STATES_z4[0][2])*eV2J/BOLTZMAN/Te);
if(Ei<0) qi=0;
Q_z4+=qi;
// if(myid==0)
// printf("Z4, qi:%.4e, exp:%.4e, gi:%.4e,Q:%.4e\n", qi,
// exp(-(STATES_z4[i][2]-STATES_z4[0][2])*eV2J/BOLTZMAN/Te),
// STATES_z4[i][3],Q_z4 );
}
#endif
/*
for(int i=0;i<z5_len;++i)
Q_z5+=STATES_z5[i][3]*exp(-(STATES_z5[i][2]-STATES_z5[0][2])*eV2J/BOLTZMAN/Te);
*/
// double tmp2,tmp3;
////////////
// Z=0->1 //
////////////
#ifdef DOIPD
// z=1.0;
// IPD=3.0*z*ECHARGE*ECHARGE/2.0/r0/4.0/pi/ECONST; //Ion-Sphere model
IPD=IPD0;
#endif
DeltaE=(STATES_z1[0][2]-0.0)*eV2J-IPD+mu;
// DeltaE=fmax(0.0,DeltaE);
p=exp(-DeltaE/BOLTZMAN/Te);
// r10=2.0/ne*tmp*Q_z1/Q_z0*p; //r10= ratio of ion-concentrations n(Z=1)/n(Z=0); g_e=2 (statistical weight of electron)
r10=Q_z1/Q_z0*p;
// double r01=Q_z0/Q_z1*p;
//printf("IPD0:%f\n",IPD*J2eV);
// if(isnan(r10)!=0 || isinf(r10)!=0)
// {
// char errstr[255];
// sprintf(errstr,"ERROR in Saha-Init: r10 is inf or nan: p0:%.4e,Q_z1:%.4e,Q_z0:%.4e\n",p,Q_z1,Q_z0);
// error(errstr);
// }
// if(myid==0)
// printf("ERROR in Saha-Init: r10 is inf or nan: p0:%.4e,Q_z1:%.4e,Q_z0:%.4e\n",p,Q_z1,Q_z0);
////////////
// Z=1->2 //
////////////
#if MAXLEVEL > 1
#ifdef DOIPD
// z=2.0;
// IPD=3.0*z*ECHARGE*ECHARGE/2.0/r0/4.0/pi/ECONST; //Ion-Sphere model
IPD=IPD1;
#endif
DeltaE=(STATES_z2[0][2]-STATES_z1[0][2])*eV2J-IPD+mu;
// DeltaE=fmax(0.0,DeltaE);
p=exp(-DeltaE/BOLTZMAN/Te);
// p=exp(DeltaE/BOLTZMAN/Te);
// r21=2.0/ne*tmp*Q_z2/Q_z1*p;
r21=Q_z2/Q_z1*p;
// double r12=Q_z1/Q_z2*p;
// if(isnan(r21)!=0 || isinf(r21)!=0)
// {
// char errstr[255];
// sprintf(errstr,"ERROR in Saha-Init: r21 is inf or nan: p2:%.4e,Q_z2:%.4e,Q_z1:%.4e\n",p,Q_z2,Q_z1);
// error(errstr);
// }
#endif
// ////////////
// // Z=2->3 //
// ////////////
#if MAXLEVEL > 2
#ifdef DOIPD
// z=3.0;
// IPD=3.0*z*ECHARGE*ECHARGE/2.0/r0/4.0/pi/ECONST; //Ion-Sphere model
IPD=IPD2;
#endif
DeltaE=(STATES_z3[0][2]-STATES_z2[0][2])*eV2J-IPD+mu;
// DeltaE=fmax(0.0,DeltaE);
p=exp(-DeltaE/BOLTZMAN/Te);
// p=exp(DeltaE/BOLTZMAN/Te);
// r32=2.0/ne*tmp*Q_z3/Q_z2*p;
r32=Q_z3/Q_z2*p;
// double r23=Q_z2/Q_z3*p;
if(isnan(r32)!=0 || isinf(r32)!=0)
{
char errstr[255];
sprintf(errstr,"ERROR in Saha-Init: r32 is inf or nan: p3:%.4e,Q_z3:%.4e,Q_z2:%.4e\n",p,Q_z3,Q_z2);
error(errstr);
}
#endif
// ////////////
// // Z=3->4 //
// ////////////
#if MAXLEVEL > 3
#ifdef DOIPD
// z=4.0;
// IPD=3.0*z*ECHARGE*ECHARGE/2.0/r0/4.0/pi/ECONST; //Ion-Sphere model
IPD=IPD3;
#endif
DeltaE=(STATES_z4[0][2]-STATES_z3[0][2])*eV2J-IPD+mu;
// DeltaE=fmax(0.0,DeltaE);
p=exp(-DeltaE/BOLTZMAN/Te);
// p=exp(DeltaE/BOLTZMAN/Te);
// r43=2.0/ne*tmp*Q_z4/Q_z3*p;
r43=Q_z4/Q_z3*p;
// double r34=Q_z3/Q_z4*p;
// printf("r34:%.4e,p:%.4e,DeltaE/kT:%.4e\n",r34,p,DeltaE/BOLTZMAN/Te);
// if(isnan(r43)!=0 || isinf(r43)!=0)
// {
// char errstr[255];
// sprintf(errstr,"ERROR in Saha-Init: r43 is inf or nan: p4:%.4e,Q_z4:%.4e,Q_z3:%.4e\n",p,Q_z4,Q_z3);
// error(errstr);
// }
#endif
//concentrations from ratios and totalc
n0=totalc/(r43*r32*r21*r10+r32*r21*r10+r21*r10+r10+1.0); // ?
//n0=totalc*Zav/(4*r43*r32*r21*r10 + 3*r32*r21*r10+ 2*r21*r10+1.0);
n1=r10*n0;
//D.h. Neutrals komplett druck-ionisiert
if(Q_z0==0)
{
n0=0.0;
// n1=totalc*Zav/(4*r43*r32*r21 + 3*r32*r21+ 2*r21+1.0);
n1=totalc/(r43*r32*r21 + r32*r21+ r21+1.0);
}
n2=r21*n1;
n3=r32*n2;
n4=r43*n3;
n5=r54*n4;
// Zav=(1*n1+4*n2+9*n3+16*n4+25*n5)/(1*n1+2*n2+3*n3+4*n4+5*n5);
// n4=Zav*totalc/(r12*r23*r34+2*r23*r34+3*r34+4);
// n3=r34*n4;
// n2=r23*n3;
// n1=r12*n2;
// n0=r01*n1;
// if(myid==0)
// {
// printf("n0:%.4e,n1:%.4e,n2:%.4e,n3:%.4e,n4:%.4e\n",n0,n1,n2,n3,n4);
// printf("r10:%.4e,r21:%.4e,r32:%.4e,r43:%.4e\n",r10,r21,r32,r43);
// printf("Qz4:%.4e,Qz3:%.4e,Qz2:%.4e,Qz1:%.4e,Qz0:%.4e\n",Q_z4, Q_z3,Q_z2,Q_z1,Q_z0);
// }
/*
printf("********************************************************************************************************************** \n");
printf(" Initial distribution of concentration according to generalized Saha-Equation\n");
printf(" Ti=Te=%f\n",Te);
printf(" totalc=%.4e\n",totalc);
printf(" Zmean=%.4e,ne:%.6e\n",ne/totalc,ne);
printf(" [Al0]:%.2e,[Al1]:%.2e,[Al2]:%.2e,[Al3]:%.2e,[Al4]:%.2e,[Al5]:%.2e\n",n0,n1,n2,n3,n4,n5);
printf(" I0=%.4e\n",I0);
printf(" t_FWHM=%.4e\n",tFWHM);
printf(" Lambda=%.4e\n",lambda);
printf(" NEQ:%d\n",neq);
printf("********************************************************************************************************************** \n");
*/
// ************************
// * FILL Z0 STATES
// ************************
int ishift=3;
//Now fill states
for(i=0;i<z0_len;++i)
{
DeltaE=(STATES_z0[i][2]-0)*eV2J; // bzgl. ground state
double Ei=0.0;
double prob=exp(-DeltaE/BOLTZMAN/Te);
#ifdef DOIPD
IPD=IPD0;
Ei=STATES_z0[i][2]*eV2J-IPD+mu;
if(Ei<0) prob=0.0;
#endif
if(Q_z0>0)
{
Ith(y,i+ishift)=n0/Q_z0*STATES_z0[i][3]*prob;
if(Ith(y,i+ishift) < MINCONC)
Ith(y,i+ishift)=0.0;
// printf("ITH(%d):%.4e,prob:%.4e,Q_z0:%.4e,dE:%.4e\n",
// i+ishift,Ith(y,i+ishift), prob, Q_z0, DeltaE);
}
if(isnan(Ith(y,i+ishift))!=0 || isinf(Ith(y,i+ishift))!=0)
{
char errstr[255];
sprintf(errstr,"ERROR in do_Saha z0: y is inf or nan! prob:%.4e, Ei:%.4e,DeltaE:%.4e\n",
prob,Ei,DeltaE);
error(errstr);
}
}
// ************************
// * FILL Z1 STATES
// ************************
for(i=0;i<z1_len;++i)
{
// DeltaE=(STATES_z1[i][2]-STATES_z1[0][2])*eV2J-IPD0+EF;
// DeltaE=(STATES_z1[i][2]-STATES_z1[0][2])*eV2J-IPD1+EF;
DeltaE=(STATES_z1[i][2]-STATES_z1[0][2])*eV2J;
double Ei=0.0;
double prob=exp(-DeltaE/BOLTZMAN/Te);
#ifdef DOIPD
IPD=IPD1;
// Ei=(STATES_z1[i][2]-STATES_z1[0][2])*eV2J-IPD0+EF;
// Ei=(STATES_z1[i][2]-STATES_z1[0][2])*eV2J-IPD1+EF;
Ei=(STATES_z1[i][2])*eV2J-IPD0+mu;
if(Ei<0) prob=0.0;
#endif
if(Q_z1>0)
Ith(y,i+ishift+z0_len)=n1/Q_z1*STATES_z1[i][3]*prob;
if(Ith(y,i+ishift+z0_len) < MINCONC)
Ith(y,i+ishift+z0_len)=0.0;
if(isnan(Ith(y,i+ishift+z0_len))!=0 || isinf(Ith(y,i+ishift+z0_len))!=0)
{
char errstr[255];
sprintf(errstr,"ERROR in do_Saha z1: y is inf or nan! prob:%.4e, Ei:%.4e,DeltaE:%.4e\n",
prob,Ei,DeltaE);
error(errstr);
}
}
// ************************
// * FILL Z2 STATES
// ************************
#if MAXLEVEL > 1
for(i=0;i<z2_len;++i)
{
DeltaE=(STATES_z2[i][2]-STATES_z2[0][2])*eV2J;//-IPD2+EF;
double Ei=0.0;
double prob=exp(-DeltaE/BOLTZMAN/Te);
#ifdef DOIPD
IPD=IPD2;
Ei=STATES_z2[i][2]*eV2J-IPD1+mu;
if(Ei<0) prob=0.0;
#endif
if(Q_z2>0)
Ith(y,i+ishift+z0_len+z1_len)=n2/Q_z2*STATES_z2[i][3]*prob;
if(Ith(y,i+ishift+z0_len+z1_len) < MINCONC)
Ith(y,i+ishift+z0_len+z1_len)=0.0;
if(isnan(Ith(y,i+ishift+z0_len+z1_len))!=0 || isinf(Ith(y,i+ishift+z0_len+z1_len))!=0)
{
char errstr[255];
sprintf(errstr,"ERROR in do_Saha z2: y is inf or nan! prob:%.4e, Ei:%.4e,DeltaE:%.4e\n",
prob,Ei,DeltaE);
error(errstr);
}
}
#endif
// ************************
// * FILL Z3 STATES
// ************************
#if MAXLEVEL > 2
for(i=0;i<z3_len;++i)
{
DeltaE=(STATES_z3[i][2]-STATES_z3[0][2])*eV2J;//-IPD3+EF;
double Ei=0.0;
double prob=exp(-DeltaE/BOLTZMAN/Te);
#ifdef DOIPD
IPD=IPD3;
Ei=STATES_z3[i][2]*eV2J-IPD2+mu;
if(Ei<0) prob=0.0;
#endif
if(Q_z3>0)
Ith(y,i+ishift+z0_len+z1_len+z2_len)=n3/Q_z3*STATES_z3[i][3]*prob;
if(Ith(y,i+ishift+z0_len+z1_len+z2_len) < MINCONC)
Ith(y,i+ishift+z0_len+z1_len+z2_len)=0.0;
if(isnan(Ith(y,i+ishift+z0_len+z1_len+z2_len))!=0 || isinf(Ith(y,i+ishift+z0_len+z1_len+z2_len))!=0)
{
char errstr[255];
sprintf(errstr,"ERROR in do_Saha z3: y is inf or nan! prob:%.4e, Ei:%.4e,DeltaE:%4.e\n",
prob,Ei,DeltaE);
error(errstr);
}
}
#endif
// ************************
// * FILL Z4 STATES
// ************************
#if MAXLEVEL > 3
for(i=0;i<z4_len;++i)
{
DeltaE=(STATES_z4[i][2]-STATES_z4[0][2])*eV2J;//-IPD4+EF;
double prob=exp(-DeltaE/BOLTZMAN/Te);
double Ei=0.0;
#ifdef DOIPD
IPD=IPD4;
Ei=STATES_z4[i][2]*eV2J-IPD3+mu;
if(Ei<0) prob=0.0;
#endif
if(Q_z4>0)
Ith(y,i+ishift+z0_len+z1_len+z2_len+z3_len)=n4/Q_z4*STATES_z4[i][3]*prob;
if(Ith(y,i+ishift+z0_len+z1_len+z2_len+z3_len) < MINCONC)
Ith(y,i+ishift+z0_len+z1_len+z2_len+z3_len)=0.0;
if(isnan(Ith(y,i+ishift+z0_len+z1_len+z2_len+z3_len))!=0 || isinf(Ith(y,i+ishift+z0_len+z1_len+z2_len+z3_len))!=0)
{
char errstr[255];
sprintf(errstr,"ERROR in do_Saha z4: y is inf or nan! prob:%.4e, Ei:%.4e,DeltaE:%4.e\n",
prob,Ei,DeltaE);
error(errstr);
}
}
#endif
double totalc_check=0.0;
double n0_check=0.0;
double n1_check=0.0;
double n2_check=0.0;
double n3_check=0.0;
double n4_check=0.0;
for(i=3;i<neq;i++)
{
totalc_check+=Ith(y,i);
if(i-3 < z0_len)
n0_check+=Ith(y,i);
if(i-3 >= z0_len && i-3-z0_len < z1_len)
n1_check+=Ith(y,i);
if(i-3 >= z0_len+z1_len && i-3-z0_len-z1_len < z2_len)
n2_check+=Ith(y,i);
if(i-3 >= z0_len+z1_len+z2_len && i-3-z0_len-z1_len-z2_len < z3_len)
n3_check+=Ith(y,i);
if(i-3 >= z0_len+z1_len+z2_len + z3_len && i-3-z0_len-z1_len-z2_len - z3_len < z4_len)
n4_check+=Ith(y,i);
// if(myid==0) printf("y[%d]:%.4e\n",i,Ith(y,i));
}
/*
if(ABS(totalc-totalc_check) > 0.01*totalc || ABS(n0_check-n0) > 0.01* n0 ||
ABS(n1_check-n1) > 0.01* n1 || ABS(n2_check-n2) > 0.01* n2 || ABS(n3_check-n3) > 0.01* n3 ||
ABS(n4_check-n4) > 0.01* n4 )
if(myid==0)
{
char errstr[400];
sprintf(errstr,"Inconsistency in do_Saha: totalc_check= %.4e, and totalc=%.4e,sum_n:%.4e,"
"n0:%.4e, n1:%.4e,n2:%.4e,n3:%.4e, n4:%.4e\n"
"n0_check:%.4e, n1_check:%.4e,n2_check:%.4e,n3_check:%.4e, n4_check:%.4e\n",
totalc_check,totalc,n1+n2+n3+n4, n0, n1, n2, n3, n4,n0_check,n1_check,n2_check,n3_check,n4_check);
error(errstr);
}
*/
}
// ************************************************************************************************************
// ACTION
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
int colrad_ydot(double t, N_Vector y, N_Vector colrad_ydot, void *user_data)
{
/*
double t0=1e-12;
double I0=1e17;
double tFWHM=100e-15;
double sigmat=tFWHM/2.3548;
double sigmatsq=sigmat*sigmat;
*/
//It=I0*exp(-POWR((t-t0),2.0)/2.0/sigmatsq);
colrad_UserData data;
data = (colrad_UserData) user_data;
Real It=data->It;
It=0; //It ist LOKALE Intesität!
bool initial_equi=data->initial_equi; //falls ja, wird temperatur nicht variiert.
Real Eexc;
P_E_EE=0.0;
P_E_EI=0.0;
P_E_MPI2=0.0;
P_E_MPI3=0.0;
P_E_RAD_RECOMB=0.0;
Real DeltaE;
Real kfwd,krev;
Real kfwd2; // für 3-Photon absorption
int i,j;
int ishift=3; // UND NICHT =4 (colrad_ydot fängt bei 0 das zählen an!)
int shift,shift1,shift2;
Real ne=Ith(y,2);
Real Te=Ith(y,0);
Real Ti=Ith(y,1);
//FOR REABSORPTION
// Real escape_factor;
Real Ajk;
// Real lambda;
// Real lambda0;
Real sigma_PI,abs_coeff,thickness,tau,wstark_freq,lambda0,wstark_len,escape_factor,groundstate_ioniz;
// thickness=1e-3;
Real sigma_tmp=64.0*POWR(pi,4.0)*POWR(ECHARGE,10.0)*EMASS/3.0/SQRTR(3.0)/POWR(4.0*pi*ECONST,5.0)/POWR(planck,6.0)/LIGHTSPEED/POWR(LASERFREQ,3.0)/POWR(13.6*eV2J,2.0);
//Pre-Zero <--- MUI IMPORTANTE!!!!
//and count totalc for ipd and stark effect
totalc=0.0;
// #ifdef OMP
// #pragma omp parallel for reduction(+: totalc)
// #endif
for(i=0;i<neq;i++)
{
Ith(colrad_ydot,i)=0.0;
if(i >= 3) totalc+=Ith(y,i);
if(isnan(Ith(y,i))!=0)
{
printf("myid:%d, WARNING Ith(y,%d) became NaN! z0len:%d,z1len:%d,z2len:%d\n",myid,i,z0_len,z1_len,z2_len);
return 1;
}
}
data->ni=totalc;
if(totalc<0)
return 1; // <-- RHS fail
// IPD KRAM
Real IPD0,IPD1,IPD2,IPD3,IPD4;
IPD0=IPD1=IPD2=IPD3=0.0;
Real EF=fermi_E(ne);
data->EF=EF;
#ifdef DOIPD
Real r0,debye;
r0=POWR(3.0/4.0/pi/totalc,1.0/3.0);
debye=SQRTR(BOLTZMAN*Te/4.0/pi/POWR(totalc+ne,2.0));
// Atoms, solids, and plasmas in super-intense laser fields S.220
IPD0=1.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;
IPD1=2.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;
IPD2=3.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;
IPD3=4.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;
IPD4=5.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;
data->IPD0=IPD0;
data->IPD1=IPD1;
data->IPD2=IPD2;
data->IPD3=IPD3;
data->IPD4=IPD4;
#endif
int retval=colrad_GetCoeffs(y,It,data);
if(retval !=0 )
{
printf("myid:%d, Warning: colrad getcoeefs returned not 0\n",myid);
return 1; //d.h. failure of RHS
}
//printf("IPD0:%.4e,IPD1:%.4e,IPD2:%.4e\n", IPD0*J2eV,IPD1*J2eV,IPD2*J2eV);
//**********************************************
//Z=0, Exec/De-Exec + SPONTANEOUS EMISSION
//**********************************************
#ifdef OMP //OMP FUNZT AUF DIESE WEISE NICHT !!!
//#pragma omp parallel for schedule(static) collapse(2) private(DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc) num_threads(num_threads)
#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc)
#endif
for(i=0;i<z0_len;++i)
{
for(j=0;j<z0_len;++j)
{
if(j<=i) continue; // MUI IMPORTANTE
Real engi=STATES_z0[i][2]*eV2J-IPD0+EF;
if(engi < 0) continue; //depressed state is continuum
DeltaE=(STATES_z0[j][2]-STATES_z0[i][2])*eV2J;
kfwd=k_EE_z0_z0[i][j]*Ith(y,i+ishift)*ne;
krev=k_EE_z0_z0_b[i][j]*Ith(y,j+ishift)*ne;
//exec. reduces conc. of i state and increases conc. of j state
Ith(colrad_ydot,i+ishift) -=kfwd;
Ith(colrad_ydot,j+ishift) +=kfwd;
//de-excec. increases conc. of i state & decr. conc. of j state
Ith(colrad_ydot,i+ishift)+=krev;
Ith(colrad_ydot,j+ishift)-=krev;
Eexc= (-kfwd+krev)*DeltaE;
P_E_EE+=Eexc;
// printf("Z0-exc:i:%d,j:%d, kfwd:%.4e,krev:%.4e\n", i,j,kfwd,krev);
#ifdef SPONT
// ********SPONT EMISSION ********* //
//Spont.emiss: delta-n !=>0 und delta-l=+-1 (nur opt.allowed trans.)
if((STATES_z0[j][5]-STATES_z0[i][5])>0 && STATES_z0[j][4]-STATES_z0[i][4]==1)
{
Ajk=0.0;
escape_factor=1.0;
lambda0=planck*LIGHTSPEED/DeltaE;
Ajk=EinsteinCoeff(STATES_z0[i][5],STATES_z0[j][5],STATES_z0[j][3],DeltaE);
krev=Ith(y,ishift+j)*Ajk; //neues krev
Ith(colrad_ydot,ishift+j) -= krev;
Ith(colrad_ydot,ishift+i) += krev;
//P_A_SE+=krev*DeltaE; ??
}
#endif
}
}
// *************************************
//Z=1, Exec/De-Exec & SPONTANEOUS EMISSION
// ***************************************
shift2=z0_len;
#ifdef OMP
//#pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc) num_threads(num_threads)
#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc)
#endif
for(i=0;i<z1_len;++i)
{
for(j=0;j<z1_len;++j)
{
if(i<=j) continue; // MUI IMPORTANTE
Real engi=STATES_z1[i][2]*eV2J-IPD0+EF;
if(engi < 0) continue; //depressed state is continuum
DeltaE=(STATES_z1[j][2]-STATES_z1[i][2])*eV2J;
kfwd=k_EE_z1_z1[i][j]*Ith(y,i+ishift+shift2)*ne;
krev=k_EE_z1_z1_b[i][j]*Ith(y,j+ishift+shift2)*ne;
//exec. reduces conc. of i state and increases conc. of j state
Ith(colrad_ydot,i+ishift+shift2) -=kfwd;
Ith(colrad_ydot,j+ishift+shift2) +=kfwd;
//de-excec. increases conc. of i state & decr. conc. of j state
Ith(colrad_ydot,i+ishift+shift2)+=krev;
Ith(colrad_ydot,j+ishift+shift2)-=krev;
// if(myid==1)
// printf("Z=1:kfwd:%.4e,krev:%.4e, yi:%.4e,yj:%.4e\n", kfwd,krev, Ith(y,i+ishift+shift2), Ith(y,j+ishift+shift2));
Eexc= (-kfwd+krev)*DeltaE;
P_E_EE+=Eexc;
// printf("Z1-exc:i:%d,j:%d, kfwd:%.4e,krev:%.4e\n", i,j,kfwd,krev);
#ifdef SPONT
// ********SPONT EMISSION ********* //
//Spont.emiss: delta-n !=>0 und delta-l=+-1 (nur opt.allowed trans.)
if((STATES_z1[j][5]-STATES_z1[i][5])>0 && STATES_z1[j][4]-STATES_z1[i][4]==1)
{
escape_factor=1.0;
lambda0=planck*LIGHTSPEED/DeltaE;
Ajk=EinsteinCoeff(STATES_z1[i][5],STATES_z1[j][5],STATES_z1[j][3],DeltaE);
krev=Ith(y,ishift+shift2+j)*Ajk;
Ith(colrad_ydot,ishift+shift2+j) -= krev;
Ith(colrad_ydot,ishift+shift2+i) += krev;
//P_A_SE+=krev*DeltaE; ??
}
#endif
}
}
// // *************************************
// //Z=2, Exec/De-Exec & SPONTANEOUS EMISSION
// // ***************************************
#if MAXLEVEL > 1
shift2=z0_len+z1_len;
#ifdef OMP
//#pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc) num_threads(num_threads)
#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc)
#endif
for(i=0;i<z2_len;++i)
{
for(j=0;j<z2_len;++j)
{
if(j<=i) continue; // MUI IMPORTANTE
Real engi=STATES_z2[i][2]*eV2J-IPD1+EF;
if(engi < 0) continue; //depressed state is continuum
DeltaE=(STATES_z2[j][2]-STATES_z2[i][2])*eV2J;
kfwd=k_EE_z2_z2[i][j]*Ith(y,i+ishift+shift2)*ne;
krev=k_EE_z2_z2_b[i][j]*Ith(y,j+ishift+shift2)*ne;
//exec. reduces conc. of i state and increases conc. of j state
Ith(colrad_ydot,i+ishift+shift2) -=kfwd;
Ith(colrad_ydot,j+ishift+shift2) +=kfwd;
//de-excec. increases conc. of i state & decr. conc. of j state
Ith(colrad_ydot,i+ishift+shift2)+=krev;
Ith(colrad_ydot,j+ishift+shift2)-=krev;
// if(myid==1)
// printf("Z=2:kfwd:%.4e,krev:%.4e, yi:%.4e,yj:%.4e\n", kfwd,krev, Ith(y,i+ishift+shift2), Ith(y,j+ishift+shift2));
// printf("kfwd:%.5e, krev:%.5e,i:%d,j:%d,keefwd:%.4e,keeb:%.4e,T:%.4e\n",kfwd,krev,i,j,k_EE_z2_z2[i][j], k_EE_z2_z2_b[i][j],Te);
Eexc= (-kfwd+krev)*DeltaE;
P_E_EE+=Eexc;
// printf("Z2-exc:i:%d,j:%d, kfwd:%.4e,krev:%.4e\n", i,j,kfwd,krev);
#ifdef SPONT
// ********SPONT EMISSION ********* //
//Spont.emiss: delta-n !=>0 und delta-l=+-1 (nur opt.allowed trans.)
if((STATES_z2[j][5]-STATES_z2[i][5])>0 && STATES_z2[j][4]-STATES_z2[i][4]==1)
{
escape_factor=1.0;
lambda0=planck*LIGHTSPEED/DeltaE;
Ajk=EinsteinCoeff(STATES_z2[i][5],STATES_z2[j][5],STATES_z2[j][3],DeltaE);
krev=Ith(y,ishift+shift2+j)*Ajk;
Ith(colrad_ydot,ishift+shift2+j) -= krev;
Ith(colrad_ydot,ishift+shift2+i) += krev;
//P_A_SE+=krev*DeltaE; ??
}
#endif
}
}
#endif
// *************************************
//Z=3, Exec/De-Exec & SPONTANEOUS EMISSION
// ***************************************
#if MAXLEVEL > 2
shift2=z0_len+z1_len+z2_len;
#ifdef OMP
// #pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc) num_threads(num_threads)
#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc)
#endif
for(i=0;i<z3_len;++i)
{
for(j=0;j<z3_len;++j)
{
if(j<=i) continue; // MUI IMPORTANTE
Real engi=STATES_z3[i][2]*eV2J-IPD2+EF;
if(engi < 0) continue; //depressed state is continuum
DeltaE=(STATES_z3[j][2]-STATES_z3[i][2])*eV2J;
kfwd=k_EE_z3_z3[i][j]*Ith(y,i+ishift+shift2)*ne;
krev=k_EE_z3_z3_b[i][j]*Ith(y,j+ishift+shift2)*ne;
// if(myid==1)
// printf("Z=3 kfwd:%.4e,krev:%.4e, yi:%.4e,yj:%.4e\n", kfwd,krev, Ith(y,i+ishift+shift2), Ith(y,j+ishift+shift2));
//exec. reduces conc. of i state and increases conc. of j state
Ith(colrad_ydot,i+ishift+shift2) -=kfwd;
Ith(colrad_ydot,j+ishift+shift2) +=kfwd;
//de-excec. increases conc. of i state & decr. conc. of j state
Ith(colrad_ydot,i+ishift+shift2)+=krev;
Ith(colrad_ydot,j+ishift+shift2)-=krev;
Eexc= (-kfwd+krev)*DeltaE;
P_E_EE+=Eexc;
// if(Ith(y,i+ishift+shift2) >0 || Ith(y,j+ishift+shift2)>0)
// printf("myid:%d, i:%d,j:%d,kEE3:%.4e, kEE3b:%.4e,kfwd:%.4e,krev:%.4e,ni:%.4e,nj:%.4e,ne:%.4e\n",myid,i,j,
// k_EE_z3_z3[i][j],k_EE_z3_z3_b[i][j],kfwd,krev,
// Ith(y,i+ishift+shift2),Ith(y,j+ishift+shift2),ne );
// printf("Z3-exc:i:%d,j:%d, kfwd:%.4e,krev:%.4e\n", i,j,kfwd,krev);
#ifdef SPONT
// ********SPONT EMISSION ********* //
//Spont.emiss: delta-n !=>0 und delta-l=+-1 (nur opt.allowed trans.)
if((STATES_z3[j][5]-STATES_z3[i][5])>0 && STATES_z3[j][4]-STATES_z3[i][4]==1)
{
escape_factor=1.0;
lambda0=planck*LIGHTSPEED/DeltaE;
Ajk=EinsteinCoeff(STATES_z3[i][5],STATES_z3[j][5],STATES_z3[j][3],DeltaE);
krev=Ith(y,ishift+shift2+j)*Ajk;
Ith(colrad_ydot,ishift+shift2+j) -= krev;
Ith(colrad_ydot,ishift+shift2+i) += krev;
//P_A_SE+=krev*DeltaE; ??
}
#endif
}
}
#endif //MAXLEVEL > 2
// *************************************
//Z=4, Exec/De-Exec & SPONTANEOUS EMISSION
// ***************************************
#if MAXLEVEL > 3
shift2=z0_len+z1_len+z2_len+z3_len;
#ifdef OMP
// #pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc) num_threads(num_threads)
#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc)
#endif
for(i=0;i<z4_len;++i)
{
for(j=0;j<z4_len;++j)
{
if(j<=i) continue; // MUI IMPORTANTE
DeltaE=(STATES_z4[j][2]-STATES_z4[i][2])*eV2J-IPD3+EF;
kfwd=k_EE_z4_z4[i][j]*Ith(y,i+ishift+shift2)*ne;
krev=k_EE_z4_z4_b[i][j]*Ith(y,j+ishift+shift2)*ne;
//exec. reduces conc. of i state and increases conc. of j state
Ith(colrad_ydot,i+ishift+shift2) -=kfwd;
Ith(colrad_ydot,j+ishift+shift2) +=kfwd;
//de-excec. increases conc. of i state & decr. conc. of j state
Ith(colrad_ydot,i+ishift+shift2)+=krev;
Ith(colrad_ydot,j+ishift+shift2)-=krev;
// if(myid==1)
// printf("Z=4:kfwd:%.4e,krev:%.4e, yi:%.4e,yj:%.4e\n", kfwd,krev, Ith(y,i+ishift+shift2), Ith(y,j+ishift+shift2));
Eexc= (-kfwd+krev)*DeltaE;
P_E_EE+=Eexc;
// printf("Z4-exc:i:%d,j:%d, kfwd:%.4e,krev:%.4e\n", i,j,kfwd,krev);
#ifdef SPONT
// ********SPONT EMISSION ********* //
//Spont.emiss: delta-n !=>0 und delta-l=+-1 (nur opt.allowed trans.)
if((STATES_z4[j][5]-STATES_z4[i][5])>0 && STATES_z4[j][4]-STATES_z4[i][4]==1)
{
escape_factor=1.0;
lambda0=planck*LIGHTSPEED/DeltaE;
Ajk=EinsteinCoeff(STATES_z3[i][5],STATES_z3[j][5],STATES_z3[j][3],DeltaE);
krev=Ith(y,ishift+shift2+j)*Ajk;
Ith(colrad_ydot,ishift+shift2+j) -= krev;
Ith(colrad_ydot,ishift+shift2+i) += krev;
//P_A_SE+=krev*DeltaE; ??
}
#endif
}
}
#endif // MAXLEVEL > 3
// ********************************************************
// NOW IONIZATION RATES
// ********************************************************
// ***************************
//Z=0->Z=1, Ioniz./Recomb.
// ***************************
shift1=ishift;
shift2=ishift+z0_len;
#ifdef OMP
// #pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,kfwd2,krev,\
escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc) num_threads(num_threads)
#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,kfwd2,krev,\
escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc)
#endif
for(i=0;i<z0_len;++i)
{
for(j=0;j<z1_len;++j)
{
DeltaE=(STATES_z1[j][2]-STATES_z0[i][2])*eV2J-IPD0+EF;
#ifdef DOIPD
if(DeltaE<0) continue;
DeltaE=MAX(0.0,DeltaE);
#endif
//COLL IONIZ
Ith(colrad_ydot,i+shift1) -= k_EI_z0_z1[i][j]*Ith(y,i+shift1)*ne;
Ith(colrad_ydot,2) += k_EI_z0_z1[i][j]*Ith(y,i+shift1)*ne; //Ne inc.
Ith(colrad_ydot,j+shift2) += k_EI_z0_z1[i][j]*Ith(y,i+shift1)*ne;
//3-body recomb
Ith(colrad_ydot,j+shift2) -= k_EI_z1_z0[i][j]*Ith(y,j+shift2)*ne*ne;
Ith(colrad_ydot,i+shift1) += k_EI_z1_z0[i][j]*Ith(y,j+shift2)*ne*ne;
Ith(colrad_ydot,2) -= k_EI_z1_z0[i][j]*Ith(y,j+shift2)*ne*ne;
Eexc = -k_EI_z0_z1[i][j]*Ith(y,i+shift1)*ne*DeltaE;
Eexc += k_EI_z1_z0[i][j]*Ith(y,j+shift2)*ne*ne*DeltaE;
P_E_EI += Eexc;
// printf("Z0-ioniz: i:%d,j:%d, kfwd:%.4e,krev:%.4e\n", i,j, k_EI_z0_z1[i][j], k_EI_z1_z0[i][j]);
//////////
// MPI
//////////
escape_factor=1.0;
#ifdef MULTIPHOTON
#ifdef STARK
if(k_MPI_z1_z0[i][j][0]>0 && STATES_z1[j][5]>STATES_z0[i][5])
{
//außerdem geht die quasi-static. approx. nur mit nu-nl>0
groundstate_ioniz=(STATES_z1[0][2]-STATES_z0[0][2])*eV2J;
sigma_PI=sigma_tmp*POWR(DeltaE,2.5)/SQRTR(groundstate_ioniz);
abs_coeff=sigma_PI*ne; //cross-section mit Pauli-blocking-faktor korrigieren!
tau=abs_coeff*thickness;
wstark_freq=StarkWidth(STATES_z1[j][5],STATES_z0[i][5],Te/11605,Ti/11605,Ti/11605,ne,totalc);
lambda0=planck*LIGHTSPEED/DeltaE;
wstark_len=wstark_freq*lambda0*lambda0/LIGHTSPEED;
escape_factor=EscapeFactor(wstark_len*1e10,tau);
}
#endif
//ACHTUNG: Diskussion ob MPI sich überhaupt für Potential-Lowering interessiert...?
if(DeltaE >0 ) //DeltaE ist bereits abzgl. IPD
{
kfwd= k_MPI_z0_z1[i][j][0]*Ith(y,i+shift1); // Einheit: k_MPI = 1/s
kfwd2=k_MPI_z0_z1[i][j][1]*Ith(y,i+shift1); // *wup; // 2 photon- and 3-photon ionization!
krev=k_MPI_z1_z0[i][j][0]*Ith(y,j+shift2)*ne;// *escape_factor; // *wlo; // einheit: k_RADRECOMB= m^3/s
//kfwd2=0.0; // 3-photon-ioniz. off
Ith(colrad_ydot,shift1+i) -=(kfwd +kfwd2);
Ith(colrad_ydot,2) +=(kfwd +kfwd2); //Ne inc.
Ith(colrad_ydot,shift2+j) +=(kfwd +kfwd2);
//krev=fmin(krev,kfwd);
Ith(colrad_ydot,shift2+j) -=krev;
Ith(colrad_ydot,shift1+i) +=krev;
Ith(colrad_ydot,2)-=krev;
// für 2 photonen und rad.recomb
P_E_MPI2 += kfwd* (2.0*planck*LASERFREQ-(DeltaE)); //kein heating durch rad.recomb->Photon verschwindet (bisher ohne self-absorption)
//jetzt für 3 photonen
P_E_MPI3 += kfwd2*(3.0*planck*LASERFREQ-(DeltaE));
//jetzt rad recomb
P_E_RAD_RECOMB -= krev*(DeltaE)*escape_factor; //Radiative cooling, c.f. http://www.astronomy.ohio-state.edu/~dhw/A825/notes8.pdf S.2
}
#endif //MPI
}
}
// ***************************
// Z=1->Z=2, Ioniz./Recomb.
// ***************************
#if MAXLEVEL > 1
shift1=ishift+z0_len;
shift2=ishift+z0_len+z1_len;
#ifdef OMP
//#pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,kfwd2,krev,\
escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc) num_threads(num_threads)
#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,kfwd2,krev,\
escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc)
#endif
for(i=0;i<z1_len;++i)
{
for(j=0;j<z2_len;++j)
{
DeltaE=(STATES_z2[j][2]-STATES_z1[i][2])*eV2J-IPD1+EF;
#ifdef DOIPD
if(DeltaE<0) continue;
DeltaE=MAX(0.0,DeltaE);
#endif
//COLL IONIZ
Ith(colrad_ydot,i+shift1) -= k_EI_z1_z2[i][j]*Ith(y,i+shift1)*ne;
Ith(colrad_ydot,2) += k_EI_z1_z2[i][j]*Ith(y,i+shift1)*ne; //Ne inc.
Ith(colrad_ydot,j+shift2) += k_EI_z1_z2[i][j]*Ith(y,i+shift1)*ne;
//3-body recomb
Ith(colrad_ydot,shift2+j) -= k_EI_z2_z1[i][j]*Ith(y,j+shift2)*ne*ne;
Ith(colrad_ydot,shift1+i) += k_EI_z2_z1[i][j]*Ith(y,j+shift2)*ne*ne;
Ith(colrad_ydot,2) -= k_EI_z2_z1[i][j]*Ith(y,j+shift2)*ne*ne;
Eexc = -k_EI_z1_z2[i][j]*Ith(y,i+shift1)*ne*DeltaE;
Eexc += k_EI_z2_z1[i][j]*Ith(y,j+shift2)*ne*ne*DeltaE;
P_E_EI += Eexc;
// printf("Z1-ioniz: i:%d,j:%d, kfwd:%.4e,krev:%.4e\n", i,j, k_EI_z1_z2[i][j], k_EI_z2_z1[i][j]);
//////////
// MPI
//////////
escape_factor=1.0;
#ifdef MULTIPHOTON
#ifdef STARK
if(k_MPI_z2_z1[i][j][0]>0 && STATES_z2[j][5]>STATES_z1[i][5])
{
//außerdem geht die quasi-static. approx. nur mit nu-nl>0
groundstate_ioniz=(STATES_z2[0][2]-STATES_z1[0][2])*eV2J;
sigma_PI=sigma_tmp*POWR(DeltaE,2.5)/SQRTR(groundstate_ioniz);
abs_coeff=sigma_PI*ne; //cross-section mit Pauli-blocking-faktor korrigieren!
tau=abs_coeff*thickness;
wstark_freq=StarkWidth(STATES_z2[j][5],STATES_z1[i][5],Te/11605,Ti/11605,Ti/11605,ne,totalc);
lambda0=planck*LIGHTSPEED/DeltaE;
wstark_len=wstark_freq*lambda0*lambda0/LIGHTSPEED;
escape_factor=EscapeFactor(wstark_len*1e10,tau);
}
#endif
if(DeltaE >0)
{
kfwd= k_MPI_z1_z2[i][j][0]*Ith(y,i+shift1); // *wup;
kfwd2=k_MPI_z1_z2[i][j][1]*Ith(y,i+shift1); // *wup; // 2 photon- and 3-photon ionization!
krev=k_MPI_z2_z1[i][j][0]*Ith(y,shift2+j)*ne; // *wlo; //eigentlich Rad-recomb.!=k_MPI_rev, einheit von k=m^3/s
//kfwd2=0.0; // 3-photon-ioniz. off
Ith(colrad_ydot,i+shift1) -=(kfwd +kfwd2);
Ith(colrad_ydot,2) +=(kfwd +kfwd2); //Ne inc.
Ith(colrad_ydot,shift2+j) +=(kfwd +kfwd2);
//krev=fmin(krev,kfwd);
Ith(colrad_ydot,shift2+j) -=krev;
Ith(colrad_ydot,shift1+i) +=krev;
Ith(colrad_ydot,2)-=krev;
// für 2 photonen und rad.recomb
P_E_MPI2 += kfwd* (2.0*planck*LASERFREQ-(DeltaE)); //kein heating durch rad.recomb->Photon verschwindert (bisher ohne self-absorption)
//jetzt für 3 photonen
P_E_MPI3 += kfwd2*(3.0*planck*LASERFREQ-(DeltaE));
//jetzt rad recomb
P_E_RAD_RECOMB -= krev*(DeltaE)*escape_factor;
}
#endif //MPI
}
}
#endif // MAXLEVEL > 1
// ***************************
// Z=2->Z=3, Ioniz./Recomb.
// ***************************
#if MAXLEVEL > 2
shift1=ishift+z0_len+z1_len;
shift2=ishift+z0_len+z1_len+z2_len;
#ifdef OMP
//#pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,kfwd2,krev,\
escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc) num_threads(num_threads)
#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,kfwd2,krev,\
escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc)
#endif
for(i=0;i<z2_len;++i)
{
for(j=0;j<z3_len;++j)
{
DeltaE=(STATES_z3[j][2]-STATES_z2[i][2])*eV2J-IPD2+EF;
#ifdef DOIPD
if(DeltaE<0) continue;
DeltaE=MAX(0.0,DeltaE);
#endif
//COLL IONIZ
Ith(colrad_ydot,i+shift1) -= k_EI_z2_z3[i][j]*Ith(y,i+shift1)*ne;
Ith(colrad_ydot,2) += k_EI_z2_z3[i][j]*Ith(y,i+shift1)*ne; //Ne inc.
Ith(colrad_ydot,j+shift2) += k_EI_z2_z3[i][j]*Ith(y,i+shift1)*ne;
//3-body recomb
Ith(colrad_ydot,shift2+j) -= k_EI_z3_z2[i][j]*Ith(y,j+shift2)*ne*ne;
Ith(colrad_ydot,shift1+i) += k_EI_z3_z2[i][j]*Ith(y,j+shift2)*ne*ne;
Ith(colrad_ydot,2) -= k_EI_z3_z2[i][j]*Ith(y,j+shift2)*ne*ne;
Eexc = -k_EI_z2_z3[i][j]*Ith(y,i+shift1)*ne*DeltaE;
Eexc += k_EI_z3_z2[i][j]*Ith(y,j+shift2)*ne*ne*DeltaE;
P_E_EI += Eexc;
// printf("Z2-ioniz: i:%d,j:%d, kfwd:%.4e,krev:%.4e\n", i,j, k_EI_z2_z3[i][j], k_EI_z3_z2[i][j]);
//////////
// MPI
//////////
escape_factor=1.0;
#ifdef MULTIPHOTON
#ifdef STARK
if(k_MPI_z3_z2[i][j][0]>0 && STATES_z3[j][5]>STATES_z2[i][5])
{
//außerdem geht die quasi-static. approx. nur mit nu-nl>0
groundstate_ioniz=(STATES_z3[0][2]-STATES_z2[0][2])*eV2J;
sigma_PI=sigma_tmp*POWR(DeltaE,2.5)/SQRTR(groundstate_ioniz);
abs_coeff=sigma_PI*ne; //cross-section mit Pauli-blocking-faktor korrigieren!
tau=abs_coeff*thickness;
wstark_freq=StarkWidth(STATES_z3[j][5],STATES_z2[i][5],Te/11605,Ti/11605,Ti/11605,ne,totalc);
lambda0=planck*LIGHTSPEED/DeltaE;
wstark_len=wstark_freq*lambda0*lambda0/LIGHTSPEED;
escape_factor=EscapeFactor(wstark_len*1e10,tau);
}
#endif
if(DeltaE >0)
{
kfwd= k_MPI_z2_z3[i][j][0]*Ith(y,i+shift1); // *wup;
kfwd2=k_MPI_z3_z2[i][j][1]*Ith(y,i+shift1); // *wup; // 2 photon- and 3-photon ionization!
krev=k_MPI_z3_z2[i][j][0]*Ith(y,shift2+j)*ne; // *wlo; //eigentlich Rad-recomb.!=k_MPI_rev, einheit von k=m^3/s
//kfwd2=0.0; // 3-photon-ioniz. off
Ith(colrad_ydot,i+shift1) -=(kfwd +kfwd2);
Ith(colrad_ydot,2) +=(kfwd +kfwd2); //Ne inc.
Ith(colrad_ydot,shift2+j) +=(kfwd +kfwd2);
//krev=fmin(krev,kfwd);
Ith(colrad_ydot,shift2+j) -=krev;
Ith(colrad_ydot,shift1+i) +=krev;
Ith(colrad_ydot,2)-=krev;
// für 2 photonen und rad.recomb
P_E_MPI2 += kfwd* (2.0*planck*LASERFREQ-(DeltaE)); //kein heating durch rad.recomb->Photon verschwindert (bisher ohne self-absorption)
//jetzt für 3 photonen
P_E_MPI3 += kfwd2*(3.0*planck*LASERFREQ-(DeltaE));
//jetzt rad recomb
P_E_RAD_RECOMB -= krev*(DeltaE)*escape_factor;
}
#endif //MPI
}
}
#endif // MAXLEVEL > 2
// ***************************
// Z=3->Z=4, Ioniz./Recomb.
// ***************************
#if MAXLEVEL > 3
shift1=ishift+z0_len+z1_len+z2_len;
shift2=ishift+z0_len+z1_len+z2_len+z3_len;
#ifdef OMP
//#pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,kfwd2,krev,\
escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc) num_threads(num_threads)
#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,kfwd2,krev,\
escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc)
#endif
for(i=0;i<z3_len;++i)
{
for(j=0;j<z4_len;++j)
{
DeltaE=(STATES_z4[j][2]-STATES_z3[i][2])*eV2J-IPD3+EF;
#ifdef DOIPD
if(DeltaE<0) continue;
DeltaE=MAX(0.0,DeltaE);
#endif
//COLL IONIZ
Ith(colrad_ydot,i+shift1) -= k_EI_z3_z4[i][j]*Ith(y,i+shift1)*ne;
Ith(colrad_ydot,2) += k_EI_z3_z4[i][j]*Ith(y,i+shift1)*ne; //Ne inc.
Ith(colrad_ydot,j+shift2) += k_EI_z3_z4[i][j]*Ith(y,i+shift1)*ne;
//3-body recomb
Ith(colrad_ydot,shift2+j) -= k_EI_z4_z3[i][j]*Ith(y,j+shift2)*ne*ne;
Ith(colrad_ydot,shift1+i) += k_EI_z4_z3[i][j]*Ith(y,j+shift2)*ne*ne;
Ith(colrad_ydot,2) -= k_EI_z4_z3[i][j]*Ith(y,j+shift2)*ne*ne;
Eexc = -k_EI_z3_z4[i][j]*Ith(y,i+shift1)*ne*DeltaE;
Eexc += k_EI_z4_z3[i][j]*Ith(y,j+shift2)*ne*ne*DeltaE;
P_E_EI += Eexc;
// printf("Z3-ioniz: i:%d,j:%d, kfwd:%.4e,krev:%.4e\n", i,j, k_EI_z3_z4[i][j], k_EI_z4_z3[i][j]);
//////////
// MPI
//////////
escape_factor=1.0;
#ifdef MULTIPHOTON
#ifdef STARK
if(k_MPI_z4_z3[i][j][0]>0 && STATES_z4[j][5]>STATES_z3[i][5])
{
//außerdem geht die quasi-static. approx. nur mit nu-nl>0
groundstate_ioniz=(STATES_z4[0][2]-STATES_z3[0][2])*eV2J;
sigma_PI=sigma_tmp*POWR(DeltaE,2.5)/SQRTR(groundstate_ioniz);
abs_coeff=sigma_PI*ne; //cross-section mit Pauli-blocking-faktor korrigieren!
tau=abs_coeff*thickness;
wstark_freq=StarkWidth(STATES_z4[j][5],STATES_z3[i][5],Te/11605,Ti/11605,Ti/11605,ne,totalc);
lambda0=planck*LIGHTSPEED/DeltaE;
wstark_len=wstark_freq*lambda0*lambda0/LIGHTSPEED;
escape_factor=EscapeFactor(wstark_len*1e10,tau);
}
#endif
if(DeltaE >0)
{
kfwd= k_MPI_z3_z4[i][j][0]*Ith(y,i+shift1); // *wup;
kfwd2=k_MPI_z4_z3[i][j][1]*Ith(y,i+shift1); // *wup; // 2 photon- and 3-photon ionization!
krev=k_MPI_z4_z3[i][j][0]*Ith(y,shift2+j)*ne; // *wlo; //eigentlich Rad-recomb.!=k_MPI_rev, einheit von k=m^3/s
//kfwd2=0.0; // 3-photon-ioniz. off
Ith(colrad_ydot,i+shift1) -=(kfwd +kfwd2);
Ith(colrad_ydot,2) +=(kfwd +kfwd2); //Ne inc.
Ith(colrad_ydot,shift2+j) +=(kfwd +kfwd2);
//krev=fmin(krev,kfwd);
Ith(colrad_ydot,shift2+j) -=krev;
Ith(colrad_ydot,shift1+i) +=krev;
Ith(colrad_ydot,2)-=krev;
// für 2 photonen und rad.recomb
P_E_MPI2 += kfwd* (2.0*planck*LASERFREQ-(DeltaE)); //kein heating durch rad.recomb->Photon verschwindert (bisher ohne self-absorption)
//jetzt für 3 photonen
P_E_MPI3 += kfwd2*(3.0*planck*LASERFREQ-(DeltaE));
//jetzt rad recomb
P_E_RAD_RECOMB -= krev*(DeltaE)*escape_factor;
}
#endif //MPI
}
}
#endif //MAXLEVEL > 3
// ********************** THERMO ******************************************
// double cvinv=1.0/(1.5*BOLTZMAN*ne);
Real P_E_TOTAL=P_E_EI+P_E_EE+P_E_MPI2+P_E_MPI3+P_E_RAD_RECOMB;
data->P_TOTAL=P_E_TOTAL;
data->P_EE=P_E_EE;
data->P_EI=P_E_EI;
data->P_MPI2=P_E_MPI2;
data->P_MPI3=P_E_MPI3;
data->P_RR=P_E_RAD_RECOMB;
// printf("myid:%d, PEI:%.4e, PEE:%.4e,MPI2:%.4e, MPI3:%.4e, RADREC:%.4e\n",
// myid,
// P_E_EI,
// P_E_EE,
// P_E_MPI2,
// P_E_MPI3,
// P_E_RAD_RECOMB);
//BEI PRE-EQUILIBRIERUNG T=CONST !
if(initial_equi==false)
{
Real cv=EOS_cve_from_r_te(data->dens, Te);
cv *= 1e30/11604.5*eV2J; // von eV/(eV*A^3) to J/(K*m^3)
Real cvinv=1.0/cv;
// double cvinv= 1.0/Cv(Te/11604.5, ne);
//double cvinv=1.0/(1.5*BOLTZMAN*Te);
Ith(colrad_ydot,0) = cvinv*P_E_TOTAL;
Ith(colrad_ydot,0) += data->Heatrate;
// if(myid==1)
// for(i=0;i<neq;i++)
// {
// printf("theta:%.4e\n", cvinv*P_E_TOTAL);
// }
}
else
{
Ith(colrad_ydot,0)=0.0;
}
return 0; // 0 heisst alles ok
}
// ********************************************************************+
// * COMPUTE RATE COEFFS
// ********************************************************************+
int colrad_GetCoeffs(N_Vector y,Real It,void *user_data)
{
int i,j,k;
Real kronecker;
Real DeltaE;
Real Te,ne;
Te=Ith(y,0);
if(Te <0 || isnan(Te)!=0) return -1;
ne=Ith(y,2);
if(ne <0 || isnan(ne)!=0) return -1;
// double v_e=SQRTR(8.0*BOLTZMAN*Te/pi/EMASS);
// Real E_ion_H=13.6*eV2J;
// double alpha_i=0.05;
// double alpha_e=0.05;
// double beta_i=4.0;
// double four_pi_a0_sq=4.0*pi*POWR(bohr_radius,2.0);
// double E_ion_H_div_kTe_sq=POWR((E_ion_H/BOLTZMAN/Te),2.0);
// double two_pi_me_kT_hsq=2.0*pi*EMASS*BOLTZMAN*Te/POWR(planck,2.0);
// double log54_beta_i=log(5.0/4.0*beta_i);
Real kbTe=(BOLTZMAN*Te);
kbTe=Te/11604.5;
Real tmp0,tmp1,tmp2;
colrad_UserData data;
data = (colrad_UserData) user_data;
Real IPD0=data->IPD0*J2eV;
Real IPD1=data->IPD1*J2eV;
Real IPD2=data->IPD2*J2eV;
Real IPD3=data->IPD3*J2eV;
Real IPD4=data->IPD4*J2eV;
Real EF=data->EF*J2eV;
Real Tinit=data->Tinit;
bool initial_equi = data->initial_equi;
if(initial_equi)
{
if(ABS(Te-Tinit) > Tinit*0.03) // cvode war zu eifrig und probiert extreme temp. aus
return -1;
}
// else
// {
// // if(ABS(Te-Tinit) > Tinit*0.5) // cvode war zu eifrig und probiert extreme temp. aus
// // return -1;
// if(Te>1e4) //ACHTUNG: Keine gute lösung...eher hotfix
// return -1;
// }
//MPI
// Real k_RR_fact1=32*pi*POWR(bohr_radius,2.0)/3.0/175700.00067;
// Real k_RR_fact2=POWR((E_ion_H/BOLTZMAN/Te),2.0);
// Real sigma_MPI_2;//=sigma1/LASERFREQ/POWR(planck*LASERFREQ,2.0); //MPI-cross-sect. (2-photon)
// Real sigma_MPI_3;
// Real sigma1;
//const. zur berechnung von sigma1
// Real sigma_tmp=64.0*POWR(pi,4.0)*POWR(ECHARGE,10.0)*EMASS/3.0/SQRTR(3.0)/POWR(4.0*pi*ECONST,5.0)/POWR(planck,6.0)/LIGHTSPEED/POWR(LASERFREQ,3.0)/POWR(13.6*eV2J,2.0);
// Real I_sq=It*It; //for 2-photon-ioniz.
// Real I_cu=I_sq*It; // for 3-photon-ioniz.
int fail=0;
// Real pow_two_pi_me_kT_hsq_tmp1= POWR(two_pi_me_kT_hsq,1.5); //ACHTUNG: Das ist thermal De-Broglie Lambda
//Ich muss das für die rückwärts-raten irgendie
//durch chempot ersetzen sonst pass das net
//Ebenso in Saha
#ifdef MULTIPHOTON
Real twophoton_energy=2.0*planck*LASERFREQ*J2eV;
Real threephoton_energy=3.0*planck*LASERFREQ*J2eV;
Real nu_div_hnu_sq=LASERFREQ/POWR(planck*LASERFREQ,2.0);
Real nu_div_nu_div_hnu_cub=LASERFREQ/LASERFREQ/POWR(planck*LASERFREQ,3.0);
#endif
Real mu=chempot(ne,Te);
Real mu_eV=mu*J2eV;
//Real fermi_factor=eval_fermi_integrand(ne,Te,mu);
Real fermi_factor=1.0;
if(fermi_factor==-1)
return -1;
// Real kmax_estim=1e4;
Real nesq=gsl_pow_2(ne);
//PREZERO RATE-COEFFS CODEBLOCK
{
//pre-zero k_EE's
for(i=0;i<z0_len;i++)
{
for(j=0;j<z0_len;j++)
{
k_EE_z0_z0[i][j]=0.0;
k_EE_z0_z0_b[i][j]=0.0;
}
}
for(i=0;i<z1_len;i++)
{
for(j=0;j<z1_len;j++)
{
k_EE_z1_z1[i][j]=0.0;
k_EE_z1_z1_b[i][j]=0.0;
}
}
#if MAXLEVEL > 1
for(i=0;i<z2_len;i++)
{
for(j=0;j<z2_len;j++)
{
k_EE_z2_z2[i][j]=0.0;
k_EE_z2_z2_b[i][j]=0.0;
}
}
#endif
#if MAXLEVEL > 2
for(i=0;i<z3_len;i++)
{
for(j=0;j<z3_len;j++)
{
k_EE_z3_z3[i][j]=0.0;
k_EE_z3_z3_b[i][j]=0.0;
}
}
#endif
#if MAXLEVEL > 3
for(i=0;i<z4_len;i++)
{
for(j=0;j<z4_len;j++)
{
k_EE_z4_z4[i][j]=0.0;
k_EE_z4_z4_b[i][j]=0.0;
}
}
#endif
//pre-zero k_MPI's
for(i=0;i<z0_len;i++)
{
for(j=0;j<z1_len;j++)
{
k_EI_z0_z1[i][j]=0.0;
k_EE_z1_z1[i][j]=0.0;
for(k=0;k<2;k++)
{
k_MPI_z0_z1[i][j][k]=0.0;
k_MPI_z1_z0[i][j][k]=0.0;
}
}
}
#if MAXLEVEL > 1
for(i=0;i<z1_len;i++)
{
for(j=0;j<z2_len;j++)
{
k_EI_z1_z2[i][j]=0.0;
k_EI_z2_z1[i][j]=0.0;
for(k=0;k<2;k++)
{
k_MPI_z1_z2[i][j][k]=0.0;
k_MPI_z2_z1[i][j][k]=0.0;
}
}
}
#endif
#if MAXLEVEL > 2
for(i=0;i<z2_len;i++)
{
for(j=0;j<z3_len;j++)
{
k_EI_z2_z3[i][j]=0.0;
k_EI_z3_z2[i][j]=0.0;
for(k=0;k<2;k++)
{
k_MPI_z2_z3[i][j][k]=0.0;
k_MPI_z3_z2[i][j][k]=0.0;
}
}
}
#endif
#if MAXLEVEL > 3
for(i=0;i<z3_len;i++)
{
for(j=0;j<z4_len;j++)
{
k_EI_z3_z4[i][j]=0.0;
k_EI_z4_z3[i][j]=0.0;
for(k=0;k<2;k++)
{
k_MPI_z3_z4[i][j][k]=0.0;
k_MPI_z4_z3[i][j][k]=0.0;
}
}
}
#endif
}
//ACHTUNG: Nur um initial equi zu überspringen!
// if(initial_equi==true)
// return 0;
///////////////////////////////
// Elec. excitation for Z=0
///////////////////////////////
#ifdef OMP
//#pragma omp parallel for schedule(dynamic,1) collapse(2) private(kronecker,DeltaE,a,expint,G2,I_1,I_2) num_threads(num_threads)
// #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_exc, winteg_exc)
// #pragma omp for simd schedule(static) collapse(2) private(kronecker,DeltaE,a,expint,G2,I_1,I_2)
#endif
for(i=0;i<z0_len;++i)
{
for(j=0;j<z0_len;++j)
{
if(j<=i) continue;
kronecker=0.0; //optically allowed transition
if(STATES_z0[i][4]==STATES_z0[j][4]) // l_j==l_i ?
kronecker=1.0;//optically forbidden transition
DeltaE=(STATES_z0[j][2]-STATES_z0[i][2]);
#ifdef DOIPD
Real Ei=(STATES_z0[i][2])-IPD0+mu_eV;//+EF;
if(Ei<0) continue;
#endif
k_EE_z0_z0[i][j]=eval_excitation_integral(ne,Te,mu,DeltaE*eV2J,kronecker); // in m^3/s
k_EE_z0_z0_b[i][j]=eval_dexcitation_integral(ne,Te,mu,DeltaE*eV2J,kronecker)*STATES_z0[i][3]/STATES_z0[j][3];
k_EE_MAX=MAX(k_EE_z0_z0[i][j],k_EE_MAX);
k_EE_REV_MAX=MAX(k_EE_z0_z0_b[i][j],k_EE_REV_MAX);
}
}
////////////////////////
// Elec. exc. for Z=1
///////////////////////
fail=0;
#ifdef OMP
// #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_exc,winteg_exc)
#endif
for(i=0;i<z1_len;++i)
{
for(j=0;j<z1_len;++j)
{
if(j<=i) continue;
kronecker=0.0;
if(STATES_z1[i][4]==STATES_z1[j][4])
kronecker=1.0;
#ifdef DOIPD
//Real Ei=(STATES_z1[i][2]-STATES_z1[0][2])-IPD1+EF;
Real Ei=STATES_z1[i][2]-IPD0+mu_eV;
if(Ei<0) continue;
#endif
DeltaE=(STATES_z1[j][2]-STATES_z1[i][2]);
k_EE_z1_z1[i][j]=eval_excitation_integral(ne,Te,mu,DeltaE*eV2J,kronecker); // in m^3/s
k_EE_z1_z1_b[i][j]=eval_dexcitation_integral(ne,Te,mu,DeltaE*eV2J,kronecker)*STATES_z1[i][3]/STATES_z1[j][3];
k_EE_MAX=MAX(k_EE_z1_z1[i][j],k_EE_MAX);
k_EE_REV_MAX=MAX(k_EE_z1_z1_b[i][j],k_EE_REV_MAX);
}
}
////////////////////////
// Elec. exc. for Z=2
///////////////////////
#if MAXLEVEL > 1
fail=0;
#ifdef OMP
// #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_exc,winteg_exc)
#endif
for(i=0;i<z2_len;++i)
{
for(j=0;j<z2_len;++j)
{
if(j<=i) continue;
kronecker=0.0;
if(STATES_z2[i][4]==STATES_z2[j][4])
kronecker=1.0;
#ifdef DOIPD
// Real Ei=(STATES_z2[i][2]-STATES_z2[0][2])-IPD2+EF;
Real Ei=STATES_z2[i][2]-IPD1+mu_eV;
if(Ei<0) continue;
#endif
DeltaE=(STATES_z2[j][2]-STATES_z2[i][2]);
k_EE_z2_z2[i][j]=eval_excitation_integral(ne,Te,mu,DeltaE*eV2J,kronecker);
k_EE_z2_z2_b[i][j]=eval_dexcitation_integral(ne,Te,mu,DeltaE*eV2J,kronecker)*STATES_z2[i][3]/STATES_z2[j][3];
k_EE_MAX=MAX(k_EE_z2_z2[i][j],k_EE_MAX);
k_EE_REV_MAX=MAX(k_EE_z2_z2_b[i][j],k_EE_REV_MAX);
}
}
#endif //MAXLEVEL > 1
////////////////////////
// Elec. exc. for Z=3
///////////////////////
#if MAXLEVEL > 2
fail=0;
#ifdef OMP
// #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_exc,winteg_exc)
#endif
for(i=0;i<z3_len;++i)
{
for(j=0;j<z3_len;++j)
{
if(j<=i) continue;
kronecker=0.0;
if(STATES_z3[i][4]==STATES_z3[j][4])
kronecker=1.0;
#ifdef DOIPD
// Real Ei=(STATES_z3[i][2]-STATES_z3[0][2])-IPD3+EF;
Real Ei=STATES_z3[i][2]-IPD2+mu_eV;
if(Ei<0) continue;
#endif
DeltaE=(STATES_z3[j][2]-STATES_z3[i][2]);
k_EE_z3_z3[i][j]=eval_excitation_integral(ne,Te,mu,DeltaE*eV2J,kronecker);
k_EE_z3_z3_b[i][j]=eval_dexcitation_integral(ne,Te,mu,DeltaE*eV2J,kronecker)*STATES_z3[i][3]/STATES_z3[j][3];
k_EE_MAX=MAX(k_EE_z3_z3[i][j],k_EE_MAX);
k_EE_REV_MAX=MAX(k_EE_z3_z3_b[i][j],k_EE_REV_MAX);
// printf("myid:%d,kfw:%.4e,krev:%.4e,i:%d,j:%d\n",myid,k_EE_z3_z3[i][j],k_EE_z3_z3_b[i][j],i,j);
}
}
#endif // MAXLEVEL > 2
////////////////////////
// Elec. exc. for Z=4
///////////////////////
#if MAXLEVEL > 3
fail=0;
#ifdef OMP
// #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_exc,winteg_exc)
#endif
for(i=0;i<z4_len;++i)
{
for(j=0;j<z4_len;++j)
{
if(j<=i) continue;
kronecker=0.0;
if(STATES_z4[i][4]==STATES_z4[j][4])
kronecker=1.0;
#ifdef DOIPD
// Real Ei=(STATES_z4[i][2]-STATES_z4[0][2])-IPD4+EF;
Real Ei=STATES_z4[i][2]-IPD3+mu_eV;
if(Ei<0) continue;
#endif
DeltaE=(STATES_z4[j][2]-STATES_z4[i][2]);
k_EE_z4_z4[i][j]=eval_excitation_integral(ne,Te,mu,DeltaE*eV2J,kronecker);
k_EE_z4_z4_b[i][j]=eval_dexcitation_integral(ne,Te,mu,DeltaE*eV2J,kronecker);
k_EE_MAX=MAX(k_EE_z4_z4[i][j],k_EE_MAX);
k_EE_REV_MAX=MAX(k_EE_z4_z4_b[i][j],k_EE_REV_MAX);
}
}
#endif // MAXLEVEL > 3
// *************************************************
// * NOW IONIZATION COEFFS
// *************************************************
/////////////////
// Ioniz. 0->1
/////////////////
fail=0;
#ifdef OMP
// #pragma omp parallel for schedule(static) collapse(2) private(kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2) num_threads(num_threads)
// #pragma omp for nowait schedule(static) private(j,kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2)
// #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_inner, fparams_outer, winteg_inner, winteg_outer,winteg_rb_inner,winteg_rb_outer)
#endif
for(i=0;i<z0_len;++i)
{
for(j=0;j<z1_len;++j)
{
DeltaE=(STATES_z1[j][2]-STATES_z0[i][2])-IPD0;//+EF;
if(DeltaE <0 )
continue;
if(RATEIONIZMAX*ne*fermi_factor*Ith(y,i+3)> MINRATE)
k_EI_z0_z1[i][j]=MAX(0.0,double_integral_ionization2(ne,Te, mu, DeltaE*eV2J));
if(RATERECOMBMAX*nesq*fermi_factor*Ith(y,j+z0_len+3) > MINRATE)
k_EI_z1_z0[i][j]=STATES_z0[i][3]/STATES_z1[j][3]*double_integral_recombination(ne,Te, mu, DeltaE*eV2J);
k_EI_MAX=MAX(k_EI_MAX,k_EI_z0_z1[i][j]);
k_EI_REV_MAX=MAX(k_EI_REV_MAX,k_EI_z1_z0[i][j]);
k_EI_z0_z1[i][j]*=fermi_factor;
k_EI_z1_z0[i][j]*=fermi_factor;
#ifdef MULTIPHOTON
// *******************
// * MPI 2 PHOTONS *
// *******************
Real dE_SI=DeltaE*eV2J;
if(twophoton_energy >= DeltaE-IPD0 && DeltaE-IPD0 > 0.0 )
{
sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);
sigma_MPI_2=sigma1*sigma1/nu_div_hnu_sq;
k_MPI_z0_z1[i][j][0]=sigma_MPI_2*I_sq;
}
// *******************
// * MPI 3 PHOTONS *
// *******************
if(threephoton_energy >= DeltaE-IPD0 && DeltaE-IPD0 >0.0 )
{
sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);
sigma_MPI_3=sigma1*sigma1*sigma1/2.0/nu_div_nu_div_hnu_cub;
k_MPI_z0_z1[i][j][1]=sigma_MPI_3*I_cu;//*prob*beta_pi(Te,mu,DeltaE);
}
#endif
// ***************
// * RAD RECOMB *
// ***************
// if(DeltaE>0)
// {
// if(expint > 0 )
// {
// //k_MPI_z1_z0[i][j][0]=v_e*k_RR_fact1*1.0*k_RR_fact2*POWR((DeltaE)*J2eV/STATES_z1[j][2],1.5)*expint*exp(a);
// k_MPI_z1_z0[i][j][0]=v_e*k_RR_fact1*1.0*k_RR_fact2*POWR((DeltaE)/STATES_z1[j][2],1.5)*expint*exp(a);
// }
// else
// {
// k_MPI_z1_z0[i][j][0]=0.0; //exp(a) kann +Inf werden--> unsinnige rate coeff.. wenn einer der faktoren=0 --> rest egal
// }
// }
}
}
/////////////////
// Ioniz. 1->2
/////////////////
#if MAXLEVEL > 1
fail=0;
#ifdef OMP
// #pragma omp parallel for schedule(static) collapse(2) private(kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2) num_threads(num_threads)
// #pragma omp for nowait schedule(static) private(j,kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2)
// #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_inner, fparams_outer, winteg_inner, winteg_outer,winteg_rb_inner,winteg_rb_outer)
#endif
for(i=0;i<z1_len;++i)
{
for(j=0;j<z2_len;++j)
{
DeltaE=(STATES_z2[j][2]-STATES_z1[i][2])-IPD1; //+EF;
if(DeltaE <0 )
continue;
if(RATEIONIZMAX*ne*fermi_factor*Ith(y,i+z0_len+3)> MINRATE)
{
k_EI_z1_z2[i][j]=MAX(0.0,double_integral_ionization2(ne,Te, mu, DeltaE*eV2J));
// if(myid==1)
// printf("EVAL dE:%.4e, kEI:%.4e,i:%d,j:%d\n", DeltaE, k_EI_z1_z2[i][j],i,j);
}
// if(kmax_estim*ne*ne*Ith(y,j+z0_len+z1_len+3)>MINRATE)
if(RATERECOMBMAX*nesq*fermi_factor*Ith(y,j+z0_len+z1_len+3) > MINRATE)
k_EI_z2_z1[i][j]=STATES_z1[i][3]/STATES_z2[j][3]*double_integral_recombination(ne,Te, mu, DeltaE*eV2J);
k_EI_MAX=MAX(k_EI_MAX,k_EI_z1_z2[i][j]);
k_EI_REV_MAX=MAX(k_EI_REV_MAX,k_EI_z2_z1[i][j]);
k_EI_z1_z2[i][j]*=fermi_factor;
k_EI_z2_z1[i][j]*=fermi_factor;
#ifdef MULTIPHOTON
Real dE_SI=DeltaE*eV2J;
// *******************
// * MPI 2 PHOTONS *
// *******************
if(twophoton_energy >= DeltaE - IPD1)
{
sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);
sigma_MPI_2=sigma1*sigma1/nu_div_hnu_sq;
k_MPI_z1_z2[i][j][0]=sigma_MPI_2*I_sq;
}
// *******************
// * MPI 3 PHOTONS *
// *******************
if(threephoton_energy > DeltaE - IPD1)
{
sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);
sigma_MPI_3=sigma1*sigma1*sigma1/2.0/nu_div_nu_div_hnu_cub;
k_MPI_z1_z2[i][j][1]=sigma_MPI_3*I_cu;//*prob*beta_pi(Te,mu,DeltaE);
}
#endif
// **************
// * RAD RECOMB *
// **************
// if(DeltaE>0)
// {
// if(expint > 0 )
// {
// k_MPI_z2_z1[i][j][0]=v_e*k_RR_fact1*4.0*k_RR_fact2*POWR((DeltaE)/STATES_z2[j][2],1.5)*expint*exp(a);
// }
// else
// {
// k_MPI_z2_z1[i][j][0]=0.0; //exp(a) kann +Inf werden--> unsinnige rate coeff.. wenn einer der faktoren=0 --> rest egal
// }
// }
}
}
#endif //MAXLEVEL > 1
/////////////////
// Ioniz. 2->3
/////////////////
#if MAXLEVEL > 2
fail=0;
#ifdef OMP
// #pragma omp parallel for schedule(static) collapse(2) private(kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2) num_threads(num_threads)
// #pragma omp for nowait schedule(static) private(j,kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2)
// #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_inner, fparams_outer, winteg_inner, winteg_outer,winteg_rb_inner,winteg_rb_outer)
#endif
for(i=0;i<z2_len;++i)
{
for(j=0;j<z3_len;++j)
{
DeltaE=(STATES_z3[j][2]-STATES_z2[i][2])-IPD2;//+EF;
if(DeltaE <0 )
continue;
if(RATEIONIZMAX*ne*fermi_factor*Ith(y,i+z0_len+z1_len+3)> MINRATE)
k_EI_z2_z3[i][j]=MAX(0.0,double_integral_ionization2(ne,Te, mu, DeltaE*eV2J));
// if(kmax_estim*ne*ne*Ith(y,j+z0_len+z1_len+z2_len+3)>MINRATE)
if(RATERECOMBMAX*nesq*fermi_factor*Ith(y,j+z0_len+z1_len+z2_len+3) > MINRATE)
{
k_EI_z3_z2[i][j]=STATES_z2[i][3]/STATES_z3[j][3]*double_integral_recombination(ne,Te, mu, DeltaE*eV2J);
}
k_EI_MAX=MAX(k_EI_MAX,k_EI_z1_z2[i][j]);
k_EI_REV_MAX=MAX(k_EI_REV_MAX,k_EI_z2_z1[i][j]);
k_EI_z2_z3[i][j]*=fermi_factor;
k_EI_z3_z2[i][j]*=fermi_factor;
#ifdef MULTIPHOTON
Real dE_SI=DeltaE*eV2J;
// *******************
// * MPI 2 PHOTONS *
// *******************
if(twophoton_energy > DeltaE - IPD2)
{
sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);
sigma_MPI_2=sigma1*sigma1/nu_div_hnu_sq;
k_MPI_z2_z3[i][j][0]=sigma_MPI_2*I_sq;
}
// *******************
// * MPI 3 PHOTONS *
// *******************
if(threephoton_energy > DeltaE -IPD2)
{
sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);
sigma_MPI_3=sigma1*sigma1*sigma1/2.0/nu_div_nu_div_hnu_cub;
k_MPI_z2_z3[i][j][1]=sigma_MPI_3*I_cu;//*prob*beta_pi(Te,mu,DeltaE);
}
#endif
}
}
if(fail==1) return -1;
#endif // MAXLEVEL > 2
/////////////////
// Ioniz. 3->4
/////////////////
#if MAXLEVEL > 3
fail=0;
#ifdef OMP
// #pragma omp parallel for schedule(static) collapse(2) private(kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2) num_threads(num_threads)
// #pragma omp for nowait schedule(static) private(j,kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2)
// #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_inner, fparams_outer, winteg_inner, winteg_outer,winteg_rb_inner,winteg_rb_outer)
#endif
for(i=0;i<z3_len;++i)
{
for(j=0;j<z4_len;++j)
{
DeltaE=(STATES_z4[j][2]-STATES_z3[i][2])-IPD3;//+EF;
if(DeltaE <0 )
continue;
if(RATEIONIZMAX*ne*fermi_factor*Ith(y,i+z0_len+z1_len+z2_len+3)> MINRATE)
k_EI_z3_z4[i][j]=MAX(0.0,double_integral_ionization2(ne,Te, mu, DeltaE*eV2J));
// if(kmax_estim*ne*ne*Ith(y,j+z0_len+z1_len+z2_len+z3_len+3)>MINRATE)
if(RATERECOMBMAX*nesq*fermi_factor*Ith(y,j+z0_len+z1_len+z2_len+z3_len+3) > MINRATE)
k_EI_z4_z3[i][j]=STATES_z3[i][3]/STATES_z4[j][3]*double_integral_recombination(ne,Te, mu, DeltaE*eV2J);
k_EI_MAX=MAX(k_EI_MAX,k_EI_z3_z4[i][j]);
k_EI_REV_MAX=MAX(k_EI_REV_MAX,k_EI_z4_z3[i][j]);
k_EI_z3_z4[i][j]*=fermi_factor;
k_EI_z4_z3[i][j]*=fermi_factor;
#ifdef MULTIPHOTON
Real dE_SI=DeltaE*eV2J;
// *******************
// * MPI 2 PHOTONS *
// *******************
if(twophoton_energy> DeltaE - IPD3)
{
sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);
sigma_MPI_2=sigma1*sigma1/nu_div_hnu_sq;
k_MPI_z3_z4[i][j][0]=sigma_MPI_2*I_sq;
}
// *******************
// * MPI 3 PHOTONS *
// *******************
if(threephoton_energy > DeltaE - IPD3)
{
sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);
sigma_MPI_3=sigma1*sigma1*sigma1/2.0/nu_div_nu_div_hnu_cub;
k_MPI_z3_z4[i][j][1]=sigma_MPI_3*I_cu;//*prob*beta_pi(Te,mu,DeltaE);
}
#endif
// **************
// * RAD RECOMB *
// **************
// if(DeltaE>0)
// {
// if(expint>0)
// {
// k_MPI_z4_z3[i][j][0]=v_e*k_RR_fact1*4.0*k_RR_fact2*POWR((DeltaE)/STATES_z4[j][2],1.5)*expint*exp(a);
// }
// else
// {
// k_MPI_z4_z3[i][j][0]=0.0;
// }
// }
}
}
#endif // MAXLEVEL > 3
// if(k_EI_MAX >0 || k_EI_REV_MAX > 0)
// printf("myid:%d, k_EI_MAX:%.4e, k_EI_REV_MAX:%.4e,fac:%.4e\n",myid,k_EI_MAX,k_EI_REV_MAX,fermi_factor);
return 0;
}
// ***************************************************************************************
// ********************************************************************
// * WRITE COLRAD CONCENTRATIONS TO FILE FOR RESTART
// ********************************************************************
int colrad_write(int number)
{
FILE *outfile;
char fname[255];
sprintf(fname, "%s.%d.%d.colrad", outfilename, myid,number);
outfile = fopen(fname, "w");
if (NULL == outfile)
{
char errstr[255];
sprintf(errstr,"ERROR: cannot open colrad outfile %s\n",fname);
error(errstr);
}
int i,j,k,l;
for(i=1; i < local_fd_dim.x-1; i++)
{
for(j=1; j < local_fd_dim.y-1; j++)
{
for(k=1; k < local_fd_dim.z-1; k++)
{
fprintf(outfile,"%d %d %d",i,j,k);
for(l=0;l<neq;l++)
{
fprintf(outfile, " %.4e ", Ith(node.y,l));
}
fprintf(outfile,"\n");
}
}
}
fclose(outfile);
return 0; //alles ok
}
// ********************************************************************
// * READ COLRAD CONCENTRATIONS FOR RESTART
// ********************************************************************
int colrad_read(int number)
{
FILE *infile;
char fname[255];
int i,j,k,l;
sprintf(fname, "%s.%d.%d.colrad", outfilename, myid,number);
infile=fopen(fname,"r");
if(infile==NULL)
{
char errstr[255];
sprintf(errstr,"ERROR: Colrad infile %s not found\n", fname);
error(errstr);
}
double tmp;
char **tokens;
size_t numtokens;
char line[MAX_LINE_LENGTH];
int linenr=1;
for(i=1; i < local_fd_dim.x-1; i++)
{
for(j=1; j < local_fd_dim.y-1; j++)
{
for(k=1; k < local_fd_dim.z-1; k++)
{
//read data
if (fgets (line, MAX_LINE_LENGTH, infile) == NULL) {
char errstr[255];
sprintf(errstr,"Error Reading colrad-input-file: %s in line %d.\n", fname,linenr);
error(errstr);
}
tokens = strsplit(line, ", \t\n", &numtokens); //strsplit in imd_ttm.char
for(l=0;l<neq;l++)
{
sscanf(tokens[l+3], "%lf", &tmp);
Ith(node.y,l)=tmp;
}
linenr++;
for (l = 0; l < numtokens; l++) {
free(tokens[l]);
}
if (tokens != NULL)
free(tokens);
}
}
}
fclose(infile);
return 0;
}
// ***************************************
// * INTEGRATION STUFF
// *************************************
double inner_integrand_ionization(double x, void *p) // x=E_strich
{
struct my_f_params * params = (struct my_f_params *)p;
Real E_prime=x;
Real ne=params->ne;
Real T=params->T;
Real mu=params->mu;
Real DeltaE = params->DeltaE;
Real E=params->E; //brauche ich nachher für E''=E-E'-DELTAE
Real E_prime_prime=E-E_prime-DeltaE;
Real Pauli_E_prime=1.0-1.0/(1.0+EXPR((E_prime-mu)/BOLTZMAN/T));
Real Pauli_E_prime_prime=1.0-1.0/(1.0+EXPR((E_prime_prime-mu)/BOLTZMAN/T));
Real f=Pauli_E_prime*Pauli_E_prime_prime; //F(E), sigmaderiv und SQRTR(2*eng1/emass) im outer integrand
return f;
}
double inner_integrand_recombination(double x, void *p) // x=incoming elec. energy : ACHTUNG: Für x=0 --> NaN
{
struct my_f_params * params = (struct my_f_params *)p;
Real E_prime=x;
Real ne=params->ne;
Real T=params->T;
Real mu=params->mu;
Real DeltaE = params->DeltaE;
Real E=params->E;
// Anmerkung: E'' und E' sind die enregien der einfallenden elektronen
// während E=DeltaE+E'+E'' energie des sekunddären Elektrons!
// Real E=DeltaE+E_prime+E_prime_prime;
Real E_prime_prime=E-DeltaE-E_prime;
Real fermi_fun_E_prime= 1.0/(1.0+EXPR((E_prime-mu)/BOLTZMAN/T));
Real fermi_fun_E_prime_prime=1.0/(1.0+EXPR((E_prime_prime-mu)/BOLTZMAN/T));
Real f= fermi_fun_E_prime * fermi_fun_E_prime_prime;
return f;
}
double outer_integrand_recombination(double x,void *p)
{
struct my_f_params * params = (struct my_f_params *)p;
Real E=x; //other incoming electron (inneres Integral behandelt E_prime)
//Das sekundäre Elektron hat Energie E,
Real DeltaE = params->DeltaE;
Real ne=params->ne;
Real T=params->T;
Real mu=params->mu;
if(E <= DeltaE)
return 0.0; //Cross section wird =0
Real fermi_fun=1.0/(1.0+EXPR((E-mu)/BOLTZMAN/T));
Real Pauli_E = 1.0-fermi_fun;
struct my_f_params fparams_inner;
fparams_inner.T=T;
fparams_inner.ne=ne;
fparams_inner.mu=mu;
fparams_inner.DeltaE=DeltaE;
fparams_inner.E=E;
gsl_function gslfun_inner;
gslfun_inner.function=&inner_integrand_recombination;
gslfun_inner.params=&fparams_inner;
double integ_inner;
double integ_err;
Real y=E/DeltaE;
// Real sigma_deriv = 4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J / gsl_pow_2(DeltaE) * alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4)
// /2.0/(E-DeltaE);
//konstanten nach double_integral_recombination verfrachtet
Real sigma_deriv = (y-1.0)/POWR(y,2.0)*LOGR(beta_i*1.25*y)/(E-DeltaE);
// gsl_integration_qag(&gslfun_inner, 1e-21, E-DeltaE, 1e-4, 1e-4, integ_meshdim,1,
// winteg_inner, &integ_inner, &integ_err);
// size_t evals;
// gsl_integration_romberg(&gslfun_inner, 1e-21, E-DeltaE, 1e-4, 1e-4, &integ_inner,
// &evals, winteg_rb_inner);
stack_t stack2;
create_stack(&stack2, sizeof(work_gkq));
integ_inner=gkq(inner_integrand_recombination, 1e-21, E-DeltaE, 1e-3, &fparams_inner, stack2);
free(stack2->elements);
free(stack2);
return ((Real) sigma_deriv*Pauli_E*E*integ_inner);
}
Real double_integral_recombination(Real ne,Real T, Real mu, Real DeltaE)
{
// return 0;
gsl_function gslfun_outer;
gslfun_outer.function = &outer_integrand_recombination;
struct my_f_params fparams_outer;
fparams_outer.T=T;
fparams_outer.ne=ne;
fparams_outer.mu=mu;
fparams_outer.DeltaE=DeltaE;
gslfun_outer.params = &fparams_outer;
double integ_outer=0;
double integ_err=0;
//angepasste obere integr. grenze
Real eupper=0.0;
if(mu> 0) eupper=POWR(3*T,0.33) * eV2J + mu +DeltaE;
else eupper=10.0*T/11604* eV2J+ DeltaE;
// integrand_inner=@(eng1,eng2) sigma_deriv(eng1).*SQRTR(2*eng1/emass) ...
// .*F(eng1).*Pauli(eng2).*Pauli(eng1-DeltaE-eng2);
// gsl_integration_qagiu(&gslfun_outer, 0.0, integ_abstol, integ_reltol, integ_meshdim,
// winteg_outer, &integ_outer, &integ_err);
// gsl_integration_qag(&gslfun_outer, DeltaE, eupper, integ_abstol_recomb, integ_reltol, integ_meshdim,1,
// winteg_outer, &integ_outer, &integ_err);
stack_t stack;
create_stack(&stack, sizeof(work_gkq));
integ_outer=gkq(outer_integrand_recombination,DeltaE*1.001, eupper, 1e-3, &fparams_outer,stack);
free(stack->elements);
free(stack);
integ_outer *= 2.0*M_PI*bohr_radius_sq*E_ion_H_sq_J * gsl_pow_2(1.0/DeltaE)*alpha_i; //konstanten aus sigma_deriv herausgezogen
// size_t evals;
// gsl_integration_romberg(&gslfun_outer, DeltaE, muINF, 1e-6, integ_reltol, &integ_outer,
// &evals, winteg_rb_outer);
//NICHT VERGESSEN: RATIO DER STATISTICAL WEIGHTS
integ_outer *= recomb_const/ne/ne; //Später ne^2 entfernen und in ydot entfernen!
// if(integ_outer < 1e-100) integ_outer=0.0;
return MAX((Real) integ_outer,0.0);
}
double fermi_integrand(double x, void *p)
{
struct my_f_params * params = (struct my_f_params *)p;
Real eng=x;
Real ne=params->ne;
Real T=params->T;
Real mu=params->mu;
Real vel=SQRTR(2.0*eng/EMASS);
Real fermi_fun=1.0/(1.0+EXPR((eng-mu)/BOLTZMAN/T));
Real F=double_emass_pow_3_2/2.0/ne/hbar_cub/pi_sq*SQRTR(eng)*fermi_fun; // DOS * f_fermi
return F;
}
Real eval_fermi_integrand(Real ne,Real T, Real mu)
{
struct my_f_params fparams_fermi;
fparams_fermi.T=T;
fparams_fermi.ne=ne;
fparams_fermi.mu=mu;
gsl_function fun;
fun.function=&fermi_integrand;
fun.params=&fparams_fermi;
double integ_err=0;
double integ_result=0;
gsl_error_handler_t *old_error_handler=gsl_set_error_handler_off ();
// int code= gsl_integration_qags (&fun, mu, muINF, integ_abstol, integ_reltol, integ_meshdim,
// winteg_fermi, &integ_result, &integ_err);
// int code=gsl_integration_qagiu(&fun, mu, integ_abstol, integ_reltol, integ_meshdim,
// winteg_fermi, &integ_result, &integ_err);
int code= gsl_integration_qag(&fun, 0, 3.0*muINF, integ_abstol, integ_reltol, integ_meshdim,1,
winteg_fermi, &integ_result, &integ_err);
gsl_set_error_handler(old_error_handler); //reset the error handler
return (code==GSL_SUCCESS ? (Real) integ_result : -1); // RHS abbrechen -> neuer versuch
//return integ_result;
}
Real eval_excitation_integral(Real ne,Real T,Real mu, Real DeltaE, int allowed)
{
gsl_function fun;
fun.function = &integrand_excitation;
struct my_f_params fparams_exc;
fparams_exc.T=T;
fparams_exc.ne=ne;
fparams_exc.mu=mu;
fparams_exc.DeltaE=DeltaE;
fparams_exc.allowed=allowed;
fun.params = &fparams_exc;
double integ_result=0;
double integ_err=0;
double eupper=0.0;
if(mu> 0) eupper=POWR(3*T,0.33) * eV2J + mu +DeltaE; //entartet
else eupper=10.0*T/11604* eV2J+ DeltaE; //nicht-entartet
// integ_result = integral_simpson(&integrand_excitation, DeltaE, 20*DeltaE, 5000, &fparams_exc);
// gsl_error_handler_t *old_error_handler=gsl_set_error_handler_off ();
// // int code= gsl_integration_qags (&fun, DeltaE, muINF, integ_abstol, integ_reltol, integ_meshdim,
// // winteg_exc, &integ_result, &integ_err);
// //Abstol ist zwar nicht streng aber scheint ausreichend...ergebnisse sind genauso gut
// int code= gsl_integration_qag(&fun, (double) DeltaE, (double) eupper, 1e-6, (double) integ_reltol, integ_meshdim,1,
// winteg_exc, &integ_result, &integ_err);
// gsl_set_error_handler(old_error_handler); //reset the error handler
// if (code != GSL_SUCCESS)
// {
// //print integrand
// int i=0;
// Real dx=(muINF-DeltaE)/250;
// for(i=0;i<250;i++)
// {
// printf("x:%.4e,T:%f, ne:%.2e, dE:%.2e, integ:%.4e\n",
// dx*i,fparams_exc.T, fparams_exc.ne, fparams_exc.DeltaE, integrand_excitation_debug(dx*i,&fparams_exc));
// }
// error("ERROR in eval_excitation_integral\n");
// }
stack_t stack;
create_stack(&stack, sizeof(work_gkq));
integ_result=gkq(integrand_excitation, DeltaE*1.001, eupper, 1e-3, &fparams_exc,stack);
free(stack->elements);
free(stack);
return MAX((Real) integ_result,0.0);
}
Real eval_dexcitation_integral(Real ne,Real T,Real mu, Real DeltaE, int allowed)
{
gsl_function fun;
fun.function = &integrand_deexcitation;
struct my_f_params fparams_exc;
fparams_exc.T=T;
fparams_exc.ne=ne;
fparams_exc.mu=mu;
fparams_exc.DeltaE=DeltaE;
fparams_exc.allowed=allowed;
fun.params = &fparams_exc;
double integ_result=0;
double integ_err=0;
double eupper=0.0;
if(mu> 0) eupper=POWR(3*T,0.33) * eV2J + mu +DeltaE; //entartet
else eupper=10.0*T/11604* eV2J+ DeltaE; //nicht-entartet
// gsl_integration_qagiu(&fun, DeltaE, integ_abstol, integ_reltol, integ_meshdim,
// winteg_exc, &integ_result, &integ_err);
//Wird sonst immer zu null
// gsl_integration_qags (&fun, DeltaE, muINF, integ_abstol, integ_reltol, integ_meshdim,
// winteg_exc, &integ_result, &integ_err);
//Variante Aslan: effektives chem.pot und integriere wieder excitation_integrand statt de-exc.integrand
fparams_exc.mu=mu+DeltaE;
fun.function = &integrand_excitation;
// gsl_integration_qags (&fun, DeltaE, muINF, integ_abstol, integ_reltol, integ_meshdim,
// winteg_exc, &integ_result, &integ_err);
// gsl_integration_qag(&fun, DeltaE, eupper, 1e-6, integ_reltol, integ_meshdim,1,
// winteg_exc, &integ_result, &integ_err);
stack_t stack;
create_stack(&stack, sizeof(work_gkq));
integ_result=gkq(integrand_excitation, DeltaE*1.001, eupper, 1e-3, &fparams_exc,stack);
free(stack->elements);
free(stack);
return MAX((Real) integ_result,0.0);
}
double integrand_deexcitation(double x,void *p)
{
struct my_f_params * params = (struct my_f_params *)p;
Real eng=x;
Real DeltaE = params->DeltaE;
Real ne=params->ne;
Real T=params->T;
Real mu=params->mu;
int allowed=params->allowed;
if(eng <= DeltaE)
return 0.0;
Real vel=SQRTR(2.0*eng/EMASS);
// if(vel< 1e-100) return 0;
Real fermi_fun=1.0/(1.0+EXPR((eng-DeltaE-mu)/BOLTZMAN/T)); //mod
// if(fermi_fun < 1e-100) return 0;
Real sigma=0.0;
Real y=eng/DeltaE;
Real Pauli=1.0-1.0/(1.0+EXPR((eng+mu)/BOLTZMAN/T)); //mod
// if(Pauli<1e-100) return 0;
if(allowed==1)
sigma=4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J* gsl_pow_2(1.0/DeltaE)*alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4);
else
sigma=4.0*M_PI*bohr_radius_sq*alpha_i*(y-1.0)/gsl_pow_2(y);
// Real F=double_emass_pow_3_2/2.0/ne/hbar_cub/pi_sq*SQRTR(eng)*fermi_fun*SQRTR(eng/(eng-DeltaE)); //ACHTUNG: Letzter Term --> divergent
Real F=1.062234185782204e+56/ne*SQRTR(eng/(eng-DeltaE))*fermi_fun;
return vel*sigma*F*Pauli;
}
double integrand_excitation(double x,void *p)
{
struct my_f_params * params = (struct my_f_params *)p;
Real eng=x;
Real DeltaE = params->DeltaE;
Real ne=params->ne;
Real T=params->T;
Real mu=params->mu;
int allowed=params->allowed;
if(eng <= DeltaE)
return 0.0; //siehe flychk manual
Real vel=SQRTR(2.0*eng/EMASS);
Real fermi_fun=1.0/(1.0+EXPR((eng-mu)/BOLTZMAN/T));
// if(fermi_fun < 1e-100) return 0;
Real sigma=0.0;
Real y=eng/DeltaE;
Real Pauli=1.0-1.0/(1.0+EXPR((eng-DeltaE+mu)/BOLTZMAN/T));
// if(Pauli < 1e-100) return 0;
if(allowed==1)
sigma=4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J* gsl_pow_2(1.0/DeltaE)*alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4);
else
sigma=4.0*M_PI*bohr_radius_sq*alpha_i*(y-1.0)/gsl_pow_2(y);
// Real F=double_emass_pow_3_2/2.0/ne/hbar_cub/pi_sq*SQRTR(eng)*fermi_fun;
Real F=1.062234185782204e+56/ne*SQRTR(eng)*fermi_fun;
// printf("F:%.4e, Pauli:%.4e, eng:%.4e, sigma:%.4e, y:%.4e, de:%.4e,ne:%.4e,T:%.4e\n",
// F, Pauli, eng, sigma, y, DeltaE, ne, T);
return vel*sigma*F*Pauli;
}
// *** EXAKTE KOPIE MIT ZUSÄTZL. PRINTF ****
double integrand_excitation_debug(double x,void *p)
{
struct my_f_params * params = (struct my_f_params *)p;
Real eng=x;
Real DeltaE = params->DeltaE;
Real ne=params->ne;
Real T=params->T;
Real mu=params->mu;
int allowed=params->allowed;
if(eng <= DeltaE)
return 0.0; //siehe flychk manual
Real vel=SQRTR(2.0*eng/EMASS);
Real fermi_fun=1.0/(1.0+EXPR((eng-mu)/BOLTZMAN/T));
// if(fermi_fun < 1e-100) return 0;
Real sigma=0.0;
Real y=eng/DeltaE;
Real Pauli=1.0-1.0/(1.0+EXPR((eng-DeltaE+mu)/BOLTZMAN/T));
// if(Pauli < 1e-100) return 0;
if(allowed==1)
sigma=4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J* gsl_pow_2(1.0/DeltaE)*alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4);
else
sigma=4.0*M_PI*bohr_radius_sq*alpha_i*(y-1.0)/gsl_pow_2(y);
// Real F=double_emass_pow_3_2/2.0/ne/hbar_cub/pi_sq*SQRTR(eng)*fermi_fun;
Real F=1.062234185782204e+56/ne*SQRTR(eng)*fermi_fun;
printf("F:%.4e, Pauli:%.4e, eng:%.4e, sigma:%.4e, y:%.4e, de:%.4e,ne:%.4e,T:%.4e,sqrteng:%.4e,fermi_fun:%.4e\n",
F, Pauli, eng, sigma, y, DeltaE, ne, T, SQRTR(eng),fermi_fun);
return vel*sigma*F*Pauli;
}
double outer_integrand_ionization(double x,void *p)
{
struct my_f_params * params = (struct my_f_params *)p;
Real eng=x;
Real DeltaE = params->DeltaE;
Real ne=params->ne;
Real T=params->T;
Real mu=params->mu;
Real fermi_fun=1.0/(1.0+EXPR((eng-mu)/BOLTZMAN/T));
// if(fermi_fun < 1e-100) return 0;
if(eng <= DeltaE)
return 0.0; //Cross section wird zu 0
Real y=eng/DeltaE;
// Real sigma_deriv = 4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J * gsl_pow_2(1.0/DeltaE)*alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4)
// /2.0/(eng-DeltaE);
//sigma_deriv: konstanten rausgezogen und nach double_integral_ionization verfrachtet
Real sigma_deriv = (y-1.0)/POWR(y,2.0)*LOGR(beta_i*1.25*y)/(eng-DeltaE);
struct my_f_params fparams_inner;
fparams_inner.T=T;
fparams_inner.ne=ne;
fparams_inner.mu=mu;
fparams_inner.DeltaE=DeltaE;
fparams_inner.E=eng;
gsl_function gslfun_inner;
gslfun_inner.function=&inner_integrand_ionization;
gslfun_inner.params=&fparams_inner;
double integ_inner=0.0;
double integ_err;
gsl_integration_qag(&gslfun_inner, 1e-21, eng-DeltaE, 1e-20, 1e-4, integ_meshdim,1,
winteg_inner, &integ_inner, &integ_err);
// gsl_integration_qags(&gslfun_inner, 1e-21, eng-DeltaE, 1e-20, 1e-4, integ_meshdim,
// winteg_inner, &integ_inner, &integ_err);
// size_t evals;
// gsl_integration_romberg(&gslfun_inner, 1e-21, eng-DeltaE, 1e-4, 1e-4, &integ_inner,
// &evals, winteg_rb_inner);
stack_t stack2;
create_stack(&stack2, sizeof(work_gkq));
double res2=0.0;
terminate_gkq=0;
res2=gkq(inner_integrand_ionization2, 1e-21, eng-DeltaE, 1e-4, &fparams_inner, stack2);
work_gkq wtmp;
free(stack2->elements);
free(stack2);//hatte ich vorher vergessen
// double res2=gkq_serial(inner_integrand_ionization2, 1e-21, eng-DeltaE, 1e-4, &fparams_inner);
if(myid==1 && (res2 >0))
printf("gsl:%.4e, gkq:%.4e\n", integ_inner, res2);
return ((Real) eng*fermi_fun*sigma_deriv*integ_inner);
}
double outer_integrand_ionization2(double x, struct my_f_params* p)
{
Real eng=x;
Real DeltaE=p->DeltaE;
Real T=p->T;
Real ne=p->ne;
Real mu=p->mu;
struct my_f_params fparams_inner;
fparams_inner.T=T;
fparams_inner.ne=ne;
fparams_inner.mu=mu;
fparams_inner.DeltaE=DeltaE;
fparams_inner.E=eng;
Real fermi_fun=1.0/(1.0+EXPR((eng-mu)/BOLTZMAN/T));
// if(fermi_fun < 1e-100) return 0;
if(eng <= DeltaE)
return 0.0; //Cross section wird zu 0
Real y=eng/DeltaE;
// Real sigma_deriv = 4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J * gsl_pow_2(1.0/DeltaE)*alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4)
// /2.0/(eng-DeltaE);
//sigma_deriv: konstanten rausgezogen und nach double_integral_ionization verfrachtet
Real sigma_deriv = (y-1.0)/POWR(y,2.0)*LOGR(beta_i*1.25*y)/(eng-DeltaE);
terminate_gkq=0;
stack_t stack2;
create_stack(&stack2, sizeof(work_gkq));
double integ_inner=gkq(inner_integrand_ionization2, 1e-21, eng-DeltaE, 1e-3, &fparams_inner, stack2);
free(stack2->elements);
free(stack2);
return ((Real) eng*fermi_fun*sigma_deriv*integ_inner);
}
Real double_integral_ionization(Real ne,Real T, Real mu, Real DeltaE)
{
// return 0;
gsl_function gslfun_outer;
gslfun_outer.function = &outer_integrand_ionization;
struct my_f_params fparams_outer;
fparams_outer.T=T;
fparams_outer.ne=ne;
fparams_outer.mu=mu;
fparams_outer.DeltaE=DeltaE;
gslfun_outer.params = &fparams_outer;
double integ_outer=0;
double integ_err=0;
double eupper=0.0;
if(mu> 0) eupper=POWR(3*T,0.33) * eV2J + mu +DeltaE; //entartet
else eupper=10.0*T/11604* eV2J+ DeltaE; //nicht-entartet
gsl_integration_qag(&gslfun_outer, DeltaE*1.001, eupper, 1e-6, 1e-4, integ_meshdim,1,
winteg_outer, &integ_outer, &integ_err);
// serial simpson rule
// integ_outer = integral_simpson(&outer_integrand_ionization, DeltaE*1.001, eupper, 1000, &fparams_outer);
// *****************************************************
// if(integ_outer<MINRATE) integ_outer=0.0;
integ_outer *= 2.0*M_PI*bohr_radius_sq*E_ion_H_sq_J * gsl_pow_2(1.0/DeltaE)*alpha_i; //konstanten aus sigma_deriv herausgezogen
integ_outer *= ioniz_const / ne; //ACHTUNG: Später ne entfernenu und in ydot nicht mehr multiplizieren!
// if(steps> 1)
// if(myid==1 && integ_outer > 0)
// {
// if(DeltaE*J2eV > 5.9062 && DeltaE*J2eV < 5.9064) // && T> 1.9826e+03 && T > 1.9828e+03 && mu >1.6238e-18 && mu <1.6240e-18)
// printf("AFTER: dE:%.4e, T:%.6e, mu:%.15e, ne:%.15e, integ:%.4e\n",DeltaE*J2eV,T,mu,ne,integ_outer);
// }
//WTF???
// dE:5.9063e+00, T:1.208983e+03, mu:1.624114145844772e-18, ne:1.465920522460179e+29, integ:8.1974e-105
// dE:5.9063e+00, T:1.208983e+03, mu:1.624114145844772e-18, ne:1.465920522460179e+29, integ:2.5497e-104
// dE:5.9063e+00, T:1.208983e+03, mu:1.624114145844772e-18, ne:1.465920522460179e+29, integ:1.6998e-104
return MAX((Real) integ_outer,0.0);
}
Real double_integral_ionization2(Real ne,Real T, Real mu, Real DeltaE)
{
// return 0;
struct my_f_params fparams_outer;
fparams_outer.T=T;
fparams_outer.ne=ne;
fparams_outer.mu=mu;
fparams_outer.DeltaE=DeltaE;
terminate_gkq=0;
double integ_outer=0;
double integ_err=0;
double eupper=0.0;
if(mu> 0) eupper=POWR(3*T,0.33) * eV2J + mu +DeltaE; //entartet
else eupper=10.0*T/11604* eV2J+ DeltaE; //nicht-entartet
stack_t stack;
create_stack(&stack, sizeof(work_gkq));
integ_outer=gkq(outer_integrand_ionization2, DeltaE*1.001, eupper, 1e-3, &fparams_outer,stack);
free(stack->elements);
free(stack);
// *****************************************************
// if(integ_outer<MINRATE) integ_outer=0.0;
integ_outer *= 2.0*M_PI*bohr_radius_sq*E_ion_H_sq_J * gsl_pow_2(1.0/DeltaE)*alpha_i; //konstanten aus sigma_deriv herausgezogen
integ_outer *= ioniz_const / ne; //ACHTUNG: Später ne entfernenu und in ydot nicht mehr multiplizieren!
return MAX((Real) integ_outer,0.0);
}
double inner_integrand_ionization2(double x, struct my_f_params* p) // x=E_strich
{
//struct my_f_params * params = (struct my_f_params *)p;
Real E_prime=x;
Real ne=p->ne;
Real T=p->T;
Real mu=p->mu;
Real DeltaE = p->DeltaE;
Real E=p->E; //brauche ich nachher für E''=E-E'-DELTAE
Real E_prime_prime=E-E_prime-DeltaE;
Real Pauli_E_prime=1.0-1.0/(1.0+EXPR((E_prime-mu)/BOLTZMAN/T));
Real Pauli_E_prime_prime=1.0-1.0/(1.0+EXPR((E_prime_prime-mu)/BOLTZMAN/T));
Real f=Pauli_E_prime*Pauli_E_prime_prime; //F(E), sigmaderiv und SQRTR(2*eng1/emass) im outer integrand
return f;
} | {
"alphanum_fraction": 0.5743658657,
"avg_line_length": 30.0729001585,
"ext": "c",
"hexsha": "82c1925cbec8da00de331bac9333e3681357b883",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "fmqeisfeld/IMD",
"max_forks_repo_path": "imd_colrad.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "fmqeisfeld/IMD",
"max_issues_repo_path": "imd_colrad.c",
"max_line_length": 177,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "fmqeisfeld/IMD",
"max_stars_repo_path": "imd_colrad.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-08T07:49:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-30T08:23:34.000Z",
"num_tokens": 42728,
"size": 113856
} |
/* multimin/gsl_multimin.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Fabrice Rossi
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Modified by Tuomo Keskitalo to include fminimizer and
Nelder Mead related lines */
#ifndef __GSL_MULTIMIN_H__
#define __GSL_MULTIMIN_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_min.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Definition of an arbitrary real-valued function with gsl_vector input and */
/* parameters */
struct gsl_multimin_function_struct
{
double (* f) (const gsl_vector * x, void * params);
size_t n;
void * params;
};
typedef struct gsl_multimin_function_struct gsl_multimin_function;
#define GSL_MULTIMIN_FN_EVAL(F,x) (*((F)->f))(x,(F)->params)
/* Definition of an arbitrary differentiable real-valued function */
/* with gsl_vector input and parameters */
struct gsl_multimin_function_fdf_struct
{
double (* f) (const gsl_vector * x, void * params);
void (* df) (const gsl_vector * x, void * params,gsl_vector * df);
void (* fdf) (const gsl_vector * x, void * params,double *f,gsl_vector * df);
size_t n;
void * params;
};
typedef struct gsl_multimin_function_fdf_struct gsl_multimin_function_fdf;
#define GSL_MULTIMIN_FN_EVAL_F(F,x) (*((F)->f))(x,(F)->params)
#define GSL_MULTIMIN_FN_EVAL_DF(F,x,g) (*((F)->df))(x,(F)->params,(g))
#define GSL_MULTIMIN_FN_EVAL_F_DF(F,x,y,g) (*((F)->fdf))(x,(F)->params,(y),(g))
int gsl_multimin_diff (const gsl_multimin_function * f,
const gsl_vector * x, gsl_vector * g);
/* minimization of non-differentiable functions */
typedef struct
{
const char *name;
size_t size;
int (*alloc) (void *state, size_t n);
int (*set) (void *state, gsl_multimin_function * f,
const gsl_vector * x,
double * size,
const gsl_vector * step_size);
int (*iterate) (void *state, gsl_multimin_function * f,
gsl_vector * x,
double * size,
double * fval);
void (*free) (void *state);
}
gsl_multimin_fminimizer_type;
typedef struct
{
/* multi dimensional part */
const gsl_multimin_fminimizer_type *type;
gsl_multimin_function *f;
double fval;
gsl_vector * x;
double size;
void *state;
}
gsl_multimin_fminimizer;
gsl_multimin_fminimizer *
gsl_multimin_fminimizer_alloc(const gsl_multimin_fminimizer_type *T,
size_t n);
int
gsl_multimin_fminimizer_set (gsl_multimin_fminimizer * s,
gsl_multimin_function * f,
const gsl_vector * x,
const gsl_vector * step_size);
void
gsl_multimin_fminimizer_free(gsl_multimin_fminimizer *s);
const char *
gsl_multimin_fminimizer_name (const gsl_multimin_fminimizer * s);
int
gsl_multimin_fminimizer_iterate(gsl_multimin_fminimizer *s);
gsl_vector *
gsl_multimin_fminimizer_x (const gsl_multimin_fminimizer * s);
double
gsl_multimin_fminimizer_minimum (const gsl_multimin_fminimizer * s);
double
gsl_multimin_fminimizer_size (const gsl_multimin_fminimizer * s);
/* Convergence test functions */
int
gsl_multimin_test_gradient(const gsl_vector * g,double epsabs);
int
gsl_multimin_test_size(const double size ,double epsabs);
/* minimisation of differentiable functions */
typedef struct
{
const char *name;
size_t size;
int (*alloc) (void *state, size_t n);
int (*set) (void *state, gsl_multimin_function_fdf * fdf,
const gsl_vector * x, double * f,
gsl_vector * gradient, double step_size, double tol);
int (*iterate) (void *state,gsl_multimin_function_fdf * fdf,
gsl_vector * x, double * f,
gsl_vector * gradient, gsl_vector * dx);
int (*restart) (void *state);
void (*free) (void *state);
}
gsl_multimin_fdfminimizer_type;
typedef struct
{
/* multi dimensional part */
const gsl_multimin_fdfminimizer_type *type;
gsl_multimin_function_fdf *fdf;
double f;
gsl_vector * x;
gsl_vector * gradient;
gsl_vector * dx;
void *state;
}
gsl_multimin_fdfminimizer;
gsl_multimin_fdfminimizer *
gsl_multimin_fdfminimizer_alloc(const gsl_multimin_fdfminimizer_type *T,
size_t n);
int
gsl_multimin_fdfminimizer_set (gsl_multimin_fdfminimizer * s,
gsl_multimin_function_fdf *fdf,
const gsl_vector * x,
double step_size, double tol);
void
gsl_multimin_fdfminimizer_free(gsl_multimin_fdfminimizer *s);
const char *
gsl_multimin_fdfminimizer_name (const gsl_multimin_fdfminimizer * s);
int
gsl_multimin_fdfminimizer_iterate(gsl_multimin_fdfminimizer *s);
int
gsl_multimin_fdfminimizer_restart(gsl_multimin_fdfminimizer *s);
gsl_vector *
gsl_multimin_fdfminimizer_x (gsl_multimin_fdfminimizer * s);
gsl_vector *
gsl_multimin_fdfminimizer_dx (gsl_multimin_fdfminimizer * s);
gsl_vector *
gsl_multimin_fdfminimizer_gradient (gsl_multimin_fdfminimizer * s);
double
gsl_multimin_fdfminimizer_minimum (gsl_multimin_fdfminimizer * s);
GSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_steepest_descent;
GSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_conjugate_pr;
GSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_conjugate_fr;
GSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_vector_bfgs;
GSL_VAR const gsl_multimin_fdfminimizer_type *gsl_multimin_fdfminimizer_vector_bfgs2;
GSL_VAR const gsl_multimin_fminimizer_type *gsl_multimin_fminimizer_nmsimplex;
__END_DECLS
#endif /* __GSL_MULTIMIN_H__ */
| {
"alphanum_fraction": 0.7225669744,
"avg_line_length": 29.2345132743,
"ext": "h",
"hexsha": "53c342da3b5db54c12029f42070101bfda9a414f",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/multimin/gsl_multimin.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/multimin/gsl_multimin.h",
"max_line_length": 89,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/multimin/gsl_multimin.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 1771,
"size": 6607
} |
/*
Excited States software: KGS
Contributors: See CONTRIBUTORS.txt
Contact: kgs-contact@simtk.org
Copyright (C) 2009-2017 Stanford University
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
This entire text, including the above copyright notice and this permission notice
shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#ifndef COORDINATE_H
#define COORDINATE_H
#include <string>
#include "math3d/primitives.h"
#include <gsl/gsl_vector.h>
class Coordinate : public Math3D::Vector3 {
public:
Coordinate();
Coordinate(double x,double y,double z);
~Coordinate();
std::string tostring() const;
double distanceTo (Coordinate& other) const; // Euclidean distance between self and other
bool isWithinSphere (Coordinate& center, double radius) const;
double getAngle (Coordinate& left, Coordinate& right) const; // Angle in degrees between left-this-right
Coordinate mid_point (Coordinate& other) const;
Coordinate crossproduct (Coordinate& other) const;
static void copyToGslVector (Math3D::Vector3 v, gsl_vector* gslv);
static double getPlanarAngle (Coordinate& c1, Coordinate& c2, Coordinate& c3, Coordinate& c4); // Angle between plane c123 and plane c234
};
#endif
| {
"alphanum_fraction": 0.7870905588,
"avg_line_length": 37.7454545455,
"ext": "h",
"hexsha": "4a1bbe75615eea0ec1dcb0c0b00a3574bb8024eb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_forks_repo_path": "src/core/Coordinate.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_issues_repo_issues_event_max_datetime": "2021-02-06T16:06:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-26T19:54:38.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_issues_repo_path": "src/core/Coordinate.h",
"max_line_length": 138,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "117c4a3d39ec6285eccc1d3b8e5de9a21db21ec9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "XiyuChenFAU/kgs_vibration_entropy",
"max_stars_repo_path": "src/core/Coordinate.h",
"max_stars_repo_stars_event_max_datetime": "2020-05-23T18:26:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-23T18:26:14.000Z",
"num_tokens": 470,
"size": 2076
} |
/*System includes*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
/*GSL includes*/
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_statistics_double.h>
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_multimin.h>
#include <pthread.h>
/*User includes*/
#include "../Lib/FileUtils.h"
#include "../Lib/MatrixUtils.h"
#include "MetroIG.h"
static char *usage[] = {"MetroIG - Fits the compound Poisson Inverse Gaussian\n",
"Required parameters:\n",
" -out filestub output file stub\n",
" -in filename parameter file \n",
"Optional:\n",
" -s integer generate integer MCMC samples\n",
" -seed long seed random number generator\n",
" -sigmaA float std. dev. of alpha prop. distn\n",
" -sigmaB float ... beta \n",
" -sigmaS float ... S \n",
" -v verbose\n"};
static int nLines = 11;
static int verbose = FALSE;
int main(int argc, char* argv[])
{
int i = 0, nNA = 0;
t_Params tParams;
t_Data tData;
gsl_vector* ptX = gsl_vector_alloc(3); /*parameter estimates*/
t_MetroInit atMetroInit[3];
gsl_rng_env_setup();
gsl_set_error_handler_off();
/*get command line params*/
getCommandLineParams(&tParams, argc, argv);
/*read in abundance distribution*/
readAbundanceData(tParams.szInputFile, &tData);
/*set initial estimates for parameters*/
gsl_vector_set(ptX, 0, INIT_A);
gsl_vector_set(ptX, 1, INIT_B);
gsl_vector_set(ptX, 2, tData.nL*2);
printf("D = %d L = %d Chao = %f\n",tData.nL, tData.nJ, chao(&tData));
minimiseSimplex(ptX, 3, (void*) &tData, &nLogLikelihood);
outputResults(ptX, &tData);
if(tParams.nIter > 0){
mcmc(&tParams, &tData, ptX);
}
/*free up allocated memory*/
gsl_vector_free(ptX);
freeAbundanceData(&tData);
exit(EXIT_SUCCESS);
}
void writeUsage(FILE* ofp)
{
int i = 0;
char *line;
for(i = 0; i < nLines; i++){
line = usage[i];
fputs(line,ofp);
}
}
char *extractParameter(int argc, char **argv, char *param,int when)
{
int i = 0;
while((i < argc) && (strcmp(param,argv[i]))){
i++;
}
if(i < argc - 1){
return(argv[i + 1]);
}
if((i == argc - 1) && (when == OPTION)){
return "";
}
if(when == ALWAYS){
fprintf(stdout,"Can't find asked option %s\n",param);
}
return (char *) NULL;
}
void getCommandLineParams(t_Params *ptParams,int argc,char *argv[])
{
char *szTemp = NULL;
char *cError = NULL;
/*get parameter file name*/
ptParams->szInputFile = extractParameter(argc,argv, INPUT_FILE,ALWAYS);
if(ptParams->szInputFile == NULL)
goto error;
/*get out file stub*/
ptParams->szOutFileStub = extractParameter(argc,argv,OUT_FILE_STUB,ALWAYS);
if(ptParams->szOutFileStub == NULL)
goto error;
/*get out file stub*/
szTemp = extractParameter(argc,argv,SEED,OPTION);
if(szTemp != NULL){
ptParams->lSeed = strtol(szTemp,&cError,10);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->lSeed = 0;
}
/*verbosity*/
szTemp = extractParameter(argc, argv, VERBOSE, OPTION);
if(szTemp != NULL){
verbose = TRUE;
}
szTemp = extractParameter(argc,argv,SAMPLE,OPTION);
if(szTemp != NULL){
ptParams->nIter = strtol(szTemp,&cError,10);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->nIter = 0;
}
szTemp = extractParameter(argc,argv,SIGMA_A,OPTION);
if(szTemp != NULL){
ptParams->dSigmaA = strtod(szTemp,&cError);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->dSigmaA = DEF_SIGMA;
}
szTemp = extractParameter(argc,argv,SIGMA_B,OPTION);
if(szTemp != NULL){
ptParams->dSigmaB = strtod(szTemp,&cError);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->dSigmaB = DEF_SIGMA;
}
szTemp = extractParameter(argc,argv,SIGMA_S,OPTION);
if(szTemp != NULL){
ptParams->dSigmaS = strtod(szTemp,&cError);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->dSigmaS = DEF_SIGMA_S;
}
return;
error:
writeUsage(stdout);
exit(EXIT_FAILURE);
}
void readAbundanceData(const char *szFile, t_Data *ptData)
{
int **aanAbund = NULL;
int i = 0, nNA = 0, nA = 0, nC = 0;
int nL = 0, nJ = 0;
char szLine[MAX_LINE_LENGTH];
FILE* ifp = NULL;
ifp = fopen(szFile, "r");
if(ifp){
char* szTok = NULL;
char* pcError = NULL;
fgets(szLine, MAX_LINE_LENGTH, ifp);
szTok = strtok(szLine, DELIM);
nNA = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
aanAbund = (int **) malloc(nNA*sizeof(int*));
for(i = 0; i < nNA; i++){
aanAbund[i] = (int *) malloc(sizeof(int)*2);
fgets(szLine, MAX_LINE_LENGTH, ifp);
szTok = strtok(szLine, DELIM);
nA = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
szTok = strtok(NULL, DELIM);
nC = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
nL += nC;
nJ += nC*nA;
aanAbund[i][0] = nA;
aanAbund[i][1] = nC;
}
}
else{
fprintf(stderr, "Failed to open abundance data file %s aborting\n", szFile);
fflush(stderr);
exit(EXIT_FAILURE);
}
ptData->nJ = nJ;
ptData->nL = nL;
ptData->aanAbund = aanAbund;
ptData->nNA = nNA;
return;
formatError:
fprintf(stderr, "Incorrectly formatted abundance data file\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
int compare_doubles(const void* a, const void* b)
{
double* arg1 = (double *) a;
double* arg2 = (double *) b;
if( *arg1 < *arg2 ) return -1;
else if( *arg1 == *arg2 ) return 0;
else return 1;
}
double chao(t_Data *ptData)
{
double n1 = 0.0, n2 = 0.0;
int **aanAbund = ptData->aanAbund;
if(aanAbund[0][0] == 1 && aanAbund[1][0] == 2){
n1 = (double) aanAbund[0][1]; n2 = (double) aanAbund[1][1];
return ((double) ptData->nL) + 0.5*((n1*n1)/n2);
}
else{
return -1.0;
}
}
double fX(double x, double dA, double dB, double dNDash)
{
double dTemp1 = (dA*(x - dB)*(x - dB))/x;
return log(x) - (1.0/dNDash)*(x + dTemp1);
}
double f2X(double x, double dA, double dB, double dNDash)
{
double dRet = 0.0, dTemp = 2.0*dA*dB*dB;
dRet = (1.0/(x*x))*(1.0 + (1.0/dNDash)*(dTemp/x));
return -dRet;
}
double sd(int n, double dAlpha, double dBeta)
{
double dGamma = -0.5;
double dA = 0.5*(-1.0 + sqrt(1.0 + (dAlpha*dAlpha)/(dBeta*dBeta)));
double dN = (double) n, dNDash = dN + dGamma - 1.0, dRN = 1.0/dN;
double dTemp1 = (0.5*dN)/(1.0 + dA), dTemp2 = 4.0*dRN*dRN*(1.0 + dA)*dA*dBeta*dBeta;
double dXStar = dTemp1*(1.0 + sqrt(1.0 + dTemp2));
double dFX = fX(dXStar, dA, dBeta, dNDash);
double d2FX = -dNDash*f2X(dXStar, dA, dBeta, dNDash);
double dLogK = 0.0, dGamma1 = dGamma;
if(dGamma1 < 0.0){
dGamma1 *= -1.0;
}
dLogK = gsl_sf_bessel_lnKnu(dGamma1,2.0*dA*dBeta);
return -2.0*dA*dBeta -log(2.0) -dLogK -dGamma*log(dBeta) + dNDash*dFX + 0.5*log(2.0*M_PI) - 0.5*log(d2FX);
}
int bessel(double* pdResult, int n, double dAlpha, double dBeta)
{
double dGamma = -0.5;
double dResult = 0.0;
double dOmega = 0.0, dGamma2 = 0.0;
double dLogK1 = 0.0, dLogK2 = 0.0;
double dN = (double) n, dNu = dGamma + dN;
double dTemp1 = 0.0;
if(dNu < 0.0){
dNu = -dNu;
}
if(dGamma < 0.0){
dGamma2 = -dGamma;
}
else{
dGamma2 = dGamma;
}
dOmega = sqrt(dBeta*dBeta + dAlpha*dAlpha) - dBeta;
dLogK2 = gsl_sf_bessel_lnKnu(dNu, dAlpha);
if(!gsl_finite(dLogK2)){
if(dAlpha < 0.1*sqrt(dNu + 1.0)){
//printf("l ");
dLogK2 = gsl_sf_lngamma(dNu) + (dNu - 1.0)*log(2.0) - dNu*log(dAlpha);
}
else{
//printf("sd ");
(*pdResult) = dResult;
return FALSE;
}
}
dLogK1 = dGamma*log(dOmega/dAlpha) -gsl_sf_bessel_lnKnu(dGamma2,dOmega);
dTemp1 = log((dBeta*dOmega)/dAlpha);
dResult = dN*dTemp1 + dLogK2 + dLogK1;
(*pdResult) = dResult;
return TRUE;
}
double logLikelihood(int n, double dAlpha, double dBeta)
{
double dLogFacN = 0.0;
int status = 0;
double dRet = 0.0;
if(n < 50){
dLogFacN = gsl_sf_fact(n);
dLogFacN = log(dLogFacN);
}
else{
dLogFacN = gsl_sf_lngamma(((double) n) + 1.0);
}
status = bessel(&dRet,n, dAlpha,dBeta);
if(status == FALSE){
dRet = sd(n, dAlpha,dBeta);
}
return dRet - dLogFacN;
}
double nLogLikelihood(const gsl_vector * x, void * params)
{
double dAlpha = gsl_vector_get(x,0), dBeta = gsl_vector_get(x,1);
int nS = (int) floor(gsl_vector_get(x, 2));
t_Data *ptData = (t_Data *) params;
int i = 0;
double dLogNot0 = 0.0, dLogL = 0.0;
double dLog0 = 0.0, dLog1 = 0.0, dLog2 = 0.0, dLog3 = 0.0;
if(dAlpha <= 0.0 || dBeta <= 0.0){
return PENALTY;
}
for(i = 0; i < ptData->nNA; i++){
double dLogP = 0.0;
int nA = ptData->aanAbund[i][0];
dLogP = logLikelihood(nA, dAlpha, dBeta);
dLogL += ((double) ptData->aanAbund[i][1])*dLogP;
dLogL -= gsl_sf_lnfact(ptData->aanAbund[i][1]);
}
dLog0 = logLikelihood(0, dAlpha, dBeta);
dLog1 = (nS - ptData->nL)*dLog0;
dLog2 = - gsl_sf_lnfact(nS - ptData->nL);
dLog3 = gsl_sf_lnfact(nS);
dLogL += dLog1 + dLog2 + dLog3;
/*return*/
return -dLogL;
}
double negLogLikelihood(double dAlpha, double dBeta, int nS, void * params)
{
t_Data *ptData = (t_Data *) params;
int i = 0;
double dLogNot0 = 0.0, dLogL = 0.0;
double dLog0 = 0.0, dLog1 = 0.0, dLog2 = 0.0, dLog3 = 0.0;
if(dAlpha <= 0.0 || dBeta <= 0.0){
return PENALTY;
}
for(i = 0; i < ptData->nNA; i++){
double dLogP = 0.0;
int nA = ptData->aanAbund[i][0];
dLogP = logLikelihood(nA, dAlpha, dBeta);
dLogL += ((double) ptData->aanAbund[i][1])*dLogP;
dLogL -= gsl_sf_lnfact(ptData->aanAbund[i][1]);
}
dLog0 = logLikelihood(0, dAlpha, dBeta);
dLog1 = (nS - ptData->nL)*dLog0;
dLog2 = - gsl_sf_lnfact(nS - ptData->nL);
dLog3 = gsl_sf_lnfact(nS);
dLogL += dLog1 + dLog2 + dLog3;
/*return*/
return -dLogL;
}
int minimiseSimplex(gsl_vector* ptX, size_t nP, void* pvData, double (*f)(const gsl_vector*, void* params))
{
const gsl_multimin_fminimizer_type *T =
gsl_multimin_fminimizer_nmsimplex;
gsl_multimin_fminimizer *s = NULL;
gsl_vector *ss;
gsl_multimin_function minex_func;
size_t iter = 0;
int i = 0, status;
double size;
/* Initial vertex size vector */
ss = gsl_vector_alloc (nP);
/* Set all step sizes to default constant */
gsl_vector_set_all(ss, INIT_SIMPLEX_SIZE);
gsl_vector_set(ss,nP - 1,INIT_S_SS*gsl_vector_get(ptX,0));
/* Initialize method and iterate */
minex_func.f = f;
minex_func.n = nP;
minex_func.params = pvData;
s = gsl_multimin_fminimizer_alloc (T, nP);
gsl_multimin_fminimizer_set(s, &minex_func, ptX, ss);
do{
iter++;
status = gsl_multimin_fminimizer_iterate(s);
if(status)
break;
size = gsl_multimin_fminimizer_size(s);
status = gsl_multimin_test_size(size, MIN_SIMPLEX_SIZE);
if(status == GSL_SUCCESS){
for(i = 0; i < nP; i++){
gsl_vector_set(ptX, i, gsl_vector_get(s->x, i));
}
if(verbose) printf("converged to minimum at\n");
}
if(verbose){
printf ("%5d ", iter);
for (i = 0; i < nP; i++) printf("%10.3e ", gsl_vector_get(s->x, i));
printf("f() = %7.3f size = %.3f\n", s->fval, size);
}
}
while(status == GSL_CONTINUE && iter < MAX_SIMPLEX_ITER);
for(i = 0; i < nP; i++){
gsl_vector_set(ptX, i, gsl_vector_get(s->x, i));
}
gsl_vector_free(ss);
gsl_multimin_fminimizer_free (s);
return status;
}
void freeAbundanceData(t_Data *ptData)
{
int i = 0;
for(i = 0; i < ptData->nNA; i++){
free(ptData->aanAbund[i]);
}
free(ptData->aanAbund);
}
void getProposal(gsl_rng *ptGSLRNG, gsl_vector *ptXDash, gsl_vector *ptX, int* pnSDash, int nS, t_Params *ptParams)
{
double dDeltaS = gsl_ran_gaussian(ptGSLRNG, ptParams->dSigmaS);
double dDeltaA = gsl_ran_gaussian(ptGSLRNG, ptParams->dSigmaA);
double dDeltaB = gsl_ran_gaussian(ptGSLRNG, ptParams->dSigmaB);
int nSDash = 0;
gsl_vector_set(ptXDash, 0, gsl_vector_get(ptX,0) + dDeltaA);
gsl_vector_set(ptXDash, 1, gsl_vector_get(ptX,1) + dDeltaB);
//printf("%e %e %e\n",dDeltaA,dDeltaB,dDeltaG);
nSDash = nS + (int) floor(dDeltaS);
if(nSDash < 1){
nSDash = 1;
}
(*pnSDash) = nSDash;
}
void outputResults(gsl_vector *ptX, t_Data *ptData)
{
double dAlpha = 0.0, dBeta = 0.0, dS = 0.0, dL = 0.0;
dAlpha = gsl_vector_get(ptX, 0);
dBeta = gsl_vector_get(ptX, 1);
dS = gsl_vector_get(ptX, 2);
dL = nLogLikelihood(ptX, ptData);
printf("\nML simplex: a = %.2f b = %.2f S = %.2f NLL = %.2f\n",dAlpha, dBeta, dS, dL);
}
void* metropolis (void * pvInitMetro)
{
t_MetroInit *ptMetroInit = (t_MetroInit *) pvInitMetro;
gsl_vector *ptX = ptMetroInit->ptX;
t_Data *ptData = ptMetroInit->ptData;
t_Params *ptParams = ptMetroInit->ptParams;
gsl_vector *ptXDash = gsl_vector_alloc(3); /*proposal*/
char *szSampleFile = (char *) malloc(MAX_LINE_LENGTH*sizeof(char));
const gsl_rng_type *T;
gsl_rng *ptGSLRNG;
FILE *sfp = NULL;
int nS = 0, nSDash = 0, nIter = 0;
double dRand = 0.0, dNLL = 0.0;
void *pvRet = NULL;
/*set up random number generator*/
T = gsl_rng_default;
ptGSLRNG = gsl_rng_alloc (T);
nS = (int) floor(gsl_vector_get(ptX,2));
dNLL = negLogLikelihood(gsl_vector_get(ptX,0), gsl_vector_get(ptX,1), nS,(void*) ptData);
sprintf(szSampleFile,"%s_%d%s", ptParams->szOutFileStub, ptMetroInit->nThread, SAMPLE_FILE_SUFFIX);
sfp = fopen(szSampleFile, "w");
if(!sfp){
exit(EXIT_FAILURE);
}
/*seed random number generator*/
gsl_rng_set(ptGSLRNG, ptMetroInit->lSeed);
/*now perform simple Metropolis algorithm*/
while(nIter < ptParams->nIter){
double dA = 0.0, dNLLDash = 0.0;
getProposal(ptGSLRNG, ptXDash, ptX, &nSDash, nS, ptParams);
dNLLDash = negLogLikelihood(gsl_vector_get(ptXDash,0), gsl_vector_get(ptXDash,1), nSDash, (void*) ptData);
//printf("X' %e %e %e %d %f\n", gsl_vector_get(ptXDash,0), gsl_vector_get(ptXDash,1), gsl_vector_get(ptXDash,2), nSDash, dNLLDash);
//printf("X %e %e %e %d %f\n", gsl_vector_get(ptX,0), gsl_vector_get(ptX,1), gsl_vector_get(ptX,2), nS, dNLL);
dA = exp(dNLL - dNLLDash);
if(dA > 1.0){
dA = 1.0;
}
dRand = gsl_rng_uniform(ptGSLRNG);
if(dRand < dA){
gsl_vector_memcpy(ptX, ptXDash);
nS = nSDash;
dNLL = dNLLDash;
ptMetroInit->nAccepted++;
}
if(nIter % SLICE == 0){
fprintf(sfp, "%d,%e,%e,%d,%f\n",nIter,gsl_vector_get(ptX, 0), gsl_vector_get(ptX, 1), nS, dNLL);
fflush(sfp);
}
nIter++;
}
fclose(sfp);
/*free up allocated memory*/
gsl_vector_free(ptXDash);
free(szSampleFile);
gsl_rng_free(ptGSLRNG);
return pvRet;
}
void writeThread(t_MetroInit *ptMetroInit)
{
gsl_vector *ptX = ptMetroInit->ptX;
printf("%d: a = %.2f b = %.2f S = %.2f\n", ptMetroInit->nThread,
gsl_vector_get(ptX, 0),
gsl_vector_get(ptX, 1),
gsl_vector_get(ptX, 2));
}
void mcmc(t_Params *ptParams, t_Data *ptData, gsl_vector* ptX)
{
pthread_t thread1, thread2, thread3;
int iret1 , iret2 , iret3;
gsl_vector *ptX1 = gsl_vector_alloc(3),
*ptX2 = gsl_vector_alloc(3),
*ptX3 = gsl_vector_alloc(3);
t_MetroInit atMetroInit[3];
printf("\nMCMC iter = %d sigmaA = %.2f sigmaB = %.2f sigmaS = %.2f\n",
ptParams->nIter, ptParams->dSigmaA, ptParams->dSigmaB, ptParams->dSigmaS);
gsl_vector_memcpy(ptX1, ptX);
gsl_vector_set(ptX2, 0, gsl_vector_get(ptX,0) + 2.0*ptParams->dSigmaA);
gsl_vector_set(ptX2, 1, gsl_vector_get(ptX,1) + 2.0*ptParams->dSigmaB);
gsl_vector_set(ptX2, 2, gsl_vector_get(ptX,2) + 2.0*ptParams->dSigmaS);
gsl_vector_set(ptX3, 0, gsl_vector_get(ptX,0) - 2.0*ptParams->dSigmaA);
gsl_vector_set(ptX3, 1, gsl_vector_get(ptX,1) - 2.0*ptParams->dSigmaB);
if(gsl_vector_get(ptX,2) - 2.0*ptParams->dSigmaS > (double) ptData->nL){
gsl_vector_set(ptX3, 2, gsl_vector_get(ptX,2) - 2.0*ptParams->dSigmaS);
}
else{
gsl_vector_set(ptX3, 2, (double) ptData->nL);
}
atMetroInit[0].ptParams = ptParams;
atMetroInit[0].ptData = ptData;
atMetroInit[0].ptX = ptX1;
atMetroInit[0].nThread = 0;
atMetroInit[0].lSeed = ptParams->lSeed;
atMetroInit[0].nAccepted = 0;
atMetroInit[1].ptParams = ptParams;
atMetroInit[1].ptData = ptData;
atMetroInit[1].ptX = ptX2;
atMetroInit[1].nThread = 1;
atMetroInit[1].lSeed = ptParams->lSeed + 1;
atMetroInit[1].nAccepted = 0;
atMetroInit[2].ptParams = ptParams;
atMetroInit[2].ptData = ptData;
atMetroInit[2].ptX = ptX3;
atMetroInit[2].nThread = 2;
atMetroInit[2].lSeed = ptParams->lSeed + 2;
atMetroInit[2].nAccepted = 0;
writeThread(&atMetroInit[0]);
writeThread(&atMetroInit[1]);
writeThread(&atMetroInit[2]);
iret1 = pthread_create(&thread1, NULL, metropolis, (void*) &atMetroInit[0]);
iret2 = pthread_create(&thread2, NULL, metropolis, (void*) &atMetroInit[1]);
iret3 = pthread_create(&thread3, NULL, metropolis, (void*) &atMetroInit[2]);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
printf("%d: accept. ratio %d/%d = %f\n", atMetroInit[0].nThread,
atMetroInit[0].nAccepted, ptParams->nIter,((double) atMetroInit[0].nAccepted)/((double) ptParams->nIter));
printf("%d: accept. ratio %d/%d = %f\n", atMetroInit[1].nThread,
atMetroInit[1].nAccepted, ptParams->nIter,((double) atMetroInit[1].nAccepted)/((double) ptParams->nIter));
printf("%d: accept. ratio %d/%d = %f\n", atMetroInit[2].nThread,
atMetroInit[2].nAccepted, ptParams->nIter, ((double) atMetroInit[2].nAccepted)/((double) ptParams->nIter));
gsl_vector_free(ptX1); gsl_vector_free(ptX2); gsl_vector_free(ptX3);
}
| {
"alphanum_fraction": 0.6147855714,
"avg_line_length": 24.9878378378,
"ext": "c",
"hexsha": "420ecc5f246e90c29f763efda733d1f18003c9a6",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "chrisquince/DiversityEstimates",
"max_forks_repo_path": "MetroIG/MetroIG.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "chrisquince/DiversityEstimates",
"max_issues_repo_path": "MetroIG/MetroIG.c",
"max_line_length": 135,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "chrisquince/DiversityEstimates",
"max_stars_repo_path": "MetroIG/MetroIG.c",
"max_stars_repo_stars_event_max_datetime": "2019-03-19T13:22:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-18T17:56:16.000Z",
"num_tokens": 6625,
"size": 18491
} |
// Copyright (c) 2013-2017 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
// and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/** \file sht.h
*
* \brief Contains declaration and particular implementation of sirius::SHT class.
*/
#ifndef __SHT_H__
#define __SHT_H__
#include <math.h>
#include <stddef.h>
#include <gsl/gsl_sf_coupling.h>
#include <gsl/gsl_sf_legendre.h>
#include <string.h>
#include <vector>
#include <algorithm>
#include "typedefs.h"
#include "utils.h"
#include "linalg.hpp"
#include "lebedev_grids.hpp"
namespace sirius {
/// Spherical harmonics transformations and related oprtations.
/** This class is responsible for the generation of complex and real spherical harmonics, generation of transformation
* matrices, transformation between spectral and real-space representations, generation of Gaunt and Clebsch-Gordan
* coefficients and calculation of spherical harmonic derivatives */
class SHT // TODO: better name
{
private:
/// Maximum \f$ \ell \f$ of spherical harmonics.
int lmax_;
/// Maximum number of \f$ \ell, m \f$ components.
int lmmax_;
/// Number of real-space \f$ (\theta, \phi) \f$ points on the sphere.
int num_points_;
/// Cartesian coordinates of points (normalized to 1).
mdarray<double, 2> coord_;
/// \f$ (\theta, \phi) \f$ angles of points.
mdarray<double, 2> tp_;
/// Point weights.
std::vector<double> w_;
/// Backward transformation from Ylm to spherical coordinates.
mdarray<double_complex, 2> ylm_backward_;
/// Forward transformation from spherical coordinates to Ylm.
mdarray<double_complex, 2> ylm_forward_;
/// Backward transformation from Rlm to spherical coordinates.
mdarray<double, 2> rlm_backward_;
/// Forward transformation from spherical coordinates to Rlm.
mdarray<double, 2> rlm_forward_;
/// Type of spherical grid (0: Lebedev-Laikov, 1: uniform).
int mesh_type_;
public:
/// Default constructor.
SHT(int lmax__)
: lmax_(lmax__)
, mesh_type_(0)
{
lmmax_ = (lmax_ + 1) * (lmax_ + 1);
if (mesh_type_ == 0) {
num_points_ = Lebedev_Laikov_npoint(2 * lmax_);
}
if (mesh_type_ == 1) {
num_points_ = lmmax_;
}
std::vector<double> x(num_points_);
std::vector<double> y(num_points_);
std::vector<double> z(num_points_);
coord_ = mdarray<double, 2>(3, num_points_);
tp_ = mdarray<double, 2>(2, num_points_);
w_.resize(num_points_);
if (mesh_type_ == 0) Lebedev_Laikov_sphere(num_points_, &x[0], &y[0], &z[0], &w_[0]);
if (mesh_type_ == 1) uniform_coverage();
ylm_backward_ = mdarray<double_complex, 2>(lmmax_, num_points_);
ylm_forward_ = mdarray<double_complex, 2>(num_points_, lmmax_);
rlm_backward_ = mdarray<double, 2>(lmmax_, num_points_);
rlm_forward_ = mdarray<double, 2>(num_points_, lmmax_);
for (int itp = 0; itp < num_points_; itp++) {
if (mesh_type_ == 0) {
coord_(0, itp) = x[itp];
coord_(1, itp) = y[itp];
coord_(2, itp) = z[itp];
auto vs = spherical_coordinates(vector3d<double>(x[itp], y[itp], z[itp]));
tp_(0, itp) = vs[1];
tp_(1, itp) = vs[2];
spherical_harmonics(lmax_, vs[1], vs[2], &ylm_backward_(0, itp));
spherical_harmonics(lmax_, vs[1], vs[2], &rlm_backward_(0, itp));
for (int lm = 0; lm < lmmax_; lm++) {
ylm_forward_(itp, lm) = std::conj(ylm_backward_(lm, itp)) * w_[itp] * fourpi;
rlm_forward_(itp, lm) = rlm_backward_(lm, itp) * w_[itp] * fourpi;
}
}
if (mesh_type_ == 1) {
double t = tp_(0, itp);
double p = tp_(1, itp);
coord_(0, itp) = sin(t) * cos(p);
coord_(1, itp) = sin(t) * sin(p);
coord_(2, itp) = cos(t);
spherical_harmonics(lmax_, t, p, &ylm_backward_(0, itp));
spherical_harmonics(lmax_, t, p, &rlm_backward_(0, itp));
for (int lm = 0; lm < lmmax_; lm++) {
ylm_forward_(lm, itp) = ylm_backward_(lm, itp);
rlm_forward_(lm, itp) = rlm_backward_(lm, itp);
}
}
}
if (mesh_type_ == 1) {
linalg<CPU>::geinv(lmmax_, ylm_forward_);
linalg<CPU>::geinv(lmmax_, rlm_forward_);
}
#if (__VERIFICATION > 0)
{
double dr = 0;
double dy = 0;
for (int lm = 0; lm < lmmax_; lm++)
{
for (int lm1 = 0; lm1 < lmmax_; lm1++)
{
double t = 0;
double_complex zt(0, 0);
for (int itp = 0; itp < num_points_; itp++)
{
zt += ylm_forward_(itp, lm) * ylm_backward_(lm1, itp);
t += rlm_forward_(itp, lm) * rlm_backward_(lm1, itp);
}
if (lm == lm1)
{
zt -= 1.0;
t -= 1.0;
}
dr += std::abs(t);
dy += std::abs(zt);
}
}
dr = dr / lmmax_ / lmmax_;
dy = dy / lmmax_ / lmmax_;
if (dr > 1e-15 || dy > 1e-15)
{
std::stringstream s;
s << "spherical mesh error is too big" << std::endl
<< " real spherical integration error " << dr << std::endl
<< " complex spherical integration error " << dy;
WARNING(s.str())
}
std::vector<double> flm(lmmax_);
std::vector<double> ftp(num_points_);
for (int lm = 0; lm < lmmax_; lm++)
{
std::memset(&flm[0], 0, lmmax_ * sizeof(double));
flm[lm] = 1.0;
backward_transform(lmmax_, &flm[0], 1, lmmax_, &ftp[0]);
forward_transform(&ftp[0], 1, lmmax_, lmmax_, &flm[0]);
flm[lm] -= 1.0;
double t = 0.0;
for (int lm1 = 0; lm1 < lmmax_; lm1++) t += std::abs(flm[lm1]);
t /= lmmax_;
if (t > 1e-15)
{
std::stringstream s;
s << "test of backward / forward real SHT failed" << std::endl
<< " total error " << t;
WARNING(s.str());
}
}
}
#endif
}
/// Perform a backward transformation from spherical harmonics to spherical coordinates.
/** \f[
* f(\theta, \phi, r) = \sum_{\ell m} f_{\ell m}(r) Y_{\ell m}(\theta, \phi)
* \f]
*
* \param [in] ld Size of leading dimension of flm.
* \param [in] flm Raw pointer to \f$ f_{\ell m}(r) \f$.
* \param [in] nr Number of radial points.
* \param [in] lmmax Maximum number of lm- harmonics to take into sum.
* \param [out] ftp Raw pointer to \f$ f(\theta, \phi, r) \f$.
*/
template <typename T>
void backward_transform(int ld, T const* flm, int nr, int lmmax, T* ftp);
/// Perform a forward transformation from spherical coordinates to spherical harmonics.
/** \f[
* f_{\ell m}(r) = \iint f(\theta, \phi, r) Y_{\ell m}^{*}(\theta, \phi) \sin \theta d\phi d\theta =
* \sum_{i} f(\theta_i, \phi_i, r) Y_{\ell m}^{*}(\theta_i, \phi_i) w_i
* \f]
*
* \param [in] ftp Raw pointer to \f$ f(\theta, \phi, r) \f$.
* \param [in] nr Number of radial points.
* \param [in] lmmax Maximum number of lm- coefficients to generate.
* \param [in] ld Size of leading dimension of flm.
* \param [out] flm Raw pointer to \f$ f_{\ell m}(r) \f$.
*/
template <typename T>
void forward_transform(T const* ftp, int nr, int lmmax, int ld, T* flm);
/// Convert form Rlm to Ylm representation.
static void convert(int lmax__, double const* f_rlm__, double_complex* f_ylm__)
{
int lm = 0;
for (int l = 0; l <= lmax__; l++) {
for (int m = -l; m <= l; m++) {
if (m == 0) {
f_ylm__[lm] = f_rlm__[lm];
} else {
int lm1 = Utils::lm_by_l_m(l, -m);
f_ylm__[lm] = ylm_dot_rlm(l, m, m) * f_rlm__[lm] + ylm_dot_rlm(l, m, -m) * f_rlm__[lm1];
}
lm++;
}
}
}
/// Convert from Ylm to Rlm representation.
static void convert(int lmax__, double_complex const* f_ylm__, double* f_rlm__)
{
int lm = 0;
for (int l = 0; l <= lmax__; l++) {
for (int m = -l; m <= l; m++) {
if (m == 0) {
f_rlm__[lm] = std::real(f_ylm__[lm]);
} else {
int lm1 = Utils::lm_by_l_m(l, -m);
f_rlm__[lm] = std::real(rlm_dot_ylm(l, m, m) * f_ylm__[lm] + rlm_dot_ylm(l, m, -m) * f_ylm__[lm1]);
}
lm++;
}
}
}
//void rlm_forward_iterative_transform(double *ftp__, int lmmax, int ncol, double* flm)
//{
// Timer t("sirius::SHT::rlm_forward_iterative_transform");
//
// assert(lmmax <= lmmax_);
// mdarray<double, 2> ftp(ftp__, num_points_, ncol);
// mdarray<double, 2> ftp1(num_points_, ncol);
//
// blas<cpu>::gemm(1, 0, lmmax, ncol, num_points_, 1.0, &rlm_forward_(0, 0), num_points_, &ftp(0, 0), num_points_, 0.0,
// flm, lmmax);
//
// for (int i = 0; i < 2; i++)
// {
// rlm_backward_transform(flm, lmmax, ncol, &ftp1(0, 0));
// double tdiff = 0.0;
// for (int ir = 0; ir < ncol; ir++)
// {
// for (int itp = 0; itp < num_points_; itp++)
// {
// ftp1(itp, ir) = ftp(itp, ir) - ftp1(itp, ir);
// //tdiff += fabs(ftp1(itp, ir));
// }
// }
//
// for (int itp = 0; itp < num_points_; itp++)
// {
// tdiff += fabs(ftp1(itp, ncol - 1));
// }
// std::cout << "iter : " << i << " avg. MT diff = " << tdiff / num_points_ << std::endl;
// blas<cpu>::gemm(1, 0, lmmax, ncol, num_points_, 1.0, &rlm_forward_(0, 0), num_points_, &ftp1(0, 0), num_points_, 1.0,
// flm, lmmax);
// }
//}
/// Transform Cartesian coordinates [x,y,z] to spherical coordinates [r,theta,phi]
static vector3d<double> spherical_coordinates(vector3d<double> vc)
{
vector3d<double> vs;
const double eps{1e-12};
vs[0] = vc.length();
if (vs[0] <= eps) {
vs[1] = 0.0;
vs[2] = 0.0;
} else {
vs[1] = std::acos(vc[2] / vs[0]); // theta = cos^{-1}(z/r)
if (std::abs(vc[0]) > eps || std::abs(vc[1]) > eps) {
vs[2] = std::atan2(vc[1], vc[0]); // phi = tan^{-1}(y/x)
if (vs[2] < 0.0) {
vs[2] += twopi;
}
} else {
vs[2] = 0.0;
}
}
return vs;
}
/// Generate complex spherical harmonics Ylm
static void spherical_harmonics(int lmax, double theta, double phi, double_complex* ylm)
{
double x = std::cos(theta);
std::vector<double> result_array(lmax + 1);
for (int l = 0; l <= lmax; l++) {
for (int m = 0; m <= l; m++) {
double_complex z = std::exp(double_complex(0.0, m * phi));
ylm[Utils::lm_by_l_m(l, m)] = gsl_sf_legendre_sphPlm(l, m, x) * z;
if (m % 2) {
ylm[Utils::lm_by_l_m(l, -m)] = -std::conj(ylm[Utils::lm_by_l_m(l, m)]);
} else {
ylm[Utils::lm_by_l_m(l, -m)] = std::conj(ylm[Utils::lm_by_l_m(l, m)]);
}
}
}
}
/// Generate real spherical harmonics Rlm
/** Mathematica code:
* \verbatim
* R[l_, m_, th_, ph_] :=
* If[m > 0, std::sqrt[2]*ComplexExpand[Re[SphericalHarmonicY[l, m, th, ph]]],
* If[m < 0, std::sqrt[2]*ComplexExpand[Im[SphericalHarmonicY[l, m, th, ph]]],
* If[m == 0, ComplexExpand[Re[SphericalHarmonicY[l, 0, th, ph]]]]]]
* \endverbatim
*/
static void spherical_harmonics(int lmax, double theta, double phi, double* rlm)
{
int lmmax = (lmax + 1) * (lmax + 1);
std::vector<double_complex> ylm(lmmax);
spherical_harmonics(lmax, theta, phi, &ylm[0]);
double const t = std::sqrt(2.0);
rlm[0] = y00;
for (int l = 1; l <= lmax; l++) {
for (int m = -l; m < 0; m++) {
rlm[Utils::lm_by_l_m(l, m)] = t * ylm[Utils::lm_by_l_m(l, m)].imag();
}
rlm[Utils::lm_by_l_m(l, 0)] = ylm[Utils::lm_by_l_m(l, 0)].real();
for (int m = 1; m <= l; m++) {
rlm[Utils::lm_by_l_m(l, m)] = t * ylm[Utils::lm_by_l_m(l, m)].real();
}
}
}
/// Compute element of the transformation matrix from complex to real spherical harmonics.
/** Real spherical harmonic can be written as a linear combination of complex harmonics:
\f[
R_{\ell m}(\theta, \phi) = \sum_{m'} a^{\ell}_{m' m}Y_{\ell m'}(\theta, \phi)
\f]
where
\f[
a^{\ell}_{m' m} = \langle Y_{\ell m'} | R_{\ell m} \rangle
\f]
which gives the name to this function.
Transformation from real to complex spherical harmonics is conjugate transpose:
\f[
Y_{\ell m}(\theta, \phi) = \sum_{m'} a^{\ell*}_{m m'}R_{\ell m'}(\theta, \phi)
\f]
Mathematica code:
\verbatim
b[m1_, m2_] :=
If[m1 == 0, 1,
If[m1 < 0 && m2 < 0, -I/Sqrt[2],
If[m1 > 0 && m2 < 0, (-1)^m1*I/Sqrt[2],
If[m1 < 0 && m2 > 0, (-1)^m2/Sqrt[2],
If[m1 > 0 && m2 > 0, 1/Sqrt[2]]]]]]
a[m1_, m2_] := If[Abs[m1] == Abs[m2], b[m1, m2], 0]
Rlm[l_, m_, t_, p_] := Sum[a[m1, m]*SphericalHarmonicY[l, m1, t, p], {m1, -l, l}]
\endverbatim
*/
static inline double_complex ylm_dot_rlm(int l, int m1, int m2)
{
double const isqrt2 = 1.0 / std::sqrt(2);
assert(l >= 0 && std::abs(m1) <= l && std::abs(m2) <= l);
if (!((m1 == m2) || (m1 == -m2))) {
return double_complex(0, 0);
}
if (m1 == 0) {
return double_complex(1, 0);
}
if (m1 < 0) {
if (m2 < 0) {
return -double_complex(0, isqrt2);
} else {
return std::pow(-1.0, m2) * double_complex(isqrt2, 0);
}
} else {
if (m2 < 0) {
return std::pow(-1.0, m1) * double_complex(0, isqrt2);
} else {
return double_complex(isqrt2, 0);
}
}
}
static inline double_complex rlm_dot_ylm(int l, int m1, int m2)
{
return std::conj(ylm_dot_rlm(l, m2, m1));
}
/// Gaunt coefficent of three complex spherical harmonics.
/**
* \f[
* \langle Y_{\ell_1 m_1} | Y_{\ell_2 m_2} | Y_{\ell_3 m_3} \rangle
* \f]
*/
static double gaunt_ylm(int l1, int l2, int l3, int m1, int m2, int m3)
{
assert(l1 >= 0);
assert(l2 >= 0);
assert(l3 >= 0);
assert(m1 >= -l1 && m1 <= l1);
assert(m2 >= -l2 && m2 <= l2);
assert(m3 >= -l3 && m3 <= l3);
return std::pow(-1.0, std::abs(m1)) * std::sqrt(double(2 * l1 + 1) * double(2 * l2 + 1) * double(2 * l3 + 1) / fourpi) *
gsl_sf_coupling_3j(2 * l1, 2 * l2, 2 * l3, 0, 0, 0) *
gsl_sf_coupling_3j(2 * l1, 2 * l2, 2 * l3, -2 * m1, 2 * m2, 2 * m3);
}
/// Gaunt coefficent of three real spherical harmonics.
/**
* \f[
* \langle R_{\ell_1 m_1} | R_{\ell_2 m_2} | R_{\ell_3 m_3} \rangle
* \f]
*/
static double gaunt_rlm(int l1, int l2, int l3, int m1, int m2, int m3)
{
assert(l1 >= 0);
assert(l2 >= 0);
assert(l3 >= 0);
assert(m1 >= -l1 && m1 <= l1);
assert(m2 >= -l2 && m2 <= l2);
assert(m3 >= -l3 && m3 <= l3);
double d = 0;
for (int k1 = -l1; k1 <= l1; k1++) {
for (int k2 = -l2; k2 <= l2; k2++) {
for (int k3 = -l3; k3 <= l3; k3++) {
d += std::real(std::conj(SHT::ylm_dot_rlm(l1, k1, m1)) *
SHT::ylm_dot_rlm(l2, k2, m2) *
SHT::ylm_dot_rlm(l3, k3, m3)) * SHT::gaunt_ylm(l1, l2, l3, k1, k2, k3);
}
}
}
return d;
}
/// Gaunt coefficent of two real spherical harmonics with a complex one.
/**
* \f[
* \langle R_{\ell_1 m_1} | Y_{\ell_2 m_2} | R_{\ell_3 m_3} \rangle
* \f]
*/
static double gaunt_rlm_ylm_rlm(int l1, int l2, int l3, int m1, int m2, int m3)
{
assert(l1 >= 0);
assert(l2 >= 0);
assert(l3 >= 0);
assert(m1 >= -l1 && m1 <= l1);
assert(m2 >= -l2 && m2 <= l2);
assert(m3 >= -l3 && m3 <= l3);
double d = 0;
for (int k1 = -l1; k1 <= l1; k1++) {
for (int k3 = -l3; k3 <= l3; k3++) {
d += std::real(std::conj(SHT::ylm_dot_rlm(l1, k1, m1)) *
SHT::ylm_dot_rlm(l3, k3, m3)) * SHT::gaunt_ylm(l1, l2, l3, k1, m2, k3);
}
}
return d;
}
/// Gaunt coefficent of two complex and one real spherical harmonics.
/**
* \f[
* \langle Y_{\ell_1 m_1} | R_{\ell_2 m_2} | Y_{\ell_3 m_3} \rangle
* \f]
*/
static double_complex gaunt_hybrid(int l1, int l2, int l3, int m1, int m2, int m3)
{
assert(l1 >= 0);
assert(l2 >= 0);
assert(l3 >= 0);
assert(m1 >= -l1 && m1 <= l1);
assert(m2 >= -l2 && m2 <= l2);
assert(m3 >= -l3 && m3 <= l3);
if (m2 == 0) {
return double_complex(gaunt_ylm(l1, l2, l3, m1, m2, m3), 0.0);
} else {
return (ylm_dot_rlm(l2, m2, m2) * gaunt_ylm(l1, l2, l3, m1, m2, m3) +
ylm_dot_rlm(l2, -m2, m2) * gaunt_ylm(l1, l2, l3, m1, -m2, m3));
}
}
void uniform_coverage()
{
tp_(0, 0) = pi;
tp_(1, 0) = 0;
for (int k = 1; k < num_points_ - 1; k++) {
double hk = -1.0 + double(2 * k) / double(num_points_ - 1);
tp_(0, k) = std::acos(hk);
double t = tp_(1, k - 1) + 3.80925122745582 / std::sqrt(double(num_points_)) / std::sqrt(1 - hk * hk);
tp_(1, k) = std::fmod(t, twopi);
}
tp_(0, num_points_ - 1) = 0;
tp_(1, num_points_ - 1) = 0;
}
/// Return Clebsch-Gordan coefficient.
/** Clebsch-Gordan coefficients arise when two angular momenta are combined into a
* total angular momentum.
*/
static inline double clebsch_gordan(int l1, int l2, int l3, int m1, int m2, int m3)
{
assert(l1 >= 0);
assert(l2 >= 0);
assert(l3 >= 0);
assert(m1 >= -l1 && m1 <= l1);
assert(m2 >= -l2 && m2 <= l2);
assert(m3 >= -l3 && m3 <= l3);
return std::pow(-1, l1 - l2 + m3) * std::sqrt(double(2 * l3 + 1)) *
gsl_sf_coupling_3j(2 * l1, 2 * l2, 2 * l3, 2 * m1, 2 * m2, -2 * m3);
}
inline double_complex ylm_backward(int lm, int itp) const
{
return ylm_backward_(lm, itp);
}
inline double rlm_backward(int lm, int itp) const
{
return rlm_backward_(lm, itp);
}
inline double coord(int x, int itp) const
{
return coord_(x, itp);
}
inline vector3d<double> coord(int idx__) const
{
return vector3d<double>(coord_(0, idx__), coord_(1, idx__), coord(2, idx__));
}
inline double theta(int idx__) const
{
return tp_(0, idx__);
}
inline double phi(int idx__) const
{
return tp_(1, idx__);
}
inline int num_points() const
{
return num_points_;
}
inline int lmax() const
{
return lmax_;
}
inline int lmmax() const
{
return lmmax_;
}
static void wigner_d_matrix(int l, double beta, mdarray<double, 2>& d_mtrx__)
{
long double cos_b2 = std::cos((long double)beta / 2.0L);
long double sin_b2 = std::sin((long double)beta / 2.0L);
for (int m1 = -l; m1 <= l; m1++) {
for (int m2 = -l; m2 <= l; m2++) {
long double d = 0;
for (int j = 0; j <= std::min(l + m1, l - m2); j++) {
if ((l - m2 - j) >= 0 && (l + m1 - j) >= 0 && (j + m2 - m1) >= 0) {
long double g = (std::sqrt(Utils::factorial(l + m1)) / Utils::factorial(l - m2 - j)) *
(std::sqrt(Utils::factorial(l - m1)) / Utils::factorial(l + m1 - j)) *
(std::sqrt(Utils::factorial(l - m2)) / Utils::factorial(j + m2 - m1)) *
(std::sqrt(Utils::factorial(l + m2)) / Utils::factorial(j));
d += g * std::pow(-1, j) * std::pow(cos_b2, 2 * l + m1 - m2 - 2 * j) * std::pow(sin_b2, 2 * j + m2 - m1);
}
}
d_mtrx__(m1 + l, m2 + l) = (double)d;
}
}
}
static void rotation_matrix_l(int l, vector3d<double> euler_angles, int proper_rotation,
double_complex* rot_mtrx__, int ld)
{
mdarray<double_complex, 2> rot_mtrx(rot_mtrx__, ld, 2 * l + 1);
mdarray<double, 2> d_mtrx(2 * l + 1, 2 * l + 1);
wigner_d_matrix(l, euler_angles[1], d_mtrx);
for (int m1 = -l; m1 <= l; m1++) {
for (int m2 = -l; m2 <= l; m2++) {
rot_mtrx(m1 + l, m2 + l) = std::exp(double_complex(0, -euler_angles[0] * m1 - euler_angles[2] * m2)) *
d_mtrx(m1 + l, m2 + l) * std::pow(proper_rotation, l);
}
}
}
static void rotation_matrix_l(int l, vector3d<double> euler_angles, int proper_rotation,
double* rot_mtrx__, int ld)
{
mdarray<double, 2> rot_mtrx_rlm(rot_mtrx__, ld, 2 * l + 1);
mdarray<double_complex, 2> rot_mtrx_ylm(2 * l + 1, 2 * l + 1);
mdarray<double, 2> d_mtrx(2 * l + 1, 2 * l + 1);
wigner_d_matrix(l, euler_angles[1], d_mtrx);
for (int m1 = -l; m1 <= l; m1++)
{
for (int m2 = -l; m2 <= l; m2++)
{
rot_mtrx_ylm(m1 + l, m2 + l) = std::exp(double_complex(0, -euler_angles[0] * m1 - euler_angles[2] * m2)) *
d_mtrx(m1 + l, m2 + l) * std::pow(proper_rotation, l);
}
}
for (int m1 = -l; m1 <= l; m1++)
{
auto i13 = (m1 == 0) ? std::vector<int>({0}) : std::vector<int>({-m1, m1});
for (int m2 = -l; m2 <= l; m2++)
{
auto i24 = (m2 == 0) ? std::vector<int>({0}) : std::vector<int>({-m2, m2});
for (int m3: i13)
{
for (int m4: i24)
{
rot_mtrx_rlm(m1 + l, m2 + l) += std::real(rlm_dot_ylm(l, m1, m3) *
rot_mtrx_ylm(m3 + l, m4 + l) *
ylm_dot_rlm(l, m4, m2));
}
}
}
}
}
template <typename T>
static void rotation_matrix(int lmax,
vector3d<double> euler_angles,
int proper_rotation,
mdarray<T, 2>& rotm)
{
rotm.zero();
for (int l = 0; l <= lmax; l++) {
rotation_matrix_l(l, euler_angles, proper_rotation, &rotm(l * l, l * l), rotm.ld());
}
}
/// Compute derivative of real-spherical harmonic with respect to theta angle.
static void dRlm_dtheta(int lmax, double theta, double phi, mdarray<double, 1>& data)
{
assert(lmax <= 8);
data[0]=0;
if (lmax==0) return;
auto cos_theta = SHT::cosxn(lmax, theta);
auto sin_theta = SHT::sinxn(lmax, theta);
auto cos_phi = SHT::cosxn(lmax, phi);
auto sin_phi = SHT::sinxn(lmax, phi);
data[1]=-(std::sqrt(3/pi)*cos_theta[0]*sin_phi[0])/2.;
data[2]=-(std::sqrt(3/pi)*sin_theta[0])/2.;
data[3]=-(std::sqrt(3/pi)*cos_phi[0]*cos_theta[0])/2.;
if (lmax==1) return;
data[4]=-(std::sqrt(15/pi)*cos_phi[0]*cos_theta[0]*sin_phi[0]*sin_theta[0]);
data[5]=-(std::sqrt(15/pi)*cos_theta[1]*sin_phi[0])/2.;
data[6]=(-3*std::sqrt(5/pi)*cos_theta[0]*sin_theta[0])/2.;
data[7]=-(std::sqrt(15/pi)*cos_phi[0]*cos_theta[1])/2.;
data[8]=(std::sqrt(15/pi)*cos_phi[1]*sin_theta[1])/4.;
if (lmax==2) return;
data[9]=(-3*std::sqrt(35/(2.*pi))*cos_theta[0]*sin_phi[2]*std::pow(sin_theta[0],2))/4.;
data[10]=(std::sqrt(105/pi)*sin_phi[1]*(sin_theta[0] - 3*sin_theta[2]))/16.;
data[11]=-(std::sqrt(21/(2.*pi))*(cos_theta[0] + 15*cos_theta[2])*sin_phi[0])/16.;
data[12]=(-3*std::sqrt(7/pi)*(sin_theta[0] + 5*sin_theta[2]))/16.;
data[13]=-(std::sqrt(21/(2.*pi))*cos_phi[0]*(cos_theta[0] + 15*cos_theta[2]))/16.;
data[14]=-(std::sqrt(105/pi)*cos_phi[1]*(sin_theta[0] - 3*sin_theta[2]))/16.;
data[15]=(-3*std::sqrt(35/(2.*pi))*cos_phi[2]*cos_theta[0]*std::pow(sin_theta[0],2))/4.;
if (lmax==3) return;
data[16]=(-3*std::sqrt(35/pi)*cos_theta[0]*sin_phi[3]*std::pow(sin_theta[0],3))/4.;
data[17]=(-3*std::sqrt(35/(2.*pi))*(1 + 2*cos_theta[1])*sin_phi[2]*std::pow(sin_theta[0],2))/4.;
data[18]=(3*std::sqrt(5/pi)*sin_phi[1]*(2*sin_theta[1] - 7*sin_theta[3]))/16.;
data[19]=(-3*std::sqrt(5/(2.*pi))*(cos_theta[1] + 7*cos_theta[3])*sin_phi[0])/8.;
data[20]=(-15*(2*sin_theta[1] + 7*sin_theta[3]))/(32.*std::sqrt(pi));
data[21]=(-3*std::sqrt(5/(2.*pi))*cos_phi[0]*(cos_theta[1] + 7*cos_theta[3]))/8.;
data[22]=(3*std::sqrt(5/pi)*cos_phi[1]*(-2*sin_theta[1] + 7*sin_theta[3]))/16.;
data[23]=(-3*std::sqrt(35/(2.*pi))*cos_phi[2]*(1 + 2*cos_theta[1])*std::pow(sin_theta[0],2))/4.;
data[24]=(3*std::sqrt(35/pi)*cos_phi[3]*cos_theta[0]*std::pow(sin_theta[0],3))/4.;
if (lmax==4) return;
data[25]=(-15*std::sqrt(77/(2.*pi))*cos_theta[0]*sin_phi[4]*std::pow(sin_theta[0],4))/16.;
data[26]=(-3*std::sqrt(385/pi)*(3 + 5*cos_theta[1])*sin_phi[3]*std::pow(sin_theta[0],3))/32.;
data[27]=(-3*std::sqrt(385/(2.*pi))*cos_theta[0]*(1 + 15*cos_theta[1])*sin_phi[2]*std::pow(sin_theta[0],2))/32.;
data[28]=(std::sqrt(1155/pi)*sin_phi[1]*(2*sin_theta[0] + 3*(sin_theta[2] - 5*sin_theta[4])))/128.;
data[29]=-(std::sqrt(165/pi)*(2*cos_theta[0] + 21*(cos_theta[2] + 5*cos_theta[4]))*sin_phi[0])/256.;
data[30]=(-15*std::sqrt(11/pi)*(2*sin_theta[0] + 7*(sin_theta[2] + 3*sin_theta[4])))/256.;
data[31]=-(std::sqrt(165/pi)*cos_phi[0]*(2*cos_theta[0] + 21*(cos_theta[2] + 5*cos_theta[4])))/256.;
data[32]=(std::sqrt(1155/pi)*cos_phi[1]*(-2*sin_theta[0] - 3*sin_theta[2] + 15*sin_theta[4]))/128.;
data[33]=(-3*std::sqrt(385/(2.*pi))*cos_phi[2]*(17*cos_theta[0] + 15*cos_theta[2])*std::pow(sin_theta[0],2))/64.;
data[34]=(3*std::sqrt(385/pi)*cos_phi[3]*(3 + 5*cos_theta[1])*std::pow(sin_theta[0],3))/32.;
data[35]=(-15*std::sqrt(77/(2.*pi))*cos_phi[4]*cos_theta[0]*std::pow(sin_theta[0],4))/16.;
if (lmax==5) return;
data[36]=(-3*std::sqrt(3003/(2.*pi))*cos_theta[0]*sin_phi[5]*std::pow(sin_theta[0],5))/16.;
data[37]=(-3*std::sqrt(1001/(2.*pi))*(2 + 3*cos_theta[1])*sin_phi[4]*std::pow(sin_theta[0],4))/16.;
data[38]=(-3*std::sqrt(91/pi)*cos_theta[0]*(7 + 33*cos_theta[1])*sin_phi[3]*std::pow(sin_theta[0],3))/32.;
data[39]=(-3*std::sqrt(1365/(2.*pi))*(7 + 14*cos_theta[1] + 11*cos_theta[3])*sin_phi[2]*std::pow(sin_theta[0],2))/64.;
data[40]=(std::sqrt(1365/(2.*pi))*sin_phi[1]*(17*sin_theta[1] + 12*sin_theta[3] - 99*sin_theta[5]))/512.;
data[41]=-(std::sqrt(273/pi)*(5*cos_theta[1] + 24*cos_theta[3] + 99*cos_theta[5])*sin_phi[0])/256.;
data[42]=(-21*std::sqrt(13/pi)*(5*sin_theta[1] + 12*sin_theta[3] + 33*sin_theta[5]))/512.;
data[43]=-(std::sqrt(273/pi)*cos_phi[0]*(5*cos_theta[1] + 24*cos_theta[3] + 99*cos_theta[5]))/256.;
data[44]=(std::sqrt(1365/(2.*pi))*cos_phi[1]*(-17*sin_theta[1] - 12*sin_theta[3] + 99*sin_theta[5]))/512.;
data[45]=(-3*std::sqrt(1365/(2.*pi))*cos_phi[2]*(7 + 14*cos_theta[1] + 11*cos_theta[3])*std::pow(sin_theta[0],2))/64.;
data[46]=(3*std::sqrt(91/pi)*cos_phi[3]*(47*cos_theta[0] + 33*cos_theta[2])*std::pow(sin_theta[0],3))/64.;
data[47]=(-3*std::sqrt(1001/(2.*pi))*cos_phi[4]*(2 + 3*cos_theta[1])*std::pow(sin_theta[0],4))/16.;
data[48]=(3*std::sqrt(3003/(2.*pi))*cos_phi[5]*cos_theta[0]*std::pow(sin_theta[0],5))/16.;
if (lmax==6) return;
data[49]=(-21*std::sqrt(715/pi)*cos_theta[0]*sin_phi[6]*std::pow(sin_theta[0],6))/64.;
data[50]=(-3*std::sqrt(5005/(2.*pi))*(5 + 7*cos_theta[1])*sin_phi[5]*std::pow(sin_theta[0],5))/64.;
data[51]=(-3*std::sqrt(385/pi)*cos_theta[0]*(29 + 91*cos_theta[1])*sin_phi[4]*std::pow(sin_theta[0],4))/128.;
data[52]=(-3*std::sqrt(385/pi)*(81 + 148*cos_theta[1] + 91*cos_theta[3])*sin_phi[3]*std::pow(sin_theta[0],3))/256.;
data[53]=(-3*std::sqrt(35/pi)*cos_theta[0]*(523 + 396*cos_theta[1] + 1001*cos_theta[3])*sin_phi[2]*std::pow(sin_theta[0],2))/512.;
data[54]=(3*std::sqrt(35/(2.*pi))*sin_phi[1]*(75*sin_theta[0] + 171*sin_theta[2] + 55*sin_theta[4] - 1001*sin_theta[6]))/2048.;
data[55]=-(std::sqrt(105/pi)*(25*cos_theta[0] + 243*cos_theta[2] + 825*cos_theta[4] + 3003*cos_theta[6])*sin_phi[0])/4096.;
data[56]=(-7*std::sqrt(15/pi)*(25*sin_theta[0] + 81*sin_theta[2] + 165*sin_theta[4] + 429*sin_theta[6]))/2048.;
data[57]=-(std::sqrt(105/pi)*cos_phi[0]*(25*cos_theta[0] + 243*cos_theta[2] + 825*cos_theta[4] + 3003*cos_theta[6]))/4096.;
data[58]=(-3*std::sqrt(35/(2.*pi))*cos_phi[1]*(75*sin_theta[0] + 171*sin_theta[2] + 55*sin_theta[4] - 1001*sin_theta[6]))/2048.;
data[59]=(-3*std::sqrt(35/pi)*cos_phi[2]*(1442*cos_theta[0] + 1397*cos_theta[2] + 1001*cos_theta[4])*std::pow(sin_theta[0],2))/1024.;
data[60]=(3*std::sqrt(385/pi)*cos_phi[3]*(81 + 148*cos_theta[1] + 91*cos_theta[3])*std::pow(sin_theta[0],3))/256.;
data[61]=(-3*std::sqrt(385/pi)*cos_phi[4]*(149*cos_theta[0] + 91*cos_theta[2])*std::pow(sin_theta[0],4))/256.;
data[62]=(3*std::sqrt(5005/(2.*pi))*cos_phi[5]*(5 + 7*cos_theta[1])*std::pow(sin_theta[0],5))/64.;
data[63]=(-21*std::sqrt(715/pi)*cos_phi[6]*cos_theta[0]*std::pow(sin_theta[0],6))/64.;
if (lmax==7) return;
data[64]=(-3*std::sqrt(12155/pi)*cos_theta[0]*sin_phi[7]*std::pow(sin_theta[0],7))/32.;
data[65]=(-3*std::sqrt(12155/pi)*(3 + 4*cos_theta[1])*sin_phi[6]*std::pow(sin_theta[0],6))/64.;
data[66]=(-3*std::sqrt(7293/(2.*pi))*cos_theta[0]*(2 + 5*cos_theta[1])*sin_phi[5]*std::pow(sin_theta[0],5))/16.;
data[67]=(-3*std::sqrt(17017/pi)*(11 + 19*cos_theta[1] + 10*cos_theta[3])*sin_phi[4]*std::pow(sin_theta[0],4))/128.;
data[68]=(-3*std::sqrt(1309/pi)*cos_theta[0]*(43 + 52*cos_theta[1] + 65*cos_theta[3])*sin_phi[3]*std::pow(sin_theta[0],3))/128.;
data[69]=(-3*std::sqrt(19635/pi)*(21 + 42*cos_theta[1] + 39*cos_theta[3] + 26*cos_theta[5])*sin_phi[2]*std::pow(sin_theta[0],2))/512.;
data[70]=(-3*std::sqrt(595/(2.*pi))*(-8 + 121*cos_theta[1] + 143*cos_theta[5])*sin_phi[1]*sin_theta[1])/512.;
data[71]=(-3*std::sqrt(17/pi)*(35*cos_theta[1] + 154*cos_theta[3] + 429*cos_theta[5] + 1430*cos_theta[7])*sin_phi[0])/2048.;
data[72]=(-9*std::sqrt(17/pi)*(70*sin_theta[1] + 154*sin_theta[3] + 286*sin_theta[5] + 715*sin_theta[7]))/4096.;
data[73]=(-3*std::sqrt(17/pi)*cos_phi[0]*(35*cos_theta[1] + 154*cos_theta[3] + 429*cos_theta[5] + 1430*cos_theta[7]))/2048.;
data[74]=(3*std::sqrt(595/(2.*pi))*cos_phi[1]*(-16*sin_theta[1] - 22*sin_theta[3] + 143*sin_theta[7]))/1024.;
data[75]=(-3*std::sqrt(19635/pi)*cos_phi[2]*(21 + 42*cos_theta[1] + 39*cos_theta[3] + 26*cos_theta[5])*std::pow(sin_theta[0],2))/512.;
data[76]=(3*std::sqrt(1309/pi)*cos_phi[3]*(138*cos_theta[0] + 117*cos_theta[2] + 65*cos_theta[4])*std::pow(sin_theta[0],3))/256.;
data[77]=(-3*std::sqrt(17017/pi)*cos_phi[4]*(11 + 19*cos_theta[1] + 10*cos_theta[3])*std::pow(sin_theta[0],4))/128.;
data[78]=(3*std::sqrt(7293/(2.*pi))*cos_phi[5]*(9*cos_theta[0] + 5*cos_theta[2])*std::pow(sin_theta[0],5))/32.;
data[79]=(-3*std::sqrt(12155/pi)*cos_phi[6]*(3 + 4*cos_theta[1])*std::pow(sin_theta[0],6))/64.;
data[80]=(3*std::sqrt(12155/pi)*cos_phi[7]*cos_theta[0]*std::pow(sin_theta[0],7))/32.;
}
/// Compute derivative of real-spherical harmonic with respect to phi angle and divide by sin(theta).
static void dRlm_dphi_sin_theta(int lmax, double theta, double phi, mdarray<double, 1>& data)
{
assert(lmax <= 8);
data[0]=0;
if (lmax==0) return;
auto cos_theta = SHT::cosxn(lmax, theta);
auto sin_theta = SHT::sinxn(lmax, theta);
auto cos_phi = SHT::cosxn(lmax, phi);
auto sin_phi = SHT::sinxn(lmax, phi);
data[1]=-(std::sqrt(3/pi)*cos_phi[0])/2.;
data[2]=0;
data[3]=(std::sqrt(3/pi)*sin_phi[0])/2.;
if (lmax==1) return;
data[4]=-(std::sqrt(15/pi)*cos_phi[1]*sin_theta[0])/2.;
data[5]=-(std::sqrt(15/pi)*cos_phi[0]*cos_theta[0])/2.;
data[6]=0;
data[7]=(std::sqrt(15/pi)*cos_theta[0]*sin_phi[0])/2.;
data[8]=-(std::sqrt(15/pi)*cos_phi[0]*sin_phi[0]*sin_theta[0]);
if (lmax==2) return;
data[9]=(-3*std::sqrt(35/(2.*pi))*cos_phi[2]*std::pow(sin_theta[0],2))/4.;
data[10]=-(std::sqrt(105/pi)*cos_phi[1]*sin_theta[1])/4.;
data[11]=-(std::sqrt(21/(2.*pi))*cos_phi[0]*(3 + 5*cos_theta[1]))/8.;
data[12]=0;
data[13]=(std::sqrt(21/(2.*pi))*(3 + 5*cos_theta[1])*sin_phi[0])/8.;
data[14]=-(std::sqrt(105/pi)*cos_phi[0]*cos_theta[0]*sin_phi[0]*sin_theta[0]);
data[15]=(3*std::sqrt(35/(2.*pi))*sin_phi[2]*std::pow(sin_theta[0],2))/4.;
if (lmax==3) return;
data[16]=(-3*std::sqrt(35/pi)*cos_phi[3]*std::pow(sin_theta[0],3))/4.;
data[17]=(-9*std::sqrt(35/(2.*pi))*cos_phi[2]*cos_theta[0]*std::pow(sin_theta[0],2))/4.;
data[18]=(-3*std::sqrt(5/pi)*cos_phi[1]*(3*sin_theta[0] + 7*sin_theta[2]))/16.;
data[19]=(-3*std::sqrt(5/(2.*pi))*cos_phi[0]*(9*cos_theta[0] + 7*cos_theta[2]))/16.;
data[20]=0;
data[21]=(3*std::sqrt(5/(2.*pi))*cos_theta[0]*(1 + 7*cos_theta[1])*sin_phi[0])/8.;
data[22]=(-3*std::sqrt(5/pi)*sin_phi[1]*(3*sin_theta[0] + 7*sin_theta[2]))/16.;
data[23]=(9*std::sqrt(35/(2.*pi))*cos_theta[0]*sin_phi[2]*std::pow(sin_theta[0],2))/4.;
data[24]=(-3*std::sqrt(35/pi)*sin_phi[3]*std::pow(sin_theta[0],3))/4.;
if (lmax==4) return;
data[25]=(-15*std::sqrt(77/(2.*pi))*cos_phi[4]*std::pow(sin_theta[0],4))/16.;
data[26]=(-3*std::sqrt(385/pi)*cos_phi[3]*cos_theta[0]*std::pow(sin_theta[0],3))/4.;
data[27]=(-3*std::sqrt(385/(2.*pi))*cos_phi[2]*(7 + 9*cos_theta[1])*std::pow(sin_theta[0],2))/32.;
data[28]=-(std::sqrt(1155/pi)*cos_phi[1]*(2*sin_theta[1] + 3*sin_theta[3]))/32.;
data[29]=-(std::sqrt(165/pi)*cos_phi[0]*(15 + 28*cos_theta[1] + 21*cos_theta[3]))/128.;
data[30]=0;
data[31]=(std::sqrt(165/pi)*(15 + 28*cos_theta[1] + 21*cos_theta[3])*sin_phi[0])/128.;
data[32]=-(std::sqrt(1155/pi)*sin_phi[1]*(2*sin_theta[1] + 3*sin_theta[3]))/32.;
data[33]=(3*std::sqrt(385/(2.*pi))*(7 + 9*cos_theta[1])*sin_phi[2]*std::pow(sin_theta[0],2))/32.;
data[34]=(-3*std::sqrt(385/pi)*cos_theta[0]*sin_phi[3]*std::pow(sin_theta[0],3))/4.;
data[35]=(15*std::sqrt(77/(2.*pi))*sin_phi[4]*std::pow(sin_theta[0],4))/16.;
if (lmax==5) return;
data[36]=(-3*std::sqrt(3003/(2.*pi))*cos_phi[5]*std::pow(sin_theta[0],5))/16.;
data[37]=(-15*std::sqrt(1001/(2.*pi))*cos_phi[4]*cos_theta[0]*std::pow(sin_theta[0],4))/16.;
data[38]=(-3*std::sqrt(91/pi)*cos_phi[3]*(9 + 11*cos_theta[1])*std::pow(sin_theta[0],3))/16.;
data[39]=(-3*std::sqrt(1365/(2.*pi))*cos_phi[2]*(21*cos_theta[0] + 11*cos_theta[2])*std::pow(sin_theta[0],2))/64.;
data[40]=-(std::sqrt(1365/(2.*pi))*cos_phi[1]*(10*sin_theta[0] + 27*sin_theta[2] + 33*sin_theta[4]))/256.;
data[41]=-(std::sqrt(273/pi)*cos_phi[0]*(50*cos_theta[0] + 45*cos_theta[2] + 33*cos_theta[4]))/256.;
data[42]=0;
data[43]=(std::sqrt(273/pi)*cos_theta[0]*(19 + 12*cos_theta[1] + 33*cos_theta[3])*sin_phi[0])/128.;
data[44]=-(std::sqrt(1365/(2.*pi))*sin_phi[1]*(10*sin_theta[0] + 27*sin_theta[2] + 33*sin_theta[4]))/256.;
data[45]=(3*std::sqrt(1365/(2.*pi))*cos_theta[0]*(5 + 11*cos_theta[1])*sin_phi[2]*std::pow(sin_theta[0],2))/32.;
data[46]=(-3*std::sqrt(91/pi)*(9 + 11*cos_theta[1])*sin_phi[3]*std::pow(sin_theta[0],3))/16.;
data[47]=(15*std::sqrt(1001/(2.*pi))*cos_theta[0]*sin_phi[4]*std::pow(sin_theta[0],4))/16.;
data[48]=(-3*std::sqrt(3003/(2.*pi))*sin_phi[5]*std::pow(sin_theta[0],5))/16.;
if (lmax==6) return;
data[49]=(-21*std::sqrt(715/pi)*cos_phi[6]*std::pow(sin_theta[0],6))/64.;
data[50]=(-9*std::sqrt(5005/(2.*pi))*cos_phi[5]*cos_theta[0]*std::pow(sin_theta[0],5))/16.;
data[51]=(-15*std::sqrt(385/pi)*cos_phi[4]*(11 + 13*cos_theta[1])*std::pow(sin_theta[0],4))/128.;
data[52]=(-3*std::sqrt(385/pi)*cos_phi[3]*(27*cos_theta[0] + 13*cos_theta[2])*std::pow(sin_theta[0],3))/32.;
data[53]=(-9*std::sqrt(35/pi)*cos_phi[2]*(189 + 308*cos_theta[1] + 143*cos_theta[3])*std::pow(sin_theta[0],2))/512.;
data[54]=(-3*std::sqrt(35/(2.*pi))*cos_phi[1]*(75*sin_theta[1] + 132*sin_theta[3] + 143*sin_theta[5]))/512.;
data[55]=-(std::sqrt(105/pi)*cos_phi[0]*(350 + 675*cos_theta[1] + 594*cos_theta[3] + 429*cos_theta[5]))/2048.;
data[56]=0;
data[57]=(std::sqrt(105/pi)*(350 + 675*cos_theta[1] + 594*cos_theta[3] + 429*cos_theta[5])*sin_phi[0])/2048.;
data[58]=(-3*std::sqrt(35/(2.*pi))*sin_phi[1]*(75*sin_theta[1] + 132*sin_theta[3] + 143*sin_theta[5]))/512.;
data[59]=(9*std::sqrt(35/pi)*(189 + 308*cos_theta[1] + 143*cos_theta[3])*sin_phi[2]*std::pow(sin_theta[0],2))/512.;
data[60]=(-3*std::sqrt(385/pi)*cos_theta[0]*(7 + 13*cos_theta[1])*sin_phi[3]*std::pow(sin_theta[0],3))/16.;
data[61]=(15*std::sqrt(385/pi)*(11 + 13*cos_theta[1])*sin_phi[4]*std::pow(sin_theta[0],4))/128.;
data[62]=(-9*std::sqrt(5005/(2.*pi))*cos_theta[0]*sin_phi[5]*std::pow(sin_theta[0],5))/16.;
data[63]=(21*std::sqrt(715/pi)*sin_phi[6]*std::pow(sin_theta[0],6))/64.;
if (lmax==7) return;
data[64]=(-3*std::sqrt(12155/pi)*cos_phi[7]*std::pow(sin_theta[0],7))/32.;
data[65]=(-21*std::sqrt(12155/pi)*cos_phi[6]*cos_theta[0]*std::pow(sin_theta[0],6))/64.;
data[66]=(-3*std::sqrt(7293/(2.*pi))*cos_phi[5]*(13 + 15*cos_theta[1])*std::pow(sin_theta[0],5))/64.;
data[67]=(-15*std::sqrt(17017/pi)*cos_phi[4]*(11*cos_theta[0] + 5*cos_theta[2])*std::pow(sin_theta[0],4))/256.;
data[68]=(-3*std::sqrt(1309/pi)*cos_phi[3]*(99 + 156*cos_theta[1] + 65*cos_theta[3])*std::pow(sin_theta[0],3))/256.;
data[69]=(-3*std::sqrt(19635/pi)*cos_phi[2]*(126*cos_theta[0] + 91*cos_theta[2] + 39*cos_theta[4])*std::pow(sin_theta[0],2))/1024.;
data[70]=(-3*std::sqrt(595/(2.*pi))*cos_phi[1]*(35*sin_theta[0] + 11*(9*sin_theta[2] + 13*(sin_theta[4] + sin_theta[6]))))/2048.;
data[71]=(-3*std::sqrt(17/pi)*cos_phi[0]*(1225*cos_theta[0] + 11*(105*cos_theta[2] + 91*cos_theta[4] + 65*cos_theta[6])))/4096.;
data[72]=0;
data[73]=(3*std::sqrt(17/pi)*cos_theta[0]*(178 + 869*cos_theta[1] + 286*cos_theta[3] + 715*cos_theta[5])*sin_phi[0])/2048.;
data[74]=(-3*std::sqrt(595/(2.*pi))*sin_phi[1]*(35*sin_theta[0] + 11*(9*sin_theta[2] + 13*(sin_theta[4] + sin_theta[6]))))/2048.;
data[75]=(3*std::sqrt(19635/pi)*cos_theta[0]*(37 + 52*cos_theta[1] + 39*cos_theta[3])*sin_phi[2]*std::pow(sin_theta[0],2))/512.;
data[76]=(-3*std::sqrt(1309/pi)*(99 + 156*cos_theta[1] + 65*cos_theta[3])*sin_phi[3]*std::pow(sin_theta[0],3))/256.;
data[77]=(15*std::sqrt(17017/pi)*(11*cos_theta[0] + 5*cos_theta[2])*sin_phi[4]*std::pow(sin_theta[0],4))/256.;
data[78]=(-3*std::sqrt(7293/(2.*pi))*(13 + 15*cos_theta[1])*sin_phi[5]*std::pow(sin_theta[0],5))/64.;
data[79]=(21*std::sqrt(12155/pi)*cos_theta[0]*sin_phi[6]*std::pow(sin_theta[0],6))/64.;
data[80]=(-3*std::sqrt(12155/pi)*sin_phi[7]*std::pow(sin_theta[0],7))/32.;
}
/// convert 3x3 transformation matrix to SU2 2x2 matrix
/// Create quaternion components from the 3x3 matrix. The components are just a w = Cos(\Omega/2)
/// and {x,y,z} = unit rotation vector multiplied by Sin[\Omega/2]
/// see https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
/// and https://en.wikipedia.org/wiki/Rotation_group_SO(3)#Quaternions_of_unit_norm
static mdarray<double_complex, 2> rotation_matrix_su2(const matrix3d<double>& m)
{
double det = m.det() > 0 ? 1.0 : -1.0;
matrix3d<double> mat = m * det;
mdarray<double_complex, 2> su2mat(2, 2);
su2mat.zero();
/* make quaternion components*/
double w = sqrt( std::max( 0., 1. + mat(0,0) + mat(1,1) + mat(2,2) ) ) / 2.;
double x = sqrt( std::max( 0., 1. + mat(0,0) - mat(1,1) - mat(2,2) ) ) / 2.;
double y = sqrt( std::max( 0., 1. - mat(0,0) + mat(1,1) - mat(2,2) ) ) / 2.;
double z = sqrt( std::max( 0., 1. - mat(0,0) - mat(1,1) + mat(2,2) ) ) / 2.;
x = std::copysign( x, mat(2,1) - mat(1,2) );
y = std::copysign( y, mat(0,2) - mat(2,0) );
z = std::copysign( z, mat(1,0) - mat(0,1) );
su2mat(0, 0) = double_complex( w, -z);
su2mat(1, 1) = double_complex( w, z);
su2mat(0, 1) = double_complex(-y, -x);
su2mat(1, 0) = double_complex( y, -x);
return std::move(su2mat);
}
/// Compute the derivatives of real spherical harmonics over the components of cartesian vector.
/** The following derivative is computed:
* \f[
* \frac{\partial R_{\ell m}(\theta_r, \phi_r)}{\partial r_{\mu}} =
* \frac{\partial R_{\ell m}(\theta_r, \phi_r)}{\partial \theta_r} \frac{\partial \theta_r}{\partial r_{\mu}} +
* \frac{\partial R_{\ell m}(\theta_r, \phi_r)}{\partial \phi_r} \frac{\partial \phi_r}{\partial r_{\mu}}
* \f]
* The derivatives of angles are:
* \f[
* \frac{\partial \theta_r}{\partial r_{x}} = \frac{\cos(\phi_r) \cos(\theta_r)}{r} \\
* \frac{\partial \theta_r}{\partial r_{y}} = \frac{\cos(\theta_r) \sin(\phi_r)}{r} \\
* \frac{\partial \theta_r}{\partial r_{z}} = -\frac{\sin(\theta_r)}{r}
* \f]
* and
* \f[
* \frac{\partial \phi_r}{\partial r_{x}} = -\frac{\sin(\phi_r)}{\sin(\theta_r) r} \\
* \frac{\partial \phi_r}{\partial r_{y}} = \frac{\cos(\phi_r)}{\sin(\theta_r) r} \\
* \frac{\partial \phi_r}{\partial r_{z}} = 0
* \f]
* The derivative of \f$ \phi \f$ has discontinuities at \f$ \theta = 0, \theta=\pi \f$. This, however, is not a problem, because
* multiplication by the the derivative of \f$ R_{\ell m} \f$ removes it. The following functions have to be hardcoded:
* \f[
* \frac{\partial R_{\ell m}(\theta, \phi)}{\partial \theta} \\
* \frac{\partial R_{\ell m}(\theta, \phi)}{\partial \phi} \frac{1}{\sin(\theta)}
* \f]
*
* Mathematica script for spherical harmonic derivatives:
\verbatim
Rlm[l_, m_, th_, ph_] :=
If[m > 0, Sqrt[2]*ComplexExpand[Re[SphericalHarmonicY[l, m, th, ph]]],
If[m < 0, Sqrt[2]*ComplexExpand[Im[SphericalHarmonicY[l, m, th, ph]]],
If[m == 0, ComplexExpand[Re[SphericalHarmonicY[l, 0, th, ph]]]]
]
]
Do[Print[FullSimplify[D[Rlm[l, m, theta, phi], theta]]], {l, 0, 4}, {m, -l, l}]
Do[Print[FullSimplify[TrigExpand[D[Rlm[l, m, theta, phi], phi]/Sin[theta]]]], {l, 0, 4}, {m, -l, l}]
\endverbatim
*/
static void dRlm_dr(int lmax__, vector3d<double>& r__, mdarray<double, 2>& data__)
{
/* get spherical coordinates of the Cartesian vector */
auto vrs = spherical_coordinates(r__);
if (vrs[0] < 1e-12) {
data__.zero();
return;
}
int lmmax = (lmax__ + 1) * (lmax__ + 1);
double theta = vrs[1];
double phi = vrs[2];
vector3d<double> dtheta_dr({std::cos(phi) * std::cos(theta), std::cos(theta) * std::sin(phi), -std::sin(theta)});
vector3d<double> dphi_dr({-std::sin(phi), std::cos(phi), 0.0});
mdarray<double, 1> dRlm_dt(lmmax);
mdarray<double, 1> dRlm_dp_sin_t(lmmax);
dRlm_dtheta(lmax__, theta, phi, dRlm_dt);
dRlm_dphi_sin_theta(lmax__, theta, phi, dRlm_dp_sin_t);
for (int mu = 0; mu < 3; mu++) {
for (int lm = 0; lm < lmmax; lm++) {
data__(lm, mu) = (dRlm_dt[lm] * dtheta_dr[mu] + dRlm_dp_sin_t[lm] * dphi_dr[mu]) / vrs[0];
}
}
}
/// Generate \f$ \cos(m x) \f$ for m in [1, n] using recursion.
static mdarray<double, 1> cosxn(int n__, double x__)
{
assert(n__ > 0);
mdarray<double, 1> data(n__);
data[0] = std::cos(x__);
if (n__ > 1) {
data[1] = std::cos(2 * x__);
for (int i = 2; i < n__; i++) {
data[i] = 2 * data[0] * data[i - 1] - data[i - 2];
}
}
return std::move(data);
}
/// Generate \f$ \sin(m x) \f$ for m in [1, n] using recursion.
static mdarray<double, 1> sinxn(int n__, double x__)
{
assert(n__ > 0);
mdarray<double, 1> data(n__);
auto cosx = std::cos(x__);
data[0] = std::sin(x__);
if (n__ > 1) {
data[1] = std::sin(2 * x__);
for (int i = 2; i < n__; i++) {
data[i] = 2 * cosx * data[i - 1] - data[i - 2];
}
}
return std::move(data);
}
};
template <>
inline void SHT::backward_transform<double>(int ld, double const* flm, int nr, int lmmax, double* ftp)
{
assert(lmmax <= lmmax_);
assert(ld >= lmmax);
linalg<CPU>::gemm(1, 0, num_points_, nr, lmmax, &rlm_backward_(0, 0), lmmax_, flm, ld, ftp, num_points_);
}
template <>
inline void SHT::backward_transform<double_complex>(int ld, double_complex const* flm, int nr, int lmmax, double_complex* ftp)
{
assert(lmmax <= lmmax_);
assert(ld >= lmmax);
linalg<CPU>::gemm(1, 0, num_points_, nr, lmmax, &ylm_backward_(0, 0), lmmax_, flm, ld, ftp, num_points_);
}
template <>
inline void SHT::forward_transform<double>(double const* ftp, int nr, int lmmax, int ld, double* flm)
{
assert(lmmax <= lmmax_);
assert(ld >= lmmax);
linalg<CPU>::gemm(1, 0, lmmax, nr, num_points_, &rlm_forward_(0, 0), num_points_, ftp, num_points_, flm, ld);
}
template <>
inline void SHT::forward_transform<double_complex>(double_complex const* ftp, int nr, int lmmax, int ld, double_complex* flm)
{
assert(lmmax <= lmmax_);
assert(ld >= lmmax);
linalg<CPU>::gemm(1, 0, lmmax, nr, num_points_, &ylm_forward_(0, 0), num_points_, ftp, num_points_, flm, ld);
}
}
#endif // __SHT_H__
| {
"alphanum_fraction": 0.4894596922,
"avg_line_length": 41.8605015674,
"ext": "h",
"hexsha": "ba9e0c7b24a9bab75cee5df44dbe70b50275233d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "ckae95/SIRIUS",
"max_forks_repo_path": "src/sht.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "ckae95/SIRIUS",
"max_issues_repo_path": "src/sht.h",
"max_line_length": 146,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ecb7edb4f19577c85b0cec82aa6a0d5374ee1f33",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "ckae95/SIRIUS",
"max_stars_repo_path": "src/sht.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 17201,
"size": 53414
} |
/*
* A rng module implementation which can return a sample as an array.
* Author : Pierre Schnizer <schnizer@users.sourceforge.net>
* Date : 1. July. 2003
*
*/
#include <pygsl/error_helpers.h>
#include <pygsl/block_helpers.h>
#include <pygsl/utils.h>
#ifdef PyGSL_NO_IMPORT_API
#undef PyGSL_NO_IMPORT_API
#endif
#include <pygsl/rng_helpers.h>
#include <pygsl/rng.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/*
* All doc strings
*/
static PyObject *module = NULL;
#include "rng_helpers.c"
#include "rngmodule_docs.h"
static void rng_delete(PyGSL_rng *self);
static PyObject * rng_call(PyGSL_rng *self, PyObject *args);
#undef PyGSL_RNG_Check
#define PyGSL_RNG_Check(op) ((op)->ob_type == &PyGSL_rng_pytype)
static PyObject * /* on "instance.attr" */
rng_getattr (PyGSL_rng *self, char *name);
PyTypeObject PyGSL_rng_pytype = {
PyObject_HEAD_INIT(NULL) /* fix up the type slot in initcrng */
0, /* ob_size */
"PyGSL_rng", /* tp_name */
sizeof(PyGSL_rng), /* tp_basicsize */
0, /* tp_itemsize */
/* standard methods */
(destructor) rng_delete, /* tp_dealloc ref-count==0 */
(printfunc) 0, /* tp_print "print x" */
(getattrfunc) rng_getattr, /* tp_getattr "x.attr" */
(setattrfunc) 0, /* tp_setattr "x.attr=v" */
(cmpfunc) 0, /* tp_compare "x > y" */
(reprfunc) 0, /* tp_repr `x`, print x */
/* type categories */
0, /* tp_as_number +,-,*,/,%,&,>>,pow...*/
0, /* tp_as_sequence +,[i],[i:j],len, ...*/
0, /* tp_as_mapping [key], len, ...*/
/* more methods */
(hashfunc) 0, /* tp_hash "dict[x]" */
(ternaryfunc) rng_call, /* tp_call "x()" */
(reprfunc) 0, /* tp_str "str(x)" */
(getattrofunc) 0, /* tp_getattro */
(setattrofunc) 0, /* tp_setattro */
0, /* tp_as_buffer */
0L, /* tp_flags */
rng_type_doc /* tp_doc */
};
static PyObject *
PyGSL_rng_init(PyObject *self, PyObject *args, const gsl_rng_type * rng_type)
{
PyGSL_rng *rng = NULL;
FUNC_MESS_BEGIN();
rng = (PyGSL_rng *) PyObject_NEW(PyGSL_rng, &PyGSL_rng_pytype);
if(rng == NULL){
return NULL;
}
if(rng_type == NULL){
rng->rng = gsl_rng_alloc(gsl_rng_default);
gsl_rng_set(rng->rng, gsl_rng_default_seed);
}else{
rng->rng = gsl_rng_alloc(rng_type);
}
FUNC_MESS_END();
return (PyObject *) rng;
}
#define RNG_ARNG(name) \
static PyObject* PyGSL_rng_init_ ## name (PyObject *self, PyObject *args) \
{ \
PyObject *tmp = NULL; \
FUNC_MESS_BEGIN(); \
tmp = PyGSL_rng_init(self, args, gsl_rng_ ## name); \
if (tmp == NULL){ \
PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \
} \
FUNC_MESS_END(); \
return tmp; \
}
#include "rng_list.h"
static PyObject *
PyGSL_rng_init_default(PyObject *self, PyObject *args)
{
PyObject *tmp = NULL;
FUNC_MESS_BEGIN();
tmp = PyGSL_rng_init(self, args, NULL);
if (tmp == NULL){
PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__ - 1);
}
FUNC_MESS_END();
return tmp;
}
static void
rng_delete(PyGSL_rng *self)
{
FUNC_MESS_BEGIN();
assert(PyGSL_RNG_Check(self));
if(self->rng != NULL){
DEBUG_MESS(5, "Freeing gsl_rng @ %p", self->rng);
gsl_rng_free(self->rng);
self->rng = NULL;
}
DEBUG_MESS(1, " self %p\n",(void *) self);
PyObject_Del(self);
self = NULL;
FUNC_MESS_END();
}
static PyObject * /* on "instance.uniform()" and "instance()" */
rng_call (PyGSL_rng *self, PyObject *args)
{
PyObject *tmp;
FUNC_MESS_BEGIN();
assert(PyGSL_RNG_Check(self));
tmp = PyGSL_rng_to_double(self, args, gsl_rng_uniform);
if(!tmp)
PyGSL_add_traceback(module, __FILE__, "rng.__call__", __LINE__ - 2);
FUNC_MESS_END();
return tmp;
}
static PyObject *
rng_uniform_pos (PyGSL_rng *self, PyObject *args)
{
PyObject *tmp;
FUNC_MESS_BEGIN();
assert(PyGSL_RNG_Check(self));
tmp = PyGSL_rng_to_double(self, args, gsl_rng_uniform_pos);
if(!tmp)
PyGSL_add_traceback(module, __FILE__, "rng.uniform_pos", __LINE__-2);
FUNC_MESS_END();
return tmp;
}
static PyObject *
rng_uniform_int (PyGSL_rng *self, PyObject *args)
{
PyObject *tmp = NULL;
FUNC_MESS_BEGIN();
assert(PyGSL_RNG_Check(self));
tmp = PyGSL_rng_ul_to_ulong(self, args, gsl_rng_uniform_int);
if(!tmp)
PyGSL_add_traceback(module, __FILE__, "rng.uniform_int", __LINE__-2);
FUNC_MESS_END();
return tmp;
}
static PyObject *
rng_get(PyGSL_rng *self, PyObject *args)
{
PyObject *tmp = NULL;
FUNC_MESS_BEGIN();
assert(PyGSL_RNG_Check(self));
tmp = PyGSL_rng_to_ulong(self, args, gsl_rng_get);
if(!tmp)
PyGSL_add_traceback(module, __FILE__, "rng.get", __LINE__ - 2);
FUNC_MESS_END();
return tmp;
}
static PyObject *
rng_set(PyGSL_rng *self, PyObject *args)
{
PyObject *tmp = NULL, *seed = NULL;
unsigned long int useed;
int lineno;
FUNC_MESS_BEGIN();
assert(PyGSL_RNG_Check(self));
if(0 == PyArg_ParseTuple(args, "O", &tmp)){
lineno = __LINE__; goto fail;
}
assert(tmp != NULL);
seed = PyNumber_Long(tmp);
if(!seed){lineno = __LINE__ - 1; goto fail;}
useed = PyLong_AsUnsignedLong(seed);
gsl_rng_set(self->rng, useed);
Py_INCREF(Py_None);
FUNC_MESS_END();
return Py_None;
fail:
FUNC_MESS("FAIL");
PyGSL_add_traceback(module, __FILE__, "rng.set", lineno);
return NULL;
}
static PyObject *
rng_name(PyGSL_rng *self, PyObject *args)
{
PyObject *tmp = NULL;
FUNC_MESS_BEGIN();
assert(PyGSL_RNG_Check(self));
if(0 == PyArg_ParseTuple(args, ":name"))
return NULL;
tmp = PyString_FromString(gsl_rng_name(self->rng));
FUNC_MESS_END();
return tmp;
}
static PyObject *
rng_max(PyGSL_rng *self, PyObject *args)
{
PyObject *tmp = NULL;
FUNC_MESS_BEGIN();
assert(PyGSL_RNG_Check(self));
if(0 == PyArg_ParseTuple(args, ":max"))
return NULL;
tmp = PyLong_FromUnsignedLong(gsl_rng_max(self->rng));
FUNC_MESS_END();
return tmp;
}
static PyObject *
rng_min(PyGSL_rng *self, PyObject *args)
{
PyObject *tmp = NULL;
FUNC_MESS_BEGIN();
assert(PyGSL_RNG_Check(self));
if(0 == PyArg_ParseTuple(args, ":min"))
return NULL;
tmp = PyLong_FromUnsignedLong(gsl_rng_min(self->rng));
FUNC_MESS_END();
return tmp;
}
static PyObject *
rng_clone(PyGSL_rng *self, PyObject *args)
{
PyGSL_rng * rng = NULL;
FUNC_MESS_BEGIN();
assert(PyGSL_RNG_Check(self));
if(0 == PyArg_ParseTuple(args, ":clone"))
return NULL;
rng = (PyGSL_rng *) PyObject_NEW(PyGSL_rng, &PyGSL_rng_pytype);
rng->rng = gsl_rng_clone(self->rng);
FUNC_MESS_END();
return (PyObject *) rng;
}
/*
* Is #name a standard macro definition?
*/
#define RNG_DISTRIBUTION(name, function) \
static PyObject* rng_ ## name (PyGSL_rng *self, PyObject *args) \
{ \
PyObject *tmp = NULL; \
FUNC_MESS_BEGIN(); \
tmp = PyGSL_rng_ ## function (self, args, gsl_ran_ ## name); \
if (tmp == NULL){ \
/* PyGSL_add_traceback(module, __FILE__, "rng." #name, __LINE__); */ \
PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \
} \
FUNC_MESS_END(); \
return tmp; \
}
#include "rng_distributions.h"
/* Redefine to trigger emacs into correct coloring */
/*
* This list is not optimized. I guess... Do you know how to optimize it?
*/
static struct PyMethodDef rng_methods[] = {
{"get", (PyCFunction) rng_get, METH_VARARGS, rng_get_doc},
{"set", (PyCFunction) rng_set, METH_VARARGS, rng_set_doc},
{"uniform", (PyCFunction) rng_call, METH_VARARGS, rng_uniform_doc},
{"uniform_pos", (PyCFunction) rng_uniform_pos, METH_VARARGS, rng_uniform_pos_doc},
{"uniform_int", (PyCFunction) rng_uniform_int, METH_VARARGS, rng_uniform_int_doc},
{"name", (PyCFunction) rng_name, METH_VARARGS, NULL},
{"max", (PyCFunction) rng_max, METH_VARARGS, rng_max_doc},
{"min", (PyCFunction) rng_min, METH_VARARGS, rng_min_doc},
{"clone", (PyCFunction) rng_clone, METH_VARARGS, rng_clone_doc},
#if (PY_MAJOR_VERSION == 2) && (PY_MINOR_VERSION == 3)
/* RNG clone can not be used to copy a rng type in python 2.3 No idea how to do that correctly */
#else
{"__copy__", (PyCFunction) rng_clone, METH_VARARGS, rng_clone_doc},
#endif
/* distributions */
{"gaussian", (PyCFunction) rng_gaussian,METH_VARARGS, rng_gaussian_doc},
{"gaussian_ratio_method", (PyCFunction) rng_gaussian_ratio_method,METH_VARARGS, rng_gaussian_ratio_doc},
{"ugaussian", (PyCFunction) rng_ugaussian,METH_VARARGS, rng_ugaussian_doc},
{"ugaussian_ratio_method",(PyCFunction) rng_ugaussian_ratio_method,METH_VARARGS, rng_ugaussian_ratio_doc},
{"gaussian_tail", (PyCFunction) rng_gaussian_tail,METH_VARARGS, rng_gaussian_tail_doc},
{"ugaussian_tail",(PyCFunction) rng_ugaussian_tail,METH_VARARGS, rng_ugaussian_tail_doc},
{"bivariate_gaussian", (PyCFunction) rng_bivariate_gaussian,METH_VARARGS, rng_bivariate_gaussian_doc},
{"exponential",(PyCFunction)rng_exponential,METH_VARARGS, rng_exponential_doc},
{"laplace",(PyCFunction)rng_laplace,METH_VARARGS, rng_laplace_doc},
{"exppow",(PyCFunction)rng_exppow,METH_VARARGS, rng_exppow_doc},
{"cauchy",(PyCFunction)rng_cauchy,METH_VARARGS, rng_cauchy_doc},
{"rayleigh",(PyCFunction)rng_rayleigh,METH_VARARGS, rng_rayleigh_doc},
{"rayleigh_tail",(PyCFunction)rng_rayleigh_tail,METH_VARARGS, rng_rayleigh_tail_doc},
{"levy",(PyCFunction)rng_levy,METH_VARARGS, rng_levy_doc},
{"levy_skew",(PyCFunction)rng_levy_skew,METH_VARARGS, rng_levy_skew_doc},
{"gamma",(PyCFunction)rng_gamma,METH_VARARGS, rng_gamma_doc},
{"gamma_int",(PyCFunction)rng_gamma_int,METH_VARARGS, NULL},
{"flat",(PyCFunction)rng_flat,METH_VARARGS, rng_flat_doc},
{"lognormal",(PyCFunction)rng_lognormal,METH_VARARGS, rng_lognormal_doc},
{"chisq",(PyCFunction)rng_chisq,METH_VARARGS, rng_chisq_doc},
{"fdist",(PyCFunction)rng_fdist,METH_VARARGS, rng_fdist_doc},
{"tdist",(PyCFunction)rng_tdist,METH_VARARGS, rng_tdist_doc},
{"beta",(PyCFunction)rng_beta,METH_VARARGS, rng_beta_doc},
{"logistic",(PyCFunction)rng_logistic,METH_VARARGS, rng_logistic_doc},
{"pareto",(PyCFunction)rng_pareto,METH_VARARGS, rng_pareto_doc},
{"dir_2d",(PyCFunction)rng_dir_2d,METH_VARARGS, rng_dir_2d_doc},
{"dir_2d_trig_method",(PyCFunction)rng_dir_2d_trig_method,METH_VARARGS, rng_dir_2d_trig_method_doc},
{"dir_3d",(PyCFunction)rng_dir_3d,METH_VARARGS, rng_dir_3d_doc},
{"dir_nd",(PyCFunction)rng_dir_nd,METH_VARARGS, rng_dir_nd_doc},
{"weibull",(PyCFunction)rng_weibull,METH_VARARGS, rng_weibull_doc},
{"gumbel1",(PyCFunction)rng_gumbel1,METH_VARARGS, rng_gumbel1_doc},
{"gumbel2",(PyCFunction)rng_gumbel2,METH_VARARGS, rng_gumbel2_doc},
{"poisson",(PyCFunction)rng_poisson,METH_VARARGS, rng_poisson_doc},
{"bernoulli",(PyCFunction)rng_bernoulli,METH_VARARGS, rng_bernoulli_doc},
{"binomial",(PyCFunction)rng_binomial,METH_VARARGS, rng_binomial_doc},
{"negative_binomial",(PyCFunction)rng_negative_binomial,METH_VARARGS, rng_negative_binomial_doc},
{"pascal",(PyCFunction)rng_pascal,METH_VARARGS, rng_pascal_doc},
{"geometric",(PyCFunction)rng_geometric,METH_VARARGS, rng_geometric_doc},
{"hypergeometric",(PyCFunction)rng_hypergeometric,METH_VARARGS, rng_hypergeometric_doc},
{"logarithmic",(PyCFunction)rng_logarithmic,METH_VARARGS, rng_logarithmic_doc},
{"landau",(PyCFunction)rng_landau,METH_VARARGS, rng_landau_doc},
{"erlang",(PyCFunction)rng_erlang,METH_VARARGS, NULL},
{"multinomial",(PyCFunction)rng_multinomial,METH_VARARGS, multinomial_doc},
{"dirichlet",(PyCFunction)rng_dirichlet,METH_VARARGS, rng_dirichlet_doc},
{NULL, NULL,}
};
static PyObject *
rng_getattr(PyGSL_rng *self, char *name)
{
PyObject *tmp = NULL;
FUNC_MESS_BEGIN();
assert(PyGSL_RNG_Check(self));
tmp = Py_FindMethod(rng_methods, (PyObject *) self, name);
if(NULL == tmp){
PyGSL_add_traceback(module, __FILE__, "rng.__attr__", __LINE__ - 1);
return NULL;
}
return tmp;
}
static PyObject *
rng_create_list(PyObject *self, PyObject *args)
{
const gsl_rng_type** thisRNGType=gsl_rng_types_setup();
PyObject* list = NULL, *item=NULL;
FUNC_MESS_BEGIN();
/* provide other rng types as subclasses of rng */
list = PyList_New(0);
while ((*thisRNGType)!=NULL) {
item = PyString_FromString((*thisRNGType)->name);
Py_INCREF(item);
assert(item);
PyGSL_clear_name(PyString_AsString(item), PyString_Size(item));
if(PyList_Append(list, item) != 0)
goto fail;
thisRNGType++;
}
FUNC_MESS_END();
return list;
fail:
Py_XDECREF(list);
Py_XDECREF(item);
return NULL;
}
/*---------------------------------------------------------------------------*/
/* Module set up */
#define RNG_GENERATE_PDF
#undef RNG_DISTRIBUTION
#define RNG_DISTRIBUTION(name, function) \
static PyObject* rng_ ## name ## _pdf (PyObject *self, PyObject *args) \
{ \
PyObject * tmp; \
FUNC_MESS_BEGIN(); \
tmp = PyGSL_pdf_ ## function (self, args, gsl_ran_ ## name ## _pdf); \
if (tmp == NULL){ \
PyGSL_add_traceback(module, __FILE__, #name "_pdf", __LINE__); \
} \
FUNC_MESS_END(); \
return tmp; \
}
#include "rng_distributions.h"
static PyObject* rng_dirichlet_lnpdf (PyObject *self, PyObject *args)
{
PyObject *tmp;
FUNC_MESS_BEGIN();
tmp = PyGSL_pdf_dA_to_dA(self, args, gsl_ran_dirichlet_lnpdf);
FUNC_MESS_END();
return tmp;
}
static PyObject* rng_multinomial_lnpdf (PyObject *self, PyObject *args)
{
PyObject *tmp;
FUNC_MESS_BEGIN();
tmp = PyGSL_pdf_uidA_to_uiA(self, args, gsl_ran_multinomial_lnpdf);
FUNC_MESS_END();
return tmp;
}
static const char rng_env_setup_doc[] =
"This function reads the environment variables `GSL_RNG_TYPE' and\n\
`GSL_RNG_SEED'.\n\
The environment variable `GSL_RNG_TYPE' should be the name of a\n\
generator, such as `taus' or `mt19937'. The environment variable\n\
`GSL_RNG_SEED' should contain the desired seed value. It is\n\
converted to an `unsigned long int' using the C library function\n\
`strtoul'.\n";
static PyObject *
PyGSL_rng_env_setup(PyObject *self, PyObject *args)
{
gsl_rng_env_setup();
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef PyGSL_rng_module_functions[] = {
{"borosh13" , PyGSL_rng_init_borosh13 , METH_NOARGS, NULL},
{"cmrg" , PyGSL_rng_init_cmrg , METH_NOARGS, NULL},
{"coveyou" , PyGSL_rng_init_coveyou , METH_NOARGS, NULL},
{"fishman18" , PyGSL_rng_init_fishman18 , METH_NOARGS, NULL},
{"fishman20" , PyGSL_rng_init_fishman20 , METH_NOARGS, NULL},
{"fishman2x" , PyGSL_rng_init_fishman2x , METH_NOARGS, NULL},
{"gfsr4" , PyGSL_rng_init_gfsr4 , METH_NOARGS, NULL},
{"knuthran" , PyGSL_rng_init_knuthran , METH_NOARGS, NULL},
{"knuthran2" , PyGSL_rng_init_knuthran2 , METH_NOARGS, NULL},
#ifdef _PYGSL_GSL_HAS_RNG_KNUTHRAN2002
{"knuthran2002" , PyGSL_rng_init_knuthran2002 , METH_NOARGS, NULL},
#endif
{"lecuyer21" , PyGSL_rng_init_lecuyer21 , METH_NOARGS, NULL},
{"minstd" , PyGSL_rng_init_minstd , METH_NOARGS, NULL},
{"mrg" , PyGSL_rng_init_mrg , METH_NOARGS, NULL},
{"mt19937" , PyGSL_rng_init_mt19937 , METH_NOARGS, NULL},
{"mt19937_1999" , PyGSL_rng_init_mt19937_1999 , METH_NOARGS, NULL},
{"mt19937_1998" , PyGSL_rng_init_mt19937_1998 , METH_NOARGS, NULL},
{"r250" , PyGSL_rng_init_r250 , METH_NOARGS, NULL},
{"ran0" , PyGSL_rng_init_ran0 , METH_NOARGS, NULL},
{"ran1" , PyGSL_rng_init_ran1 , METH_NOARGS, NULL},
{"ran2" , PyGSL_rng_init_ran2 , METH_NOARGS, NULL},
{"ran3" , PyGSL_rng_init_ran3 , METH_NOARGS, NULL},
{"rand" , PyGSL_rng_init_rand , METH_NOARGS, NULL},
{"rand48" , PyGSL_rng_init_rand48 , METH_NOARGS, NULL},
{"random128_bsd" , PyGSL_rng_init_random128_bsd , METH_NOARGS, NULL},
{"random128_glibc2", PyGSL_rng_init_random128_glibc2, METH_NOARGS, NULL},
{"random128_libc5" , PyGSL_rng_init_random128_libc5 , METH_NOARGS, NULL},
{"random256_bsd" , PyGSL_rng_init_random256_bsd , METH_NOARGS, NULL},
{"random256_glibc2", PyGSL_rng_init_random256_glibc2, METH_NOARGS, NULL},
{"random256_libc5" , PyGSL_rng_init_random256_libc5 , METH_NOARGS, NULL},
{"random32_bsd" , PyGSL_rng_init_random32_bsd , METH_NOARGS, NULL},
{"random32_glibc2" , PyGSL_rng_init_random32_glibc2 , METH_NOARGS, NULL},
{"random32_libc5" , PyGSL_rng_init_random32_libc5 , METH_NOARGS, NULL},
{"random64_bsd" , PyGSL_rng_init_random64_bsd , METH_NOARGS, NULL},
{"random64_glibc2" , PyGSL_rng_init_random64_glibc2 , METH_NOARGS, NULL},
{"random64_libc5" , PyGSL_rng_init_random64_libc5 , METH_NOARGS, NULL},
{"random8_bsd" , PyGSL_rng_init_random8_bsd , METH_NOARGS, NULL},
{"random8_glibc2" , PyGSL_rng_init_random8_glibc2 , METH_NOARGS, NULL},
{"random8_libc5" , PyGSL_rng_init_random8_libc5 , METH_NOARGS, NULL},
{"random_bsd" , PyGSL_rng_init_random_bsd , METH_NOARGS, NULL},
{"random_glibc2" , PyGSL_rng_init_random_glibc2 , METH_NOARGS, NULL},
{"random_libc5" , PyGSL_rng_init_random_libc5 , METH_NOARGS, NULL},
{"randu" , PyGSL_rng_init_randu , METH_NOARGS, NULL},
{"ranf" , PyGSL_rng_init_ranf , METH_NOARGS, NULL},
{"ranlux" , PyGSL_rng_init_ranlux , METH_NOARGS, NULL},
{"ranlux389" , PyGSL_rng_init_ranlux389 , METH_NOARGS, NULL},
{"ranlxd1" , PyGSL_rng_init_ranlxd1 , METH_NOARGS, NULL},
{"ranlxd2" , PyGSL_rng_init_ranlxd2 , METH_NOARGS, NULL},
{"ranlxs0" , PyGSL_rng_init_ranlxs0 , METH_NOARGS, NULL},
{"ranlxs1" , PyGSL_rng_init_ranlxs1 , METH_NOARGS, NULL},
{"ranlxs2" , PyGSL_rng_init_ranlxs2 , METH_NOARGS, NULL},
{"ranmar" , PyGSL_rng_init_ranmar , METH_NOARGS, NULL},
{"slatec" , PyGSL_rng_init_slatec , METH_NOARGS, NULL},
{"taus" , PyGSL_rng_init_taus , METH_NOARGS, NULL},
{"taus2" , PyGSL_rng_init_taus2 , METH_NOARGS, NULL},
{"taus113" , PyGSL_rng_init_taus113 , METH_NOARGS, NULL},
{"transputer" , PyGSL_rng_init_transputer , METH_NOARGS, NULL},
{"tt800" , PyGSL_rng_init_tt800 , METH_NOARGS, NULL},
{"uni" , PyGSL_rng_init_uni , METH_NOARGS, NULL},
{"uni32" , PyGSL_rng_init_uni32 , METH_NOARGS, NULL},
{"vax" , PyGSL_rng_init_vax , METH_NOARGS, NULL},
{"waterman14" , PyGSL_rng_init_waterman14 , METH_NOARGS, NULL},
{"zuf" , PyGSL_rng_init_zuf , METH_NOARGS, NULL},
{"rng", PyGSL_rng_init_default, METH_NOARGS, rng_doc},
{"list_available_rngs", rng_create_list, METH_VARARGS},
/*densities*/
{"gaussian_pdf",rng_gaussian_pdf,METH_VARARGS, rng_gaussian_pdf_doc},
{"ugaussian_pdf",rng_ugaussian_pdf,METH_VARARGS, rng_ugaussian_pdf_doc},
{"gaussian_tail_pdf",rng_gaussian_tail_pdf,METH_VARARGS, rng_gaussian_tail_pdf_doc},
{"ugaussian_tail_pdf",rng_ugaussian_tail_pdf,METH_VARARGS, rng_ugaussian_tail_pdf_doc},
{"bivariate_gaussian_pdf",rng_bivariate_gaussian_pdf,METH_VARARGS, rng_bivariate_gaussian_pdf_doc},
{"exponential_pdf",rng_exponential_pdf,METH_VARARGS, rng_exponential_pdf_doc},
{"laplace_pdf",rng_laplace_pdf,METH_VARARGS, rng_laplace_pdf_doc},
{"exppow_pdf",rng_exppow_pdf,METH_VARARGS, rng_exppow_pdf_doc},
{"cauchy_pdf",rng_cauchy_pdf,METH_VARARGS, rng_cauchy_pdf_doc},
{"rayleigh_pdf",rng_rayleigh_pdf,METH_VARARGS, rng_rayleigh_pdf_doc},
{"rayleigh_tail_pdf",rng_rayleigh_tail_pdf,METH_VARARGS, rng_rayleigh_tail_pdf_doc},
{"gamma_pdf",rng_gamma_pdf,METH_VARARGS, rng_gamma_pdf_doc},
{"flat_pdf",rng_flat_pdf,METH_VARARGS, rng_flat_pdf_doc},
{"lognormal_pdf",rng_lognormal_pdf,METH_VARARGS, rng_lognormal_pdf_doc},
{"chisq_pdf",rng_chisq_pdf,METH_VARARGS, rng_chisq_pdf_doc},
{"fdist_pdf",rng_fdist_pdf,METH_VARARGS, rng_fdist_pdf_doc},
{"tdist_pdf",rng_tdist_pdf,METH_VARARGS, rng_tdist_pdf_doc},
{"beta_pdf",rng_beta_pdf,METH_VARARGS, rng_beta_pdf_doc},
{"logistic_pdf",rng_logistic_pdf,METH_VARARGS, rng_logistic_pdf_doc},
{"pareto_pdf",rng_pareto_pdf,METH_VARARGS, rng_pareto_pdf_doc},
{"weibull_pdf",rng_weibull_pdf,METH_VARARGS, rng_weibull_pdf_doc},
{"gumbel1_pdf",rng_gumbel1_pdf,METH_VARARGS, rng_gumbel1_pdf_doc},
{"gumbel2_pdf",rng_gumbel2_pdf,METH_VARARGS, rng_gumbel2_pdf_doc},
{"poisson_pdf",rng_poisson_pdf,METH_VARARGS, rng_poisson_pdf_doc},
{"bernoulli_pdf",rng_bernoulli_pdf,METH_VARARGS, rng_bernoulli_pdf_doc},
{"binomial_pdf",rng_binomial_pdf,METH_VARARGS, rng_binomial_pdf_doc},
{"negative_binomial_pdf",rng_negative_binomial_pdf,METH_VARARGS, rng_negative_binomial_pdf_doc},
{"pascal_pdf",rng_pascal_pdf,METH_VARARGS, rng_pascal_pdf_doc},
{"geometric_pdf",rng_geometric_pdf,METH_VARARGS, rng_geometric_pdf_doc},
{"hypergeometric_pdf",rng_hypergeometric_pdf,METH_VARARGS, rng_hypergeometric_pdf_doc},
{"logarithmic_pdf",rng_logarithmic_pdf,METH_VARARGS, rng_logarithmic_pdf_doc},
{"landau_pdf",rng_landau_pdf,METH_VARARGS, rng_landau_pdf_doc},
{"erlang_pdf",rng_erlang_pdf,METH_VARARGS, NULL},
{"multinomial_pdf",rng_multinomial_pdf,METH_VARARGS,multinomial_pdf_doc},
{"dirichlet_pdf",rng_dirichlet_pdf,METH_VARARGS, rng_dirichlet_pdf_doc},
{"multinomial_lnpdf",rng_multinomial_lnpdf,METH_VARARGS, NULL},
{"dirichlet_lnpdf",rng_dirichlet_lnpdf,METH_VARARGS, rng_dirichlet_lnpdf_doc},
{"env_setup",PyGSL_rng_env_setup,METH_NOARGS, (char*) rng_env_setup_doc},
{NULL, NULL, 0} /* Sentinel */
};
static void
set_api_pointer(void)
{
FUNC_MESS_BEGIN();
PyGSL_API[PyGSL_RNG_ObjectType_NUM] = (void *) &PyGSL_rng_pytype;
DEBUG_MESS(2, "__PyGSL_RNG_API @ %p, ", (void *) PyGSL_API);
DEBUG_MESS(2, "PyGSL_rng_pytype @ %p, ", (void *) &PyGSL_rng_pytype);
/* fprintf(stderr, "__PyGSL_RNG_API @ %p\n", (void *) __PyGSL_RNG_API); */
FUNC_MESS_END();
}
void
initrng(void)
{
PyObject *m=NULL, *item=NULL, *dict=NULL;
PyObject *api=NULL;
m = Py_InitModule("rng", PyGSL_rng_module_functions);
assert(m);
/* import_array(); */
init_pygsl();
/* create_rng_types(m); */
module = m;
dict = PyModule_GetDict(m);
if(!dict)
goto fail;
if (!(item = PyString_FromString(rng_module_doc))){
PyErr_SetString(PyExc_ImportError,
"I could not generate module doc string!");
goto fail;
}
if (PyDict_SetItemString(dict, "__doc__", item) != 0){
PyErr_SetString(PyExc_ImportError,
"I could not init doc string!");
goto fail;
}
PyGSL_rng_pytype.ob_type = &PyType_Type;
set_api_pointer();
api = PyCObject_FromVoidPtr((void *) PyGSL_API, NULL);
assert(api);
if (PyDict_SetItemString(dict, "_PYGSL_RNG_API", api) != 0){
PyErr_SetString(PyExc_ImportError,
"I could not add _PYGSL_RNG_API!");
goto fail;
}
return;
fail:
if(!PyErr_Occurred()){
PyErr_SetString(PyExc_ImportError, "I could not init rng module!");
}
}
| {
"alphanum_fraction": 0.6275971267,
"avg_line_length": 40.6499215071,
"ext": "c",
"hexsha": "80bbc24c799fb146544aa4fd510b56fa5075ac1a",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/src/rng/rngmodule.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/src/rng/rngmodule.c",
"max_line_length": 108,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/src/rng/rngmodule.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7305,
"size": 25894
} |
#include <viaio/VImage.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <viaio/Vlib.h>
#include "gsl_utils.h"
void whitecov(VImage rho_vol, gsl_matrix_float *Y,
gsl_matrix_float* invM, gsl_matrix_float* pinvX,
gsl_matrix_float* X, int numlags, int slice)
{
/* set up variables */
int n = Y->size1;
/* these values represent the matlab interval 2:n */
int k1 = 1;
int k2 = n-1;
/* loop counter */
int i,j;
/* matrix buffers */
gsl_matrix_float *result,*buffer;
/* : X^T */
gsl_matrix_float* transX = gsl_matrix_float_alloc(X->size2,X->size1);
gsl_matrix_float_transpose_memcpy(transX,X);
/* : betahat_ls = pinvX * Y; */
gsl_matrix_float* betahat_ls = fmat_x_mat(pinvX, Y, NULL);
/* gsl_blas_sgemm(CblasNoTrans,CblasNoTrans,1.0,pinvX,Y,0.0,betahat_ls); */
/* : resid = Y - X' * betahat_ls; */
result = fmat_x_mat(transX, betahat_ls, NULL);
gsl_matrix_float_sub(Y,result);
gsl_matrix_float_free(result);
/* rename */
gsl_matrix_float* resid = Y;
if (numlags == 1) {
/* : Cov0=sum(resid.*resid,1); */
result = gsl_matrix_float_alloc(resid->size1, resid->size2);
gsl_matrix_float_memcpy (result, resid);
gsl_matrix_float_mul_elements (result, result);
gsl_vector_float* Cov0 = fsum(result, 1,NULL);
gsl_matrix_float_free(result);
/* : Cov1=sum(resid(k1,:).*resid(k1-1,:),1); */
gsl_matrix_float_view sub1 =
gsl_matrix_float_submatrix(resid, k1,0,k2,resid->size2);
gsl_matrix_float_view sub2 =
gsl_matrix_float_submatrix(resid, k1-1, 0,k2,resid->size2);
result = gsl_matrix_float_alloc(k2, resid->size2);
gsl_matrix_float_memcpy (result, &sub1.matrix);
gsl_matrix_float_mul_elements (result, &sub2.matrix);
gsl_vector_float* Cov1 = fsum(result,1,NULL);
gsl_matrix_float_free(result);
/* : Covadj=invM*[Cov0; Cov1]; */
buffer = gsl_matrix_float_alloc(2,Cov0->size);
float* pBuffer = buffer->data;
float* pCov0 = Cov0->data;
float* pCov1 = Cov1->data;
for(i=0;i<Cov0->size;i++) {
*pBuffer++ = *pCov0++;
}
for(i=0;i<Cov1->size;i++) {
*pBuffer++ = *pCov1++;
}
gsl_matrix_float* Covadj = fmat_x_mat(invM, buffer, NULL);
gsl_matrix_float_free(buffer);
/* : rho_vol(:,slice,1)=(Covadj(2,:)./ ...
* (Covadj(1,:)+(Covadj(1,:)<=0)).*(Covadj(1,:)>0))'; */
int cols = Covadj->size2;
float* p = Covadj->data;
float val;
for(i=0;i<cols;i++) {
val = *(p+cols) / ((*p <= 0) ? *p +1 : *p) * (*p > 0);
VPixel(rho_vol, i, slice, 0, VFloat) = val;
p++;
}
gsl_matrix_float_free(Covadj);
gsl_vector_float_free(Cov0);
gsl_vector_float_free(Cov1);
}
else {
/* :
* for lag=0:numlags
* Cov(lag+1,:)=sum(resid(1:(n-lag),:).*resid((lag+1):n,:));
* end
*/
int lag;
gsl_matrix_float* Cov = gsl_matrix_float_alloc(numlags+1,resid->size2);
gsl_vector_float* v;
for(lag=0;lag<=numlags;lag++) {
gsl_matrix_float_view sub1 =
gsl_matrix_float_submatrix(resid,0,0,n-lag,resid->size2);
gsl_matrix_float_view sub2 =
gsl_matrix_float_submatrix(resid,lag,0,n-lag,resid->size2 );
result = gsl_matrix_float_alloc(n-lag, resid->size2);
gsl_matrix_float_memcpy (result, &sub1.matrix);
gsl_matrix_float_mul_elements (result, &sub2.matrix);
v = fsum(result, 1,NULL);
gsl_matrix_float_free(result);
memcpy((float*)(Cov->data+(lag*Cov->size2)),
(float*)v->data,
sizeof(float)*v->size);
gsl_vector_float_free(v);
}
/* : Covadj=invM*Cov; */
gsl_matrix_float* Covadj = fmat_x_mat(invM, Cov, NULL);
/* : rho_vol(:,slice,:)= ( Covadj(0:(numlags+1),:) ...
* .*( ones(numlags,1)*((Covadj(1,:)>0)./ ...
* (Covadj(1,:)+(Covadj(1,:)<=0)))) )'; */
gsl_matrix_float* line = gsl_matrix_float_alloc(1,Covadj->size2);
float* pC = Covadj->data;
float* pB = line->data;
for(i=0;i<line->size2;i++) {
*pB = (float)(*pC > 0) / (float)(*pC+(*pC<=0));
pB++;
pC++;
}
buffer = gsl_matrix_float_alloc(numlags,1);
gsl_matrix_float_set_all(buffer,1);
result = fmat_x_mat(buffer, line,NULL);
gsl_matrix_float_view sub =
gsl_matrix_float_submatrix(Covadj,1,0,numlags,Covadj->size2);
gsl_matrix_float_free(buffer);
buffer = gsl_matrix_float_alloc(result->size1, result->size2);
gsl_matrix_float_memcpy (buffer, &sub.matrix);
gsl_matrix_float_mul_elements (buffer, result);
float* p = buffer->data;
for(i=0;i<buffer->size1;i++) {
for(j=0;j<buffer->size2;j++) {
VPixel(rho_vol,j,slice,i, VFloat) = (float)*p++;
}
}
gsl_matrix_float_free(buffer);
gsl_matrix_float_free(result);
gsl_matrix_float_free(line);
gsl_matrix_float_free(Covadj);
gsl_matrix_float_free(Cov);
}
gsl_matrix_float_free(betahat_ls);
gsl_matrix_float_free(transX);
}
| {
"alphanum_fraction": 0.6085848687,
"avg_line_length": 31.6894409938,
"ext": "c",
"hexsha": "ad4d6edf36b6b182a21b68258d2bd484cd46cdc9",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/stats/vlisa_prewhitening/whitecov.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/stats/vlisa_prewhitening/whitecov.c",
"max_line_length": 83,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/stats/vlisa_prewhitening/whitecov.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z",
"num_tokens": 1584,
"size": 5102
} |
/**
*/
#ifndef _DISP_CONF_H
#define _DISP_CONF_H
#include <gsl/gsl_vector.h>
#include "aXe_grism.h"
/**
* A structure to contain the coefficient of a 2D
* polynomial that can be used to compute the given
* coefficient of the polynomial dispersion relation
* as at a particular i.j location in the image
*/
typedef struct
{
gsl_vector *pol; /* A vector containing the 2D polynomial coefficients */
int for_grism; /* If true, pol is of form sum(a_i x^i, i=0..order)
otherwise, it is of form sum(a_i 1/x^i, i=0..order) */
d_point cpoint; /* The detector location at which this structure
was computed */
int ID; /* The ID of the beam for which this coefficient
is defined */
char file[MAXCHAR];
}
dispstruct;
typedef struct
{
char file[MAXCHAR];
int ID;
int for_grism;
int n_order;
gsl_vector **all_coeffs;
}
global_disp;
extern float
get_beam_mmag_extract (char *filename, int beamID);
extern float
get_beam_mmag_mark (char *filename, int beamID);
extern int
get_beam_disp_norder (char *filename, int beamID);
extern gsl_vector *
get_beam_disp_order (char *filename, const int for_grism,
int beamID, int order);
extern float
get_disp_coeff_at_pos (char *filename, const int for_grism, int beamID,
int order, d_point p);
extern gsl_vector *
get_disp_coeffs_at_pos (char *filename, const int for_grism,
int beamID, d_point p);
extern void
free_dispstruct(dispstruct *p);
extern dispstruct *
get_dispersion_at_pos (char *filename, int beamID, d_point p);
extern void
dispstruct_fprintf (FILE * file, dispstruct * disp);
extern dispstruct *
get_dispstruct_at_pos (char *filename, const int for_grism,
int beamID, d_point p);
extern int
check_for_grism (char *filename, int beamID);
extern int
check_disp_coeff (char *filename,const int for_grism,int beamID,int order);
extern gsl_vector *
get_prange (char *filename, int beamID);
extern global_disp *
get_global_disp(char *filename, const int for_grism, int beamID);
extern gsl_vector *
get_calvector_from_gdisp(const global_disp *gdisp, const d_point p);
extern double
get_2Ddep_value(const gsl_vector *coeffs, const d_point p);
extern void
print_global_disp(const global_disp *gdisp);
extern int
check_disp_order(const gsl_vector *tmp, const int beamID, const int order);
extern void
free_global_disp(global_disp *gdisp);
#endif
| {
"alphanum_fraction": 0.7007097792,
"avg_line_length": 24.862745098,
"ext": "h",
"hexsha": "166a906da7784873fd7ea76d1f0431029bd550da",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/disp_conf.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/disp_conf.h",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/disp_conf.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 621,
"size": 2536
} |
/****************************************************************************
* Constants
***************************************************************************/
#ifndef CONST_H
#define CONST_H
#include <string>
#include <random>
#include <chrono>
#include <iostream>
#include <gsl/gsl_vector_float.h>
#include <gsl/gsl_blas.h>
using namespace std;
namespace MD
{
//GLOBAL ALIASES
typedef float myCoor;
typedef gsl_vector_float myVect;
typedef gsl_matrix_float myMatr;
static const auto& myVectMalloc = gsl_vector_float_calloc;
static const auto& myVectMemdel = gsl_vector_float_free;
static const auto& myVectSet = gsl_vector_float_set;
static const auto& myVectGet = gsl_vector_float_get;
static const auto& myVectMin = gsl_vector_float_min;
static const auto& myVectMax = gsl_vector_float_max;
static const auto& myVectCpy = gsl_vector_float_memcpy;
static const auto& myVectZro = gsl_vector_float_set_zero;
static const auto& myMatrMalloc = gsl_matrix_float_calloc;
static const auto& myMatrMemdel = gsl_matrix_float_free;
static const auto& myMatrSet = gsl_matrix_float_set;
static const auto& myMatrSetrow = gsl_matrix_float_set_row;
static const auto& myMatrGet = gsl_matrix_float_get;
static const auto& myMatrZro = gsl_matrix_float_set_zero;
static const auto& myVectAdd = gsl_vector_float_add;
static const auto& myVectSub = gsl_vector_float_sub;
static const auto& myVectScl = gsl_vector_float_scale;
static const auto& myVectMul = gsl_vector_float_mul;
static const auto& myVectDiv = gsl_vector_float_div;
static const auto& myMatrAdd = gsl_matrix_float_add;
static const auto& myMatrScl = gsl_matrix_float_scale;
static const auto& myVectDot = gsl_blas_sdot;
static const auto& myVectNrm = gsl_blas_snrm2;
static const auto& myMatrVecmul = gsl_blas_sgemv;
//GLOBAL VARIABLES
static ostream& COUTPT = cout;
static istream& CINPUT = cin;
extern const myCoor ONEPIE, TWOPIE, ROOTWO, IVRTWO, COULMB, BOLTZM, MINZRO;
extern const myCoor STPSZE, STPHLF, STPINV, STPIHF, STEPSQ, STPIRT;
extern const int DIM;
extern const int MAXNPART, MAXNBOND, MAXNANGL, MAXNDHED;
extern const int BONDFORC;
extern const bool ANGLPART, LJONPART, DPDPARTK, LONGMEMO;
extern const char *paraFl, *topoFl, *strcFl, *coorFl, *trajFl, *memoFl,
*convFl, *defNme, *datNme, *cgStFl;
extern const char *crdFmt, *typFmt, *nmeFmt, *sNmFmt;
extern const string ctrlAtom, ctrlMass, ctrlBond, ctrlAngl, ctrlDhed,
ctrlRsid, ctrlTime, ctrlStop, ctrlIgnr, ctrlEnd,
emptyNme;
//GLOBAL FUNCTIONS
static default_random_engine ENGINE;
static normal_distribution<myCoor> NRMDIS{0.0, 1.0};
static uniform_real_distribution<myCoor> UNIDIS(0.0,1.0);
void myVectInv(myVect* vec1, const myCoor leng);
void myVectRev(myVect* vec1);
void myVectCrs(myVect* vec1, const myVect* vec2);
void myVectVecCrs(const myVect* vec1, const myVect* vec2, myVect* vec3);
void myVectUnt(myVect* uVec, myCoor& dist);
void myVectRnd(myVect* uVec);
void myVectOrd(myVect* sVec, const myVect* uVec);
void myVectInp(myVect* vect, istream& iput);
void rndVec(myVect* uVec);
void myVectOut(const myVect* vect);
void dbuggr();
//GLOBAL DUMMY VECTOR
static myVect *FOR1 = myVectMalloc(DIM), *FOR2 = myVectMalloc(DIM),
*FOR3 = myVectMalloc(DIM), *FTOT = myVectMalloc(DIM),
*FORC = myVectMalloc(DIM),
*VELO = myVectMalloc(DIM), *POST = myVectMalloc(DIM),
*PBC1 = myVectMalloc(DIM), *PBC2 = myVectMalloc(DIM);
//NOTE: be careful when using these vectors, as they may be
// used elsewhere
static myVect *NRM1 = myVectMalloc(DIM), *NRM2 = myVectMalloc(DIM),
*LEN1 = myVectMalloc(DIM), *LEN2 = myVectMalloc(DIM),
*LEN3 = myVectMalloc(DIM), *UNIT = myVectMalloc(DIM);
}
#endif
| {
"alphanum_fraction": 0.6968534152,
"avg_line_length": 42.0322580645,
"ext": "h",
"hexsha": "c9b4cdb400b4eeb62f11d0b2a71b99d959a7b190",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "80a3104101348d1c599ecc0a1e08aec855fc70a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "htran118/MD-MS-CG",
"max_forks_repo_path": "libs/const.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "80a3104101348d1c599ecc0a1e08aec855fc70a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "htran118/MD-MS-CG",
"max_issues_repo_path": "libs/const.h",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "80a3104101348d1c599ecc0a1e08aec855fc70a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "htran118/MD-MS-CG",
"max_stars_repo_path": "libs/const.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1142,
"size": 3909
} |
/* $Id$ */
/*--------------------------------------------------------------------*/
/*; Copyright (C) 2003-2013 */
/*; Associated Universities, Inc. Washington DC, USA. */
/*; */
/*; This program is free software; you can redistribute it and/or */
/*; modify it under the terms of the GNU General Public License as */
/*; published by the Free Software Foundation; either version 2 of */
/*; the License, or (at your option) any later version. */
/*; */
/*; This program is distributed in the hope that it will be useful, */
/*; but WITHOUT ANY WARRANTY; without even the implied warranty of */
/*; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/*; GNU General Public License for more details. */
/*; */
/*; You should have received a copy of the GNU General Public */
/*; License along with this program; if not, write to the Free */
/*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */
/*; MA 02139, USA. */
/*; */
/*; Correspondence about this software should be addressed as follows:*/
/*; Internet email: bcotton@nrao.edu. */
/*; Postal address: William Cotton */
/*; National Radio Astronomy Observatory */
/*; 520 Edgemont Road */
/*; Charlottesville, VA 22903-2475 USA */
/*--------------------------------------------------------------------*/
#include <gsl/gsl_multifit.h>
#include <stdlib.h>
#include "ObitOTFGetSoln.h"
#include "ObitTableOTFFlag.h"
#include "ObitOTFUtil.h"
#include "ObitTimeFilter.h"
#include "ObitPennArrayAtmFit.h"
#include "ObitPlot.h"
#include "ObitUtil.h"
#include "ObitTableOTFTargetUtil.h"
/*----------------Obit: Merx mollis mortibus nuper ------------------*/
/**
* \file ObitOTFGetSoln.c
* ObitOTFGetSoln utility module calibration function definitions.
*/
#define MAXSAMPSCAN 5000 /* Maximum number of samples in a scan */
/*---------------Private function prototypes----------------*/
/** Private: Solve for atmospheric offset calibration */
static void
ObitOTFGetSolnSolve (ObitOTFArrayGeom *geom, ObitOTFDesc *desc,
ObitPennArrayAtmFit *fitter, ofloat *rec, ObitTableOTFSolnRow *row);
/** Private: Solve for gain calibration */
static void
ObitOTFGetSolnGainSolve (olong nsample, ofloat *time, ofloat *cal, ofloat calJy, ofloat *data,
ofloat minrms, ofloat lastgood, olong detect, ObitTableOTFSolnRow *row);
/** Private: Solve for instrumental calibration */
static void
ObitOTFGetInstSolve (ObitOTFArrayGeom *geom, ObitOTFDesc *desc,
olong nDet, olong nTime, ofloat **data, ofloat *iCal,
ObitTableOTFSolnRow *row);
/** Private: Get average around median value of an array */
static ofloat GetSolnMedianAvg (ofloat *array, olong incs, olong n);
/** Private: Fit polynomial */
static void FitBLPoly (ofloat *poly, olong order, ofloat *x,
ofloat *y, ofloat *wt, olong n);
/** Private: Fit polynomial */
static void FitMBBLPoly (ofloat solint, olong *npoly, ofloat **tpoly, ofloat **poly,
ofloat *offset, olong ndetect, olong maxdata,
ofloat *x, ofloat *y, ofloat *wt, olong n);
/** Private: Reject outlyers */
static void FitMBBLOut (olong npoly, ofloat *tpoly, ofloat *poly, ofloat *offset,
olong ndetect, olong maxdata, ofloat *x, ofloat *y,
ofloat *wt, olong n, ofloat sigma);
/** Private: Plot multibeam baseline data and model */
static void PlotMBBL (olong npoly, ofloat *tpoly, ofloat *poly, ofloat *offset,
olong ndetect, olong maxdata,
ofloat *x, ofloat *y, ofloat *wt, olong n,
olong plotDetect, ofloat t0, ObitErr *err);
/** Private: Flatten curves, determine cal and Weights */
static void doPARCalWeight (olong nDet, olong nTime, ofloat *iCal, ofloat **accum,
ofloat *time, ofloat *lastCal, ofloat *lastWeight,
gboolean fitWate);
/** Private: qsort ofloat comparison */
static int compare_gfloat (const void* arg1, const void* arg2);
/** return opacity */
static ofloat getTau0 (ofloat time, gint32 taudim[], ofloat *taudata);
/** return RMS of an array (with blanking) */
static ofloat RMSValue (ofloat *array, olong n);
/** return ID of "Blank" Scan */
static ofloat FindBlankID (ObitOTF *inOTF, ObitErr *err);
/*----------------------Public functions---------------------------*/
/**
* Determine offset calibration for an OTF residual for multibeam
* systems using an Atmospheric model across the array of detectors.
* Calibration parameters are on the inOTF info member.
* \li "solInt" OBIT_float (1,1,1) Solution interval in days [def 1 sec].
* \li "Tau0" OBIT_float (?,?,1) Zenith opacity in nepers [def 0].
* Can be passed as either a constant scalar or
* an array of (time, tau0) pairs.
* \li "minEl" OBIT_float (1,1,1) Minimum elevation allowed (deg)
* \li "Clip" OBIT_float (1,1,1) data outside of range +/- Clip are replaced by
* + or - Clip. [Def 1.0e20]
* \li "plotTime" OBIT_boolean (1,1,1) If True plot filtered time serieses
* \li "plotFreq" OBIT_boolean (1,1,1) If True plot filtered power spectra
* \param inOTF Input OTF data.
* \param outOTF OTF with which the output OTFSoln is to be associated
* \param err Error stack, returns if not empty.
* \return Pointer to the newly created OTFSoln object which is
* associated with outOTF.
*/
ObitTableOTFSoln* ObitOTFGetSolnCal (ObitOTF *inOTF, ObitOTF *outOTF, ObitErr *err)
{
ObitTableOTFSoln *outSoln=NULL;
ObitTableOTFSolnRow *row=NULL;
ObitPennArrayAtmFit *fitter;
ObitTimeFilter *filter = NULL;
gint32 taudim[MAXINFOELEMDIM] = {1,1,1,1,1}, dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
ObitIOAccess access;
ofloat *rec=NULL, solInt, t0, fblank = ObitMagicF();
ofloat *tau0, tMult, airmass;
ofloat minEl, el, clip, lastScan=-1.0, lastTarget=-1.0;
ofloat *time, dTime, *data, coef[20];
ofloat totalTime, samp, parms[10];
olong iRow, ver, i, j, k, ibuf, lrec, ncoef, nsample;
olong npoly, ndetect, incdatawt;
gboolean flag, doCalSelect, someOK, someData, allBad;
gboolean plotTime, plotFreq;
ObitIOCode retCode;
gchar *tname;
gchar *routine = "ObitOTFGetSolnCal";
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return outSoln;
g_assert (ObitOTFIsA(inOTF));
/* Calibration wanted? */
doCalSelect = FALSE;
ObitInfoListGetTest(inOTF->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect);
if (doCalSelect) access = OBIT_IO_ReadCal;
else access = OBIT_IO_ReadWrite;
/* open OTF data if not already open */
if ((inOTF->myStatus==OBIT_Inactive) || (inOTF->myStatus==OBIT_Defined)) {
retCode = ObitOTFOpen (inOTF, access, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
}
/* Create output */
tname = g_strconcat ("Calibration for: ",inOTF->name, NULL);
ver = 0;
ncoef = 1; /* do first order atmospheric model (0=1, 1=3, 2nd = 6, 3rd=10) */
npoly = ncoef;
outSoln = newObitTableOTFSolnValue(tname, (ObitData*)outOTF, &ver, OBIT_IO_WriteOnly,
inOTF->geom->numberDetect, npoly, err);
g_free (tname);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Create work arrays */
ndetect = inOTF->geom->numberDetect; /* number of detectors */
lrec = inOTF->myDesc->lrec;
time = g_malloc0(MAXSAMPSCAN*sizeof(ofloat));
data = g_malloc0(ncoef*MAXSAMPSCAN*sizeof(ofloat));
nsample = 0;
t0 = -1.0e20;
lastScan = -1000.0;
incdatawt = inOTF->myDesc->incdatawt; /* increment in data-wt axis */
/* Get parameters for calibration */
/* Solution interval default 10 sec */
solInt = 10.0 / 86400.0;
ObitInfoListGetTest(inOTF->info, "solInt", &type, dim, (gpointer*)&solInt);
/* minimum allowed elevation for solution */
minEl = 1.0;
ObitInfoListGetTest(inOTF->info, "minEl", &type, dim, (gpointer*)&minEl);
/* Clip value */
clip = 1.0e20;
ObitInfoListGetTest(inOTF->info, "Clip", &type, dim, (gpointer*)&clip);
if (clip<1.0e19)
Obit_log_error(err, OBIT_InfoErr, "%s: Clipping residuals at %f", routine,clip);
/* Opacity */
tau0 = NULL;
ObitInfoListGetP(inOTF->info, "Tau0", &type, taudim, (gpointer*)&tau0);
/* Plotting? */
plotTime = FALSE;
ObitInfoListGetTest(inOTF->info, "plotTime", &type, dim, (gpointer*)&plotTime);
plotFreq = FALSE;
ObitInfoListGetTest(inOTF->info, "plotFreq", &type, dim, (gpointer*)&plotFreq);
/* Open output table */
if ((ObitTableOTFSolnOpen (outSoln, OBIT_IO_WriteOnly, err)
!= OBIT_IO_OK) || (err->error)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s ERROR opening input OTFSoln table", routine);
return outSoln;
}
/* Create Row */
row = newObitTableOTFSolnRow (outSoln);
/* Attach row to output buffer */
ObitTableOTFSolnSetRow (outSoln, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Initialize solution row */
row->dAz = 0.0; /* no pointing corrections */
row->dEl = 0.0; /* no pointing corrections */
row->Target = 0;
for (j=0; j<ndetect; j++) row->mult[j] = 1.0;
for (j=0; j<ndetect; j++) row->wt[j] = 1.0;
for (j=0; j<ndetect; j++) row->cal[j] = 0.0;
for (j=0; j<ndetect; j++) row->add[j] = 0.0;
for (i=0; i<npoly; i++) row->poly[i] = 0.0;
flag = FALSE;
someOK = FALSE;
someData = FALSE;
/* Create fitter for atmospheric model */
fitter = ObitPennArrayAtmFitValue ("Atm Fitter", inOTF->geom, ncoef, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* loop over input data */
retCode = OBIT_IO_OK;
while (retCode == OBIT_IO_OK) {
/* read buffer */
if (doCalSelect) retCode = ObitOTFReadSelect (inOTF, NULL, err);
else retCode = ObitOTFRead (inOTF, NULL, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
if (retCode==OBIT_IO_EOF) break; /* done? */
/* Record pointer */
rec = inOTF->buffer;
if (lastScan<0.0) {
lastScan = rec[inOTF->myDesc->ilocscan]; /* Which scan number */
lastTarget = rec[inOTF->myDesc->iloctar]; /* Which target number */
}
/* Loop over buffer */
for (ibuf=0; ibuf<inOTF->myDesc->numRecBuff; ibuf++) {
/* Scan read? If so, compute solution and write. Also if work arrays full */
if (( rec[inOTF->myDesc->ilocscan] != lastScan) || /* new scan */
(nsample>=MAXSAMPSCAN)) { /* or exceed limit on number of samples */
/* Any good data to filter? */
if (someOK) {
/* Filter data */
/* clip data */
if (clip<1.0e19) {
allBad = TRUE;
for (j=0; j<npoly; j++) {
for (k=0; k<nsample; k++) {
if (data[j*MAXSAMPSCAN+k]!=fblank) {
if (data[j*MAXSAMPSCAN+k] > clip) data[j*MAXSAMPSCAN+k] = fblank;
if (data[j*MAXSAMPSCAN+k] <-clip) data[j*MAXSAMPSCAN+k] = fblank;
if (data[j*MAXSAMPSCAN+k]!=fblank) allBad = FALSE;
}
}
}
/* Warn and flag if all clipped */
if (allBad) {
someOK = FALSE;
Obit_log_error(err, OBIT_InfoWarn,
"Warning: All data in a scan clipped");
}
} /* End if clipping */
/* Create filter as needed */
if (filter==NULL) filter = newObitTimeFilter("Cal Filter", nsample, npoly);
/* Copy data to filter */
dTime = (time[nsample-1] - time[0]) / nsample; /* Time increment */
for (j=0; j<npoly; j++) {
ObitTimeFilterGridTime (filter, j, dTime, nsample, time, &data[j*MAXSAMPSCAN]);
}
/* Plot? */
if (plotTime) ObitTimeFilterPlotTime (filter, 0, "Before filter", err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Transform to frequency */
ObitTimeFilter2Freq (filter);
/* Apply filter */
totalTime = (time[nsample-1] - time[0]); /* Total time in scan */
samp = totalTime / nsample; /* sampling interval */
parms[0] = 2.0*samp / MAX(solInt,samp); /* Cutoff frequency in units of highest */
parms[0] = 1.0/ (solInt*86400.0); /* Cutoff frequency in Hz */
ObitTimeFilterDoFilter (filter, -1, OBIT_TimeFilter_LowPass, parms, err);
if (err->error) {
Obit_log_error(err, OBIT_InfoErr, "%s: Total time %f sample time %f No. %d solInt %f",
routine,totalTime, samp, nsample, solInt);
Obit_traceback_val (err, routine, inOTF->name, outSoln);
}
/* Plot? */
if (plotFreq) ObitTimeFilterPlotPower (filter, 0, "Power", err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* FT back to time */
ObitTimeFilter2Time (filter);
/* Plot? */
if (plotTime) ObitTimeFilterPlotTime (filter, 0, "After filter", err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Copy data back to time series */
for (j=0; j<npoly; j++) {
ObitTimeFilterUngridTime (filter, j, nsample, time, &data[j*MAXSAMPSCAN]);
}
} /* end of filter good data */
/* Loop over solutions in scan */
k = 0;
t0 = time[0];
while (k<nsample) {
/* Use values in filtered time series separated by solInt/4
to over Nyquist sample highest frequency */
/* Find next time */
while ((time[k]<t0) && (k<nsample)) {k++;}
k = MIN (k, (nsample-1));
/* Set descriptive info on Row */
row->Time = time[k]; /* time */
row->TimeI = 0.25*solInt; /* time interval*/
row->Target = (oint)(lastTarget+0.5);
/* Opacity correction */
el = ObitOTFArrayGeomElev (inOTF->geom, row->Time,
rec[inOTF->myDesc->ilocra],
rec[inOTF->myDesc->ilocdec]);
if (el > 0.1)
airmass = 1.0 / cos (DG2RAD * (90.0 - el));
else
airmass = 10.0;
tMult = exp (getTau0(row->Time,taudim,tau0) * airmass); /* multiplicative term */
for (j=0; j<ndetect; j++) row->mult[j] = tMult;
/* Write Soln table */
iRow = -1;
/* Set poly filtered values */
if (someOK) { /* Some data OK */
for (j=0; j<npoly; j++) row->poly[j] = data[j*MAXSAMPSCAN+k];
} else { /* no good data - blank */
for (j=0; j<npoly; j++) row->poly[j] = fblank;
}
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
return outSoln;
}
t0 += 0.25*solInt; /* time of next entry in Soln table */
/* done? */
if (k>=(nsample-1)) break;
} /* end loop over times in scan */
/* initialize accumulators */
t0 = rec[inOTF->myDesc->iloct];
nsample = 0;
lastScan = -1000.0;
someOK = FALSE;
} /* end do solution */
/* Save sata */
/* Is data below the elevation limit? */
el = ObitOTFArrayGeomElev (inOTF->geom, rec[inOTF->myDesc->iloct],
rec[inOTF->myDesc->ilocra],
rec[inOTF->myDesc->ilocdec]);
flag = (el < minEl);
/* Fit model per data sample */
ObitPennArrayAtmFitFit (fitter, &rec[inOTF->myDesc->ilocdata], incdatawt, coef);
/* accumulate */
time[nsample] = rec[inOTF->myDesc->iloct];
if (!flag) { /* OK */
for (j=0; j<npoly; j++ ) {
data[nsample+j*MAXSAMPSCAN] = coef[j];
someOK = someOK || (data[nsample+j*MAXSAMPSCAN]!=fblank);
}
} else { /* too low el - blank */
for (j=0; j<npoly; j++ ) data[nsample+j*MAXSAMPSCAN] = fblank;
}
nsample++; /* how many samples in buffer */
someData = someData || someOK; /* Any valid data? */
if (lastScan<0.0) {
lastScan = rec[inOTF->myDesc->ilocscan]; /* Which scan number */
lastTarget = rec[inOTF->myDesc->iloctar]; /* Which target number */
}
rec += inOTF->myDesc->lrec; /* Update data record pointer */
} /* end loop over buffer load */
} /* end loop reading data */
/* Do last scan still in arrays*/
if (nsample>1) {
/* Any good data to filter? */
if (someOK) {
/* Filter data */
/* clip data */
if (clip<1.0e19) {
allBad = TRUE;
for (j=0; j<npoly; j++) {
for (k=0; k<nsample; k++) {
if (data[j*MAXSAMPSCAN+k]!=fblank) {
if (data[j*MAXSAMPSCAN+k] > clip) data[j*MAXSAMPSCAN+k] = fblank;
if (data[j*MAXSAMPSCAN+k] <-clip) data[j*MAXSAMPSCAN+k] = fblank;
if (data[j*MAXSAMPSCAN+k]!=fblank) allBad = FALSE;
}
}
}
/* Warn and flag if all clipped */
if (allBad) {
someOK = FALSE;
Obit_log_error(err, OBIT_InfoWarn,
"Warning: All data in a scan clipped");
}
} /* End if clipping */
/* Create filter as needed */
if (filter==NULL) filter = newObitTimeFilter("Cal Filter", nsample, npoly);
/* Copy data to filter */
dTime = (time[nsample-1] - time[0]) / nsample; /* Time increment */
for (j=0; j<npoly; j++) {
ObitTimeFilterGridTime (filter, j, dTime, nsample, time, &data[j*MAXSAMPSCAN]);
}
/* Transform to frequency */
ObitTimeFilter2Freq (filter);
/* Apply filter */
totalTime = (time[nsample-1] - time[0]); /* Total time in scan */
samp = totalTime / nsample; /* sampling interval */
parms[0] = 2.0*samp / MAX(solInt,samp); /* Cutoff frequency in units of highest */
parms[0] = 1.0/ (solInt*86400.0); /* Cutoff frequency in Hz */
ObitTimeFilterDoFilter (filter, -1, OBIT_TimeFilter_LowPass, parms, err);
if (err->error) {
Obit_log_error(err, OBIT_InfoErr, "%s: Total time %f sample time %f No. %d solInt %f",
routine,totalTime, samp, nsample, solInt);
Obit_traceback_val (err, routine, inOTF->name, outSoln);
}
/* Plot? */
if (plotTime) ObitTimeFilterPlotTime (filter, 0, "Before filter", err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* FT back to time */
ObitTimeFilter2Time (filter);
/* Time Plot? */
if (plotTime) ObitTimeFilterPlotTime (filter, 0, "After filter", err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Power spectrum plot? */
if (plotTime) ObitTimeFilterPlotTime (filter, 0, "Power", err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Copy data back to time series */
for (j=0; j<npoly; j++) {
ObitTimeFilterUngridTime (filter, j, nsample, time, &data[j*MAXSAMPSCAN]);
}
} /* end of filter good data */
/* Loop over solutions in scan */
k = 0;
t0 = time[0];
while (k<nsample) {
/* Use values in filtered time series separated by solInt/4
to over Nyquist sample highest frequency */
/* Find next time */
while ((time[k]<t0) && (k<nsample)) {k++;}
k = MIN (k, (nsample-1));
/* Set descriptive info on Row */
row->Time = time[k]; /* time */
row->TimeI = 0.25*solInt; /* time interval*/
row->Target = (oint)(lastTarget+0.5);
/* Opacity correction */
el = ObitOTFArrayGeomElev (inOTF->geom, row->Time,
rec[inOTF->myDesc->ilocra],
rec[inOTF->myDesc->ilocdec]);
if (el > 0.1)
airmass = 1.0 / cos (DG2RAD * (90.0 - el));
else
airmass = 10.0;
tMult = exp (getTau0(row->Time,taudim,tau0) * airmass); /* multiplicative term */
for (j=0; j<ndetect; j++) row->mult[j] = tMult;
/* Write Soln table */
iRow = -1;
/* Set poly filtered values */
if (someOK) { /* Some data OK */
for (j=0; j<npoly; j++) row->poly[j] = data[j*MAXSAMPSCAN+k];
} else { /* no good data - blank */
for (j=0; j<npoly; j++) row->poly[j] = fblank;
}
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
return outSoln;
}
t0 += 0.25*solInt; /* time of next entry in Soln table */
/* done? */
if (k>=(nsample-1)) break;
} /* end loop over times in scan */
} /* end finish up data in arrays */
/* Close output cal table */
if ((ObitTableOTFSolnClose (outSoln, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s ERROR closing output OTFSoln Table file", routine);
return outSoln;
}
/* Close data */
retCode = ObitOTFClose (inOTF, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Give warning if no data selected */
if (!someData) Obit_log_error(err, OBIT_InfoWarn,
"%s: Warning: NO data selected", routine);
/* Cleanup */
fitter = ObitPennArrayAtmFitUnref (fitter);
filter = ObitTimeFilterUnref(filter);
row = ObitTableOTFSolnUnref(row);
if (time) g_free(time);
if (data) g_free(data);
return outSoln;
} /* end ObitOTFGetSolnCal */
/**
* Determine gain calibration for an OTF from a residual data set.
* Gain Calibration is based on the "Cal" values in the data.
* Average value of the noise Cal is computed and entered in the data. (Gain only)
* Additive values are determined from the median values of the residual data.
* Solution type controlled by calType
* Calibration parameters are on the inOTF info member.
* \li "solInt" OBIT_float (1,1,1) Solution interval in days [def 10 sec].
* This should not exceed 1000 samples. Solutions will be truncated
* at this limit.
* \li "minRMS" OBIT_float (1,1,1) minimum allowable fractional solution RMS [def 0.1].
* bad solutions are replaced with pervious good value. [Gain soln]
* \li "calJy" OBIT_float (*,1,1) Calibrator value in Jy per detector [Gain soln] [def 1.0] .
* \li "minEl" OBIT_float (1,1,1) Minimum elevation allowed (deg)
* \li "calType" OBIT_string (*,1,1) Calibration type desired
* "Gain" => Gain (multiplicative, cal) solution only
* "Offset" => Offset (additive) solution only
* "GainOffset" both gain and offset calibration (probably bad idea).
* anything else or absent => Gain only.
* \param inOTF Input OTF data.
* \param outOTF OTF with which the output OTFSoln is to be associated
* \param err Error stack, returns if not empty.
* \return Pointer to the newly created OTFSoln object which is
* associated with inOTF.
*/
ObitTableOTFSoln* ObitOTFGetSolnGain (ObitOTF *inOTF, ObitOTF *outOTF, ObitErr *err)
{
#define MAXSAMPLE 1000 /* Maximum number of samples in an integration */
ObitTableOTFSoln *outSoln=NULL;
ObitTableOTFSolnRow *row=NULL;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
ObitOTFDesc *desc=inOTF->myDesc;
ofloat lastScan=-1.0, lastTarget=-1.0;
ofloat *rec=NULL, solInt, minEl, el, t0, tEnd, value, fblank = ObitMagicF();
ofloat *time, *cal, *data, *lastgood, sumTime, minrms, *calJy=NULL;
ofloat *value1=NULL, *value2=NULL;
olong nfeed=1, nstok, nchan, nscal=1, ifeed, istok, incs=1, incfeed=1, ilocdata=1;
olong iRow, ver, i, j, lrec, nsample;
olong npoly, ndetect, incdatawt;
ObitIOCode retCode;
gboolean flag, someData, doGain, doOffset;
gchar *tname;
gchar calType[50];
gchar *routine = "ObitOTFGetSolnGain";
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return outSoln;
g_assert (ObitOTFIsA(inOTF));
/* open OTF data to fully instantiate if not already open */
if ((inOTF->myStatus==OBIT_Inactive) || (inOTF->myStatus==OBIT_Defined)) {
retCode = ObitOTFOpen (inOTF, OBIT_IO_ReadWrite, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
}
/* Create output */
tname = g_strconcat ("Calibration for: ",inOTF->name, NULL);
ver = 0;
npoly = 1;
outSoln = newObitTableOTFSolnValue(tname, (ObitData*)outOTF, &ver, OBIT_IO_WriteOnly,
inOTF->geom->numberDetect, npoly, err);
g_free (tname);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* How many detectors? */
if (desc->OTFType==OBIT_GBTOTF_VEGAS) {
incs = desc->incs;
incfeed = desc->incfeed;
ilocdata = desc->ilocdata;
nfeed = desc->inaxes[desc->jlocfeed];
nstok = desc->inaxes[desc->jlocs];
nscal = MIN (2, nstok); /* Number of stokes in cal table */
nchan = desc->inaxes[desc->jlocf];
ndetect = nscal*nfeed;
/* Better be frequency averaged */
Obit_retval_if_fail ((nchan==1), err, outSoln,
"%s VEGAS data must be frequency averaged",
routine);
} else { /* Non VEGAS */
ndetect = inOTF->geom->numberDetect; /* number of detectors */
}
/* Create work arrays */
lrec = inOTF->myDesc->lrec;
lastgood = g_malloc0(ndetect*sizeof(ofloat));
time = g_malloc0(MAXSAMPLE*sizeof(ofloat));
cal = g_malloc0(MAXSAMPLE*sizeof(ofloat));
data = g_malloc0(ndetect*MAXSAMPLE*sizeof(ofloat));
calJy = g_malloc0(ndetect*sizeof(ofloat));
value1 = g_malloc0(ndetect*sizeof(ofloat));
value2 = g_malloc0(ndetect*sizeof(ofloat));
nsample = 0;
t0 = -1.0e20;
tEnd = -1.0e20;
sumTime = 0.0;
lastScan = -1000;
incdatawt = inOTF->myDesc->incdatawt; /* increment in data-wt axis */
someData = FALSE;
/* Get parameters for calibration */
/* Solution interval default 10 sec */
solInt = 10.0 / 86400.0;
ObitInfoListGetTest(inOTF->info, "solInt", &type, dim, (gpointer*)&solInt);
/* minimum RMS in solution */
minrms = 0.1;
ObitInfoListGetTest(inOTF->info, "minRMS", &type, dim, (gpointer*)&minrms);
/* minimum allowed elevation for solution */
minEl = 1.0;
ObitInfoListGetTest(inOTF->info, "minEl", &type, dim, (gpointer*)&minEl);
/* cal value in Jy */
for (j=0; j<ndetect; j++) calJy[j] = 1.0;
ObitInfoListGetTest(inOTF->info, "calJy", &type, dim, (gpointer*)calJy);
/* calibration type */
for (i=0; i<50; i++) calType[i] = 0;
strcpy (calType, "Gain");
ObitInfoListGetTest(inOTF->info, "calType", &type, dim, calType);
/* What calibrations are desired? */
doGain = FALSE; doOffset = FALSE;
if (!strncmp(calType, "Gain",4)) doGain = TRUE;
else if (!strncmp(calType, "Offset",6)) doOffset = TRUE;
else if (!strncmp(calType, "GainOffset",10)) {doGain=TRUE; doOffset = TRUE;}
else doGain = TRUE;
/* Open table */
if ((ObitTableOTFSolnOpen (outSoln, OBIT_IO_WriteOnly, err)
!= OBIT_IO_OK) || (err->error)) { /* error test */
Obit_log_error(err, OBIT_Error, "ERROR opening input OTFSoln table");
return outSoln;
}
/* Create Row */
row = newObitTableOTFSolnRow (outSoln);
/* Attach row to output buffer */
ObitTableOTFSolnSetRow (outSoln, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Initialize solution row */
row->dAz = 0.0; /* no pointing corrections */
row->dEl = 0.0; /* no pointing corrections */
row->Target = 0;
for (j=0; j<ndetect; j++) row->mult[j] = 1.0;
for (j=0; j<ndetect; j++) row->wt[j] = 1.0;
for (j=0; j<ndetect; j++) row->cal[j] = 0.0;
for (j=0; j<ndetect; j++) row->add[j] = 0.0;
for (j=0; j<ndetect; j++) lastgood[j] = fblank;
for (j=0; j<npoly; j++) row->poly[j] = 0.0;
flag = FALSE;
rec = inOTF->buffer;
/* loop calibrating data */
retCode = OBIT_IO_OK;
while (retCode == OBIT_IO_OK) {
/* read buffer */
retCode = ObitOTFRead (inOTF, NULL, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
if (retCode==OBIT_IO_EOF) break; /* done? */
/* Record pointer */
rec = inOTF->buffer;
/* First time */
if (t0<-1.0e10) {
t0 = rec[inOTF->myDesc->iloct];
tEnd = t0+1.0E-20;
lastScan = rec[inOTF->myDesc->ilocscan]; /* Which scan number */
lastTarget = rec[inOTF->myDesc->iloctar]; /* Which target number */
}
/* Loop over buffer */
for (i=0; i<inOTF->myDesc->numRecBuff; i++) {
/* Solution interval finished? If so, compute solution and write.
also if work arrays full */
if ((rec[inOTF->myDesc->iloct] > (t0+solInt)) ||
/* or end of scan */
( rec[inOTF->myDesc->ilocscan] != lastScan) ||
/* or exceed limit on number of samples */
(nsample>=MAXSAMPLE)) {
/* Set descriptive info on Row */
row->Target = (oint)(lastTarget+0.5);
if (nsample>0) {
row->Time = sumTime/nsample; /* time */
row->TimeI = 2.0 * (row->Time - t0);
} else {
row->Time = rec[inOTF->myDesc->iloct];
row->TimeI = 0.0;
}
/* Get calibration, per detector */
for (j=0; j<ndetect; j++) {
row->add[j] = 0.0;
row->mult[j] = 1.0;
row->wt[j] = 1.0;
row->cal[j] = 0.0;
if (doGain) { /* gain solution */
ObitOTFGetSolnGainSolve (nsample, time, cal, calJy[j], &data[j*MAXSAMPLE],
minrms, lastgood[j], j, row);
lastgood[j] = row->mult[j]; /* save last good value */
}
if (doOffset ) { /* Offset solution */
if (nsample>1) {
/* Do it all at once */
value = GetSolnMedianAvg (&data[j*MAXSAMPLE], 1, nsample);
if (value!=fblank) value = -value;
value1[j] = value; /* for beginning */
value2[j] = value; /* for end */
} else { /* no data */
value1[j] = fblank;
value2[j] = fblank;
}
}
}
/* Write Soln table, write at beginning and end of solution */
iRow = -1;
/* Beginning */
row->Time = t0;
/* Set offset solution values */
if (doOffset) for (j=0; j<ndetect; j++) row->add[j] = value1[j];
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
return outSoln;
}
/* End */
row->Time = tEnd;
/* Set offset solution values */
if (doOffset) for (j=0; j<ndetect; j++) row->add[j] = value2[j];
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
return outSoln;
}
/* initialize accumulators */
t0 = rec[inOTF->myDesc->iloct];
tEnd = t0+1.0E-20;
sumTime = 0.0;
nsample = 0;
} /* end do solution */
/* Is data below the elevation limit? */
el = ObitOTFArrayGeomElev (inOTF->geom, rec[inOTF->myDesc->iloct],
rec[inOTF->myDesc->ilocra],
rec[inOTF->myDesc->ilocdec]);
flag = flag || (el < minEl);
/* accumulate */
if (!flag) {
sumTime += rec[inOTF->myDesc->iloct];
time[nsample] = rec[inOTF->myDesc->iloct];
cal[nsample] = rec[inOTF->myDesc->iloccal];
/* VEGAS different use, parallel poln and feeds */
j = 0;
if (desc->OTFType==OBIT_GBTOTF_VEGAS) {
/* Loop over feed */
for (ifeed=0; ifeed<nfeed; ifeed++) {
/* Loop over parallel Stokes */
for (istok=0; istok<nscal; istok++) {
data[nsample+j*MAXSAMPLE] =
rec[ilocdata + ifeed*incfeed + istok*incs];
j++;
} /* end Stokes loop */
} /* end feed loop */
} else { /* Non VEGAS */
for (j=0; j<ndetect; j++ )
data[nsample+j*MAXSAMPLE] = rec[ilocdata+j*incdatawt];
} /* end non VEGAS */
nsample++;
someData = TRUE; /* Any valid data? */
} /* end if not flagged */
/* last time in accumulation */
tEnd = rec[inOTF->myDesc->iloct]+1.0E-20;
lastScan = rec[inOTF->myDesc->ilocscan]; /* Which scan number */
lastTarget = rec[inOTF->myDesc->iloctar]; /* Which target number */
rec += inOTF->myDesc->lrec; /* Data record pointer */
} /* end loop over buffer load */
} /* end loop reading data */
/* Finish up any data in arrays */
/* Set descriptive info on Row */
row->Target = (oint)(lastTarget+0.5);
if (nsample>0) {
row->Time = sumTime/nsample; /* time */
row->TimeI = 2.0 * (row->Time - t0);
} else {
row->Time = rec[inOTF->myDesc->iloct];
row->TimeI = 0.0;
}
/* Get calibration, per detector */
for (j=0; j<ndetect; j++) {
row->add[j] = 0.0;
row->mult[j] = 1.0;
row->wt[j] = 1.0;
row->cal[j] = 0.0;
if (doGain) { /* gain solution */
ObitOTFGetSolnGainSolve (nsample, time, cal, calJy[j], &data[j*MAXSAMPLE],
minrms, lastgood[j], j, row);
lastgood[j] = row->mult[j]; /* save last good value */
}
if (doOffset ) { /* Offset solution */
if (nsample>1) {
/* all at once */
value = GetSolnMedianAvg (&data[j*MAXSAMPLE], 1, nsample);
if (value!=fblank) value = -value;
value1[j] = value;
/* NO Do second half
value = GetSolnMedianAvg (&data[j*MAXSAMPLE+nsample/2], incdatawt, nsample/2);
if (value!=fblank) value = -value;*/
value2[j] = value;
} else { /* no data */
value1[j] = fblank;
value2[j] = fblank;
}
}
}
/* Write Soln table, write at beginning and end of solution */
iRow = -1;
/* Beginning */
row->Target = (oint)(lastTarget+0.5);
row->Time = t0;
/* Set offset solution values */
if (doOffset) for (j=0; j<ndetect; j++) row->add[j] = value1[j];
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
return outSoln;
}
/* End */
row->Time = tEnd;
/* Set offset solution values */
if (doOffset) for (j=0; j<ndetect; j++) row->add[j] = value2[j];
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
return outSoln;
}
/* End final solution */
/* Close cal table */
if ((ObitTableOTFSolnClose (outSoln, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s ERROR closing output OTFSoln Table file", routine);
return outSoln;
}
/* Close data */
retCode = ObitOTFClose (inOTF, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Give warning if no data selected */
if (!someData) Obit_log_error(err, OBIT_InfoWarn,
"%s: Warning: NO data selected", routine);
/* Cleanup */
row = ObitTableOTFSolnUnref(row);
if (time) g_free(time);
if (cal) g_free(cal);
if (data) g_free(data);
return outSoln;
} /* end ObitOTFGetSolnGain */
/**
* Determine offset calibration for an OTF by time filtering a residual data set.
* The time series of each detector is filtered to remove structure on time
* scales longer than solInt.
* Scans in excess of 5000 samples will be broken into several.
* Calibration parameters are on the inOTF info member.
* \li "solInt" OBIT_float (1,1,1) Solution interval in days [def 10 sec].
* There will be 4 Soln table entries per solInt
* This should not exceed 1000 samples. Solutions will be truncated
* at this limit.
* \li "minEl" OBIT_float (1,1,1) Minimum elevation allowed (deg)
* \li "Clip" OBIT_float (1,1,1) data outside of range +/- Clip are replaced by
* + or - Clip. [Def 1.0e20]
* \param inOTF Input OTF data. Prior calibration applied if requested.
* \param outOTF OTF with which the output OTFSoln is to be associated
* \param err Error stack, returns if not empty.
* \return Pointer to the newly created OTFSoln object which is
* associated with inOTF.
*/
ObitTableOTFSoln* ObitOTFGetSolnFilter (ObitOTF *inOTF, ObitOTF *outOTF, ObitErr *err)
{
ObitTableOTFSoln *outSoln=NULL;
ObitTableOTFSolnRow *row=NULL;
ObitTimeFilter *filter = NULL;
ObitOTFDesc *desc=inOTF->myDesc;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
ObitIOAccess access;
ofloat lastScan=-1.0, lastTarget=-1.0;
ofloat *rec, solInt, minEl, el, t0, fblank = ObitMagicF();
ofloat *time, *data, clip;
ofloat totalTime, samp, parms[10];
olong nfeed=0, nstok, nchan, nscal=0, ifeed, istok, incs=1, incfeed=1, ilocdata=0;
olong iRow, ver, i, j, k, ibuf, lrec, nsample;
olong npoly, ndetect, incdatawt, nTime=0;
ObitIOCode retCode;
gboolean flag, someOK, someData, doCalSelect, done;
gchar *tname;
gchar *routine = "ObitOTFGetSolnFilter";
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return outSoln;
g_assert (ObitOTFIsA(inOTF));
/* Calibration wanted? */
doCalSelect = FALSE;
ObitInfoListGetTest(inOTF->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect);
if (doCalSelect) access = OBIT_IO_ReadCal;
else access = OBIT_IO_ReadWrite;
/* open OTF data if not already open */
if ((inOTF->myStatus==OBIT_Inactive) || (inOTF->myStatus==OBIT_Defined)) {
retCode = ObitOTFOpen (inOTF, access, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
}
/* Create output */
tname = g_strconcat ("Calibration for: ",inOTF->name, NULL);
ver = 0;
npoly = 1;
outSoln = newObitTableOTFSolnValue(tname, (ObitData*)outOTF, &ver, OBIT_IO_WriteOnly,
inOTF->geom->numberDetect, npoly, err);
g_free (tname);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* How many detectors? */
if (desc->OTFType==OBIT_GBTOTF_VEGAS) {
incs = desc->incs;
incfeed = desc->incfeed;
ilocdata = desc->ilocdata;
nfeed = desc->inaxes[desc->jlocfeed];
nstok = desc->inaxes[desc->jlocs];
nscal = MIN (2, nstok); /* Number of stokes in cal table */
nchan = desc->inaxes[desc->jlocf];
ndetect = nscal*nfeed;
/* Better be frequency averaged */
Obit_retval_if_fail ((nchan==1), err, outSoln,
"%s VEGAS data must be frequency averaged",
routine);
} else { /* Non VEGAS */
ndetect = inOTF->geom->numberDetect; /* number of detectors */
}
/* Create work arrays */
lrec = inOTF->myDesc->lrec;
time = g_malloc0(MAXSAMPSCAN*sizeof(ofloat));
data = g_malloc0(ndetect*MAXSAMPSCAN*sizeof(ofloat));
nsample = 0;
t0 = -1.0e20;
lastScan = -1000.0;
incdatawt = inOTF->myDesc->incdatawt; /* increment in data-wt axis */
/* Get parameters for calibration */
/* Solution interval default 10 sec */
solInt = 10.0 / 86400.0;
ObitInfoListGetTest(inOTF->info, "solInt", &type, dim, (gpointer*)&solInt);
/* minimum allowed elevation for solution */
minEl = 1.0;
ObitInfoListGetTest(inOTF->info, "minEl", &type, dim, (gpointer*)&minEl);
/* Clip value */
clip = 1.0e20;
ObitInfoListGetTest(inOTF->info, "Clip", &type, dim, (gpointer*)&clip);
if (clip<1.0e19)
Obit_log_error(err, OBIT_InfoErr, "%s: Clipping residuals at %f", routine,clip);
/* Open output table */
if ((ObitTableOTFSolnOpen (outSoln, OBIT_IO_WriteOnly, err)
!= OBIT_IO_OK) || (err->error)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s ERROR opening input OTFSoln table", routine);
return outSoln;
}
/* Create Row */
row = newObitTableOTFSolnRow (outSoln);
/* Attach row to output buffer */
ObitTableOTFSolnSetRow (outSoln, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Initialize solution row */
row->dAz = 0.0; /* no pointing corrections */
row->dEl = 0.0; /* no pointing corrections */
row->Target = 0;
for (j=0; j<ndetect; j++) row->mult[j] = 1.0;
for (j=0; j<ndetect; j++) row->wt[j] = 1.0;
for (j=0; j<ndetect; j++) row->cal[j] = 0.0;
for (j=0; j<ndetect; j++) row->add[j] = 0.0;
for (i=0; i<npoly; i++) row->poly[i] = 0.0;
flag = FALSE;
someOK = FALSE;
someData = FALSE;
/* loop over input data */
retCode = OBIT_IO_OK;
while (retCode == OBIT_IO_OK) {
/* read buffer */
if (doCalSelect) retCode = ObitOTFReadSelect (inOTF, NULL, err);
else retCode = ObitOTFRead (inOTF, NULL, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
done = retCode==OBIT_IO_EOF;
if (done) break; /* done? */
/* Record pointer */
rec = inOTF->buffer;
if (lastScan<0.0) {
lastScan = rec[inOTF->myDesc->ilocscan]; /* Which scan number */
lastTarget = rec[inOTF->myDesc->iloctar]; /* Which target number */
}
/* Loop over buffer */
for (ibuf=0; ibuf<inOTF->myDesc->numRecBuff; ibuf++) {
/* Scan read? If so, compute solution and write. Also if work arrays full */
if (( rec[inOTF->myDesc->ilocscan] != lastScan) || /* new scan */
(nsample>=MAXSAMPSCAN) || done) { /* or exceed limit on number of samples, or done */
/* Any good data to filter? */
if (someOK) {
/* Filter data */
/* Get optimum filter length - zero pad */
nTime = ObitFFTSuggestSize (nsample*2);
/* Create or resize filter as needed */
if (filter==NULL) {
filter = newObitTimeFilter("Cal Filter", nTime, ndetect);
} else {
ObitTimeFilterResize (filter, nTime);
}
/* copy data */
for (j=0; j<ndetect; j++) {
for (k=0; k<nsample; k++) filter->timeData[j][k] = data[j*MAXSAMPSCAN+k];
}
/* clip data */
if (clip<1.0e19) {
for (j=0; j<ndetect; j++) {
for (k=0; k<nsample; k++) {
if (filter->timeData[j][k]!=fblank) {
if (filter->timeData[j][k] > clip) filter->timeData[j][k] = clip;
if (filter->timeData[j][k] <-clip) filter->timeData[j][k] =-clip;
}
}
}
}
/* blank fill remainder of time series */
for (j=0; j<ndetect; j++) {
for (k=nsample; k<nTime; k++) filter->timeData[j][k] = fblank;
}
/* Transform to frequency */
ObitTimeFilter2Freq (filter);
/* Apply filter */
totalTime = (time[nsample-1] - time[0]); /* Total time in scan */
samp = totalTime / nsample; /* sampling interval */
parms[0] = 2.0 * samp / MAX(solInt,samp); /* Cutoff frequency in units of highest */
ObitTimeFilterFilter (filter, -1, OBIT_TimeFilter_LowPass, parms, err);
if (err->error) {
Obit_log_error(err, OBIT_InfoErr, "%s: Total time %f sample time %f No. %d solInt %f",
routine,totalTime, samp, nsample, solInt);
Obit_traceback_val (err, routine, inOTF->name, outSoln);
}
/* FT back to time */
ObitTimeFilter2Time (filter);
} /* end of filter good data */
/* Loop over solutions in scan */
k = 0;
t0 = time[0];
while (k<nsample) {
/* Use values in filtered time series separated by solInt/4
to over Nyquist sample highest frequency */
/* Find next time */
while ((time[k]<t0) && (k<nsample)) {k++;}
k = MIN (k, (nsample-1));
/* Set descriptive info on Row */
row->Time = time[k]; /* time */
row->TimeI = 0.25*solInt; /* time interval*/
row->Target = (oint)(lastTarget+0.5);
/* Write Soln table */
iRow = -1;
/* Set offset -filtered values */
if (someOK) { /* Some data OK */
for (j=0; j<ndetect; j++) row->add[j] = -filter->timeData[j][k];
} else { /* no good data - blank */
for (j=0; j<ndetect; j++) row->add[j] = fblank;
}
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
return outSoln;
}
t0 += 0.25*solInt; /* time of next entry in Soln table */
/* done? */
if (k>=(nsample-1)) break;
} /* end loop over times in scan */
/* initialize accumulators */
t0 = rec[inOTF->myDesc->iloct];
nsample = 0;
lastScan = -1000.0;
someOK = FALSE;
} /* end do solution */
/* Is data below the elevation limit? */
el = ObitOTFArrayGeomElev (inOTF->geom, rec[inOTF->myDesc->iloct],
rec[inOTF->myDesc->ilocra],
rec[inOTF->myDesc->ilocdec]);
flag = (el < minEl);
/* accumulate */
time[nsample] = rec[inOTF->myDesc->iloct];
if (!flag) { /* OK */
/* VEGAS different use, parallel poln and feeds */
j = 0;
if (desc->OTFType==OBIT_GBTOTF_VEGAS) {
/* Loop over feed */
for (ifeed=0; ifeed<nfeed; ifeed++) {
/* Loop over parallel Stokes */
for (istok=0; istok<nscal; istok++) {
data[nsample+j*MAXSAMPSCAN] =
rec[ilocdata + ifeed*incfeed + istok*incs];
someOK = someOK || (data[nsample+j*MAXSAMPSCAN]!=fblank);
j++;
} /* end Stokes loop */
} /* end feed loop */
} else { /* Non VEGAS */
for (j=0; j<ndetect; j++ ) {
data[nsample+j*MAXSAMPSCAN] = rec[inOTF->myDesc->ilocdata+j*incdatawt];
someOK = someOK || (data[nsample+j*MAXSAMPSCAN]!=fblank);
}
} /* end non VEGAS */
someData = someData || someOK; /* Any valid data? */
} else { /* too low el - blank */
for (j=0; j<ndetect; j++ ) data[nsample+j*MAXSAMPSCAN] = fblank;
}
nsample++; /* how many samples in buffer */
if (lastScan<0.0) {
lastScan = rec[inOTF->myDesc->ilocscan]; /* Which scan number */
}
lastTarget = rec[inOTF->myDesc->iloctar]; /* Which target number */
rec += inOTF->myDesc->lrec; /* Update data record pointer */
} /* end loop over buffer load */
} /* end loop reading data */
/* Do last scan still in arrays*/
if (nsample>1) {
/* Any good data to filter? */
if (someOK) {
/* Filter data */
/* Get optimum filter length - zero pad */
nTime = ObitFFTSuggestSize (nsample*2);
/* Create or resize filter as needed */
if (filter==NULL) {
filter = newObitTimeFilter("Cal Filter", nTime, ndetect);
} else {
ObitTimeFilterResize (filter, nTime);
}
/* copy data */
for (j=0; j<ndetect; j++) {
for (i=0; i<nsample; i++) filter->timeData[j][i] = data[j*MAXSAMPSCAN+i];
}
/* clip data */
if (clip<1.0e19) {
for (j=0; j<ndetect; j++) {
for (k=0; k<nsample; k++) {
if (filter->timeData[j][k]!=fblank) {
if (filter->timeData[j][k] > clip) filter->timeData[j][k] = clip;
if (filter->timeData[j][k] <-clip) filter->timeData[j][k] =-clip;
}
}
}
}
/* blank fill remainder of time series */
for (j=0; j<ndetect; j++) {
for (i=nsample; i<nTime; i++) filter->timeData[j][i] = fblank;
}
/* Transform to frequency */
ObitTimeFilter2Freq (filter);
/* Apply filter */
totalTime = (time[nsample-1] - time[0]); /* Total time in scan */
samp = totalTime / nsample; /* sampling interval */
parms[0] = 2.0 * samp / MAX(solInt,samp); /* Cutoff frequency in units of highest */
ObitTimeFilterFilter (filter, -1, OBIT_TimeFilter_LowPass, parms, err);
if (err->error) {
Obit_log_error(err, OBIT_InfoErr, "%s: Total time %f sample time %f No. %d solInt %f",
routine,totalTime, samp, nsample, solInt);
Obit_traceback_val (err, routine, inOTF->name, outSoln);
}
/* FT back to time */
ObitTimeFilter2Time (filter);
} /* end of filter good data */
/* Loop over solutions in scan */
i = 0;
t0 = time[0];
while (i<nsample) {
/* Use values in filtered time series separated by solInt */
/* Find next time */
while ((time[i]<t0) && (i<nsample)) {i++;}
i = MIN (i, (nsample-1));
/* Set descriptive info on Row */
row->Time = time[i]; /* time */
row->TimeI = solInt; /* time interval*/
row->Target = (oint)(lastTarget+0.5);
/* Write Soln table */
iRow = -1;
/* Set offset -filtered values */
if (someOK) { /* Some data OK */
for (j=0; j<ndetect; j++) row->add[j] = -filter->timeData[j][i];
} else { /* no good data - blank */
for (j=0; j<ndetect; j++) row->add[j] = fblank;
}
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
return outSoln;
}
if (i>=(nsample-1)) break; /* done? */
t0 += 0.25*solInt; /* time of next entry in Soln table */
} /* end loop over times in scan */
} /* end finish up data in arrays */
/* Close output cal table */
if ((ObitTableOTFSolnClose (outSoln, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s ERROR closing output OTFSoln Table file", routine);
return outSoln;
}
/* Close data */
retCode = ObitOTFClose (inOTF, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Give warning if no data selected */
if (!someData) Obit_log_error(err, OBIT_InfoWarn,
"%s: Warning: NO data selected", routine);
/* Cleanup */
filter = ObitTimeFilterUnref(filter);
row = ObitTableOTFSolnUnref(row);
if (time) g_free(time);
if (data) g_free(data);
return outSoln;
} /* end ObitOTFGetSolnFilter */
/**
* Fits polynomial "baseline" to median filtered scan data as additive term in
* an output OTFSoln table.
* Calibration parameters are on the inOTF info member.
* \li "solInt" OBIT_float (1,1,1) Solution interval in days [def 10 sec].
* This should not exceed 5000 samples. Solutions will be truncated
* at this limit. This should be a sub multiple of the scan length.
* \li "minEl" OBIT_float (1,1,1) Minimum elevation allowed (deg)
* \li "Order" OBIT_int (1,1,1) Order of polynomial to fit [def 1]
* Must not exceed the number of solution intervals in a scan.
* \param inOTF Input OTF data.
* \param outOTF OTF with which the output OTFSoln is to be associated
* \param err Error stack, returns if not empty.
* \return Pointer to the newly created OTFSoln object which is
* associated with inOTF.
*/
ObitTableOTFSoln* ObitOTFGetSolnPolyBL (ObitOTF *inOTF, ObitOTF *outOTF, ObitErr *err)
{
#define MAXBLSAMPLE 1000 /* Maximum number of samples in a solution interval */
#define MAXSISAMPLE 1000 /* Maximum number of solution intervals in a scan */
ObitTableOTFSoln *outSoln=NULL;
ObitTableOTFSolnRow *row=NULL;
ObitTimeFilter *filter = NULL;
ObitOTFDesc *desc=inOTF->myDesc;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitIOAccess access;
ObitInfoType type;
ofloat lastScan=-1.0, lastTarget=-1.0;
ofloat *rec, solInt, minEl, el, t0, tbeg=-1.0, tend=-1.0, fblank = ObitMagicF();
ofloat *time, *data, *mtime, *mdata, *mwt, *poly;
olong order, torder, iRow, ver, i, j, k, ibuf, lrec, nsample, msample;
olong npoly, ndetect, incdatawt;
olong nfeed=0, nstok, nchan, nscal=0, ifeed, istok, incs=1, incfeed=1, ilocdata=0;
ObitIOCode retCode;
gboolean flag, doCalSelect, someOK, done, someData;
gchar *tname;
gchar *routine = "ObitOTFGetSolnPolyBL";
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return outSoln;
g_assert (ObitOTFIsA(inOTF));
/* Calibration wanted? */
doCalSelect = FALSE;
ObitInfoListGetTest(inOTF->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect);
if (doCalSelect) access = OBIT_IO_ReadCal;
else access = OBIT_IO_ReadWrite;
/* open OTF data if not already open */
if ((inOTF->myStatus==OBIT_Inactive) || (inOTF->myStatus==OBIT_Defined)) {
retCode = ObitOTFOpen (inOTF, access, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
}
/* Create output */
tname = g_strconcat ("Calibration for: ",inOTF->name, NULL);
ver = 0;
npoly = 1;
outSoln = newObitTableOTFSolnValue(tname, (ObitData*)outOTF, &ver, OBIT_IO_WriteOnly,
inOTF->geom->numberDetect, npoly, err);
g_free (tname);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Get parameters for calibration */
/* Solution interval default 10 sec */
solInt = 10.0 / 86400.0;
ObitInfoListGetTest(inOTF->info, "solInt", &type, dim, (gpointer*)&solInt);
/* minimum allowed elevation for solution */
minEl = 1.0;
ObitInfoListGetTest(inOTF->info, "minEl", &type, dim, &minEl);
/* polynomial order */
order = 1;
ObitInfoListGetTest(inOTF->info, "Order", &type, dim, &order);
/* How many detectors? */
if (desc->OTFType==OBIT_GBTOTF_VEGAS) {
incs = desc->incs;
incfeed = desc->incfeed;
ilocdata = desc->ilocdata;
nfeed = desc->inaxes[desc->jlocfeed];
nstok = desc->inaxes[desc->jlocs];
nscal = MIN (2, nstok); /* Number of stokes in cal table */
nchan = desc->inaxes[desc->jlocf];
ndetect = nscal*nfeed;
/* Better be frequency averaged */
Obit_retval_if_fail ((nchan==1), err, outSoln,
"%s VEGAS data must be frequency averaged",
routine);
} else { /* Non VEGAS */
ndetect = inOTF->geom->numberDetect; /* number of detectors */
}
/* Create work arrays */
lrec = inOTF->myDesc->lrec;
time = g_malloc0(MAXBLSAMPLE*sizeof(ofloat));
data = g_malloc0(ndetect*MAXBLSAMPLE*sizeof(ofloat));
mtime = g_malloc0(MAXSISAMPLE*sizeof(ofloat));
mdata = g_malloc0(ndetect*MAXSISAMPLE*sizeof(ofloat));
mwt = g_malloc0(MAXSISAMPLE*sizeof(ofloat));
poly = g_malloc0(ndetect*(order+1)*sizeof(ofloat));
nsample = 0;
msample = 0;
t0 = -1.0e20;
lastScan = -1000.0;
incdatawt = inOTF->myDesc->incdatawt; /* increment in data-wt axis */
/* Open output table */
if ((ObitTableOTFSolnOpen (outSoln, OBIT_IO_WriteOnly, err)
!= OBIT_IO_OK) || (err->error)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s ERROR opening input OTFSoln table", routine);
return outSoln;
}
/* Create Row */
row = newObitTableOTFSolnRow (outSoln);
/* Attach row to output buffer */
ObitTableOTFSolnSetRow (outSoln, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Initialize solution row */
row->dAz = 0.0; /* no pointing corrections */
row->dEl = 0.0; /* no pointing corrections */
row->TimeI = solInt; /* time interval*/
row->Target = 0;
for (j=0; j<ndetect; j++) row->mult[j] = 1.0;
for (j=0; j<ndetect; j++) row->wt[j] = 1.0;
for (j=0; j<ndetect; j++) row->cal[j] = 0.0;
for (j=0; j<ndetect; j++) row->add[j] = 0.0;
for (i=0; i<npoly; i++) row->poly[i] = 0.0;
flag = FALSE;
someOK = FALSE;
someData = FALSE;
/* loop over input data */
retCode = OBIT_IO_OK;
while (retCode == OBIT_IO_OK) {
/* read buffer */
if (doCalSelect) retCode = ObitOTFReadSelect (inOTF, NULL, err);
else retCode = ObitOTFRead (inOTF, NULL, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
done = retCode==OBIT_IO_EOF;
if (done) break; /* done? */
/* Record pointer */
rec = inOTF->buffer;
if (lastScan<0.0) {
lastScan = rec[inOTF->myDesc->ilocscan]; /* Which scan number */
lastTarget = rec[inOTF->myDesc->iloctar]; /* Which target number */
t0 = rec[inOTF->myDesc->iloct]; /* Start time */
}
/* Loop over buffer */
for (ibuf=0; ibuf<inOTF->myDesc->numRecBuff; ibuf++) {
/* Finished solution interval? */
if ((rec[inOTF->myDesc->iloct] > (t0+solInt)) ||
/* or end of scan */
( rec[inOTF->myDesc->ilocscan] != lastScan) ||
/* or exceed limit on number of samples */
(nsample>=MAXBLSAMPLE)) {
if (msample==0) tbeg = t0; /* save start time */
tend = time[nsample-1]; /* save end time */
mtime[msample] = meanValue(time, 1, nsample) - tbeg;
mwt[msample] = (ofloat)nsample; /* weight by number of samples */
if (someOK) {
for (j=0; j<ndetect; j++ )
mdata[msample+j*MAXSISAMPLE] =
GetSolnMedianAvg(&data[j*MAXBLSAMPLE], 1, nsample);
} else {
for (j=0; j<ndetect; j++ ) mdata[msample+j*MAXSISAMPLE] = fblank;
}
if (msample<MAXSISAMPLE-1) msample++;
/* reset SI accumulators */
nsample = 0;
t0 = rec[inOTF->myDesc->iloct];
someOK = FALSE;
} /* end process SI */
/* Finished Scan? */
if (rec[inOTF->myDesc->ilocscan] != lastScan) {
/* Fit polynomials */
if (msample>order) torder = order;
else torder = MAX (0, msample-1);
for (j=0; j<ndetect; j++ )
FitBLPoly (&poly[j*(torder+1)], torder, mtime, &mdata[j*MAXSISAMPLE],
mwt, msample);
/* Write beginnning (tbeg) solution */
/* Fill Soln row */
row->Target = (oint)(lastTarget+0.5);
row->Time = tbeg;
for (j=0; j<ndetect; j++)
row->add[j] = -EvalPoly (torder, &poly[j*(torder+1)], tbeg - tbeg);
iRow = -1;
ObitTableOTFSolnWriteRow (outSoln, iRow, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Write output solutions */
for (k=0; k<msample; k++) {
/* Fill Soln row */
row->Time = mtime[k] + tbeg;
for (j=0; j<ndetect; j++)
row->add[j] = -EvalPoly (torder, &poly[j*(torder+1)], mtime[k]);
ObitTableOTFSolnWriteRow (outSoln, iRow, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
} /* end loop over solution intervals */
/* Add end (tend) solution */
/* Fill Soln row */
row->Time = tend;
for (j=0; j<ndetect; j++)
row->add[j] = -EvalPoly (torder, &poly[j*(torder+1)], tend - tbeg);
ObitTableOTFSolnWriteRow (outSoln, iRow, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* reset scan accumulators */
lastScan = rec[inOTF->myDesc->ilocscan];
msample = 0;
} /* end finish scan */
/* Is data below the elevation limit? */
el = ObitOTFArrayGeomElev (inOTF->geom, rec[inOTF->myDesc->iloct],
rec[inOTF->myDesc->ilocra],
rec[inOTF->myDesc->ilocdec]);
flag = (el < minEl);
/* accumulate */
time[nsample] = rec[inOTF->myDesc->iloct];
if (!flag) { /* OK */
/* VEGAS different use, parallel poln and feeds */
j = 0;
if (desc->OTFType==OBIT_GBTOTF_VEGAS) {
/* Loop over feed */
for (ifeed=0; ifeed<nfeed; ifeed++) {
/* Loop over parallel Stokes */
for (istok=0; istok<nscal; istok++) {
data[nsample+j*MAXSAMPLE] =
rec[ilocdata + ifeed*incfeed + istok*incs];
someOK = someOK || (data[nsample+j*MAXBLSAMPLE]!=fblank);
j++;
} /* end Stokes loop */
} /* end feed loop */
} else { /* Non VEGAS */
for (j=0; j<ndetect; j++ ) {
data[nsample+j*MAXBLSAMPLE] = rec[inOTF->myDesc->ilocdata+j*incdatawt];
someOK = someOK || (data[nsample+j*MAXBLSAMPLE]!=fblank);
}
} /* end non VEGAS */
someData = someData || someOK; /* Any valid data? */
} else { /* too low el - blank */
for (j=0; j<ndetect; j++ ) data[nsample+j*MAXBLSAMPLE] = fblank;
}
nsample++; /* how many samples in buffer */
lastTarget = rec[inOTF->myDesc->iloctar]; /* Which target number */
rec += inOTF->myDesc->lrec; /* Update data record pointer */
} /* end loop over buffer load */
} /* end loop reading data */
/* Do last SI still in arrays*/
if (nsample>1) {
/* Finished solution interval? */
if (msample==0) tbeg = t0; /* save start time */
tend = time[nsample-1]; /* save end time */
mtime[msample] = meanValue(time, 1, nsample) - tbeg;
mwt[msample] = (ofloat)nsample; /* weight by number of samples */
if (someOK) {
for (j=0; j<ndetect; j++ )
mdata[msample+j*MAXSISAMPLE] = GetSolnMedianAvg(&data[j*MAXBLSAMPLE], 1, nsample);
} else {
for (j=0; j<ndetect; j++ ) mdata[msample+j*MAXSISAMPLE] = fblank;
}
if (msample<MAXSISAMPLE-1) msample++;
} /* end process SI */
/* Something left in last scan? */
if (msample>1) {
/* Fit polynomials */
if (msample>order) torder = order;
else torder = MAX (0, msample-1);
for (j=0; j<ndetect; j++ )
FitBLPoly (&poly[j*(torder+1)], torder, mtime, &mdata[j*MAXSISAMPLE],
mwt, msample);
/* Write beginnning (tbeg) solution */
/* Fill Soln row */
row->Target = (oint)(lastTarget+0.5);
row->Time = tbeg;
for (j=0; j<ndetect; j++)
row->add[j] = -EvalPoly (torder, &poly[j*(torder+1)], tbeg - tbeg);
iRow = -1;
ObitTableOTFSolnWriteRow (outSoln, iRow, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Write output solutions */
for (k=0; k<msample; k++) {
/* Fill Soln row */
row->Time = mtime[k] + tbeg;
for (j=0; j<ndetect; j++)
row->add[j] = -EvalPoly (torder, &poly[j*(torder+1)], mtime[k]);
ObitTableOTFSolnWriteRow (outSoln, iRow, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
} /* end loop over solution intervals */
/* Add end (tend) solution */
/* Fill Soln row */
row->Time = tend;
for (j=0; j<ndetect; j++)
row->add[j] = -EvalPoly (torder, &poly[j*(torder+1)], tend - tbeg);
ObitTableOTFSolnWriteRow (outSoln, iRow, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
} /* end finish scan */
/* Close output cal table */
ObitTableOTFSolnClose (outSoln, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Close data */
retCode = ObitOTFClose (inOTF, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Give warning if no data selected */
if (!someData) Obit_log_error(err, OBIT_InfoWarn,
"%s: Warning: NO data selected", routine);
/* Cleanup */
filter = ObitTimeFilterUnref(filter);
row = ObitTableOTFSolnUnref(row);
if (time) g_free(time);
if (data) g_free(data);
if (mtime) g_free(mtime);
if (mdata) g_free(mdata);
if (mwt) g_free(mwt);
if (poly ) g_free(poly);
return outSoln;
} /* end ObitOTFGetSolnPolyBL */
/**
* Baseline removal for multibeam instrument.
* Fit one term, time variable common, atmospheric polynomial and a single offset
* per detector.
* Since the different detectors each have an individual multiplicative term, the
* Atmospheric + offset are places in the the detector's additive term and the
* polynomical is set to zero.
* Scans in excess of 5000 samples will be broken into several.
* Either detector offsets, common mode variations or both may be selected to Soln.
* Calibration parameters are on the inOTF info member.
* \li "solInt" OBIT_float (1,1,1) Solution interval in days [def 10 sec].
* \li "maxInt" OBIT_float (1,1,1) max. Interval in days [def 10 min].
* Scans longer than this will be broken into pieces
* \li "Tau0" OBIT_float (?,?,1) Zenith opacity in nepers [def 0].
* Can be passed as either a constant scalar or
* an array of (time, tau0) pairs.
* \li "minEl" OBIT_float (1,1,1) Minimum elevation allowed (deg)
* \li "clipSig" OBIT_float (1,1,1) data outside of range +/- Clip sigma are blanked
* [def very large -> no clipping]
* \li "plotDet" OBIT_long (1,1,1) Detector number to plot per scan [def =-1 = none]
* \li "calType" OBIT_string (*,1,1) Calibration type desired [def "Both"]
* "Both" => Detector offsets and common mode poly
* "Common" => common mode poly
* "Offset" Detector offsets
* \param inOTF Input OTF data.
* \param outOTF OTF with which the output OTFSoln is to be associated
* \param err Error stack, returns if not empty.
* \return Pointer to the newly created OTFSoln object which is
* associated with inOTF.
*/
ObitTableOTFSoln* ObitOTFGetSolnMBBase (ObitOTF *inOTF, ObitOTF *outOTF, ObitErr *err)
{
ObitTableOTFSoln *outSoln=NULL;
ObitTableOTFSolnRow *row=NULL;
gint32 taudim[MAXINFOELEMDIM] = {1,1,1,1,1}, dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
ObitIOAccess access;
ofloat *tau0, tMult, airmass;
ofloat lastScan=-1.0, lastTarget=-1.0, lastTime=-1000.0;
ofloat *rec=NULL, solInt, maxInt, minEl, el, t0, fblank = ObitMagicF();
ofloat *time=NULL, *data=NULL, *poly=NULL, *tpoly=NULL, *offset=NULL, *wt=NULL, clipsig;
olong iRow, ver, i, j, k, ibuf, lrec, nsample, npoly, off;
olong mpoly, ndetect, plotDetect, incdatawt;
ObitIOCode retCode;
gboolean flag, doCalSelect, someOK, someData, done, doCommon, doOffset;
gchar *tname, calType[50];
gchar *routine = "ObitOTFGetSolnMBBase";
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return outSoln;
g_assert (ObitOTFIsA(inOTF));
/* Calibration wanted? */
doCalSelect = FALSE;
ObitInfoListGetTest(inOTF->info, "doCalSelect", &type, (gint32*)dim, &doCalSelect);
if (doCalSelect) access = OBIT_IO_ReadCal;
else access = OBIT_IO_ReadWrite;
/* open OTF data if not already open */
if ((inOTF->myStatus==OBIT_Inactive) || (inOTF->myStatus==OBIT_Defined)) {
retCode = ObitOTFOpen (inOTF, access, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
}
/* Create output */
tname = g_strconcat ("Calibration for: ",inOTF->name, NULL);
ver = 0;
mpoly = 1;
outSoln = newObitTableOTFSolnValue(tname, (ObitData*)outOTF, &ver, OBIT_IO_WriteOnly,
inOTF->geom->numberDetect, mpoly, err);
g_free (tname);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Create work arrays */
ndetect = inOTF->geom->numberDetect; /* number of detectors */
lrec = inOTF->myDesc->lrec;
time = g_malloc0(MAXSAMPSCAN*sizeof(ofloat));
data = g_malloc0(ndetect*MAXSAMPSCAN*sizeof(ofloat));
wt = g_malloc0(ndetect*MAXSAMPSCAN*sizeof(ofloat));
offset = g_malloc0(ndetect*sizeof(ofloat));
nsample = 0;
t0 = -1.0e20; lastScan = -1000.0;
time[0] = 1.0e20; /* No data yet */
incdatawt = inOTF->myDesc->incdatawt; /* increment in data-wt axis */
/* Get parameters for calibration */
/* Solution interval default 10 sec */
solInt = 10.0 / 86400.0;
ObitInfoListGetTest(inOTF->info, "solInt", &type, dim, (gpointer*)&solInt);
/* maximum interval default 10 min */
maxInt = 10.0 * 60.0 / 86400.0;
ObitInfoListGetTest(inOTF->info, "maxInt", &type, dim, (gpointer*)&maxInt);
/* minimum allowed elevation for solution */
minEl = 1.0;
ObitInfoListGetTest(inOTF->info, "minEl", &type, dim, (gpointer*)&minEl);
/* Clip value */
clipsig = 1.0e20;
ObitInfoListGetTest(inOTF->info, "clipSig", &type, dim, (gpointer*)&clipsig);
if (clipsig<1.0e19)
Obit_log_error(err, OBIT_InfoErr, "%s: Clipping outliers at %7.2f sigma",
routine, clipsig);
/* Opacity */
tau0 = NULL;
ObitInfoListGetP(inOTF->info, "Tau0", &type, taudim, (gpointer*)&tau0);
/* Detector to plot */
plotDetect = -1;
ObitInfoListGetTest(inOTF->info, "plotDet", &type, dim, &plotDetect);
/* calibration type */
for (i=0; i<50; i++) calType[i] = 0;
strcpy (calType, "Both");
ObitInfoListGetTest(inOTF->info, "calType", &type, dim, calType);
/* What calibrations are desired? */
doCommon = FALSE; doOffset = FALSE;
if (!strncmp(calType, "Common",4)) doCommon = TRUE;
else if (!strncmp(calType, "Offset",6)) doOffset = TRUE;
else if (!strncmp(calType, "Both",10)) {doCommon=TRUE; doOffset = TRUE;}
else {doCommon=TRUE; doOffset = TRUE;}
/* Open output table */
if ((ObitTableOTFSolnOpen (outSoln, OBIT_IO_WriteOnly, err)
!= OBIT_IO_OK) || (err->error)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s ERROR opening input OTFSoln table", routine);
goto cleanup;
}
/* Create Row */
row = newObitTableOTFSolnRow (outSoln);
/* Attach row to output buffer */
ObitTableOTFSolnSetRow (outSoln, row, err);
if (err->error) goto cleanup;
/* Initialize solution row */
row->dAz = 0.0; /* no pointing corrections */
row->dEl = 0.0; /* no pointing corrections */
row->Target = 0;
for (j=0; j<ndetect; j++) row->mult[j] = 1.0;
for (j=0; j<ndetect; j++) row->wt[j] = 1.0;
for (j=0; j<ndetect; j++) row->cal[j] = 0.0;
for (j=0; j<ndetect; j++) row->add[j] = 0.0;
flag = FALSE;
someOK = FALSE;
someData = FALSE;
/* loop over input data */
retCode = OBIT_IO_OK;
while (retCode == OBIT_IO_OK) {
/* read buffer */
if (doCalSelect) retCode = ObitOTFReadSelect (inOTF, NULL, err);
else retCode = ObitOTFRead (inOTF, NULL, err);
if (err->error) goto cleanup;
done = retCode==OBIT_IO_EOF;
if (done) break; /* done? */
/* Record pointer */
rec = inOTF->buffer;
if (lastScan<0.0) {
lastScan = rec[inOTF->myDesc->ilocscan]; /* Which scan number */
lastTarget = rec[inOTF->myDesc->iloctar]; /* Which target number */
}
/* Loop over buffer */
for (ibuf=0; ibuf<inOTF->myDesc->numRecBuff; ibuf++) {
/* Scan read? maxInt? If so, compute solution and write. Also if work arrays full */
if (( rec[inOTF->myDesc->ilocscan] != lastScan) || /* new scan */
((rec[inOTF->myDesc->iloct]-time[0])>maxInt) || /* or maxInt Done */
(nsample>=MAXSAMPSCAN) || done) { /* or exceed limit on number of samples, or done */
/* Any good data to process? */
if (someOK) {
/* time relative to first integration */
t0 = time[0];
for (i=0; i<nsample; i++) time[i] -= t0;
/* DEBUG
fprintf (stderr,"DEBUG lastScan %f \n", lastScan); */
/* Fit data */
FitMBBLPoly (solInt, &npoly, &tpoly, &poly, offset, ndetect, MAXSAMPSCAN, time,
data, wt, nsample);
/* reject outlyers */
FitMBBLOut (npoly, tpoly, poly, offset, ndetect, MAXSAMPSCAN, time,
data, wt, nsample, clipsig);
/* Again to be sure */
FitMBBLOut (npoly, tpoly, poly, offset, ndetect, MAXSAMPSCAN, time,
data, wt, nsample, clipsig);
if (tpoly) g_free(tpoly); tpoly = NULL;/* free work memory */
if (poly) g_free(poly); poly = NULL;
/* refit data */
FitMBBLPoly (solInt, &npoly, &tpoly, &poly, offset, ndetect, MAXSAMPSCAN, time,
data, wt, nsample);
/* Plot? */
if (plotDetect>0)
PlotMBBL (npoly, tpoly, poly, offset, ndetect, MAXSAMPSCAN, time,
data, wt, nsample, plotDetect, t0, err);
if (err->error) goto cleanup;
} /* end of fit good data */
/* Loop over time segments */
off = 0;
if (tpoly==NULL) npoly = 0; /* In case no good data */
for (k=0; k<npoly; k++) {
/* Set descriptive info on Row */
row->TimeI = solInt; /* time interval*/
row->Target = (oint)(lastTarget+0.5);
row->Time = tpoly[k] + t0; /* start time */
/* Opacity correction */
el = ObitOTFArrayGeomElev (inOTF->geom, row->Time,
rec[inOTF->myDesc->ilocra],
rec[inOTF->myDesc->ilocdec]);
if (el > 0.1)
airmass = 1.0 / cos (DG2RAD * (90.0 - el));
else
airmass = 10.0;
tMult = exp (getTau0(row->Time,taudim,tau0) * airmass); /* multiplicative term */
for (j=0; j<ndetect; j++) row->mult[j] = tMult;
/* solution (as correction) */
if (someOK && (poly[2*k]!=fblank)) { /* Some data and fit OK */
/* Find and evaluate time segment */
while ((tpoly[k+1]>time[off]) && (off<nsample)) {off++;}
if (doCommon) row->poly[0] = -(poly[2*k] + poly[2*k+1]*(tpoly[k]));
else row->poly[0] = 0.0;
/* row->poly[0] = 0.0; DEBUG */
for (j=0; j<ndetect; j++) {
if (doOffset) {
if (offset[j]!=fblank) row->add[j] = -offset[j];
else row->add[j] = fblank;
} else row->add[j] = 0.0;
}
} else { /* no good data - blank */
for (j=0; j<ndetect; j++) row->add[j] = fblank;
row->poly[0] = fblank;
}
/* Write Soln table for beginning and end of segment */
iRow = -1;
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
goto cleanup;
}
row->Time = MIN (t0, lastTime); /* end time */
/* Opacity correction */
el = ObitOTFArrayGeomElev (inOTF->geom, row->Time,
rec[inOTF->myDesc->ilocra],
rec[inOTF->myDesc->ilocdec]);
if (el > 0.1)
airmass = 1.0 / cos (DG2RAD * (90.0 - el));
else
airmass = 10.0;
tMult = exp (getTau0(row->Time,taudim,tau0) * airmass); /* multiplicative term */
for (j=0; j<ndetect; j++) row->mult[j] = tMult;
/* solution (as correction) */
if (someOK && (poly[2*k]!=fblank)) { /* Some data and fit OK */
row->Time = MIN (tpoly[k+1]+t0, lastTime); /* end time */
/* Find and evaluate time segment */
while ((tpoly[k+1]>time[off]) && (off<nsample)) {off++;}
row->poly[0] = -(poly[2*k] + poly[2*k+1]*(tpoly[k+1]));
for (j=0; j<ndetect; j++) {
if (offset[j]!=fblank) row->add[j] = -offset[j];
else row->add[j] = fblank;
}
} else { /* no good data - blank */
for (j=0; j<ndetect; j++) row->add[j] = fblank;
row->poly[0] = fblank;
}
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
goto cleanup;
}
} /* end loop over time segments */
/* initialize accumulators */
if (tpoly) g_free(tpoly); tpoly = NULL;/* free work memory */
if (poly) g_free(poly); poly = NULL;
nsample = 0;
lastScan = -1000.0;
someOK = FALSE;
} /* end do solution */
/* Is data below the elevation limit? */
el = ObitOTFArrayGeomElev (inOTF->geom, rec[inOTF->myDesc->iloct],
rec[inOTF->myDesc->ilocra],
rec[inOTF->myDesc->ilocdec]);
flag = (el < minEl);
/* accumulate */
time[nsample] = rec[inOTF->myDesc->iloct];
lastTime = time[nsample];
if (!flag) { /* OK */
for (j=0; j<ndetect; j++ ) {
data[nsample+j*MAXSAMPSCAN] = rec[inOTF->myDesc->ilocdata+j*incdatawt];
someOK = someOK || (data[nsample+j*MAXSAMPSCAN]!=fblank);
if (data[nsample+j*MAXSAMPSCAN]!=fblank) {
wt[nsample+j*MAXSAMPSCAN] = 1.0;
} else {
wt[nsample+j*MAXSAMPSCAN] = 0.0;
}
}
someData = someData || someOK; /* Any valid data? */
} else { /* too low el - blank */
for (j=0; j<ndetect; j++ ) data[nsample+j*MAXSAMPSCAN] = fblank;
for (j=0; j<ndetect; j++ ) wt[nsample+j*MAXSAMPSCAN] = 0.0;
}
nsample++; /* how many samples in buffer */
if (lastScan<0.0) {
lastScan = rec[inOTF->myDesc->ilocscan]; /* Which scan number */
}
lastTarget = rec[inOTF->myDesc->iloctar]; /* Which target number */
rec += inOTF->myDesc->lrec; /* Update data record pointer */
} /* end loop over buffer load */
} /* end loop reading data */
/* Do last scan still in arrays*/
if (nsample>1) {
/* Any good data to process? */
if (someOK) {
/* time relative to first integration */
t0 = time[0];
for (i=0; i<nsample; i++) time[i] -= t0;
/* DEBUG
fprintf (stderr,"DEBUG lastScan %f \n", lastScan); */
/* Fit data */
FitMBBLPoly (solInt, &npoly, &tpoly, &poly, offset, ndetect, MAXSAMPSCAN, time,
data, wt, nsample);
/* reject outlyers */
FitMBBLOut (npoly, tpoly, poly, offset, ndetect, MAXSAMPSCAN, time,
data, wt, nsample, clipsig);
/* Again to be sure */
FitMBBLOut (npoly, tpoly, poly, offset, ndetect, MAXSAMPSCAN, time,
data, wt, nsample, clipsig);
if (tpoly) g_free(tpoly); tpoly = NULL;/* free work memory */
if (poly) g_free(poly); poly = NULL;
/* refit data */
FitMBBLPoly (solInt, &npoly, &tpoly, &poly, offset, ndetect, MAXSAMPSCAN, time,
data, wt, nsample);
/* Plot? */
if (plotDetect>0)
PlotMBBL (npoly, tpoly, poly, offset, ndetect, MAXSAMPSCAN, time,
data, wt, nsample, plotDetect, t0, err);
if (err->error) goto cleanup;
} /* end of fit good data */
/* Loop over time segments */
off = 0;
if (tpoly==NULL) npoly = 0; /* In case no good data */
for (k=0; k<npoly; k++) {
/* Set descriptive info on Row */
row->TimeI = 0.5*solInt; /* time interval*/
row->Target = (oint)(lastTarget+0.5);
row->Time = tpoly[k] + t0; /* start time */
/* solution (as correction) */
if (someOK && (poly[2*k]!=fblank)) { /* Some data OK */
/* Find and evaluate time segment */
while ((tpoly[k+1]>time[off]) && (off<nsample)) {off++;}
if (doCommon) row->poly[0] = -(poly[2*k] + poly[2*k+1]*(tpoly[k]));
else row->poly[0] = 0.0;
for (j=0; j<ndetect; j++) {
if (doOffset) {
if (offset[j]!=fblank) row->add[j] = -offset[j];
else row->add[j] = fblank;
} else row->add[j] = 0.0;
}
} else { /* no good data - blank */
for (j=0; j<ndetect; j++) row->add[j] = fblank;
row->poly[0] = fblank;
}
/* Write Soln table for beginning and end of segment */
iRow = -1;
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
goto cleanup;
}
row->Time = MIN (t0, lastTime); /* end time */
/* Opacity correction */
el = ObitOTFArrayGeomElev (inOTF->geom, row->Time,
rec[inOTF->myDesc->ilocra],
rec[inOTF->myDesc->ilocdec]);
if (el > 0.1)
airmass = 1.0 / cos (DG2RAD * (90.0 - el));
else
airmass = 10.0;
tMult = exp (getTau0(row->Time,taudim,tau0) * airmass); /* multiplicative term */
for (j=0; j<ndetect; j++) row->mult[j] = tMult;
/* solution (as correction) */
if (someOK && (poly[2*k]!=fblank)) { /* Some data OK */
row->Time = MIN (tpoly[k+1]+t0, lastTime); /* end time */
/* Find and evaluate time segment */
while ((tpoly[k+1]>time[off]) && (off<nsample)) {off++;}
row->poly[0] = -(poly[2*k] + poly[2*k+1]*(tpoly[k+1]));
/* row->poly[0] = 0.0; DEBUG */
for (j=0; j<ndetect; j++) {
if (offset[j]!=fblank) row->add[j] = -offset[j];
else row->add[j] = fblank;
}
} else { /* no good data - blank */
for (j=0; j<ndetect; j++) row->add[j] = fblank;
row->poly[0] = fblank;
}
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
goto cleanup;
} /* end loop over time segments */
} /* end loop over polynomials */
} /* end finish up data in arrays */
/* Close output cal table */
if ((ObitTableOTFSolnClose (outSoln, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s ERROR closing output OTFSoln Table file", routine);
goto cleanup;
}
/* Close data */
retCode = ObitOTFClose (inOTF, err);
if (err->error) goto cleanup;
/* Give warning if no data selected */
if (!someData) Obit_log_error(err, OBIT_InfoWarn,
"%s: Warning: NO data selected", routine);
/* Deallocate arrays */
cleanup:
row = ObitTableOTFSolnUnref(row);
if (time) g_free(time);
if (data) g_free(data);
if (wt) g_free(wt);
if (offset) g_free(offset);
if (tpoly) g_free(tpoly); /* free work memory */
if (poly) g_free(poly);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
return outSoln;
} /* end ObitOTFGetSolnMBBase */
/**
* Determine estimates of the cal value from a set of data and then
* calculate the median value.
* Successive off/on/off triplets are used for each estimate.
* \param n number of data values
* \param isCal For each datum, TRUE if cal on.
* \param data On input the data values, will be replaced on output
* by the sequence of valid estimates of the cal.
* \return Median Cal value or fblank if not possible
*/
ofloat ObitOTFGetSolnAvgCal (olong n, gboolean *isCal, ofloat *data)
{
olong i, j, prior, follow, ngood=0;
ofloat fblank = ObitMagicF();
/* loop over data looking for cal on with previous and following cal off*/
ngood = 0;
for (i=1; i<n-1; i++) {
/* if cal off ignore this one of invalid datum */
if ((!isCal[i]) || (data[i]==fblank)) continue;
/* find previous good cal off */
prior = -1;
for (j=i-1; j>=0; j--) {
if (!isCal[j] && (data[j]!=fblank)) {
prior = j;
break;
}
}
/* if not found, ignore */
if (prior<0) continue;
/* find following good cal off */
follow = -1;
for (j=i+1; j<n; j++) {
if (!isCal[j] && (data[j]!=fblank)) {
follow = j;
break;
}
}
/* if not found, ignore */
if (follow<0) continue;
/* Add it to the good list */
data[ngood++] = data[i] - 0.5*(data[prior] + data[follow]);
} /* end loop over data */
/* any good data? */
if (ngood<1) return fblank;
/* Get median */
return GetSolnMedianAvg (data, 1, ngood);
} /* end ObitOTFGetSolnAvgCal */
/**
* Determine instrumental calibration for an OTF multibeam OTF dataset.
* Calculates average gain from cal measurements
* calculates median ofset
* Calibration parameters are on the inOTF info member.
* \li "solInt" OBIT_float (1,1,1) Solution interval in days [def 1 sec].
* \param inOTF Input OTF data.
* \param outOTF OTF with which the output OTFSoln is to be associated
* \param err Error stack, returns if not empty.
* \return Pointer to the newly created OTFSoln object which is
* associated with outOTF.
*/
ObitTableOTFSoln* ObitOTFGetInstCal (ObitOTF *inOTF, ObitOTF *outOTF, ObitErr *err)
{
#define MAXSAMPLE 1000 /* Maximum number of samples in an integration */
ObitTableOTFSoln *outSoln=NULL;
ObitTableOTFSolnRow *row=NULL;
ObitOTFDesc *desc=NULL;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
ofloat *rec, solInt, t0, *iCal, val, **accum, sumTime, fblank = ObitMagicF();
ofloat lastTarget=-1.0, lastScan=-1.0, lastTime=-1.0, *lastCal=NULL;
olong iRow, ver, i, j, k, lrec, ncoef;
olong npoly, nDet, nTime, incdatawt;
ObitIOCode retCode;
gboolean someData;
gchar *tname;
gchar *routine = "ObitOTFGetInstCal";
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return outSoln;
g_assert (ObitOTFIsA(inOTF));
desc = inOTF->myDesc;
/* open OTF data to fully instantiate if not already open */
if ((inOTF->myStatus==OBIT_Inactive) || (inOTF->myStatus==OBIT_Defined)) {
retCode = ObitOTFOpen (inOTF, OBIT_IO_ReadWrite, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
}
/* Create output */
tname = g_strconcat ("Calibration for: ",inOTF->name, NULL);
ver = 0;
ncoef = 1;
npoly = ncoef;
outSoln = newObitTableOTFSolnValue(tname, (ObitData*)outOTF, &ver, OBIT_IO_WriteOnly,
inOTF->geom->numberDetect, npoly, err);
g_free (tname);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Create work arrays */
nDet = inOTF->geom->numberDetect;
lrec = inOTF->myDesc->lrec;
iCal = g_malloc0(MAXSAMPLE*sizeof(ofloat));
lastCal = g_malloc0(nDet*sizeof(ofloat));
for (i=0; i<nDet; i++) lastCal[i] = fblank;
accum = g_malloc0(nDet*sizeof(ofloat*));
for (i=0; i<nDet; i++) accum[i] = g_malloc0(MAXSAMPLE*sizeof(ofloat));
t0 = -1.0e20;
incdatawt = inOTF->myDesc->incdatawt; /* increment in data-wt axis */
someData = FALSE;
/* Get parameters for calibration */
/* Solution interval default 1 sec */
solInt = 1.0 / 86400.0;
ObitInfoListGetTest(inOTF->info, "solInt", &type, dim, (gpointer*)&solInt);
/* Open table */
if ((ObitTableOTFSolnOpen (outSoln, OBIT_IO_WriteOnly, err)
!= OBIT_IO_OK) || (err->error)) { /* error test */
Obit_log_error(err, OBIT_Error, "ERROR opening input OTFSoln table");
return outSoln;
}
/* Create Row */
row = newObitTableOTFSolnRow (outSoln);
/* Attach row to output buffer */
ObitTableOTFSolnSetRow (outSoln, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* loop calibrating data */
retCode = OBIT_IO_OK;
sumTime = 0.0;
nTime = 0;
while (retCode == OBIT_IO_OK) {
/* read buffer */
retCode = ObitOTFRead (inOTF, NULL, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
if (retCode==OBIT_IO_EOF) break; /* done? */
/* Record pointer */
rec = inOTF->buffer;
/* First time */
if (t0<-1.0e10) {
t0 = rec[inOTF->myDesc->iloct];
lastTime = rec[inOTF->myDesc->iloct];
lastTarget = rec[inOTF->myDesc->iloctar];
lastScan = rec[inOTF->myDesc->ilocscan];
}
/* Loop over buffer */
for (i=0; i<inOTF->myDesc->numRecBuff; i++) {
/* Accumulation finished? If so, compute solution and write.*/
if ((rec[inOTF->myDesc->iloct] > (t0+solInt)) || (nTime>=MAXSAMPLE) ||
(rec[inOTF->myDesc->iloctar] != lastTarget) ||
(rec[inOTF->myDesc->ilocscan] != lastScan)) {
/* Not first time - assume first descriptive parameter never blanked */
if (nTime>0) {
/* Set descriptive info on Row */
row->Time = sumTime/nTime; /* center time */
row->TimeI = 2.0 * (row->Time - t0);
/* Get calibration */
ObitOTFGetInstSolve (inOTF->geom, inOTF->myDesc, nDet, nTime, accum, iCal, row);
/* Propagate last good cals if needed */
for (j=0; j<nDet; j++ ) {
if (row->cal[j]==fblank) {
row->cal[j] = lastCal[j];
row->mult[j] = 1.0 / lastCal[j];
}
lastCal[j] = row->cal[j];
}
/* Write Soln table - bracket interval */
iRow = -1;
row->Target = (oint)(lastTarget+0.5);
row->Time = t0;
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "ERROR writing OTFSoln Table file");
return outSoln;
}
row->Time = lastTime;
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "ERROR writing OTFSoln Table file");
return outSoln;
}
/* initialize accumulators */
t0 = rec[inOTF->myDesc->iloct];
lastTime = rec[inOTF->myDesc->iloct];
lastTarget = rec[inOTF->myDesc->iloctar];
lastScan = rec[inOTF->myDesc->ilocscan];
sumTime = 0.0;
nTime = 0;
for (k=0; k<MAXSAMPLE; k++) iCal[k] = 0;
for (j=0; j<nDet; j++ ) {
for (k=0; k<MAXSAMPLE; k++) accum[j][k] = 0.0;
}
} /* end of do solution if there is data */
} /* end do solution */
/* accumulate */
lastTime = rec[inOTF->myDesc->iloct];
sumTime += rec[inOTF->myDesc->iloct];
iCal[nTime] = fabs(rec[inOTF->myDesc->iloccal]);
for (j=0; j<nDet; j++ ) {
val = rec[desc->ilocdata+j*incdatawt];
if (val != fblank) {
accum[j][nTime] = val;
}
}
nTime++; /* how many data points */
someData = TRUE;
rec += inOTF->myDesc->lrec; /* Data record pointer */
} /* end loop over buffer load */
} /* end loop reading/gridding data */
/* Finish up any data in accumulator */
if (nTime>0) {
/* Set descriptive info on Row */
row->Time = sumTime/nTime; /* time */
row->TimeI = 2.0 * (row->Time - t0);
/* Get calibration */
ObitOTFGetInstSolve (inOTF->geom, inOTF->myDesc, nDet, nTime, accum, iCal, row);
rec += inOTF->myDesc->lrec; /* Data record pointer */
/* Propagate last good cals if needed */
for (j=0; j<nDet; j++ ) {
if (row->cal[j]==fblank) {
row->cal[j] = lastCal[j];
row->mult[j] = 1.0 / lastCal[j];
}
}
/* Write Soln table - bracket interval */
iRow = -1;
row->Time = t0;
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "ERROR writing OTFSoln Table file");
return outSoln;
}
row->Time = lastTime;
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "ERROR writing OTFSoln Table file");
return outSoln;
}
} /* End final solution */
/* Close cal table */
if ((ObitTableOTFSolnClose (outSoln, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "ERROR closing input OTFSoln Table file");
return outSoln;
}
/* Close data */
retCode = ObitOTFClose (inOTF, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Give warning if no data selected */
if (!someData) Obit_log_error(err, OBIT_InfoWarn,
"%s: Warning: NO data selected", routine);
/* Cleanup */
for (k=0; k<nDet; k++) if (accum[k]) g_free(accum[k]);
if (accum) g_free(accum);
if (iCal) g_free(iCal);
if (lastCal) g_free(lastCal);
return outSoln;
} /* end ObitOTFGetInstCal */
/**
* Determine instrumental gain from Penn Array-like cal measurements
* Penn Array-like = slow switching, many samples between state changes.
* Average On and Off for each detector and differences
* Mult factor = calJy/(cal_on-cal_off) per detector, may be negative.
* Data scan averaged and repeated for any subsequent scans without cal On data
* If doWate==True then determine weights from the reciprocal of the variance
* in scans which have both cal-on and cal-off measurements; values are reused
* between such scans
* Write Soln entries at beginning and end of each scan.
* Note: Any scans prior to a scan with calibration data will be flagged.
* \li "calJy" OBIT_float (*,1,1) Calibrator value in Jy per detector [def 1.0] .
* Duplicates for all detectors if only one given.
* \li "doWate" OBIT_boolean (1,1,1) If true determine Weights from RMS [def False]
* \li "minSNR" OBIT_float (1,1,1) Minimum SNR for acceptable cal (ratio cal/RMS)
* Only used if doWate is True [def. 10.0]
* \param inOTF Input OTF data, prior calibration/selection applied if requested
* \param outOTF OTF with which the output OTFSoln is to be associated
* \param err Error stack, returns if not empty.
* \return Pointer to the newly created OTFSoln object which is
* associated with outOTF.
*/
ObitTableOTFSoln* ObitOTFGetSolnPARGain (ObitOTF *inOTF, ObitOTF *outOTF, ObitErr *err)
{
ObitTableOTFSoln *outSoln=NULL;
ObitTableOTFSolnRow *row=NULL;
ObitOTFDesc *desc=NULL;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
ObitIOAccess access;
ofloat *iCal, **accum, *time, blankID;
ofloat *rec, *calJy=NULL, minsnr, fblank = ObitMagicF();
ofloat t0, sumTime, lastTarget=-1.0, lastScan=-1.0, lastTime=-1.0;
ofloat snr, *lastCal=NULL, *lastWeight=NULL;
gboolean doCalSelect, doWate, fitWate, someData=FALSE, gotCal=FALSE;
olong iRow, ver, i, j, lrec, ncoef;
olong npoly, nDet, nTime, incdatawt;
ObitIOCode retCode;
gchar *tname;
gchar *routine = "ObitOTFGetSolnPARGain";
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return outSoln;
g_assert (ObitOTFIsA(inOTF));
desc = inOTF->myDesc;
/* Calibration wanted? */
doCalSelect = FALSE;
ObitInfoListGetTest(inOTF->info, "doCalSelect", &type, dim, &doCalSelect);
if (doCalSelect) access = OBIT_IO_ReadCal;
else access = OBIT_IO_ReadWrite;
/* Weights wanted? */
doWate = FALSE;
ObitInfoListGetTest(inOTF->info, "doWate", &type, dim, &doWate);
/* If weights are wanted lookup ID of "Blank" scans */
if (doWate) blankID = FindBlankID(inOTF, err);
else blankID = -1.0;
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* min SNR */
minsnr = 10.0;
ObitInfoListGetTest(inOTF->info, "minSNR", &type, dim, &minsnr);
/* open OTF data to fully instantiate if not already open */
if ((inOTF->myStatus==OBIT_Inactive) || (inOTF->myStatus==OBIT_Defined)) {
retCode = ObitOTFOpen (inOTF, access, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
}
/* Create output */
tname = g_strconcat ("Calibration for: ",inOTF->name, NULL);
ver = 0;
ncoef = 1;
npoly = ncoef;
outSoln = newObitTableOTFSolnValue(tname, (ObitData*)outOTF, &ver, OBIT_IO_WriteOnly,
inOTF->geom->numberDetect, npoly, err);
g_free (tname);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Create work arrays */
nDet = inOTF->geom->numberDetect;
lrec = desc->lrec;
lastCal = g_malloc0(nDet*sizeof(ofloat));
lastWeight = g_malloc0(nDet*sizeof(ofloat));
calJy = g_malloc0(nDet*sizeof(ofloat));
iCal = g_malloc0(MAXSAMPLE*sizeof(ofloat));
time = g_malloc0(MAXSAMPLE*sizeof(ofloat));
accum = g_malloc0(nDet*sizeof(ofloat*));
for (i=0; i<nDet; i++) accum[i] = g_malloc0(MAXSAMPLE*sizeof(ofloat));
for (i=0; i<nDet; i++) lastCal[i] = fblank;
for (i=0; i<nDet; i++) lastWeight[i] = fblank;
t0 = -1.0e20;
incdatawt = inOTF->myDesc->incdatawt; /* increment in data-wt axis */
/* cal value in Jy */
for (j=0; j<nDet; j++) calJy[j] = 1.0;
ObitInfoListGetTest(inOTF->info, "calJy", &type, dim, (gpointer*)calJy);
/* Duplicate if only one */
if (dim[0]==1) for (j=0; j<nDet; j++) calJy[j] = calJy[0];
/* Open table */
if ((ObitTableOTFSolnOpen (outSoln, OBIT_IO_WriteOnly, err)
!= OBIT_IO_OK) || (err->error)) { /* error test */
Obit_log_error(err, OBIT_Error, "ERROR opening input OTFSoln table");
goto cleanup;
}
/* Create Row */
row = newObitTableOTFSolnRow (outSoln);
/* Attach row to output buffer */
ObitTableOTFSolnSetRow (outSoln, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Initialize solution row */
row->dAz = 0.0; /* no pointing corrections */
row->dEl = 0.0; /* no pointing corrections */
row->Target = 0;
for (j=0; j<nDet; j++) row->mult[j] = 1.0;
for (j=0; j<nDet; j++) row->wt[j] = 1.0;
for (j=0; j<nDet; j++) row->cal[j] = 0.0;
for (j=0; j<nDet; j++) row->add[j] = 0.0;
for (i=0; i<npoly; i++) row->poly[i] = 0.0;
/* loop over data file */
retCode = OBIT_IO_OK;
sumTime = 0.0;
nTime = 0;
while (retCode == OBIT_IO_OK) {
/* read buffer */
if (doCalSelect) retCode = ObitOTFReadSelect (inOTF, NULL, err);
else retCode = ObitOTFRead (inOTF, NULL, err);
if (err->error) goto cleanup;
if (retCode==OBIT_IO_EOF) break; /* done? */
/* Record pointer */
rec = inOTF->buffer;
/* First time */
if (t0<-1.0e10) {
t0 = rec[desc->iloct];
lastTime = rec[desc->iloct];
lastTarget = rec[desc->iloctar];
lastScan = rec[desc->ilocscan];
}
/* Loop over buffer */
for (i=0; i<desc->numRecBuff; i++) {
/* Accumulation (scan) finished? If so, compute solution and write.*/
if ((rec[desc->iloctar] != lastTarget) || (nTime>=MAXSAMPLE) ||
(rec[desc->ilocscan] != lastScan)) {
/* Not first time - assume first descriptive parameter never blanked */
if (nTime>0) {
/* Set descriptive info on Row */
row->Time = sumTime/nTime; /* center time */
row->TimeI = 2.0 * (row->Time - t0);
/* Flatten curves, estimate cal, Weights */
/* Is this a "Blank Scan? */
fitWate = (fabs(lastTarget-blankID)<0.1) || (blankID<0.0);
doPARCalWeight(nDet, nTime, iCal, accum, time, lastCal, lastWeight, fitWate);
/* Propagate last good cals if needed */
for (j=0; j<nDet; j++ ) {
row->cal[j] = lastCal[j];
if (lastCal[j]!=fblank) row->mult[j] = calJy[j] / lastCal[j];
else row->mult[j] = 1.0;
}
/* Calibrating weights? Propagate last weight */
if (doWate) {
for (j=0; j<nDet; j++ ) {
/* Acceptable SNR? */
if ((lastCal[j]!=fblank) && (lastWeight[j]!=fblank)) {
snr = fabs(lastCal[j]) * sqrt(lastWeight[j]);
if (snr < minsnr) {
/* No - off with their heads! */
row->wt[j] = 0.0;
row->add[j] = fblank;
}
} /* End check SNR */
if (lastWeight[j]!=fblank) {
row->wt[j] = lastWeight[j];
row->add[j] = 0.0;
}
} /* end loop over detectors */
} /* end calibrating weights */
/* Write Soln table - bracket interval */
iRow = -1;
row->Target = (oint)(lastTarget+0.5);
row->Time = t0;
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "ERROR writing OTFSoln Table file");
goto cleanup;
}
row->Time = lastTime;
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "ERROR writing OTFSoln Table file");
goto cleanup;
}
/* initialize accumulators */
t0 = rec[desc->iloct];
lastTime = rec[desc->iloct];
lastTarget = rec[desc->iloctar];
lastScan = rec[desc->ilocscan];
sumTime = 0.0;
nTime = 0;
} /* end of do solution if there is data */
} /* end do solution */
/* accumulate */
lastTime = rec[desc->iloct];
sumTime += rec[desc->iloct];
iCal[nTime] = fabs(rec[inOTF->myDesc->iloccal]);
time[nTime] = rec[inOTF->myDesc->iloct];
for (j=0; j<nDet; j++ ) {
accum[j][nTime] = rec[desc->ilocdata+j*incdatawt];
}
nTime++;
rec += desc->lrec; /* Data record pointer */
someData = TRUE;
} /* end loop over buffer load */
} /* end loop reading data file */
/* Finish up any data in accumulator */
if (nTime>0) {
/* Set descriptive info on Row */
row->Time = sumTime/nTime; /* time */
row->TimeI = 2.0 * (row->Time - t0);
/* Flatten curves, estimate cal, Weights */
fitWate = (fabs(lastTarget-blankID)<0.1) || (blankID<0.0);
doPARCalWeight(nDet, nTime, iCal, accum, time, lastCal, lastWeight, fitWate);
/* Propagate last good cals if needed */
for (j=0; j<nDet; j++ ) {
row->cal[j] = lastCal[j];
if (lastCal[j]!=fblank) row->mult[j] = calJy[j] / lastCal[j];
else row->mult[j] = 1.0;
}
/* Calibrating weights? Propagate last weight */
if (doWate) {
for (j=0; j<nDet; j++ ) {
/* Acceptable SNR? */
if ((lastCal[j]!=fblank) && (lastWeight[j]!=fblank)) {
snr = fabs(lastCal[j]) * sqrt(lastWeight[j]);
if (snr < minsnr) {
/* No - off with their heads! */
row->wt[j] = 0.0;
row->add[j] = fblank;
}
} /* End check SNR */
if (lastWeight[j]!=fblank) row->wt[j] = lastWeight[j];
} /* end loop over detectors */
} /* end calibrating weights */
/* Write Soln table - bracket interval */
iRow = -1;
row->Time = t0;
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "ERROR writing OTFSoln Table file");
goto cleanup;
}
row->Time = lastTime;
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "ERROR writing OTFSoln Table file");
goto cleanup;
}
} /* End final solution */
/* Make sure this worked -final lastCal must have some good data */
gotCal = FALSE;
for (j=0; j<nDet; j++ ) {
if ((lastCal[j]!=fblank) && (lastWeight[j]!=fblank)) gotCal = TRUE;
}
if (!gotCal) {
Obit_log_error(err, OBIT_Error, "%s: ERROR NO calibration data found", routine);
}
/* Cleanup */
cleanup:
/* Close cal table */
if ((ObitTableOTFSolnClose (outSoln, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "ERROR closing input OTFSoln Table file");
}
/* Close data */
retCode = ObitOTFClose (inOTF, err);
/* Give warning if no data selected */
if (!someData) Obit_log_error(err, OBIT_InfoWarn,
"%s: Warning: NO data selected", routine);
/* Cleanup */
if (calJy) g_free(calJy);
if (lastCal) g_free(lastCal);
if (lastWeight) g_free(lastWeight);
for (i=0; i<nDet; i++) if (accum[i]) g_free(accum[i]);
if (accum) g_free(accum);
if (iCal) g_free(iCal);
if (time) g_free(time);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
return outSoln;
} /* end ObitOTFGetSolnPARGain */
/**
* Write pointing corrections into a table
* Given a set of pointing correction, write to OTFSoln table
* Calibration parameters are on the inOTF info member.
* \li "POffset" OBIT_float (3,?,1) Table of pointing offsets
* Triplets (time(day), Azoff(asec), Decoff(asec))
* \param inOTF Input OTF data.
* \param outOTF OTF with which the output OTFSoln is to be associated
* \param err Error stack, returns if not empty.
* \return Pointer to the newly created OTFSoln object which is
* associated with inOTF.
*/
ObitTableOTFSoln* ObitOTFGetSolnPointTab (ObitOTF *inOTF, ObitOTF *outOTF, ObitErr *err)
{
ObitTableOTFSoln *outSoln=NULL;
ObitTableOTFSolnRow *row=NULL;
gint32 pntdim[MAXINFOELEMDIM] = {1,1,1,1,1};
ofloat *pointTab;
ObitInfoType type;
olong iRow, ver, j, mpoly, ndetect;
gchar *tname;
gchar *routine = "ObitOTFGetSolnPointTab";
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return outSoln;
g_assert (ObitOTFIsA(inOTF));
/* Create output */
tname = g_strconcat ("Calibration for: ",inOTF->name, NULL);
ver = 0;
mpoly = 1;
outSoln = newObitTableOTFSolnValue(tname, (ObitData*)outOTF, &ver, OBIT_IO_WriteOnly,
inOTF->geom->numberDetect, mpoly, err);
g_free (tname);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
/* Get offset table */
pointTab = NULL;
ObitInfoListGetP(inOTF->info, "POffset", &type, pntdim, (gpointer*)&pointTab);
/* error checks */
if (pointTab==NULL) {
Obit_log_error(err, OBIT_Error, "%s ERROR, NO POffset array given", routine);
goto cleanup;
}
if ((pntdim[0]!=3) || (type!=OBIT_float)) {
Obit_log_error(err, OBIT_Error, "%s Invalid POffset array given", routine);
goto cleanup;
}
/* Open output table */
if ((ObitTableOTFSolnOpen (outSoln, OBIT_IO_WriteOnly, err)
!= OBIT_IO_OK) || (err->error)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s ERROR opening input OTFSoln table", routine);
goto cleanup;
}
/* Create Row */
row = newObitTableOTFSolnRow (outSoln);
/* Attach row to output buffer */
ObitTableOTFSolnSetRow (outSoln, row, err);
if (err->error) goto cleanup;
/* Initialize solution row */
ndetect = inOTF->geom->numberDetect; /* number of detectors */
row->dAz = 0.0; /* no pointing corrections */
row->dEl = 0.0; /* no pointing corrections */
row->Target = 0;
row->TimeI = 0.0;
for (j=0; j<ndetect; j++) row->mult[j] = 1.0;
for (j=0; j<ndetect; j++) row->wt[j] = 1.0;
for (j=0; j<ndetect; j++) row->cal[j] = 0.0;
for (j=0; j<ndetect; j++) row->add[j] = 0.0;
/* Loop over table */
for (iRow=1; iRow<=pntdim[1]; iRow++) {
row->Time = pointTab[iRow*3-3];
row->dAz = pointTab[iRow*3-2]/3600.0; /* To deg */
row->dEl = pointTab[iRow*3-1]/3600.0;
if ((ObitTableOTFSolnWriteRow (outSoln, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s ERROR writing OTFSoln Table file", routine);
goto cleanup;
}
} /* end loop writing table */
/* Close output cal table */
if ((ObitTableOTFSolnClose (outSoln, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s ERROR closing output OTFSoln Table file", routine);
goto cleanup;
}
/* Deallocate arrays */
cleanup:
row = ObitTableOTFSolnUnref(row);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outSoln);
return outSoln;
} /* end ObitOTFGetSolnPointTab */
/**
* Create dummy OTFCal table table (applying will not modify data)
* \li "solInt" OBIT_float (1,1,1) Solution interval in days [def 1 sec].
* \param inOTF Input OTF data.
* \param outOTF OTF with which the output OTFCal is to be associated
* \param ver OTFCal table version
* \param ncoef Number of coefficients in table
* \param err Error stack, returns if not empty.
* \return Pointer to the newly created OTFCal object which is
* associated with inOTF.
*/
ObitTableOTFCal* ObitOTFGetDummyCal (ObitOTF *inOTF, ObitOTF *outOTF, olong ver,
oint ncoef, ObitErr *err)
{
#define MAXSAMPLE 1000 /* Maximum number of samples in an integration */
ObitTableOTFCal *outCal=NULL;
ObitTableOTFCalRow *row=NULL;
ObitOTFDesc *desc=NULL;
ObitIOAccess access;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
ofloat *rec, solInt, t0, sumTime, lastTime=-1.0, lastTarget=-1.0, lastScan=-1.0;
olong iRow, i, lrec;
olong nDet, nTime;
gboolean doCalSelect, someData=FALSE;
ObitIOCode retCode;
gchar *tname;
gchar *routine = "ObitOTFGetDummyCal";
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return outCal;
g_assert (ObitOTFIsA(inOTF));
desc = inOTF->myDesc;
/* Calibration/selection wanted? */
doCalSelect = FALSE;
ObitInfoListGetTest(inOTF->info, "doCalSelect", &type, dim, &doCalSelect);
if (doCalSelect) access = OBIT_IO_ReadCal;
else access = OBIT_IO_ReadWrite;
/* open OTF data to fully instantiate if not already open */
if ((inOTF->myStatus==OBIT_Inactive) || (inOTF->myStatus==OBIT_Defined)) {
retCode = ObitOTFOpen (inOTF, access, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outCal);
}
lrec = inOTF->myDesc->lrec;
nDet = inOTF->geom->numberDetect;
t0 = -1.0e20;
/* Create output */
tname = g_strconcat ("Calibration for: ",inOTF->name, NULL);
outCal = newObitTableOTFCalValue(tname, (ObitData*)outOTF, &ver, OBIT_IO_WriteOnly,
inOTF->geom->numberDetect, ncoef, err);
g_free (tname);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outCal);
/* Get parameters for calibration */
/* "Solution interval" default 1 sec */
solInt = 1.0 / 86400.0;
ObitInfoListGetTest(inOTF->info, "solInt", &type, dim, (gpointer*)&solInt);
/* Open table */
if ((ObitTableOTFCalOpen (outCal, OBIT_IO_WriteOnly, err)
!= OBIT_IO_OK) || (err->error)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s: ERROR opening input OTFCal table", routine);
return outCal;
}
/* Create Row */
row = newObitTableOTFCalRow (outCal);
/* Attach row to output buffer */
ObitTableOTFCalSetRow (outCal, row, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outCal);
/* Initialize */
row->dAz = 0.0; /* no pointing corrections */
row->dEl = 0.0; /* no pointing corrections */
for (i=0; i<nDet; i++) {
row->mult[i] = 1.0;
row->wt[i] = 1.0;
row->add[i] = 0.0;
row->cal[i] = 0.0;
}
/* loop calibrating data */
retCode = OBIT_IO_OK;
sumTime = 0.0;
nTime = 0;
while (retCode == OBIT_IO_OK) {
/* read buffer */
if (doCalSelect) retCode = ObitOTFReadSelect (inOTF, NULL, err);
else retCode = ObitOTFRead (inOTF, NULL, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outCal);
if (retCode==OBIT_IO_EOF) break; /* done? */
/* Record pointer */
rec = inOTF->buffer;
/* First time */
if (t0<-1.0e10) {
t0 = rec[inOTF->myDesc->iloct];
lastTarget = rec[inOTF->myDesc->iloctar];
lastScan = rec[inOTF->myDesc->ilocscan];
lastTime = rec[inOTF->myDesc->iloct];
/* Write entry at very beginning */
row->Time = rec[inOTF->myDesc->iloct];
row->TimeI = 0.0;
row->Target = (oint)(rec[inOTF->myDesc->iloctar]+0.5);
iRow = -1;
if ((ObitTableOTFCalWriteRow (outCal, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s: ERROR writing OTFCal Table file", routine);
return outCal;
}
}
/* Loop over buffer */
for (i=0; i<inOTF->myDesc->numRecBuff; i++) {
/* Accumulation or scan finished? If so, write "calibration".*/
if ((rec[inOTF->myDesc->iloct] > (t0+solInt)) || (nTime>=MAXSAMPLE) ||
(rec[inOTF->myDesc->iloctar] != lastTarget) ||
(rec[inOTF->myDesc->ilocscan] != lastScan)) {
/* Not first time - assume first descriptive parameter never blanked */
if (nTime>0) {
/* if new scan write end of last scan and this time */
if ((rec[inOTF->myDesc->iloctar] != lastTarget) ||
(rec[inOTF->myDesc->ilocscan] != lastScan)) {
/* values for end of previous scan */
row->Time = lastTime;
row->TimeI = 0.0;
row->Target = (oint)(lastTarget+0.5);
iRow = -1;
if ((ObitTableOTFCalWriteRow (outCal, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s: ERROR writing OTFCal Table file", routine);
return outCal;
}
/* Values for start of next scan */
row->Time = rec[inOTF->myDesc->iloct];
row->TimeI = 0.0;
row->Target = (oint)(rec[inOTF->myDesc->iloctar]+0.5);
} else { /* in middle of scan - use average time */
/* Set descriptive info on Row */
row->Time = sumTime/nTime; /* time */
row->TimeI = 2.0 * (row->Time - t0);
row->Target = (oint)(rec[inOTF->myDesc->iloctar]+0.5);
}
/* Write Cal table */
iRow = -1;
if ((ObitTableOTFCalWriteRow (outCal, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s: ERROR writing OTFCal Table file", routine);
return outCal;
}
/* initialize accumulators */
t0 = rec[inOTF->myDesc->iloct];
lastTarget = rec[inOTF->myDesc->iloctar];
lastScan = rec[inOTF->myDesc->ilocscan];
sumTime = 0.0;
nTime = 0;
} /* end of do solution if there is data */
} /* end do solution */
/* accumulate */
sumTime += rec[inOTF->myDesc->iloct];
lastTime = rec[inOTF->myDesc->iloct];
nTime++; /* how many data points */
rec += inOTF->myDesc->lrec; /* Data record pointer */
someData = TRUE;
} /* end loop over buffer load */
} /* end loop reading/gridding data */
/* Finish up any data in accumulator */
if (nTime>0) {
/* Set descriptive info on Row */
row->Time = lastTime;
row->TimeI = 0.0;
row->Target = (oint)(lastTarget+0.5);
/* Write Cal table */
iRow = -1;
if ((ObitTableOTFCalWriteRow (outCal, iRow, row, err)
!= OBIT_IO_OK) || (err->error>0)) {
Obit_log_error(err, OBIT_Error, "%s: ERROR writing OTFCal Table file", routine);
return outCal;
}
} /* End final cal */
/* Close cal table */
if ((ObitTableOTFCalClose (outCal, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s: ERROR closing input OTFCal Table file", routine);
return outCal;
}
/* Close data */
retCode = ObitOTFClose (inOTF, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, outCal);
/* Give warning if no data selected */
if (!someData) Obit_log_error(err, OBIT_InfoWarn,
"%s: Warning: NO data selected", routine);
return outCal;
} /* end ObitOTFGetDummyCal */
/**
* Determine flagging from the statistics of time stream data.
* If a model is supplied, this is determined from the residuals to the model.
* The residual data will be derived from inOTF minus the model.
* Detector/intervals in excess of the larger of maxRMS or maxRatio times the
* equivalent model RMS are flagged in OTFFlag table FGVer on outOTF.
* An evaluation is made independently in each flagInt and detector.
* Control parameters are on the inOTF info member.
* \li "flagInt" OBIT_float (1,1,1) Flaffing interval in days [def 10 sec].
* This should not exceed 1000 samples. Intervals will be truncated
* at this limit.
* \li "maxRMS" OBIT_float (1,1,1) Maximum allowable RMS in Jy[ def 1.0].
* \li "maxRatio" OBIT_float (*,1,1) Max. allowable ratio to equivalent model RMS [2]
* \li "minEl" OBIT_float (1,1,1) Minimum elevation allowed (deg)
* \param inOTF Input OTF data.
* \param model Input CLEAN model, if not provided (NULL) then the model RMS
* is assumed 0.0
* The pixels values in the image array should be the estimated
* antenna response to the source in that direction.
* \param outOTF OTF with which the output OTFFlag is to be associated
* \param FGVer Flag version for output, if 0 create new
* \param err Error stack, returns if not empty.
*/
void ObitOTFGetSolnFlag (ObitOTF *inOTF, ObitImage *model,
ObitOTF *outOTF, olong FGVer, ObitErr *err)
{
#define MAXFLAGSAMPLE 1000 /* Maximum number of samples in an integration */
ObitTableOTFFlag *outFlag=NULL, *inFlag=NULL;
ObitTableOTFFlagRow *row=NULL;
ObitOTF *modelOTF=NULL, *residOTF=NULL;
ObitIOAccess access;
ObitIOSize IOBy;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
ObitInfoType type;
ofloat lastScan=-1.0, lastTarget=-1.0;
ofloat *residRec=NULL, *modelRec=NULL, flagInt, minEl, maxRMS, maxRatio, el, t0, tEnd;
ofloat *time, *data=NULL, *moddata=NULL, residRMS, modelRMS;
ofloat fblank = ObitMagicF();
olong iRow, oRow,ver, i, j, lrec, nsample, flagCnt, totalCnt;
olong ndetect, incdatawt, NPIO;
ObitIOCode retCode;
gboolean flag, someData, doCalSelect, doFlag;
olong blc[IM_MAXDIM] = {1,1,1,1,1,1,1};
olong trc[IM_MAXDIM] = {0,0,0,0,0,0,0};
gchar *tname;
gchar *routine = "ObitOTFGetSolnFlag";
/* error checks */
g_assert (ObitErrIsA(err));
if (err->error) return ;
g_assert (ObitOTFIsA(inOTF));
g_assert (ObitOTFIsA(outOTF));
/* Create output - write new OTFFlag table and then copy to FGVer at the end
This avoids the potential for trouble of reading (applying) and writing the
same table at the same time */
tname = g_strconcat ("Flagging for: ",outOTF->name, NULL);
ver = 0;
outFlag = newObitTableOTFFlagValue(tname, (ObitData*)outOTF, &ver, OBIT_IO_WriteOnly,
err);
g_free (tname);
if (err->error) Obit_traceback_msg (err, routine, outOTF->name);
/* If model given generate model and residual data files */
NPIO = 1000;
dim[0] = 1;
ObitInfoListAlwaysPut (inOTF->info, "nRecPIO", OBIT_long, dim, &NPIO);
if (model) {
/* Open model */
IOBy = OBIT_IO_byPlane;
dim[0] = 1;
ObitInfoListAlwaysPut (model->info, "IOBy", OBIT_long, dim, &IOBy);
dim[0] = 7;
ObitInfoListAlwaysPut (model->info, "BLC", OBIT_long, dim, blc);
ObitInfoListAlwaysPut (model->info, "TRC", OBIT_long, dim, trc);
ObitImageOpen (model, OBIT_IO_ReadOnly, err);
/* Read input plane */
ObitImageRead (model, NULL , err);
modelOTF = newObitOTFScratch(inOTF, err); /* Scratch file for model */
dim[0] = 1;
ObitInfoListPut (modelOTF->info, "nRecPIO", OBIT_long, dim, &NPIO, err);
/* Form model data */
ObitOTFUtilModelImage (inOTF, modelOTF, model->image, model->myDesc, err);
/* open model OTF data to fully instantiate if not already open */
ObitOTFOpen (modelOTF, OBIT_IO_ReadOnly, err);
if (err->error) Obit_traceback_msg (err, routine, modelOTF->name);
residOTF = newObitOTFScratch(inOTF, err); /* Scratch file for residual */
/* Form residual data set */
ObitOTFUtilSubImage (inOTF, residOTF, model->image, model->myDesc, err);
/* Close model */
ObitImageClose(model, err);
if (err->error) Obit_traceback_msg (err, routine, residOTF->name);
/* free image memory if not memory resident */
if (model->mySel->FileType!=OBIT_IO_MEM)
model->image = ObitFArrayUnref(model->image);
} else { /* No model - use data as residual */
residOTF = ObitOTFRef(inOTF);
}
/* Calibration wanted for residual? (only really if no model) */
doCalSelect = FALSE;
ObitInfoListGetTest(residOTF->info, "doCalSelect", &type, dim, &doCalSelect);
if (doCalSelect) access = OBIT_IO_ReadCal;
else access = OBIT_IO_ReadWrite;
/* open resid OTF data */
dim[0] = 1;
ObitInfoListPut (residOTF->info, "nRecPIO", OBIT_long, dim, (gpointer)&NPIO, err);
ObitOTFOpen (residOTF, access, err);
if (err->error) Obit_traceback_msg (err, routine, residOTF->name);
/* Create work arrays */
ndetect = inOTF->geom->numberDetect; /* number of detectors */
lrec = inOTF->myDesc->lrec;
time = g_malloc0(MAXFLAGSAMPLE*sizeof(ofloat));
if (model) moddata = g_malloc0(ndetect*MAXFLAGSAMPLE*sizeof(ofloat));
data = g_malloc0(ndetect*MAXFLAGSAMPLE*sizeof(ofloat));
nsample = 0;
t0 = -1.0e20;
tEnd = -1.0e20;
lastScan = -1000;
incdatawt= inOTF->myDesc->incdatawt; /* increment on data-wt axis */
someData = FALSE;
/* Get parameters for flagging */
/* interval default 10 sec */
flagInt = 10.0 / 86400.0;
ObitInfoListGetTest(inOTF->info, "flagInt", &type, dim, (gpointer*)&flagInt);
Obit_log_error(err, OBIT_InfoErr,
"%s: Flagging interval %6.2f second", routine, flagInt*86400.0);
/* maximum RMS in interval */
maxRMS = 1.0;
ObitInfoListGetTest(inOTF->info, "maxRMS", &type, dim, (gpointer*)&maxRMS);
/* maximum ratio to model RMS in interval */
maxRatio = 2.0;
ObitInfoListGetTest(inOTF->info, "maxRatio", &type, dim, (gpointer*)&maxRatio);
/* minimum allowed elevation for interval */
minEl = 1.0;
ObitInfoListGetTest(inOTF->info, "minEl", &type, dim, (gpointer*)&minEl);
/* Open output table */
if ((ObitTableOTFFlagOpen (outFlag, OBIT_IO_WriteOnly, err)
!= OBIT_IO_OK) || (err->error)) { /* error test */
Obit_log_error(err, OBIT_Error, "ERROR opening input OTFFlag table");
goto cleanup;
}
/* Create Row */
row = newObitTableOTFFlagRow (outFlag);
/* Attach row to output buffer */
ObitTableOTFFlagSetRow (outFlag, row, err);
if (err->error) Obit_traceback_msg (err, routine, inOTF->name);
/* Initialize solution row */
row->TargetID = 0;
row->Feed = (oint)0;
row->TimeRange[0] = 0.0; row->TimeRange[1] = 0.0;
row->chans[0] = 1; row->chans[1] = 0;
row->pFlags[0] = 0x1 | 0x2 | 0x4 | 0x8; /* Flag all Stokes */
strcpy (row->reason, "Excessive RMS");
flag = FALSE;
residRec = residOTF->buffer;
if (model) modelRec = modelOTF->buffer;
flagCnt = 0;
totalCnt = 0;
/* loop over data */
retCode = OBIT_IO_OK;
while (retCode == OBIT_IO_OK) {
/* read buffer */
if (doCalSelect) retCode = ObitOTFReadSelect (residOTF, NULL, err);
else retCode = ObitOTFRead (residOTF, NULL, err);
if (err->error) goto cleanup;
if (retCode==OBIT_IO_EOF) break; /* done? */
/* Read model if given */
if (model) {
retCode = ObitOTFRead (modelOTF, NULL, err);
if (err->error) goto cleanup;
if (retCode==OBIT_IO_EOF) break; /* done? */
}
/* Record pointers */
residRec = residOTF->buffer;
if (model) {
modelRec = modelOTF->buffer;
/* Also consistency checks - check number of records in buffer */
if (modelOTF->myDesc->numRecBuff!=residOTF->myDesc->numRecBuff) {
Obit_log_error(err, OBIT_Error,
"%s: model and residual have different no. records",
routine);
goto cleanup;
}
/* Check timetags of first records */
if (residRec[residOTF->myDesc->iloct]!=modelRec[modelOTF->myDesc->iloct]) {
Obit_log_error(err, OBIT_Error,
"%s: model and residual have different timetags",
routine);
goto cleanup;
}
} /* End consistency checks */
/* First time */
if (t0<-1.0e10) {
t0 = residRec[residOTF->myDesc->iloct];
tEnd = t0+1.0E-20;
lastScan = residRec[residOTF->myDesc->ilocscan]; /* Which scan number */
lastTarget = residRec[residOTF->myDesc->iloctar]; /* Which target number */
}
/* Loop over buffer */
for (i=0; i<residOTF->myDesc->numRecBuff; i++) {
/* Flagging interval finished? If so, compute solution and write.
also if work arrays full */
if ((residRec[residOTF->myDesc->iloct] > (t0+flagInt)) ||
/* or end of scan */
( residRec[residOTF->myDesc->ilocscan] != lastScan) ||
/* or exceed limit on number of samples */
(nsample>=MAXFLAGSAMPLE)) {
/* Any data in buffers? */
if (nsample>0) {
/* Set descriptive info on Row */
row->TargetID = (oint)(lastTarget+0.5);
row->TimeRange[0] = t0; /* time range */
row->TimeRange[1] = tEnd;
/* Check each detector */
doFlag = FALSE;
/* Is data below the elevation limit? */
el = ObitOTFArrayGeomElev (residOTF->geom, residRec[residOTF->myDesc->iloct],
residRec[residOTF->myDesc->ilocra],
residRec[residOTF->myDesc->ilocdec]);
for (j=0; j<ndetect; j++) {
/* RMSes of residual, model */
residRMS = RMSValue (&data[j*MAXFLAGSAMPLE], nsample);
if (residRMS!=fblank) {
totalCnt++;
if (model) {
/* have model */
modelRMS = RMSValue (&moddata[j*MAXFLAGSAMPLE], nsample);
if (modelRMS!=fblank) doFlag = residRMS > MAX(maxRatio*modelRMS, maxRMS);
} else {
/* Only residual */
doFlag = residRMS > maxRMS;
}
doFlag = doFlag || (el < minEl);
}
/* Write entry if needed */
if (doFlag) {
row->Feed = (oint)(j+1);
iRow = -1;
ObitTableOTFFlagWriteRow (outFlag, iRow, row, err);
if (err->error) goto cleanup;
flagCnt++;
}
} /* End loop checking detectors */
} /* end if some valid data */
/* initialize accumulators */
t0 = residRec[residOTF->myDesc->iloct];
tEnd = t0+1.0E-20;
nsample = 0;
} /* end do solution */
/* accumulate */
if (!flag) {
time[nsample] = residRec[residOTF->myDesc->iloct];
for (j=0; j<ndetect; j++ )
data[nsample+j*MAXFLAGSAMPLE] = residRec[residOTF->myDesc->ilocdata+j*incdatawt];
if (model) {
for (j=0; j<ndetect; j++ )
moddata[nsample+j*MAXFLAGSAMPLE] = modelRec[modelOTF->myDesc->ilocdata+j*incdatawt];
}
nsample++;
someData = TRUE; /* Any valid data? */
}
/* last time in accumulation */
tEnd = residRec[residOTF->myDesc->iloct]+1.0E-20;
lastScan = residRec[residOTF->myDesc->ilocscan]; /* Which scan number */
lastTarget = residRec[residOTF->myDesc->iloctar]; /* Which target number */
residRec += residOTF->myDesc->lrec; /* Data record pointers */
if (model) modelRec += modelOTF->myDesc->lrec;
} /* end loop over buffer load */
} /* end loop reading data */
/* Finish up any data in arrays */
/* Any data in buffers? */
if (nsample>0) {
/* Set descriptive info on Row */
row->TargetID = (oint)(lastTarget+0.5);
row->TimeRange[0] = t0; /* time range */
row->TimeRange[1] = tEnd;
/* Check each detector */
doFlag = FALSE;
for (j=0; j<ndetect; j++) {
/* RMSes of residual, model */
residRMS = RMSValue (&data[j*MAXFLAGSAMPLE], nsample);
if (residRMS!=fblank) {
totalCnt++;
if (model) {
/* have model */
modelRMS = RMSValue (&moddata[j*MAXFLAGSAMPLE], nsample);
if (modelRMS!=fblank) doFlag = residRMS > MAX(maxRatio*modelRMS, maxRMS);
} else {
/* Only residual */
doFlag = residRMS > maxRMS;
}
}
/* Is data below the elevation limit? */
el = ObitOTFArrayGeomElev (residOTF->geom, residRec[residOTF->myDesc->iloct],
residRec[residOTF->myDesc->ilocra],
residRec[residOTF->myDesc->ilocdec]);
doFlag = doFlag || (el < minEl);
/* Write entry if needed */
if (doFlag) {
row->Feed = (oint)(j+1);
iRow = -1;
ObitTableOTFFlagWriteRow (outFlag, iRow, row, err);
if (err->error) goto cleanup;
flagCnt++;
}
} /* End loop checking detectors */
} /* end if some valid data */
/* tell how much flagged */
Obit_log_error(err, OBIT_InfoErr,
"%s: Flagged %d/ %d detector/intervals", routine, flagCnt, totalCnt);
/* Give warning if no data selected */
if (!someData) Obit_log_error(err, OBIT_InfoWarn,
"%s: Warning: NO data selected", routine);
/* if ver is not FGVer, then copy entries and delete the temporary table */
if (FGVer<=0) FGVer = ver;
if (FGVer!=ver) {
/* Clean up old */
row = ObitTableOTFFlagUnref(row);
outFlag = ObitTableOTFFlagUnref(outFlag);
/* Input table */
tname = g_strconcat ("input for: ",outOTF->name, NULL);
inFlag = newObitTableOTFFlagValue(tname, (ObitData*)outOTF, &ver, OBIT_IO_ReadOnly,
err);
g_free (tname);
if (err->error) Obit_traceback_msg (err, routine, outOTF->name);
/* Output table */
tname = g_strconcat ("output for: ",outOTF->name, NULL);
outFlag = newObitTableOTFFlagValue(tname, (ObitData*)outOTF, &FGVer, OBIT_IO_ReadWrite,
err);
g_free (tname);
if (err->error) Obit_traceback_msg (err, routine, outOTF->name);
/* append input to output */
/* Open input tables */
ObitTableOTFFlagOpen (inFlag, OBIT_IO_ReadOnly, err);
ObitTableOTFFlagOpen (outFlag, OBIT_IO_ReadWrite, err);
if (err->error) goto cleanup;
/* If there are entries in the output table, mark it unsorted */
if (outFlag->myDesc->nrow>0)
{outFlag->myDesc->sort[0]=0; outFlag->myDesc->sort[1]=0;}
/* Create Row */
row = newObitTableOTFFlagRow (outFlag);
/* Attach row to output buffer */
ObitTableOTFFlagSetRow (outFlag, row, err);
if (err->error) Obit_traceback_msg (err, routine, inOTF->name);
for (iRow=1; iRow<=inFlag->myDesc->nrow; iRow++) {
ObitTableOTFFlagReadRow (inFlag, iRow, row, err);
oRow = -1;
ObitTableOTFFlagWriteRow (outFlag, oRow, row, err);
if (err->error) goto cleanup;
} /* end loop copying */
ObitTableOTFFlagClose (inFlag, err);
ObitTableOTFFlagClose (outFlag, err);
/* Zap temporary table */
ObitOTFZapTable(outOTF, "OTFFlag", ver, err);
if (err->error) goto cleanup;
} /* end copy table */
/* Cleanup */
cleanup:
/* Close data */
retCode = ObitOTFClose (residOTF, err);
/* Close flag table */
if ((ObitTableOTFFlagClose (outFlag, err)
!= OBIT_IO_OK) || (err->error>0)) { /* error test */
Obit_log_error(err, OBIT_Error, "%s ERROR closing output OTFFlag Table file", routine);
}
outFlag = ObitTableOTFFlagUnref(outFlag);
inFlag = ObitTableOTFFlagUnref(inFlag);
modelOTF = ObitOTFUnref(modelOTF);
residOTF = ObitOTFUnref(residOTF);
row = ObitTableOTFFlagUnref(row);
if (time) g_free(time);
if (data) g_free(data);
if (moddata) g_free(moddata);
if (err->error) Obit_traceback_msg (err, routine, residOTF->name);
} /* end ObitOTFGetSolnFlag */
/*----------------------Private functions---------------------------*/
/**
* Fit an atmospheric model across a grid of detectors.
* If a model fitter is provided, it is used, else a median of the values.
* \param geom Array geometry structure
* \param desc OTF descriptor
* \param rec OTF Data record
* \param fitter Atmospheric model fitter, NULL if none
* \param row Solution table row
*/
static void
ObitOTFGetSolnSolve (ObitOTFArrayGeom *geom, ObitOTFDesc *desc,
ObitPennArrayAtmFit *fitter, ofloat *rec, ObitTableOTFSolnRow *row)
{
olong i, incdatawt;
ofloat value, corr, fblank = ObitMagicF();
/* Initialize */
row->dAz = 0.0; /* no pointing corrections */
row->dEl = 0.0; /* no pointing corrections */
incdatawt = desc->incdatawt; /* increment in data-wt axis */
/* Model fitting or median? */
if (fitter!=NULL) { /* model fitting */
ObitPennArrayAtmFitFit (fitter, &rec[desc->ilocdata], incdatawt, row->poly);
corr = 0.0;
} else { /* Get median */
value = GetSolnMedianAvg (&rec[desc->ilocdata], incdatawt, geom->numberDetect);
if (value!=fblank) corr = -value;
else corr = fblank;
}
/* Set values on calibration row */
for (i=0; i<geom->numberDetect; i++) {
row->add[i] = corr;
row->mult[i] = 1.0;
row->wt[i] = 1.0;
}
} /* end ObitOTFGetSolnSolve */
/**
* Use cal measurements in a data set to estimate the gain calibration factor.
* The value in cal is assumed 0.0 if the cal is off and the value of the cal in Jy if > 0.
* If a model fitter is provided, it is used, else a median of the values.
* The average noise cal values are written on row->cal[detect].
* \param nsample The number of samples
* \param time Array of time tags, used to interpolate cal off values to time of cal on.
* \param cal >0 if cal on else cal is off per integration.
* \param calJy Cal value in Jy.
* \param data data values, per integration
* \param minrms minimum allowed RMS in solution as a fraction of the gain.
* \param lastgood Last good value of gain.
* \param detect The detector number (used to determine which value is set in row).
* \param row Solution table row
*/
static void
ObitOTFGetSolnGainSolve (olong nsample, ofloat *time, ofloat *cal, ofloat calJy, ofloat *data,
ofloat minrms, ofloat lastgood, olong detect, ObitTableOTFSolnRow *row)
{
ofloat gain, diff, sum, w1, w2, delta, d1=0.0, d2=0.0, fblank=ObitMagicF();
ofloat sum2, sum3, rms, caloff;
olong i, count;
/* If no data merely flag solution and return */
if (nsample<=0) {
row->add[detect] = fblank;
row->mult[detect] = 0.0;
row->wt[detect] = 0.0;
row->cal[detect] = fblank;
return;
} /* end flag if no data */
/* Loop over data */
count = 0;
sum = sum2 = sum3 = 0.0;
for (i=0; i<nsample; i++) {
if ((cal[i]>0.0) && (data[i]!=fblank)) { /* is this a valid cal value */
/* First special case */
if (i==0) {
if ((cal[i+1]<=0.0) && (data[i+1]!=fblank)) {
diff = data[i] - data[i+1];
if (diff>0.0) { /* ignore clearly bad values */
count++;
sum += calJy / diff;
sum2 += (calJy / diff) * (calJy / diff);
sum3 += diff;
}
}
/* last datum special case */
} else if (i==(nsample-1)) {
if ((cal[i-1]<=0.0) && (data[i-1]!=fblank)) {
diff = data[i] - data[i-1];
if (diff>0.0) { /* ignore clearly bad values */
count++;
sum += calJy / diff;
sum2 += (calJy / diff) * (calJy / diff);
sum3 += diff;
}
}
/* neither first nor last */
} else {
/* determine interpolation weights */
delta = time[i+1] - time[i-1]; /* time difference */
w1 = w2 = 0.0;
d1 = d2 = 0.0;
/* prior time */
if ((cal[i-1]<=0.0) && (data[i-1]!=fblank)) {
d1 = data[i] - data[i-1];
if (d1>0.0) { /* ignore clearly bad values */
w1 = (time[i+1] - time[i]) / delta;
}
}
/* following time */
if ((cal[i+1]<=0.0) && (data[i+1]!=fblank)) {
d2 = data[i] - data[i+1];
if (d2>0.0) { /* ignore clearly bad values */
w2 = (time[i] - time[i-1]) / delta;
}
}
/* determine gain */
if (w1+w2 > 0.0) {
diff = (w1 * d1 + w2 * d2) / (w1+w2);
count++;
sum += calJy / diff;
sum2 += (calJy / diff) * (calJy / diff);
sum3 += diff;
}
} /* end of process by position in time */
} /* End of cal value */
} /* end loop over data */
/* determine gain */
if (count>0) gain = sum / count;
else gain = fblank; /* no valid data */
/* determine fractonal RMS */
if ((count>0) && (gain!=fblank)) {
sum2 /= count;
caloff = sum3 / count; /* average cal value */
rms = sum2 - gain*gain;
if (rms>0.0) rms = sqrt(rms) / gain;
} else {
rms = fblank; /* no valid data */
caloff = 0.0;
}
/* if not acceptable replace with lastgood */
if (rms > minrms) gain = lastgood;
/* Set gain in record */
if ((gain!=fblank) && (gain!=0.0)) gain = 1.0 / gain; /* as correction */
row->mult[detect] = gain;
row->cal[detect] = caloff;
} /* end ObitOTFGetSolnGainSolve */
/**
* Return average of 50% of values around median
* Does sort then returns average of center array
* \param array array of values, on return will be in ascending order
* \param incs increment in data array, >1 => weights
* \param n dimension of array
* \return Median/average
*/
static ofloat GetSolnMedianAvg (ofloat *array, olong incs, olong n)
{
olong i, cnt, wid, ngood, ind, hi, lo;
ofloat temp, wt, out=0.0, fblank = ObitMagicF();
ofloat maxWt, clipWt, center;
if (n<=0) return fblank;
/* If weights, clip to top 95% and set to 2.0e20 */
ngood = 0;
if (incs>1) {
maxWt = -1.0e20;
for (i=0; i<n; i++) if (array[i*incs]!=fblank) maxWt = MAX(maxWt, array[i*incs+1]);
/* Clip weights and set to large value */
clipWt = 0.05*maxWt;
for (i=0; i<n; i++) {
if ((array[i*incs]==fblank) || (array[i*incs+1]<clipWt)) {
array[i*incs] = 2.0e20;
array[i*incs+1] = 0.0;
} else ngood++;
}
} else { /* No weights */
for (i=0; i<n; i++) {
if (array[i]==fblank) array[i] = 2.0e20;
else ngood++;
}
}
if (ngood<1) return fblank; /* Any good data? */
/* Sort to ascending order */
qsort ((void*)array, n, MIN(2,incs)*sizeof(ofloat), compare_gfloat);
/* How many good values? */
cnt = 0;
for (i=0; i<n; i++) if (array[i*incs]<1.0e20) cnt++;
wid = cnt/4;
ngood = cnt;
ind = (ngood/incs)/2; /* make center pixel even to get value not wt */
ind = (ind/2)*2;
out = array[ind];
/* average central 50% values */
if (ngood>5) {
center = (ngood-1)/2.0;
lo = (olong)(center - wid + 0.6);
hi = (olong)(center + wid);
/* Weighted? */
if (incs>1) {
temp = 0.0; wt = 0.0;
for (i=lo; i<=hi; i++) {
if (array[i*incs]<1.0e20) {
wt += array[i*incs+1];
temp += array[i*incs]*array[i*incs+1];
}
}
if (wt>0.0) out = temp/wt;
} else { /* unweighted */
temp = 0.0; cnt = 0;
for (i=lo; i<=hi; i++) {
if (array[i]<1.0e20) {
cnt++;
temp += array[i];
}
if (cnt>0) out = temp/cnt;
}
} /* end if weighting */
}
/* reblank values */
for (i=0; i<n; i++) {
if (array[i*incs]>1.0e20) array[i*incs] = fblank;
}
return out;
} /* end GetSolnMedianAvg */
/**
* Fit for instrumental model in each detector
* offset is the median value, gain determined from cal-on values
* \param geom Array geometry structure
* \param desc OTF descriptor
* \param nDet Number of detectors in data
* \param nTime Number of times in data, iCal
* \param data OTF Data array, destructive operation
* \param iCal If > 0 then the cal value in Jy and this is a cal on.
* \param row Solution table row
*/
static void
ObitOTFGetInstSolve (ObitOTFArrayGeom *geom, ObitOTFDesc *desc,
olong nDet, olong nTime, ofloat **data, ofloat *iCal,
ObitTableOTFSolnRow *row)
{
olong i, j, count;
ofloat value, corr, cal=0.0, diff, sum, fblank=ObitMagicF();
/* Initialize */
row->dAz = 0.0; /* no pointing corrections */
row->dEl = 0.0; /* no pointing corrections */
/* Get calibration value gain */
for (i=0; i<nDet; i++) {
sum = 0.0;
count = 0;
for (j=1; j<nTime; j++) {
if (((iCal[j]>0.0) && (iCal[j-1]<=0.0)) &&
((data[i][j]!=fblank)&&(data[i][j-1]!=fblank))){
cal = iCal[j];
diff = data[i][j] - data[i][j-1];
sum += diff;
count++;
}
if (count>0) {
row->mult[i] = cal / (sum / count);
row->cal[i] = sum / count;
} else {
row->mult[i] = fblank;
row->cal[i] = fblank;
}
}
/* Subtract cals */
if (row->cal[i] != fblank) {
for (j=0; j<nTime; j++) {
if (iCal[j]>0.0) data[i][j] -= row->cal[i];
}
}
} /* End loop over detector */
/* median of data per detector, will reorder data */
for (i=0; i<nDet; i++) {
value = GetSolnMedianAvg (data[i], 1, nTime);
if (value!=fblank) corr = -value;
else corr = fblank;
row->add[i] = corr;
}
} /* end ObitOTFGetInstSolve */
/**
* Fit polynomial y = f(poly, x)
* Use gsl package.
* \param poly [out] polynomial coef in order of increasing power of x
* \param order order of the polynomial
* \param x values at which y is sampled
* \param y values to be fitted
* \param wt weights for values
* \param n number of (x,y) value pairs
*/
static void FitBLPoly (ofloat *poly, olong order, ofloat *x, ofloat *y,
ofloat *wt, olong n)
{
olong i, j, k, good, p=order+1;
ofloat fgood=0.0;
double xi, chisq;
gsl_matrix *X, *cov;
gsl_vector *yy, *w, *c;
gsl_multifit_linear_workspace *work;
ofloat fblank = ObitMagicF();
/* Only use good data */
good = 0;
for (i=0; i<n; i++) if (y[i]!=fblank) {good++; fgood = y[i];}
/* If only one good datum - use it */
if (good==1) {
poly[0] = fgood;
poly[1] = 0.0;
}
if (good<(order+1)) { /* Not enough good data */
poly[0] = fblank;
return;
}
/* If only one and order=0 use it */
if ((good==1) && (order==0)) {
poly[0] = y[0];
return;
}
/* allocate arrays */
X = gsl_matrix_alloc(good, p);
yy = gsl_vector_alloc(good);
w = gsl_vector_alloc(good);
c = gsl_vector_alloc(p);
cov = gsl_matrix_alloc(p, p);
work = gsl_multifit_linear_alloc (good, p);
/* set data */
k = 0;
for (i=0; i<n; i++) {
if (y[i]!=fblank) {
gsl_vector_set(yy, k, y[i]);
gsl_vector_set(w, k, wt[i]);
xi = 1.0;
for (j=0; j<p; j++) {
gsl_matrix_set(X, k, j, xi);
xi *= x[i];
}
k++; /* good ones */
}
}
/* Fit */
gsl_multifit_wlinear (X, w, yy, c, cov, &chisq, work);
/* get results */
for (j=0; j<p; j++) poly[j] = gsl_vector_get(c, j);
/* Deallocate arrays */
gsl_matrix_free(X);
gsl_vector_free(yy);
gsl_vector_free(w);
gsl_vector_free(c);
gsl_matrix_free(cov);
gsl_multifit_linear_free (work);
} /* end FitBLPoly */
/**
* Determine median value for each detector (returned as offset) then fit
* Piecewise linear segments of time length solint.
* \param solint desired solution interval in units of x
* \param npoly [out] Number of polynomial segments in tpoly, poly
* \param tpoly [out] time (x value) of beginning of each segment,
* tpoly[npoly] = last time in x + epsilon.
* array allocated, must be g_freeed when done
* \param poly [out] polynomial (zeroth, first order coef) x npoly
* array allocated, must be g_freeed when done
* \param offset [out] offset per detector
* \param ndetect Number of detectors
* \param maxdata Max. number of samples per detector
* \param x values at which y is sampled
* \param y values to be fitted
* \param wt weights for values
* \param n number of (x,y) value pairs
*/
static void FitMBBLPoly (ofloat solint, olong *npoly, ofloat **tpoly, ofloat **poly,
ofloat *offset, olong ndetect, olong maxdata,
ofloat *x, ofloat *y, ofloat *wt, olong n)
{
olong i, j, tgood, ngood, np, off, nseg, first;
ofloat *array=NULL, *tarray=NULL, *wwt=NULL;
ofloat si, tnext, fblank = ObitMagicF();
/* Init output */
*npoly = 0;
*poly = NULL;
*tpoly = NULL;
/* Median values for each detector */
tarray = g_malloc0(n*sizeof(ofloat));
wwt = g_malloc0(n*sizeof(ofloat));
for (i=0; i<ndetect; i++) {
ngood = 0;
for (j=0; j<n; j++) {
if ((y[j+i*maxdata]!=fblank) && (wt[j+i*maxdata]>0.0)) {
tarray[ngood] = y[j+i*maxdata];
ngood++;
}
} /* end accumulate array */
offset[i] = GetSolnMedianAvg (tarray, 1, ngood);
} /* End loop over detectors */
/* Get median residual in each time */
array = g_malloc0(ndetect*sizeof(ofloat));
for (j=0; j<n; j++) {
tgood = 0;
for (i=0; i<ndetect; i++) {
if ((y[j+i*maxdata]!=fblank) && (wt[j+i*maxdata]>0.0) && (offset[i]!=fblank)) {
array[tgood] = y[j+i*maxdata] - offset[i];
tgood++;
}
} /* end accumulate array */
tarray[j] = GetSolnMedianAvg (array, 1, tgood);
wwt[j] = 1.0;
} /* End loop over detectors */
/* Create output arrays */
np = 5.999 + (x[n-1] - x[0]) / solint; /* How many segments possible? */
np = MAX (np, 6);
si = (x[n-1] - x[0]) / (np - 5.0); /* Make intervals equal */
*tpoly = g_malloc0(np*sizeof(ofloat));
*poly = g_malloc0(2*np*sizeof(ofloat));
/* Loop over list */
off = 0;
tnext = x[0] + si; /* end of segment */
nseg = 0;
while ((off<(n-1)) && ((nseg+1)<np)) {
first = off;
/* Find end of segment */
while ((x[off+1]<=tnext) && (off<(n-1))) {off++;}
/* Fit time seqment */
FitBLPoly (&(*poly)[2*nseg], 1, &x[first], &tarray[first], &wwt[first], off-first);
/* DEBUG * No common mode
(*poly)[2*nseg] = 0.0; (*poly)[2*nseg+1] = 0.0; */
(*tpoly)[nseg] = x[first];
tnext = x[off+1] + si; /* end of next segment */
nseg++;
/* Ignore orphans */
if (off>(n-2)) break;
g_assert (nseg<np); /* Trap overflow */
} /* end loop over list */
*npoly = nseg; /* save number */
(*tpoly)[nseg] = x[n-1]+0.001*si; /* last plus a bit */
/* Free internal work arrays */
g_free(tarray);
g_free(wwt);
g_free(array);
} /* end FitMBBLPoly */
/**
* Remove outlyers from multi-beam data array
* The Mean and RMS offset from the poly/offset model is computed for
* each detectoris computed and then data more discrepant than sigma times
* the RMS from its detector mean has it's weight set to zero.
* Halve weight of points with residuals > sigma/2 times the RMS
* \param npoly Number of polynomial segments in tpoly, poly
* \param tpoly Time (x value) of beginning of each segment,
* tpoly[npoly] = last time+epsilon;
* \param poly Polynomial (zeroth, first order coef) x npoly
* \param offset offset per detector
* \param ndetect Number of detectors
* \param maxdata Max. number of samples per detector
* \param x values at which y is sampled [n]
* \param y values to be fitted [n][ndetect]
* \param wt weights for values [n][ndetect]
* \param n number of (x,y) value pairs
* \param sigma number of sigma from detector mean to flag data
*/
static void FitMBBLOut (olong npoly, ofloat *tpoly, ofloat *poly, ofloat *offset,
olong ndetect, olong maxdata,
ofloat *x, ofloat *y, ofloat *wt, olong n,
ofloat sigma)
{
olong i, j, off;
odouble *sum, *count, *mean, *rms, resid, half;
olong *flagged;
ofloat atm, fblank = ObitMagicF();
/* Allocate */
sum = g_malloc0(ndetect*sizeof(odouble));
count = g_malloc0(ndetect*sizeof(odouble));
mean = g_malloc0(ndetect*sizeof(odouble));
rms = g_malloc0(ndetect*sizeof(odouble));
flagged= g_malloc0(ndetect*sizeof(olong));
/* Get statistics per detector */
/* Get means */
for (j=0; j<ndetect; j++) sum[j] = count[j] = 0.0;
off = 0;
for (i=0; i<n; i++) {
/* Find and evaluate time segment */
while ((tpoly[off+1]<x[i]) && (off<(npoly+1))) {off++;}
/*atm = poly[2*off] + poly[2*off+1]*(x[i] - tpoly[off]);*/
atm = poly[2*off] + poly[2*off+1]*(x[i]);
for (j=0; j<ndetect; j++) {
if ((y[i+j*maxdata]!=fblank) && (wt[i+j*maxdata]>0.0)) {
resid = y[i+j*maxdata] - (offset[j] + atm);
sum[j] += resid;
count[j] += 1.0;
}
}
}
for (j=0; j<ndetect; j++) {
mean[j] = sum[j] / MAX (1.0, count[j]);
}
/* Get RMSes */
for (j=0; j<ndetect; j++) sum[j] = count[j] = 0.0;
off = 0;
for (i=0; i<n; i++) {
/* Find and evaluate time segment */
while ((tpoly[off+1]<x[i]) && (off<(npoly+1))) {off++;}
/*atm = poly[2*off] + poly[2*off+1]*(x[i] - tpoly[off]);*/
atm = poly[2*off] + poly[2*off+1]*(x[i]);
for (j=0; j<ndetect; j++) {
if ((y[i+j*maxdata]!=fblank) && (wt[i+j*maxdata]>0.0)) {
resid = y[i+j*maxdata] - (offset[j] + atm) - mean[j];
sum[j] += resid*resid;
count[j] += 1.0;
}
}
}
for (j=0; j<ndetect; j++) {
rms[j] = sqrt (sum[j] / MAX (1.0, count[j]));
flagged[j] = 0;
}
/* debug
j = 0;
fprintf (stderr,"clip level %d %f %f %f\n", j, sigma*rms[j], rms[j],sigma);
fprintf (stderr," %lf %lf \n", sum[j], count[j]); */
/* flag outliers */
half = sigma*0.5;
off = 0;
for (i=0; i<n; i++) {
/* Find and evaluate time segment */
while ((tpoly[off+1]<x[i]) && (off<(npoly+1))) {off++;}
/*atm = poly[2*off] + poly[2*off+1]*(x[i] - tpoly[off]);*/
atm = poly[2*off] + poly[2*off+1]*(x[i]);
for (j=0; j<ndetect; j++) {
if ((y[i+j*maxdata]!=fblank) && (wt[i+j*maxdata]>0.0)) {
resid = y[i+j*maxdata] - (offset[j] + atm);
if (fabs(resid-mean[j]) > sigma*rms[j]) {
wt[i+j*maxdata] = 0.0;
flagged[j]++;
}
/* Only halve weigh of points more discrepant than sigma/2 */
if (fabs(resid-mean[j]) > half*rms[j] ) wt[i+j*maxdata] *= 0.5;
/* debug
if (j==0)
fprintf (stderr," %d %f %f %lf %f\n",
i,y[i+j*maxdata],(offset[j] + atm),resid,wt[i+j*maxdata]); */
}
}
}
/* DEBUG
for (j=0; j<ndetect; j++) {
if (offset[j]!=fblank)
fprintf (stderr,"DEBUG det %d offset %f mean %f rms %f flagged %d\n",
j, offset[j], mean[j], rms[j], flagged[j]);
} END DEBUG */
/* Deallocate arrays */
if (sum) g_free(sum);
if (count) g_free(count);
if (mean) g_free(mean);
if (rms) g_free(rms);
if (flagged) g_free(flagged);
} /* end FitMBBLOut */
/**
* Plot model and residuals
* \param npoly Number of polynomial segments in tpoly, poly
* \param tpoly Time (x value) of beginning of each segment,
* tpoly[npoly] = last time+epsilon;
* \param poly Polynomial (zeroth, first order coef) x npoly
* \param offset offset per detector
* \param ndetect Number of detectors
* \param maxdata Max. number of samples per detector
* \param order order of the polynomial
* \param x values at which y is sampled [n]
* \param y values to be fitted [n][ndetect]
* \param wt weights for values [n][ndetect]
* \param n number of (x,y) value pairs
* \param plotDetect detector number (1-rel) to plot
* \param t0 time offset to add to x
* \param err Error stack, returns if not empty.
*/
static void PlotMBBL (olong npoly, ofloat *tpoly, ofloat *poly, ofloat *offset,
olong ndetect, olong maxdata,
ofloat *x, ofloat *y, ofloat *wt, olong n,
olong plotDetect, ofloat t0, ObitErr *err)
{
olong i, j, nplot, off=0;
ofloat *ptime, *pdata, ymax, ymin, yy, atm=0.0, fblank = ObitMagicF();
ObitPlot *plot = NULL;
gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};
gchar strTemp[121];
gchar *routine = "PlotMBBL";
/* Asked for something? */
if ((plotDetect<1) || (plotDetect>=ndetect)) return;
/* initialize plotting */
plot = newObitPlot (routine);
/* Plot labels */
g_snprintf (strTemp, 120, "MB BL model (line) and data, detector %d", plotDetect);
dim[0] = strlen (strTemp);
ObitInfoListAlwaysPut (plot->info, "TITLE", OBIT_string, dim, strTemp);
strncpy (strTemp, "Time (days)", 120);
dim[0] = strlen (strTemp);
ObitInfoListAlwaysPut (plot->info, "XLABEL", OBIT_string, dim, strTemp);
strncpy (strTemp, "Offset", 120);
dim[0] = strlen (strTemp);
ObitInfoListAlwaysPut (plot->info, "YLABEL", OBIT_string, dim, strTemp);
/* initialize plotting */
ObitPlotInitPlot (plot, NULL, 15,1,1, err);
if (err->error) {
plot = ObitPlotUnref(plot);
Obit_traceback_msg (err, routine, plot->name);
}
/* Allocate arrays */
ptime = g_malloc0(n*sizeof(ofloat));
pdata = g_malloc0(n*sizeof(ofloat));
/* Find extrema */
ymax = -1.0e20;
ymin = 1.0e20;
j = plotDetect-1;
off = 0;
atm = poly[2*off] + poly[2*off+1]*(x[j]);
for (i=0; i<n; i++) {
/*if ((y[i+j*maxdata]!=fblank) && (wt[i+j*maxdata]>0.0)) {*/
if (y[i+j*maxdata]!=fblank) {
yy = y[i+j*maxdata] - atm - offset[j];
ymax = MAX (ymax, y[i+j*maxdata]);
ymin = MIN (ymin, y[i+j*maxdata]);
}
}
/* Set extrema */
dim[0] = 1;
ObitInfoListAlwaysPut(plot->info, "YMAX", OBIT_float, dim, (gpointer*)&ymax);
ObitInfoListAlwaysPut(plot->info, "YMIN", OBIT_float, dim, (gpointer*)&ymin);
/* model to plot */
j = plotDetect-1;
nplot = 0;
off = 0;
for (i=0; i<n; i++) {
/* Find and evaluate time segment */
while ((tpoly[off+1]<x[i]) && (off<(npoly+1))) {off++;}
/*atm = poly[2*off] + poly[2*off+1]*(x[i] - tpoly[off]);*/
atm = poly[2*off] + poly[2*off+1]*(x[i]);
ptime[nplot] = x[i]+t0;
pdata[nplot] = offset[j] + atm;
nplot++;
}
/* plot it */
ObitPlotXYPlot (plot, -1, nplot, ptime, pdata, err);
/* get valid data to plot */
j = plotDetect-1;
nplot = 0;
for (i=0; i<n; i++) {
if ((y[i+j*maxdata]!=fblank) && (wt[i+j*maxdata]>0.0)) {
ptime[nplot] = x[i]+t0;
pdata[nplot] = y[i+j*maxdata];
nplot++;
}
}
/* plot it */
ObitPlotXYOver (plot, 2, nplot, ptime, pdata, err);
/* get invalid data to plot */
j = plotDetect-1;
nplot = 0;
for (i=0; i<n; i++) {
if ((y[i+j*maxdata]!=fblank) && (wt[i+j*maxdata]<=0.0)) {
ptime[nplot] = x[i]+t0;
pdata[nplot] = y[i+j*maxdata];
nplot++;
}
}
/* plot it */
ObitPlotXYOver (plot, 3, nplot, ptime, pdata, err);
ObitPlotFinishPlot (plot, err);
if (err->error) {
plot = ObitPlotUnref(plot);
if (ptime) g_free(ptime);
if (pdata) g_free(pdata);
Obit_traceback_msg (err, routine, routine);
}
/* Deallocate arrays */
plot = ObitPlotUnref(plot);
if (ptime) g_free(ptime);
if (pdata) g_free(pdata);
} /* end PlotMBBL */
/**
* Remove variations in data, calculate cal delta and weight
* from inverse variance of data.
* Per detector:
* 1) Determined cal from averaging each segment
* and differencing transitions;
* 2) Corrects data for cal value
* 3) Fit polynomial (5th order) to data
* 4) Determine rms deviation
* 5) Clip points > 5 sigma from 0
* 6) Refit polynomial
* 7) redetermine rms deviation
* 8) Flag scans with weights with entries further than 10X low or
5X high from the median weight
* \param nDet Number of detectors
* \param nTime Number of times
* \param iCal is Cal [nTime] 0 = cal off
* \param accum data accumulation[det][time] modified on return
* \param time time per datum[time] modified on output
* \param lastCal [out] Cal signal difference per detector
* \param lastWeight [out] Weight per detector (1/variance)
* \param fitWate if TRUE then determine weight from this scan, else keep last
*/
static void doPARCalWeight (olong nDet, olong nTime, ofloat *iCal, ofloat **accum,
ofloat *time, ofloat *lastCal, ofloat *lastWeight,
gboolean fitWate)
{
olong i, j, which, other;
olong naxis[1], pos[1], msample, order;
ofloat cal, onCnt, offCnt, fblank = ObitMagicF();
ofloat cnt[2], sum[2];
ofloat *tmp = NULL, *wt = NULL, poly[10], rms, t0, medWt;
ofloat flipCnt, flipSum;
gboolean isCal, redo, Cal[2]={FALSE,FALSE};
ObitFArray *tmpFA = NULL;
/* error checks */
g_assert(iCal!=NULL);
g_assert(accum!=NULL);
g_assert(lastCal!=NULL);
g_assert(lastWeight!=NULL);
if ((nDet<=0) || (nTime<=0)) return; /* Anything to do? */
/* Work ObitFArray */
naxis[0] = nTime;
tmpFA = ObitFArrayCreate ("temp", 1L, naxis);
pos[0] = 0;
tmp = ObitFArrayIndex (tmpFA, pos); /* Pointer to data array */
/* Order of polynomial */
order = MAX(1, nTime/50);
order = MIN (5, order);
/* Work Weight array */
wt = g_malloc0(nTime*sizeof(ofloat));
for (i=0; i<10; i++) poly[i] = 0.0;
/* reference times to first */
t0 = time[0];
for (i=0; i<nTime; i++) time[i] -= t0;
/* Loop over detector */
for (j=0; j<nDet; j++) {
cal = lastCal[j]; /* Last good cal */
/* Difference average On and off */
onCnt = offCnt = 0.0;
cnt[0] = cnt[1] = 0.0; sum[0] = sum[1] = 0.0;
which = 0; other = 1-which;
flipCnt = flipSum = 0.0;
for (i=0; i<nTime; i++) {
if (accum[j][i] != fblank) {
isCal = iCal[i]==0.0;
/* Did state switch? */
if (isCal!=Cal[which]) {
other = 1-which; /* not which */
/* Have both states */
if ((cnt[0]>0.0) && (cnt[1]>0.0)) {
flipCnt++;
/* Which way did it go? */
if (isCal) { /* off to on */
flipSum += (sum[which]/cnt[which]) - (sum[other]/cnt[other]);
} else { /* on to off */
flipSum += (sum[other]/cnt[other]) - (sum[which]/cnt[which]);
}
}
/* Flip which */
which = other;
cnt[which] = 0.0;
sum[which] = 0.0;
Cal[which] = isCal;
}
/* Sums for this cycle part */
cnt[which]++;
sum[which] += accum[j][i];
/* Total counts */
if (isCal) { /* cal on */
onCnt++;
} else { /* cal off */
offCnt++;
}
}
} /* end loop over time averaging cal */
/* If no valid data skip this detctor */
if ((onCnt<1) && (offCnt<1)) continue;
if (flipCnt>0) { /* Need both cal on and cal off */
cal = flipSum/flipCnt;
lastCal[j] = cal;
/* Correct cal on to cal off */
for (i=0; i<nTime; i++) {
if ((accum[j][i] != fblank) && (iCal[i]!=0.0)) accum[j][i] -= cal;
} /* end loop over time correcting cal */
} /* End both cal on and cal off */
/* Set fitting weights */
for (i=0; i<nTime; i++) {
if (accum[j][i] != fblank) wt[i] = 1.0;
else wt[i] = 0.0;
}
/* Need to determine weight? */
if (!fitWate) continue;
/* Flatten curve - first fit 5th order polynomial */
msample = nTime;
FitBLPoly (poly, order, time, accum[j], wt, msample);
/* determine RMS from histogram analysis - use FArray class */
for (i=0; i<nTime; i++) {
if (accum[j][i]!=fblank)
tmp[i] = accum[j][i] - EvalPoly (order, poly, time[i]);
else tmp[i] = fblank;
}
rms =ObitFArrayRawRMS (tmpFA);
if ((rms!=fblank) && (rms>0.0)) {
rms = MAX (rms, 1.0);
lastWeight[j] = 1.0e-4*cal*cal / (rms*rms);
}
/* DEBUG
if ((lastWeight[j]!=fblank) && (lastWeight[j]>20.0)) {
fprintf (stderr,"DEBUG detector %d weight %f rms %f cal %f\n",
j, lastWeight[j],rms,cal);
} */
/* Clip >5 sigma deviations */
redo = FALSE;
for (i=0; i<nTime; i++) {
if ((tmp[i]!=fblank) && (fabs(tmp[i]) > 5.0*rms)) {
wt[i] = 0.0;
tmp[i] = fblank;
redo = TRUE;
}
}
if (redo) {
/* Refit curve */
FitBLPoly (poly, order, time, accum[j], wt, msample);
/* Redetermine RMS */
for (i=0; i<nTime; i++) {
if (accum[j][i]!=fblank)
tmp[i] = accum[j][i] - EvalPoly (order, poly, time[i]);
else tmp[i] = fblank;
}
rms = ObitFArrayRawRMS (tmpFA);
if ((rms!=fblank) && (rms>0.0)) {
rms = MAX (rms, 1.0);
lastWeight[j] = 1.0e-4*cal*cal / (rms*rms);
}
}/* End redo after clipping */
} /* end loop over detectors */
/* flag detectors with cal amplitude more than 10 X from median */
if (wt) g_free(wt);
wt = g_malloc0(nDet*2*sizeof(ofloat));
for (j=0; j<nDet; j++) {
if (lastCal[j]!=fblank) wt[j] = fabs(lastCal[j]);
else wt[j] = fblank;
}
medWt = medianValue (wt, 1, (olong)nDet);
if (medWt!=fblank) {
for (j=0; j<nDet; j++) {
if ((fabs(lastCal[j])<0.1*medWt) || (fabs(lastCal[j])>10.0*medWt)) {
/* Bad */
/* lastCal will blank lastWeight[j] = 0.0;*/
lastCal[j] = fblank;
}
}
}
/* flag weights more than 10 X low or 5 X high from median */
if (fitWate){
for (j=0; j<nDet; j++) wt[j] = lastWeight[j];
medWt = medianValue (wt, 1, (olong)nDet);
if (medWt!=fblank) {
for (j=0; j<nDet; j++) {
if ((lastWeight[j]<0.1*medWt) || (lastWeight[j]>5.0*medWt)) {
/* Bad */
lastWeight[j] = 0.0;
}
}
}
}
/* Cleanup */
if (wt) g_free(wt);
ObitFArrayUnref(tmpFA);
} /* end doPARCalWeight */
/**
* ofloat comparison of two arguments
* \param arg1 first value to compare
* \param arg2 second value to compare
* \return negative if arg1 is less than arg2, zero if equal
* and positive if arg1 is greater than arg2.
*/
static int compare_gfloat (const void* arg1, const void* arg2)
{
int out = 0;
ofloat larg1, larg2;
larg1 = *(ofloat*)arg1;
larg2 = *(ofloat*)arg2;
if (larg1<larg2) out = -1;
else if (larg1>larg2) out = 1;
return out;
} /* end compare_gfloat */
/**
* Determine the zenith opacity from either a constant scalar or
* an array of (time,tau0) values.
* Values MUST be in increasing time order.
* \param taudim Dimensionality of taudata
* \param taudata scalar tau0 or array of (time,tau0)
* \return Zenith opacity
*/
static ofloat getTau0 (ofloat time, gint32 taudim[MAXINFOELEMDIM], ofloat *taudata)
{
ofloat out = 0.0;
ofloat wt1, wt2;
olong i, ntime, pre=0;
if (taudata==NULL) return out; /* Given anything? */
/* Scalar?*/
if (taudim[0]==1) out = *taudata;
else if (taudim[0]==2) {
if (taudim[1]==1) out = taudata[1]; /* Only one entry */
else { /* Multiple entries */
ntime = taudim[1];
/* Interpolate/extrapolate */
if (time<=taudata[0]) out = taudata[1]; /* Before first */
if (time>=taudata[(ntime-1)*2]) out = taudata[2*(ntime-1)+1]; /* After last */
else {
/* interpolate */
/* find last preceeding */
for (i=0; i<ntime; i++) if (time>taudata[2*i]) pre = i;
wt2 = (time - taudata[2*pre]) / (taudata[2*ntime-2] - taudata[0]);
wt1 = 1.0 - wt2;
out = wt1*taudata[2*pre+1] + wt2*taudata[2*pre+3];
}
}
}
return out;
} /* end getTau0*/
/**
* Get RMS values of an array.
* \param array array of values may be magic value blanked
* \param n dimension of array
* \return RMS about mean value, possibly blanked
*/
static ofloat RMSValue (ofloat *array, olong n)
{
olong i, count;
ofloat sum, sum2, rawRMS, fblank = ObitMagicF();
count = 0; sum = sum2 = 0.0;
for (i=0; i<n; i++) if (array[i]!=fblank) {
count++;
sum += array[i];
sum2 += array[i] * array[i];
}
if (count<5) return fblank; /* better have some */
/* Get raw RMS */
rawRMS = (sum2/count) - ((sum / count) * (sum / count));
if (rawRMS>0.0) rawRMS = sqrt(rawRMS);
return rawRMS;
} /* end RMSValue */
/**
* Lookup the ID number of Target named "Blank"
* \param inOTF Input OTF data
* \param err Error stack, returns if not empty.
* \return "Blank" Target ID if found, else -1.0
*/
static ofloat FindBlankID (ObitOTF *inOTF, ObitErr *err)
{
ofloat out = -1.0;
ObitTableOTFTarget *TarTable=NULL;
gint32 dim[2];
olong iver, target[2];
gchar *Blank = "Blank";
gchar *routine = "FindBlankID";
if (err->error) return out; /* existing error? */
iver = 1;
TarTable = newObitTableOTFTargetValue (inOTF->name, (ObitData*)inOTF, &iver,
OBIT_IO_ReadOnly, err);
if (err->error) Obit_traceback_val (err, routine, inOTF->name, out);
if (TarTable==NULL) {/*No Target table */
out = -1.0;
} else { /* Table exists */
dim[0] = strlen(Blank);
dim[1] = 1;
/* Do lookup */
ObitTableOTFTargetLookup (TarTable, dim, Blank, target, err);
if(err->error) Obit_traceback_val (err, routine, inOTF->name, out);
TarTable = ObitTableOTFTargetUnref(TarTable); /* release table */
out = (ofloat)target[0];
}
return out;
} /* end FindBlankID */
| {
"alphanum_fraction": 0.6082190917,
"avg_line_length": 34.3706672444,
"ext": "c",
"hexsha": "e73cf282f11006aa3d9f123e532680372dfb2ea2",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T12:16:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-29T15:12:32.000Z",
"max_forks_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_forks_repo_licenses": [
"Linux-OpenIB"
],
"max_forks_repo_name": "sarrvesh/Obit",
"max_forks_repo_path": "ObitSystem/ObitSD/src/ObitOTFGetSoln.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Linux-OpenIB"
],
"max_issues_repo_name": "sarrvesh/Obit",
"max_issues_repo_path": "ObitSystem/ObitSD/src/ObitOTFGetSoln.c",
"max_line_length": 97,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "e4ce6029e9beb2a8c0316ee81ea710b66b2b7986",
"max_stars_repo_licenses": [
"Linux-OpenIB"
],
"max_stars_repo_name": "sarrvesh/Obit",
"max_stars_repo_path": "ObitSystem/ObitSD/src/ObitOTFGetSoln.c",
"max_stars_repo_stars_event_max_datetime": "2020-10-20T01:08:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-26T06:53:08.000Z",
"num_tokens": 53237,
"size": 158655
} |
/*
MPCOTool:
The Multi-Purposes Calibration and Optimization Tool. A software to perform
calibrations or optimizations of empirical parameters.
AUTHORS: Javier Burguete and Borja Latorre.
Copyright 2012-2019, AUTHORS.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/
/**
* \file optimize.c
* \brief Source file to define the optimization functions.
* \authors Javier Burguete and Borja Latorre.
* \copyright Copyright 2012-2019, all rights reserved.
*/
#define _GNU_SOURCE
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/param.h>
#include <gsl/gsl_rng.h>
#include <libxml/parser.h>
#include <libintl.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <json-glib/json-glib.h>
#ifdef G_OS_WIN32
#include <windows.h>
#elif !defined(__BSD_VISIBLE) && !defined(NetBSD)
#include <alloca.h>
#endif
#if HAVE_MPI
#include <mpi.h>
#endif
#include "genetic/genetic.h"
#include "utils.h"
#include "experiment.h"
#include "variable.h"
#include "input.h"
#include "optimize.h"
#define DEBUG_OPTIMIZE 0 ///< Macro to debug optimize functions.
/**
* \def RM
* \brief Macro to define the shell remove command.
*/
#ifdef G_OS_WIN32
#define RM "del"
#else
#define RM "rm"
#endif
Optimize optimize[1]; ///< Optimization data.
unsigned int nthreads_climbing;
///< Number of threads for the hill climbing method.
static void (*optimize_algorithm) ();
///< Pointer to the function to perform a optimization algorithm step.
static double (*optimize_estimate_climbing) (unsigned int variable,
unsigned int estimate);
///< Pointer to the function to estimate the climbing.
static double (*optimize_norm) (unsigned int simulation);
///< Pointer to the error norm function.
/**
* Function to write the simulation input file.
*/
static inline void
optimize_input (unsigned int simulation, ///< Simulation number.
char *input, ///< Input file name.
GMappedFile * stencil) ///< Template of the input file name.
{
char buffer[32], value[32];
GRegex *regex;
FILE *file;
char *buffer2, *buffer3 = NULL, *content;
gsize length;
unsigned int i;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_input: start\n");
#endif
// Checking the file
if (!stencil)
goto optimize_input_end;
// Opening stencil
content = g_mapped_file_get_contents (stencil);
length = g_mapped_file_get_length (stencil);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_input: length=%lu\ncontent:\n%s", length, content);
#endif
file = g_fopen (input, "w");
// Parsing stencil
for (i = 0; i < optimize->nvariables; ++i)
{
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_input: variable=%u\n", i);
#endif
snprintf (buffer, 32, "@variable%u@", i + 1);
regex = g_regex_new (buffer, (GRegexCompileFlags) 0, (GRegexMatchFlags) 0,
NULL);
if (i == 0)
{
buffer2 = g_regex_replace_literal (regex, content, length, 0,
optimize->label[i],
(GRegexMatchFlags) 0, NULL);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_input: buffer2\n%s", buffer2);
#endif
}
else
{
length = strlen (buffer3);
buffer2 = g_regex_replace_literal (regex, buffer3, length, 0,
optimize->label[i],
(GRegexMatchFlags) 0, NULL);
g_free (buffer3);
}
g_regex_unref (regex);
length = strlen (buffer2);
snprintf (buffer, 32, "@value%u@", i + 1);
regex = g_regex_new (buffer, (GRegexCompileFlags) 0, (GRegexMatchFlags) 0,
NULL);
snprintf (value, 32, format[optimize->precision[i]],
optimize->value[simulation * optimize->nvariables + i]);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_input: value=%s\n", value);
#endif
buffer3 = g_regex_replace_literal (regex, buffer2, length, 0, value,
(GRegexMatchFlags) 0, NULL);
g_free (buffer2);
g_regex_unref (regex);
}
// Saving input file
fwrite (buffer3, strlen (buffer3), sizeof (char), file);
g_free (buffer3);
fclose (file);
optimize_input_end:
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_input: end\n");
#endif
return;
}
/**
* Function to parse input files, simulating and calculating the objective
* function.
*
* \return Objective function value.
*/
static double
optimize_parse (unsigned int simulation, ///< Simulation number.
unsigned int experiment) ///< Experiment number.
{
unsigned int i;
double e;
char buffer[512], input[MAX_NINPUTS][32], output[32], result[32], *buffer2,
*buffer3, *buffer4;
FILE *file_result;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_parse: start\n");
fprintf (stderr, "optimize_parse: simulation=%u experiment=%u\n",
simulation, experiment);
#endif
// Opening input files
for (i = 0; i < optimize->ninputs; ++i)
{
snprintf (&input[i][0], 32, "input-%u-%u-%u", i, simulation, experiment);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_parse: i=%u input=%s\n", i, &input[i][0]);
#endif
optimize_input (simulation, &input[i][0], optimize->file[i][experiment]);
}
for (; i < MAX_NINPUTS; ++i)
strcpy (&input[i][0], "");
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_parse: parsing end\n");
#endif
// Performing the simulation
snprintf (output, 32, "output-%u-%u", simulation, experiment);
buffer2 = g_path_get_dirname (optimize->simulator);
buffer3 = g_path_get_basename (optimize->simulator);
buffer4 = g_build_filename (buffer2, buffer3, NULL);
snprintf (buffer, 512, "\"%s\" %s %s %s %s %s %s %s %s %s",
buffer4, input[0], input[1], input[2], input[3], input[4],
input[5], input[6], input[7], output);
g_free (buffer4);
g_free (buffer3);
g_free (buffer2);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_parse: %s\n", buffer);
#endif
if (system (buffer) == -1)
error_message = buffer;
// Checking the objective value function
if (optimize->evaluator)
{
snprintf (result, 32, "result-%u-%u", simulation, experiment);
buffer2 = g_path_get_dirname (optimize->evaluator);
buffer3 = g_path_get_basename (optimize->evaluator);
buffer4 = g_build_filename (buffer2, buffer3, NULL);
snprintf (buffer, 512, "\"%s\" %s %s %s",
buffer4, output, optimize->experiment[experiment], result);
g_free (buffer4);
g_free (buffer3);
g_free (buffer2);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_parse: %s\n", buffer);
fprintf (stderr, "optimize_parse: result=%s\n", result);
#endif
if (system (buffer) == -1)
error_message = buffer;
file_result = g_fopen (result, "r");
e = atof (fgets (buffer, 512, file_result));
fclose (file_result);
}
else
{
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_parse: output=%s\n", output);
#endif
strcpy (result, "");
file_result = g_fopen (output, "r");
e = atof (fgets (buffer, 512, file_result));
fclose (file_result);
}
// Removing files
#if !DEBUG_OPTIMIZE
for (i = 0; i < optimize->ninputs; ++i)
{
if (optimize->file[i][0])
{
snprintf (buffer, 512, RM " %s", &input[i][0]);
if (system (buffer) == -1)
error_message = buffer;
}
}
snprintf (buffer, 512, RM " %s %s", output, result);
if (system (buffer) == -1)
error_message = buffer;
#endif
// Processing pending events
if (show_pending)
show_pending ();
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_parse: end\n");
#endif
// Returning the objective function
return e * optimize->weight[experiment];
}
/**
* Function to calculate the Euclidian error norm.
*
* \return Euclidian error norm.
*/
static double
optimize_norm_euclidian (unsigned int simulation) ///< simulation number.
{
double e, ei;
unsigned int i;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_norm_euclidian: start\n");
#endif
e = 0.;
for (i = 0; i < optimize->nexperiments; ++i)
{
ei = optimize_parse (simulation, i);
e += ei * ei;
}
e = sqrt (e);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_norm_euclidian: error=%lg\n", e);
fprintf (stderr, "optimize_norm_euclidian: end\n");
#endif
return e;
}
/**
* Function to calculate the maximum error norm.
*
* \return Maximum error norm.
*/
static double
optimize_norm_maximum (unsigned int simulation) ///< simulation number.
{
double e, ei;
unsigned int i;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_norm_maximum: start\n");
#endif
e = 0.;
for (i = 0; i < optimize->nexperiments; ++i)
{
ei = fabs (optimize_parse (simulation, i));
e = fmax (e, ei);
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_norm_maximum: error=%lg\n", e);
fprintf (stderr, "optimize_norm_maximum: end\n");
#endif
return e;
}
/**
* Function to calculate the P error norm.
*
* \return P error norm.
*/
static double
optimize_norm_p (unsigned int simulation) ///< simulation number.
{
double e, ei;
unsigned int i;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_norm_p: start\n");
#endif
e = 0.;
for (i = 0; i < optimize->nexperiments; ++i)
{
ei = fabs (optimize_parse (simulation, i));
e += pow (ei, optimize->p);
}
e = pow (e, 1. / optimize->p);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_norm_p: error=%lg\n", e);
fprintf (stderr, "optimize_norm_p: end\n");
#endif
return e;
}
/**
* Function to calculate the taxicab error norm.
*
* \return Taxicab error norm.
*/
static double
optimize_norm_taxicab (unsigned int simulation) ///< simulation number.
{
double e;
unsigned int i;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_norm_taxicab: start\n");
#endif
e = 0.;
for (i = 0; i < optimize->nexperiments; ++i)
e += fabs (optimize_parse (simulation, i));
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_norm_taxicab: error=%lg\n", e);
fprintf (stderr, "optimize_norm_taxicab: end\n");
#endif
return e;
}
/**
* Function to print the results.
*/
static void
optimize_print ()
{
unsigned int i;
char buffer[512];
#if HAVE_MPI
if (optimize->mpi_rank)
return;
#endif
printf ("%s\n", _("Best result"));
fprintf (optimize->file_result, "%s\n", _("Best result"));
printf ("error = %.15le\n", optimize->error_old[0]);
fprintf (optimize->file_result, "error = %.15le\n", optimize->error_old[0]);
for (i = 0; i < optimize->nvariables; ++i)
{
snprintf (buffer, 512, "%s = %s\n",
optimize->label[i], format[optimize->precision[i]]);
printf (buffer, optimize->value_old[i]);
fprintf (optimize->file_result, buffer, optimize->value_old[i]);
}
fflush (optimize->file_result);
}
/**
* Function to save in a file the variables and the error.
*/
static void
optimize_save_variables (unsigned int simulation, ///< Simulation number.
double error) ///< Error value.
{
unsigned int i;
char buffer[64];
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_save_variables: start\n");
#endif
for (i = 0; i < optimize->nvariables; ++i)
{
snprintf (buffer, 64, "%s ", format[optimize->precision[i]]);
fprintf (optimize->file_variables, buffer,
optimize->value[simulation * optimize->nvariables + i]);
}
fprintf (optimize->file_variables, "%.14le\n", error);
fflush (optimize->file_variables);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_save_variables: end\n");
#endif
}
/**
* Function to save the best simulations.
*/
static void
optimize_best (unsigned int simulation, ///< Simulation number.
double value) ///< Objective function value.
{
unsigned int i, j;
double e;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_best: start\n");
fprintf (stderr, "optimize_best: nsaveds=%u nbest=%u\n",
optimize->nsaveds, optimize->nbest);
#endif
if (optimize->nsaveds < optimize->nbest
|| value < optimize->error_best[optimize->nsaveds - 1])
{
if (optimize->nsaveds < optimize->nbest)
++optimize->nsaveds;
optimize->error_best[optimize->nsaveds - 1] = value;
optimize->simulation_best[optimize->nsaveds - 1] = simulation;
for (i = optimize->nsaveds; --i;)
{
if (optimize->error_best[i] < optimize->error_best[i - 1])
{
j = optimize->simulation_best[i];
e = optimize->error_best[i];
optimize->simulation_best[i] = optimize->simulation_best[i - 1];
optimize->error_best[i] = optimize->error_best[i - 1];
optimize->simulation_best[i - 1] = j;
optimize->error_best[i - 1] = e;
}
else
break;
}
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_best: end\n");
#endif
}
/**
* Function to optimize sequentially.
*/
static void
optimize_sequential ()
{
unsigned int i;
double e;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_sequential: start\n");
fprintf (stderr, "optimize_sequential: nstart=%u nend=%u\n",
optimize->nstart, optimize->nend);
#endif
for (i = optimize->nstart; i < optimize->nend; ++i)
{
e = optimize_norm (i);
optimize_best (i, e);
optimize_save_variables (i, e);
if (e < optimize->threshold)
{
optimize->stop = 1;
break;
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_sequential: i=%u e=%lg\n", i, e);
#endif
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_sequential: end\n");
#endif
}
/**
* Function to optimize on a thread.
*
* \return NULL.
*/
static void *
optimize_thread (ParallelData * data) ///< Function data.
{
unsigned int i, thread;
double e;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_thread: start\n");
#endif
thread = data->thread;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_thread: thread=%u start=%u end=%u\n", thread,
optimize->thread[thread], optimize->thread[thread + 1]);
#endif
for (i = optimize->thread[thread]; i < optimize->thread[thread + 1]; ++i)
{
e = optimize_norm (i);
g_mutex_lock (mutex);
optimize_best (i, e);
optimize_save_variables (i, e);
if (e < optimize->threshold)
optimize->stop = 1;
g_mutex_unlock (mutex);
if (optimize->stop)
break;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_thread: i=%u e=%lg\n", i, e);
#endif
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_thread: end\n");
#endif
g_thread_exit (NULL);
return NULL;
}
/**
* Function to merge the 2 optimization results.
*/
static inline void
optimize_merge (unsigned int nsaveds, ///< Number of saved results.
unsigned int *simulation_best,
///< Array of best simulation numbers.
double *error_best)
///< Array of best objective function values.
{
unsigned int i, j, k, s[optimize->nbest];
double e[optimize->nbest];
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_merge: start\n");
#endif
i = j = k = 0;
do
{
if (i == optimize->nsaveds)
{
s[k] = simulation_best[j];
e[k] = error_best[j];
++j;
++k;
if (j == nsaveds)
break;
}
else if (j == nsaveds)
{
s[k] = optimize->simulation_best[i];
e[k] = optimize->error_best[i];
++i;
++k;
if (i == optimize->nsaveds)
break;
}
else if (optimize->error_best[i] > error_best[j])
{
s[k] = simulation_best[j];
e[k] = error_best[j];
++j;
++k;
}
else
{
s[k] = optimize->simulation_best[i];
e[k] = optimize->error_best[i];
++i;
++k;
}
}
while (k < optimize->nbest);
optimize->nsaveds = k;
memcpy (optimize->simulation_best, s, k * sizeof (unsigned int));
memcpy (optimize->error_best, e, k * sizeof (double));
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_merge: end\n");
#endif
}
/**
* Function to synchronise the optimization results of MPI tasks.
*/
#if HAVE_MPI
static void
optimize_synchronise ()
{
unsigned int i, nsaveds, simulation_best[optimize->nbest], stop;
double error_best[optimize->nbest];
MPI_Status mpi_stat;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_synchronise: start\n");
#endif
if (optimize->mpi_rank == 0)
{
for (i = 1; (int) i < ntasks; ++i)
{
MPI_Recv (&nsaveds, 1, MPI_INT, i, 1, MPI_COMM_WORLD, &mpi_stat);
MPI_Recv (simulation_best, nsaveds, MPI_INT, i, 1,
MPI_COMM_WORLD, &mpi_stat);
MPI_Recv (error_best, nsaveds, MPI_DOUBLE, i, 1,
MPI_COMM_WORLD, &mpi_stat);
optimize_merge (nsaveds, simulation_best, error_best);
MPI_Recv (&stop, 1, MPI_UNSIGNED, i, 1, MPI_COMM_WORLD, &mpi_stat);
if (stop)
optimize->stop = 1;
}
for (i = 1; (int) i < ntasks; ++i)
MPI_Send (&optimize->stop, 1, MPI_UNSIGNED, i, 1, MPI_COMM_WORLD);
}
else
{
MPI_Send (&optimize->nsaveds, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
MPI_Send (optimize->simulation_best, optimize->nsaveds, MPI_INT, 0, 1,
MPI_COMM_WORLD);
MPI_Send (optimize->error_best, optimize->nsaveds, MPI_DOUBLE, 0, 1,
MPI_COMM_WORLD);
MPI_Send (&optimize->stop, 1, MPI_UNSIGNED, 0, 1, MPI_COMM_WORLD);
MPI_Recv (&stop, 1, MPI_UNSIGNED, 0, 1, MPI_COMM_WORLD, &mpi_stat);
if (stop)
optimize->stop = 1;
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_synchronise: end\n");
#endif
}
#endif
/**
* Function to optimize with the sweep algorithm.
*/
static void
optimize_sweep ()
{
unsigned int i, j, k, l;
double e;
GThread *thread[nthreads];
ParallelData data[nthreads];
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_sweep: start\n");
#endif
for (i = 0; i < optimize->nsimulations; ++i)
{
k = i;
for (j = 0; j < optimize->nvariables; ++j)
{
l = k % optimize->nsweeps[j];
k /= optimize->nsweeps[j];
e = optimize->rangemin[j];
if (optimize->nsweeps[j] > 1)
e += l * (optimize->rangemax[j] - optimize->rangemin[j])
/ (optimize->nsweeps[j] - 1);
optimize->value[i * optimize->nvariables + j] = e;
}
}
optimize->nsaveds = 0;
if (nthreads <= 1)
optimize_sequential ();
else
{
for (i = 0; i < nthreads; ++i)
{
data[i].thread = i;
thread[i]
= g_thread_new (NULL, (GThreadFunc) optimize_thread, &data[i]);
}
for (i = 0; i < nthreads; ++i)
g_thread_join (thread[i]);
}
#if HAVE_MPI
// Communicating tasks results
optimize_synchronise ();
#endif
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_sweep: end\n");
#endif
}
/**
* Function to optimize with the Monte-Carlo algorithm.
*/
static void
optimize_MonteCarlo ()
{
unsigned int i, j;
GThread *thread[nthreads];
ParallelData data[nthreads];
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_MonteCarlo: start\n");
#endif
for (i = 0; i < optimize->nsimulations; ++i)
for (j = 0; j < optimize->nvariables; ++j)
optimize->value[i * optimize->nvariables + j]
= optimize->rangemin[j] + gsl_rng_uniform (optimize->rng)
* (optimize->rangemax[j] - optimize->rangemin[j]);
optimize->nsaveds = 0;
if (nthreads <= 1)
optimize_sequential ();
else
{
for (i = 0; i < nthreads; ++i)
{
data[i].thread = i;
thread[i]
= g_thread_new (NULL, (GThreadFunc) optimize_thread, &data[i]);
}
for (i = 0; i < nthreads; ++i)
g_thread_join (thread[i]);
}
#if HAVE_MPI
// Communicating tasks results
optimize_synchronise ();
#endif
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_MonteCarlo: end\n");
#endif
}
/**
* Function to optimize with the orthogonal sampling algorithm.
*/
static void
optimize_orthogonal ()
{
unsigned int i, j, k, l;
double e;
GThread *thread[nthreads];
ParallelData data[nthreads];
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_orthogonal: start\n");
#endif
for (i = 0; i < optimize->nsimulations; ++i)
{
k = i;
for (j = 0; j < optimize->nvariables; ++j)
{
l = k % optimize->nsweeps[j];
k /= optimize->nsweeps[j];
e = optimize->rangemin[j];
if (optimize->nsweeps[j] > 1)
e += (l + gsl_rng_uniform (optimize->rng))
* (optimize->rangemax[j] - optimize->rangemin[j])
/ optimize->nsweeps[j];
optimize->value[i * optimize->nvariables + j] = e;
}
}
optimize->nsaveds = 0;
if (nthreads <= 1)
optimize_sequential ();
else
{
for (i = 0; i < nthreads; ++i)
{
data[i].thread = i;
thread[i]
= g_thread_new (NULL, (GThreadFunc) optimize_thread, &data[i]);
}
for (i = 0; i < nthreads; ++i)
g_thread_join (thread[i]);
}
#if HAVE_MPI
// Communicating tasks results
optimize_synchronise ();
#endif
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_orthogonal: end\n");
#endif
}
/**
* Function to save the best simulation in a hill climbing method.
*/
static void
optimize_best_climbing (unsigned int simulation, ///< Simulation number.
double value) ///< Objective function value.
{
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_best_climbing: start\n");
fprintf (stderr,
"optimize_best_climbing: simulation=%u value=%.14le best=%.14le\n",
simulation, value, optimize->error_best[0]);
#endif
if (value < optimize->error_best[0])
{
optimize->error_best[0] = value;
optimize->simulation_best[0] = simulation;
#if DEBUG_OPTIMIZE
fprintf (stderr,
"optimize_best_climbing: BEST simulation=%u value=%.14le\n",
simulation, value);
#endif
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_best_climbing: end\n");
#endif
}
/**
* Function to estimate the hill climbing sequentially.
*/
static inline void
optimize_climbing_sequential (unsigned int simulation) ///< Simulation number.
{
double e;
unsigned int i, j;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing_sequential: start\n");
fprintf (stderr, "optimize_climbing_sequential: nstart_climbing=%u "
"nend_climbing=%u\n",
optimize->nstart_climbing, optimize->nend_climbing);
#endif
for (i = optimize->nstart_climbing; i < optimize->nend_climbing; ++i)
{
j = simulation + i;
e = optimize_norm (j);
optimize_best_climbing (j, e);
optimize_save_variables (j, e);
if (e < optimize->threshold)
{
optimize->stop = 1;
break;
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing_sequential: i=%u e=%lg\n", i, e);
#endif
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing_sequential: end\n");
#endif
}
/**
* Function to estimate the hill climbing on a thread.
*
* \return NULL
*/
static void *
optimize_climbing_thread (ParallelData * data) ///< Function data.
{
unsigned int i, thread;
double e;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing_thread: start\n");
#endif
thread = data->thread;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing_thread: thread=%u start=%u end=%u\n",
thread,
optimize->thread_climbing[thread],
optimize->thread_climbing[thread + 1]);
#endif
for (i = optimize->thread_climbing[thread];
i < optimize->thread_climbing[thread + 1]; ++i)
{
e = optimize_norm (i);
g_mutex_lock (mutex);
optimize_best_climbing (i, e);
optimize_save_variables (i, e);
if (e < optimize->threshold)
optimize->stop = 1;
g_mutex_unlock (mutex);
if (optimize->stop)
break;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing_thread: i=%u e=%lg\n", i, e);
#endif
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing_thread: end\n");
#endif
g_thread_exit (NULL);
return NULL;
}
/**
* Function to estimate a component of the hill climbing vector.
*/
static double
optimize_estimate_climbing_random (unsigned int variable,
///< Variable number.
unsigned int estimate
__attribute__((unused)))
///< Estimate number.
{
double x;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_estimate_climbing_random: start\n");
#endif
x = optimize->climbing[variable]
+ (1. - 2. * gsl_rng_uniform (optimize->rng)) * optimize->step[variable];
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_estimate_climbing_random: climbing%u=%lg\n",
variable, x);
fprintf (stderr, "optimize_estimate_climbing_random: end\n");
#endif
return x;
}
/**
* Function to estimate a component of the hill climbing vector.
*/
static double
optimize_estimate_climbing_coordinates (unsigned int variable,
///< Variable number.
unsigned int estimate)
///< Estimate number.
{
double x;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_estimate_climbing_coordinates: start\n");
#endif
x = optimize->climbing[variable];
if (estimate >= (2 * variable) && estimate < (2 * variable + 2))
{
if (estimate & 1)
x += optimize->step[variable];
else
x -= optimize->step[variable];
}
#if DEBUG_OPTIMIZE
fprintf (stderr,
"optimize_estimate_climbing_coordinates: climbing%u=%lg\n",
variable, x);
fprintf (stderr, "optimize_estimate_climbing_coordinates: end\n");
#endif
return x;
}
/**
* Function to do a step of the hill climbing method.
*/
static inline void
optimize_step_climbing (unsigned int simulation) ///< Simulation number.
{
GThread *thread[nthreads_climbing];
ParallelData data[nthreads_climbing];
unsigned int i, j, k, b;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step_climbing: start\n");
#endif
for (i = 0; i < optimize->nestimates; ++i)
{
k = (simulation + i) * optimize->nvariables;
b = optimize->simulation_best[0] * optimize->nvariables;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step_climbing: simulation=%u best=%u\n",
simulation + i, optimize->simulation_best[0]);
#endif
for (j = 0; j < optimize->nvariables; ++j, ++k, ++b)
{
#if DEBUG_OPTIMIZE
fprintf (stderr,
"optimize_step_climbing: estimate=%u best%u=%.14le\n",
i, j, optimize->value[b]);
#endif
optimize->value[k]
= optimize->value[b] + optimize_estimate_climbing (j, i);
optimize->value[k] = fmin (fmax (optimize->value[k],
optimize->rangeminabs[j]),
optimize->rangemaxabs[j]);
#if DEBUG_OPTIMIZE
fprintf (stderr,
"optimize_step_climbing: estimate=%u variable%u=%.14le\n",
i, j, optimize->value[k]);
#endif
}
}
if (nthreads_climbing == 1)
optimize_climbing_sequential (simulation);
else
{
for (i = 0; i <= nthreads_climbing; ++i)
{
optimize->thread_climbing[i]
= simulation + optimize->nstart_climbing
+ i * (optimize->nend_climbing - optimize->nstart_climbing)
/ nthreads_climbing;
#if DEBUG_OPTIMIZE
fprintf (stderr,
"optimize_step_climbing: i=%u thread_climbing=%u\n",
i, optimize->thread_climbing[i]);
#endif
}
for (i = 0; i < nthreads_climbing; ++i)
{
data[i].thread = i;
thread[i] = g_thread_new
(NULL, (GThreadFunc) optimize_climbing_thread, &data[i]);
}
for (i = 0; i < nthreads_climbing; ++i)
g_thread_join (thread[i]);
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step_climbing: end\n");
#endif
}
/**
* Function to optimize with a hill climbing method.
*/
static inline void
optimize_climbing ()
{
unsigned int i, j, k, b, s, adjust;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing: start\n");
#endif
for (i = 0; i < optimize->nvariables; ++i)
optimize->climbing[i] = 0.;
b = optimize->simulation_best[0] * optimize->nvariables;
s = optimize->nsimulations;
adjust = 1;
for (i = 0; i < optimize->nsteps; ++i, s += optimize->nestimates, b = k)
{
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing: step=%u old_best=%u\n",
i, optimize->simulation_best[0]);
#endif
optimize_step_climbing (s);
k = optimize->simulation_best[0] * optimize->nvariables;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing: step=%u best=%u\n",
i, optimize->simulation_best[0]);
#endif
if (k == b)
{
if (adjust)
for (j = 0; j < optimize->nvariables; ++j)
optimize->step[j] *= 0.5;
for (j = 0; j < optimize->nvariables; ++j)
optimize->climbing[j] = 0.;
adjust = 1;
}
else
{
for (j = 0; j < optimize->nvariables; ++j)
{
#if DEBUG_OPTIMIZE
fprintf (stderr,
"optimize_climbing: best%u=%.14le old%u=%.14le\n",
j, optimize->value[k + j], j, optimize->value[b + j]);
#endif
optimize->climbing[j]
= (1. - optimize->relaxation) * optimize->climbing[j]
+ optimize->relaxation
* (optimize->value[k + j] - optimize->value[b + j]);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing: climbing%u=%.14le\n",
j, optimize->climbing[j]);
#endif
}
adjust = 0;
}
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_climbing: end\n");
#endif
}
/**
* Function to calculate the objective function of an entity.
*
* \return objective function value.
*/
static double
optimize_genetic_objective (Entity * entity) ///< entity data.
{
unsigned int j;
double objective;
char buffer[64];
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_genetic_objective: start\n");
#endif
for (j = 0; j < optimize->nvariables; ++j)
{
optimize->value[entity->id * optimize->nvariables + j]
= genetic_get_variable (entity, optimize->genetic_variable + j);
}
objective = optimize_norm (entity->id);
g_mutex_lock (mutex);
for (j = 0; j < optimize->nvariables; ++j)
{
snprintf (buffer, 64, "%s ", format[optimize->precision[j]]);
fprintf (optimize->file_variables, buffer,
genetic_get_variable (entity, optimize->genetic_variable + j));
}
fprintf (optimize->file_variables, "%.14le\n", objective);
g_mutex_unlock (mutex);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_genetic_objective: end\n");
#endif
return objective;
}
/**
* Function to optimize with the genetic algorithm.
*/
static void
optimize_genetic ()
{
double *best_variable = NULL;
char *best_genome = NULL;
double best_objective = 0.;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_genetic: start\n");
fprintf (stderr, "optimize_genetic: ntasks=%u nthreads=%u\n", ntasks,
nthreads);
fprintf (stderr,
"optimize_genetic: nvariables=%u population=%u generations=%u\n",
optimize->nvariables, optimize->nsimulations, optimize->niterations);
fprintf (stderr,
"optimize_genetic: mutation=%lg reproduction=%lg adaptation=%lg\n",
optimize->mutation_ratio, optimize->reproduction_ratio,
optimize->adaptation_ratio);
#endif
genetic_algorithm_default (optimize->nvariables,
optimize->genetic_variable,
optimize->nsimulations,
optimize->niterations,
optimize->mutation_ratio,
optimize->reproduction_ratio,
optimize->adaptation_ratio,
optimize->seed,
optimize->threshold,
&optimize_genetic_objective,
&best_genome, &best_variable, &best_objective);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_genetic: the best\n");
#endif
optimize->error_old = (double *) g_malloc (sizeof (double));
optimize->value_old
= (double *) g_malloc (optimize->nvariables * sizeof (double));
optimize->error_old[0] = best_objective;
memcpy (optimize->value_old, best_variable,
optimize->nvariables * sizeof (double));
g_free (best_genome);
g_free (best_variable);
optimize_print ();
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_genetic: end\n");
#endif
}
/**
* Function to save the best results on iterative methods.
*/
static inline void
optimize_save_old ()
{
unsigned int i, j;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_save_old: start\n");
fprintf (stderr, "optimize_save_old: nsaveds=%u\n", optimize->nsaveds);
#endif
memcpy (optimize->error_old, optimize->error_best,
optimize->nbest * sizeof (double));
for (i = 0; i < optimize->nbest; ++i)
{
j = optimize->simulation_best[i];
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_save_old: i=%u j=%u\n", i, j);
#endif
memcpy (optimize->value_old + i * optimize->nvariables,
optimize->value + j * optimize->nvariables,
optimize->nvariables * sizeof (double));
}
#if DEBUG_OPTIMIZE
for (i = 0; i < optimize->nvariables; ++i)
fprintf (stderr, "optimize_save_old: best variable %u=%lg\n",
i, optimize->value_old[i]);
fprintf (stderr, "optimize_save_old: end\n");
#endif
}
/**
* Function to merge the best results with the previous step best results on
* iterative methods.
*/
static inline void
optimize_merge_old ()
{
unsigned int i, j, k;
double v[optimize->nbest * optimize->nvariables], e[optimize->nbest],
*enew, *eold;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_merge_old: start\n");
#endif
enew = optimize->error_best;
eold = optimize->error_old;
i = j = k = 0;
do
{
if (*enew < *eold)
{
memcpy (v + k * optimize->nvariables,
optimize->value
+ optimize->simulation_best[i] * optimize->nvariables,
optimize->nvariables * sizeof (double));
e[k] = *enew;
++k;
++enew;
++i;
}
else
{
memcpy (v + k * optimize->nvariables,
optimize->value_old + j * optimize->nvariables,
optimize->nvariables * sizeof (double));
e[k] = *eold;
++k;
++eold;
++j;
}
}
while (k < optimize->nbest);
memcpy (optimize->value_old, v, k * optimize->nvariables * sizeof (double));
memcpy (optimize->error_old, e, k * sizeof (double));
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_merge_old: end\n");
#endif
}
/**
* Function to refine the search ranges of the variables in iterative
* algorithms.
*/
static inline void
optimize_refine ()
{
unsigned int i, j;
double d;
#if HAVE_MPI
MPI_Status mpi_stat;
#endif
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_refine: start\n");
#endif
#if HAVE_MPI
if (!optimize->mpi_rank)
{
#endif
for (j = 0; j < optimize->nvariables; ++j)
{
optimize->rangemin[j] = optimize->rangemax[j]
= optimize->value_old[j];
}
for (i = 0; ++i < optimize->nbest;)
{
for (j = 0; j < optimize->nvariables; ++j)
{
optimize->rangemin[j]
= fmin (optimize->rangemin[j],
optimize->value_old[i * optimize->nvariables + j]);
optimize->rangemax[j]
= fmax (optimize->rangemax[j],
optimize->value_old[i * optimize->nvariables + j]);
}
}
for (j = 0; j < optimize->nvariables; ++j)
{
d = optimize->tolerance
* (optimize->rangemax[j] - optimize->rangemin[j]);
switch (optimize->algorithm)
{
case ALGORITHM_MONTE_CARLO:
d *= 0.5;
break;
default:
if (optimize->nsweeps[j] > 1)
d /= optimize->nsweeps[j] - 1;
else
d = 0.;
}
optimize->rangemin[j] -= d;
optimize->rangemin[j]
= fmax (optimize->rangemin[j], optimize->rangeminabs[j]);
optimize->rangemax[j] += d;
optimize->rangemax[j]
= fmin (optimize->rangemax[j], optimize->rangemaxabs[j]);
printf ("%s min=%lg max=%lg\n", optimize->label[j],
optimize->rangemin[j], optimize->rangemax[j]);
fprintf (optimize->file_result, "%s min=%lg max=%lg\n",
optimize->label[j], optimize->rangemin[j],
optimize->rangemax[j]);
}
#if HAVE_MPI
for (i = 1; (int) i < ntasks; ++i)
{
MPI_Send (optimize->rangemin, optimize->nvariables, MPI_DOUBLE, i,
1, MPI_COMM_WORLD);
MPI_Send (optimize->rangemax, optimize->nvariables, MPI_DOUBLE, i,
1, MPI_COMM_WORLD);
}
}
else
{
MPI_Recv (optimize->rangemin, optimize->nvariables, MPI_DOUBLE, 0, 1,
MPI_COMM_WORLD, &mpi_stat);
MPI_Recv (optimize->rangemax, optimize->nvariables, MPI_DOUBLE, 0, 1,
MPI_COMM_WORLD, &mpi_stat);
}
#endif
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_refine: end\n");
#endif
}
/**
* Function to do a step of the iterative algorithm.
*/
static void
optimize_step ()
{
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step: start\n");
#endif
optimize_algorithm ();
if (optimize->nsteps)
optimize_climbing ();
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_step: end\n");
#endif
}
/**
* Function to iterate the algorithm.
*/
static inline void
optimize_iterate ()
{
unsigned int i;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_iterate: start\n");
#endif
optimize->error_old = (double *) g_malloc (optimize->nbest * sizeof (double));
optimize->value_old =
(double *) g_malloc (optimize->nbest * optimize->nvariables *
sizeof (double));
optimize_step ();
optimize_save_old ();
optimize_refine ();
optimize_print ();
for (i = 1; i < optimize->niterations && !optimize->stop; ++i)
{
optimize_step ();
optimize_merge_old ();
optimize_refine ();
optimize_print ();
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_iterate: end\n");
#endif
}
/**
* Function to free the memory used by the Optimize struct.
*/
void
optimize_free ()
{
unsigned int i, j;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_free: start\n");
#endif
for (j = 0; j < optimize->ninputs; ++j)
{
for (i = 0; i < optimize->nexperiments; ++i)
g_mapped_file_unref (optimize->file[j][i]);
g_free (optimize->file[j]);
}
g_free (optimize->error_old);
g_free (optimize->value_old);
g_free (optimize->value);
g_free (optimize->genetic_variable);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_free: end\n");
#endif
}
/**
* Function to open and perform a optimization.
*/
void
optimize_open ()
{
GTimeZone *tz;
GDateTime *t0, *t;
unsigned int i, j;
#if DEBUG_OPTIMIZE
char *buffer;
fprintf (stderr, "optimize_open: start\n");
#endif
// Getting initial time
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: getting initial time\n");
#endif
tz = g_time_zone_new_utc ();
t0 = g_date_time_new_now (tz);
// Obtaining and initing the pseudo-random numbers generator seed
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: getting initial seed\n");
#endif
if (optimize->seed == DEFAULT_RANDOM_SEED)
optimize->seed = input->seed;
gsl_rng_set (optimize->rng, optimize->seed);
// Replacing the working directory
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: replacing the working directory\n");
#endif
g_chdir (input->directory);
// Getting results file names
optimize->result = input->result;
optimize->variables = input->variables;
// Obtaining the simulator file
optimize->simulator = input->simulator;
// Obtaining the evaluator file
optimize->evaluator = input->evaluator;
// Reading the algorithm
optimize->algorithm = input->algorithm;
switch (optimize->algorithm)
{
case ALGORITHM_MONTE_CARLO:
optimize_algorithm = optimize_MonteCarlo;
break;
case ALGORITHM_SWEEP:
optimize_algorithm = optimize_sweep;
break;
case ALGORITHM_ORTHOGONAL:
optimize_algorithm = optimize_orthogonal;
break;
default:
optimize_algorithm = optimize_genetic;
optimize->mutation_ratio = input->mutation_ratio;
optimize->reproduction_ratio = input->reproduction_ratio;
optimize->adaptation_ratio = input->adaptation_ratio;
}
optimize->nvariables = input->nvariables;
optimize->nsimulations = input->nsimulations;
optimize->niterations = input->niterations;
optimize->nbest = input->nbest;
optimize->tolerance = input->tolerance;
optimize->nsteps = input->nsteps;
optimize->nestimates = 0;
optimize->threshold = input->threshold;
optimize->stop = 0;
if (input->nsteps)
{
optimize->relaxation = input->relaxation;
switch (input->climbing)
{
case CLIMBING_METHOD_COORDINATES:
optimize->nestimates = 2 * optimize->nvariables;
optimize_estimate_climbing = optimize_estimate_climbing_coordinates;
break;
default:
optimize->nestimates = input->nestimates;
optimize_estimate_climbing = optimize_estimate_climbing_random;
}
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: nbest=%u\n", optimize->nbest);
#endif
optimize->simulation_best
= (unsigned int *) alloca (optimize->nbest * sizeof (unsigned int));
optimize->error_best = (double *) alloca (optimize->nbest * sizeof (double));
// Reading the experimental data
#if DEBUG_OPTIMIZE
buffer = g_get_current_dir ();
fprintf (stderr, "optimize_open: current directory=%s\n", buffer);
g_free (buffer);
#endif
optimize->nexperiments = input->nexperiments;
optimize->ninputs = input->experiment->ninputs;
optimize->experiment
= (char **) alloca (input->nexperiments * sizeof (char *));
optimize->weight = (double *) alloca (input->nexperiments * sizeof (double));
for (i = 0; i < input->experiment->ninputs; ++i)
optimize->file[i] = (GMappedFile **)
g_malloc (input->nexperiments * sizeof (GMappedFile *));
for (i = 0; i < input->nexperiments; ++i)
{
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: i=%u\n", i);
#endif
optimize->experiment[i] = input->experiment[i].name;
optimize->weight[i] = input->experiment[i].weight;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: experiment=%s weight=%lg\n",
optimize->experiment[i], optimize->weight[i]);
#endif
for (j = 0; j < input->experiment->ninputs; ++j)
{
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: stencil%u\n", j + 1);
#endif
optimize->file[j][i]
= g_mapped_file_new (input->experiment[i].stencil[j], 0, NULL);
}
}
// Reading the variables data
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: reading variables\n");
#endif
optimize->label = (char **) alloca (input->nvariables * sizeof (char *));
j = input->nvariables * sizeof (double);
optimize->rangemin = (double *) alloca (j);
optimize->rangeminabs = (double *) alloca (j);
optimize->rangemax = (double *) alloca (j);
optimize->rangemaxabs = (double *) alloca (j);
optimize->step = (double *) alloca (j);
j = input->nvariables * sizeof (unsigned int);
optimize->precision = (unsigned int *) alloca (j);
optimize->nsweeps = (unsigned int *) alloca (j);
optimize->nbits = (unsigned int *) alloca (j);
for (i = 0; i < input->nvariables; ++i)
{
optimize->label[i] = input->variable[i].name;
optimize->rangemin[i] = input->variable[i].rangemin;
optimize->rangeminabs[i] = input->variable[i].rangeminabs;
optimize->rangemax[i] = input->variable[i].rangemax;
optimize->rangemaxabs[i] = input->variable[i].rangemaxabs;
optimize->precision[i] = input->variable[i].precision;
optimize->step[i] = input->variable[i].step;
optimize->nsweeps[i] = input->variable[i].nsweeps;
optimize->nbits[i] = input->variable[i].nbits;
}
if (input->algorithm == ALGORITHM_SWEEP
|| input->algorithm == ALGORITHM_ORTHOGONAL)
{
optimize->nsimulations = 1;
for (i = 0; i < input->nvariables; ++i)
{
optimize->nsimulations *= optimize->nsweeps[i];
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: nsweeps=%u nsimulations=%u\n",
optimize->nsweeps[i], optimize->nsimulations);
#endif
}
}
if (optimize->nsteps)
optimize->climbing
= (double *) alloca (optimize->nvariables * sizeof (double));
// Setting error norm
switch (input->norm)
{
case ERROR_NORM_EUCLIDIAN:
optimize_norm = optimize_norm_euclidian;
break;
case ERROR_NORM_MAXIMUM:
optimize_norm = optimize_norm_maximum;
break;
case ERROR_NORM_P:
optimize_norm = optimize_norm_p;
optimize->p = input->p;
break;
default:
optimize_norm = optimize_norm_taxicab;
}
// Allocating values
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: allocating variables\n");
fprintf (stderr, "optimize_open: nvariables=%u algorithm=%u\n",
optimize->nvariables, optimize->algorithm);
#endif
optimize->genetic_variable = NULL;
if (optimize->algorithm == ALGORITHM_GENETIC)
{
optimize->genetic_variable = (GeneticVariable *)
g_malloc (optimize->nvariables * sizeof (GeneticVariable));
for (i = 0; i < optimize->nvariables; ++i)
{
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: i=%u min=%lg max=%lg nbits=%u\n",
i, optimize->rangemin[i], optimize->rangemax[i],
optimize->nbits[i]);
#endif
optimize->genetic_variable[i].minimum = optimize->rangemin[i];
optimize->genetic_variable[i].maximum = optimize->rangemax[i];
optimize->genetic_variable[i].nbits = optimize->nbits[i];
}
}
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: nvariables=%u nsimulations=%u\n",
optimize->nvariables, optimize->nsimulations);
#endif
optimize->value = (double *)
g_malloc ((optimize->nsimulations
+ optimize->nestimates * optimize->nsteps)
* optimize->nvariables * sizeof (double));
// Calculating simulations to perform for each task
#if HAVE_MPI
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: rank=%u ntasks=%u\n",
optimize->mpi_rank, ntasks);
#endif
optimize->nstart = optimize->mpi_rank * optimize->nsimulations / ntasks;
optimize->nend = (1 + optimize->mpi_rank) * optimize->nsimulations / ntasks;
if (optimize->nsteps)
{
optimize->nstart_climbing
= optimize->mpi_rank * optimize->nestimates / ntasks;
optimize->nend_climbing
= (1 + optimize->mpi_rank) * optimize->nestimates / ntasks;
}
#else
optimize->nstart = 0;
optimize->nend = optimize->nsimulations;
if (optimize->nsteps)
{
optimize->nstart_climbing = 0;
optimize->nend_climbing = optimize->nestimates;
}
#endif
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: nstart=%u nend=%u\n", optimize->nstart,
optimize->nend);
#endif
// Calculating simulations to perform for each thread
optimize->thread
= (unsigned int *) alloca ((1 + nthreads) * sizeof (unsigned int));
for (i = 0; i <= nthreads; ++i)
{
optimize->thread[i] = optimize->nstart
+ i * (optimize->nend - optimize->nstart) / nthreads;
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: i=%u thread=%u\n", i,
optimize->thread[i]);
#endif
}
if (optimize->nsteps)
optimize->thread_climbing = (unsigned int *)
alloca ((1 + nthreads_climbing) * sizeof (unsigned int));
// Opening result files
optimize->file_result = g_fopen (optimize->result, "w");
optimize->file_variables = g_fopen (optimize->variables, "w");
// Performing the algorithm
switch (optimize->algorithm)
{
// Genetic algorithm
case ALGORITHM_GENETIC:
optimize_genetic ();
break;
// Iterative algorithm
default:
optimize_iterate ();
}
// Getting calculation time
t = g_date_time_new_now (tz);
optimize->calculation_time = 0.000001 * g_date_time_difference (t, t0);
g_date_time_unref (t);
g_date_time_unref (t0);
g_time_zone_unref (tz);
printf ("%s = %.6lg s\n", _("Calculation time"), optimize->calculation_time);
fprintf (optimize->file_result, "%s = %.6lg s\n",
_("Calculation time"), optimize->calculation_time);
// Closing result files
fclose (optimize->file_variables);
fclose (optimize->file_result);
#if DEBUG_OPTIMIZE
fprintf (stderr, "optimize_open: end\n");
#endif
}
| {
"alphanum_fraction": 0.6170516836,
"avg_line_length": 29.6804183614,
"ext": "c",
"hexsha": "1660a2e592a65c0c3f8271c8d7479baab8a7a492",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/mpcotool",
"max_forks_repo_path": "4.0.5/optimize.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610",
"max_issues_repo_issues_event_max_datetime": "2016-03-08T17:02:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-03-08T17:02:14.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/mpcotool",
"max_issues_repo_path": "4.0.5/optimize.c",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e8a6a9713d4ef73b0aa8a0a552d91117ebd22610",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/mpcotool",
"max_stars_repo_path": "4.0.5/optimize.c",
"max_stars_repo_stars_event_max_datetime": "2018-12-17T14:59:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-17T14:59:29.000Z",
"num_tokens": 13215,
"size": 51080
} |
/*
LAPACKE_dgesv Example
=====================
The program computes the solution to the system of linear
equations with a square matrix A and multiple
right-hand sides B, where A is the coefficient matrix
and b is the right-hand side matrix:
Description
===========
The routine solves for X the system of linear equations A*X = B,
where A is an n-by-n matrix, the columns of matrix B are individual
right-hand sides, and the columns of X are the corresponding
solutions.
The LU decomposition with partial pivoting and row interchanges is
used to factor A as A = P*L*U, where P is a permutation matrix, L
is unit lower triangular, and U is upper triangular. The factored
form of A is then used to solve the system of equations A*X = B.
LAPACKE Interface
=================
LAPACKE_dgesv (row-major, high-level) Example Program Results
-- LAPACKE Example routine (version 3.7.0) --
-- LAPACK is a software package provided by Univ. of Tennessee, --
-- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
December 2016
*/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <math.h>
#include <sys/time.h>
#include <unistd.h>
#include <lapacke.h>
#include <string.h>
#ifndef _LAPACKE_EXAMPLE_AUX_
#define _LAPACKE_EXAMPLE_AUX_
void print_matrix_rowmajor( char* desc, lapack_int m, lapack_int n, double* mat, lapack_int ldm );
void print_matrix_colmajor( char* desc, lapack_int m, lapack_int n, double* mat, lapack_int ldm );
void print_vector( char* desc, lapack_int n, lapack_int* vec );
#endif /* _LAPACKE_EXAMPLE_AUX_*/
#define FLT double
//void mset(FLT **m, int n, int in) {
void mset(FLT *m, int n, int in) {
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++) {
if(i == j) {
//m[i][j]=in;
m[i+j*n]=in;
} else {
// m[i][j]=0.1;
m[i+j*n]=0.1;
}
}
}
FLT system_clock() {
FLT t;
FLT six=1.0e-6;
struct timeval tb;
struct timezone tz;
gettimeofday(&tb,&tz);
t=(FLT)tb.tv_sec+((FLT)tb.tv_usec)*six;
return(t);
}
/* Main program */
int main(int argc, char **argv) {
/* Locals */
lapack_int n, nrhs, lda, ldb, info;
int i, j;
int DOP=0;
/* Local arrays */
double *A, *b;
lapack_int *ipiv;
int icount,jcount;
double t1,t2,tmin,tmax,dt,tstart;
double *tvect;
tmin=1e30;
tmax=0.0;
/* Default Value */
n = 5; nrhs = 1;
/* Arguments */
for( i = 1; i < argc; i++ ) {
if( strcmp( argv[i], "-n" ) == 0 ) {
n = atoi(argv[i+1]);
i++;
}
if( strcmp( argv[i], "-nrhs" ) == 0 ) {
nrhs = atoi(argv[i+1]);
i++;
}
}
scanf("%d",&n);
/* Initialization */
lda=n, ldb=nrhs;
A = (double *)malloc(n*n*sizeof(double)) ;
if (A==NULL){ printf("error of memory allocation\n"); exit(0); }
b = (double *)malloc(n*nrhs*sizeof(double)) ;
if (b==NULL){ printf("error of memory allocation\n"); exit(0); }
ipiv = (lapack_int *)malloc(n*sizeof(lapack_int)) ;
if (ipiv==NULL){ printf("error of memory allocation\n"); exit(0); }
tstart=system_clock();
tvect=(double*)malloc(500*sizeof(double)) ;
for (icount=0; icount<500;icount++){
mset(A,n,10);
for(i=0;i<n*nrhs;i++)
b[i] = 10.0;
//b[i] = ((double) rand()) / ((double) RAND_MAX) - 0.5;
/* Print Entry Matrix */
if(DOP)print_matrix_rowmajor( "Entry Matrix A", n, n, A, lda );
/* Print Right Rand Side */
if(DOP)print_matrix_rowmajor( "Right Rand Side b", n, nrhs, b, ldb );
if(DOP)printf( "\n" );
/* Executable statements */
if(DOP)printf( "LAPACKE_dgesv (row-major, high-level) Example Program Results\n" );
/* Solve the equations A*X = B */
t1=system_clock();
info = LAPACKE_dgesv( LAPACK_ROW_MAJOR, n, nrhs, A, lda, ipiv,
b, ldb );
t2=system_clock();
dt=t2-t1;
jcount=icount+1;
if(dt > tmax)tmax=dt;
if(dt < tmin)tmin=dt;
tvect[icount]=dt;
if(t2-tstart> 120.0)icount=1000000;
/* Check for the exact singularity */
if( info > 0 ) {
printf( "The diagonal element of the triangular factor of A,\n" );
printf( "U(%i,%i) is zero, so that A is singular;\n", info, info );
printf( "the solution could not be computed.\n" );
exit( 1 );
}
if (info <0) exit( 1 );
/* Print solution */
if(DOP)print_matrix_rowmajor( "Solution", n, nrhs, b, ldb );
/* Print details of LU factorization */
if(DOP)print_matrix_rowmajor( "Details of LU factorization", n, n, A, lda );
/* Print pivot indices */
if(DOP)print_vector( "Pivot indices", n, ipiv );
}
printf("size= %d min=%g max=%g total=%g inverts=%d\n",n,tmin,tmax,t2-tstart,jcount);
n=0;
for(icount=0;icount<jcount;icount++){
printf("%f10.5 ",tvect[icount]);
n=n+1;
if(n==8){
printf("\n");
n=0;}
}
exit( 0 );
} /* End of LAPACKE_dgesv Example */
| {
"alphanum_fraction": 0.5906911706,
"avg_line_length": 29.1046511628,
"ext": "c",
"hexsha": "c6ecf12df4021081de8f2f1e9b04280a18c1675b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "04c162ec890a1c9ba83498b275fbdc81a4704062",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "timkphd/examples",
"max_forks_repo_path": "inverts/regt.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "04c162ec890a1c9ba83498b275fbdc81a4704062",
"max_issues_repo_issues_event_max_datetime": "2022-02-09T01:59:47.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-02-09T01:59:47.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "timkphd/examples",
"max_issues_repo_path": "inverts/regt.c",
"max_line_length": 98,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "04c162ec890a1c9ba83498b275fbdc81a4704062",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "timkphd/examples",
"max_stars_repo_path": "inverts/regt.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-24T19:09:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-01T00:29:22.000Z",
"num_tokens": 1568,
"size": 5006
} |
/* specfunc/gsl_sf_airy.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: G. Jungman */
#ifndef __GSL_SF_AIRY_H__
#define __GSL_SF_AIRY_H__
#include <gsl/gsl_mode.h>
#include <gsl/gsl_sf_result.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Airy function Ai(x)
*
* exceptions: GSL_EUNDRFLW
*/
int gsl_sf_airy_Ai_e(const double x, const gsl_mode_t mode, gsl_sf_result * result);
double gsl_sf_airy_Ai(const double x, gsl_mode_t mode);
/* Airy function Bi(x)
*
* exceptions: GSL_EOVRFLW
*/
int gsl_sf_airy_Bi_e(const double x, gsl_mode_t mode, gsl_sf_result * result);
double gsl_sf_airy_Bi(const double x, gsl_mode_t mode);
/* scaled Ai(x):
* Ai(x) x < 0
* exp(+2/3 x^{3/2}) Ai(x) x > 0
*
* exceptions: none
*/
int gsl_sf_airy_Ai_scaled_e(const double x, gsl_mode_t mode, gsl_sf_result * result);
double gsl_sf_airy_Ai_scaled(const double x, gsl_mode_t mode);
/* scaled Bi(x):
* Bi(x) x < 0
* exp(-2/3 x^{3/2}) Bi(x) x > 0
*
* exceptions: none
*/
int gsl_sf_airy_Bi_scaled_e(const double x, gsl_mode_t mode, gsl_sf_result * result);
double gsl_sf_airy_Bi_scaled(const double x, gsl_mode_t mode);
/* derivative Ai'(x)
*
* exceptions: GSL_EUNDRFLW
*/
int gsl_sf_airy_Ai_deriv_e(const double x, gsl_mode_t mode, gsl_sf_result * result);
double gsl_sf_airy_Ai_deriv(const double x, gsl_mode_t mode);
/* derivative Bi'(x)
*
* exceptions: GSL_EOVRFLW
*/
int gsl_sf_airy_Bi_deriv_e(const double x, gsl_mode_t mode, gsl_sf_result * result);
double gsl_sf_airy_Bi_deriv(const double x, gsl_mode_t mode);
/* scaled derivative Ai'(x):
* Ai'(x) x < 0
* exp(+2/3 x^{3/2}) Ai'(x) x > 0
*
* exceptions: none
*/
int gsl_sf_airy_Ai_deriv_scaled_e(const double x, gsl_mode_t mode, gsl_sf_result * result);
double gsl_sf_airy_Ai_deriv_scaled(const double x, gsl_mode_t mode);
/* scaled derivative:
* Bi'(x) x < 0
* exp(-2/3 x^{3/2}) Bi'(x) x > 0
*
* exceptions: none
*/
int gsl_sf_airy_Bi_deriv_scaled_e(const double x, gsl_mode_t mode, gsl_sf_result * result);
double gsl_sf_airy_Bi_deriv_scaled(const double x, gsl_mode_t mode);
/* Zeros of Ai(x)
*/
int gsl_sf_airy_zero_Ai_e(unsigned int s, gsl_sf_result * result);
double gsl_sf_airy_zero_Ai(unsigned int s);
/* Zeros of Bi(x)
*/
int gsl_sf_airy_zero_Bi_e(unsigned int s, gsl_sf_result * result);
double gsl_sf_airy_zero_Bi(unsigned int s);
/* Zeros of Ai'(x)
*/
int gsl_sf_airy_zero_Ai_deriv_e(unsigned int s, gsl_sf_result * result);
double gsl_sf_airy_zero_Ai_deriv(unsigned int s);
/* Zeros of Bi'(x)
*/
int gsl_sf_airy_zero_Bi_deriv_e(unsigned int s, gsl_sf_result * result);
double gsl_sf_airy_zero_Bi_deriv(unsigned int s);
__END_DECLS
#endif /* __GSL_SF_AIRY_H__ */
| {
"alphanum_fraction": 0.7131236443,
"avg_line_length": 26.3428571429,
"ext": "h",
"hexsha": "f4be70d31b19dd7259763ad4c659baa9fdc34f7c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_airy.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_airy.h",
"max_line_length": 91,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/gsl_sf_airy.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z",
"num_tokens": 1069,
"size": 3688
} |
#pragma once
#include <bgfx/bgfx.h>
#include <napi/napi.h>
#include <gsl/gsl>
#include <optional>
namespace Babylon
{
class IndexBuffer final
{
public:
IndexBuffer(gsl::span<uint8_t> bytes, uint16_t flags, bool dynamic);
~IndexBuffer();
void Dispose();
void Update(Napi::Env env, gsl::span<uint8_t> bytes, uint32_t startIndex);
bool CreateHandle();
void Set(bgfx::Encoder* encoder, uint32_t firstIndex, uint32_t numIndices);
private:
std::optional<std::vector<uint8_t>> m_bytes{};
uint16_t m_flags{};
bool m_dynamic{};
union
{
bgfx::IndexBufferHandle m_handle{bgfx::kInvalidHandle};
bgfx::DynamicIndexBufferHandle m_dynamicHandle;
};
bool m_disposed{};
};
}
| {
"alphanum_fraction": 0.6154791155,
"avg_line_length": 22,
"ext": "h",
"hexsha": "b30dbaa8336876aac2dff28a8462dc8c557a5db2",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "HarveyLijh/ReactNativeBabylon",
"max_forks_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/IndexBuffer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "HarveyLijh/ReactNativeBabylon",
"max_issues_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/IndexBuffer.h",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d9ac79d1e1a00f03f9a4fcf5419e5b118e65e586",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "HarveyLijh/ReactNativeBabylon",
"max_stars_repo_path": "Modules/@babylonjs/react-native/submodules/BabylonNative/Plugins/NativeEngine/Source/IndexBuffer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 200,
"size": 814
} |
/*
* Copyright 2009-2017 The VOTCA Development Team
* (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License")
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _VOTCA_XTP_DIIS__H
#define _VOTCA_XTP_DIIS__H
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_vector.h>
#include <votca/tools/linalg.h>
#include <votca/xtp/aomatrix.h>
#include <votca/xtp/orbitals.h>
#include <votca/ctp/logger.h>
using namespace votca::tools;
namespace votca { namespace xtp {
namespace ub = boost::numeric::ublas;
class Diis{
public:
Diis() {_maxerrorindex=0;
_maxerror=0.0; };
~Diis() {
for (std::vector< ub::matrix<double>* >::iterator it = _mathist.begin() ; it !=_mathist.end(); ++it){
delete *it;
}
_mathist.clear();
for (std::vector< ub::matrix<double>* >::iterator it = _dmathist.begin() ; it !=_dmathist.end(); ++it){
delete *it;
}
_dmathist.clear();
for (std::vector< ub::matrix<double>* >::iterator it = _errormatrixhist.begin() ; it !=_errormatrixhist.end(); ++it){
delete *it;
}
_errormatrixhist.clear();
for (std::vector< std::vector<double>* >::iterator it = _Diis_Bs.begin() ; it !=_Diis_Bs.end(); ++it){
delete *it;
}
_Diis_Bs.clear();
}
void Configure(bool usediis,bool noisy, unsigned histlength, bool maxout, string diismethod, double adiis_start,double diis_start,double levelshift,double levelshiftend,unsigned nocclevels){
_usediis=usediis;
_noisy=noisy;
_histlength=histlength;
_maxout=maxout;
_diismethod=diismethod;
_adiis_start=adiis_start;
_diis_start=diis_start;
_levelshift=levelshift;
_levelshiftend=levelshiftend;
_nocclevels=nocclevels;
}
void setOverlap(ub::matrix<double>* _S){
S=_S;
}
void setSqrtOverlap(ub::matrix<double>* _Sminusahalf){
Sminusahalf=_Sminusahalf;
}
void setLogger(ctp::Logger *pLog){_pLog=pLog;}
double Evolve(const ub::matrix<double>& dmat,const ub::matrix<double>& H,ub::vector<double> &MOenergies,ub::matrix<double> &MOs, int this_iter,double totE);
void SolveFockmatrix(ub::vector<double>& MOenergies,ub::matrix<double>& MOs,ub::matrix<double>&H);
void Levelshift(ub::matrix<double>& H,const ub::matrix<double>&MOs);
unsigned gethistlength(){return _mathist.size();}
double get_E_adiis(const gsl_vector * x) const;
void get_dEdx_adiis(const gsl_vector * x, gsl_vector * dEdx) const;
void get_E_dEdx_adiis(const gsl_vector * x, double * Eval, gsl_vector * dEdx) const;
private:
ctp::Logger *_pLog;
ub::matrix<double>* S;
ub::matrix<double>* Sminusahalf;
bool _usediis;
bool _noisy;
unsigned _histlength;
bool _maxout;
string _diismethod;
ub::matrix<double> _Sminusonehalf;
double _maxerror;
double _adiis_start;
double _diis_start;
double _levelshiftend;
unsigned _maxerrorindex;
std::vector< ub::matrix<double>* > _mathist;
std::vector< ub::matrix<double>* > _dmathist;
std::vector< ub::matrix<double>* > _errormatrixhist;
std::vector< std::vector<double>* > _Diis_Bs;
std::vector<double> _totE;
ub::vector<double> _DiF;
ub::matrix<double> _DiFj;
ub::vector<double> ADIIsCoeff();
ub::vector<double> compute_c(const gsl_vector * x);
/// Compute jacobian
ub::matrix<double> compute_jac(const gsl_vector * x);
/// Compute energy
double min_f(const gsl_vector * x, void * params);
/// Compute derivative
void min_df(const gsl_vector * x, void * params, gsl_vector * g);
/// Compute energy and derivative
void min_fdf(const gsl_vector * x, void * params, double * f, gsl_vector * g);
ub::vector<double> DIIsCoeff();
unsigned _nocclevels;
double _levelshift;
};
namespace adiis {
/// Compute weights
ub::vector<double> compute_c(const gsl_vector * x);
/// Compute jacobian
ub::matrix<double> compute_jac(const gsl_vector * x);
/// Compute energy
double min_f(const gsl_vector * x, void * params);
/// Compute derivative
void min_df(const gsl_vector * x, void * params, gsl_vector * g);
/// Compute energy and derivative
void min_fdf(const gsl_vector * x, void * params, double * f, gsl_vector * g);
};
}}
#endif
| {
"alphanum_fraction": 0.6136840099,
"avg_line_length": 31.2321428571,
"ext": "h",
"hexsha": "918615cac9fe4f23236bba2e139a5aba283586f8",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "choudarykvsp/xtp",
"max_forks_repo_path": "include/votca/xtp/diis.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "choudarykvsp/xtp",
"max_issues_repo_path": "include/votca/xtp/diis.h",
"max_line_length": 193,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "choudarykvsp/xtp",
"max_stars_repo_path": "include/votca/xtp/diis.h",
"max_stars_repo_stars_event_max_datetime": "2018-03-05T17:36:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-03-05T17:36:53.000Z",
"num_tokens": 1376,
"size": 5247
} |
/* rb.c
*
* Copyright (C) 1998-2002, 2004 Free Software Foundation, Inc.
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* This code is originally from GNU libavl, with some modifications */
#include <config.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_bst.h>
#include <gsl/gsl_errno.h>
typedef struct gsl_bst_rb_node rb_node;
typedef gsl_bst_rb_table rb_table;
typedef gsl_bst_rb_traverser rb_traverser;
enum rb_color
{
RB_BLACK, /* black */
RB_RED /* red */
};
#ifndef RB_MAX_HEIGHT
#define RB_MAX_HEIGHT GSL_BST_RB_MAX_HEIGHT
#endif
/* tree functions */
static int rb_init(const gsl_bst_allocator * allocator, gsl_bst_cmp_function * compare,
void * params, void * vtable);
static size_t rb_nodes (const void * vtable);
static int rb_empty (void * vtable);
static void ** rb_probe (void * item, rb_table * table);
static void * rb_insert (void * item, void * vtable);
static void * rb_find (const void * item, const void * vtable);
static void * rb_remove (const void * item, void * vtable);
/* traverser functions */
static int rb_t_init (void * vtrav, const void * vtable);
static void * rb_t_first (void * vtrav, const void * vtable);
static void * rb_t_last (void * vtrav, const void * vtable);
static void * rb_t_find (const void * item, void * vtrav, const void * vtable);
static void * rb_t_insert (void * item, void * vtrav, void * vtable);
static void * rb_t_copy (void * vtrav, const void * vsrc);
static void * rb_t_next (void * vtrav);
static void * rb_t_prev (void * vtrav);
static void * rb_t_cur (const void * vtrav);
static void * rb_t_replace (void * vtrav, void * new_item);
static void rb_trav_refresh (rb_traverser *trav);
static int
rb_init(const gsl_bst_allocator * allocator, gsl_bst_cmp_function * compare,
void * params, void * vtable)
{
rb_table * table = (rb_table *) vtable;
table->rb_alloc = allocator;
table->rb_compare = compare;
table->rb_param = params;
table->rb_root = NULL;
table->rb_count = 0;
table->rb_generation = 0;
return GSL_SUCCESS;
}
static size_t
rb_nodes (const void * vtable)
{
const rb_table * table = (const rb_table *) vtable;
return table->rb_count;
}
/* empty tree (delete all nodes) but do not free the tree itself */
static int
rb_empty (void * vtable)
{
rb_table * table = (rb_table *) vtable;
rb_node *p, *q;
for (p = table->rb_root; p != NULL; p = q)
{
if (p->rb_link[0] == NULL)
{
q = p->rb_link[1];
table->rb_alloc->free (p, table->rb_param);
}
else
{
q = p->rb_link[0];
p->rb_link[0] = q->rb_link[1];
q->rb_link[1] = p;
}
}
table->rb_root = NULL;
table->rb_count = 0;
table->rb_generation = 0;
return GSL_SUCCESS;
}
/* Inserts |item| into |table| and returns a pointer to |item|'s address.
If a duplicate item is found in the tree,
returns a pointer to the duplicate without inserting |item|.
Returns |NULL| in case of memory allocation failure. */
static void **
rb_probe (void * item, rb_table * table)
{
rb_node *pa[RB_MAX_HEIGHT]; /* nodes on stack */
unsigned char da[RB_MAX_HEIGHT]; /* directions moved from stack nodes */
int k; /* stack height */
rb_node *p; /* traverses tree looking for insertion point */
rb_node *n; /* newly inserted node */
pa[0] = (rb_node *) &table->rb_root;
da[0] = 0;
k = 1;
for (p = table->rb_root; p != NULL; p = p->rb_link[da[k - 1]])
{
int cmp = table->rb_compare (item, p->rb_data, table->rb_param);
if (cmp == 0)
return &p->rb_data;
pa[k] = p;
da[k++] = cmp > 0;
}
n = pa[k - 1]->rb_link[da[k - 1]] =
table->rb_alloc->alloc (sizeof *n, table->rb_param);
if (n == NULL)
return NULL;
n->rb_data = item;
n->rb_link[0] = n->rb_link[1] = NULL;
n->rb_color = RB_RED;
table->rb_count++;
table->rb_generation++;
while (k >= 3 && pa[k - 1]->rb_color == RB_RED)
{
if (da[k - 2] == 0)
{
rb_node *y = pa[k - 2]->rb_link[1];
if (y != NULL && y->rb_color == RB_RED)
{
pa[k - 1]->rb_color = y->rb_color = RB_BLACK;
pa[k - 2]->rb_color = RB_RED;
k -= 2;
}
else
{
rb_node *x;
if (da[k - 1] == 0)
y = pa[k - 1];
else
{
x = pa[k - 1];
y = x->rb_link[1];
x->rb_link[1] = y->rb_link[0];
y->rb_link[0] = x;
pa[k - 2]->rb_link[0] = y;
}
x = pa[k - 2];
x->rb_color = RB_RED;
y->rb_color = RB_BLACK;
x->rb_link[0] = y->rb_link[1];
y->rb_link[1] = x;
pa[k - 3]->rb_link[da[k - 3]] = y;
break;
}
}
else
{
rb_node *y = pa[k - 2]->rb_link[0];
if (y != NULL && y->rb_color == RB_RED)
{
pa[k - 1]->rb_color = y->rb_color = RB_BLACK;
pa[k - 2]->rb_color = RB_RED;
k -= 2;
}
else
{
rb_node *x;
if (da[k - 1] == 1)
y = pa[k - 1];
else
{
x = pa[k - 1];
y = x->rb_link[0];
x->rb_link[0] = y->rb_link[1];
y->rb_link[1] = x;
pa[k - 2]->rb_link[1] = y;
}
x = pa[k - 2];
x->rb_color = RB_RED;
y->rb_color = RB_BLACK;
x->rb_link[1] = y->rb_link[0];
y->rb_link[0] = x;
pa[k - 3]->rb_link[da[k - 3]] = y;
break;
}
}
}
table->rb_root->rb_color = RB_BLACK;
return &n->rb_data;
}
/* Inserts |item| into |table|.
Returns |NULL| if |item| was successfully inserted
or if a memory allocation error occurred.
Otherwise, returns the duplicate item. */
static void *
rb_insert (void * item, void * vtable)
{
void **p = rb_probe (item, vtable);
return p == NULL || *p == item ? NULL : *p;
}
/* Search |table| for an item matching |item|, and return it if found.
Otherwise return |NULL|. */
static void *
rb_find (const void * item, const void * vtable)
{
const rb_table * table = (const rb_table *) vtable;
const rb_node *p;
for (p = table->rb_root; p != NULL; )
{
int cmp = table->rb_compare (item, p->rb_data, table->rb_param);
if (cmp < 0)
p = p->rb_link[0];
else if (cmp > 0)
p = p->rb_link[1];
else /* |cmp == 0| */
return p->rb_data;
}
return NULL;
}
#if 0 /*XXX*/
/* Inserts |item| into |table|, replacing any duplicate item.
Returns |NULL| if |item| was inserted without replacing a duplicate,
or if a memory allocation error occurred.
Otherwise, returns the item that was replaced. */
void *
rb_replace (struct rb_table *table, void *item)
{
void **p = rb_probe (table, item);
if (p == NULL || *p == item)
return NULL;
else
{
void *r = *p;
*p = item;
return r;
}
}
#endif
/* Deletes from |table| and returns an item matching |item|.
Returns a null pointer if no matching item found. */
static void *
rb_remove (const void * item, void * vtable)
{
rb_table * table = (rb_table *) vtable;
rb_node *pa[RB_MAX_HEIGHT]; /* nodes on stack */
unsigned char da[RB_MAX_HEIGHT]; /* directions moved from stack nodes */
int k; /* stack height */
rb_node *p; /* the node to delete, or a node part way to it */
int cmp; /* result of comparison between |item| and |p| */
k = 0;
p = (rb_node *) &table->rb_root;
for (cmp = -1; cmp != 0;
cmp = table->rb_compare (item, p->rb_data, table->rb_param))
{
int dir = cmp > 0;
pa[k] = p;
da[k++] = dir;
p = p->rb_link[dir];
if (p == NULL)
return NULL;
}
item = p->rb_data;
if (p->rb_link[1] == NULL)
pa[k - 1]->rb_link[da[k - 1]] = p->rb_link[0];
else
{
enum rb_color t;
rb_node *r = p->rb_link[1];
if (r->rb_link[0] == NULL)
{
r->rb_link[0] = p->rb_link[0];
t = r->rb_color;
r->rb_color = p->rb_color;
p->rb_color = t;
pa[k - 1]->rb_link[da[k - 1]] = r;
da[k] = 1;
pa[k++] = r;
}
else
{
rb_node *s;
int j = k++;
for (;;)
{
da[k] = 0;
pa[k++] = r;
s = r->rb_link[0];
if (s->rb_link[0] == NULL)
break;
r = s;
}
da[j] = 1;
pa[j] = s;
pa[j - 1]->rb_link[da[j - 1]] = s;
s->rb_link[0] = p->rb_link[0];
r->rb_link[0] = s->rb_link[1];
s->rb_link[1] = p->rb_link[1];
t = s->rb_color;
s->rb_color = p->rb_color;
p->rb_color = t;
}
}
if (p->rb_color == RB_BLACK)
{
for (;;)
{
rb_node *x = pa[k - 1]->rb_link[da[k - 1]];
if (x != NULL && x->rb_color == RB_RED)
{
x->rb_color = RB_BLACK;
break;
}
if (k < 2)
break;
if (da[k - 1] == 0)
{
rb_node *w = pa[k - 1]->rb_link[1];
if (w->rb_color == RB_RED)
{
w->rb_color = RB_BLACK;
pa[k - 1]->rb_color = RB_RED;
pa[k - 1]->rb_link[1] = w->rb_link[0];
w->rb_link[0] = pa[k - 1];
pa[k - 2]->rb_link[da[k - 2]] = w;
pa[k] = pa[k - 1];
da[k] = 0;
pa[k - 1] = w;
k++;
w = pa[k - 1]->rb_link[1];
}
if ((w->rb_link[0] == NULL
|| w->rb_link[0]->rb_color == RB_BLACK)
&& (w->rb_link[1] == NULL
|| w->rb_link[1]->rb_color == RB_BLACK))
w->rb_color = RB_RED;
else
{
if (w->rb_link[1] == NULL
|| w->rb_link[1]->rb_color == RB_BLACK)
{
rb_node *y = w->rb_link[0];
y->rb_color = RB_BLACK;
w->rb_color = RB_RED;
w->rb_link[0] = y->rb_link[1];
y->rb_link[1] = w;
w = pa[k - 1]->rb_link[1] = y;
}
w->rb_color = pa[k - 1]->rb_color;
pa[k - 1]->rb_color = RB_BLACK;
w->rb_link[1]->rb_color = RB_BLACK;
pa[k - 1]->rb_link[1] = w->rb_link[0];
w->rb_link[0] = pa[k - 1];
pa[k - 2]->rb_link[da[k - 2]] = w;
break;
}
}
else
{
rb_node *w = pa[k - 1]->rb_link[0];
if (w->rb_color == RB_RED)
{
w->rb_color = RB_BLACK;
pa[k - 1]->rb_color = RB_RED;
pa[k - 1]->rb_link[0] = w->rb_link[1];
w->rb_link[1] = pa[k - 1];
pa[k - 2]->rb_link[da[k - 2]] = w;
pa[k] = pa[k - 1];
da[k] = 1;
pa[k - 1] = w;
k++;
w = pa[k - 1]->rb_link[0];
}
if ((w->rb_link[0] == NULL
|| w->rb_link[0]->rb_color == RB_BLACK)
&& (w->rb_link[1] == NULL
|| w->rb_link[1]->rb_color == RB_BLACK))
w->rb_color = RB_RED;
else
{
if (w->rb_link[0] == NULL
|| w->rb_link[0]->rb_color == RB_BLACK)
{
rb_node *y = w->rb_link[1];
y->rb_color = RB_BLACK;
w->rb_color = RB_RED;
w->rb_link[1] = y->rb_link[0];
y->rb_link[0] = w;
w = pa[k - 1]->rb_link[0] = y;
}
w->rb_color = pa[k - 1]->rb_color;
pa[k - 1]->rb_color = RB_BLACK;
w->rb_link[0]->rb_color = RB_BLACK;
pa[k - 1]->rb_link[0] = w->rb_link[1];
w->rb_link[1] = pa[k - 1];
pa[k - 2]->rb_link[da[k - 2]] = w;
break;
}
}
k--;
}
}
table->rb_alloc->free (p, table->rb_param);
table->rb_count--;
table->rb_generation++;
return (void *) item;
}
/* Initializes |trav| for use with |tree| and selects the null node. */
static int
rb_t_init (void * vtrav, const void * vtable)
{
rb_traverser * trav = (rb_traverser *) vtrav;
const rb_table * table = (const rb_table *) vtable;
trav->rb_table = table;
trav->rb_node = NULL;
trav->rb_height = 0;
trav->rb_generation = table->rb_generation;
return GSL_SUCCESS;
}
/* Initializes |trav| for |table|
and selects and returns a pointer to its least-valued item.
Returns |NULL| if |table| contains no nodes. */
static void *
rb_t_first (void * vtrav, const void * vtable)
{
const rb_table * table = (const rb_table *) vtable;
rb_traverser * trav = (rb_traverser *) vtrav;
rb_node *x;
trav->rb_table = table;
trav->rb_height = 0;
trav->rb_generation = table->rb_generation;
x = table->rb_root;
if (x != NULL)
{
while (x->rb_link[0] != NULL)
{
if (trav->rb_height >= RB_MAX_HEIGHT)
{
GSL_ERROR_NULL ("traverser height exceeds maximum", GSL_ETABLE);
}
trav->rb_stack[trav->rb_height++] = x;
x = x->rb_link[0];
}
}
trav->rb_node = x;
return x != NULL ? x->rb_data : NULL;
}
/* Initializes |trav| for |table|
and selects and returns a pointer to its greatest-valued item.
Returns |NULL| if |table| contains no nodes. */
static void *
rb_t_last (void * vtrav, const void * vtable)
{
const rb_table * table = (const rb_table *) vtable;
rb_traverser * trav = (rb_traverser *) vtrav;
rb_node *x;
trav->rb_table = table;
trav->rb_height = 0;
trav->rb_generation = table->rb_generation;
x = table->rb_root;
if (x != NULL)
{
while (x->rb_link[1] != NULL)
{
if (trav->rb_height >= RB_MAX_HEIGHT)
{
GSL_ERROR_NULL ("traverser height exceeds maximum", GSL_ETABLE);
}
trav->rb_stack[trav->rb_height++] = x;
x = x->rb_link[1];
}
}
trav->rb_node = x;
return x != NULL ? x->rb_data : NULL;
}
/* Searches for |item| in |table|.
If found, initializes |trav| to the item found and returns the item
as well.
If there is no matching item, initializes |trav| to the null item
and returns |NULL|. */
static void *
rb_t_find (const void * item, void * vtrav, const void * vtable)
{
const rb_table * table = (const rb_table *) vtable;
rb_traverser * trav = (rb_traverser *) vtrav;
rb_node *p, *q;
trav->rb_table = table;
trav->rb_height = 0;
trav->rb_generation = table->rb_generation;
for (p = table->rb_root; p != NULL; p = q)
{
int cmp = table->rb_compare (item, p->rb_data, table->rb_param);
if (cmp < 0)
q = p->rb_link[0];
else if (cmp > 0)
q = p->rb_link[1];
else /* |cmp == 0| */
{
trav->rb_node = p;
return p->rb_data;
}
if (trav->rb_height >= RB_MAX_HEIGHT)
{
GSL_ERROR_NULL ("traverser height exceeds maximum", GSL_ETABLE);
}
trav->rb_stack[trav->rb_height++] = p;
}
trav->rb_height = 0;
trav->rb_node = NULL;
return NULL;
}
/* Attempts to insert |item| into |table|.
If |item| is inserted successfully, it is returned and |trav| is
initialized to its location.
If a duplicate is found, it is returned and |trav| is initialized to
its location. No replacement of the item occurs.
If a memory allocation failure occurs, |NULL| is returned and |trav|
is initialized to the null item. */
static void *
rb_t_insert (void * item, void * vtrav, void * vtable)
{
rb_table * table = (rb_table *) vtable;
rb_traverser * trav = (rb_traverser *) vtrav;
void **p;
p = rb_probe (item, table);
if (p != NULL)
{
trav->rb_table = table;
trav->rb_node = ((rb_node *) ((char *) p - offsetof (rb_node, rb_data)));
trav->rb_generation = table->rb_generation - 1;
return *p;
}
else
{
rb_t_init (vtrav, vtable);
return NULL;
}
}
/* Initializes |trav| to have the same current node as |src|. */
static void *
rb_t_copy (void * vtrav, const void * vsrc)
{
const rb_traverser * src = (const rb_traverser *) vsrc;
rb_traverser * trav = (rb_traverser *) vtrav;
if (trav != src)
{
trav->rb_table = src->rb_table;
trav->rb_node = src->rb_node;
trav->rb_generation = src->rb_generation;
if (trav->rb_generation == trav->rb_table->rb_generation)
{
trav->rb_height = src->rb_height;
memcpy (trav->rb_stack, (const void *) src->rb_stack,
sizeof *trav->rb_stack * trav->rb_height);
}
}
return trav->rb_node != NULL ? trav->rb_node->rb_data : NULL;
}
/* Returns the next data item in inorder
within the tree being traversed with |trav|,
or if there are no more data items returns |NULL|. */
static void *
rb_t_next (void * vtrav)
{
rb_traverser * trav = (rb_traverser *) vtrav;
rb_node *x;
if (trav->rb_generation != trav->rb_table->rb_generation)
rb_trav_refresh (trav);
x = trav->rb_node;
if (x == NULL)
{
return rb_t_first (vtrav, trav->rb_table);
}
else if (x->rb_link[1] != NULL)
{
if (trav->rb_height >= RB_MAX_HEIGHT)
{
GSL_ERROR_NULL ("traverser height exceeds maximum", GSL_ETABLE);
}
trav->rb_stack[trav->rb_height++] = x;
x = x->rb_link[1];
while (x->rb_link[0] != NULL)
{
if (trav->rb_height >= RB_MAX_HEIGHT)
{
GSL_ERROR_NULL ("traverser height exceeds maximum", GSL_ETABLE);
}
trav->rb_stack[trav->rb_height++] = x;
x = x->rb_link[0];
}
}
else
{
rb_node *y;
do
{
if (trav->rb_height == 0)
{
trav->rb_node = NULL;
return NULL;
}
y = x;
x = trav->rb_stack[--trav->rb_height];
}
while (y == x->rb_link[1]);
}
trav->rb_node = x;
return x->rb_data;
}
/* Returns the previous data item in inorder
within the tree being traversed with |trav|,
or if there are no more data items returns |NULL|. */
static void *
rb_t_prev (void * vtrav)
{
rb_traverser * trav = (rb_traverser *) vtrav;
rb_node *x;
if (trav->rb_generation != trav->rb_table->rb_generation)
rb_trav_refresh (trav);
x = trav->rb_node;
if (x == NULL)
{
return rb_t_last (vtrav, trav->rb_table);
}
else if (x->rb_link[0] != NULL)
{
if (trav->rb_height >= RB_MAX_HEIGHT)
{
GSL_ERROR_NULL ("traverser height exceeds maximum", GSL_ETABLE);
}
trav->rb_stack[trav->rb_height++] = x;
x = x->rb_link[0];
while (x->rb_link[1] != NULL)
{
if (trav->rb_height >= RB_MAX_HEIGHT)
{
GSL_ERROR_NULL ("traverser height exceeds maximum", GSL_ETABLE);
}
trav->rb_stack[trav->rb_height++] = x;
x = x->rb_link[1];
}
}
else
{
rb_node *y;
do
{
if (trav->rb_height == 0)
{
trav->rb_node = NULL;
return NULL;
}
y = x;
x = trav->rb_stack[--trav->rb_height];
}
while (y == x->rb_link[0]);
}
trav->rb_node = x;
return x->rb_data;
}
/* Returns |trav|'s current item. */
static void *
rb_t_cur (const void * vtrav)
{
const rb_traverser * trav = (const rb_traverser *) vtrav;
return trav->rb_node != NULL ? trav->rb_node->rb_data : NULL;
}
/* Replaces the current item in |trav| by |new| and returns the item replaced.
|trav| must not have the null item selected.
The new item must not upset the ordering of the tree. */
static void *
rb_t_replace (void * vtrav, void * new_item)
{
rb_traverser * trav = (rb_traverser *) vtrav;
void *old;
old = trav->rb_node->rb_data;
trav->rb_node->rb_data = new_item;
return old;
}
#if 0 /*XXX*/
/* Destroys |new| with |rb_destroy (new, destroy)|,
first setting right links of nodes in |stack| within |new|
to null pointers to avoid touching uninitialized data. */
static void
copy_error_recovery (rb_node **stack, int height,
struct rb_table *new, rb_item_func *destroy)
{
assert (stack != NULL && height >= 0 && new != NULL);
for (; height > 2; height -= 2)
stack[height - 1]->rb_link[1] = NULL;
rb_destroy (new, destroy);
}
/* Copies |org| to a newly created tree, which is returned.
If |copy != NULL|, each data item in |org| is first passed to |copy|,
and the return values are inserted into the tree,
with |NULL| return values taken as indications of failure.
On failure, destroys the partially created new tree,
applying |destroy|, if non-null, to each item in the new tree so far,
and returns |NULL|.
If |allocator != NULL|, it is used for allocation in the new tree.
Otherwise, the same allocator used for |org| is used. */
struct rb_table *
rb_copy (const struct rb_table *org, rb_copy_func *copy,
rb_item_func *destroy, struct libavl_allocator *allocator)
{
rb_node *stack[2 * (RB_MAX_HEIGHT + 1)];
int height = 0;
struct rb_table *new;
const rb_node *x;
rb_node *y;
assert (org != NULL);
new = rb_create (org->rb_compare, org->rb_param,
allocator != NULL ? allocator : org->rb_alloc);
if (new == NULL)
return NULL;
new->rb_count = org->rb_count;
if (new->rb_count == 0)
return new;
x = (const rb_node *) &org->rb_root;
y = (rb_node *) &new->rb_root;
for (;;)
{
while (x->rb_link[0] != NULL)
{
assert (height < 2 * (RB_MAX_HEIGHT + 1));
y->rb_link[0] =
new->rb_alloc->libavl_malloc (new->rb_alloc,
sizeof *y->rb_link[0]);
if (y->rb_link[0] == NULL)
{
if (y != (rb_node *) &new->rb_root)
{
y->rb_data = NULL;
y->rb_link[1] = NULL;
}
copy_error_recovery (stack, height, new, destroy);
return NULL;
}
stack[height++] = (rb_node *) x;
stack[height++] = y;
x = x->rb_link[0];
y = y->rb_link[0];
}
y->rb_link[0] = NULL;
for (;;)
{
y->rb_color = x->rb_color;
if (copy == NULL)
y->rb_data = x->rb_data;
else
{
y->rb_data = copy (x->rb_data, org->rb_param);
if (y->rb_data == NULL)
{
y->rb_link[1] = NULL;
copy_error_recovery (stack, height, new, destroy);
return NULL;
}
}
if (x->rb_link[1] != NULL)
{
y->rb_link[1] =
new->rb_alloc->libavl_malloc (new->rb_alloc,
sizeof *y->rb_link[1]);
if (y->rb_link[1] == NULL)
{
copy_error_recovery (stack, height, new, destroy);
return NULL;
}
x = x->rb_link[1];
y = y->rb_link[1];
break;
}
else
y->rb_link[1] = NULL;
if (height <= 2)
return new;
y = stack[--height];
x = stack[--height];
}
}
}
#endif
/* Refreshes the stack of parent pointers in |trav|
and updates its generation number. */
static void
rb_trav_refresh (rb_traverser *trav)
{
trav->rb_generation = trav->rb_table->rb_generation;
if (trav->rb_node != NULL)
{
gsl_bst_cmp_function *cmp = trav->rb_table->rb_compare;
void *param = trav->rb_table->rb_param;
rb_node *node = trav->rb_node;
rb_node *i;
trav->rb_height = 0;
for (i = trav->rb_table->rb_root; i != node; )
{
if (trav->rb_height >= RB_MAX_HEIGHT)
{
GSL_ERROR_VOID ("traverser height exceeds maximum", GSL_ETABLE);
}
trav->rb_stack[trav->rb_height++] = i;
i = i->rb_link[cmp (node->rb_data, i->rb_data, param) > 0];
}
}
}
static const gsl_bst_type rb_tree_type =
{
"red-black",
sizeof(rb_node),
rb_init,
rb_nodes,
rb_insert,
rb_find,
rb_remove,
rb_empty,
rb_t_init,
rb_t_first,
rb_t_last,
rb_t_find,
rb_t_insert,
rb_t_copy,
rb_t_next,
rb_t_prev,
rb_t_cur,
rb_t_replace
};
const gsl_bst_type * gsl_bst_rb = &rb_tree_type;
| {
"alphanum_fraction": 0.5149878271,
"avg_line_length": 26.5535353535,
"ext": "c",
"hexsha": "c8bd1d5e2876579a7103253eeef025780c412f1d",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/bst/rb.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/bst/rb.c",
"max_line_length": 87,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/bst/rb.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z",
"num_tokens": 7427,
"size": 26288
} |
#ifndef TNet_Matrix_h
#define TNet_Matrix_h
#include <stddef.h>
#include <stdlib.h>
#include <stdexcept>
#include <iostream>
#ifdef HAVE_ATLAS
extern "C"{
#include <cblas.h>
#include <clapack.h>
}
#endif
#include "Common.h"
#include "MathAux.h"
#include "Types.h"
#include "Error.h"
//#define TRACE_MATRIX_OPERATIONS
#define CHECKSIZE
namespace TNet
{
// class matrix_error : public std::logic_error {};
// class matrix_sizes_error : public matrix_error {};
// declare the class so the header knows about it
template<typename _ElemT> class Vector;
template<typename _ElemT> class SubVector;
template<typename _ElemT> class Matrix;
template<typename _ElemT> class SubMatrix;
// we need to declare the friend << operator here
template<typename _ElemT>
std::ostream & operator << (std::ostream & rOut, const Matrix<_ElemT> & rM);
// we need to declare the friend << operator here
template<typename _ElemT>
std::istream & operator >> (std::istream & rIn, Matrix<_ElemT> & rM);
// we need to declare this friend function here
template<typename _ElemT>
_ElemT TraceOfProduct(const Matrix<_ElemT> &A, const Matrix<_ElemT> &B); // tr(A B)
// we need to declare this friend function here
template<typename _ElemT>
_ElemT TraceOfProductT(const Matrix<_ElemT> &A, const Matrix<_ElemT> &B); // tr(A B^T)==tr(A^T B)
/** **************************************************************************
** **************************************************************************
* @brief Provides a matrix class
*
* This class provides a way to work with matrices in TNet.
* It encapsulates basic operations and memory optimizations.
*
*/
template<typename _ElemT>
class Matrix
{
public:
/// defines a transpose type
struct HtkHeader
{
INT_32 mNSamples;
INT_32 mSamplePeriod;
INT_16 mSampleSize;
UINT_16 mSampleKind;
};
/**
* @brief Extension of the HTK header
*/
struct HtkHeaderExt
{
INT_32 mHeaderSize;
INT_32 mVersion;
INT_32 mSampSize;
};
/// defines a type of this
typedef Matrix<_ElemT> ThisType;
// Constructors
/// Empty constructor
Matrix<_ElemT> ():
mpData(NULL), mMCols(0), mMRows(0), mStride(0)
#ifdef STK_MEMALIGN_MANUAL
, mpFreeData(NULL)
#endif
{}
/// Copy constructor
Matrix<_ElemT> (const Matrix<_ElemT> & rM, MatrixTrasposeType trans=NO_TRANS):
mpData(NULL)
{ if(trans==NO_TRANS){ Init(rM.mMRows, rM.mMCols); Copy(rM); } else { Init(rM.mMCols,rM.mMRows); Copy(rM,TRANS); } }
/// Copy constructor from another type.
template<typename _ElemU>
explicit Matrix<_ElemT> (const Matrix<_ElemU> & rM, MatrixTrasposeType trans=NO_TRANS):
mpData(NULL)
{ if(trans==NO_TRANS){ Init(rM.Rows(), rM.Cols()); Copy(rM); } else { Init(rM.Cols(),rM.Rows()); Copy(rM,TRANS); } }
/// Basic constructor
Matrix(const size_t r, const size_t c, bool clear=true)
{ mpData=NULL; Init(r, c, clear); }
Matrix<_ElemT> &operator = (const Matrix <_ElemT> &other) { Init(other.Rows(), other.Cols()); Copy(other); return *this; } // Needed for inclusion in std::vector
/// Destructor
~Matrix()
{ Destroy(); }
/// Initializes matrix (if not done by constructor)
ThisType &
Init(const size_t r,
const size_t c, bool clear=true);
/**
* @brief Dealocates the matrix from memory and resets the dimensions to (0, 0)
*/
void
Destroy();
ThisType &
Zero();
ThisType &
Unit(); // set to unit.
/**
* @brief Copies the contents of a matrix
* @param rM Source data matrix
* @return Returns reference to this
*/
template<typename _ElemU> ThisType &
Copy(const Matrix<_ElemU> & rM, MatrixTrasposeType Trans=NO_TRANS);
/**
* @brief Copies the elements of a vector row-by-row into a matrix
* @param rV Source vector
* @param nRows Number of rows of returned matrix
* @param nCols Number of columns of returned matrix
*
* Note that rV.Dim() must equal nRows*nCols
*/
ThisType &
CopyVectorSplicedRows(const Vector<_ElemT> &rV, const size_t nRows, const size_t nCols);
/**
* @brief Returns @c true if matrix is initialized
*/
bool
IsInitialized() const
{ return mpData != NULL; }
/// Returns number of rows in the matrix
inline size_t
Rows() const
{
return mMRows;
}
/// Returns number of columns in the matrix
inline size_t
Cols() const
{
return mMCols;
}
/// Returns number of columns in the matrix memory
inline size_t
Stride() const
{
return mStride;
}
/**
* @brief Gives access to a specified matrix row without range check
* @return Pointer to the const array
*/
inline const _ElemT* __attribute__((aligned(16)))
pData () const
{
return mpData;
}
/**
* @brief Gives access to a specified matrix row without range check
* @return Pointer to the non-const data array
*/
inline _ElemT* __attribute__((aligned(16)))
pData ()
{
return mpData;
}
/**
* @brief pData_workaround is a workaround that allows SubMatrix to get a
* @return pointer to non-const data even though the Matrix is const...
*/
protected:
inline _ElemT* __attribute__((aligned(16)))
pData_workaround () const
{
return mpData;
}
public:
/// Returns size of matrix in memory
size_t
MSize() const
{
return mMRows * mStride * sizeof(_ElemT);
}
/// Checks the content of the matrix for nan and inf values
void
CheckData(const std::string file = "") const
{
for(size_t row=0; row<Rows(); row++) {
for(size_t col=0; col<Cols(); col++) {
if(isnan((*this)(row,col)) || isinf((*this)(row,col))) {
std::ostringstream os;
os << "Invalid value: " << (*this)(row,col)
<< " in matrix row: " << row
<< " col: " << col
<< " file: " << file;
Error(os.str());
}
}
}
}
/**
* **********************************************************************
* **********************************************************************
* @defgroup RESHAPE Matrix reshaping rutines
* **********************************************************************
* **********************************************************************
* @{
*/
/**
* @brief Removes one row from the matrix. The memory is not reallocated.
*/
ThisType &
RemoveRow(size_t i);
/** @} */
/**
* **********************************************************************
* **********************************************************************
* @defgroup ACCESS Access functions and operators
* **********************************************************************
* **********************************************************************
* @{
*/
/**
* @brief Gives access to a specified matrix row without range check
* @return Subvector object representing the row
*/
inline const SubVector<_ElemT>
operator [] (size_t i) const
{
assert(i < mMRows);
return SubVector<_ElemT>(mpData + (i * mStride), Cols());
}
inline SubVector<_ElemT>
operator [] (size_t i)
{
assert(i < mMRows);
return SubVector<_ElemT>(mpData + (i * mStride), Cols());
}
/**
* @brief Gives access to a specified matrix row without range check
* @return pointer to the first field of the row
*/
inline _ElemT*
pRowData(size_t i)
{
assert(i < mMRows);
return mpData + i * mStride;
}
/**
* @brief Gives access to a specified matrix row without range check
* @return pointer to the first field of the row (const version)
*/
inline const _ElemT*
pRowData(size_t i) const
{
assert(i < mMRows);
return mpData + i * mStride;
}
/**
* @brief Gives access to matrix elements (row, col)
* @return reference to the desired field
*/
inline _ElemT&
operator () (size_t r, size_t c)
{
#ifdef PARANOID
assert(r < mMRows && c < mMCols);
#endif
return *(mpData + r * mStride + c);
}
/**
* @brief Gives access to matrix elements (row, col)
* @return pointer to the desired field (const version)
*/
inline const _ElemT
operator () (size_t r, size_t c) const
{
#ifdef PARANOID
assert(r < mMRows && c < mMCols);
#endif
return *(mpData + r * mStride + c);
}
/**
* @brief Returns a matrix sub-range
* @param ro Row offset
* @param r Rows in range
* @param co Column offset
* @param c Coluns in range
* See @c SubMatrix class for details
*/
SubMatrix<_ElemT>
Range(const size_t ro, const size_t r,
const size_t co, const size_t c)
{ return SubMatrix<_ElemT>(*this, ro, r, co, c); }
const SubMatrix<_ElemT>
Range(const size_t ro, const size_t r,
const size_t co, const size_t c) const
{ return SubMatrix<_ElemT>(*this, ro, r, co, c); }
/** @} */
/**
* **********************************************************************
* **********************************************************************
* @defgroup MATH ROUTINES
* **********************************************************************
* **********************************************************************
* @{
**/
/**
* @brief Returns sum of all elements
*/
_ElemT&
Sum() const;
ThisType &
DotMul(const ThisType& a);
ThisType &
Scale(_ElemT alpha);
ThisType &
ScaleCols(const Vector<_ElemT> &scale); // Equivalent to (*this) = (*this) * diag(scale).
ThisType &
ScaleRows(const Vector<_ElemT> &scale); // Equivalent to (*this) = diag(scale) * (*this);
/// Sum another matrix rMatrix with this matrix
ThisType&
Add(const Matrix<_ElemT>& rMatrix);
/// Sum scaled matrix rMatrix with this matrix
ThisType&
AddScaled(_ElemT alpha, const Matrix<_ElemT>& rMatrix);
/// Apply log to all items of the matrix
ThisType&
ApplyLog();
/**
* @brief Computes the determinant of this matrix
* @return Returns the determinant of a matrix
* @ingroup MATH
*
*/
_ElemT LogAbsDeterminant(_ElemT *DetSign=NULL);
/**
* @brief Performs matrix inplace inversion
*/
ThisType &
Invert(_ElemT *LogDet=NULL, _ElemT *DetSign=NULL, bool inverse_needed=true);
/**
* @brief Performs matrix inplace inversion in double precision, even if this object is not double precision.
*/
ThisType &
InvertDouble(_ElemT *LogDet=NULL, _ElemT *DetSign=NULL, bool inverse_needed=true){
double LogDet_tmp, DetSign_tmp;
Matrix<double> dmat(*this); dmat.Invert(&LogDet_tmp, &DetSign_tmp, inverse_needed); if(inverse_needed) (*this).Copy(dmat);
if(LogDet) *LogDet = LogDet_tmp; if(DetSign) *DetSign = DetSign_tmp;
return *this;
}
/**
* @brief Inplace matrix transposition. Applicable only to square matrices
*/
ThisType &
Transpose()
{
assert(Rows()==Cols());
size_t M=Rows();
for(size_t i=0;i<M;i++)
for(size_t j=0;j<i;j++){
_ElemT &a = (*this)(i,j), &b = (*this)(j,i);
std::swap(a,b);
}
return *this;
}
bool IsSymmetric(_ElemT cutoff = 1.0e-05) const;
bool IsDiagonal(_ElemT cutoff = 1.0e-05) const;
bool IsUnit(_ElemT cutoff = 1.0e-05) const;
bool IsZero(_ElemT cutoff = 1.0e-05) const;
_ElemT FrobeniusNorm() const; // sqrt of sum of square elements.
_ElemT LargestAbsElem() const; // largest absolute value.
friend _ElemT TNet::TraceOfProduct<_ElemT>(const Matrix<_ElemT> &A, const Matrix<_ElemT> &B); // tr(A B)
friend _ElemT TNet::TraceOfProductT<_ElemT>(const Matrix<_ElemT> &A, const Matrix<_ElemT> &B); // tr(A B^T)==tr(A^T B)
friend class SubMatrix<_ElemT>; // so it can get around const restrictions on the pointer to mpData.
/** **********************************************************************
* **********************************************************************
* @defgroup BLAS_ROUTINES BLAS ROUTINES
* @ingroup MATH
* **********************************************************************
* **********************************************************************
**/
ThisType &
BlasGer(const _ElemT alpha, const Vector<_ElemT>& rA, const Vector<_ElemT>& rB);
ThisType &
Axpy(const _ElemT alpha, const Matrix<_ElemT> &rM, MatrixTrasposeType transA=NO_TRANS);
ThisType &
BlasGemm(const _ElemT alpha,
const ThisType& rA, MatrixTrasposeType transA,
const ThisType& rB, MatrixTrasposeType transB,
const _ElemT beta = 0.0);
/** @} */
/** **********************************************************************
* **********************************************************************
* @defgroup IO Input/Output ROUTINES
* **********************************************************************
* **********************************************************************
* @{
**/
friend std::ostream &
operator << <> (std::ostream & out, const ThisType & m);
void PrintOut(char *file);
void ReadIn(char *file);
bool
LoadHTK(const char* pFileName);
/** @} */
protected:
// inline void swap4b(void *a);
// inline void swap2b(void *a);
protected:
/// data memory area
_ElemT* mpData;
/// these atributes store the real matrix size as it is stored in memory
/// including memalignment
size_t mMCols; ///< Number of columns
size_t mMRows; ///< Number of rows
size_t mStride; ///< true number of columns for the internal matrix.
///< This number may differ from M_cols as memory
///< alignment might be used
#ifdef STK_MEMALIGN_MANUAL
/// data to be freed (in case of manual memalignment use, see Common.h)
_ElemT* mpFreeData;
#endif
}; // class Matrix
template<> Matrix<float> & Matrix<float>::Invert(float *LogDet, float *DetSign, bool inverse_needed); // state that we will implement separately for float and double.
template<> Matrix<double> & Matrix<double>::Invert(double *LogDet, double *DetSign, bool inverse_needed);
/** **************************************************************************
** **************************************************************************
* @brief Sub-matrix representation
*
* This class provides a way to work with matrix cutouts in STK.
*
*
*/
template<typename _ElemT>
class SubMatrix : public Matrix<_ElemT>
{
typedef SubMatrix<_ElemT> ThisType;
public:
/// Constructor
SubMatrix(const Matrix<_ElemT>& rT, // Input matrix cannot be const because SubMatrix can change its contents.
const size_t ro,
const size_t r,
const size_t co,
const size_t c);
/// The destructor
~SubMatrix<_ElemT>()
{
#ifndef STK_MEMALIGN_MANUAL
Matrix<_ElemT>::mpData = NULL;
#else
Matrix<_ElemT>::mpFreeData = NULL;
#endif
}
/// Assign operator
ThisType& operator=(const ThisType& rSrc)
{
//std::cout << "[PERFORMing operator= SubMatrix&^2]" << std::flush;
this->mpData = rSrc.mpData;
this->mMCols = rSrc.mMCols;
this->mMRows = rSrc.mMRows;
this->mStride = rSrc.mStride;
this->mpFreeData = rSrc.mpFreeData;
return *this;
}
/// Initializes matrix (if not done by constructor)
ThisType &
Init(const size_t r,
const size_t c, bool clear=true)
{ Error("Submatrix cannot do Init"); return *this; }
/**
* @brief Dealocates the matrix from memory and resets the dimensions to (0, 0)
*/
void
Destroy()
{ Error("Submatrix cannot do Destroy"); }
};
//Create useful shortcuts
typedef Matrix<BaseFloat> BfMatrix;
typedef SubMatrix<BaseFloat> BfSubMatrix;
/**
* Function for summing matrices of different types
*/
template<typename _ElemT, typename _ElemU>
void Add(Matrix<_ElemT>& rDst, const Matrix<_ElemU>& rSrc) {
assert(rDst.Cols() == rSrc.Cols());
assert(rDst.Rows() == rSrc.Rows());
for(size_t i=0; i<rDst.Rows(); i++) {
const _ElemU* p_src = rSrc.pRowData(i);
_ElemT* p_dst = rDst.pRowData(i);
for(size_t j=0; j<rDst.Cols(); j++) {
*p_dst++ += (_ElemT)*p_src++;
}
}
}
/**
* Function for summing matrices of different types
*/
template<typename _ElemT, typename _ElemU>
void AddScaled(Matrix<_ElemT>& rDst, const Matrix<_ElemU>& rSrc, _ElemT scale) {
assert(rDst.Cols() == rSrc.Cols());
assert(rDst.Rows() == rSrc.Rows());
Vector<_ElemT> tmp(rDst[0]);
for(size_t i=0; i<rDst.Rows(); i++) {
tmp.Copy(rSrc[i]);
rDst[i].BlasAxpy(scale, tmp);
/*
const _ElemU* p_src = rSrc.pRowData(i);
_ElemT* p_dst = rDst.pRowData(i);
for(size_t j=0; j<rDst.Cols(); j++) {
*p_dst++ += (_ElemT)(*p_src++) * scale;
}
*/
}
}
} // namespace STK
//*****************************************************************************
//*****************************************************************************
// we need to include the implementation
#include "Matrix.tcc"
//*****************************************************************************
//*****************************************************************************
/******************************************************************************
******************************************************************************
* The following section contains specialized template definitions
* whose implementation is in Matrix.cc
*/
//#ifndef TNet_Matrix_h
#endif
| {
"alphanum_fraction": 0.5055636439,
"avg_line_length": 28.3657817109,
"ext": "h",
"hexsha": "d33cb0cf0830501705c9430a3c8df2e5b8c9b344",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "troylee/nnet-asr",
"max_forks_repo_path": "src/KaldiLib/Matrix.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "troylee/nnet-asr",
"max_issues_repo_path": "src/KaldiLib/Matrix.h",
"max_line_length": 172,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0381dcb95d9482c36a24d95af16155da9c12f43d",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "troylee/nnet-asr",
"max_stars_repo_path": "src/KaldiLib/Matrix.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4538,
"size": 19232
} |
/**
General definitions
@author Álvaro Barbero Jiménez
@author Suvrit Sra
*/
#ifndef _GENERAL_H
#define _GENERAL_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <float.h>
#include <limits.h>
/* Mex and LAPACK includes */
#ifdef NOMATLAB
//#undef lapack_int
//#define lapack_int long
//#include <lapacke.h>
//#undef MKL_INT
//#define MKL_INT long
#include <mkl.h>
inline double mxGetInf() { return INFINITY; }
#else
#include "mex.h"
#include "lapack.h"
#include "matrix.h"
#define lapack_int ptrdiff_t
#endif
/* Uncomment to print debug messages to a debug file */
//#define DEBUG
/* Choose here the name of the debug file */
#ifdef DEBUG
static FILE* DEBUG_FILE = fopen("debug.tmp","w");
#else
static FILE* DEBUG_FILE = NULL;
#endif
#define DEBUG_N 10 /* Maximum vector length to print in debug messages */
/* Uncomment to produce timing messages (in some of the algorithms) */
//#define TIMING
/* Includes for parallel computation */
#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#define omp_get_max_threads() 1
#define omp_set_num_threads(nThreads) /**/;
#endif
/* Indexes of info structure of solvers */
#define N_INFO 3
#define INFO_ITERS 0
#define INFO_GAP 1
#define INFO_RC 2
/* Comparison tolerance */
#define EPSILON 1e-10
#define IS_ZERO(x) (x < EPSILON & x > -EPSILON)
#define IS_POSITIVE(x) (x > EPSILON)
#define IS_NEGATIVE(x) (x < -EPSILON)
/* Return Codes */
#define RC_OK 0 // Solution found at the specified error level
#define RC_ITERS 1 // Maximum number of iterations reaches, result might be suboptimal
#define RC_STUCK 2 // Algorithm stuck, impossible to improve the objetive function further, result might be suboptimal
#define RC_ERROR 3 // Fatal error during the algorithm, value of the solution is undefined.
#endif
| {
"alphanum_fraction": 0.714360587,
"avg_line_length": 25.44,
"ext": "h",
"hexsha": "a13f4c61b248d21a028ddfdd625e8d6187f60f21",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "493151de568da608e3306ff04f233641be6e5b04",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "hijizhou/NeuronDemix",
"max_forks_repo_path": "trefide/src/proxtv/general.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "493151de568da608e3306ff04f233641be6e5b04",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "hijizhou/NeuronDemix",
"max_issues_repo_path": "trefide/src/proxtv/general.h",
"max_line_length": 118,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "493151de568da608e3306ff04f233641be6e5b04",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "hijizhou/NeuronDemix",
"max_stars_repo_path": "trefide/src/proxtv/general.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-27T14:58:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-27T14:58:12.000Z",
"num_tokens": 492,
"size": 1908
} |
/*
NAME:
splitnmergegauss
PURPOSE:
split one gaussian and merge two other gaussians
CALLING SEQUENCE:
splitnmergegauss(struct gaussian * gaussians,int K, gsl_matrix * qij,
int j, int k, int l)
INPUT:
gaussians - model gaussians
K - number of gaussians
qij - matrix of log(posterior likelihoods)
j,k - gaussians that need to be merged
l - gaussian that needs to be split
OUTPUT:
updated gaussians
REVISION HISTORY:
2008-09-21 - Written Bovy
*/
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
#include "proj_gauss_mixtures.h"
void splitnmergegauss(struct gaussian * gaussians,int K,
gsl_matrix * qij, int j, int k, int l){
//get the gaussians to be split 'n' merged
int d = (gaussians->VV)->size1;//dim of mm
//int partial_indx[]= {-1,-1,-1};/* dummy argument for logsum */
//bool * dummy_allfixed = (bool *) calloc(K,sizeof(bool));
//j,k,l gaussians
struct gaussian gaussianj, gaussiank, gaussianl;
gaussianj.mm = gsl_vector_alloc(d);
gaussianj.VV = gsl_matrix_alloc(d,d);
gaussiank.mm = gsl_vector_alloc(d);
gaussiank.VV = gsl_matrix_alloc(d,d);
gaussianl.mm = gsl_vector_alloc(d);
gaussianl.VV = gsl_matrix_alloc(d,d);
gsl_matrix * unitm = gsl_matrix_alloc(d,d);
gsl_matrix_set_identity(unitm);
gsl_vector * eps = gsl_vector_alloc(d);
double qjj,qjk,detVVjl;
int kk;
for (kk = 0; kk != K; ++kk){
if (kk == j){
gaussianj.alpha = gaussians->alpha;
gsl_vector_memcpy(gaussianj.mm,gaussians->mm);
gsl_matrix_memcpy(gaussianj.VV,gaussians->VV);
qjj = exp(logsum(qij,j,false));//,dummy_allfixed));
}
if (kk == k){
gaussiank.alpha = gaussians->alpha;
gsl_vector_memcpy(gaussiank.mm,gaussians->mm);
gsl_matrix_memcpy(gaussiank.VV,gaussians->VV);
qjk = exp(logsum(qij,k,false));//,dummy_allfixed));
}
if (kk == l){
gaussianl.alpha = gaussians->alpha;
gsl_vector_memcpy(gaussianl.mm,gaussians->mm);
gsl_matrix_memcpy(gaussianl.VV,gaussians->VV);
}
++gaussians;
}
gaussians -= K;
//merge j & k
gaussianj.alpha += gaussiank.alpha;
if (qjk == 0. && qjj == 0){
gsl_vector_add(gaussianj.mm,gaussiank.mm);
gsl_vector_scale(gaussianj.mm,0.5);
gsl_matrix_add(gaussianj.VV,gaussiank.VV);
gsl_matrix_scale(gaussianj.VV,0.5);
}
else{
gsl_vector_scale(gaussianj.mm,qjj/(qjj+qjk));
gsl_vector_scale(gaussiank.mm,qjk/(qjj+qjk));
gsl_vector_add(gaussianj.mm,gaussiank.mm);
gsl_matrix_scale(gaussianj.VV,qjj/(qjj+qjk));
gsl_matrix_scale(gaussiank.VV,qjk/(qjj+qjk));
gsl_matrix_add(gaussianj.VV,gaussiank.VV);
}
//split l
gaussianl.alpha /= 2.;
gaussiank.alpha = gaussianl.alpha;
detVVjl = bovy_det(gaussianl.VV);
detVVjl= pow(detVVjl,1./d);
gsl_matrix_scale(unitm,detVVjl);
gsl_matrix_memcpy(gaussiank.VV,unitm);
gsl_matrix_memcpy(gaussianl.VV,unitm);
gsl_vector_memcpy(gaussiank.mm,gaussianl.mm);
bovy_randvec(eps,d,sqrt(detVVjl));
gsl_vector_add(gaussiank.mm,eps);
bovy_randvec(eps,d,sqrt(detVVjl));
gsl_vector_add(gaussianl.mm,eps);
//copy everything back into the right gaussians
for (kk = 0; kk != K; ++kk){
if (kk == j){
gaussians->alpha = gaussianj.alpha;
gsl_vector_memcpy(gaussians->mm,gaussianj.mm);
gsl_matrix_memcpy(gaussians->VV,gaussianj.VV);
}
if (kk == k){
gaussians->alpha = gaussiank.alpha;
gsl_vector_memcpy(gaussians->mm,gaussiank.mm);
gsl_matrix_memcpy(gaussians->VV,gaussiank.VV);
}
if (kk == l){
gaussians->alpha = gaussianl.alpha;
gsl_vector_memcpy(gaussians->mm,gaussianl.mm);
gsl_matrix_memcpy(gaussians->VV,gaussianl.VV);
}
++gaussians;
}
gaussians -= K;
//cleanup
gsl_matrix_free(unitm);
gsl_vector_free(eps);
//free(dummy_allfixed);
return ;
}
| {
"alphanum_fraction": 0.6672588832,
"avg_line_length": 31.0236220472,
"ext": "c",
"hexsha": "5cb737322f5c4f6616adb92b903dadb3dd7ffec2",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b66d2af16503bc46d785ac9c9ba447ecc29b6fae",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "surbut/mashr",
"max_forks_repo_path": "src/splitnmergegauss.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b66d2af16503bc46d785ac9c9ba447ecc29b6fae",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "surbut/mashr",
"max_issues_repo_path": "src/splitnmergegauss.c",
"max_line_length": 75,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b66d2af16503bc46d785ac9c9ba447ecc29b6fae",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "surbut/mashr",
"max_stars_repo_path": "src/splitnmergegauss.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1203,
"size": 3940
} |
#ifndef _PURSUIT_SHIP_H_
#define _PURSUIT_SHIP_H_
//-----------------------------------------------------------------------------
#include <boost/shared_ptr.hpp>
#include <Ravelin/Pose3d.h>
#include <Ravelin/SpatialRBInertiad.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multifit_nlin.h>
#include <ompl/control/SpaceInformation.h>
#include <ompl/base/goals/GoalState.h>
#include <ompl/base/spaces/SE2StateSpace.h>
#include <ompl/control/spaces/RealVectorControlSpace.h>
#include <ompl/control/planners/rrt/RRT.h>
#include <ompl/control/SimpleSetup.h>
#include <ompl/config.h>
#include <ompl/control/SimpleDirectedControlSampler.h>
#include <ompl/control/ODESolver.h>
#include "experiment.h"
#include "aabb.h"
#include "control_space.h"
//-----------------------------------------------------------------------------
class space_c;
typedef boost::shared_ptr<space_c> space_p;
class ship_c;
typedef boost::shared_ptr<ship_c> ship_p;
//-----------------------------------------------------------------------------
class ship_c {
public:
//---------------------------------------------------------------------------
// Members
//---------------------------------------------------------------------------
Ravelin::Pose3d _pose;
Ravelin::SVelocityd _velocity;
// the inertial mass matrix of the ship
Ravelin::SpatialRBInertiad _inertial;
space_p _space;
//----------
// the set of possible player types
enum role_e {
NONE = 0,
PREY,
PREDATOR
};
role_e role;
ship_p adversary;
double time;
double dtime;
double integration_step;
double controller_step;
// the ship's bounding box in the ship's frame of reference
aabb_c ship_frame_bb;
// whether or not a capture event has occurred
bool capture;
bool stopped;
//---------------------------------------------------------------------------
// Constructors
//---------------------------------------------------------------------------
ship_c( role_e role );
ship_c( ompl::base::StateSpace *_statespace );
//---------------------------------------------------------------------------
// Destructor
//---------------------------------------------------------------------------
virtual ~ship_c( void );
//---------------------------------------------------------------------------
// Base Class Definitions
//---------------------------------------------------------------------------
virtual bool open( void ) { return false; }
virtual bool read( std::vector<double>& q ) { return false; }
virtual bool write( const std::vector<double>& u ) { return false; }
virtual void reset( void ) { }
virtual bool read_ke( double& ke ) { return false; }
public:
static unsigned long compute_prey_command_seed( double time, double dtime );
static double compute_predator_time_randval( double time, double dtime );
// computes commands (forces) if the ship is prey
static void compute_prey_command( const std::vector<double>& pred_state, const std::vector<double>& prey_state, std::vector<double>& prey_u, const double& time, const double& dtime, space_c* space );
// normalizes the quaternion components of the state
static void renormalize_state_quat(std::vector<double>& q);
// compute the bounding box for the ship given a state
aabb_c aabb( const std::vector<double>& q );
// query whether a bounding box intersects another bounding box
//bool intersects_any_obstacle( const aabb_c& mybb, aabb_c& obstacle );
// query whether the ship intersects the world bounding box
bool intersects_world_bounds( const aabb_c& mybb );
// compute any force(field) that the boundary contributes to repel collision
static Ravelin::Vector3d boundary_force( space_c* space, const Ravelin::Vector3d& pos, const Ravelin::Vector3d& vel );
static Ravelin::SForced drag_force( Ravelin::SVelocityd& v, boost::shared_ptr<Ravelin::Pose3d> P_CoM );
// computes a repulsive force for a given distance
static double repulsive_force( double repulsion_factor, double dist );
static double flee_force( double repulsion_factor, double dist );
// - Feedback Control -
// compute the desired state based on the current command and current state
void compute_desired_state( const std::vector<double>& u, const std::vector<double>& x_current, std::vector<double>& x_desired );
// computes the feedback command based on error in the current state
void compute_feedback( const std::vector<double>& x_current, std::vector<double>& x_desired, const std::vector<double>& u_current, std::vector<double>& u_feedback );
// - Dynamics -
// compute the inverse dynamics for the ship
static void inv_dyn( space_c* space, const std::vector<double>& q, const std::vector<double>& qdot_des, std::vector<double>& u, const Ravelin::SpatialRBInertiad& inertial );
// ordinary differential equations for the ship
static void ode( space_c* space, const std::vector<double>& q, const std::vector<double>& u, std::vector<double>& dq, const Ravelin::SpatialRBInertiad& inertial );
// - OMPL --
// plans using the ompl rrt planner
//bool plan_rrt( const std::vector<double>& pred_q, const std::vector<double>& prey_q, std::vector<double>& u );
bool compute_predator_plan( const std::vector<double>& pred_q, const std::vector<double>& prey_q, std::vector< std::vector<double> >& us, std::vector<double>& durations, unsigned& control_count );
// the reference to the statespace the planner has generated
ompl::base::StateSpace *_statespace;
// query whether or not the state generated by the planner is valid
bool is_state_valid(const ompl::control::SpaceInformation *si, const ompl::base::State *state);
// allocates the predator/prey control sampler for the planner
ompl::control::DirectedControlSamplerPtr allocate_pp_control_sampler( const ompl::control::SpaceInformation* si );
// ode. called by the eular_integrator_c in integrator.h
void operator()( const ompl::base::State* state, const ompl::control::Control* control, std::vector<double>& dstate, const Ravelin::SpatialRBInertiad& inertial ) const;
// post integration update method
void update( ompl::base::State* state, const std::vector<double>& dstate ) const;
static double compute_distance( const std::vector<double>& pred_state, const std::vector<double>& prey_state );
private:
void get_predator_control(const std::vector<double>& last_pred_q, const std::vector<double>& new_prey_q, const Ravelin::SpatialRBInertiad& predJ, space_c* space, double DT, std::vector<double>& u);
void integrate_prey(const std::vector<double>& prey_q, const std::vector<double>& pred_q, const Ravelin::SpatialRBInertiad& Jprey, double time, space_c* space, double DT, std::vector<double>& qnew);
void integrate_predator(const std::vector<double>& q, const std::vector<double>& u, const Ravelin::SpatialRBInertiad& J, space_c* space, double DT, std::vector<double>& qnew);
};
#endif // _PURSUIT_SHIP_H_
| {
"alphanum_fraction": 0.6481402309,
"avg_line_length": 41.2764705882,
"ext": "h",
"hexsha": "8ca763bf9d895e23c0744960700e1f02c331c69a",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "c43bc3244b3c68cd1b42358afd18d5a0716d3e0f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "PositronicsLab/tcs",
"max_forks_repo_path": "examples/pursuit/ship.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c43bc3244b3c68cd1b42358afd18d5a0716d3e0f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "PositronicsLab/tcs",
"max_issues_repo_path": "examples/pursuit/ship.h",
"max_line_length": 202,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c43bc3244b3c68cd1b42358afd18d5a0716d3e0f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "PositronicsLab/tcs",
"max_stars_repo_path": "examples/pursuit/ship.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1636,
"size": 7017
} |
/* interpolation/akima.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include "integ_eval.h"
#include <gsl/gsl_interp.h>
typedef struct
{
double * b;
double * c;
double * d;
double * _m;
} akima_state_t;
/* common creation */
static void *
akima_alloc (size_t size)
{
akima_state_t *state = (akima_state_t *) malloc (sizeof (akima_state_t));
if (state == NULL)
{
GSL_ERROR_NULL("failed to allocate space for state", GSL_ENOMEM);
}
state->b = (double *) malloc (size * sizeof (double));
if (state->b == NULL)
{
free (state);
GSL_ERROR_NULL("failed to allocate space for b", GSL_ENOMEM);
}
state->c = (double *) malloc (size * sizeof (double));
if (state->c == NULL)
{
free (state->b);
free (state);
GSL_ERROR_NULL("failed to allocate space for c", GSL_ENOMEM);
}
state->d = (double *) malloc (size * sizeof (double));
if (state->d == NULL)
{
free (state->c);
free (state->b);
free (state);
GSL_ERROR_NULL("failed to allocate space for d", GSL_ENOMEM);
}
state->_m = (double *) malloc ((size + 4) * sizeof (double));
if (state->_m == NULL)
{
free (state->d);
free (state->c);
free (state->b);
free (state);
GSL_ERROR_NULL("failed to allocate space for _m", GSL_ENOMEM);
}
return state;
}
/* common calculation */
static void
akima_calc (const double x_array[], double b[], double c[], double d[], size_t size, double m[])
{
size_t i;
for (i = 0; i < (size - 1); i++)
{
const double NE = fabs (m[i + 1] - m[i]) + fabs (m[i - 1] - m[i - 2]);
if (NE == 0.0)
{
b[i] = m[i];
c[i] = 0.0;
d[i] = 0.0;
}
else
{
const double h_i = x_array[i + 1] - x_array[i];
const double NE_next = fabs (m[i + 2] - m[i + 1]) + fabs (m[i] - m[i - 1]);
const double alpha_i = fabs (m[i - 1] - m[i - 2]) / NE;
double alpha_ip1;
double tL_ip1;
if (NE_next == 0.0)
{
tL_ip1 = m[i];
}
else
{
alpha_ip1 = fabs (m[i] - m[i - 1]) / NE_next;
tL_ip1 = (1.0 - alpha_ip1) * m[i] + alpha_ip1 * m[i + 1];
}
b[i] = (1.0 - alpha_i) * m[i - 1] + alpha_i * m[i];
c[i] = (3.0 * m[i] - 2.0 * b[i] - tL_ip1) / h_i;
d[i] = (b[i] + tL_ip1 - 2.0 * m[i]) / (h_i * h_i);
}
}
}
static int
akima_init (void * vstate, const double x_array[], const double y_array[],
size_t size)
{
akima_state_t *state = (akima_state_t *) vstate;
double * m = state->_m + 2; /* offset so we can address the -1,-2
components */
size_t i;
for (i = 0; i <= size - 2; i++)
{
m[i] = (y_array[i + 1] - y_array[i]) / (x_array[i + 1] - x_array[i]);
}
/* non-periodic boundary conditions */
m[-2] = 3.0 * m[0] - 2.0 * m[1];
m[-1] = 2.0 * m[0] - m[1];
m[size - 1] = 2.0 * m[size - 2] - m[size - 3];
m[size] = 3.0 * m[size - 2] - 2.0 * m[size - 3];
akima_calc (x_array, state->b, state->c, state->d, size, m);
return GSL_SUCCESS;
}
static int
akima_init_periodic (void * vstate,
const double x_array[],
const double y_array[],
size_t size)
{
akima_state_t *state = (akima_state_t *) vstate;
double * m = state->_m + 2; /* offset so we can address the -1,-2
components */
size_t i;
for (i = 0; i <= size - 2; i++)
{
m[i] = (y_array[i + 1] - y_array[i]) / (x_array[i + 1] - x_array[i]);
}
/* periodic boundary conditions */
m[-2] = m[size - 1 - 2];
m[-1] = m[size - 1 - 1];
m[size - 1] = m[0];
m[size] = m[1];
akima_calc (x_array, state->b, state->c, state->d, size, m);
return GSL_SUCCESS;
}
static void
akima_free (void * vstate)
{
akima_state_t *state = (akima_state_t *) vstate;
free (state->b);
free (state->c);
free (state->d);
free (state->_m);
free (state);
}
static
int
akima_eval (const void * vstate,
const double x_array[], const double y_array[], size_t size,
double x,
gsl_interp_accel * a,
double *y)
{
const akima_state_t *state = (const akima_state_t *) vstate;
size_t index;
if (a != 0)
{
index = gsl_interp_accel_find (a, x_array, size, x);
}
else
{
index = gsl_interp_bsearch (x_array, x, 0, size - 1);
}
/* evaluate */
{
const double x_lo = x_array[index];
const double delx = x - x_lo;
const double b = state->b[index];
const double c = state->c[index];
const double d = state->d[index];
*y = y_array[index] + delx * (b + delx * (c + d * delx));
return GSL_SUCCESS;
}
}
static int
akima_eval_deriv (const void * vstate,
const double x_array[], const double y_array[], size_t size,
double x,
gsl_interp_accel * a,
double *dydx)
{
const akima_state_t *state = (const akima_state_t *) vstate;
size_t index;
DISCARD_POINTER(y_array); /* prevent warning about unused parameter */
if (a != 0)
{
index = gsl_interp_accel_find (a, x_array, size, x);
}
else
{
index = gsl_interp_bsearch (x_array, x, 0, size - 1);
}
/* evaluate */
{
double x_lo = x_array[index];
double delx = x - x_lo;
double b = state->b[index];
double c = state->c[index];
double d = state->d[index];
*dydx = b + delx * (2.0 * c + 3.0 * d * delx);
return GSL_SUCCESS;
}
}
static
int
akima_eval_deriv2 (const void * vstate,
const double x_array[], const double y_array[], size_t size,
double x,
gsl_interp_accel * a,
double *y_pp)
{
const akima_state_t *state = (const akima_state_t *) vstate;
size_t index;
DISCARD_POINTER(y_array); /* prevent warning about unused parameter */
if (a != 0)
{
index = gsl_interp_accel_find (a, x_array, size, x);
}
else
{
index = gsl_interp_bsearch (x_array, x, 0, size - 1);
}
/* evaluate */
{
const double x_lo = x_array[index];
const double delx = x - x_lo;
const double c = state->c[index];
const double d = state->d[index];
*y_pp = 2.0 * c + 6.0 * d * delx;
return GSL_SUCCESS;
}
}
static
int
akima_eval_integ (const void * vstate,
const double x_array[], const double y_array[], size_t size,
gsl_interp_accel * acc,
double a, double b,
double * result)
{
const akima_state_t *state = (const akima_state_t *) vstate;
size_t i, index_a, index_b;
if (acc != 0)
{
index_a = gsl_interp_accel_find (acc, x_array, size, a);
index_b = gsl_interp_accel_find (acc, x_array, size, b);
}
else
{
index_a = gsl_interp_bsearch (x_array, a, 0, size - 1);
index_b = gsl_interp_bsearch (x_array, b, 0, size - 1);
}
*result = 0.0;
/* interior intervals */
for(i=index_a; i<=index_b; i++) {
const double x_hi = x_array[i + 1];
const double x_lo = x_array[i];
const double y_lo = y_array[i];
const double dx = x_hi - x_lo;
if(dx != 0.0) {
if (i == index_a || i == index_b)
{
double x1 = (i == index_a) ? a : x_lo;
double x2 = (i == index_b) ? b : x_hi;
*result += integ_eval (y_lo, state->b[i], state->c[i], state->d[i],
x_lo, x1, x2);
}
else
{
*result += dx * (y_lo
+ dx*(0.5*state->b[i]
+ dx*(state->c[i]/3.0
+ 0.25*state->d[i]*dx)));
}
}
else {
*result = 0.0;
return GSL_EINVAL;
}
}
return GSL_SUCCESS;
}
static const gsl_interp_type akima_type =
{
"akima",
5,
&akima_alloc,
&akima_init,
&akima_eval,
&akima_eval_deriv,
&akima_eval_deriv2,
&akima_eval_integ,
&akima_free
};
const gsl_interp_type * gsl_interp_akima = &akima_type;
static const gsl_interp_type akima_periodic_type =
{
"akima-periodic",
5,
&akima_alloc,
&akima_init_periodic,
&akima_eval,
&akima_eval_deriv,
&akima_eval_deriv2,
&akima_eval_integ,
&akima_free
};
const gsl_interp_type * gsl_interp_akima_periodic = &akima_periodic_type;
| {
"alphanum_fraction": 0.5457738982,
"avg_line_length": 24.0871794872,
"ext": "c",
"hexsha": "4244e0f1af7d96040cfe176e5736bc7763f39998",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/akima.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/akima.c",
"max_line_length": 98,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/interpolation/akima.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z",
"num_tokens": 2865,
"size": 9394
} |
///
/// @file This file contains OpenMP and BLAS thread count configuration
/// interface.
///
/// @author Mirko Myllykoski (mirkom@cs.umu.se), Umeå University
///
/// @internal LICENSE
///
/// Copyright (c) 2019-2020, Umeå Universitet
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
///
/// 2. Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// 3. Neither the name of the copyright holder nor the names of its
/// contributors may be used to endorse or promote products derived from this
/// software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///
#include <starneig_test_config.h>
#include <starneig/configuration.h>
#include "threads.h"
#include "parse.h"
#include "omp.h"
#include <hwloc.h>
#ifdef MKL_SET_NUM_THREADS_LOCAL_FOUND
#include <mkl.h>
#endif
#if defined(OPENBLAS_SET_NUM_THREADS_FOUND) || \
defined(GOTO_SET_NUM_THREADS_FOUND)
#include <cblas.h>
#endif
static struct {
int worker_threads;
int blas_threads;
int lapack_threads;
int scalapack_threads;
} status = {
.worker_threads = 1,
.blas_threads = 1,
.lapack_threads = 1,
.scalapack_threads = 1
};
static int get_core_count()
{
hwloc_topology_t topology;
hwloc_topology_init(&topology);
hwloc_topology_load(topology);
hwloc_cpuset_t res = hwloc_bitmap_alloc();
hwloc_cpuset_t mask = hwloc_bitmap_alloc();
hwloc_get_cpubind(topology, mask, HWLOC_CPUBIND_THREAD);
int depth_cores = hwloc_get_type_depth(topology, HWLOC_OBJ_CORE);
int num_cores = hwloc_get_nbobjs_by_depth(topology, depth_cores);
int num_hwloc_cpus = 0;
// iterate over all COREs
for (int i = 0; i < num_cores; i++) {
hwloc_obj_t core = hwloc_get_obj_by_depth(topology, depth_cores, i);
// if the CORE has PUs inside it, ...
if (core->first_child && core->first_child->type == HWLOC_OBJ_PU) {
// iterate over them
hwloc_obj_t pu = core->first_child;
while (pu) {
// if the PU is in the binding mask, ...
hwloc_bitmap_and(res, mask, pu->cpuset);
if (!hwloc_bitmap_iszero(res)) {
// count the PU as a CORE
num_hwloc_cpus++;
break;
}
pu = pu->next_sibling;
}
}
else {
// if the CORE is in the binding mask, ...
hwloc_bitmap_and(res, mask, core->cpuset);
if (!hwloc_bitmap_iszero(res)) {
// count the CORE
num_hwloc_cpus++;
}
}
}
hwloc_bitmap_free(mask);
hwloc_bitmap_free(res);
hwloc_topology_destroy(topology);
return num_hwloc_cpus;
}
static void set_blas_threads(int threads)
{
#if defined(MKL_SET_NUM_THREADS_LOCAL_FOUND)
mkl_set_num_threads_local(threads);
#elif defined(OPENBLAS_SET_NUM_THREADS_FOUND)
openblas_set_num_threads(threads);
#elif defined(GOTO_SET_NUM_THREADS_FOUND)
goto_set_num_threads(threads);
#endif
}
void thread_print_usage(int argc, char * const *argv)
{
printf(
" --test-workers [(num),default] -- Test program StarPU worker count\n"
" --blas-threads [(num),default] -- Test program BLAS thread count\n"
" --lapack-threads [(num),default] -- LAPACK solver thread count\n"
" --scalapack-threads [(num),default] -- ScaLAPACK solver thread "
"count\n"
);
}
void thread_print_args(int argc, char * const *argv)
{
print_multiarg("--test-workers", argc, argv, "default", NULL);
print_multiarg("--blas-threads", argc, argv, "default", NULL);
print_multiarg("--lapack-threads", argc, argv, "default", NULL);
print_multiarg("--scalapack-threads", argc, argv, "default", NULL);
}
int thread_check_args(int argc, char * const *argv, int *argr)
{
struct multiarg_t worker_threads =
read_multiarg("--test-workers", argc, argv, argr, "default", NULL);
if (worker_threads.type == MULTIARG_INVALID ||
(worker_threads.type == MULTIARG_INT && worker_threads.int_value < 1)) {
fprintf(stderr, "Invalid number of StarPU worker threads.\n");
return 1;
}
struct multiarg_t blas_threads =
read_multiarg("--blas-threads", argc, argv, argr, "default", NULL);
if (blas_threads.type == MULTIARG_INVALID ||
(blas_threads.type == MULTIARG_INT && blas_threads.int_value < 1)) {
fprintf(stderr, "Invalid number of BLAS threads.\n");
return 1;
}
struct multiarg_t lapack_threads =
read_multiarg("--lapack-threads", argc, argv, argr, "default", NULL);
if (lapack_threads.type == MULTIARG_INVALID ||
(lapack_threads.type == MULTIARG_INT && lapack_threads.int_value < 1)) {
fprintf(stderr, "Invalid number of LAPACK threads.\n");
return 1;
}
struct multiarg_t scalapack_threads =
read_multiarg("--scalapack-threads", argc, argv, argr, "default", NULL);
if (scalapack_threads.type == MULTIARG_INVALID ||
(scalapack_threads.type == MULTIARG_INT &&
scalapack_threads.int_value < 1)) {
fprintf(stderr, "Invalid number of ScaLAPACK threads.\n");
return 1;
}
return 0;
}
void threads_init(int argc, char * const *argv)
{
struct multiarg_t worker_threads =
read_multiarg("--test-workers", argc, argv, NULL, "default", NULL);
if (worker_threads.type == MULTIARG_INT)
status.worker_threads = worker_threads.int_value;
else
status.worker_threads = get_core_count();
printf(
"THREADS: Using %d StarPU worker threads during initialization and "
"validation.\n", status.worker_threads);
struct multiarg_t blas_threads =
read_multiarg("--blas-threads", argc, argv, NULL, "default", NULL);
if (blas_threads.type == MULTIARG_INT)
status.blas_threads = blas_threads.int_value;
else
status.blas_threads = get_core_count();
printf(
"THREADS: Using %d BLAS threads during initialization and "
"validation.\n", status.blas_threads);
struct multiarg_t lapack_threads =
read_multiarg("--lapack-threads", argc, argv, NULL, "default", NULL);
if (lapack_threads.type == MULTIARG_INT)
status.lapack_threads = lapack_threads.int_value;
else
status.lapack_threads = get_core_count();
printf(
"THREADS: Using %d BLAS threads in LAPACK solvers.\n",
status.lapack_threads);
struct multiarg_t scalapack_threads =
read_multiarg("--scalapack-threads", argc, argv, NULL, "default", NULL);
if (scalapack_threads.type == MULTIARG_INT)
status.scalapack_threads = scalapack_threads.int_value;
else
status.scalapack_threads = 1;
printf(
"THREADS: Using %d BLAS threads in ScaLAPACK solvers.\n",
status.scalapack_threads);
threads_set_mode(THREADS_MODE_DEFAULT);
}
void threads_set_mode(thread_mode_t mode)
{
switch (mode) {
case THREADS_MODE_BLAS:
set_blas_threads(status.blas_threads);
break;
case THREADS_MODE_LAPACK:
set_blas_threads(status.lapack_threads);
break;
case THREADS_MODE_SCALAPACK:
set_blas_threads(status.scalapack_threads);
break;
default:
set_blas_threads(1);
}
}
int threads_get_workers()
{
return status.worker_threads;
}
starneig_flag_t threads_get_fast_dm()
{
if (1 < threads_get_workers())
return STARNEIG_FAST_DM;
return STARNEIG_HINT_DM;
}
| {
"alphanum_fraction": 0.6687256921,
"avg_line_length": 33.4942528736,
"ext": "c",
"hexsha": "5a9b58a8cf2290256d739cd2319a60e2246409b3",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z",
"max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/StarNEig",
"max_forks_repo_path": "test/common/threads.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/StarNEig",
"max_issues_repo_path": "test/common/threads.c",
"max_line_length": 80,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/StarNEig",
"max_stars_repo_path": "test/common/threads.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z",
"num_tokens": 2092,
"size": 8742
} |
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_matrix.h>
#include "../csm_all.h"
#include "gpm.h"
#include <egsl/egsl_macros.h>
void sm_gpm(struct sm_params*params, struct sm_result*res) {
res->valid = 0;
/* Check for well-formedness of the input data */
if(!ld_valid_fields(params->laser_ref) ||
!ld_valid_fields(params->laser_sens)) {
return;
}
LDP laser_ref = params->laser_ref;
LDP laser_sens = params->laser_sens;
/* We need to compute cartesian points */
ld_compute_cartesian(laser_ref);
/* ... and orientation */
ld_simple_clustering(laser_ref, params->clustering_threshold);
ld_compute_orientation(laser_ref, params->orientation_neighbourhood, params->sigma);
/* ... for both scans. */
ld_compute_cartesian(laser_sens);
ld_simple_clustering(laser_sens, params->clustering_threshold);
ld_compute_orientation(laser_sens, params->orientation_neighbourhood, params->sigma);
/* Create an histogram whose bin is large `theta_bin_size` */
double theta_bin_size = deg2rad(params->gpm_theta_bin_size_deg);
double hist_min = -M_PI-theta_bin_size; /* be robust */
double hist_max = +M_PI+theta_bin_size;
size_t nbins = (size_t) ceil( (hist_max-hist_min) / theta_bin_size);
gsl_histogram*hist = gsl_histogram_alloc(nbins);
gsl_histogram_set_ranges_uniform(hist, hist_min, hist_max);
/* Fill the histogram with samples */
double u[3]; copy_d(params->first_guess, 3, u);
sm_debug("gpm 1/2: old u = : %s \n", friendly_pose(u) );
int interval = params->gpm_interval;
int num_correspondences_theta=-1;
ght_find_theta_range(laser_ref, laser_sens,
u, params->max_linear_correction,
params->max_angular_correction_deg, interval, hist, &num_correspondences_theta);
if(num_correspondences_theta < laser_ref->nrays) {
sm_error("sm_gpm(): I found only %d correspondences in the first pass of GPM. I consider it a failure.\n",
num_correspondences_theta);
return;
}
/* Find the bin with most samples */
size_t max_bin = gsl_histogram_max_bin(hist);
/* Around that value will be the range admissible for theta */
double min_range, max_range;
gsl_histogram_get_range(hist,max_bin,&min_range,&max_range);
/* Extend the range of the search */
double extend_range = deg2rad(params->gpm_extend_range_deg);
min_range += -extend_range;
max_range += +extend_range;
/* if(jf()) fprintf(jf(), "iteration 0\n");
journal_pose("x_old", u);*/
/* if(jf()) fprintf(jf(), "iteration 1\n");
journal_pose("x_old", u);*/
/* Now repeat the samples generation with a smaller domain */
u[2] = 0.5 * (max_range + min_range);
double new_range_deg = rad2deg( 0.5*(max_range - min_range) );
double x_new[3];
int num_correspondences=-1;
ght_one_shot(laser_ref, laser_sens,
u, params->max_linear_correction*2,
new_range_deg, interval, x_new, &num_correspondences) ;
if(num_correspondences < laser_ref->nrays) {
sm_error("sm_gpm(): I found only %d correspondences in the second pass of GPM. I consider it a failure.\n",
num_correspondences);
return;
}
/* Et voila, in x_new we have the answer */
{
sm_debug("gpm : max_correction_lin %f def %f\n", params->max_linear_correction, params->max_angular_correction_deg);
sm_debug("gpm : acceptable range for theta: [%f, %f]\n", min_range,max_range);
sm_debug("gpm : 1) Num correspondences for theta: %d\n", num_correspondences_theta);
sm_debug("gpm 1/2: new u = : %s \n", friendly_pose(u) );
sm_debug("gpm 1/2: New range: %f to %f\n",rad2deg(min_range),rad2deg(max_range));
sm_debug("gpm 2/2: Solution: %s \n", friendly_pose(x_new));
/* if(jf()) fprintf(jf(), "iteration 2\n");
journal_pose("x_old", x_new); */
}
/* Administrivia */
res->valid = 1;
copy_d(x_new, 3, res->x);
res->iterations = 0;
gsl_histogram_free(hist);
}
void ght_find_theta_range(LDP laser_ref, LDP laser_sens,
const double*x0, double max_linear_correction,
double max_angular_correction_deg, int interval, gsl_histogram*hist, int*num_correspondences)
{
/** Compute laser_sens's points in laser_ref's coordinates by roto-translating by x0 */
ld_compute_world_coords(laser_sens, x0);
int count = 0;
int i;
for(i=0;i<laser_sens->nrays;i++) {
if(!laser_sens->alpha_valid[i]) continue;
if(i % interval) continue;
const double * p_i = laser_sens->points[i].p;
const double * p_i_w = laser_sens->points_w[i].p;
int from; int to; int start_cell;
possible_interval(p_i_w, laser_ref, max_angular_correction_deg,
max_linear_correction, &from, &to, &start_cell);
// printf("\n i=%d interval = [%d,%d] ", i, from, to);
int j;
for(j=from;j<=to;j++) {
if(!laser_ref->alpha_valid[j]) continue;
if(j % interval) continue;
double theta = angleDiff(laser_ref->alpha[j], laser_sens->alpha[i]);
double theta_diff = angleDiff(theta,x0[2]);
if( fabs(theta_diff) > deg2rad(max_angular_correction_deg) )
continue;
theta = x0[2] + theta_diff; // otherwise problems near +- PI
const double * p_j = laser_ref->points[j].p;
double c = cos(theta); double s = sin(theta);
double t_x = p_j[0] - (c*p_i[0]-s*p_i[1]);
double t_y = p_j[1] - (s*p_i[0]+c*p_i[1]);
double t_dist = sqrt( square(t_x-x0[0]) + square(t_y-x0[1]) );
if(t_dist > max_linear_correction)
continue;
/*double weight = 1/(laser_sens->cov_alpha[i]+laser_ref->cov_alpha[j]);*/
double weight = 1;
gsl_histogram_accumulate(hist, theta, weight);
gsl_histogram_accumulate(hist, theta+2*M_PI, weight); /* be robust */
gsl_histogram_accumulate(hist, theta-2*M_PI, weight);
count ++;
}
}
*num_correspondences = count;
sm_debug(" correspondences = %d\n",count);
}
void ght_one_shot(LDP laser_ref, LDP laser_sens,
const double*x0, double max_linear_correction,
double max_angular_correction_deg, int interval, double*x, int*num_correspondences)
{
/** Compute laser_sens's points in laser_ref's coordinates by roto-translating by x0 */
ld_compute_world_coords(laser_sens, x0);
double L[3][3] = {{0,0,0},{0,0,0},{0,0,0}};
double z[3] = {0,0,0};
int count = 0;
int i;
for(i=0;i<laser_sens->nrays;i++) {
if(!laser_sens->alpha_valid[i]) continue;
if(i % interval) continue;
const double * p_i = laser_sens->points_w[i].p;
const double * p_i_w = laser_sens->points_w[i].p;
int from; int to; int start_cell;
possible_interval(p_i_w, laser_ref, max_angular_correction_deg,
max_linear_correction, &from, &to, &start_cell);
// from = 0; to = laser_ref->nrays-1;
int j;
for(j=from;j<=to;j++) {
if(j % interval) continue;
if(!laser_ref->alpha_valid[j]) continue;
double theta = angleDiff(laser_ref->alpha[j], laser_sens->alpha[i]);
double theta_diff = angleDiff(theta,x0[2]);
if( fabs(theta_diff) > deg2rad(max_angular_correction_deg) )
continue;
theta = x0[2] + theta_diff; // otherwise problems near +- PI
const double * p_j = laser_ref->points[j].p;
double c = cos(theta); double s = sin(theta);
double t_x = p_j[0] - (c*p_i[0]-s*p_i[1]);
double t_y = p_j[1] - (s*p_i[0]+c*p_i[1]);
double t_dist = sqrt( square(t_x-x0[0]) + square(t_y-x0[1]) );
if(t_dist > max_linear_correction)
continue;
/*double weight = 1/(laser_sens->cov_alpha[i]+laser_ref->cov_alpha[j]);
double weight = exp( -square(t_dist) - 5 * square(theta-x0[2]) );*/
double weight = 1;
double alpha = laser_ref->alpha[j];
double ca = cos(alpha); double sa=sin(alpha);
// printf("%d ", (int) rad2deg(theta));
/* printf("valid %d alpha %f weight %f t_x %f t_y %f\n",
laser_ref->alpha_valid[j],alpha,weight,
t_x, t_y); */
z[0] += weight*(ca*ca*t_x + sa*ca*t_y);
z[1] += weight*(sa*ca*t_x + sa*sa*t_y);
z[2] += weight*theta;
L[0][0] += weight* ca * ca;
L[0][1] += weight* sa * ca;
L[1][0] += weight* sa * ca;
L[1][1] += weight* sa * sa;
L[2][2] += weight;
count += 1;
}
}
*num_correspondences = count;
if(1) {
double weight = 0.5 * count;
z[0] += x0[0] * weight;
z[1] += x0[1] * weight;
L[0][0] += weight;
L[0][1] += 0;
L[1][0] += 0;
L[1][1] += weight;
}
egsl_push();
val eL = egsl_alloc(3,3);
size_t a,b;
for(a=0;a<3;a++)
for(b=0;b<3;b++)
*egsl_atmp(eL,a,b) = L[a][b];
/* egsl_print("eL", eL);*/
val ez = egsl_vFa(3,z);
val ex = m(inv(eL), ez);
egsl_v2a(ex, x);
/* egsl_print("eL", eL);
egsl_print("ez", ez);
egsl_print("ex", ex); */
egsl_pop();
// sm_debug("gpm: second step: theta = %f %f / %d = %f \n", rad2deg(x[2]), rad2deg(z[2]), count, rad2deg(z[2]) / count);
sm_debug("gpm: second step: found %d correspondences\n",count);
}
| {
"alphanum_fraction": 0.6689510977,
"avg_line_length": 29.9965156794,
"ext": "c",
"hexsha": "cf88254a8206f7100fcbd0a22f1dd5ba5f89584f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alecone/ROS_project",
"max_forks_repo_path": "src/csm/sm/csm/gpm/gpm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "alecone/ROS_project",
"max_issues_repo_path": "src/csm/sm/csm/gpm/gpm.c",
"max_line_length": 122,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alecone/ROS_project",
"max_stars_repo_path": "src/csm/sm/csm/gpm/gpm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2751,
"size": 8609
} |
/*
Example usage of MIXMAX with GSL
* Copyright Konstantin Savvidy.
*
* Free to use, academic or commercial. Do not redistribute without permission.
*
* G.K.Savvidy and N.G.Ter-Arutyunian,
* On the Monte Carlo simulation of physical systems,
* J.Comput.Phys. 97, 566 (1991);
* Preprint EPI-865-16-86, Yerevan, Jan. 1986
*
* K.Savvidy
* The MIXMAX random number generator
* Comp. Phys. Commun. 196 (2015), pp 161–165
* http://dx.doi.org/10.1016/j.cpc.2015.06.003
*
*/
// cc -std=c99 -O3 -funroll-loops -Wall -I /usr/local/include/ driver_gsl.c mixmax.o -L/usr/local/lib -DHOOKUP_GSL=1 -o gsl -lgsl
// make gsl; GSL_RNG_SEED=123 GSL_RNG_TYPE=MIXMAX ./gsl
#include <stdio.h>
#include "mixmax.h"
#include <gsl/gsl_rng.h>
#include <gsl/gsl_version.h>
int
main (void)
{
const gsl_rng_type * T;
gsl_rng * r;
unsigned long int seed = 0;
int i, n = 10;
// gsl_rng_env_setup();
// gsl_rng_types_setup ();
T = gsl_rng_mixmax;
const char *p = getenv ("GSL_RNG_SEED");
if (p)
{
seed = strtoul (p, 0, 0);
fprintf (stderr, "GSL_RNG_SEED=%lu\n", seed);
};
gsl_rng_default_seed = seed;
r = gsl_rng_alloc (T);
printf("generator type: %s\n", gsl_rng_name (r));
printf("seed = %lu\n", gsl_rng_default_seed);
printf("gsl_version=%s\n", gsl_version);
for (i = 0; i < n; i++)
{
double u = gsl_rng_uniform (r);
printf ("%.16F\n", u);
}
gsl_rng_free (r);
return 0;
}
| {
"alphanum_fraction": 0.6242424242,
"avg_line_length": 22.1641791045,
"ext": "c",
"hexsha": "ff5df2301deb994e6f1172cff6ff8935e0438559",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "8f9e7af78f010f44fda81a4ab064e32421a205f9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ruicamposcolabpt/MontyCarlo",
"max_forks_repo_path": "MontyCarlo/external/mixmax_release_200final/driver_gsl.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8f9e7af78f010f44fda81a4ab064e32421a205f9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ruicamposcolabpt/MontyCarlo",
"max_issues_repo_path": "MontyCarlo/external/mixmax_release_200final/driver_gsl.c",
"max_line_length": 130,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8f9e7af78f010f44fda81a4ab064e32421a205f9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ruicamposcolabpt/MontyCarlo",
"max_stars_repo_path": "MontyCarlo/external/mixmax_release_200final/driver_gsl.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 501,
"size": 1485
} |
/************************************************************************
Dataset.h.h - Copyright marcello
Here you can write a license for your code, some comments or any other
information you want to have in your generated code. To to this simply
configure the "headings" directory in uml to point to a directory
where you have your heading files.
or you can just replace the contents of this file with your own.
If you want to do this, this file is located at
/usr/share/apps/umbrello/headings/heading.h
-->Code Generators searches for heading files based on the file extension
i.e. it will look for a file name ending in ".h" to include in C++ header
files, and for a file name ending in ".java" to include in all generated
java code.
If you name the file "heading.<extension>", Code Generator will always
choose this file even if there are other files with the same extension in the
directory. If you name the file something else, it must be the only one with that
extension in the directory to guarantee that Code Generator will choose it.
you can use variables in your heading files which are replaced at generation
time. possible variables are : author, date, time, filename and filepath.
just write %variable_name%
This file was generated on Sat Nov 10 2007 at 15:05:38
The original location of this file is /home/marcello/Projects/fitted/Developing/Dataset.h
**************************************************************************/
#ifndef DATASET_H
#define DATASET_H
#include <vector>
#include <set>
#include <map>
//#include <gsl/gsl_matrix.h>
#include "Sample.h"
//<< Sam
namespace PoliFitted
{
typedef enum
{
OVERWRITE,
APPEND
} ModalityType;
typedef enum
{
EUCLIDEAN,
MANHATTAN,
MAHALANOBIS
} MetricType;
/**
* Represents an in-memory cache of numeric data.
* A Dataset is nothing more than what its name implies: a set of data.
* Since each data is a sample, the dataset can be split into input and
* output data. In contrast with the Sample class, the
* dataset stores the information related to the dimension of the input and output
* tuples.
*
* Advanced features include iterator, random subsampling, normalization,
* statistical data, import and export.
*
* @brief In-memory cache of numeric data.
*/
class Dataset: public vector<Sample*>
{
public:
// Constructors/Destructors
//
/**
* Empty Constructor
*/
Dataset(unsigned int input_size = 1, unsigned int output_size = 1);
/**
* Empty Destructor
*/
virtual ~Dataset();
/**
* Destroys the content of the dataset but not the dataset itself.
*
* The input data of each sample are destroyed only if \a clear_input
* is set to true.
*
* @brief Clear tuple
* @param clear_input If true the input data are destrayed, false otherwise.
*/
void Clear(bool clear_input = false);
/**
* @brief Set input data dimension
* @param size The dimension of the input data.
*/
void SetInputSize(unsigned int size);
/**
* @brief Set output data dimension
* @param size The dimension of the output data.
*/
void SetOutputSize(unsigned int size);
/**
* @brief Return the input dimension.
* @return The dimension of the input component of each sample.
*/
unsigned int GetInputSize();
/**
* @brief Return the output dimension.
* @return The dimension of the output component of each sample.
*/
unsigned int GetOutputSize();
/**
* Adds a new element at the end of the dataset, after its current last element.
* This effectively increases the container size by one, which causes an automatic
* allocation of a new samples initialized with the given input and output tuples.
*
* @brief Add element at the end.
* @param input The input tuple to be added.
* @param output The output tuple to be added.
*/
void AddSample(Tuple* input, Tuple* output);
/**
* Returns a pointer to a newly created memory array storing
* the elements of the dataset.
* Data are stored linearly in the new array \f$A\f$. For any
* sample in the dataset, input elements are stored before
* output elements. As a consequence the dimension of the
* array \f$A\f$ is \f$n_{el} * (input_dim + output_dim)\f$.
* \f[ A = {input_i(1),\dots,input_i(m), output_i(1),\dots,output_i(n)}_{i=0}^{n_{el}-1}\f]
*
* @brief Get a copy of the elements.
* @return A reference to the first element of an array storing
* the dataset elements
*/
//double* GetMatrix();
/**
* Returns a pointer to a newly created GSL matrix storing
* the elements of the dataset. Each row represents a sample
* of the dataset. For any
* sample in the dataset, input elements are stored before
* output elements. As a consequence the dimension of the
* array \f$A\f$ is \f$n_{el} \times (input_dim + output_dim)\f$.
* The element M(i,j) corresponds to the i-th sample of the dataset,
* if j is less then input_dimension corresponds to the j-th element
* of the input tuple. If j is greater or equal than the input_dimension,
* M(i,j) corresponds to the (j-input_dimension) element of the output
* tuple.
*
* @brief Get a copy of the elements.
* @return A GSL matrix storing the dataset elements
*/
//gsl_matrix* GetGSLMatrix();
/**
*
*/
//gsl_matrix* GetCovarianceMatrix();
/**
* Clone the current instance filling the new dataset with
* a clone of each sample. This function performs a deep copy.
*
* @brief Clone object
* @return A newly created dataset.
*
* @see Sample::Clone
*/
Dataset* Clone();
/**
* @brief Resize the output tuple of each sample
* @param new_size the new size of the output tuple
*/
void ResizeOutput(unsigned int new_size);
/**
*
*/
Dataset* GetReducedDataset(unsigned int size, bool random = false);
/**
*
*/
Dataset* GetReducedDataset(float proportion, bool random = false);
/**
*
*/
void GetTrainAndTestDataset(unsigned int num_partitions, unsigned int partition,
Dataset* train_ds, Dataset* test_ds);
/**
*
*/
vector<Dataset*> SplitDataset(unsigned int parts);
/**
*
*/
map<float, Dataset*> SplitByAttribute(unsigned int attribute);
/**
*
*/
Dataset* ExtractNewDataset(set<unsigned int> inputs, set<unsigned int> outputs);
/**
*
*/
Sample* GetNearestNeighbor(Tuple& input, MetricType metric = EUCLIDEAN);
/**
*
*/
void Save(string filename, ModalityType modality = OVERWRITE);
/**
*
*/
void Load(string filename);
/**
*
*/
Dataset* NormalizeMinMax(vector<pair<float, float> >& input_parameters,
vector<pair<float, float> >& output_parameters);
/**
*
*/
Dataset* NormalizeOutputMinMax(vector<pair<float, float> >& output_parameters);
/**
* @brief Mean of the first output element.
* @return The mean value of the first output element.
*/
float Mean();
/**
* @brief Variance of the first output element.
* @return The variance value of the first output element.
*/
float Variance();
/**
* Insert a formatted representation of the dataset into the given output stream.
*
* @brief Insert formatted output
* @param out Output stream object where characters are inserted.
* @param ds Dataset to be printed out
* @return The reference to the stream it receives
*/
friend ofstream& operator<<(ofstream& out, PoliFitted::Dataset& ds);
/**
* Extract formatted input from the stream and fill the dataset
* accordingly to that information.
*
* @brief Extract formatted input
* @param in Input stream object from which characters are extracted.
* @param ds where the extracted information are stored.
* @return The reference to the stream it receives
*/
friend ifstream& operator>>(ifstream& in, PoliFitted::Dataset& ds);
protected:
private:
unsigned int mInputSize;
unsigned int mOutputSize;
float mMean;
float mVariance;
/**
* @brief Compute mean and variance of the first output element.
*/
void ComputeMeanVariance();
};
inline void Dataset::SetInputSize(unsigned int size)
{
mInputSize = size;
}
inline void Dataset::SetOutputSize(unsigned int size)
{
mOutputSize = size;
}
inline unsigned int Dataset::GetInputSize()
{
return mInputSize;
}
inline unsigned int Dataset::GetOutputSize()
{
return mOutputSize;
}
inline void Dataset::AddSample(Tuple* input, Tuple* output)
{
push_back(new Sample(input, output));
}
inline void Dataset::Save(string filename, ModalityType modality)
{
ofstream log_file;
if (modality == OVERWRITE)
{
log_file.open(filename.c_str(), ios::out);
}
else
{
log_file.open(filename.c_str(), ios::out | ios::app);
}
if (log_file.is_open())
{
log_file << *(this);
}
log_file.close();
}
inline void Dataset::Load(string filename)
{
ifstream log_file;
log_file.open(filename.c_str(), ios::in);
log_file >> *(this);
log_file.close();
}
}
#endif // DATASET_H
| {
"alphanum_fraction": 0.6517153207,
"avg_line_length": 27.2057971014,
"ext": "h",
"hexsha": "dff57ca3f643ebed7a49825c098d15bbd04fe0fe",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "akangasr/sdirl",
"max_forks_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Dataset.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "akangasr/sdirl",
"max_issues_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Dataset.h",
"max_line_length": 95,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "akangasr/sdirl",
"max_stars_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Dataset.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2189,
"size": 9386
} |
/*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: lymastee@hotmail.com
*
* This file is part of the gslib project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#ifndef dvt_31727ef2_2dfa_4e64_b93d_deab9c280036_h
#define dvt_31727ef2_2dfa_4e64_b93d_deab9c280036_h
#include <gslib/config.h>
#include <gslib/type.h>
#include <gslib/std.h>
__gslib_begin__
template<class _targetfn>
inline uint method_address(_targetfn fn)
{
uint r;
memcpy(&r, &fn, sizeof(r));
return r;
}
extern uint dsm_get_address(uint addr, uint pthis);
extern void dvt_recover_vtable(void* pthis, void* ovt, int vtsize);
class dvt_bridge_code;
template<class _cls>
class vtable_ops:
public _cls
{
public:
typedef vtable_ops<_cls> myref;
public:
myref() {}
template<class _arg1>
myref(_arg1 a1): _cls(a1) {}
template<class _arg1, class _arg2>
myref(_arg1 a1, _arg2 a2): _cls(a1, a2) {}
template<class _arg1, class _arg2, class _arg3>
myref(_arg1 a1, _arg2 a2, _arg3 a3): _cls(a1, a2, a3) {}
virtual void end_of_vtable() { __asm { nop } } /* add some real stuff in this function to prevent optimization in release. */
public:
int get_virtual_method_index(uint m) const
{
uint mv = dsm_final_address(m);
uint eov = dsm_final_address(method_address(&myref::end_of_vtable));
uint* ovt = *(uint**)this;
int i = 0;
for(;; ++ i) {
uint cv = dsm_final_address(ovt[i]);
if(cv == mv)
return i;
if(cv == eov) {
assert(!"get index failed.");
return i;
}
}
return -1;
}
int size_of_vtable() const
{
return get_virtual_method_index(
dsm_final_address(method_address(&myref::end_of_vtable))
);
}
void* create_per_instance_vtable(_cls* p, dvt_bridge_code& bridges)
{
assert(p);
int count = size_of_vtable();
byte* ovt = *(byte**)p;
void** pvt = (void**)VirtualAlloc(nullptr, count * 4, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
assert(pvt);
bridges.install(ovt, count);
for(int i = 0; i < count; i ++)
pvt[i] = bridges.get_bridge(i);
memcpy(p, &pvt, 4);
DWORD oldpro;
VirtualProtect(pvt, count * 4, PAGE_EXECUTE_READ, &oldpro);
return ovt;
}
void destroy_per_instance_vtable(_cls* p, void* ovt)
{
assert(p && ovt);
dvt_recover_vtable(p, ovt, size_of_vtable());
}
template<class _func>
uint replace_vtable_method(_cls* p, int index, _func func)
{
uint* vt = *(uint**)p;
vt += index;
uint r = *vt;
DWORD oldpro;
VirtualProtect(vt, 4, PAGE_EXECUTE_READWRITE, &oldpro);
*vt = (uint)func;
VirtualProtect(vt, 4, oldpro, &oldpro);
return r;
}
private:
uint dsm_final_address(uint addr) const
{
return dsm_get_address(
addr, (uint)((void*)this)
);
}
};
class dvt_detour_code
{
typedef unsigned long ulong;
public:
enum detour_type
{
detour_notify,
detour_reflect,
};
public:
dvt_detour_code(detour_type dty, int argsize);
~dvt_detour_code();
void finalize(uint old_func, uint host, uint action);
uint get_code_address() const { return (uint)_ptr; }
private:
detour_type _type;
int _argsize;
byte* _ptr;
int _len;
ulong _oldpro;
};
/*
* The two kind of DVT callings:
* 1.notify: the original function would be called first, and then the notify function will be called after, you MUST specify the size of the argument table.
* 2.reflect: the original function would NOT be called, simply jump to the reflect function, and the argument table of the reflect function SHOULD be exactly the same with the original function.
*/
#define connect_typed_detour(targettype, target, trigger, host, action, dty, argsize) { \
auto& vo = vtable_ops<targettype>(nullptr); \
(target)->ensure_dvt_available<targettype>(); \
auto* detour = (target)->add_detour(dty, argsize); \
assert(detour); \
uint old_func = vo.replace_vtable_method(target, vo.get_virtual_method_index(method_address(trigger)), detour->get_code_address()); \
detour->finalize(old_func, (uint)host, method_address(action)); \
}
#define connect_typed_notify(targettype, target, trigger, host, action, argsize) \
connect_typed_detour(targettype, target, trigger, host, action, dvt_detour_code::detour_notify, argsize)
#define connect_notify(target, trigger, host, action, argsize) \
connect_typed_notify(std::remove_reference_t<decltype(*target)>, target, trigger, host, action, argsize)
#define connect_typed_reflect(targettype, target, trigger, host, action) \
connect_typed_detour(targettype, target, trigger, host, action, dvt_detour_code::detour_reflect, 0)
#define connect_reflect(target, trigger, host, action) \
connect_typed_reflect(std::remove_reference_t<decltype(*target)>, target, trigger, host, action)
/*
* Bridge to jump to the original vtable
* The reason why we can't simply copy the original vtable was that it's hard to determine how long the vtable actually was.
* If the target class had a complex derivations, missing a part of the vtable would make you unable to call __super::function.
*/
class dvt_bridge_code
{
public:
dvt_bridge_code();
~dvt_bridge_code();
void install(void* vt, int count);
void* get_bridge(int index) const;
protected:
byte* _bridges;
int _bridge_size; /* in bytes */
int _jt_stride; /* jump table stride in bytes */
};
class dvt_holder
{
public:
typedef vector<dvt_detour_code*> detour_list;
public:
dvt_holder();
virtual ~dvt_holder();
private:
void* _backvt;
int _backvtsize;
void* _switchvt;
detour_list _detours;
bool _delete_later;
dvt_bridge_code _bridges;
public:
template<class _cls>
void ensure_dvt_available()
{
if(_backvt)
return;
auto& vo = vtable_ops<_cls>(nullptr);
_backvtsize = vo.size_of_vtable();
_backvt = vo.create_per_instance_vtable(static_cast<_cls*>(this), _bridges);
}
dvt_detour_code* add_detour(dvt_detour_code::detour_type dty, int argsize);
dvt_holder* switch_to_ovt(); /* switch to original vtable */
dvt_holder* switch_to_dvt();
/*
* In case the holder would be tagged more than once by the garbage collector, the cause might be
* a message re-entrant of the msg callback function. So here we tag it.
*/
void set_delete_later() { _delete_later = true; }
bool is_delete_later() const { return _delete_later; }
};
class dvt_collector
{
public:
typedef vector<dvt_holder*> holder_list;
private:
holder_list _holders;
dvt_collector() {}
public:
static dvt_collector* get_singleton_ptr()
{
static dvt_collector inst;
return &inst;
}
~dvt_collector() { cleanup(); }
bool set_delete_later(dvt_holder* holder);
void cleanup();
};
__gslib_end__
#endif
| {
"alphanum_fraction": 0.6432312886,
"avg_line_length": 32.5416666667,
"ext": "h",
"hexsha": "a12943dacf778938ce4772f948530f78eba58db5",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/gslib/dvt.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/gslib/dvt.h",
"max_line_length": 198,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/gslib/dvt.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z",
"num_tokens": 2163,
"size": 8591
} |
/* rng/rng-dump.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
int
main (int argc, char **argv)
{
int i, j ;
char buffer[1024 * 4] ;
gsl_rng * r ;
gsl_rng_env_setup () ;
r = gsl_rng_alloc (gsl_rng_default) ;
if (argc != 1)
{
printf ("Usage: diehard\n");
printf ("Output 3 million numbers in binary format,"
"suitable for testing with DIEHARD\n");
exit (0);
}
argv = 0 ; /* prevent warning about unused argument */
for (i = 0; i < 3000 ; i++)
{
int status ;
for (j = 0; j < 1024; j++)
{
unsigned long int u = gsl_rng_get (r) ;
buffer[4 * j + 0] = u & 0xFF ;
u >>= 8;
buffer[4 * j + 1] = u & 0xFF ;
u >>= 8;
buffer[4 * j + 2] = u & 0xFF ;
u >>= 8;
buffer[4 * j + 3] = u & 0xFF ;
}
status = fwrite(buffer, 4 * sizeof(char), 1024, stdout) ;
if (status != 1024)
{
perror("fwrite") ;
exit(EXIT_FAILURE) ;
}
}
return 0;
}
| {
"alphanum_fraction": 0.5831148401,
"avg_line_length": 25.7702702703,
"ext": "c",
"hexsha": "801df44dc24bd6bdafe6e1785ae66069f99646c2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/rng/rng-dump.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/rng/rng-dump.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/rng/rng-dump.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z",
"num_tokens": 551,
"size": 1907
} |
/**
*
* @file core_slarfb_gemm.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Azzam Haidar
* @date 2010-11-15
* @generated s Tue Jan 7 11:44:49 2014
*
**/
#include <cblas.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_float
*
* CORE_slarfb_gemm applies a complex block reflector H or its transpose H'
* to a complex M-by-N matrix C, from either the left or the right.
* this kernel is similar to the lapack slarfb but it do a full gemm on the
* triangular Vs assuming that the upper part of Vs is zero and ones are on
* the diagonal. It is also based on the fact that a gemm on a small block of
* k reflectors is faster than a trmm on the triangular (k,k) + gemm below.
*
* NOTE THAT:
* Only Columnwise/Forward cases are treated here.
*
*******************************************************************************
*
* @param[in] side
* @arg PlasmaLeft : apply Q or Q**T from the Left;
* @arg PlasmaRight : apply Q or Q**T from the Right.
*
* @param[in] trans
* @arg PlasmaNoTrans : No transpose, apply Q;
* @arg PlasmaTrans : ConjTranspose, apply Q**T.
*
* @param[in] direct
* Indicates how H is formed from a product of elementary
* reflectors
* @arg PlasmaForward : H = H(1) H(2) . . . H(k) (Forward)
* @arg PlasmaBackward : H = H(k) . . . H(2) H(1) (Backward)
*
* @param[in] storev
* Indicates how the vectors which define the elementary
* reflectors are stored:
* @arg PlasmaColumnwise
* @arg PlasmaRowwise
*
* @param[in] M
* The number of rows of the matrix C.
*
* @param[in] N
* The number of columns of the matrix C.
*
* @param[in] K
* The order of the matrix T (= the number of elementary
* reflectors whose product defines the block reflector).
*
* @param[in] V
* COMPLEX*16 array, dimension
* (LDV,K) if storev = 'C'
* (LDV,M) if storev = 'R' and side = 'L'
* (LDV,N) if storev = 'R' and side = 'R'
* The matrix V. See further details.
*
* @param[in] LDV
* The leading dimension of the array V.
* If storev = 'C' and side = 'L', LDV >= max(1,M);
* if storev = 'C' and side = 'R', LDV >= max(1,N);
* if storev = 'R', LDV >= K.
*
* @param[in] T
* The triangular K-by-K matrix T in the representation of the
* block reflector.
* T is upper triangular by block (economic storage);
* The rest of the array is not referenced.
*
* @param[in] LDT
* The leading dimension of the array T. LDT >= K.
*
* @param[in,out] C
* COMPLEX*16 array, dimension (LDC,N)
* On entry, the M-by-N matrix C.
* On exit, C is overwritten by H*C or H'*C or C*H or C*H'.
*
* @param[in] LDC
* The leading dimension of the array C. LDC >= max(1,M).
*
* @param[in,out] WORK
* (workspace) COMPLEX*16 array, dimension (LDWORK,K).
*
* @param[in] LDWORK
* The dimension of the array WORK.
* If side = PlasmaLeft, LDWORK >= max(1,N);
* if side = PlasmaRight, LDWORK >= max(1,M).
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_slarfb_gemm = PCORE_slarfb_gemm
#define CORE_slarfb_gemm PCORE_slarfb_gemm
#endif
int CORE_slarfb_gemm(PLASMA_enum side, PLASMA_enum trans, int direct, int storev,
int M, int N, int K,
const float *V, int LDV,
const float *T, int LDT,
float *C, int LDC,
float *WORK, int LDWORK)
{
static float zzero = 0.0;
static float zone = 1.0;
static float mzone = -1.0;
/* Check input arguments */
if ((side != PlasmaLeft) && (side != PlasmaRight)) {
coreblas_error(1, "Illegal value of side");
return -1;
}
if ((trans != PlasmaNoTrans) && (trans != PlasmaTrans)) {
coreblas_error(2, "Illegal value of trans");
return -2;
}
if ((direct != PlasmaForward) && (direct != PlasmaBackward)) {
coreblas_error(3, "Illegal value of direct");
return -3;
}
if ((storev != PlasmaColumnwise) && (storev != PlasmaRowwise)) {
coreblas_error(4, "Illegal value of direct");
return -4;
}
if (M < 0) {
coreblas_error(5, "Illegal value of M");
return -5;
}
if (N < 0) {
coreblas_error(6, "Illegal value of N");
return -6;
}
if (K < 0) {
coreblas_error(7, "Illegal value of K");
return -7;
}
/* Quick return */
if ((M == 0) || (N == 0) || (K == 0) )
return PLASMA_SUCCESS;
/* For Left case, switch the trans. noswitch for right case */
if( side == PlasmaLeft){
if ( trans == PlasmaNoTrans) {
trans = PlasmaTrans;
}
else {
trans = PlasmaNoTrans;
}
}
/* main code */
if (storev == PlasmaColumnwise )
{
if ( direct == PlasmaForward )
{
/*
* Let V = ( V1 ) (first K rows are unit Lower triangular)
* ( V2 )
*/
if ( side == PlasmaLeft )
{
/*
* Columnwise / Forward / Left
*/
/*
* Form H * C or H' * C where C = ( C1 )
* ( C2 )
*
* W := C' * V (stored in WORK)
*/
cblas_sgemm(
CblasColMajor, CblasTrans, CblasNoTrans,
N, K, M,
(zone), C, LDC,
V, LDV,
(zzero), WORK, LDWORK );
/*
* W := W * T' or W * T
*/
cblas_strmm(
CblasColMajor, CblasRight, CblasUpper,
(CBLAS_TRANSPOSE)trans, CblasNonUnit, N, K,
(zone), T, LDT, WORK, LDWORK );
/*
* C := C - V * W'
*/
cblas_sgemm(
CblasColMajor, CblasNoTrans, CblasTrans,
M, N, K,
(mzone), V, LDV,
WORK, LDWORK,
(zone), C, LDC);
}
else {
/*
* Columnwise / Forward / Right
*/
/*
* Form C * H or C * H' where C = ( C1 C2 )
* W := C * V
*/
cblas_sgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans,
M, K, N,
(zone), C, LDC,
V, LDV,
(zzero), WORK, LDWORK);
/*
* W := W * T or W * T'
*/
cblas_strmm(
CblasColMajor, CblasRight, CblasUpper,
(CBLAS_TRANSPOSE)trans, CblasNonUnit, M, K,
(zone), T, LDT, WORK, LDWORK );
/*
* C := C - W * V'
*/
cblas_sgemm(
CblasColMajor, CblasNoTrans, CblasTrans,
M, N, K,
(mzone), WORK, LDWORK,
V, LDV,
(zone), C, LDC);
}
}
else {
/*
* Columnwise / Backward / Left or Right
*/
coreblas_error(3, "Not implemented (ColMajor / Backward / Left or Right)");
return PLASMA_ERR_NOT_SUPPORTED;
}
}
else {
if (direct == PlasmaForward) {
/*
* Rowwise / Forward / Left or Right
*/
coreblas_error(3, "Not implemented (RowMajor / Backward / Left or Right)");
return PLASMA_ERR_NOT_SUPPORTED;
}
else {
/*
* Rowwise / Backward / Left or Right
*/
coreblas_error(3, "Not implemented (RowMajor / Backward / Left or Right)");
return PLASMA_ERR_NOT_SUPPORTED;
}
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.4589509692,
"avg_line_length": 32.723880597,
"ext": "c",
"hexsha": "3e2ad6b383358873a46965fdaff7362366a3cd06",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas/core_slarfb_gemm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_slarfb_gemm.c",
"max_line_length": 87,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_slarfb_gemm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2234,
"size": 8770
} |
#include <math.h>
#include <gsl/gsl_math.h>
#include <egsl/egsl_macros.h>
#include "icp.h"
#include "../csm_all.h"
val compute_C_k(val p_j1, val p_j2);
val dC_drho(val p1, val p2);
void compute_covariance_exact(
LDP laser_ref, LDP laser_sens, const gsl_vector*x,
val *cov0_x, val *dx_dy1, val *dx_dy2)
{
egsl_push_named("compute_covariance_exact");
val d2J_dxdy1 = zeros(3,(size_t)laser_ref ->nrays);
val d2J_dxdy2 = zeros(3,(size_t)laser_sens->nrays);
/* the three pieces of d2J_dx2 */
val d2J_dt2 = zeros(2,2);
val d2J_dt_dtheta = zeros(2,1);
val d2J_dtheta2 = zeros(1,1);
double theta = x->data[2];
val t = egsl_vFa(2,x->data);
int i;
for(i=0;i<laser_sens->nrays;i++) {
if(!ld_valid_corr(laser_sens,i)) continue;
egsl_push_named("compute_covariance_exact iteration");
int j1 = laser_sens->corr[i].j1;
int j2 = laser_sens->corr[i].j2;
val p_i = egsl_vFa(2, laser_sens->points[i].p);
val p_j1 = egsl_vFa(2, laser_ref ->points[j1].p);
val p_j2 = egsl_vFa(2, laser_ref ->points[j2].p);
/* v1 := rot(theta+M_PI/2)*p_i */
val v1 = m(rot(theta+M_PI/2), p_i);
/* v2 := (rot(theta)*p_i+t-p_j1) */
val v2 = sum3( m(rot(theta),p_i), t, minus(p_j1));
/* v3 := rot(theta)*v_i */
val v3 = vers(theta + laser_sens->theta[i]);
/* v4 := rot(theta+PI/2)*v_i; */
val v4 = vers(theta + laser_sens->theta[i] + M_PI/2);
val C_k = compute_C_k(p_j1, p_j2);
val d2J_dt2_k = sc(2.0, C_k);
val d2J_dt_dtheta_k = sc(2.0,m(C_k,v1));
val v_new = m(rot(theta+M_PI), p_i);
val d2J_dtheta2_k = sc(2.0, sum( m3(tr(v2),C_k, v_new), m3(tr(v1),C_k,v1)));
add_to(d2J_dt2, d2J_dt2_k);
add_to(d2J_dt_dtheta, d2J_dt_dtheta_k );
add_to(d2J_dtheta2, d2J_dtheta2_k);
/* for measurement rho_i in the second scan */
val d2Jk_dtdrho_i = sc(2.0, m(C_k,v3));
val d2Jk_dtheta_drho_i = sc(2.0, sum( m3(tr(v2),C_k,v4), m3(tr(v3),C_k,v1)));
add_to_col(d2J_dxdy2, (size_t)i, comp_col(d2Jk_dtdrho_i, d2Jk_dtheta_drho_i));
/* for measurements rho_j1, rho_j2 in the first scan */
val dC_drho_j1 = dC_drho(p_j1, p_j2);
val dC_drho_j2 = dC_drho(p_j2, p_j1);
val v_j1 = vers(laser_ref->theta[j1]);
val d2Jk_dt_drho_j1 = sum(sc(-2.0,m(C_k,v_j1)), sc(2.0,m(dC_drho_j1,v2)));
val d2Jk_dtheta_drho_j1 = sum( sc(-2.0, m3(tr(v_j1),C_k,v1)), m3(tr(v2),dC_drho_j1,v1));
add_to_col(d2J_dxdy1, (size_t)j1, comp_col(d2Jk_dt_drho_j1, d2Jk_dtheta_drho_j1));
/* for measurement rho_j2*/
val d2Jk_dt_drho_j2 = sc(2.0, m( dC_drho_j2,v2));
val d2Jk_dtheta_drho_j2 = sc(2.0, m3( tr(v2), dC_drho_j2, v1));
add_to_col(d2J_dxdy1, (size_t)j2, comp_col(d2Jk_dt_drho_j2, d2Jk_dtheta_drho_j2));
egsl_pop_named("compute_covariance_exact iteration");
}
/* composes matrix d2J_dx2 from the pieces*/
val d2J_dx2 = comp_col( comp_row( d2J_dt2 , d2J_dt_dtheta),
comp_row(tr(d2J_dt_dtheta), d2J_dtheta2));
val edx_dy1 = sc(-1.0, m(inv(d2J_dx2), d2J_dxdy1));
val edx_dy2 = sc(-1.0, m(inv(d2J_dx2), d2J_dxdy2));
val ecov0_x = sum(m(edx_dy1,tr(edx_dy1)),m(edx_dy2,tr(edx_dy2)) );
/* With the egsl_promote we save the matrix in the previous
context */
*cov0_x = egsl_promote(ecov0_x);
*dx_dy1 = egsl_promote(edx_dy1);
*dx_dy2 = egsl_promote(edx_dy2);
egsl_pop_named("compute_covariance_exact");
/* now edx_dy1 is not valid anymore, but *dx_dy1 is. */
}
val compute_C_k(val p_j1, val p_j2) {
val d = sub(p_j1, p_j2);
double alpha = M_PI/2 + atan2( atv(d,1), atv(d,0));
double c = cos(alpha); double s = sin(alpha);
double m[2*2] = {
c*c, c*s,
c*s, s*s
};
return egsl_vFda(2,2,m);
}
val dC_drho(val p1, val p2) {
double eps = 0.001;
val C_k = compute_C_k(p1, p2);
val p1b = sum(p1, sc(eps/egsl_norm(p1),p1));
val C_k_eps = compute_C_k(p1b,p2);
return sc(1/eps, sub(C_k_eps,C_k));
}
| {
"alphanum_fraction": 0.6578947368,
"avg_line_length": 29.7519379845,
"ext": "c",
"hexsha": "3d4db6447add915f705ddcedaccb954a4c5c4af1",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alecone/ROS_project",
"max_forks_repo_path": "src/csm/sm/csm/icp/icp_covariance.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "alecone/ROS_project",
"max_issues_repo_path": "src/csm/sm/csm/icp/icp_covariance.c",
"max_line_length": 90,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alecone/ROS_project",
"max_stars_repo_path": "src/csm/sm/csm/icp/icp_covariance.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1589,
"size": 3838
} |
/**
*/
#ifndef _CROSSDISP_UTILS_H
#define _CROSSDISP_UTILS_H
#include "spc_trace_functions.h"
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_statistics.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
#include <math.h>
#include "trace_conf.h"
/**
* Structure: drz_pars
* A description of an ellipse with a,b, theta.
*/
typedef struct
{
gsl_matrix *coeffs;
d_point offset;
px_point npixels;
}
drz_pars;
int
drizzle_distort(const gsl_vector * x, void *params, gsl_vector * f);
d_point
undistort_point(gsl_matrix *coeffs, const px_point pixmax,
d_point xy_image);
d_point
distort_point(gsl_matrix *coeffs, const px_point pixmax, d_point xy_image);
extern gsl_matrix *
get_crossdisp_matrix(char * filename, int sci_numext);
extern d_point
get_axis_scales(beam actbeam, gsl_matrix * drzcoeffs, px_point pixmax);
extern double
get_crossdisp_scale(trace_func *trace, d_point refpnt, gsl_matrix * drzcoeffs, px_point pixmax);
extern d_point
get_drz_position(d_point in_point, gsl_matrix * drzcoeffs, px_point pixmax);
extern d_point
get_drz_position_free(d_point in_point, gsl_matrix * drzcoeffs, px_point pix_in, px_point pix_out);
extern trace_func *
get_tracefunc_at(char *filename, d_point p);
extern double
evaln(double x, double y, gsl_matrix * drzcoeffs, int row);
extern double
devalndx(double x, double y, gsl_matrix * drzcoeffs, int row);
extern double
devalndy(double x, double y, gsl_matrix * drzcoeffs, int row);
extern gsl_matrix *
get_jacobian(int i, int j, gsl_matrix * drzcoeffs, int width, int height);
extern double
get_det_jacobian(int i, int j, gsl_matrix * drzcoeffs, int width, int height);
#endif
| {
"alphanum_fraction": 0.7601410935,
"avg_line_length": 23.301369863,
"ext": "h",
"hexsha": "743869465d71391dbce3575ca0a5276382a87877",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/crossdisp_utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/crossdisp_utils.h",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/crossdisp_utils.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 479,
"size": 1701
} |
#ifndef PYGSL_STATMODULE_H
#define PYGSL_STATMODULE_H 1
#include <pygsl/error_helpers.h>
#include <pygsl/block_helpers.h>
#include <gsl/gsl_statistics.h>
#include <Python.h>
/*
* This api will be only exported to the various statistics
* modules.
*/
static void **PyGSL_STATISTICS_API = NULL;
#define PyGSL_STATISTICS_d_A_NUM 0
#define PyGSL_STATISTICS_l_A_NUM 1
#define PyGSL_STATISTICS_d_Ad_NUM 2
#define PyGSL_STATISTICS_d_AA_NUM 3
#define PyGSL_STATISTICS_d_AAd_NUM 4
#define PyGSL_STATISTICS_d_AAdd_NUM 5
#define PyGSL_STATISTICS_d_Add_NUM 6
#define PyGSL_STATISTICS_ll_A_NUM 7
#define PyGSL_STATISTICS_d_A_PROTO (PyObject *self, PyObject *args, \
double (*pointer)(const void *, size_t, size_t),\
int array_type, int basis_type_size)
#define PyGSL_STATISTICS_l_A_PROTO (PyObject *self, PyObject *args, \
size_t (*pointer)(const void *, size_t, size_t), \
int array_type, int basis_type_size)
#define PyGSL_STATISTICS_d_Ad_PROTO (PyObject *self, PyObject *args, \
double (*pointer)(const void *, size_t, size_t, double), \
int array_type, int basis_type_size)
#define PyGSL_STATISTICS_d_AA_PROTO (PyObject *self, PyObject *args, \
double (*pointer)(const void *, size_t,const void *, size_t, size_t), \
int array_type, int basis_type_size)
#define PyGSL_STATISTICS_d_AAd_PROTO (PyObject *self, PyObject *args, \
double (*pointer)(const void *, size_t,const void *, size_t, size_t, double), \
int array_type, int basis_type_size)
#define PyGSL_STATISTICS_d_AAdd_PROTO (PyObject *self, PyObject *args, \
double (*pointer)(const void *, size_t,const void *, size_t, size_t, double, double), \
int array_type, int basis_type_size)
#define PyGSL_STATISTICS_d_Add_PROTO (PyObject *self, PyObject *args, \
double (*pointer)(const void *, size_t, size_t, double, double), \
int array_type, int basis_type_size)
#define PyGSL_STATISTICS_ll_A_PROTO (PyObject *self, PyObject *args, \
void (*pointer)(size_t *, size_t *, const void *, size_t, size_t), \
int array_type, int basis_type_size)
#if defined(PyGSL_STATISTICS_IMPORT_API)
extern PyObject * PyGSL_statistics_d_A PyGSL_STATISTICS_d_A_PROTO;
extern PyObject * PyGSL_statistics_l_A PyGSL_STATISTICS_l_A_PROTO;
extern PyObject * PyGSL_statistics_d_Ad PyGSL_STATISTICS_d_Ad_PROTO;
extern PyObject * PyGSL_statistics_d_AA PyGSL_STATISTICS_d_AA_PROTO;
extern PyObject * PyGSL_statistics_d_AAd PyGSL_STATISTICS_d_AAd_PROTO;
extern PyObject * PyGSL_statistics_d_AAdd PyGSL_STATISTICS_d_AAdd_PROTO;
extern PyObject * PyGSL_statistics_d_Add PyGSL_STATISTICS_d_Add_PROTO;
extern PyObject * PyGSL_statistics_ll_A PyGSL_STATISTICS_ll_A_PROTO;
#define PyGSL_statistics_d_A (*(PyObject* (*) PyGSL_STATISTICS_d_A_PROTO) PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_A_NUM])
#define PyGSL_statistics_l_A (*(PyObject* (*) PyGSL_STATISTICS_l_A_PROTO) PyGSL_STATISTICS_API[PyGSL_STATISTICS_l_A_NUM])
#define PyGSL_statistics_d_Ad (*(PyObject* (*) PyGSL_STATISTICS_d_Ad_PROTO) PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_Ad_NUM])
#define PyGSL_statistics_d_AA (*(PyObject* (*) PyGSL_STATISTICS_d_AA_PROTO) PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_AA_NUM])
#define PyGSL_statistics_d_AAd (*(PyObject* (*) PyGSL_STATISTICS_d_AAd_PROTO) PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_AAd_NUM])
#define PyGSL_statistics_d_AAdd (*(PyObject* (*) PyGSL_STATISTICS_d_AAdd_PROTO) PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_AAdd_NUM])
#define PyGSL_statistics_d_Add (*(PyObject* (*) PyGSL_STATISTICS_d_Add_PROTO) PyGSL_STATISTICS_API[PyGSL_STATISTICS_d_Add_NUM])
#define PyGSL_statistics_ll_A (*(PyObject* (*) PyGSL_STATISTICS_ll_A_PROTO) PyGSL_STATISTICS_API[PyGSL_STATISTICS_ll_A_NUM])
#else
static PyObject * PyGSL_statistics_d_A PyGSL_STATISTICS_d_A_PROTO;
static PyObject * PyGSL_statistics_l_A PyGSL_STATISTICS_l_A_PROTO;
static PyObject * PyGSL_statistics_d_Ad PyGSL_STATISTICS_d_Ad_PROTO;
static PyObject * PyGSL_statistics_d_AA PyGSL_STATISTICS_d_AA_PROTO;
static PyObject * PyGSL_statistics_d_AAd PyGSL_STATISTICS_d_AAd_PROTO;
static PyObject * PyGSL_statistics_d_AAdd PyGSL_STATISTICS_d_AAdd_PROTO;
static PyObject * PyGSL_statistics_d_Add PyGSL_STATISTICS_d_Add_PROTO;
static PyObject * PyGSL_statistics_ll_A PyGSL_STATISTICS_ll_A_PROTO;
#endif
#define import_pygsl_stats() \
{ \
PyObject *pygsl = NULL, *c_api = NULL, *md = NULL; \
if ( \
(pygsl = PyImport_ImportModule("pygsl.statistics._stat")) != NULL && \
(md = PyModule_GetDict(pygsl)) != NULL && \
(c_api = PyDict_GetItemString(md, "_PYGSL_STATISTICS_API")) != NULL && \
(PyCObject_Check(c_api)) \
) { \
PyGSL_STATISTICS_API = (void **)PyCObject_AsVoidPtr(c_api); \
} else { \
fprintf(stderr, "Could not init pygsl.statistics._stat!\n"); \
PyGSL_STATISTICS_API = NULL; \
} \
DEBUG_MESS(2, "PyGSL_API points to %p and PyGSL_STATISTICS_API points to %p\n", (void *) PyGSL_API, (void *) PyGSL_STATISTICS_API); \
}
#endif /* PYGSL_STATMODULE_H */
| {
"alphanum_fraction": 0.7484697781,
"avg_line_length": 46.6785714286,
"ext": "h",
"hexsha": "627ada69a3466cc5d4b5ef6ef1a2e00dc1df897e",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/statmodule.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/statmodule.h",
"max_line_length": 137,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/statmodule.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1471,
"size": 5228
} |
/**
*
* @file core_zsetvar.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mark Gates
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex64_t
*
* CORE_zsetvar sets a single variable, x := alpha.
*
*******************************************************************************
*
* @param[in] alpha
* Scalar to set x to, passed by pointer so it can depend on runtime value.
*
* @param[out] x
* On exit, x = alpha.
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zsetvar = PCORE_zsetvar
#define CORE_zsetvar PCORE_zsetvar
#endif
void CORE_zsetvar(const PLASMA_Complex64_t *alpha, PLASMA_Complex64_t *x)
{
*x = *alpha;
}
| {
"alphanum_fraction": 0.5177033493,
"avg_line_length": 25.487804878,
"ext": "c",
"hexsha": "471291394850fa47c1df598e28b5d84818a4ae3d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas/core_zsetvar.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_zsetvar.c",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_zsetvar.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 256,
"size": 1045
} |
#include <math.h>
#include <stdlib.h>
#if !defined(__APPLE__)
#include <malloc.h>
#endif
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <string.h>
#include <fftw3.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_sf_expint.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include "../cosmolike_core/theory/basics.c"
#include "../cosmolike_core/theory/structs.c"
#include "../cosmolike_core/theory/parameters.c"
#include "../cosmolike_core/emu17/P_cb/emu.c"
#include "../cosmolike_core/theory/recompute.c"
#include "../cosmolike_core/theory/cosmo3D.c"
#include "../cosmolike_core/theory/redshift_spline.c"
#include "../cosmolike_core/theory/halo.c"
#include "../cosmolike_core/theory/HOD.c"
#include "../cosmolike_core/theory/pt.c"
#include "../cosmolike_core/theory/cosmo2D_fourier.c"
#include "../cosmolike_core/theory/IA.c"
#include "../cosmolike_core/theory/cluster.c"
#include "../cosmolike_core/theory/BAO.c"
#include "../cosmolike_core/theory/external_prior.c"
#include "../cosmolike_core/theory/init_baryon.c"
#include "init_DESxPlanck.c"
// Naming convention:
// g = galaxy positions ("g" as in "galaxy")
// k = kappa CMB ("k" as in "kappa")
// s = kappa from source galaxies ("s" as in "shear")
// And alphabetical order
typedef double (*C_tomo_pointer)(double l, int n1, int n2);
void twopoint_via_hankel(double **xi, double *logthetamin, double *logthetamax, C_tomo_pointer C_tomo, int ni, int nj, int N_Bessel);
#include "../cosmolike_core/theory/CMBxLSS_fourier.c"
typedef struct input_nuisance_params_des {
double bias[10];
// double bias2[10];
double b_mag[10];
double source_z_bias[10];
double lens_z_bias[10];
double shear_m[10];
double A_ia;
double eta_ia;
// double bary[3];
} input_nuisance_params_des;
typedef struct input_cosmo_params_des {
double omega_m;
double sigma_8;
double n_s;
double w0;
double wa;
double omega_b;
double h0;
double MGSigma;
double MGmu;
} input_cosmo_params_des;
double C_shear_tomo_sys(double ell,int z1,int z2);
double C_cgl_tomo_sys(double ell_Cluster,int zl,int nN, int zs);
double C_gl_tomo_sys(double ell,int zl,int zs);
double C_ks_sys(double ell, int zs);
void set_data_shear(int Ncl, double *ell, double *data, int start);
void set_data_ggl(int Ncl, double *ell, double *data, int start);
void set_data_clustering(int Ncl, double *ell, double *data, int start);
void set_data_gk(double *ell, double *data, int start);
void set_data_ks(double *ell, double *data, int start);
void set_data_kk(double *ell, double *data, int start);
void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double BMAG1, double BMAG2, double BMAG3, double BMAG4,double BMAG5, double BMAG6, double BMAG7, double BMAG8, double BMAG9, double BMAG10, double SP1, double SP2, double SP3, double SP4, double SP5,double SP6, double SP7, double SP8, double SP9, double SP10, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double eta_ia);
double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double BMAG1, double BMAG2, double BMAG3, double BMAG4,double BMAG5, double BMAG6, double BMAG7, double BMAG8, double BMAG9, double BMAG10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double eta_ia);
void write_datavector_wrapper(char *details, input_cosmo_params_des ic, input_nuisance_params_des in);
double log_like_wrapper(input_cosmo_params_des ic, input_nuisance_params_des in);
int get_N_tomo_shear(void);
int get_N_tomo_clustering(void);
int get_N_ggl(void);
int get_N_ell(void);
int get_N_tomo_shear(void){
return tomo.shear_Nbin;
}
int get_N_tomo_clustering(void){
return tomo.clustering_Nbin;
}
int get_N_ggl(void){
return tomo.ggl_Npowerspectra;
}
int get_N_ell(void){
return like.Ncl;
}
double C_shear_tomo_sys(double ell, int z1, int z2)
{
double C;
// C= C_shear_tomo_nointerp(ell,z1,z2);
// if(like.IA==1) C+=C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2);
// if(like.IA!=1) C= C_shear_tomo_nointerp(ell,z1,z2);
// //if(like.IA==1) C= C_shear_shear_IA(ell,z1,z2);
// if(like.IA==1) C = C_shear_tomo_nointerp(ell,z1,z2)+C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2);
// if(like.IA==2) C += C_II_lin_nointerp(ell,z1,z2)+C_GI_lin_nointerp(ell,z1,z2);
if(like.IA==4){C = C_shear_shear_IA_tab(ell,z1,z2);}
else{printf("only support IA==4!\n");exit(1);}
if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[z1])*(1.0+nuisance.shear_calibration_m[z2]);
//printf("%le %d %d %le\n",ell,z1,z2,C_shear_tomo_nointerp(ell,z1,z2)+C_II_JB_nointerp(ell,z1,z2)+C_GI_JB_nointerp(ell,z1,z2));
return C;
}
double C_gl_tomo_sys(double ell,int zl,int zs)
{
double C;
// C=C_gl_tomo_nointerp(ell,zl,zs);
// if(like.IA==1) C += C_gI_nointerp(ell,zl,zs);
// if(like.IA!=1) C=C_gl_tomo_nointerp(ell,zl,zs);
// if(like.IA==1) C = C_ggl_IA(ell,zl,zs);
// if(like.IA==2) C += C_gI_lin_nointerp(ell,zl,zs);
if(like.IA==4){C = C_ggl_IA_tab(ell,zl,zs);}
else{printf("only support IA==4!\n");exit(1);}
if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);
return C;
}
double C_cgl_tomo_sys(double ell_Cluster, int zl,int nN, int zs)
{
double C;
C=C_cgl_tomo_nointerp(ell_Cluster,zl,nN,zs);
//if(like.IA!=0) C +=
if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);
return C;
}
double C_ks_sys(double ell, int zs)
{
double C;
C = C_ks(ell,zs);
if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);
return C;
}
void set_data_shear(int Ncl, double *ell, double *data, int start)
{
int i,z1,z2,nz;
double a;
for (nz = 0; nz < tomo.shear_Npowerspectra; nz++){
z1 = Z1(nz); z2 = Z2(nz);
for (i = 0; i < Ncl; i++){
// if (ell[i] < like.lmax_shear){ data[Ncl*nz+i] = C_shear_tomo_sys(ell[i],z1,z2);}
if (mask(Ncl*nz+i)){ data[Ncl*nz+i] = C_shear_tomo_sys(ell[i],z1,z2);}
else {data[Ncl*nz+i] = 0.;}
}
}
}
void set_data_ggl(int Ncl, double *ell, double *data, int start)
{
int i, zl,zs,nz;
for (nz = 0; nz < tomo.ggl_Npowerspectra; nz++){
zl = ZL(nz); zs = ZS(nz);
for (i = 0; i < Ncl; i++){
// if (test_kmax(ell[i],zl)){
if (mask(start+(Ncl*nz)+i)){
data[start+(Ncl*nz)+i] = C_gl_tomo_sys(ell[i],zl,zs);
}
else{
data[start+(Ncl*nz)+i] = 0.;
}
}
}
}
void set_data_clustering(int Ncl, double *ell, double *data, int start){
int i, nz;
for (nz = 0; nz < tomo.clustering_Npowerspectra; nz++){
//printf("%d %e %e\n",nz, gbias.b[nz][1],pf_photoz(gbias.b[nz][1],nz));
for (i = 0; i < Ncl; i++){
// if (test_kmax(ell[i],nz))
if (mask(start+(Ncl*nz)+i)) {
data[start+(Ncl*nz)+i] = C_cl_tomo_nointerp(ell[i],nz,nz);
}
else{data[start+(Ncl*nz)+i] = 0.;}
//printf("%d %d %le %le\n",nz,nz,ell[i],data[Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra + nz)+i]);
}
}
}
void set_data_gk(double *ell, double *data, int start)
{
for (int nz=0; nz<tomo.clustering_Nbin; nz++){
for (int i=0; i<like.Ncl; i++){
// if (ell[i]<like.lmax_kappacmb && test_kmax(ell[i],nz)){
if (mask(start+(like.Ncl*nz)+i)) {
data[start+(like.Ncl*nz)+i] = C_gk(ell[i],nz);
}
else{
data[start+(like.Ncl*nz)+i] = 0.;
}
}
}
}
void set_data_ks(double *ell, double *data, int start)
{
for (int nz=0; nz<tomo.shear_Nbin; nz++){
for (int i=0; i<like.Ncl; i++){
// if (ell[i]<like.lmax_kappacmb) {
if (mask(start+(like.Ncl*nz)+i)) {
data[start+(like.Ncl*nz)+i] = C_ks_sys(ell[i],nz);
}
else{
data[start+(like.Ncl*nz)+i] = 0.;
}
}
}
}
void set_data_kk(double *ell, double *data, int start)
{
for (int i=0; i<like.Ncl; i++){
// if (ell[i]<like.lmax_kappacmb){
if (mask(start+i)) {
data[start+i] = C_kk(ell[i]);
}
else{
data[start+i] = 0.;
}
}
}
int set_cosmology_params(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu)
{
cosmology.Omega_m=OMM;
cosmology.Omega_v= 1.0-cosmology.Omega_m;
cosmology.sigma_8=S8;
cosmology.n_spec= NS;
cosmology.w0=W0;
cosmology.wa=WA;
cosmology.omb=OMB;
cosmology.h0=H0;
cosmology.MGSigma=MGSigma;
cosmology.MGmu=MGmu;
if (cosmology.Omega_m < 0.05 || cosmology.Omega_m > 0.6) return 0;
if (cosmology.omb < 0.04 || cosmology.omb > 0.055) return 0;
if (cosmology.sigma_8 < 0.5 || cosmology.sigma_8 > 1.1) return 0;
if (cosmology.n_spec < 0.84 || cosmology.n_spec > 1.06) return 0;
if (cosmology.w0 < -2.1 || cosmology.w0 > -0.0) return 0;
if (cosmology.wa < -2.6 || cosmology.wa > 2.6) return 0;
if (cosmology.h0 < 0.4 || cosmology.h0 > 0.9) return 0;
//CH BEGINS
//CH: to use for running planck15_BA0_w0_wa prior alone)
//printf("like_fourier.c from WFIRST_forecasts: cosmology bounds set for running with planck15_BA0_w0_wa prior\n");
//if (cosmology.Omega_m < 0.05 || cosmology.Omega_m > 0.6) return 0;
//if (cosmology.omb < 0.01 || cosmology.omb > 0.1) return 0;
//if (cosmology.sigma_8 < 0.5 || cosmology.sigma_8 > 1.1) return 0;
//if (cosmology.n_spec < 0.84 || cosmology.n_spec > 1.06) return 0;
//if (cosmology.w0 < -2.1 || cosmology.w0 > 1.5) return 0;
//if (cosmology.wa < -5.0 || cosmology.wa > 2.6) return 0;
//if (cosmology.h0 < 0.3 || cosmology.h0 > 0.9) return 0;
//CH ENDS
return 1;
}
void set_nuisance_shear_calib(double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10)
{
nuisance.shear_calibration_m[0] = M1;
nuisance.shear_calibration_m[1] = M2;
nuisance.shear_calibration_m[2] = M3;
nuisance.shear_calibration_m[3] = M4;
nuisance.shear_calibration_m[4] = M5;
nuisance.shear_calibration_m[5] = M6;
nuisance.shear_calibration_m[6] = M7;
nuisance.shear_calibration_m[7] = M8;
nuisance.shear_calibration_m[8] = M9;
nuisance.shear_calibration_m[9] = M10;
}
int set_nuisance_shear_photoz(double SP1,double SP2,double SP3,double SP4,double SP5,double SP6,double SP7,double SP8,double SP9,double SP10)
{
int i;
nuisance.bias_zphot_shear[0]=SP1;
nuisance.bias_zphot_shear[1]=SP2;
nuisance.bias_zphot_shear[2]=SP3;
nuisance.bias_zphot_shear[3]=SP4;
nuisance.bias_zphot_shear[4]=SP5;
nuisance.bias_zphot_shear[5]=SP6;
nuisance.bias_zphot_shear[6]=SP7;
nuisance.bias_zphot_shear[7]=SP8;
nuisance.bias_zphot_shear[8]=SP9;
nuisance.bias_zphot_shear[9]=SP10;
// for (i=0;i<tomo.shear_Nbin; i++){
// nuisance.sigma_zphot_shear[i]=SPS1;
// if (nuisance.sigma_zphot_shear[i]<0.0001) return 0;
// }
return 1;
}
int set_nuisance_clustering_photoz(double CP1,double CP2,double CP3,double CP4,double CP5,double CP6,double CP7,double CP8,double CP9,double CP10)
{
int i;
nuisance.bias_zphot_clustering[0]=CP1;
nuisance.bias_zphot_clustering[1]=CP2;
nuisance.bias_zphot_clustering[2]=CP3;
nuisance.bias_zphot_clustering[3]=CP4;
nuisance.bias_zphot_clustering[4]=CP5;
nuisance.bias_zphot_clustering[5]=CP6;
nuisance.bias_zphot_clustering[6]=CP7;
nuisance.bias_zphot_clustering[7]=CP8;
nuisance.bias_zphot_clustering[8]=CP9;
nuisance.bias_zphot_clustering[9]=CP10;
// for (i=0;i<tomo.clustering_Nbin; i++){
// nuisance.sigma_zphot_clustering[i]=CPS1;
// if (nuisance.sigma_zphot_clustering[i]<0.0001) return 0;
// }
return 1;
}
int set_nuisance_ia(double A_ia, double eta_ia)
{
nuisance.A_ia=A_ia;
nuisance.eta_ia=eta_ia;
nuisance.oneplusz0_ia = 1.62;
if (nuisance.A_ia < 0.0 || nuisance.A_ia > 10.0) return 0;
if (nuisance.eta_ia < -10.0 || nuisance.eta_ia> 10.0) return 0;
return 1;
}
// int set_nuisance_ia(double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q)
// {
// nuisance.A_ia=A_ia;
// nuisance.beta_ia=beta_ia;
// nuisance.eta_ia=eta_ia;
// nuisance.eta_ia_highz=eta_ia_highz;
// nuisance.LF_alpha=LF_alpha;
// nuisance.LF_P=LF_P;
// nuisance.LF_Q=LF_Q;
// nuisance.LF_red_alpha=LF_red_alpha;
// nuisance.LF_red_P=LF_red_P;
// nuisance.LF_red_Q=LF_red_Q;
// if (nuisance.A_ia < 0.0 || nuisance.A_ia > 10.0) return 0;
// if (nuisance.beta_ia < -4.0 || nuisance.beta_ia > 6.0) return 0;
// if (nuisance.eta_ia < -10.0 || nuisance.eta_ia> 10.0) return 0;
// if (nuisance.eta_ia_highz < -1.0 || nuisance.eta_ia_highz> 1.0) return 0;
// // if(like.IA!=0){
// // if (check_LF()) return 0;
// // }
// return 1;
// }
int set_nuisance_cluster_Mobs(double cluster_Mobs_lgN0, double cluster_Mobs_alpha, double cluster_Mobs_beta, double cluster_Mobs_sigma0, double cluster_Mobs_sigma_qm, double cluster_Mobs_sigma_qz)
{
// nuisance.cluster_Mobs_lgM0 = mass_obs_norm; //fiducial : 1.72+log(1.e+14*0.7); could use e.g. sigma = 0.2 Gaussian prior
// nuisance.cluster_Mobs_alpha = mass_obs_slope; //fiducial: 1.08; e.g. sigma = 0.1 Gaussian prior
// nuisance.cluster_Mobs_beta = mass_z_slope; //fiducial: 0.0; e.g. sigma = 0.1 Gaussian prior
// nuisance.cluster_Mobs_sigma = mass_obs_scatter; //fiducial 0.25; e.g. sigma = 0.05 Gaussian prior
// fiducial values and priors from Murata et al. (2018) except for redshift-related parameters
nuisance.cluster_Mobs_lgN0 = cluster_Mobs_lgN0; //fiducial: 3.207, flat prior [0.5, 5.0]
nuisance.cluster_Mobs_alpha = cluster_Mobs_alpha; //fiducial: 0.993, flat prior [0.0, 2.0]
nuisance.cluster_Mobs_beta = cluster_Mobs_beta; //fiducial: 0.0, flat prior [-1.5, 1.5]
nuisance.cluster_Mobs_sigma0 = cluster_Mobs_sigma0; //fiducial: 0.456, flat prior [0.0, 1.5]
nuisance.cluster_Mobs_sigma_qm = cluster_Mobs_sigma_qm; //fiducial: -0.169, flat prior [-1.5, 1.5]
nuisance.cluster_Mobs_sigma_qz = cluster_Mobs_sigma_qz; //fiducial: 0.0, flat prior [-1.5, 1.5]
if (nuisance.cluster_Mobs_lgN0 < 0.5 || nuisance.cluster_Mobs_lgN0 > 5.0) return 0;
if (nuisance.cluster_Mobs_alpha < 0.0 || nuisance.cluster_Mobs_alpha > 2.0) return 0;
if (nuisance.cluster_Mobs_beta < -1.5 || nuisance.cluster_Mobs_beta > 1.5) return 0;
if (nuisance.cluster_Mobs_sigma0 < 0.0|| nuisance.cluster_Mobs_sigma0 > 1.5) return 0;
if (nuisance.cluster_Mobs_sigma_qm < -1.5 && nuisance.cluster_Mobs_sigma_qm > 1.5) return 0;
if (nuisance.cluster_Mobs_sigma_qz < -1.5 && nuisance.cluster_Mobs_sigma_qz > 1.5)return 0;
return 1;
}
int set_nuisance_gbias(double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8,double B9, double B10)
{
int i;
gbias.b[0] = B1;
gbias.b[1] = B2;
gbias.b[2] = B3;
gbias.b[3] = B4;
gbias.b[4] = B5;
gbias.b[5] = B6;
gbias.b[6] = B7;
gbias.b[7] = B8;
gbias.b[8] = B9;
gbias.b[9] = B10;
for (i = 0; i < tomo.clustering_Nbin; i++){
// printf("in set routine %d %le\n",i,gbias.b[i]);
if (gbias.b[i] < 0.4 || gbias.b[i] > 3.0) return 0;
}
return 1;
}
int set_nuisance_bmag(double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8,double B9, double B10)
{
int i;
gbias.b_mag[0] = B1;
gbias.b_mag[1] = B2;
gbias.b_mag[2] = B3;
gbias.b_mag[3] = B4;
gbias.b_mag[4] = B5;
gbias.b_mag[5] = B6;
gbias.b_mag[6] = B7;
gbias.b_mag[7] = B8;
gbias.b_mag[8] = B9;
gbias.b_mag[9] = B10;
for (i = 0; i < tomo.clustering_Nbin; i++){
// printf("in set routine %d %le\n",i,gbias.b[i]);
if (gbias.b_mag[i] < -5.0 || gbias.b_mag[i] > 5.0) return 0;
}
return 1;
}
double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double BMAG1, double BMAG2, double BMAG3, double BMAG4,double BMAG5, double BMAG6, double BMAG7, double BMAG8, double BMAG9, double BMAG10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double eta_ia)
{
int i,j,k,m=0,l;
static double *pred;
static double *ell;
static double *ell_Cluster;
static double darg;
double chisqr,a,log_L_prior=0.0, log_L=0.0;;
if(ell==0){
pred= create_double_vector(0, like.Ndata-1);
ell= create_double_vector(0, like.Ncl-1);
darg=(log(like.lmax)-log(like.lmin))/like.Ncl;
for (l=0;l<like.Ncl;l++){
ell[l]=exp(log(like.lmin)+(l+0.5)*darg);
}
// ell_Cluster= create_double_vector(0, Cluster.lbin-1);
// darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin;
// for (l=0;l<Cluster.lbin;l++){
// ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg);
// }
}
if (set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu)==0){
printf("Cosmology out of bounds\n");
return -1.0e15;
}
set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10);
if (set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10)==0){
printf("Shear photo-z sigma too small\n");
return -1.0e15;
}
if (set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10)==0){
printf("Clustering photo-z sigma too small\n");
return -1.0e15;
}
if (set_nuisance_ia(A_ia,eta_ia)==0){
printf("IA parameters out of bounds\n");
return -1.0e15;
}
if (set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10)==0){
printf("Bias out of bounds\n");
return -1.0e15;
}
if (set_nuisance_bmag(BMAG1,BMAG2,BMAG3,BMAG4,BMAG5,BMAG6,BMAG7,BMAG8,BMAG9,BMAG10)==0){
printf("Bmag out of bounds\n");
return -1.0e15;
}
// if (set_nuisance_cluster_Mobs(mass_obs_norm, mass_obs_slope, mass_z_slope, mass_obs_scatter_norm, mass_obs_scatter_mass_slope, mass_obs_scatter_z_slope)==0){
// printf("Mobs out of bounds\n");
// return -1.0e15;
// }
// for (i=0; i<10; i++){
// printf("nuisance %le %le %le\n",nuisance.shear_calibration_m[i],nuisance.bias_zphot_shear[i],nuisance.sigma_zphot_shear[i]);
// }
log_L_prior=0.0;
// if(like.Aubourg_Planck_BAO_SN==1) log_L_prior+=log_L_Planck_BAO_SN();
// if(like.SN==1) log_L_prior+=log_L_SN();
//if(like.BAO==1) log_L_prior+=log_L_BAO();
// if(like.Planck==1) log_L_prior+=log_L_Planck();
// if(like.Planck15_BAO_w0wa==1) log_L_prior+=log_L_Planck15_BAO_w0wa();//CH
//if(like.Planck15_BAO_H070p6_JLA_w0wa==1) log_L_prior+=log_L_Planck15_BAO_H070p6_JLA_w0wa();//CH
// if(like.IA!=0) log_L_prior+=log_L_ia();
// if(like.IA!=0) log_L_prior+=log_like_f_red();
if(like.wlphotoz!=0) log_L_prior+=log_L_wlphotoz();
if(like.clphotoz!=0) log_L_prior+=log_L_clphotoz();
if(like.shearcalib==1) log_L_prior+=log_L_shear_calib();
// if(like.IA!=0) {
// log_L = 0.0;
// log_L -= pow((nuisance.A_ia - prior.A_ia[0])/prior.A_ia[1],2.0);
// log_L -= pow((nuisance.beta_ia - prior.beta_ia[0])/prior.beta_ia[1],2.0);
// log_L -= pow((nuisance.eta_ia - prior.eta_ia[0])/prior.eta_ia[1],2.0);
// log_L -= pow((nuisance.eta_ia_highz - prior.eta_ia_highz[0])/prior.eta_ia_highz[1],2.0);
// log_L_prior+=0.5*log_L;
// }
// if(like.baryons==1){
// log_L = 0.0;
// log_L -= pow((Q1 - prior.bary_Q1[0])/prior.bary_Q1[1],2.0);
// log_L -= pow((Q2 - prior.bary_Q2[0])/prior.bary_Q2[1],2.0);
// log_L -= pow((Q3 - prior.bary_Q3[0])/prior.bary_Q3[1],2.0);
// log_L_prior+=0.5*log_L;
// }
// if(like.clusterMobs==1) log_L_prior+=log_L_clusterMobs();
// printf("%d %d %d %d\n",like.BAO,like.wlphotoz,like.clphotoz,like.shearcalib);
// printf("logl %le %le %le %le\n",log_L_shear_calib(),log_L_wlphotoz(),log_L_clphotoz(),log_L_clusterMobs());
int start=0;
if(like.shear_shear==1) {
set_data_shear(like.Ncl, ell, pred, start);
start=start+like.Ncl*tomo.shear_Npowerspectra;
}
if(like.shear_pos==1){
set_data_ggl(like.Ncl, ell, pred, start);
start=start+like.Ncl*tomo.ggl_Npowerspectra;
}
if(like.pos_pos==1){
set_data_clustering(like.Ncl,ell,pred, start);
start=start+like.Ncl*tomo.clustering_Npowerspectra;
}
if(like.gk==1) {
set_data_gk(ell, pred, start);
start += like.Ncl*tomo.clustering_Nbin;
}
if(like.ks==1) {
set_data_ks(ell, pred, start);
start += like.Ncl*tomo.shear_Nbin;
}
if(like.kk==1) {
set_data_kk(ell, pred, start);
start += like.Ncl;
}
chisqr=0.0;
for (i=0; i<like.Ndata; i++){
for (j=0; j<like.Ndata; j++){
// a=(pred[i]-data_read(1,i)+Q1*bary_read(1,0,i)+Q2*bary_read(1,1,i)+Q3*bary_read(1,2,i))*invcov_read(1,i,j)*(pred[j]-data_read(1,j)+Q1*bary_read(1,0,j)+Q2*bary_read(1,1,j)+Q3*bary_read(1,2,j));
a=(pred[i]-data_read(1,i))*invcov_mask(1,i,j)*(pred[j]-data_read(1,j));
// if(a>10){printf("a,i,j: %le, %d, %d, %le, %le, %le\n",a,i,j,pred[i]-data_read(1,i),pred[j]-data_read(1,j), invcov_mask(1,i,j));}
chisqr=chisqr+a;
}
// if (fabs(data_read(1,i)) < 1.e-25){
// printf("%d %le %le %le\n",i,data_read(1,i),pred[i],invcov_read(1,i,i));
// }
}
if (chisqr<0.0){
printf("error: chisqr = %le\n",chisqr);
//exit(EXIT_FAILURE);
}
printf("%le\n",chisqr);
return -0.5*chisqr+log_L_prior;
}
void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double BMAG1, double BMAG2, double BMAG3, double BMAG4,double BMAG5, double BMAG6, double BMAG7, double BMAG8, double BMAG9, double BMAG10, double SP1, double SP2, double SP3, double SP4, double SP5,double SP6, double SP7, double SP8, double SP9, double SP10, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double eta_ia)
{
int i,j,k,m=0,l;
static double *pred;
static double *ell;
static double *ell_Cluster;
static double darg;
double chisqr,a,log_L_prior=0.0;
if(ell==0){
pred= create_double_vector(0, like.Ndata-1);
ell= create_double_vector(0, like.Ncl-1);
darg=(log(like.lmax)-log(like.lmin))/like.Ncl;
for (l=0;l<like.Ncl;l++){
ell[l]=exp(log(like.lmin)+(l+0.5)*darg);
}
// ell_Cluster= create_double_vector(0, Cluster.lbin-1);
// darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin;
// for (l=0;l<Cluster.lbin;l++){
// ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg);
// }
}
// for (l=0;l<like.Ncl;l++){
// printf("%d %le\n",i,ell[l]);
// }
set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu);
set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10);
set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10);
set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10);
set_nuisance_ia(A_ia,eta_ia);
set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10);
set_nuisance_bmag(BMAG1,BMAG2,BMAG3,BMAG4,BMAG5,BMAG6,BMAG7,BMAG8,BMAG9,BMAG10);
// set_nuisance_cluster_Mobs(mass_obs_norm,mass_obs_slope,mass_z_slope,mass_obs_scatter_norm,mass_obs_scatter_mass_slope,mass_obs_scatter_z_slope);
int start=0;
if(like.shear_shear==1) {
set_data_shear(like.Ncl, ell, pred, start);
start=start+like.Ncl*tomo.shear_Npowerspectra;
}
if(like.shear_pos==1){
//printf("ggl\n");
set_data_ggl(like.Ncl, ell, pred, start);
start=start+like.Ncl*tomo.ggl_Npowerspectra;
}
if(like.pos_pos==1){
//printf("clustering\n");
set_data_clustering(like.Ncl,ell,pred, start);
start=start+like.Ncl*tomo.clustering_Npowerspectra;
}
if(like.gk==1) {
printf("Computing data vector: gk\n");
set_data_gk(ell, pred, start);
start += like.Ncl * tomo.clustering_Nbin;
}
if(like.ks==1) {
printf("Computing data vector: ks\n");
set_data_ks(ell, pred, start);
start += like.Ncl * tomo.shear_Nbin;
}
if (like.kk) {
printf("Computing data vector: kk\n");
set_data_kk(ell, pred, start);
start += like.Ncl;
}
FILE *F;
char filename[300];
if (strstr(details,"FM") != NULL){
sprintf(filename,"%s",details);
}
else {sprintf(filename,"datav/%s_%s",like.probes,details);}
F=fopen(filename,"w");
for (i=0;i<like.Ndata; i++){
fprintf(F,"%d %le\n",i,pred[i]);
//printf("%d %le\n",i,pred[i]);
}
fclose(F);
// printf("&gbias.b1_function %p\n",&gbias.b1_function);
// printf("gbias.b1_function %p\n",gbias.b1_function);
// printf("bgal_z %p\n",bgal_z);
// printf("&bgal_z %p\n",&bgal_z);
// printf("b1_per_bin %p\n",b1_per_bin);
// printf("&b1_per_bin %p\n",&b1_per_bin);
}
void write_datavector_wrapper(char *details, input_cosmo_params_des ic, input_nuisance_params_des in)
{
compute_data_vector(details, ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu,
in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9],
in.b_mag[0], in.b_mag[1], in.b_mag[2], in.b_mag[3],in.b_mag[4], in.b_mag[5], in.b_mag[6], in.b_mag[7],in.b_mag[8], in.b_mag[9],
in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4],
in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9],
in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4],
in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9],
in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4],
in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9],
in.A_ia, in.eta_ia);
}
double log_like_wrapper(input_cosmo_params_des ic, input_nuisance_params_des in)
{
double like = log_multi_like(ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu,
in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9],
in.b_mag[0], in.b_mag[1], in.b_mag[2], in.b_mag[3],in.b_mag[4], in.b_mag[5], in.b_mag[6], in.b_mag[7],in.b_mag[8], in.b_mag[9],
in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4],
in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9],
in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4],
in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9],
in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4],
in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9],
in.A_ia, in.eta_ia);
return like;
}
void save_zdistr_sources(int zs){
double z,dz =(redshift.shear_zdistrpar_zmax-redshift.shear_zdistrpar_zmin)/300.0;
printf("Printing redshift distribution n(z) for source redshift bin %d\n",zs);
FILE *F1;
char filename[300];
sprintf(filename,"zdistris/zdist_sources_bin%d.txt",zs);
F1 = fopen(filename,"w");
for (z =redshift.shear_zdistrpar_zmin; z< redshift.shear_zdistrpar_zmax; z+= dz){
fprintf(F1,"%e %e\n", z, zdistr_photoz(z,zs));
}
}
void save_zdistr_lenses(int zl){
double z,dz =(redshift.clustering_zdistrpar_zmax-redshift.clustering_zdistrpar_zmin)/300.0;
printf("Printing redshift distribution n(z) and bias b(z) for lens redshift bin %d\n",zl);
FILE *F1;
char filename[300];
sprintf(filename,"zdistris/zdist_lenses_bin%d.txt", zl);
F1 = fopen(filename,"w");
for (z =redshift.clustering_zdistrpar_zmin; z< redshift.clustering_zdistrpar_zmax; z+= dz){
fprintf(F1,"%e %e\n", z, pf_photoz(z,zl));
}
}
int main(int argc, char** argv)
{
int i;
// char arg1[400],arg2[400],arg3[400];
/* here, do your time-consuming job */
// int sce=atoi(argv[1]);
// int N_scenarios=2;
// double sigma_zphot_shear[3]={0.05,0.05};
// double sigma_zphot_clustering[3]={0.03,0.03};
// double area_table[2]={12300.0,16500.0}; // Y1 corresponds to DESC SRD Y1, Y6 corresponds to assuming that we cover the full SO area=0.4*fsky and at a depth of 26.1 which is in a range of reasonable scenarios (see https://github.com/LSSTDESC/ObsStrat/tree/static/static )
// double nsource_table[2]={11.0,23.0};
// double nlens_table[2]={18.0,41.0};
// char survey_designation[2][200]={"LSSTxSO_Y1","LSSTxSO_Y6"};
// char tomo_binning_source[2][200]={"source_std","source_std"};
// char tomo_binning_lens[2][200]={"LSST_gold","LSST_gold"};
// char source_zfile[2][400]={"src_LSSTY1","src_LSSTY6"};
// char lens_zfile[2][400]={"lens_LSSTY1", "lens_LSSTY6"};
init_cosmo_runmode("halofit");
// init_bary(argv[2]);
init_binning_fourier(20,30.0,3000.0,3000.0,20.0);
// init_priors(0.002,sigma_zphot_shear[sce],0.001,0.001,sigma_zphot_clustering[sce],0.001,0.001,3.0,1.2,3.8,2.0,16.0,5.0,0.8);
// init_survey(survey_designation[sce],nsource_table[sce],nlens_table[sce],area_table[sce]);
// sprintf(arg1,"zdistris/%s",source_zfile[sce]);
// sprintf(arg2,"zdistris/%s",lens_zfile[sce]);
// init_galaxies(arg1,arg2,"gaussian","gaussian",tomo_binning_source[sce],tomo_binning_lens[sce]);
double b1[10]={0.,0.,0.,0.,0.,0.,0.,0.,0.,0.}, b2[10] ={0.,0.,0.,0.,0.,0.,0.,0.,0.,0.},b_mag[10] ={0.,0.,0.,0.,0.,0.,0.,0.,0.,0.};
b1[0] = 1.7;
b1[1] = 1.7;
b1[2] = 1.7;
b1[3] = 2.0;
b1[4] = 2.0;
b_mag[0] = -0.19375;
b_mag[1] = -0.6285407;
b_mag[2] = -0.69319886;
b_mag[3] = 1.17735723;
b_mag[4] = 1.87509758;
// init_source_sample_mpp("./zdistris/mcal_1101_source.nz",4);
init_source_sample_mpp("./zdistris/source_DESY6_3bins.nz",3);
init_lens_sample_mpp("./zdistris/mcal_1101_lens.nz",5);
init_IA_mpp(4);
init_probes("6x2pt");
init_cmb("planck");
compute_data_vector("desy6xplanck_6x2pt_3bins_2.txt",0.25,0.75,0.97,-1.,0.,0.048,0.69,0.,0.,\
b1[0],b1[1],b1[2],b1[3],b1[4],\
b1[5],b1[6],b1[7],b1[8],b1[9],\
b_mag[0],b_mag[1],b_mag[2],b_mag[3],b_mag[4],\
b_mag[5],b_mag[6],b_mag[7],b_mag[8],b_mag[9],\
0.0,0.0,0.0,0.0,0.0,\
0.0,0.0,0.0,0.0,0.0,\
0.0,0.0,0.0,0.0,0.0,\
0.0,0.0,0.0,0.0,0.0,\
0.0,0.0,0.0,0.0,0.0,\
0.0,0.0,0.0,0.0,0.0,\
0.5,0.0);
// init_data_cov_mask("cov/cov_desy3xplanck","datav/6x2pt_desy3xplanck_6x2pt.txt", "datav/xi_Y3_6x2pt.mask");
// // init_data_cov_mask("cov/cov_desy6xplanck_3src","datav/6x2pt_desy6xplanck_6x2pt_3bins.txt", "datav/xi_Y6_6x2pt_3src.mask");
// for(double omm=0.2;omm<0.5; omm+=0.01){
// printf("%le, %le\n", omm, log_multi_like(omm,0.82355,0.97,-1.,0.,0.048,0.69,0.,0.,\
// b1[0],b1[1],b1[2],b1[3],b1[4],\
// b1[5],b1[6],b1[7],b1[8],b1[9],\
// b_mag[0],b_mag[1],b_mag[2],b_mag[3],b_mag[4],\
// b_mag[5],b_mag[6],b_mag[7],b_mag[8],b_mag[9],\
// 0.0,0.0,0.0,0.0,0.0,\
// 0.0,0.0,0.0,0.0,0.0,\
// 0.0,0.0,0.0,0.0,0.0,\
// 0.0,0.0,0.0,0.0,0.0,\
// 0.0,0.0,0.0,0.0,0.0,\
// 0.0,0.0,0.0,0.0,0.0,\
// 0.5,0.0));
// exit(0);
// }
return 0;
}
| {
"alphanum_fraction": 0.670217011,
"avg_line_length": 39.6338199513,
"ext": "c",
"hexsha": "b3e2ada822f712ebe6428412087ea61e4f48a05b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "43dfce33112480e17878b2de3421775ec9df296c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CosmoLike/LSSTxSO",
"max_forks_repo_path": "like_fourier_desxplanck.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "43dfce33112480e17878b2de3421775ec9df296c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "CosmoLike/LSSTxSO",
"max_issues_repo_path": "like_fourier_desxplanck.c",
"max_line_length": 777,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "43dfce33112480e17878b2de3421775ec9df296c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CosmoLike/LSSTxSO",
"max_stars_repo_path": "like_fourier_desxplanck.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 12495,
"size": 32579
} |
#include <stdio.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_multimin.h>
/* Paraboloid with a minimum at f(dp[0],dp[1]) = 30.0 */
double
my_f (const gsl_vector * v, void *params)
{
double x, y;
double *dp = (double *) params;
x = gsl_vector_get (v, 0);
y = gsl_vector_get (v, 1);
return 10.0 * (x - dp[0]) * (x - dp[0]) +
20.0 * (y - dp[1]) * (y - dp[1]) + 30.0;
}
/* The gradient of f, df = (df/dx, df/dy). */
void
my_df (const gsl_vector * v, void *params, gsl_vector * df)
{
double x, y;
double *dp = (double *) params;
x = gsl_vector_get (v, 0);
y = gsl_vector_get (v, 1);
gsl_vector_set (df, 0, 20.0 * (x - dp[0]));
gsl_vector_set (df, 1, 40.0 * (y - dp[1]));
}
/* Now both f and df together. */
void
my_fdf (const gsl_vector * x, void *params, double *f, gsl_vector * df)
{
*f = my_f (x, params);
my_df (x, params, df);
}
int
main (void)
{
size_t iter = 0;
int status;
const gsl_multimin_fdfminimizer_type *T;
gsl_multimin_fdfminimizer *s;
/* Position of the minimum (1,2). */
double par[2] = { 1.0, 2.0 };
gsl_vector *x;
gsl_multimin_function_fdf my_func;
my_func.f = &my_f;
my_func.df = &my_df;
my_func.fdf = &my_fdf;
my_func.n = 2;
my_func.params = ∥
/* Starting point, x = (5,7) */
x = gsl_vector_alloc (2);
gsl_vector_set (x, 0, 5.0);
gsl_vector_set (x, 1, 7.0);
T = gsl_multimin_fdfminimizer_conjugate_fr;
s = gsl_multimin_fdfminimizer_alloc (T, 2);
gsl_multimin_fdfminimizer_set (s, &my_func, x, 0.01, 1e-4);
do
{
iter++;
status = gsl_multimin_fdfminimizer_iterate (s);
if (status)
break;
status = gsl_multimin_test_gradient (s->gradient, 1e-3);
if (status == GSL_SUCCESS)
printf ("Minimum found at:\n");
printf ("%5d %.5f %.5f %10.5f\n", iter,
gsl_vector_get (s->x, 0), gsl_vector_get (s->x, 1), s->f);
}
while (status == GSL_CONTINUE && iter < 100);
gsl_multimin_fdfminimizer_free (s);
gsl_vector_free (x);
return 0;
}
| {
"alphanum_fraction": 0.5999008428,
"avg_line_length": 20.793814433,
"ext": "c",
"hexsha": "12489dc48c61f0ffb722aba6b2a905f188064452",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/multimin/demo.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/multimin/demo.c",
"max_line_length": 72,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/multimin/demo.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z",
"num_tokens": 736,
"size": 2017
} |
#ifndef SCALED_VARIANCE_H
#define SCALED_VARIANCE_H
#include "smash/decaymodes.h"
#include "smash/particletype.h"
#include <gsl/gsl_multiroots.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_vector.h>
bool load_particle_types();
class ScaledVarianceCalculator {
public:
ScaledVarianceCalculator(const smash::ParticleTypePtrList& types_in_the_box,
double T, double mub, double mus, double muq,
bool energy_conservation,
bool B_conservation,
bool S_conservation,
bool Q_conservation,
bool quantum_statistics) :
T_ (T),
mub_ (mub),
mus_ (mus),
muq_ (muq),
energy_conservation_ (energy_conservation),
B_conservation_ (B_conservation),
S_conservation_ (S_conservation),
Q_conservation_ (Q_conservation),
quantum_statistics_ (quantum_statistics),
quantum_series_max_terms_(100),
quantum_series_rel_precision_(1e-12) {
all_types_in_the_box_.clear();
for (const smash::ParticleTypePtr t : types_in_the_box) {
all_types_in_the_box_.push_back(t);
}
}
void set_T (double T) { T_ = T; }
void set_mub (double mub) { mub_ = mub; }
void set_mus (double mus) { mus_ = mus; }
void set_muq (double muq) { muq_ = muq; }
void set_B_conservation (bool B_cons) { B_conservation_ = B_cons; }
void set_S_conservation (bool S_cons) { S_conservation_ = S_cons; }
void set_Q_conservation (bool Q_cons) { Q_conservation_ = Q_cons; }
void set_quantum_statistics (bool qs) { quantum_statistics_ = qs; }
struct solver_params {
smash::ParticleTypePtrList* types;
double e; // energy density
double nb; // baryon number density
double ns; // strangeness density
double nq; // charge density
};
static int set_eos_solver_equations(const gsl_vector* x, void* params,
gsl_vector* f);
std::string print_solver_state(size_t iter,
gsl_multiroot_fsolver* solver) const;
void setTmu_from_conserved(double Etot, double V,
double B, double S, double Q);
/**
* Assumes that there is a gas of particles species defined
* by all_types_in_the_box_. This function computes fluctuations
* of the total number of particles belonging to a subset of species
* defined by type_of_interest function. Fluctuations depend on
* the ensemble and which conservation laws it respects. This is
* determined by variables energy_conservation_, B_conservation_,
* S_conservation_, and Q_conservation_.
*
* For reference see arxiv.org/pdf/0706.3290.pdf, Eq. (29-40).
* The approximations of this paper are only valid for large
* enough volume.
*
* \param[in] type_of_interest Function true for particle species, for
* which the mean and the scaled variance are computed
* \param[out] mean density and scaled variance of type_of_interest species
*/
std::pair<double, double> scaled_variance(
std::function<bool(const smash::ParticleTypePtr)> type_of_interest);
void prepare_decays();
friend std::ostream& operator<< (std::ostream&,
const ScaledVarianceCalculator&);
private:
/// List of species included in the gas
smash::ParticleTypePtrList all_types_in_the_box_;
/**
* Structure for holding all decay final state in a form convenient
* for statistical caulculations:
* resonance ->
* vector of decays
* each decay = (branching ratio and vector (product -> count))
* Sum of branching ratios should be 1 for all particles.
* By convention stable particles decay into themselves with brancing ratio 1.
*/
std::map<smash::ParticleTypePtr,
std::vector<std::pair<double,
std::map<smash::ParticleTypePtr, int>>>>
all_decay_final_states_;
/// Temperature of the gas [GeV]
double T_;
/// Baryo-chemical potential of the gas [GeV]
double mub_;
/// Strangeness chemical potential of the gas [GeV]
double mus_;
/// Charge chemical potential of the gas [GeV]
double muq_;
/// If ensemble includes energy conservation
bool energy_conservation_;
/// If ensemble includes baryon number conservation
bool B_conservation_;
/// If ensemble includes strangeness conservation
bool S_conservation_;
/// If ensemble includes electric charge conservation
bool Q_conservation_;
/// If quantum statistics is included
bool quantum_statistics_;
/// Maximal number of terms in the series for quantum formulas
const unsigned int quantum_series_max_terms_;
/// Relative precision, at which quantum series summation stops
const double quantum_series_rel_precision_;
};
#endif // SCALED_VARIANCE_H
| {
"alphanum_fraction": 0.6840909091,
"avg_line_length": 38.1102362205,
"ext": "h",
"hexsha": "3d6b4166b37d6946b9bc097a08289301f7122cf5",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "eb032fe3901cf4f3a2f9bdddb017da84654be18f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "doliinychenko/scaled_variance_cons_laws",
"max_forks_repo_path": "include/scaled_variance.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "eb032fe3901cf4f3a2f9bdddb017da84654be18f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "doliinychenko/scaled_variance_cons_laws",
"max_issues_repo_path": "include/scaled_variance.h",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "eb032fe3901cf4f3a2f9bdddb017da84654be18f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "doliinychenko/scaled_variance_cons_laws",
"max_stars_repo_path": "include/scaled_variance.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-31T10:36:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-31T10:36:07.000Z",
"num_tokens": 1162,
"size": 4840
} |
#ifndef __LISAUTILS_H__
#define __LISAUTILS_H__ 1
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_cdf.h>
#include "constants.h"
#include "struct.h"
#include "EOBNRv2HMROMstruct.h"
#include "EOBNRv2HMROM.h"
#include "waveform.h"
#include "wip.h"
#include "splinecoeffs.h"
#include "fresnel.h"
#include "likelihood.h"
#include "LISAFDresponse.h"
#include "LISAnoise.h"
#if defined(__cplusplus)
extern "C" {
#define complex _Complex
#elif 0
} /* so that editors will match preceding brace */
#endif
/***************** Enumerator to choose what masses/time set to sample for *****************/
typedef enum SampleMassParamstag {
m1m2,
Mchirpeta
} SampleMassParamstag;
/* Superseded by sampleLframe */
// typedef enum SampleTimeParamtag {
// tSSB,
// tL
// } SampleTimeParamtag;
/* Function to convert string input SampleMassParams to tag */
SampleMassParamstag ParseSampleMassParamstag(char* string);
/* Function to convert string input SampleTimeParams to tag */
//SampleTimeParamtag ParseSampleTimeParamtag(char* string);
/***************** Structure definitions *****************/
/* Parameters for the generation of a LISA waveform (in the form of a list of modes) */
typedef struct tagLISAParams {
double tRef; /* reference time (s) - GPS time at the frequency representing coalescence */
double phiRef; /* reference phase (rad) - phase at the frequency representing coalescence (or at fRef if specified) */
double m1; /* mass of companion 1 (solar masses, default 2e6) */
double m2; /* mass of companion 2 (solar masses, default 1e6) */
double distance; /* distance of source (Mpc, default 1e3) */
double lambda; /* first angle for the position in the sky (rad, default 0) */
double beta; /* second angle for the position in the sky (rad, default 0) */
double inclination; /* inclination of L relative to line of sight (rad, default PI/3) */
double polarization; /* polarization angle (rad, default 0) */
int nbmode; /* number of modes to generate (starting with 22) - defaults to 5 (all modes) */
} LISAParams;
/* Global parameters for the waveform generation and overlap computation */
typedef struct tagLISAGlobalParams {
double fRef; /* reference frequency (Hz, default 0 which is interpreted as Mf=0.14) */
double deltatobs; /* max duration of observation (years, default 2) - the start of the signals might be cut in time instead of cut in frequency */
double minf; /* Minimal frequency (Hz, default=0) - when set to 0, use the lowest frequency where the detector noise model is trusted __LISASimFD_Noise_fLow (set somewhat arbitrarily)*/
double maxf; /* Maximal frequency (Hz, default=0) - when set to 0, use the highest frequency where the detector noise model is trusted __LISASimFD_Noise_fHigh (set somewhat arbitrarily)*/
int tagextpn; /* Tag to allow PN extension of the waveform at low frequencies */
int tagtRefatLISA; /* Tag to signal time to be referenced to arrival at LISA rather than at SSB */
double Mfmatch; /* When PN extension allowed, geometric matching frequency: will use ROM above this value. If <=0, use ROM down to the lowest covered frequency */
int setphiRefatfRef; /* Flag for adjusting the FD phase at phiRef at the given fRef, which depends also on tRef - if false, treat phiRef simply as an orbital phase shift (minus an observer phase shift) (default=1) */
int nbmodeinj; /* number of modes to include in the injection (starting with 22) - defaults to 5 (all modes) */
int nbmodetemp; /* number of modes to include in the templates (starting with 22) - defaults to 5 (all modes) */
int tagint; /* Tag choosing the integrator: 0 for wip (default), 1 for linear integration */
TDItag tagtdi; /* Tag choosing the TDI variables to use */
int nbptsoverlap; /* Number of points to use in loglinear overlaps (default 32768) */
LISAconstellation *variant; /* A structure defining the LISA constellation features */
int zerolikelihood; /* Tag to zero out the likelihood, to sample from the prior for testing purposes (default 0) */
int frozenLISA; /* Freeze the orbital configuration to the time of peak of the injection (default 0) */
ResponseApproxtag responseapprox; /* Approximation in the GAB and orb response - choices are full (full response, default), lowfL (keep orbital delay frequency-dependence but simplify constellation response) and lowf (simplify constellation and orbital response) - WARNING : at the moment noises are not consistent, and TDI combinations from the GAB are unchanged */
int tagsimplelikelihood22; /* Tag to use simplified, frozen-LISA and lowf likelihood where mode overlaps are precomputed - 22-mode only - can only be used when the masses and time (tL) are pinned to injection values (Note: when using --snr, distance adjustment done using responseapprox, not the simple response) */
int tagsimplelikelihoodHM; /* Tag to use simplified, frozen-LISA and lowf likelihood where mode overlaps are precomputed - set of modes - can only be used when the masses and time (tL) are pinned to injection values (Note: when using --snr, distance adjustment done using responseapprox, not the simple response) */
} LISAGlobalParams;
typedef struct tagLISASignalCAmpPhase
{
struct tagListmodesCAmpPhaseFrequencySeries* TDI1Signal; /* Signal in the TDI channel 1, in the form of a list of the contribution of each mode */
struct tagListmodesCAmpPhaseFrequencySeries* TDI2Signal; /* Signal in the TDI channel 2, in the form of a list of the contribution of each mode */
struct tagListmodesCAmpPhaseFrequencySeries* TDI3Signal; /* Signal in the TDI channel 3, in the form of a list of the contribution of each mode */
double TDI123hh; /* Combined Inner product (h|h) for TDI channels 123 */
} LISASignalCAmpPhase;
typedef struct tagLISAInjectionCAmpPhase
{
struct tagListmodesCAmpPhaseSpline* TDI1Splines; /* Signal in the TDI channel 1, in the form of a list of splines for the contribution of each mode */
struct tagListmodesCAmpPhaseSpline* TDI2Splines; /* Signal in the TDI channel 2, in the form of a list of splines for the contribution of each mode */
struct tagListmodesCAmpPhaseSpline* TDI3Splines; /* Signal in the TDI channel 3, in the form of a list of splines for the contribution of each mode */
double TDI123ss; /* Combined Inner product (s|s) for TDI channels 123 */
} LISAInjectionCAmpPhase;
typedef struct tagLISASignalReIm /* We don't store the SNRs here, as we will use -1/2(h-s|h-s) for the likelihood */
{
struct tagReImFrequencySeries* TDI1Signal; /* Signal in the TDI channel 1, in the form of a Re/Im frequency series where the modes have been summed */
struct tagReImFrequencySeries* TDI2Signal; /* Signal in the TDI channel 2, in the form of a Re/Im frequency series where the modes have been summed */
struct tagReImFrequencySeries* TDI3Signal; /* Signal in the TDI channel 3, in the form of a Re/Im frequency series where the modes have been summed */
} LISASignalReIm;
typedef struct tagLISAInjectionReIm /* Storing the vectors of frequencies and noise values - We don't store the SNRs here, as we will use -1/2(h-s|h-s) for the likelihood */
{
struct tagReImFrequencySeries* TDI1Signal; /* Signal in the TDI channel 1, in the form of a Re/Im frequency series where the modes have been summed */
struct tagReImFrequencySeries* TDI2Signal; /* Signal in the TDI channel 2, in the form of a Re/Im frequency series where the modes have been summed */
struct tagReImFrequencySeries* TDI3Signal; /* Signal in the TDI channel 3, in the form of a Re/Im frequency series where the modes have been summed */
gsl_vector* freq; /* Vector of frequencies of the injection (assumed to be the same for A,E,T) */
gsl_vector* noisevalues1; /* Vector of noise values on freq for TDI channel 1 */
gsl_vector* noisevalues2; /* Vector of noise values on freq for TDI channel 2 */
gsl_vector* noisevalues3; /* Vector of noise values on freq for TDI channel 3 */
} LISAInjectionReIm;
typedef struct tagLISAPrior {
SampleMassParamstag samplemassparams; /* Choose the set of mass params to sample from - options are m1m2 and Mchirpeta (default m1m2) */
//SampleTimeParamtag sampletimeparam; /* Choose the time param to sample from - options are tSSB and tL (default tSSB) */
int sampleLframe; /* flag to sample L-frame params tL, lambdaL, betaL, psiL instead of SSB-frame params -- priors are interpreted for those L-frame params - no phase transformation */
double deltaT; /* width of time prior centered on injected value (s) (default 1e5) */
double comp_min; /* minimum component mass (solar masses) (default 1e4) */
double comp_max; /* maximum component mass (solar masses) (default 1e8) */
double mtot_min; /* minimum total mass (solar masses) (default 5*1e4) */
double mtot_max; /* maximum total mass (solar masses) (default 1e8) */
double qmax; /* maximum asymmetric mass ratio (>=1) (default 11.98) */
double Mchirp_min; /* Minimum chirp mass in Solar masses - when sampling Mchirpeta (default=2e4) */
double Mchirp_max; /* Maximum chirp mass in Solar masses - when sampling Mchirpeta (default=4e7) */
double eta_min; /* Minimum symmetric mass ratio eta - when sampling Mchirpeta (default=0.072) */
double eta_max; /* Maximum symmetric mass ratio eta - when sampling Mchirpeta (default=0.25) */
double dist_min; /* minimum distance of source (Mpc) (default 100) */
double dist_max; /* maximum distance of source (Mpc) (default 40*1e3) */
double lambda_min; /* minimum lambda (rad, default 0) - for testing */
double lambda_max; /* maximum lambda (rad, default 2pi) - for testing */
double beta_min; /* minimum beta (rad, default 0) - for testing */
double beta_max; /* maximum beta (rad, default pi) - for testing */
double phase_min; /* minimum phase (rad, default 0) - for testing */
double phase_max; /* maximum phase (rad, default 2pi) - for testing */
double pol_min; /* minimum polarization (rad, default 0) - for testing */
double pol_max; /* maximum polarization (rad, default 2pi) - for testing */
double inc_min; /* minimum inclination (rad, default 0) - for testing */
double inc_max; /* maximum inclination (rad, default pi) - for testing */
double fix_m1;
double fix_m2;
double fix_Mchirp;
double fix_eta;
double fix_time;
double fix_lambda;
double fix_beta;
double fix_phase;
double fix_pol;
double fix_dist;
double fix_inc;
int pin_m1;
int pin_m2;
int pin_Mchirp;
int pin_eta;
int pin_time;
int pin_lambda;
int pin_beta;
int pin_phase;
int pin_pol;
int pin_dist;
int pin_inc;
double snr_target;
int rescale_distprior;
int flat_distprior;
int logflat_massprior;
} LISAPrior;
typedef struct tagLISARunParams {
double eff; /* target efficiency (default 0.1) */
double tol; /* logZ tolerance (default 0.5) */
int consteff; /* constant efficiency mode (default 0) */
int nlive; /* number of live points (default 1000) */
int writeparams; /* Write params - if 1, write run parameters to file (default 1) */
char outroot[200]; /* output root (default "chains/LISAinference_") */
int bambi; /* run BAMBI? (default 0) */
int resume; /* resume form previous run? (default 0) */
int maxiter; /* max number of iterations (default 0 - ignore) */
char netfile[200]; /* NN settings file (default "LISAinference.inp") */
int mmodal; /* use multimodal decomposition ? */
int maxcls; /* max number of modes in multimodal decomposition */
int nclspar; /* number of parameters to use for multimodal decomposition - in the order of the cube */
double ztol; /* in multimodal decomposition, modes with lnZ lower than Ztol are ignored */
int seed; /* seed the inference by setting one of the live points to the injection ? */
} LISARunParams;
/* Parameters for the generation of a LISA waveform (in the form of a list of modes) */
typedef struct tagLISAAddParams {
double tRef; /* reference time (s) - GPS time at the frequency representing coalescence */
double phiRef; /* reference phase (rad) - phase at the frequency representing coalescence (or at fRef if specified) */
double m1; /* mass of companion 1 (solar masses, default 2e6) */
double m2; /* mass of companion 2 (solar masses, default 1e6) */
double distance; /* distance of source (Mpc, default 1e3) */
double lambda; /* first angle for the position in the sky (rad, default 0) */
double beta; /* second angle for the position in the sky (rad, default 0) */
double inclination; /* inclination of L relative to line of sight (rad, default PI/3) */
double polarization; /* polarization angle (rad, default 0) */
int loadparamsfile; /* Option to load physical parameters from file for LISAlikelihood and to output resulting likelihoods to file (default 0) */
int nlinesparams; /* Number of lines in params file for LISAlikelihood */
char indir[256]; /* Input directory for LISAlikelihood */
char infile[256]; /* Input file for LISAlikelihood */
char outdir[256]; /* Output directory for LISAlikelihood */
char outfile[256]; /* Output file for LISAlikelihood */
} LISAAddParams;
/* Saved precomputed values for the injection , when using the simplified frozenLISA lowf likelihood - here for now assumes 22 mode only, old convention */
/* NOTE: difference in convention, new convention has a factor 3 in the integrand defining <lm|l'm'> */
typedef struct tagSimpleLikelihoodPrecomputedValues22 {
double normalization;
double complex sa;
double complex se;
} SimpleLikelihoodPrecomputedValues22;
/* Saved precomputed values for the injection , when using the simplified frozenLISA lowf likelihood - here for set of modes, new convention */
/* NOTE: difference in convention, new convention has a factor 3 in the integrand defining <lm|l'm'> */
typedef struct tagSimpleLikelihoodPrecomputedValuesHM {
gsl_matrix* Lambda_lm_lpmp; /* Matrix <lm|l'm'> */
gsl_vector* sa_lm_real; /* Vector s_a^{lm}, real part*/
gsl_vector* sa_lm_imag; /* Vector s_a^{lm}, imaginary part */
gsl_vector* se_lm_real; /* Vector s_e^{lm}, real part*/
gsl_vector* se_lm_imag; /* Vector s_e^{lm}, imaginary part */
} SimpleLikelihoodPrecomputedValuesHM;
/************ Functions for LISA parameters, injection, likelihood, prior ************/
/* Parse command line to initialize LISAParams, LISAGlobalParams, LISAPrior, and LISARunParams objects */
/* Masses are input in solar masses and distances in Mpc - converted in SI for the internals */
void parse_args_LISA(ssize_t argc, char **argv,
LISAParams* params,
LISAGlobalParams* globalparams,
LISAPrior* prior,
LISARunParams* run,
LISAAddParams* addparams);
/* Functions to print the parameters of the run in files for reference */
int print_parameters_to_file_LISA(
LISAParams* params,
LISAGlobalParams* globalparams,
LISAPrior* prior,
LISARunParams* run);
int print_rescaleddist_to_file_LISA(
LISAParams* params,
LISAGlobalParams* globalparams,
LISAPrior* prior,
LISARunParams* run);
int print_snrlogZ_to_file_LISA(LISARunParams* run, double SNR, double logZ);
/* Function printing injection/signal parameters to stdout */
void report_LISAParams(LISAParams* params);
/* Initialization and clean-up for LISASignal structures */
void LISASignalCAmpPhase_Cleanup(LISASignalCAmpPhase* signal);
void LISASignalCAmpPhase_Init(LISASignalCAmpPhase** signal);
void LISAInjectionCAmpPhase_Cleanup(LISAInjectionCAmpPhase* signal);
void LISAInjectionCAmpPhase_Init(LISAInjectionCAmpPhase** signal);
void LISASignalReIm_Cleanup(LISASignalReIm* signal);
void LISASignalReIm_Init(LISASignalReIm** signal);
void LISAInjectionReIm_Cleanup(LISAInjectionReIm* signal);
void LISAInjectionReIm_Init(LISAInjectionReIm** signal);
//Function to restrict range of the signal/injection to within desired limits.
int listmodesCAmpPhaseTrim(ListmodesCAmpPhaseFrequencySeries* listSeries);
/* Function generating a LISA signal as a list of modes in CAmp/Phase form, from LISA parameters */
int LISAGenerateSignalCAmpPhase(
struct tagLISAParams* params, /* Input: set of LISA parameters of the signal */
struct tagLISASignalCAmpPhase* signal); /* Output: structure for the generated signal */
/* Function generating a LISA injection as a list of modes, given as preinterpolated splines, from LISA parameters */
int LISAGenerateInjectionCAmpPhase(
struct tagLISAParams* injectedparams, /* Input: set of LISA parameters of the signal */
struct tagLISAInjectionCAmpPhase* signal); /* Output: structure for the generated signal */
/* Function generating a LISA signal as a frequency series in Re/Im form where the modes have been summed, from LISA parameters - takes as argument the frequencies on which to evaluate */
int LISAGenerateSignalReIm(
struct tagLISAParams* params, /* Input: set of LISA parameters of the template */
gsl_vector* freq, /* Input: frequencies on which evaluating the waveform (from the injection) */
struct tagLISASignalReIm* signal); /* Output: structure for the generated signal */
/* Function generating a LISA injection as a frequency series in Re/Im form where the modes have been summed, from LISA parameters - frequencies on which to evaluate are to be determined internally */
int LISAGenerateInjectionReIm(
struct tagLISAParams* injectedparams, /* Input: set of LISA parameters of the injection */
double fLow, /* Input: starting frequency */
int nbpts, /* Input: number of frequency samples */
int tagsampling, /* Input: tag for using linear (0) or logarithmic (1) sampling */
struct tagLISAInjectionReIm* signal); /* Output: structure for the generated signal */
/*Wrapper for waveform generation with possibly a combination of EOBNRv2HMROM and TaylorF2*/
/* Note: GenerateWaveform accepts masses and distances in SI units, whereas LISA params is in solar masses and Mpc */
int GenerateWaveform(
struct tagListmodesCAmpPhaseFrequencySeries **listhlm, /* Output: list of modes in Frequency-domain amplitude and phase form */
int nbmode, /* Number of modes to generate (starting with the 22) */
double f_match, /* Minimum frequency using EOBNRv2HMROM */
double f_min, /* Minimum frequency required */
double deltatRef, /* Time shift so that the peak of the 22 mode occurs at deltatRef */
double phiRef, /* Phase at reference frequency */
double fRef, /* Reference frequency (Hz); 0 defaults to fLow */
double m1SI, /* Mass of companion 1 (kg) */
double m2SI, /* Mass of companion 2 (kg) */
double distance /* Distance of source (m) */
);
/* Non-spinning merger TaylorF2 waveform, copied and condensed from LAL */
void TaylorF2nonspin(
double *amp, /**< FD waveform amplitude (modulus)*/
double *phase, /**< FD waveform phase */
const double *freqs, /**< frequency points at which to evaluate the waveform (Hz) */
const int size, /** number of freq samples */
const double m1_SI, /**< mass of companion 1 (kg) */
const double m2_SI, /**< mass of companion 2 (kg) */
const double distance, /** distance (m) */
const double imatch /**< index at which to match phase;
assumes arrays are preloaded at imatch and imatch+1
with the required result */
);
/* checks prior boundaires */
int PriorBoundaryCheckm1m2(LISAPrior *prior, double *Cube);
int PriorBoundaryCheckMchirpeta(LISAPrior *prior, double *Cube);
/* Prior functions from Cube to physical parameters
x1 is min, x2 is max when specified
r is Cube value */
double CubeToFlatPrior(double r, double x1, double x2);
double CubeToLogFlatPrior(double r, double x1, double x2);
double CubeToPowerPrior(double p, double r, double x1, double x2);
double CubeToGaussianPrior(double r, double mean, double sigma);
double CubeToSinPrior(double r, double x1, double x2);
double CubeToCosPrior(double r, double x1, double x2);
/* Prior functions from physical parameters to Cube
x1 is min, x2 is max when specified
y is physical value */
double FlatPriorToCube(double y, double x1, double x2);
double LogFlatPriorToCube(double y, double x1, double x2);
double PowerPriorToCube(double p, double y, double x1, double x2);
double SinPriorToCube(double y, double x1, double x2);
double CosPriorToCube(double y, double x1, double x2);
/* log-Likelihood functions */
double CalculateLogLCAmpPhase(LISAParams *params, LISAInjectionCAmpPhase* injection);
double CalculateLogLReIm(LISAParams *params, LISAInjectionReIm* injection);
/* Functions for simplified likelihood using precomputing relevant values */
int LISAComputeSimpleLikelihoodPrecomputedValues22(SimpleLikelihoodPrecomputedValues22* simplelikelihoodvals22, LISAParams* params);
int LISAComputeSimpleLikelihoodPrecomputedValuesHM(SimpleLikelihoodPrecomputedValuesHM* simplelikelihoodvalsHM, LISAParams* params);
double CalculateLogLSimpleLikelihood22(SimpleLikelihoodPrecomputedValues22* simplelikelihoodvals22, LISAParams* params);
double CalculateLogLSimpleLikelihoodHM(SimpleLikelihoodPrecomputedValuesHM* simplelikelihoodvalsHM, LISAParams* params);
/************ Global Parameters ************/
extern LISAParams* injectedparams;
extern LISAGlobalParams* globalparams;
extern LISAPrior* priorParams;
extern LISAAddParams* addparams;
extern double logZdata; /* TODO: not used */
extern SimpleLikelihoodPrecomputedValues22* simplelikelihoodinjvals22;
extern SimpleLikelihoodPrecomputedValuesHM* simplelikelihoodinjvalsHM;
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif
| {
"alphanum_fraction": 0.6951266888,
"avg_line_length": 63.4712328767,
"ext": "h",
"hexsha": "2cf1486a9c976410b5a4fccd53877273a2edd59b",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "JohnGBaker/flare",
"max_forks_repo_path": "LISAinference/LISAutils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "JohnGBaker/flare",
"max_issues_repo_path": "LISAinference/LISAutils.h",
"max_line_length": 371,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "a58d2e6c2b36c0f17b310b305b45d447afc04dec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "JohnGBaker/flare",
"max_stars_repo_path": "LISAinference/LISAutils.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 5651,
"size": 23167
} |
#pragma once
#define NOMINMAX
#include <windows.h>
#include <unknwn.h>
#include <restrictederrorinfo.h>
#include <hstring.h>
#include <MemoryBuffer.h>
// DirectX
#include <windows.ui.xaml.media.dxinterop.h>
#include <d3d11.h>
#include <dxgi.h>
#include <dxgi1_2.h>
#include <dxgi1_3.h>
#include <DirectXMath.h>
// C++/WinRT
#include "winrt/Microsoft.UI.Xaml.Automation.Peers.h"
#include "winrt/Microsoft.UI.Xaml.Controls.Primitives.h"
#include "winrt/Microsoft.UI.Xaml.Media.h"
#include "winrt/Microsoft.UI.Xaml.XamlTypeInfo.h"
#include "winrt/Windows.ApplicationModel.h"
#include "winrt/Windows.ApplicationModel.Activation.h"
#include "winrt/Windows.ApplicationModel.Resources.h"
#include "winrt/Windows.Foundation.h"
#include "winrt/Windows.Foundation.Collections.h"
#include "winrt/Windows.Globalization.NumberFormatting.h"
#include "winrt/Windows.Media.h"
#include "winrt/Windows.Media.Audio.h"
#include "winrt/Windows.Media.MediaProperties.h"
#include "winrt/Windows.Media.Render.h"
#include "winrt/Windows.Storage.h"
#include "winrt/Windows.Storage.Pickers.h"
#include "winrt/Windows.Storage.Streams.h"
#include "winrt/Windows.System.Threading.h"
#include "winrt/Windows.UI.Core.h"
#include "winrt/Windows.UI.Xaml.h"
#include "winrt/Windows.UI.Xaml.Controls.h"
#include "winrt/Windows.UI.Xaml.Controls.Primitives.h"
#include "winrt/Windows.UI.Xaml.Data.h"
#include "winrt/Windows.UI.Xaml.Documents.h"
#include "winrt/Windows.UI.Xaml.Interop.h"
#include "winrt/Windows.UI.Xaml.Input.h"
#include "winrt/Windows.UI.Xaml.Markup.h"
#include "winrt/Windows.UI.Xaml.Navigation.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <stdexcept>
#include <thread>
#include <sstream>
#include <gsl/gsl>
| {
"alphanum_fraction": 0.7688984881,
"avg_line_length": 28.9375,
"ext": "h",
"hexsha": "d82c15c5518716692a12877a45c0534490d84cb5",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "a5171858351c19cf09001fbd22c08723a7a4b126",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "greg904/gc8",
"max_forks_repo_path": "gc8/Gc8/pch.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "a5171858351c19cf09001fbd22c08723a7a4b126",
"max_issues_repo_issues_event_max_datetime": "2020-07-29T08:21:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-04-12T21:20:58.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "greg904/gc8",
"max_issues_repo_path": "gc8/Gc8/pch.h",
"max_line_length": 57,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a5171858351c19cf09001fbd22c08723a7a4b126",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "greg904/gc8",
"max_stars_repo_path": "gc8/Gc8/pch.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 464,
"size": 1852
} |
/*
* Copyright 2012-2016 M. Andersen and L. Vandenberghe.
* Copyright 2010-2011 L. Vandenberghe.
* Copyright 2004-2009 J. Dahl and L. Vandenberghe.
*
* This file is part of CVXOPT.
*
* CVXOPT is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* CVXOPT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cvxopt.h"
#include <complex.h>
#include "misc.h"
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <time.h>
PyDoc_STRVAR(gsl__doc__,"Random Module.");
static unsigned long seed = 0;
static const gsl_rng_type *rng_type;
static gsl_rng *rng;
static char doc_getseed[] =
"Returns the seed value for the random number generator.\n\n"
"getseed()";
static PyObject * getseed(PyObject *self)
{
return Py_BuildValue("l",seed);
}
static char doc_setseed[] =
"Sets the seed value for the random number generator.\n\n"
"setseed(value = 0)\n\n"
"ARGUMENTS\n"
"value integer seed. If the value is 0, then the system clock\n"
" measured in seconds is used instead";
static PyObject * setseed(PyObject *self, PyObject *args)
{
unsigned long seed_ = 0;
time_t seconds;
if (!PyArg_ParseTuple(args, "|l", &seed_))
return NULL;
if (!seed_) {
time(&seconds);
seed = (unsigned long)seconds;
}
else seed = seed_;
return Py_BuildValue("");
}
static char doc_normal[] =
"Randomly generates a matrix with normally distributed entries.\n\n"
"normal(nrows, ncols=1, mean=0, std=1)\n\n"
"PURPOSE\n"
"Returns a matrix with typecode 'd' and size nrows by ncols, with\n"
"its entries randomly generated from a normal distribution with mean\n"
"m and standard deviation std.\n\n"
"ARGUMENTS\n"
"nrows number of rows\n\n"
"ncols number of columns\n\n"
"mean approximate mean of the distribution\n\n"
"std standard deviation of the distribution";
static PyObject *
normal(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *obj;
int i, nrows, ncols = 1;
double m = 0, s = 1;
char *kwlist[] = {"nrows", "ncols", "mean", "std", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "i|idd", kwlist,
&nrows, &ncols, &m, &s)) return NULL;
if (s < 0.0) PY_ERR(PyExc_ValueError, "std must be non-negative");
if ((nrows<0) || (ncols<0)) {
PyErr_SetString(PyExc_TypeError, "dimensions must be non-negative");
return NULL;
}
if (!(obj = Matrix_New(nrows, ncols, DOUBLE)))
return PyErr_NoMemory();
gsl_rng_env_setup();
rng_type = gsl_rng_default;
rng = gsl_rng_alloc (rng_type);
gsl_rng_set(rng, seed);
for (i = 0; i < nrows*ncols; i++)
MAT_BUFD(obj)[i] = gsl_ran_gaussian (rng, s) + m;
seed = gsl_rng_get (rng);
gsl_rng_free(rng);
return (PyObject *)obj;
}
static char doc_uniform[] =
"Randomly generates a matrix with uniformly distributed entries.\n\n"
"uniform(nrows, ncols=1, a=0, b=1)\n\n"
"PURPOSE\n"
"Returns a matrix with typecode 'd' and size nrows by ncols, with\n"
"its entries randomly generated from a uniform distribution on the\n"
"interval (a,b).\n\n"
"ARGUMENTS\n"
"nrows number of rows\n\n"
"ncols number of columns\n\n"
"a lower bound\n\n"
"b upper bound";
static PyObject *
uniform(PyObject *self, PyObject *args, PyObject *kwrds)
{
matrix *obj;
int i, nrows, ncols = 1;
double a = 0, b = 1;
char *kwlist[] = {"nrows", "ncols", "a", "b", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwrds, "i|idd", kwlist,
&nrows, &ncols, &a, &b)) return NULL;
if (a>b) PY_ERR(PyExc_ValueError, "a must be less than b");
if ((nrows<0) || (ncols<0))
PY_ERR_TYPE("dimensions must be non-negative");
if (!(obj = (matrix *)Matrix_New(nrows, ncols, DOUBLE)))
return PyErr_NoMemory();
gsl_rng_env_setup();
rng_type = gsl_rng_default;
rng = gsl_rng_alloc (rng_type);
gsl_rng_set(rng, seed);
for (i= 0; i < nrows*ncols; i++)
MAT_BUFD(obj)[i] = gsl_ran_flat (rng, a, b);
seed = gsl_rng_get (rng);
gsl_rng_free(rng);
return (PyObject *)obj;
}
static PyMethodDef gsl_functions[] = {
{"getseed", (PyCFunction)getseed, METH_VARARGS|METH_KEYWORDS, doc_getseed},
{"setseed", (PyCFunction)setseed, METH_VARARGS|METH_KEYWORDS, doc_setseed},
{"normal", (PyCFunction)normal, METH_VARARGS|METH_KEYWORDS, doc_normal},
{"uniform", (PyCFunction)uniform, METH_VARARGS|METH_KEYWORDS, doc_uniform},
{NULL} /* Sentinel */
};
#if PY_MAJOR_VERSION >= 3
static PyModuleDef gsl_module = {
PyModuleDef_HEAD_INIT,
"gsl",
gsl__doc__,
-1,
gsl_functions,
NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC PyInit_gsl(void)
{
PyObject *m;
if (!(m = PyModule_Create(&gsl_module))) return NULL;
if (import_cvxopt() < 0) return NULL;
return m;
}
#else
PyMODINIT_FUNC initgsl(void)
{
PyObject *m;
m = Py_InitModule3("cvxopt.gsl", gsl_functions, gsl__doc__);
if (import_cvxopt() < 0) return;
}
#endif
| {
"alphanum_fraction": 0.6781673159,
"avg_line_length": 26.4264705882,
"ext": "c",
"hexsha": "d44f7ea6ef3ab62c3736b41a7c5f1b9d2e3dd82b",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-03-31T07:08:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-14T22:02:07.000Z",
"max_forks_repo_head_hexsha": "10eee90b759638d5c54ba19994ae8e36e90e12b8",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Hap-Hugh/quicksel",
"max_forks_repo_path": "src/cpp/qpsolver/cvxopt/src/C/gsl.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "10eee90b759638d5c54ba19994ae8e36e90e12b8",
"max_issues_repo_issues_event_max_datetime": "2020-09-24T08:37:18.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-09-02T15:25:39.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Hap-Hugh/quicksel",
"max_issues_repo_path": "src/cpp/qpsolver/cvxopt/src/C/gsl.c",
"max_line_length": 75,
"max_stars_count": 15,
"max_stars_repo_head_hexsha": "10eee90b759638d5c54ba19994ae8e36e90e12b8",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Hap-Hugh/quicksel",
"max_stars_repo_path": "src/cpp/qpsolver/cvxopt/src/C/gsl.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-16T14:23:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-07T16:32:53.000Z",
"num_tokens": 1591,
"size": 5391
} |
/*
Program to trace back particles in a halo to the initial conditions
and/or to print distance of particles from the Halo center
requires gadget file at z=0 and initial conditions
requires center of mass (can be read in from a file created with virialmass.c)
gcc -std=c99 -lm -lgsl -lgslcblas -o trhalo trhalo.c libgad-gcc.o lmfit-2.2/lmmin.o lmfit-2.2/lm_eval.o KdTree.o
gcc -std=c99 -lm -lgsl -lgslcblas -o trhalo trhalo.c -lgad-altix KdTree.o
gcc -std=c99 -lm -lgsl -lgslcblas -o ../bin/altix/trhalo-nopot trhalo.c -lgad-altix-nopot KdTree.o -DNOPOT
stan:
gcc -lm -lgsl -lgslcblas -o ~/bin/trhalo trhalo.c -lgad-stan stan/KdTree.o
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
#include "libgad.h"
#include "KdTree.h"
#include "./lmmin.h"
#include "./lm_eval.h"
#define PI 3.14159265358979323846
#define GAP2BORDER 16000 //min distance to boarders to ignore periodic boundaries
#define INCLUDE 0 //(friends + INCLUDE*kpc/h) are used to determine CM
#define TRACE_FACTOR 2.0 //TRACE_FACTOR times virial radius will be traced back to IC
#define h0 0.72
#define VIROD 200
#define DIM 512
#define ENVDENSRAD (4000 * h0)
#define MIN(a, b) ((a)<(b)?(a):(b))
#define MAX(a, b) ((a)>(b)?(a):(b))
#define ABS(a) ((a) >= 0 ? (a) : -(a))
#define CMP(a,b) ((a)>(b)?(1):(-1))
#define PB(a,b) ((a)>(b)?(a-b):(a))
#define MOVE(a,b) PB(a+b/2,b)
#define MOVEB(a) MOVE((a),boxsz)
#define MV(a,b) ((a)+(b)/2)%(b)
//#define SQR(x) (x)*(x)
#define SOFTENING 0
#define G 6.6742e-11
#define Msun 1.989e30
#define kpc 3.08567758128e19
#define DEBUG 1
#define VA_USE_PART_TYPE 2
#define CM_USE_PART_TYPE 2
#define INERTIA_USE_PART_TYPE 2
#define kNN 50
double cdens;
struct particle {int ind;float dist;};
clock_t t[2];
void usage()
{
fprintf(stderr,"TrHalo v0.05\n");
fprintf(stderr," -f <snapshot file> -i <IC file> \n");
fprintf(stderr," -m <virialmass file> -n <Halo Number> or -cm <X Y Z>\n");
fprintf(stderr," if you want to search for CM in an area around the given coordinates\n");
fprintf(stderr," add -sr <radius> to include particles for the search with distance to cm < radius\n");
fprintf(stderr," -gr <gridfile> -tf <tracefactor default 2.0>\n");
fprintf(stderr," -jr <print j distribution to file> -cut <create gadget file of the halo>\n");
fprintf(stderr," -pb <force periodic boundary conditions (bitwise)>\n");
fprintf(stderr," -n <name of the halo>\n");
fprintf(stderr," -cid <center on particle with a given ID>\n");
fprintf(stderr," -trid <file with particle IDs to trace>\n");
fprintf(stderr," -r <fraction of virial radius for longest axis of Inertia Tensor>\n");
fprintf(stderr," -ui <bitcode particle types for Inertia Tensor>\n");
fprintf(stderr," -gap <min distance to Box-border for PB>\n");
fprintf(stderr," -mcnt <min particle Count for CM Search>\n");
fprintf(stderr," -sd <search distance>\n");
exit(1);
}
double fit_fct(double t, double *p)
{
return log10((p[0]) / ((t/p[1]) * SQR(1+t/p[1])));
}
// void printout ( int n_par, double* par, int m_dat, double* fvec,
// void *data, int iflag, int iter, int nfev )
// {
// // dummy function to catch fitting output
// }
float step()
{
float tm;
t[1]=clock();
tm=(float)(t[1]-t[0])/CLOCKS_PER_SEC;
t[0]=clock();
return tm;
}
/*
int cmp (struct particle *a, struct particle *b)
{
if (a[0].dist > b[0].dist) return 1; else return -1;
}
*/
int cmp (const void *first, const void *second)
{
struct particle *a = (struct particle*) first;
struct particle *b = (struct particle*) second;
if (a->dist > b->dist) return 1;
else if (a->dist < b->dist) return -1;
else return 0;
}
int cmpind (const void *first, const void *second)
{
struct particle *a = (struct particle*) first;
struct particle *b = (struct particle*) second;
if (a->ind > b->ind) return 1;
else if (a->ind < b->ind) return -1;
else return 0;
}
int compare (float *a, float *b)
{
if (*a > *b) return 1; else return -1;
}
int coord512 (int *result, long index)
{
int c[3];
int i;
result[0]=floor(index%262144/512.0);
result[1]=(index%512);
result[2]=floor(index/262144.0);
for (i=0; i<3; i++)
if ((result[i]<0) || (result[i]>512)) return 1;
return 0;
}
int main (int argc, char *argv[])
{
typedef float fltarr[3];
struct particle *part, *vpart;
gadpart *P;
struct header ic,evolved, out;
FILE *fp;
char vmfile[256],icfile[256],evolvedfile[256],snfile[256],friendsfile[256],idlfile[256],gridfile[256],jrfile[256], gadfile[256], hname[256], parfile[256], idfile[256], datfile[256];
unsigned int numpart=0, nummass=0;
int blocksize,i,j,k,l,m,dum,dum2,tr_halo=0,tr_halo_cnt = 0,id,halo,checknpart,mindum,nhalo,count,notrace=1;
int *tr_halo_id,*tr_halo_i,*tr_halo_i_dum, ca[3], size[3];
// fltarr *pos_ev,*pos_ic,*vel, *outpos, *outvel;
fltarr *pos_ic;
fltarr shift, diff;
float *mass_ev, *mass_dum,*mass_ic, *outmass,dist,maxdist,*distance,halomass,halorad, halolmd;
double posdum,max[3],min[3],srad=0, icmin[3], icmax[3], scm[3];
double lmd,vcm[3]={0,0,0},jcm[3]={0,0,0},J[3]={0,0,0}, torq[3],rdum[3], vdum[3], massdum;
int *id_ev, *outid,*iclus, halonpart;
float tm,linkle,od, tr_factor;
double mdens,boxsz,cm[3]={0,0,0}, expcm[3], masstot, gridsize, rlog[50], p[50], err[50], d, rad_ratio=0.3;
short pb[3]={0,0,0};
int minbox[3], maxbox[3], szbox[3], ***grid, boxind[3], alignf, mincnt=100;
int nfun, npar, indmax[3], indmin[3], dojr=0, docut=0, vcnt, starsonly=0, dmonly=1, doidl=1, start, end, use_inertia=0, use_va, use_cm, cmset=0, nopb=0, cid=0, traceid=0, gal_all=0, addbh=0, printcm=0;
double par[2],ddum, dx512, ddum1, totj, envdens, sqrenvdensrad, bgdens, sfl=SOFTENING, meff, halfmrad, effrad;
double GAP=GAP2BORDER, searchdist=0;
t[0]=clock();
dx512=72000.0/512.0;
if (DEBUG) printf("DEBUG-Output enabled\n");fflush(stdout);
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//filenames are ignored if given as command line parameters in the same order
strcpy(vmfile,"<none>");
strcpy(gridfile,"<none>");
strcpy(parfile,"halodata.txt");
strcpy(evolvedfile,"");
strcpy(icfile,"");
strcpy(idlfile,"<none>");
tr_factor=TRACE_FACTOR;
use_inertia=INERTIA_USE_PART_TYPE;
use_va=VA_USE_PART_TYPE;
use_cm=CM_USE_PART_TYPE;
// tr_halo=123;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
i=1;
if (1==argc) usage();
while (i<argc)
{
if (!strcmp(argv[i],"-f"))
{
i++;
strcpy(evolvedfile,argv[i]);
i++;
}
else if (!strcmp(argv[i],"-i"))
{
i++;
strcpy(icfile,argv[i]);
i++;
notrace=0;
}
else if (!strcmp(argv[i],"-m"))
{
i++;
strcpy(vmfile,argv[i]);
i++;
}
else if (!strcmp(argv[i],"-idl"))
{
i++;
strcpy(idlfile,argv[i]);
i++;
}
else if (!strcmp(argv[i],"-trid"))
{
i++;
strcpy(idfile,argv[i]);
traceid=1;
i++;
}
else if (!strcmp(argv[i],"-n"))
{
i++;
strcpy(hname,argv[i]);
i++;
}
else if (!strcmp(argv[i],"-gr"))
{
i++;
strcpy(gridfile,argv[i]);
i++;
}
else if (!strcmp(argv[i],"-n"))
{
i++;
tr_halo=atoi(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-sr"))
{
i++;
srad=atof(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-cid"))
{
i++;
cid=atoi(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-gap"))
{
i++;
GAP=atof(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-r"))
{
i++;
rad_ratio=atof(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-ui"))
{
i++;
use_inertia=atoi(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-uva"))
{
i++;
use_va=atoi(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-ucm"))
{
i++;
use_cm=atoi(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-use"))
{
i++;
use_cm=atoi(argv[i]);
use_va=use_cm;
use_inertia=use_cm;
i++;
}
else if (!strcmp(argv[i],"-soft"))
{
i++;
sfl=atof(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-sd"))
{
i++;
searchdist=atof(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-mcnt"))
{
i++;
mincnt=atoi(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-jr"))
{
i++;
dojr=1;
}
else if (!strcmp(argv[i],"-bh"))
{
i++;
addbh=1;
}
else if (!strcmp(argv[i],"-noidl"))
{
i++;
doidl=0;
}
else if (!strcmp(argv[i],"-pcm"))
{
i++;
printcm=1;
}
else if (!strcmp(argv[i],"-nopb"))
{
i++;
nopb=1;
}
else if (!strcmp(argv[i],"-ga"))
{
i++;
gal_all=1;
}
else if (!strcmp(argv[i],"-cut"))
{
i++;
docut=1;
}
else if (!strcmp(argv[i],"-pb"))
{
i++;
dum=atoi(argv[i]);
for (j=0; j<3; j++) if (dum&(1<<j)) pb[k]=1;
i++;
}
else if (!strcmp(argv[i],"-stars"))
{
i++;
starsonly=1;
}
else if (!strcmp(argv[i],"-all"))
{
i++;
dmonly=0;
}
else if (!strcmp(argv[i],"-tr"))
{
i++;
notrace=1;
}
else if (!strcmp(argv[i],"-tf"))
{
i++;
tr_factor=atof(argv[i]);
i++;
}
else if (!strcmp(argv[i],"-cm"))
{
i++;
cm[0]=atof(argv[i++]);
cm[1]=atof(argv[i++]);
cm[2]=atof(argv[i++]);
cmset=1;
} else {
usage();
}
}
if (strcmp(hname,""))
{
sprintf( idlfile, "%s.idl", hname);
sprintf(gridfile, "%s.gr", hname);
sprintf( datfile, "%s.dat", hname);
sprintf( jrfile, "%s.jr", hname);
sprintf( gadfile, "%s.gad", hname);
}
if (!traceid)
{
// auxiliary settings for fitting:
lm_control_type control;
lm_data_type data;
lm_initialize_control(&control);
data.user_func = fit_fct;
data.user_t = rlog;
data.user_y = p;
//---------------------------------------------------
/*
fp=fopen(evolvedfile,"r");
fread(&blocksize,sizeof(int),1,fp);
fread(&evolved,sizeof(struct header),1,fp); //read header of evolved gadget file
fread(&blocksize,sizeof(int),1,fp);
boxsz=evolved.boxsize;
for (i=0; i<6; i++)
{
numpart+=evolved.npart[i];
if ((evolved.npart[i]!=0) || (evolved.massarr[i]==0)) nummass+=evolved.npart[i];
}
pos_ev =(fltarr *)malloc(sizeof(fltarr)*numpart+addbh);
vel =(fltarr *)malloc(sizeof(fltarr)*numpart+addbh);
id_ev =(int *) malloc(sizeof(int)*numpart+addbh);
mass_dum=(float *) malloc(sizeof(float)*nummass+addbh);
mass_ev=(float *) malloc(sizeof(float)*numpart+addbh);
fread(&blocksize,sizeof(int),1,fp); //read particle positions of evolved snapshot file
fread(&P[0].pos,sizeof(fltarr),numpart,fp);
fread(&blocksize,sizeof(int),1,fp);
fread(&blocksize,sizeof(int),1,fp); //skip velocities
fread(&P[0].vel,sizeof(fltarr),numpart,fp);
fread(&blocksize,sizeof(int),1,fp);
fread(&blocksize,sizeof(int),1,fp); //read particle ids of evolved snapshot file
fread(&P[0].id,sizeof(int),numpart,fp);
fread(&blocksize,sizeof(int),1,fp);
if (nummass>0)
{
fread(&blocksize,sizeof(int),1,fp); //read particle masses of evolved snapshot file
fread(&mass_dum[0],sizeof(float),nummass,fp);
fread(&blocksize,sizeof(int),1,fp);
}
fclose(fp);
*/
numpart= readgadget_part(evolvedfile, &evolved, &P);
if (numpart==0)
{
extern int libgaderr;
fprintf(stderr,"LibGad Error Code: %d\n", libgaderr);
exit(libgaderr);
}
masstot=0;
j=0;
for (i=0; i< numpart; i++)
{
masstot+=P[i].mass;
if ((cid) && P[i].id==cid )
{
for (j=0; j<3; j++) cm[j]=P[i].pos[j];
}
}
mdens=masstot/pow(evolved.boxsize*evolved.time,3);
cdens=(2.78e-8);
cdens=cdens*(evolved.omegal+evolved.omega0*pow(evolved.time,-3));
bgdens=cdens*evolved.omega0;
dum=0;
for (i=0; i<5; i++)
{
dum+=evolved.npart[i];
if (DEBUG)
if (evolved.npart[i]>0) printf("%d %f %f\n", i, P[dum-1].mass, P[dum].mass);
}
if (DEBUG) printf("readin evolved %.2f\n",step());fflush(stdout);
printf("snapshot %s\n", evolvedfile);
printf("ucm %d ui %d uva %d\n", use_cm, use_inertia, use_va);
if (strcmp(vmfile,"<none>")!=0)
{
fp=fopen(vmfile,"r"); //read virialmassfile
fscanf(fp,"%d %d %s %s", &checknpart, &nhalo, &snfile, &friendsfile);
if (strcmp(snfile,evolvedfile)!=0)
{
printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
printf("Warning: Evolved Snapshotfile and the one specified in %s are not identical!\n",vmfile);
printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
}
if (tr_halo > nhalo)
{
fprintf(stderr,"Illegal Halo index\n");
exit(2);
}
j=1;
while (j < tr_halo)
{
fscanf(fp,"%d %f %d %f %f %f %f %f", &j, &halomass, &halonpart, &halolmd, &halorad, &cm[0], &cm[1], &cm[2]);
}
fclose(fp);
}
if ( (!cm[0]) && (!cm[1]) && (!cm[2]) && !(cmset) )
{
fprintf(stderr,"Neither -m nor -cm option used\n");
exit(3);
}
if ( (!cm[0]) && (!cm[1]) && (!cm[2]))
{
nopb=1;
// tr_factor=1.0;
}
/*
printf("n %d\n",j);
printf("cm %f %f %f\n",cm[0], cm[1], cm[2]);
printf("friendsfile %s\n",friendsfile);
printf("snfile %s\n",snfile);
printf("n %d\n",tr_halo);
*/
tr_halo_cnt=0;
masstot=0;
if (GAP==GAP2BORDER)
{
GAP = evolved.boxsize/4.;
}
for (k=0; k<3; k++) //check whether periodic boundaries are needed
{
if ( ((cm[k]<GAP) || (cm[k]>(evolved.boxsize-GAP) || pb[k])) && (!nopb))
{
pb[k]=1;
cm[k]=MOVE(cm[k],boxsz);
}
}
if (DEBUG) printf("search center \n");fflush(stdout);
for (i=0; i<3; i++) scm[i]=cm[i];
if (srad>0)
{
tr_halo_id=(int *)malloc(numpart*sizeof(int));
tr_halo_i =(int *)malloc(numpart*sizeof(int));
maxdist=srad*srad;
if (dmonly) {start=evolved.npart[0]; end=evolved.npart[0]+evolved.npart[1];}
else if (starsonly) {start=evolved.npart[0]+evolved.npart[1]+evolved.npart[2]+evolved.npart[3]; end=start+evolved.npart[4];}
else {start=0; end=numpart;}
{start=0; end=numpart;}
if ((end-start)<mincnt) exit(2);
while (tr_halo_cnt<mincnt)
{
tr_halo_cnt=0;
for (i=start; i < end; i++)
{
dist=0;
for (j=0; j<3; j++)
if (pb[j]) dist+=pow(MOVE(P[i].pos[j],boxsz)-cm[j],2);
else dist+=pow(P[i].pos[j]-cm[j],2);
if ((dist<maxdist) && ( (1<<P[i].type) & use_cm) )
{
tr_halo_id[tr_halo_cnt]=P[i].id;
tr_halo_i[tr_halo_cnt++]=i;
}
}
maxdist*=4;
}
printf("Number of particles for CM calculation: %d\n",tr_halo_cnt );fflush(stdout);
tr_halo_id=realloc(tr_halo_id,sizeof(int)*tr_halo_cnt);
tr_halo_i =realloc(tr_halo_i ,sizeof(int)*tr_halo_cnt);
}
/*
for (i=0; i < checknpart; i++)
{
dum=1;
for (k=0, k<3; k++)
{
if (pb[k])
{
posdum=(MOVE(P[i].pos[k],boxsz));
if ( (posdum < (MOVE(cm[k],boxsz)-GAP)) || (posdum > (MOVE(cm[k],boxsz)+GAP )) ) dum=0;
} else {
posdum=P[i].pos[k];
if ( (posdum < (cm[k]-GAP)) || (posdum > (cm[k]+GAP)) ) dum=0;
}
}
if (dum)
{
tr_halo_id[tr_halo_cnt]=P[i].id;
tr_halo_i[tr_halo_cnt++]=i;
}
}
tr_halo_id=realloc(tr_halo_id,sizeof(int)*tr_halo_cnt);
tr_halo_i =realloc(tr_halo_i ,sizeof(int)*tr_halo_cnt);
// for (j=0; j<3; j++) printf("min %f max %f cm %f\n", min[j],max[j],cm[j]);
// pos_dum=(fltarr *)malloc(sizeof(fltarr)*numpart);
tr_halo_i_dum =(int *)malloc(sizeof(int)*numpart);
count=0;
for (i=0; i < numpart; i++) //
{
dum=1;
for (j=0; j<3; j++)
{
if (pb[j])
{
if (((MOVE(P[i].pos[j],boxsz)+INCLUDE) < min[j]) || ((MOVE(P[i].pos[j],boxsz)-INCLUDE) > max[j])) dum=0;
}
else {if (((P[i].pos[j]+INCLUDE) < min[j]) || ((P[i].pos[j]-INCLUDE) > max[j])) dum=0;}
}
if (dum)
{
// for (j=0; j<3; j++) pos_dum[count][j]=P[i].pos[j];
tr_halo_i_dum[count]=i;
count++;
}
}
maxdist=0;
for (j=0; j<3; j++)
{
//if (pb[j]) maxdist+=pow((MOVE(max[j],boxsz)-MOVE(min[j],boxsz))/2,2);else
maxdist+=pow((max[j]-min[j])/2,2);
}
maxdist=sqrt(maxdist)*2;
*/
if (srad>0)
{
double cvel[3]={0.,0.,0.};
maxdist=srad;
count=tr_halo_cnt;
do
{
// printf("Center of Mass for halo %d : %f %f %f particles: %d rad %f\n ", tr_halo, cm[0], cm[1], cm[2],count,maxdist);
//pos_dum=realloc(pos_dum,sizeof(fltarr)*count);
//tr_halo_i_dum=realloc(tr_halo_i_dum,sizeof(int)*count);
//printf("ja\n");fflush(stdout);
masstot=0;
maxdist*=0.92;
for (j=0; j<3; j++){rdum[j]=cm[j];}
cm[0]=0;
cm[1]=0;
cm[2]=0;
// printf("%d\n",count);
for (i=0; i < count; i++)
{
for (j=0; j<3; j++)
{
if (pb[j]) cm[j]+=MOVE(P[tr_halo_i[i]].pos[j],boxsz)*P[tr_halo_i[i]].mass;
else cm[j]+=P[tr_halo_i[i]].pos[j]*P[tr_halo_i[i]].mass;
}
masstot+=P[tr_halo_i[i]].mass;
// if (i<10)
// printf("%f %f %f !\n", P[tr_halo_i[i]].pos[0]*P[tr_halo_i[i]].mass, cm[1], cm[2]);fflush(stdout);
//printf("%d\n",i);fflush(stdout);
}
// printf("%f %f %f !\n", cm[0], cm[1], cm[2]);fflush(stdout);
for (j=0; j<3; j++) cm[j]=cm[j]/(masstot);
dum=0;
for (i=0; i < count; i++) //
{
dist=0;
for (j=0; j<3; j++)
{
if (pb[j]) dist += pow((MOVE(P[tr_halo_i[i]].pos[j],boxsz)-cm[j]),2);
else dist += pow((P[tr_halo_i[i]].pos[j]-cm[j]),2);
}
dist=sqrt(dist);
if (dist < maxdist)
{
// for (j=0; j<3; j++) pos_dum[dum][j]=pos_dum[i][j];
tr_halo_i[dum]=tr_halo_i[i];
dum++;
}
}
count=dum;
if ((count<50) && (cvel[0]==0))
{
masstot=0;
for (i=0; i< count; i++)
{
for (j=0; j<3; j++)
{
cvel[j]+=P[tr_halo_i[i]].vel[j]*P[tr_halo_i[i]].mass;
}
masstot+= P[tr_halo_i[i]].mass;
}
for (j=0; j<3; j++) cvel[j]=cvel[j]/(masstot);
printf("%d particles for cvel-calculation\n",count);
printf("Central Velocity %10.4f %10.4f %10.4f\n", cvel[0], cvel[1], cvel[2] );
}
// printf("count: %d cm: %f %f %f change: %f% f% f rad: %f \n",count, cm[0],cm[1], cm[2], cm[0]-rdum[0], cm[1]-rdum[1], cm[2]-rdum[2], maxdist);
} while (count>5);
if (addbh)
{
if (use_cm!=16) printf("Black holed not centered on stars, are you sure? (think about using -ucm 16)\n");
for (j=0; j<3; j++)
{
P[numpart].pos[j]=cm[j];
P[numpart].vel[j]=cvel[j];
}
P[numpart].mass=P[0].mass;
P[numpart].id=numpart+1;
out=evolved;
out.npart[5]++;
out.nall[5]++;
char outfilename[256];
sprintf(outfilename,"%s-bh", evolvedfile);
// writegadget(outfilename, out, pos_ev, vel, id_ev, mass_ev);
writegadget_part(outfilename, out, P);
}
}
/*
//printf("CM found %.2f now sort by distance and calculate virial radius+mass\n",step());
// free(pos_dum);
free(tr_halo_i_dum);
part=(struct particle *)malloc(sizeof(struct particle)*tr_halo_cnt);
for (i=0; i< tr_halo_cnt; i++)
{
dist=0;
for (j=0; j<3; j++)
{
if (pb[j]) dist += pow((MOVE(P[tr_halo_i[i]].pos[j],boxsz)-cm[j]),2);
else dist += pow((P[tr_halo_i[i]].pos[j]-cm[j]),2);
}
part[i].dist=sqrt(dist);
//part[i].mass=P[tr_halo_i[i]].mass;
//part[i].id=P[tr_halo_i[i]].id;
part[i].ind=tr_halo_i[i];
}
qsort(&part[0],tr_halo_cnt,sizeof(struct particle),(void *)cmp);
masstot=0;
i=0;
od=201;
while (((od > 200) && (i<tr_halo_cnt)) || (i<11)) //Add mass until overdensity drops below 200 or all friends are examined
{
masstot+=P[part[i].ind].mass;
od=masstot/(pow(part[i].dist*evolved.time,3)*(4.0/3.0)*PI*mdens);
//printf("i %d od %f\n",i,od);
i++;
}
masstot-=P[part[i-1].ind].mass;
*/
// if (halorad!=0) maxdist=halorad; else maxdist=1000;
if (DEBUG) printf("Determine Virial Radius \n");fflush(stdout);
maxdist=GAP*GAP;
effrad=30*evolved.hubparam;
meff=0;
sqrenvdensrad=SQR(ENVDENSRAD);
part=(struct particle *)malloc(sizeof(struct particle)*numpart);
vpart=(struct particle *)malloc(sizeof(struct particle)*numpart);
count=0;
envdens=0;
for (i=0; i< numpart; i++)
{
dist=0;
for (j=0; j<3; j++)
{
if (pb[j]) dist += pow((MOVE(P[i].pos[j],boxsz)-cm[j]),2);
else dist += pow((P[i].pos[j]-cm[j]),2);
if (dist>maxdist) break;
}
if (dist < sqrenvdensrad)
{
envdens+=P[i].mass;
}
if (dist < maxdist)
{
dist=sqrt(dist);
part[count].dist=dist;
part[count++].ind=i;
if (dist < effrad)
{
dum2=0;
for (m=0; m<6; m++)
{
dum2+=evolved.npart[m];
if (dum2>i) break;
}
if ((1<<m) & use_cm)
{
meff += P[i].mass;
}
}
}
}
if (use_cm==1) printf("Gas mass inside 30 kpc %f\n", meff);
if (use_cm==16) printf("Stellar mass inside 30 kpc %f\n", meff);
if (use_cm==17) printf("Baryonic mass inside 30 kpc %f\n", meff);
qsort(&part[0],count,sizeof(struct particle),(void *)cmp); //sort particles by distance to CM of halo
masstot=0;
i=0;
od=201;
double dm_mass=0;
double b_mass=0;
double gas_mass=0;
double star_mass=0;
while ((od > VIROD) || (i<5)) //Add mass until overdensity drops below 200
{
int ind = part[i].ind;
masstot+=P[part[i].ind].mass;
if ((P[ind].type == 0) ||(P[ind].type == 4))
{
b_mass += P[ind].mass;
if (P[ind].type == 0) gas_mass += P[ind].mass;
else star_mass += P[ind].mass;
} else
{
dm_mass+= P[ind].mass;
}
od=masstot/(pow(part[i].dist*evolved.time,3)*(4.0/3.0)*PI*cdens);
//printf("i %d od %f\n",i,od);
vpart[i].dist=part[i].dist;
vpart[i].ind=part[i].ind;
i++;
if (i > count)
{
fp=fopen("error_trhalo.dat","a");
fprintf(fp,"Halo %d is making trouble\n",tr_halo);
fclose(fp);
printf("halo %d is making trouble\n",tr_halo);
break;
}
if (i>numpart) {i--;break;}
if ((part[i].dist > searchdist) && (searchdist)) break;
}
if (DEBUG) printf("Virial Radius found count %d\n", count);fflush(stdout);
masstot-=P[part[i-1].ind].mass;
if ((P[part[i-1].ind].type == 0) ||(P[part[i-1].ind].type == 4))
{
b_mass -= P[part[i-1].ind].mass;
} else
{
dm_mass-= P[part[i-1].ind].mass;
}
dum=i-1;
vcnt=i;
halorad=part[vcnt-1].dist;
envdens=envdens/((4.0/3.0)*PI*pow(ENVDENSRAD*evolved.time,3));
vpart=realloc(vpart,sizeof(struct particle)*vcnt);
qsort(&vpart[0],vcnt,sizeof(struct particle),(void *)cmpind);
{
gadpart_dist *tmppart= malloc (sizeof(gadpart_dist) * vcnt);
for (i=0; i< vcnt; i++)
{
tmppart[i].dist=part[i].dist;
tmppart[i].part=P[part[i].ind];
}
double par[2]={0.005,20};
double rcs;
double conc = nfwfit(par, tmppart, vcnt, halorad, sfl, &rcs);
printf("NFW: %f %f\nc %f\nRs %f\n", par[0], par[1], conc, rcs);
free(tmppart);
}
for (j=0; j<3; j++)
{
if (pb[j])
{
cm[j]=MOVE(cm[j],boxsz);
printf("!!!periodic boundaries used in Dimension %d !!!\n",j);
}
}
printf("\n halo %5d consists of %5d particles, virial Mass/h %5.2f\n rad %5.2f od %4.2f\n",tr_halo,vcnt,masstot,part[i-1].dist,od);
printf(" Baryonic Mass/h %5.2f\n DM Mass/h %5.2f \n\n",b_mass, dm_mass);
printf("Center of Mass: %10.4f %10.4f %10.4f\n",cm[0] ,cm[1] ,cm[2]);
printf("Shift: %10.4f %10.4f %10.4f\n",cm[0]-scm[0],cm[1]-scm[1],cm[2]-scm[2]);
if (printcm)
{
FILE *filep= fopen("cm.dat", "w");
fprintf(filep, "%f %f %f\n",cm[0],cm[1],cm[2]);
fclose(filep);
}
printf("particles in box: %d\n",count);
printf("Environmental Density (R = %f ): %g\n", ENVDENSRAD,(envdens/bgdens)-1);
if (DEBUG) printf("... \n");fflush(stdout);
tr_halo_id=(int *)malloc(count*sizeof(int));
tr_halo_i =(int *)malloc(count*sizeof(int));
tr_halo_cnt=0;
if (docut)
{
gadpart *OUT= (gadpart * ) malloc (sizeof(gadpart)*vcnt);
/* outpos =(fltarr *)malloc(sizeof(fltarr)*vcnt);
outvel =(fltarr *)malloc(sizeof(fltarr)*vcnt);
outid =(int *)malloc(sizeof(int)*vcnt);
outmass =(float *)malloc(sizeof(float)*vcnt);
*/
out=evolved;
for (i=0; i<6; i++)
{
out.npart[i]=0;
out.nall[i]=0;
}
i=0;
while (i<vcnt)
{
dist=vpart[i].dist;
k=vpart[i].ind;
OUT[i]= P[k];
for (j=0; j<3; j++)
{
if (pb[j]) OUT[i].pos[j]=MOVEB(P[k].pos[j])-MOVEB(cm[j]);
else OUT[i].pos[j]=P[k].pos[j]-cm[j];
// OUT[i].vel[j]=P[k].vel[j];
}
/*
for (l=0; l<6; l++)
{
dum+=evolved.npart[l];
if (k<dum) break;
}
*/
l = P[k].type;
out.npart[l]++;
out.nall[l]++;
i++;
}
// writegadget(gadfile, out, outpos, outvel, outid, outmass);
if (DEBUG) printf("writing... \n");fflush(stdout);
writegadget_part(gadfile, out, OUT);
free(OUT);
/*
free(outpos);
free(outvel);
free(outid);
free(outmass);
*/
if (DEBUG) printf("outputfile written... \n");fflush(stdout);
}
maxdist=halorad*tr_factor;
double hmeff=0;
double galmass=0;
double gasmass=0;
double DMmass=0;
double innertotm=0;
double gsfr=0;
double meanage=0;
int nstars_gal=0;
dist=0;
i=0;
for (j=0; j<50; j++)
{
p[j]=0;
err[j]=0;
rlog[j]=0;
}
masstot=0;
while ((dist<maxdist) && (i<=numpart))
{
dist=part[i].dist;
dum2=0;
for (m=0; m<6; m++)
{
dum2+=evolved.npart[m];
if (dum2>part[i].ind) break;
}
if ((dist<halorad) && (m==1) && (dist>sfl))
{
d=log10(dist);
j=floor(d/(log10(halorad)/50));
err[j]++;
p[j]+=P[part[i].ind].mass;
}
if ( ((1<<m) & use_cm) && (hmeff < (meff/2.0)) )
{
hmeff+=P[part[i].ind].mass;
effrad=dist;
}
if ((dist <= (halorad * 0.1)) )
{
innertotm+= P[part[i].ind].mass;
if (m==4)
{
galmass+= P[part[i].ind].mass;
double redsh = (1/P[part[i].ind].stellarage) - 1;
double sage = TIMEDIFF(redsh, (1/evolved.time)-1 );
meanage += sage;
nstars_gal++;
}
else if (m==0)
{
gasmass+= P[part[i].ind].mass;
gsfr+= P[part[i].ind].sph->sfr;
}
else if (m==1) DMmass+= P[part[i].ind].mass;
}
i++;
}
meanage /= nstars_gal;
double innerdens=innertotm/(pow((halorad * 0.1)*evolved.time,3)*(4.0/3.0)*PI);
printf("hmeff: %f effrad: %f\n", hmeff, effrad);
printf("Galaxy mass (M_star < 10 %% Rvir): %f \n", galmass);
printf("mean age: %g \n", meanage);
printf("SFR (< 10 %% Rvir): %g \n", gsfr);
printf("specific SFR (< 10 %% Rvir): %g \n", gsfr / galmass);
printf("Gas mass (M_gas < 10 %% Rvir): %f \n", gasmass);
printf("darkmatter mass (M_gas < 10 %% Rvir): %f \n", DMmass);
printf("Total mass < 10 %% Rvir: %f \n", innertotm);
printf("overdensity < 10 %% Rvir: %g\n", innerdens/bgdens - 1);
printf("density < 10 %% Rvir: %g\n", innerdens);
if (DEBUG) printf("lambda calculation: \n");fflush(stdout);
nfun=0;
k=0;
/*fitting
d=log10(halorad)/50;
for (j=0; j<50; j++)
{
if (err[j]!=0)
{
err[nfun]=(1/(sqrt(err[j])));
// err[nfun]=(1/((err[j])));
if (k==0) {
rlog[nfun]=(pow(10, ((j+1)*d )))/2;
p[nfun]=p[j]/((4.0/3.0)* PI * (pow(10, ((j+1)*d*3))));
// printf("j %d\n", j);
}
else {
ddum=p[j];
rlog[nfun]=(pow(10, ((j+1)*d )) + pow(10, (k*d)))/2;
p[nfun]=p[j]/((4.0/3.0)* PI * (pow(10, ((j+1)*d*3)) - pow(10, (k*d*3))));
if (p[nfun]<0) printf("%g %e %e \n", ddum, pow(10, ((j+1)*d*3)), pow(10, (k*d*3)) );
}
// if (rlog[nfun] < SOFTENING)
// {
// err[nfun]*=10;
// printf("S %d\n", nfun);
// }
k=j+1;
nfun++;
} else {
// p[j]=0;
// err[j]=1e10;
}
}
for (j=0; j<nfun; j++)
{
// printf("%2d: rlog %g p %e err %e d %g d*j %g \n", j, rlog[j], p[j], err[j], pow(10,d*j) ,d*j );
p[j]=log10(p[j]);
}
if (DEBUG) printf("fitting: ");fflush(stdout);
par[0]=1.00;
par[1]=10;
// lm_minimize(nfun, 2, par, err, lm_evaluate_default, printout, &data, &control);
if (DEBUG) printf("done\n ");fflush(stdout);
printf("Delta_c %g Scale Radius %g Concentration factor c %g\n", par[0], par[1], halorad/par[1]);
fitting*/
// printf("%g %g\n", d, pow(10,d*50));
i--;
if (doidl)
{
fp=fopen(idlfile,"w");
fprintf(fp,"dist/mass %s %d %d %g %g %g %g %g\n",vmfile,tr_halo,i,masstot,halorad,cm[0],cm[1],cm[2]);
}
dist=0;
i=0;
while ((dist < maxdist) && (i<=numpart))
{
tr_halo_id[tr_halo_cnt]=P[part[i].ind].id;
tr_halo_i[tr_halo_cnt++]=part[i].ind;
dist=part[i].dist;
if (doidl)
fprintf(fp,"%g %g %d %d\n",dist, P[part[i].ind].mass, P[part[i].ind].id, P[part[i].ind].type );
i++;
}
if (tr_halo_cnt> numpart) tr_halo_cnt=numpart;
printf("number of particles within %g times virial radius %d\n trhalo_cnt %d\n", tr_factor ,i, tr_halo_cnt);
if (doidl) fclose(fp);
if (count!=tr_halo_cnt)
{
tr_halo_id=realloc(tr_halo_id,sizeof(int)*tr_halo_cnt);
tr_halo_i =realloc(tr_halo_i ,sizeof(int)*tr_halo_cnt);
}
if (DEBUG) printf("... \n");fflush(stdout);
/**********************************************************************************************************************************************/
// for (l=-5; l<=5; l++)
count=vcnt; //+l*300;
for (k=0; k<3; k++)
{
jcm[k]=0;
vcm[k]=0;
J[k]=0;
}
totj=0;
massdum=0;
for (j=0; j < count; j++)
{
for (k=0; k<3; k++)
{
vcm[k]+=(P[part[j].ind].vel[k]*P[part[j].ind].mass);
if (pb[k]) jcm[k]+=(MOVE(P[part[j].ind].pos[k],boxsz)*P[part[j].ind].mass);
else jcm[k]+=(P[part[j].ind].pos[k]*P[part[j].ind].mass);
}
massdum+=P[part[j].ind].mass;
}
for (k=0; k<3; k++)
{
vcm[k]=vcm[k]/massdum;
jcm[k]=jcm[k]/massdum;
jcm[k]=jcm[k];
//test
//jcm[k]=cm[k];
}
if (dojr) fp=fopen(jrfile,"w");
for (j=0; j < count; j++)
{
for (k=0; k<3; k++)
{
if (pb[k]) rdum[k]=MOVE(P[part[j].ind].pos[k],boxsz)-jcm[k];
else rdum[k]=P[part[j].ind].pos[k]-jcm[k];
vdum[k]=P[part[j].ind].vel[k]-vcm[k];
}
torq[0]=(rdum[1]*vdum[2]-rdum[2]*vdum[1]);
torq[1]=(rdum[2]*vdum[0]-rdum[0]*vdum[2]);
torq[2]=(rdum[0]*vdum[1]-rdum[1]*vdum[0]);
ddum=0;
for (k=0; k<3; k++)
{
J[k]+=torq[k]*P[part[j].ind].mass;
ddum+=torq[k]*torq[k];
}
totj+=sqrt(ddum)*P[part[j].ind].mass;
ddum=0;
ddum1=0;
for (k=0; k<3; k++) {ddum+=SQR(rdum[k]); ddum1+=SQR(torq[k]);}
if (dojr) fprintf(fp,"%g %g\n", sqrt(ddum), sqrt(ddum1)*P[part[j].ind].mass);
}
if (dojr) fclose(fp);
lmd=0;
for (k=0; k<3; k++) {lmd+=J[k]*J[k];}
lmd=(sqrt(lmd)*1e10*(Msun/evolved.hubparam)*1e3*(kpc/evolved.hubparam))/(sqrt(2)*part[count-1].dist*(kpc/evolved.hubparam)*massdum*1e10*(Msun/evolved.hubparam));
// lmd=(totj*1e10*(Msun/evolved.hubparam)*1e3*(kpc/evolved.hubparam))/(sqrt(2)*part[count-1].dist*(kpc/evolved.hubparam)*massdum*1e10*(Msun/evolved.hubparam));
lmd=lmd/sqrt(G*massdum*1e10*(Msun/evolved.hubparam)/(part[count-1].dist*(kpc/evolved.hubparam)));
printf("Spin: lambda %e r %g\n",lmd, part[count-1].dist);
// fp=fopen(parfile,"w");
// fprintf(fp,"%g %g %g %g \n", lmd, par[0], par[1], halorad/par[1] );
// fclose(fp);
/**********************************************************************************************************************************************/
//Determine Halo-Shape
if (use_inertia)
{
maxdist=rad_ratio*halorad;
if (!(use_inertia&2))
{
if (gal_all) maxdist=30*evolved.hubparam;
else maxdist=effrad;
}
double q=1, s=1, s_old;
gsl_matrix *I = gsl_matrix_alloc (3, 3);
gsl_vector *eval = gsl_vector_alloc (3);
gsl_matrix *evec = gsl_matrix_alloc (3, 3);
gsl_matrix *LU = gsl_matrix_alloc (3, 3);
gsl_matrix *inv = gsl_matrix_alloc (3, 3);
gsl_eigen_symmv_workspace * w = gsl_eigen_symmv_alloc (3);
gsl_matrix *rotation = gsl_matrix_alloc (3, 3);
gsl_matrix_set_identity(rotation);
gsl_matrix *resultmatrix = gsl_matrix_alloc (3, 3);
gsl_matrix_set_zero(I);
struct gadpart *wpart;
wpart= (struct gadpart *)malloc(sizeof(struct gadpart)*vcnt);
m=0;
for (k=0; k < vcnt; k++)
{
l=part[k].ind;
for (j=0; j < 3; j++)
{
if (pb[j]) wpart[k].pos[j]=MOVEB(P[l].pos[j])-MOVEB(cm[j]);
else wpart[k].pos[j]=P[l].pos[j]-cm[j];
wpart[k].vel[j]=P[l].vel[j];
}
wpart[k].mass=P[l].mass;
wpart[k].id=P[l].id;
dum=0;
for (m=0; m<6; m++)
{
dum+=evolved.npart[m];
if (l<dum) break;
}
wpart[k].type=m;
}
do
{
s_old=s;
gsl_matrix_set_zero(I);
for (k=0; k < vcnt; k++)
{
l=part[k].ind;
for (i=0; i < 3; i++)
for (j=i; j < 3; j++)
{
ddum =wpart[k].pos[i] * wpart[k].pos[j];
dist =SQR(wpart[k].pos[0])+SQR(wpart[k].pos[1]/q)+SQR(wpart[k].pos[2]/s);
ddum/= dist;
if ((sqrt(dist)<maxdist) && ((1<<wpart[k].type)&use_inertia))
{
gsl_matrix_set(I,i,j, gsl_matrix_get(I,i,j)+ddum);
if (i!=j) gsl_matrix_set(I,j,i, gsl_matrix_get(I,j,i)+ddum);
}
}
}
gsl_eigen_symmv (I, eval, evec, w);
gsl_eigen_symmv_sort (eval, evec, GSL_EIGEN_SORT_ABS_DESC);
gsl_matrix_memcpy(LU, evec);
/*
for (i=0; i < 3; i++)
{
for (j=0; j < 3; j++)
printf("%15.4g", gsl_matrix_get(I,i,j));
printf("\n");
}
*/
for (i=0; i < 3; i++)
{
double eval_i = gsl_vector_get (eval, i);
// gsl_vector_view evec_i = gsl_matrix_column (evec, i);
if (i==0) ddum = sqrt(eval_i);
else if (i==1) q=sqrt(eval_i)/ddum;
else s=sqrt(eval_i)/ddum;
//printf ("Ratio = %g\n", sqrt(eval_i)/ddum);
// printf ("eigenvector = \n");
// gsl_vector_fprintf (stdout, &evec_i.vector, "%g");
}
gsl_permutation *perm = gsl_permutation_alloc (3);
int sign;
gsl_linalg_LU_decomp (LU, perm, &sign);
gsl_linalg_LU_invert (LU, perm, inv);
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
1.0, inv, rotation,
0.0, resultmatrix);
gsl_matrix_memcpy (rotation, resultmatrix);
//Rotate Particles
gsl_vector *oldpos = gsl_vector_alloc (3);
gsl_vector *newpos = gsl_vector_alloc (3);
gsl_vector *oldvel = gsl_vector_alloc (3);
gsl_vector *newvel = gsl_vector_alloc (3);
ddum=0;
for (k=0; k < vcnt; k++)
{
for (i=0; i<3; i++)
{
gsl_vector_set(oldpos, i, wpart[k].pos[i]);
gsl_vector_set(oldvel, i, wpart[k].vel[i]);
}
gsl_blas_dgemv( CblasNoTrans, 1.0, inv, oldpos, 0.0, newpos);
gsl_blas_dgemv( CblasNoTrans, 1.0, inv, oldvel, 0.0, newvel);
//ddum += gsl_blas_dnrm2 (oldvel) - gsl_blas_dnrm2 (newvel);
for (i=0; i<3; i++)
{
wpart[k].pos[i]=gsl_vector_get(newpos, i);
wpart[k].vel[i]=gsl_vector_get(newvel, i);
}
}
//printf("%g\n", ddum);
} while ((ABS(s_old-s)/s) > 1e-2);
if (docut)
{
sprintf( gadfile, "%s_rot", hname);
FILE *matrixf=fopen(gadfile,"w");
gsl_matrix_fwrite (matrixf, rotation);
fclose(matrixf);
}
gsl_matrix_set_zero(I);
for (k=0; k < vcnt; k++)
{
l=part[k].ind;
for (i=0; i < 3; i++)
for (j=i; j < 3; j++)
{
ddum =wpart[k].pos[i] * wpart[k].pos[j];
dist =SQR(wpart[k].pos[0])+SQR(wpart[k].pos[1]/q)+SQR(wpart[k].pos[2]/s);
ddum/= dist;
if ((sqrt(dist)<maxdist) && ((1<<wpart[k].type)&use_inertia))
{
gsl_matrix_set(I,i,j, gsl_matrix_get(I,i,j)+ddum);
if (i!=j) gsl_matrix_set(I,j,i, gsl_matrix_get(I,j,i)+ddum);
}
}
}
printf("I: ");
for (i=0; i < 3; i++) printf("%g ",gsl_matrix_get(I,i,i));
printf("\n");
printf("longest axis = %g r_ratio: %g \nq = %g\ns = %g\n", maxdist, rad_ratio, q, s);
fflush(stdout);
/*************************************************************************************/
/*Calculate Velocity anisotropy */
gadpart * vapart=malloc(vcnt* sizeof(gadpart));
gadpart_dist * dpart =malloc(vcnt* sizeof(gadpart_dist));
if ((vapart==NULL) || (dpart==NULL)) {fprintf(stderr, "Error allocating memory!\n");exit(1);}
double Pi[3]={0.0, 0.0, 0.0};
double T[3]={0.0, 0.0, 0.0};
double Pi_PHI=0;
double T_PHI=0;
double Pi_RR=0;
double T_RR=0;
double delta;
int num_va=0;
for (i=0; i< vcnt; i++)
{
if ((1<<(wpart[i].type))&use_va)
{
cpygadpart(&vapart[num_va] , &wpart[i]);
cpygadpart(&dpart[num_va].part, &wpart[i]);
dpart[num_va].dist=sqrt(SQR(wpart[i].pos[0])+SQR(wpart[i].pos[1]/q)+SQR(wpart[i].pos[2]/s));
num_va++;
}
}
if (DEBUG) {printf("Begin VA Calculation %d %d\n", vcnt, num_va);fflush(stdout);}
if (num_va > 50)
{
qsort(&dpart[0], num_va, sizeof(gadpart_dist), (void *) cmp_dist);
if (DEBUG) {printf("particles sorted \n");fflush(stdout);}
int distnum= gadsearch(dpart, maxdist, 0, num_va);
if (DEBUG) {printf("maxdist determined \n");fflush(stdout);}
// dpart= realloc(dpart, distnum*sizeof(gadpart_dist));
KdNode * root;
initKdNode(&root, NULL);
buildKdTree(root, vapart, num_va, 0);
if (DEBUG) {printf("KD-Tree completed \n");fflush(stdout);}
for (i=0; i<3; i++) Pi[j]=0;
int incstep;
if (distnum<120) incstep=1;
else if (distnum<300) incstep=5;
else if (distnum<500) incstep=10;
else if (distnum<5000) incstep=30;
else incstep=50;
for (i=0; i<distnum; i+=incstep)
{
masstot=0;
gadpart_dist * knn;
double knndist=findkNN(root, &dpart[i].part, 15, &knn, kNN);
double meanv[3]={0.0, 0.0, 0.0};
double sqrmv[3]={0.0, 0.0, 0.0};
double R = sqrt(SQR(dpart[i].part.pos[0])+SQR(dpart[i].part.pos[1]));
double ang;
double vR,vR2, vRsum;
double vPHI, vPHI2, vPHIsum;
for (j=0; j<3; j++)
{
meanv[j]=dpart[i].part.vel[j]*dpart[i].part.mass;
sqrmv[j]=SQR(dpart[i].part.vel[j])*dpart[i].part.mass;
}
ang = atan2(dpart[i].part.pos[1], dpart[i].part.pos[0]);
vR = dpart[i].part.vel[0]* cos(ang)+ dpart[i].part.vel[1]* sin(ang);
vR2 = SQR(vR)*dpart[i].part.mass;
vRsum = vR*dpart[i].part.mass;
vPHI = -dpart[i].part.vel[0]*sin(ang)+dpart[i].part.vel[1]*cos(ang);
vPHI2 = SQR(vPHI)*dpart[i].part.mass;
vPHIsum= vPHI*dpart[i].part.mass;
masstot=dpart[i].part.mass;
for (k=0; k<kNN; k++)
{
for (j=0; j<3; j++)
{
meanv[j]+=knn[k].part.vel[j]*knn[k].part.mass;
sqrmv[j]+=SQR(knn[k].part.vel[j])*knn[k].part.mass;
}
// ang = atan2(knn[k].part.pos[1], knn[k].part.pos[1]);
ang = atan2(knn[k].part.pos[1], knn[k].part.pos[0]);
vR = knn[k].part.vel[0]* cos(ang)+ knn[k].part.vel[1]* sin(ang);
vR2 += SQR(vR)*knn[k].part.mass;
vRsum += vR*knn[k].part.mass;
vPHI = -knn[k].part.vel[0]*sin(ang)+ knn[k].part.vel[1]* cos(ang);
vPHI2 += SQR(vPHI)*knn[k].part.mass;
vPHIsum+= vPHI*knn[k].part.mass;
masstot+=knn[k].part.mass;
}
for (j=0; j<3; j++)
{
meanv[j]=meanv[j]/masstot;
sqrmv[j]=sqrmv[j]/masstot;
double sigma=(sqrmv[j]-SQR(meanv[j]));
Pi[j]+=(sqrmv[j]-SQR(meanv[j]));
T[j]+=SQR(meanv[j]);
if (sigma < 0) printf("!sigmaerror!%g %g %g %g %g\n",sqrmv[j], meanv[j], SQR(meanv[j]), sigma, masstot);
}
vR2 = vR2/masstot;
vRsum = vRsum/masstot;
vPHI2 = vPHI2/masstot;
vPHIsum= vPHIsum/masstot;
Pi_RR += vR2-SQR(vRsum);
T_RR += SQR(vRsum);
Pi_PHI+= vPHI2-SQR(vPHIsum);
T_PHI+= SQR(vPHIsum);
// printf("%5d %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g %10.4g\n", i, dpart[i].dist, knndist, dpart[i].part.pos[0], dpart[i].part.pos[1], dpart[i].part.pos[2], Pi[i][0], Pi[i][1], Pi[i][2]);
free(knn);
}
fprintf(stdout, "PI %g %g %g\n", Pi[0], Pi[1], Pi[2]);
double mPi=(Pi[0]+Pi[1])/2;
delta= (mPi-Pi[2])/mPi;
fprintf(stdout, "Pi_RR %g\n", Pi_RR);
fprintf(stdout, "Pi_PHI %g\n", Pi_PHI);
fprintf(stdout, "delta %g\n", delta);
fprintf(stdout, "T %g %g %g\n", T[0], T[1], T[2]);
fprintf(stdout, "T_RR %g\n", T_RR);
fprintf(stdout, "T_PHI %g\n", T_PHI);
free(root);
}
free(vapart);
free(dpart);
if (DEBUG) {printf("End of VA Calculation\n");fflush(stdout);}
/*END VA Calculation************************************************************************************/
/*
if (docut)
{
outpos =(fltarr *)malloc(sizeof(fltarr)*vcnt);
outvel =(fltarr *)malloc(sizeof(fltarr)*vcnt);
outid =(int *)malloc(sizeof(int)*vcnt);
outmass =(float *)malloc(sizeof(float)*vcnt);
out=evolved;
qsort(&wpart[0],vcnt,sizeof(struct gadpart),cmp_type);
for (i=0; i<6; i++)
{
out.npart[i]=0;
out.nall[i]=0;
}
i=0;
while (i<vcnt)
{
for (j=0; j<3; j++)
{
outpos[i][j]=wpart[i].pos[j];
outvel[i][j]=wpart[i].P[j].vel;
}
outid[i]=wpart[i].id;
outmass[i]=wpart[i].mass;
l=wpart[i].type;
out.npart[l]++;
out.nall[l]++;
i++;
}
sprintf( gadfile, "%s_rot.gad", hname);
writegadget(gadfile, out, outpos, outvel, outid, outmass);
free(outpos);
free(outvel);
free(outid);
free(outmass);
}
*/
gsl_matrix_free(I);
gsl_matrix_free(evec);
gsl_matrix_free(LU);
gsl_matrix_free(inv);
gsl_matrix_free(rotation);
gsl_matrix_free(resultmatrix);
gsl_vector_free(eval);
gsl_eigen_symmv_free(w);
free(wpart);
}
}else
{
fp=fopen(idfile, "r");
fread(&tr_halo_cnt, sizeof(int), 1,fp);
fread(cm, sizeof(double), 3,fp);
tr_halo_id=(int*) malloc(tr_halo_cnt*sizeof(int));
fread(tr_halo_id, sizeof(int), tr_halo_cnt,fp);
fclose(fp);
printf("TraceIDfile (%d particles) read, CM at %f %f %f\n", tr_halo_cnt, cm[0], cm[1], cm[2]);
fflush(stdout);
}
/**********************************************************************************************************************************************/
if (notrace)
{
if (DEBUG)
printf("no IC-file specified, exitting...\n");
exit(0);
}
i=0;
numpart=0;
//read in IC File
fp=fopen(icfile,"r");
fread(&blocksize,sizeof(int),1,fp);
fread(&ic,sizeof(struct header),1,fp); //read header of ic gadget file
fread(&blocksize,sizeof(int),1,fp);
boxsz=ic.boxsize;
for (i=0; i<6; i++) numpart+=ic.npart[i];
pos_ic =(fltarr *)malloc(sizeof(fltarr)*numpart);
#ifdef LONGIDS
long *id_ic;
id_ic =(long *) malloc(sizeof(long)*numpart);
#else
int *id_ic;
id_ic =(int *) malloc(sizeof(int)*numpart);
#endif //LONGIDS
// mass_ic=(float *) malloc(sizeof(float)*numpart);
fread(&blocksize,sizeof(int),1,fp); //read particle positions of ic snapshot file
fread(&pos_ic[0],sizeof(fltarr),numpart,fp);
fread(&blocksize,sizeof(int),1,fp);
fread(&blocksize,sizeof(int),1,fp); //skip velocities
fseek(fp,blocksize,SEEK_CUR);
fread(&blocksize,sizeof(int),1,fp);
fread(&blocksize,sizeof(int),1,fp); //read particle ids of ic snapshot file
#ifdef LONGIDS
fread(&id_ic[0],sizeof(long),numpart,fp);
#else
fread(&id_ic[0],sizeof(int),numpart,fp);
#endif //LONGIDS
fread(&blocksize,sizeof(int),1,fp);
// fread(&blocksize,sizeof(int),1,fp); //read particle masses of ic snapshot file
// fread(&mass_ic[0],sizeof(float),numpart,fp);
// fread(&blocksize,sizeof(int),1,fp);
fclose(fp);
for (k=0; k<3; k++) //check whether periodic boundaries are needed
{
if ( ((cm[k]<GAP) || (cm[k]>(ic.boxsize-GAP) || pb[k])) && (!nopb))
{
pb[k]=1;
// cm[k]=MOVE(cm[k],boxsz);
}
}
// j=P[part[0].ind].id-1;
j=tr_halo_id[0]-1;
coord512(ca,j);
for (k=0; k<3; k++)
{
if (pb[k]) {icmin[k]=MV(ca[k], DIM)*dx512; icmax[k]=MV(ca[k], DIM)*dx512;}
else {icmin[k]=ca[k]*dx512;icmax[k]=ca[k]*dx512;}
}
if (!traceid) fp=fopen("ind.dat","w");
for (k=0; k<3; k++) {indmax[k]=j; indmin[k]=j;}
for (i=1; i<tr_halo_cnt; i++)
{
// j=P[part[i].ind].id-1;
j=tr_halo_id[i]-1;
coord512(ca, j);
for (k=0; k<3; k++)
{
if (pb[k])
{
ddum=MV(ca[k], DIM)*dx512;
if (ddum < icmin[k]) {icmin[k]= round(ddum); indmin[k]=j;}
if (ddum > icmax[k]) {icmax[k]= round(ddum); indmax[k]=j;}
} else
{
ddum=ca[k]*dx512;
if (ddum < icmin[k]) {icmin[k]= round(ddum); indmin[k]=j;}
if (ddum > icmax[k]) {icmax[k]= round(ddum); indmax[k]=j;}
}
}
if (!traceid)
fprintf(fp,"%g %g %g\n",P[tr_halo_i[i]].pos[0]-cm[0],P[tr_halo_i[i]].pos[1]-cm[1],P[tr_halo_i[i]].pos[2]-cm[2]);
}
if (!traceid) fclose(fp);
alignf=2;
gridsize=72000.0/(64.0*alignf);
for (k=0; k<3; k++)
{
min[k]=icmin[k];
max[k]=icmax[k];
}
if (DEBUG)
{
printf("indmin: %d %d %d...\n",indmin[0], indmin[1], indmin[2]);fflush(stdout);
printf("indmax: %d %d %d...\n",indmax[0], indmax[1], indmax[2]);fflush(stdout);
printf("icmin: %f %f %f...\n",icmin[0], icmin[1], icmin[2]);fflush(stdout);
printf("icmax: %f %f %f...\n",icmax[0], icmax[1], icmax[2]);fflush(stdout);
}
if (strcmp(gridfile,"<none>")) //build a grid and determine which cells contain particles of the halo
{
for (k=0; k<3; k++)
{
printf("%d\n", pb[k]);
coord512(ca, indmin[k]);
minbox[k]= (ca[k]>0) ? (ca[k]-1) : (ca[k]+DIM-1);
coord512(ca, indmax[k]);
maxbox[k]= (ca[k]<DIM) ? (ca[k]+1) : (ca[k]-DIM+1);
if (pb[k]) szbox[k] =ceil((icmax[k]-MOVE(minbox[k]*dx512,boxsz))/(gridsize))+2;
else szbox[k] =ceil((icmax[k]-(minbox[k]*dx512))/(gridsize))+2;
size[k] = (maxbox[k] > minbox[k]) ? (maxbox[k]-minbox[k]) : (maxbox[k]-minbox[k]+DIM);
//if ((szbox[k]&1)==1) szbox[k]++;
// szbox[k]*=alignf;
printf("%d %d %d \n",minbox[k],maxbox[k],szbox[k]);fflush(stdout);
}
grid= (int ***) malloc (szbox[0]*sizeof(int **)); //allocate 3-dimensional array
for (i=0; i < szbox[0]; i++)
{
grid[i]= (int **) malloc (szbox[1] * sizeof(int *));
}
for (i=0; i < szbox[0]; i++)
for (j=0; j < szbox[1]; j++)
{
grid[i][j]= (int *) calloc (szbox[2],sizeof(int ));
}
fp = fopen(datfile, "w");
for (i=0; i<tr_halo_cnt; i++)
{
// j=P[part[i].ind].id-1;
j=tr_halo_id[i]-1;
coord512(ca, j);
for (k=0; k<3; k++)
{
if (pb[k])
{
boxind[k]=floor(((MV(ca[k],512)*dx512)- MOVE(minbox[k]*dx512, boxsz))/gridsize );
} else
{
boxind[k]=floor((ca[k]*dx512/gridsize)- (minbox[k]*alignf/8.0));
}
fprintf(fp,"%g\t",(ca[k]*dx512/gridsize) );
if ((j==indmax[k]) ||(j==indmin[k]))
{
printf("%d %g %g\n", k, boxind[k]*gridsize , minbox[k]*(gridsize*alignf/8.0));
printf("%g %d %d\n", pos_ic[j][k], boxind[k], minbox[k]);fflush(stdout);
}
}
// if (DEBUG) {printf("%d %d %d...\n",boxind[0], boxind[1], boxind[2]);fflush(stdout);}
grid[boxind[0]][boxind[1]][boxind[2]]++;
fprintf(fp, "%d\t%d\t%d\t%d\t%d\t%d\n", boxind[0], boxind[1], boxind[2] , ca[0], ca[1], ca[2]);
// if ((i<100) && (grid[boxind[0]][boxind[1]][boxind[2]]<100000)) grid[boxind[0]][boxind[1]][boxind[2]]+=100000;
}
fclose(fp);
printf("%g\t%g\t%g\n!\n", dx512, gridsize, dx512/gridsize);
if (DEBUG) {printf("grid built...\n");fflush(stdout);}
fp=fopen(gridfile,"w");
blocksize=28;
fwrite(&blocksize,sizeof(int),1,fp);
fwrite(&szbox[0],sizeof(int),3,fp);
fwrite(&minbox[0],sizeof(int),3,fp);
fwrite(&alignf,sizeof(int),1,fp);
fwrite(&blocksize,sizeof(int),1,fp);
blocksize=sizeof(int)*szbox[0]*szbox[1]*szbox[2];
fwrite(&blocksize,sizeof(int),1,fp);
for (k=0; k < szbox[2]; k++)
for (j=0; j < szbox[1]; j++)
for (i=0; i < szbox[0]; i++)
fwrite(&grid[i][j][k],sizeof(int),1,fp);
fwrite(&blocksize,sizeof(int),1,fp);
fclose(fp);
}
printf("Min/Max positions in IC file:\n");fflush(stdout);
for (k=0; k<3; k++)
{
if (pb[k])
{
min[k]=MOVE(min[k],boxsz);max[k]=MOVE(max[k],boxsz);
icmin[k]=MOVE(icmin[k], boxsz);icmax[k]=MOVE(icmax[k], boxsz);
}
printf("%d:code units: Min %5.2f Max %5.2f physical units: Min %5.2f Max %5.2f\n",k, min[k],max[k],min[k]/ic.hubparam,max[k]/ic.hubparam);
}
for (k=0; k<3; k++)
{
//printf("%d min %g max %g\n", k, min[k], max[k]);
}
printf("minx=%g;\n",icmin[0]);
printf("maxx=%g;\n",icmax[0]);
printf("miny=%g;\n",icmin[1]);
printf("maxy=%g;\n",icmax[1]);
printf("minz=%g;\n",icmin[2]);
printf("maxz=%g;\n",icmax[2]);
printf("offx=%d;\n",minbox[0]);
printf("offy=%d;\n",minbox[1]);
printf("offz=%d;\n",minbox[2]);
printf("sizex=%d;\n",size[0]);
printf("sizey=%d;\n",size[1]);
printf("sizez=%d;\n",size[2]);
printf("Expected CM in resimulation: ");
for (k=0; k<3; k++)
{
diff[k]=icmax[k]-(minbox[k]*dx512);
diff[k]=(diff[k]>0)? diff[k] : (diff[k]+boxsz);
shift[k]=( (boxsz/2.0) - (icmin[k]+(diff[k]/2.0)));
expcm[k]=(cm[k]+shift[k]) > 0 ? (cm[k]+shift[k]) : (cm[k]+shift[k])+boxsz;
printf(" %g ", expcm[k]);
}
printf("\n");
free(part);
printf("Time needed: %.2f sec\n",((float)clock())/CLOCKS_PER_SEC);
return 0;
}
| {
"alphanum_fraction": 0.5323635079,
"avg_line_length": 28.173119469,
"ext": "c",
"hexsha": "d5dcfd1ca28f89ab0c97fdb143bf8ef75ec35c93",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lgo33/GadTools",
"max_forks_repo_path": "trhalo.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1",
"max_issues_repo_issues_event_max_datetime": "2017-01-12T14:40:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-12T14:40:32.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Fette3lke/GadTools",
"max_issues_repo_path": "trhalo.c",
"max_line_length": 209,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "164263b8084e32e15022df81e35448cfa02f1ab1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Fette3lke/GadTools",
"max_stars_repo_path": "trhalo.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 18360,
"size": 50937
} |
//====---- Sudoku/Options.h ----====//
//
// Data object containing and managing available options.
//====--------------------------------------------------------------------====//
// Templated with element size.
//
// The 0-bit is the inverse answer-bit. if [0]==0 the answer is set.
//
//====--------------------------------------------------------------------====//
#pragma once
#include "Size.h"
#include "Value.h"
#include <gsl/gsl>
#include <bitset>
#include <string>
#include <vector>
#include <utility>
#include <cassert>
#include <cstddef> // size_t
#include <cstdint> // int64_t, uint32
namespace Sudoku
{
template<int E>
class Options
{
static_assert(E >= 1);
using bitset = std::bitset<E + 1>;
public:
Options() noexcept;
Options(int) = delete; // NOLINT: implicit catch all that convert to bitset
explicit Options(const bitset&) noexcept; // 0th bit is last in input
explicit Options(bitset&&) noexcept;
explicit constexpr Options(Value) noexcept;
Options& operator=(Value) noexcept;
Options& operator=(const bitset&) noexcept;
Options& operator=(bitset&&) noexcept;
Options& clear() noexcept; // remove all options
Options& reset() noexcept; // set all options
Options& flip() noexcept;
Options& remove_option(Value const&); // remove single option
// TODO Options& remove_option(Value, ...); // remove mentioned
Options& add(Value const&); // add single option
Options& set(Value const&); // set to answer
Options& add_nocheck(Value const&) noexcept; // add single option
Options& set_nocheck(Value const&) noexcept; // set to answer
[[nodiscard]] constexpr size_t size() const noexcept;
[[nodiscard]] size_t count() const noexcept; // count available options
[[nodiscard]] size_t count_all() const noexcept; // count all (incl. answer)
[[nodiscard]] bool all() const noexcept; // test all options available
[[nodiscard]] bool test(Value const&) const; // if an option, or answer
[[nodiscard]] bool is_answer() const noexcept; // is set to answer
[[nodiscard]] bool is_empty() const noexcept;
[[nodiscard]] constexpr bool operator[](Value const&) const noexcept;
auto operator[](Value const&) noexcept;
[[nodiscard]] friend bool
operator==(const Options<E>& left, const Options<E>& right) noexcept
{
//? operator== what about the 0th 'is answer' bit?
return left.data_ == right.data_;
}
[[nodiscard]] friend bool
operator<(const Options<E>& left, const Options<E>& right)
#if defined(__ICL) && __ICL <= 1900
noexcept(false)
#else
noexcept(sizeof(Options<E>) <= sizeof(std::uint64_t))
#endif // __ICL
{
if constexpr (sizeof(Options<E>) <= sizeof(std::uint32_t))
{
return left.data_.to_ulong() < right.data_.to_ulong();
}
else
{
return left.data_.to_ullong() < right.data_.to_ullong();
}
}
// combine available options
Options& operator+=(const Options&) noexcept;
// XOR
Options& XOR(const Options&) noexcept;
// remove options
Options& operator-=(const Options&) noexcept;
// Debug Use Only, don't depend on it's result
[[nodiscard]] std::string DebugString() const;
// Shared options (binary AND)
// Prefer: shared(left, right)
[[nodiscard]] friend Options
operator&(const Options& left, const Options& right) noexcept
{
Options tmp{left};
tmp.data_ &= right.data_;
return tmp;
}
private:
// 0th bit is "need to solve":
// false if answer has been set = inverse of answer
bitset data_{};
}; // class Options
//====---- free-functions ------------------------------------------------====//
template<int E>
[[nodiscard]] bool is_answer(Options<E> const&) noexcept;
template<int E>
[[nodiscard]] constexpr bool is_answer_fast(Options<E> const&) noexcept;
template<int E>
[[nodiscard]] bool is_answer(Options<E> const&, Value const&) noexcept;
template<int E>
[[nodiscard]] bool is_option(Options<E> const&, Value const);
template<int E>
[[nodiscard]] Value get_answer(Options<E> const&) noexcept;
template<int N>
[[nodiscard]] Value to_Value(Options<elem_size<N>> const&) noexcept;
template<int E> // NOLINTNEXTLINE(bugprone-exception-escape)
[[nodiscard]] std::vector<Value> available(const Options<E>&) noexcept(true);
template<int E>
[[nodiscard]] Value read_next(const Options<E>&, Value = Value{0}) noexcept;
template<int E>
[[nodiscard]] bool operator!=(Options<E> const&, Options<E> const&) noexcept;
template<int E>
[[nodiscard]] bool operator==(Options<E> const&, Value const&) noexcept;
template<int E>
[[nodiscard]] bool operator==(Value const&, Options<E> const&) noexcept;
template<int E>
[[nodiscard]] bool operator!=(Options<E> const&, Value const&) noexcept;
template<int E>
[[nodiscard]] bool operator!=(Value const&, const Options<E>&) noexcept;
template<int E>
[[nodiscard]] Options<E> XOR(Options<E> const& A, Options<E> const& B) noexcept;
template<int E>
[[nodiscard]] Options<E>
operator+(Options<E> const&, Options<E> const&) noexcept;
template<int E>
[[nodiscard]] Options<E>
operator-(Options<E> const&, Options<E> const&) noexcept;
// return shared options
template<int E>
[[nodiscard]] Options<E>
shared(Options<E> const& A, Options<E> const& B) noexcept;
//====--------------------------------------------------------------------====//
namespace impl
{
[[nodiscard]] inline constexpr size_t exp2_(size_t value) noexcept
{
return (value < 1U) ? 1U : (2U * exp2_(--value));
}
static_assert(exp2_(0U) == 0x1U);
static_assert(exp2_(1U) == 0x2U);
static_assert(exp2_(2U) == 0x4U); //-V112
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
static_assert(exp2_(3U) == 0x8U); // NOLINT(readability-magic-numbers)
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
static_assert(exp2_(4U) == 0x10U); // NOLINT(readability-magic-numbers)
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
static_assert(exp2_(5U) == 0x20U); // NOLINT(readability-magic-numbers)
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
static_assert(exp2_(6U) == 0x40U); // NOLINT(readability-magic-numbers)
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
static_assert(exp2_(7U) == 0x80U); // NOLINT(readability-magic-numbers)
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
static_assert(exp2_(8U) == 0x100U); // NOLINT(readability-magic-numbers)
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)
static_assert(exp2_(9U) == 0x200U); // NOLINT(readability-magic-numbers)
// generate a bit-mask to use a unique bit per value
// empty for Value outside domain.
template<int E>
[[nodiscard]] inline constexpr size_t exp2_(Value value) noexcept
{
return (value > Value{E}) ? 0U : exp2_(static_cast<size_t>(value));
}
// generate a bit-mask to set all bits in std::bitset
[[nodiscard]] inline constexpr size_t all_set(size_t elements) noexcept
{
return (exp2_(++elements) - 1U);
}
} // namespace impl
//====--------------------------------------------------------------------====//
// construct with all options set
template<int E>
inline Options<E>::Options() noexcept
{
data_.flip();
}
template<int E>
inline Options<E>::Options(const bitset& other) noexcept : data_(other)
{ // empty constructor
}
template<int E>
inline Options<E>::Options(bitset&& other) noexcept : data_{other}
{ // empty constructor
}
// construct with single option set to answer
template<int E>
inline constexpr Options<E>::Options(Value value) noexcept
: data_{impl::exp2_<E>(value)}
{
assert(value <= Value{E});
}
// set to answer value
template<int E>
inline Options<E>& Options<E>::operator=(Value value) noexcept
{
assert(value <= Value{E});
data_ = impl::exp2_<E>(value);
return *this;
}
template<int E>
inline Options<E>& Options<E>::operator=(const bitset& other) noexcept
{
data_ = other;
return *this;
}
template<int E>
inline Options<E>& Options<E>::operator=(bitset&& other) noexcept
{
std::swap(data_, other); // use <utility>
return *this;
}
// remove all options
template<int E>
inline Options<E>& Options<E>::clear() noexcept
{
data_.reset(); // all false
//??? Note: answer-bit unset too -> answered?
return *this;
}
// set all options
template<int E>
inline Options<E>& Options<E>::reset() noexcept
{
data_.set(); // all true, default starting state
return *this;
}
template<int E>
inline Options<E>& Options<E>::flip() noexcept
{
// retain answer flag value
data_[0].flip(); // noexcept
data_.flip(); // noexcept
return *this;
}
// remove single option
template<int E>
inline Options<E>& Options<E>::remove_option(Value const& value)
{
assert(is_valid_option<E>(value));
assert(not Sudoku::is_answer(*this, value));
data_.set(static_cast<size_t>(value), false);
return *this;
}
// add single option
template<int E>
inline Options<E>& Options<E>::add(Value const& value)
{
assert(is_valid_option<E>(value));
data_.set(static_cast<size_t>(value), true);
return *this;
}
// add single option
template<int E>
inline Options<E>& Options<E>::add_nocheck(Value const& value) noexcept
{
assert(is_valid_option<E>(value));
data_[static_cast<size_t>(value)] = true;
return *this;
}
// set to answer
template<int E>
inline Options<E>& Options<E>::set(Value const& value)
{
clear();
return add(value); // if 0: -> not answer = [0] = true
}
// set to answer
template<int E>
inline Options<E>& Options<E>::set_nocheck(Value const& value) noexcept
{
clear();
return add_nocheck(value);
}
template<int E>
inline constexpr size_t Options<E>::size() const noexcept
{
return data_.size(); // bits
//??? size() -1 better?
// The current implementation works with size() being 1 past the last
// element. But this allows for size()-1 options to be stored. The
// direct value to location implementation is convenient. The 0th
// element in this implementation is just a flag (more could be added).
}
// available options
// if 1, a not processed answer
template<int E>
inline size_t Options<E>::count() const noexcept
{
if (data_[0])
{
return data_.count() - 1U;
}
return 0; // NO protection vs incorrect answer bit
}
// (!) counts options, including set answers == ignores answer-bit
// Returns 1 if {1 option, set as answer} || {1 option, not set as answer}
// Returns 0 if {empty} || {no option, but not set as answer}
template<int E>
inline size_t Options<E>::count_all() const noexcept
{
if (data_[0])
{
return data_.count() - 1U;
}
return data_.count();
}
// Test if all bits are set
template<int E>
inline bool Options<E>::all() const noexcept
{
return data_.all();
}
// if an option, or the answer
template<int E>
inline bool Options<E>::test(Value const& value) const
{
return data_.test(static_cast<size_t>(value));
}
// check if set to answer
template<int E>
inline bool Options<E>::is_answer() const noexcept
{
return !data_[0] && data_.count() == 1;
}
// check if set to answer
template<int E>
inline bool is_answer(const Options<E>& options) noexcept
{ // convenience function
return options.is_answer();
}
// check if set to answer without validation
template<int E>
inline constexpr bool is_answer_fast(const Options<E>& options) noexcept
{
return !options[Value{0}];
}
// check if set to answer value
template<int E>
inline bool is_answer(Options<E> const& options, Value const& value) noexcept
{
return options == Options<E>{value};
}
// check if option available
template<int E>
inline bool is_option(const Options<E>& options, const Value value)
{
assert(is_valid_option<E>(value));
return (options.test(value) && not is_answer_fast(options));
}
// Test if no options or answers available
template<int E>
inline bool Options<E>::is_empty() const noexcept
{
return data_.none();
}
// determine the answer value, even if not marked
// use with is_answer[_fast]() to determine if flagged as answer
template<int E>
inline Value get_answer(const Options<E>& options) noexcept
{
if (options.count_all() == 1)
{
return read_next(options);
}
return Value{0};
}
template<int N>
inline Value to_Value(Options<elem_size<N>> const& options) noexcept
{ // specialization of to_Value
return get_answer(options);
}
// all available options
template<int E> // NOLINTNEXTLINE(bugprone-exception-escape)
inline std::vector<Value> available(Options<E> const& options) noexcept(true)
{ // noexcept: only allocation can throw. Terminate, all is lost anyway.
const size_t count = options.count();
std::vector<Value> values{};
values.reserve(count);
if (not is_answer(options) && not options.is_empty())
{
Value item{0};
for (size_t i{0}; i < count; ++i)
{
item = read_next(options, item);
values.emplace_back(item);
}
}
return values;
}
// no-check access read only
template<int E>
inline constexpr bool Options<E>::operator[](Value const& value) const noexcept
{
assert(value <= Value{E});
return data_[static_cast<size_t>(value)];
}
// no-check access
template<int E>
inline auto Options<E>::operator[](Value const& value) noexcept
{
assert(value <= Value{E});
return data_[static_cast<size_t>(value)];
}
template<int E>
inline bool operator!=(Options<E> const& left, Options<E> const& right) noexcept
{
return !(left == right);
}
// short for is_answer(value)
template<int E>
inline bool operator==(Options<E> const& left, Value const& value) noexcept
{
return is_answer(left, value);
}
template<int E>
inline bool operator==(Value const& value, Options<E> const& right) noexcept
{
return is_answer(right, value);
}
template<int E>
inline bool operator!=(Options<E> const& left, Value const& value) noexcept
{
return not(is_answer(left, value));
}
template<int E>
inline bool operator!=(Value const& value, Options<E> const& right) noexcept
{
return not(is_answer(right, value));
}
// Combine available options (binary OR)
template<int E>
inline Options<E>& Options<E>::operator+=(const Options& other) noexcept
{
data_ |= (other.data_);
return *this;
}
// Combine (binary OR)
template<int E>
inline Options<E>
operator+(const Options<E>& left, const Options<E>& right) noexcept
{
Options<E> tmp{left};
return tmp += right;
}
// Per element (binary) XOR, exclusive OR
template<int E>
inline Options<E>& Options<E>::XOR(const Options& other) noexcept
{
data_ ^= other.data_;
return *this;
}
// Exclusive OR
template<int E>
inline Options<E> XOR(const Options<E>& A, const Options<E>& B) noexcept
{
Options<E> tmp{A};
return tmp.XOR(B);
}
// Shared options
template<int E>
inline Options<E> shared(const Options<E>& A, const Options<E>& B) noexcept
{
return A & B;
}
// Remove options existing also in other
template<int E>
inline Options<E>& Options<E>::operator-=(const Options& other) noexcept
{
assert(is_answer_fast(other)); // do not remove the answer-bit
const Options tmp = ::Sudoku::XOR(*this, other);
data_ &= tmp.data_;
return *this;
}
// Only in left
template<int E>
inline Options<E>
operator-(const Options<E>& left, const Options<E>& right) noexcept
{
Options<E> tmp{left};
return tmp -= right;
}
template<int E>
#ifndef fwkUnitTest
[[deprecated("Debug use only")]]
#endif
inline std::string
Options<E>::DebugString() const
{
return data_.to_string();
}
// return next option in data
template<int E>
inline Value read_next(const Options<E>& options, Value value) noexcept
{ // default value start = 0
++value;
for (; value <= Value{E}; ++value)
{
if (options[value])
{
return value;
}
}
return Value{0};
}
} // namespace Sudoku
| {
"alphanum_fraction": 0.6859369925,
"avg_line_length": 26.271331058,
"ext": "h",
"hexsha": "5a71d505324bbef89db6a03144eb93e188b7b96d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "FeodorFitsner/fwkSudoku",
"max_forks_repo_path": "Sudoku/Sudoku/Options.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "FeodorFitsner/fwkSudoku",
"max_issues_repo_path": "Sudoku/Sudoku/Options.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "FeodorFitsner/fwkSudoku",
"max_stars_repo_path": "Sudoku/Sudoku/Options.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3931,
"size": 15395
} |
static char help[] = "DAE system solver example using TS. Models two\n"
"equal-mass balls (particles) moving in the plane with a rigid connecting\n"
"rod between. (Alternatively, -rod_free removes the rod and the motion\n"
"is free and independent.) A stabilized index-2 constrained Lagrangian\n"
"dynamics formulation is used. We use cartesian coordinates (x,y) and\n" "velocities (v=dx/dt,w=dy/dt). The system has dimension 10.\n\n";
// DEBUG possibly a good solution using BDF3 and -snes_fd
// ./rod -ts_type bdf -ksp_type preonly -pc_type svd -ts_monitor binary:t.dat -ts_monitor_solution binary:u.dat -ts_dt 0.01 -ts_max_time 1.0 -snes_fd -ts_bdf_order 3
// ./trajectory.py -o figure.png t.dat u.dat
// DEBUG check Jacobian for rod problem using one backward-Euler step
// (2nd case with -snes_fd):
// ./rod -ts_type beuler -ts_max_time 0.1 -ts_dt 0.1 -ksp_type preonly -pc_type svd -snes_monitor -ksp_view_mat
// ./rod -ts_type beuler -ts_max_time 0.1 -ts_dt 0.1 -ksp_type preonly -pc_type svd -snes_monitor -ksp_view_mat -snes_fd
// DEBUG check BDF2 convergence in free problem using Lagrangian formulation:
//for T in 2 3 4 5 7 8 9 10 11 12; do ./rod -rod_free -ts_type bdf -ts_rtol 1.0e-$T -ts_atol 1.0e-$T; done
#include <petsc.h>
typedef struct {
PetscBool free;
PetscReal g, // m s-2; acceleration of gravity
m, // kg; ball mass
l; // m; spring or rod length
} RodCtx;
extern PetscErrorCode SetInitial(Vec, RodCtx*);
extern PetscErrorCode FreeExact(Vec, PetscReal, Vec, RodCtx*);
extern PetscErrorCode LagrangeIFcn(TS, PetscReal, Vec, Vec, Vec, void*);
extern PetscErrorCode LagrangeIJac(TS, PetscReal, Vec, Vec, PetscReal,
Mat, Mat, void*);
int main(int argc,char **argv) {
PetscErrorCode ierr;
PetscInt steps;
PetscReal t0 = 0.0, tf = 2.0, dt = 0.1, errnorm;
Vec u, u0, uexact;
Mat A;
TS ts;
RodCtx user;
char probstr[20] = "rod";
ierr = PetscInitialize(&argc, &argv, NULL, help); if (ierr) return ierr;
user.free = PETSC_FALSE;
user.g = 9.81;
user.m = 58.0e-3; // 58 g for a tennis ball
user.l = 0.5; // rod length, and determines initial condition
ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "rod_", "options for rod",
""); CHKERRQ(ierr);
ierr = PetscOptionsBool("-free","remove rod for free motion",
"rod.c", user.free, &user.free,
NULL); CHKERRQ(ierr);
ierr = PetscOptionsReal("-g", "acceleration of gravity (m s-2)",
"rod.c", user.g, &user.g, NULL); CHKERRQ(ierr);
ierr = PetscOptionsReal("-l", "rod length (m)", "rod.c",
user.l, &user.l, NULL); CHKERRQ(ierr);
ierr = PetscOptionsReal("-m", "mass of each ball (kg)", "rod.c",
user.m, &user.m, NULL); CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
ierr = VecCreate(PETSC_COMM_WORLD,&u); CHKERRQ(ierr);
ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);
ierr = TSSetApplicationContext(ts,&user); CHKERRQ(ierr);
ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);
// set time axis
ierr = TSSetTime(ts,t0); CHKERRQ(ierr);
ierr = TSSetMaxTime(ts,tf); CHKERRQ(ierr);
ierr = TSSetTimeStep(ts,dt); CHKERRQ(ierr);
ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);
// set up dimension, equation type, and solver type
ierr = VecSetSizes(u,PETSC_DECIDE,10); CHKERRQ(ierr);
ierr = MatCreate(PETSC_COMM_WORLD,&A); CHKERRQ(ierr);
ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,10,10); CHKERRQ(ierr);
ierr = MatSetFromOptions(A); CHKERRQ(ierr);
ierr = MatSetUp(A); CHKERRQ(ierr);
if (user.free) {
ierr = TSSetEquationType(ts, TS_EQ_DAE_IMPLICIT_INDEX1);
CHKERRQ(ierr);
} else {
ierr = TSSetEquationType(ts, TS_EQ_DAE_IMPLICIT_INDEX2);
CHKERRQ(ierr);
}
ierr = TSSetIFunction(ts,NULL,LagrangeIFcn,&user); CHKERRQ(ierr);
ierr = TSSetIJacobian(ts,A,A,LagrangeIJac,&user);CHKERRQ(ierr);
ierr = TSSetType(ts,TSBEULER); CHKERRQ(ierr); // FIXME BDF3 as default?
// set-up of u, ts is complete
ierr = VecSetFromOptions(u); CHKERRQ(ierr);
ierr = TSSetFromOptions(ts); CHKERRQ(ierr);
// set initial values and solve
ierr = SetInitial(u, &user); CHKERRQ(ierr);
ierr = TSSolve(ts, u); CHKERRQ(ierr);
ierr = TSGetTime(ts, &tf); CHKERRQ(ierr);
// numerical error in free case
if (user.free) {
ierr = VecDuplicate(u, &uexact); CHKERRQ(ierr);
// get initial condition for evaluating exact solution
ierr = VecDuplicate(u, &u0); CHKERRQ(ierr);
ierr = SetInitial(u0, &user); CHKERRQ(ierr);
ierr = FreeExact(u0, tf, uexact, &user); CHKERRQ(ierr);
//ierr = VecView(uexact, PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
ierr = VecAXPY(u, -1.0, uexact); CHKERRQ(ierr); // u <- u - uexact
ierr = VecNorm(u, NORM_INFINITY, &errnorm); CHKERRQ(ierr);
VecDestroy(&u0); VecDestroy(&uexact);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"numerical error at tf in free problem: |u-uexact|_inf = %.5e\n",
errnorm); CHKERRQ(ierr);
}
// report
ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr);
if (user.free)
strcpy(probstr, "free");
ierr = PetscPrintf(PETSC_COMM_WORLD,
"%s problem solved to tf = %.3f (%d steps)\n",
probstr, tf, steps); CHKERRQ(ierr);
MatDestroy(&A); VecDestroy(&u); TSDestroy(&ts);
return PetscFinalize();
}
/* Regarding the following functions:
In the rod case the solution is a 10-dimensional vector u.
Here is the correspondence with the notes (doc/rod.pdf):
u[0] = q_1 (= x_1)
u[1] = q_2 (= y_1)
u[2] = q_3 (= x_2)
u[3] = q_4 (= y_2)
u[4] = v_1 (= dx_1/dt)
u[5] = v_2 (= dy_1/dt)
u[6] = v_3 (= dx_2/dt)
u[7] = v_4 (= dy_2/dt)
u[8] = mu
u[9] = lambda
*/
PetscErrorCode SetInitial(Vec u, RodCtx *user) {
/* Set initial conditions compatible with the rod constraint
0 = g(q) = (1/2) ( (q1 - q3)^2 + (q2 - q4)^2 - l^2 ) (1)
and the velocity constraint
0 = G(q) v = (q1 - q3)(v1 - v3) + (q2 - q4)(v2 - v4) (2)
The initial conditions are based on the location of the first mass
being at cartesian location (q1,q2)=(0,1) and the second at
(q3,q4)=(0,1+l). The initial velocity of the first mass is
(v1,v2)=(10,10) and the second is (v3,v4)=(15,10). In fact we
adjust q4 and v4 from the other values so as to satisfy constraints
(1) and (2). The initial value mu=0 is always set. We set lambda
from the other values according to the acceleration constraint
lambda = (m / (2 l^2)) ((v1-v3)^2 + (v2-v4)^2) (3)
Initial values of mu and lambda are ignored in BDF solutions. */
PetscErrorCode ierr;
const PetscReal c = user->m / (2.0 * user->l * user->l);
PetscReal *au;
ierr = VecGetArray(u,&au); CHKERRQ(ierr);
au[0] = 0.0; // q1 = x1
au[1] = 1.0; // q2 = y1
au[2] = 0.0; // q3 = x2
au[3] = au[1] + user->l; // q4 = y2; satisfies (1)
au[4] = 10.0; // v1
au[5] = 10.0; // v2
au[6] = 15.0; // v3
au[7] = au[5]; // v4; satisfies (2)
au[8] = 0.0; // mu
if (user->free)
au[9] = 0.0;
else // set lambda to satisfy (3)
au[9] = c * ( (au[4] - au[6]) * (au[4] - au[6])
+ (au[5] - au[7]) * (au[5] - au[7]));
ierr = VecRestoreArray(u,&au); CHKERRQ(ierr);
return 0;
}
PetscErrorCode FreeExact(Vec u0, PetscReal tf, Vec uexact, RodCtx *user) {
/* Exact solution based on parabolic motion. Problem
m x'' = 0, x(0) = x0, x'(0) = v0
m y'' = - m g, y(0) = y0, y'(0) = w0
has solution
x(t) = x0 + v0 t, x'(t) = v0,
y(t) = y0 + w0 t - (g/2) t^2, y'(t) = w0 - g t */
PetscErrorCode ierr;
PetscReal *au0, *auex;
if (!user->free) {
SETERRQ(PETSC_COMM_SELF,7,"exact solution only implemented for free\n");
}
ierr = VecGetArray(u0, &au0); CHKERRQ(ierr);
ierr = VecGetArray(uexact, &auex); CHKERRQ(ierr);
auex[0] = au0[0] + au0[4] * tf;
auex[1] = au0[1] + au0[5] * tf - 0.5 * user->g * tf * tf;
auex[2] = au0[2] + au0[6] * tf;
auex[3] = au0[3] + au0[7] * tf - 0.5 * user->g * tf * tf;
auex[4] = au0[4];
auex[5] = au0[5] - user->g * tf;
auex[6] = au0[6];
auex[7] = au0[7] - user->g * tf;
auex[8] = 0.0; // mu
auex[9] = 0.0; // lambda
ierr = VecRestoreArray(u0, &au0); CHKERRQ(ierr);
ierr = VecRestoreArray(uexact, &auex); CHKERRQ(ierr);
return 0;
}
PetscErrorCode LagrangeIFcn(TS ts, PetscReal t, Vec u, Vec udot, Vec F,
void *ctx) {
PetscErrorCode ierr;
RodCtx *user = (RodCtx*)ctx;
const PetscReal *au, *audot, mg = user->m * user->g;
PetscReal *aF, dx, dy, dvx, dvy;
PetscFunctionBeginUser;
ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);
ierr = VecGetArrayRead(udot,&audot); CHKERRQ(ierr);
ierr = VecGetArray(F,&aF); CHKERRQ(ierr);
dx = au[0] - au[2];
dy = au[1] - au[3];
dvx = au[4] - au[6];
dvy = au[5] - au[7];
aF[0] = audot[0] - au[4] + au[8] * dx;
aF[1] = audot[1] - au[5] + au[8] * dy;
aF[2] = audot[2] - au[6] - au[8] * dx;
aF[3] = audot[3] - au[7] - au[8] * dy;
aF[4] = user->m * audot[4] + au[9] * dx;
aF[5] = user->m * audot[5] + mg + au[9] * dy;
aF[6] = user->m * audot[6] - au[9] * dx;
aF[7] = user->m * audot[7] + mg - au[9] * dy;
if (user->free) { // trivial index 1 DAE
aF[8] = au[8]; // equation: mu = 0
aF[9] = au[9]; // equation: lambda = 0
} else {
aF[8] = 0.5 * ( dx * dx + dy * dy - user->l * user->l ); // constraint
aF[9] = dx * dvx + dy * dvy; // velocity constraint
}
ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr);
ierr = VecRestoreArrayRead(udot,&audot); CHKERRQ(ierr);
ierr = VecRestoreArray(F,&aF); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscErrorCode LagrangeIJac(TS ts, PetscReal t, Vec u, Vec udot,
PetscReal sigma, Mat J, Mat Jpre, void *ctx) {
PetscErrorCode ierr;
RodCtx *user = (RodCtx*)ctx;
const PetscReal *au;
PetscInt row, col[8], n; // max nonzeros in a row of J is 4
PetscReal val[8];
PetscFunctionBeginUser;
ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);
// construct Jacobian by rows, inserting nonzeros
row = 0; n = 4; // row 0 has 4 nonzeros ...
col[0] = 0; col[1] = 2; col[2] = 4; col[3] = 8;
val[0] = sigma + au[8]; val[1] = - au[8];
val[2] = -1; val[3] = au[0] - au[2];
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
row = 1; n = 4;
col[0] = 1; col[1] = 3; col[2] = 5; col[3] = 8;
val[0] = sigma + au[8]; val[1] = - au[8];
val[2] = -1; val[3] = au[1] - au[3];
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
row = 2; n = 4;
col[0] = 0; col[1] = 2; col[2] = 6; col[3] = 8;
val[0] = - au[8]; val[1] = sigma + au[8];
val[2] = -1; val[3] = -(au[0] - au[2]);
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
row = 3; n = 4;
col[0] = 1; col[1] = 3; col[2] = 7; col[3] = 8;
val[0] = - au[8]; val[1] = sigma + au[8];
val[2] = -1; val[3] = -(au[1] - au[3]);
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
row = 4; n = 4;
col[0] = 0; col[1] = 2; col[2] = 4; col[3] = 9;
val[0] = au[9]; val[1] = - au[9];
val[2] = sigma*user->m; val[3] = au[0] - au[2];
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
row = 5; n = 4;
col[0] = 1; col[1] = 3; col[2] = 5; col[3] = 9;
val[0] = au[9]; val[1] = - au[9];
val[2] = sigma*user->m; val[3] = au[1] - au[3];
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
row = 6; n = 4;
col[0] = 0; col[1] = 2; col[2] = 6; col[3] = 9;
val[0] = -au[9]; val[1] = au[9];
val[2] = sigma*user->m; val[3] = -(au[0] - au[2]);
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
row = 7; n = 4;
col[0] = 1; col[1] = 3; col[2] = 7; col[3] = 9;
val[0] = -au[9]; val[1] = au[9];
val[2] = sigma*user->m; val[3] = -(au[1] - au[3]);
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
if (user->free) {
n = 1;
row = 8; col[0] = 8; val[0] = 1.0; // equation mu = 0
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
row = 9; col[0] = 9; val[0] = 1.0; // equation lambda = 0
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
} else {
n = 4; row = 8; n = 4;
col[0] = 0; col[1] = 1; col[2] = 2; col[3] = 3;
val[0] = au[0] - au[2]; val[1] = au[1] - au[3];
val[2] = -(au[0] - au[2]); val[3] = -(au[1] - au[3]);
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
n = 4; row = 9; n = 8;
col[0] = 0; col[1] = 1; col[2] = 2; col[3] = 3;
col[4] = 4; col[5] = 5; col[6] = 6; col[7] = 7;
val[0] = au[4] - au[6]; val[1] = au[5] - au[7];
val[2] = -(au[4] - au[6]); val[3] = -(au[5] - au[7]);
val[4] = au[0] - au[2]; val[5] = au[1] - au[3];
val[6] = -(au[0] - au[2]); val[7] = -(au[1] - au[3]);
ierr = MatSetValues(J,1,&row,n,col,val,INSERT_VALUES); CHKERRQ(ierr);
}
ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr);
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
if (J != Jpre) {
ierr = MatAssemblyBegin(Jpre,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(Jpre,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
}
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.5505774315,
"avg_line_length": 44.2276923077,
"ext": "c",
"hexsha": "365bee8d7f9e4289998371d260b05c44b9fa3f9a",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "fffd181c719e97fe1e28d01a41678357a9abde6a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bueler/dae-examples",
"max_forks_repo_path": "petsc/rod.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fffd181c719e97fe1e28d01a41678357a9abde6a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "bueler/dae-examples",
"max_issues_repo_path": "petsc/rod.c",
"max_line_length": 165,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "fffd181c719e97fe1e28d01a41678357a9abde6a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bueler/dae-examples",
"max_stars_repo_path": "petsc/rod.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5173,
"size": 14374
} |
#pragma once
#include "Cesium3DTiles/BoundingVolume.h"
#include "Cesium3DTiles/Gltf.h"
#include "Cesium3DTiles/Library.h"
#include "Cesium3DTiles/RasterMappedTo3DTile.h"
#include "Cesium3DTiles/RasterOverlayTile.h"
#include "Cesium3DTiles/TileContext.h"
#include "Cesium3DTiles/TileID.h"
#include "Cesium3DTiles/TileRefine.h"
#include "Cesium3DTiles/TileSelectionState.h"
#include "CesiumAsync/IAssetRequest.h"
#include "CesiumGeospatial/Projection.h"
#include "CesiumUtility/DoublyLinkedList.h"
#include <atomic>
#include <glm/mat4x4.hpp>
#include <gsl/span>
#include <memory>
#include <optional>
#include <string>
#include <vector>
namespace Cesium3DTiles {
class Tileset;
class TileContent;
struct TileContentLoadResult;
/**
* @brief A tile in a {@link Tileset}.
*
* The tiles of a tileset form a hierarchy, where each tile may contain
* renderable content, and each tile has an associated bounding volume.
*
* The actual hierarchy is represented with the {@link Tile::getParent}
* and {@link Tile::getChildren} functions.
*
* The renderable content is provided as a {@link TileContentLoadResult}
* from the {@link Tile::getContent} function.
* The {@link Tile::getGeometricError} function returns the geometric
* error of the representation of the renderable content of a tile.
*
* The {@link BoundingVolume} is given by the {@link Tile::getBoundingVolume}
* function. This bounding volume encloses the renderable content of the
* tile itself, as well as the renderable content of all children, yielding
* a spatially coherent hierarchy of bounding volumes.
*
* The bounding volume of the content of an individual tile is given
* by the {@link Tile::getContentBoundingVolume} function.
*
*/
class CESIUM3DTILES_API Tile final {
public:
/**
* The current state of this tile in the loading process.
*/
enum class LoadState {
/**
* @brief This tile is in the process of being destroyed.
*
* Any pointers to it will soon be invalid.
*/
Destroying = -3,
/**
* @brief Something went wrong while loading this tile and it will not be
* retried.
*/
Failed = -2,
/**
* @brief Something went wrong while loading this tile, but it may be a
* temporary problem.
*/
FailedTemporarily = -1,
/**
* @brief The tile is not yet loaded at all, beyond the metadata in
* tileset.json.
*/
Unloaded = 0,
/**
* @brief The tile content is currently being loaded.
*
* Note that while a tile is in this state, its {@link Tile::getContent},
* and {@link Tile::getState}, methods may be called from the load thread,
* and the state may change due to the internal loading process.
*/
ContentLoading = 1,
/**
* @brief The tile content has finished loading.
*/
ContentLoaded = 2,
/**
* @brief The tile is completely done loading.
*/
Done = 3
};
/**
* @brief Default constructor for an empty, uninitialized tile.
*/
Tile() noexcept;
/**
* @brief Default destructor, which clears all resources associated with this
* tile.
*/
~Tile();
/**
* @brief Copy constructor.
*
* @param rhs The other instance.
*/
Tile(Tile& rhs) noexcept = delete;
/**
* @brief Move constructor.
*
* @param rhs The other instance.
*/
Tile(Tile&& rhs) noexcept;
/**
* @brief Move assignment operator.
*
* @param rhs The other instance.
*/
Tile& operator=(Tile&& rhs) noexcept;
/**
* @brief Returns the {@link Tileset} to which this tile belongs.
*/
Tileset* getTileset() noexcept { return this->_pContext->pTileset; }
/** @copydoc Tile::getTileset() */
const Tileset* getTileset() const noexcept {
return this->_pContext->pTileset;
}
/**
* @brief Returns the {@link TileContext} of this tile.
*
* This function is not supposed to be called by clients.
*
* @return The tile context.
*/
TileContext* getContext() noexcept { return this->_pContext; }
/** @copydoc Tile::getContext() */
const TileContext* getContext() const noexcept { return this->_pContext; }
/**
* @brief Set the {@link TileContext} of this tile.
*
* This function is not supposed to be called by clients.
*
* @param pContext The tile context.
*/
void setContext(TileContext* pContext) noexcept {
this->_pContext = pContext;
}
/**
* @brief Returns the parent of this tile in the tile hierarchy.
*
* This will be the `nullptr` if this is the root tile.
*
* @return The parent.
*/
Tile* getParent() noexcept { return this->_pParent; }
/** @copydoc Tile::getParent() */
const Tile* getParent() const noexcept { return this->_pParent; }
/**
* @brief Set the parent of this tile.
*
* This function is not supposed to be called by clients.
*
* @param pParent The parent tile .
*/
void setParent(Tile* pParent) noexcept { this->_pParent = pParent; }
/**
* @brief Returns a *view* on the children of this tile.
*
* The returned span will become invalid when this tile is destroyed.
*
* @return The children of this tile.
*/
gsl::span<Tile> getChildren() noexcept {
return gsl::span<Tile>(this->_children);
}
/** @copydoc Tile::getChildren() */
gsl::span<const Tile> getChildren() const noexcept {
return gsl::span<const Tile>(this->_children);
}
/**
* @brief Allocates space for the given number of child tiles.
*
* This function is not supposed to be called by clients.
*
* @param count The number of child tiles.
* @throws `std::runtime_error` if this tile already has children.
*/
void createChildTiles(size_t count);
/**
* @brief Assigns the given child tiles to this tile.
*
* This function is not supposed to be called by clients.
*
* @param children The child tiles.
* @throws `std::runtime_error` if this tile already has children.
*/
void createChildTiles(std::vector<Tile>&& children);
/**
* @brief Returns the {@link BoundingVolume} of this tile.
*
* This is a bounding volume that encloses the content of this tile,
* as well as the content of all child tiles.
*
* @see Tile::getContentBoundingVolume
*
* @return The bounding volume.
*/
const BoundingVolume& getBoundingVolume() const noexcept {
return this->_boundingVolume;
}
/**
* @brief Set the {@link BoundingVolume} of this tile.
*
* This function is not supposed to be called by clients.
*
* @param value The bounding volume.
*/
void setBoundingVolume(const BoundingVolume& value) noexcept {
this->_boundingVolume = value;
}
/**
* @brief Returns the viewer request volume of this tile.
*
* The viewer request volume is an optional {@link BoundingVolume} that
* may be associated with a tile. It allows controlling the rendering
* process of the tile content: If the viewer request volume is present,
* then the content of the tile will only be rendered when the viewer
* (i.e. the camera position) is inside the viewer request volume.
*
* @return The viewer request volume, or an empty optional.
*/
const std::optional<BoundingVolume>& getViewerRequestVolume() const noexcept {
return this->_viewerRequestVolume;
}
/**
* @brief Set the viewer request volume of this tile.
*
* This function is not supposed to be called by clients.
*
* @param value The viewer request volume.
*/
void
setViewerRequestVolume(const std::optional<BoundingVolume>& value) noexcept {
this->_viewerRequestVolume = value;
}
/**
* @brief Returns the geometric error of this tile.
*
* This is the error, in meters, introduced if this tile is rendered and its
* children are not. This is used to compute screen space error, i.e., the
* error measured in pixels.
*
* @return The geometric error of this tile, in meters.
*/
double getGeometricError() const noexcept { return this->_geometricError; }
/**
* @brief Set the geometric error of the contents of this tile.
*
* This function is not supposed to be called by clients.
*
* @param value The geometric error, in meters.
*/
void setGeometricError(double value) noexcept {
this->_geometricError = value;
}
/**
* @brief The refinement strategy of this tile.
*
* Returns the {@link TileRefine} value that indicates the refinement strategy
* for this tile. This is `Add` when the content of the
* child tiles is *added* to the content of this tile during refinement, and
* `Replace` when the content of the child tiles *replaces*
* the content of this tile during refinement.
*
* @return The refinement strategy.
*/
TileRefine getRefine() const noexcept { return this->_refine; }
/**
* @brief Set the refinement strategy of this tile.
*
* This function is not supposed to be called by clients.
*
* @param value The refinement strategy.
*/
void setRefine(TileRefine value) noexcept { this->_refine = value; }
/**
* @brief Gets the transformation matrix for this tile.
*
* This matrix does _not_ need to be multiplied with the tile's parent's
* transform as this has already been done.
*
* @return The transform matrix.
*/
const glm::dmat4x4& getTransform() const noexcept { return this->_transform; }
/**
* @brief Set the transformation matrix for this tile.
*
* This function is not supposed to be called by clients.
*
* @param value The transform matrix.
*/
void setTransform(const glm::dmat4x4& value) noexcept {
this->_transform = value;
}
/**
* @brief Returns the {@link TileID} of this tile.
*
* This function is not supposed to be called by clients.
*
* @return The tile ID.
*/
const TileID& getTileID() const noexcept { return this->_id; }
/**
* @brief Set the {@link TileID} of this tile.
*
* This function is not supposed to be called by clients.
*
* @param id The tile ID.
*/
void setTileID(const TileID& id) noexcept;
/**
* @brief Returns the {@link BoundingVolume} of the renderable content of this
* tile.
*
* The content bounding volume is a bounding volume that tightly fits only the
* renderable content of the tile. This enables tighter view frustum culling,
* making it possible to exclude from rendering any content not in the view
* frustum.
*
* @see Tile::getBoundingVolume
*/
const std::optional<BoundingVolume>&
getContentBoundingVolume() const noexcept {
return this->_contentBoundingVolume;
}
/**
* @brief Set the {@link BoundingVolume} of the renderable content of this
* tile.
*
* This function is not supposed to be called by clients.
*
* @param value The content bounding volume
*/
void setContentBoundingVolume(
const std::optional<BoundingVolume>& value) noexcept {
this->_contentBoundingVolume = value;
}
/**
* @brief Returns the {@link TileContentLoadResult} for the content of this
* tile.
*
* This will be a `nullptr` if the content of this tile has not yet been
* loaded, as indicated by the indicated by the {@link Tile::getState} of this
* tile not being {@link Tile::LoadState::ContentLoaded}.
*
* @return The tile content load result, or `nullptr` if no content is loaded
*/
TileContentLoadResult* getContent() noexcept { return this->_pContent.get(); }
/** @copydoc Tile::getContent() */
const TileContentLoadResult* getContent() const noexcept {
return this->_pContent.get();
}
/**
* @brief Returns internal resources required for rendering this tile.
*
* This function is not supposed to be called by clients.
*
* @return The renderer resources.
*/
void* getRendererResources() const noexcept {
return this->_pRendererResources;
}
/**
* @brief Returns the {@link LoadState} of this tile.
*/
LoadState getState() const noexcept {
return this->_state.load(std::memory_order::memory_order_acquire);
}
/**
* @brief Returns the {@link TileSelectionState} of this tile.
*
* This function is not supposed to be called by clients.
*
* @return The last selection state
*/
TileSelectionState& getLastSelectionState() noexcept {
return this->_lastSelectionState;
}
/** @copydoc Tile::getLastSelectionState() */
const TileSelectionState& getLastSelectionState() const noexcept {
return this->_lastSelectionState;
}
/**
* @brief Set the {@link TileSelectionState} of this tile.
*
* This function is not supposed to be called by clients.
*
* @param newState The new stace
*/
void setLastSelectionState(const TileSelectionState& newState) noexcept {
this->_lastSelectionState = newState;
}
/**
* @brief Returns the raster overlay tiles that have been mapped to this tile.
*/
std::vector<RasterMappedTo3DTile>& getMappedRasterTiles() noexcept {
return this->_rasterTiles;
}
/** @copydoc Tile::getMappedRasterTiles() */
const std::vector<RasterMappedTo3DTile>&
getMappedRasterTiles() const noexcept {
return this->_rasterTiles;
}
/**
* @brief Determines if this tile is currently renderable.
*/
bool isRenderable() const noexcept;
/**
* @brief Trigger the process of loading the {@link Tile::getContent}.
*
* This function is not supposed to be called by clients.
*
* If this tile is not in its initial state (indicated by the
* {@link Tile::getState} of this tile being *not*
* {@link Tile::LoadState::Unloaded}), then nothing will be done.
*
* Otherwise, the tile will go into the
* {@link Tile::LoadState::ContentLoading} state, and the request for
* loading the tile content will be sent out.
* The function will then return, and the response of the request will
* be received asynchronously. Depending on the type of the tile and
* the response, the tile will eventually go into the
* {@link Tile::LoadState::ContentLoaded} state, and the
* {@link Tile::getContent} will be available.
*/
void loadContent();
/**
* @brief Frees all resources that have been allocated for the
* {@link Tile::getContent}.
*
* This function is not supposed to be called by clients.
*
* If the operation for loading the tile content is currently in progress, as
* indicated by the {@link Tile::getState} of this tile being
* {@link Tile::LoadState::ContentLoading}), then nothing will be done,
* and `false` will be returned.
*
* Otherwise, the resources that have been allocated for the tile content will
* be freed.
*
* @return Whether the content was unloaded.
*/
bool unloadContent() noexcept;
/**
* @brief Gives this tile a chance to update itself each render frame.
*
* @param previousFrameNumber The number of the previous render frame.
* @param currentFrameNumber The number of the current render frame.
*/
void update(int32_t previousFrameNumber, int32_t currentFrameNumber);
/**
* @brief Marks the tile as permanently failing to load.
*
* This function is not supposed to be called by clients.
*
* Moves the tile from the `FailedTemporarily` state to the `Failed` state.
* If the tile is not in the `FailedTemporarily` state, this method does
* nothing.
*/
void markPermanentlyFailed() noexcept;
/**
* @brief Determines the number of bytes in this tile's geometry and texture
* data.
*/
int64_t computeByteSize() const noexcept;
private:
/**
* @brief Set the {@link LoadState} of this tile.
*/
void setState(LoadState value) noexcept;
/**
* @brief Generates texture coordiantes for the raster overlays of the content
* of this tile.
*
* This will extend the accessors of the glTF model of the content of this
* tile with accessors that contain the texture coordinate sets for different
* projections. Further details are not specified here.
*
* @return The bounding region
*/
static std::optional<CesiumGeospatial::BoundingRegion>
generateTextureCoordinates(
CesiumGltf::Model& model,
const BoundingVolume& boundingVolume,
const std::vector<CesiumGeospatial::Projection>& projections);
/**
* @brief Upsample the parent of this tile.
*
* This method should only be called when this tile's parent is already
* loaded.
*/
void upsampleParent(std::vector<CesiumGeospatial::Projection>&& projections);
// Position in bounding-volume hierarchy.
TileContext* _pContext;
Tile* _pParent;
std::vector<Tile> _children;
// Properties from tileset.json.
// These are immutable after the tile leaves TileState::Unloaded.
BoundingVolume _boundingVolume;
std::optional<BoundingVolume> _viewerRequestVolume;
double _geometricError;
TileRefine _refine;
glm::dmat4x4 _transform;
TileID _id;
std::optional<BoundingVolume> _contentBoundingVolume;
// Load state and data.
std::atomic<LoadState> _state;
std::unique_ptr<TileContentLoadResult> _pContent;
void* _pRendererResources;
// Selection state
TileSelectionState _lastSelectionState;
// Overlays
std::vector<RasterMappedTo3DTile> _rasterTiles;
CesiumUtility::DoublyLinkedListPointers<Tile> _loadedTilesLinks;
public:
/**
* @brief A {@link CesiumUtility::DoublyLinkedList} for tile objects.
*/
typedef CesiumUtility::DoublyLinkedList<Tile, &Tile::_loadedTilesLinks>
LoadedLinkedList;
};
} // namespace Cesium3DTiles
| {
"alphanum_fraction": 0.6841084165,
"avg_line_length": 29.2570951586,
"ext": "h",
"hexsha": "e9da87a3a78f4da6d9aece239346f739b5603dd0",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "zy6p/cesium-native",
"max_forks_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Tile.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "zy6p/cesium-native",
"max_issues_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Tile.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d7b02d0c229e54e626e313bf2cfab31ed6e8ac3b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "zy6p/cesium-native",
"max_stars_repo_path": "Cesium3DTiles/include/Cesium3DTiles/Tile.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4329,
"size": 17525
} |
/*
* vbHmm_template.c
* Template for original model to be analyzed by VB-HMM.
*
* Created by OKAMOTO Kenji and SAKO Yasushi
* Copyright 2011
* Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.
* All rights reserved.
*
* Ver. 1.0.0
* Last modified on 2011.04.19
*/
#include <math.h>
#include <string.h>
// Special functions is probably necessary.
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_psi.h>
#include "vbHmm_template.h"
// For random number generation.
#include "rand.h"
#ifdef _OPENMP
#include "omp.h"
#endif
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
static int isGlobalAnalysis = 0;
void setFunctions__(){
commonFunctions funcs;
funcs.newModelParameters = newModelParameters__;
funcs.freeModelParameters = freeModelParameters__;
funcs.newModelStats = newModelStats__;
funcs.freeModelStats = freeModelStats__;
funcs.initializeVbHmm = initializeVbHmm__;
funcs.pTilde_z1 = pTilde_z1__;
funcs.pTilde_zn_zn1 = pTilde_zn_zn1__;
funcs.pTilde_xn_zn = pTilde_xn_zn__;
funcs.calcStatsVars = calcStatsVars__;
funcs.maximization = maximization__;
funcs.varLowerBound = varLowerBound__;
funcs.reorderParameters = reorderParameters__;
funcs.outputResults = outputResults__;
setFunctions( funcs );
}
void setGFunctions__(){
gCommonFunctions funcs;
funcs.newModelParameters = newModelParameters__;
funcs.freeModelParameters = freeModelParameters__;
funcs.newModelStats = newModelStats__;
funcs.freeModelStats = freeModelStats__;
funcs.newModelStatsG = newModelStatsG__;
funcs.freeModelStatsG = freeModelStatsG__;
funcs.initializeVbHmmG = initializeVbHmmG__;
funcs.pTilde_z1 = pTilde_z1__;
funcs.pTilde_zn_zn1 = pTilde_zn_zn1__;
funcs.pTilde_xn_zn = pTilde_xn_zn__;
funcs.calcStatsVarsG = calcStatsVarsG__;
funcs.maximizationG = maximizationG__;
funcs.varLowerBoundG = varLowerBoundG__;
funcs.reorderParametersG = reorderParametersG__;
funcs.outputResultsG = outputResultsG__;
setGFunctions( funcs );
isGlobalAnalysis = 1;
}
// Redirect output function to that for model-specific data.
void outputResults__( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
output__Results( xn, gv, iv, logFP );
}
void outputResultsG__( xns, gv, ivs, logFP )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
FILE *logFP;
{
output__ResultsG( xns, gv, ivs, logFP );
}
void *newModelParameters__( xn, sNo )
xnDataSet *xn;
int sNo;
{
int i;
tempParameters *p = (void*)malloc( sizeof(tempParameters) );
p->uPiArr = (double*)malloc( sNo * sizeof(double) );
p->sumUPi = 0.0;
p->uAMat = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->uAMat[i] = (double*)malloc( sNo * sizeof(double) );
}
p->sumUAArr = (double*)malloc( sNo * sizeof(double) );
p->avgPi = (double *)malloc( sNo * sizeof(double) );
p->avgLnPi = (double *)malloc( sNo * sizeof(double) );
p->avgA = (double **)malloc( sNo * sizeof(double*) );
p->avgLnA = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->avgA[i] = (double *)malloc( sNo * sizeof(double) );
p->avgLnA[i] = (double *)malloc( sNo * sizeof(double) );
}
return p;
}
void freeModelParameters__( p, xn, sNo )
void **p;
xnDataSet *xn;
int sNo;
{
tempParameters *gp = *p;
int i;
free( gp->uPiArr );
for( i = 0 ; i < sNo ; i++ ){
free( gp->uAMat[i] );
}
free( gp->uAMat );
free( gp->sumUAArr );
free( gp->avgPi );
free( gp->avgLnPi );
for( i = 0 ; i < sNo ; i++ ){
free( gp->avgA[i] );
free( gp->avgLnA[i] );
}
free( gp->avgA );
free( gp->avgLnA );
free( *p );
*p = NULL;
}
void *newModelStats__( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
tempStats *s = (tempStats*)malloc( sizeof(tempStats) );
int i;
s->Ni = (double *)malloc( sNo * sizeof(double) );
s->Nij = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s->Nij[i] = (double *)malloc( sNo * sizeof(double) ); }
s->Nii = (double *)malloc( sNo * sizeof(double) );
return s;
} else {
return NULL;
}
}
void freeModelStats__( s, xn, gv, iv )
void **s;
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
tempStats *gs = *s;
int i;
free( gs->Ni );
for( i = 0 ; i < sNo ; i++ )
{ free( gs->Nij[i] ); }
free( gs->Nij );
free( gs->Nii );
free( gs );
*s = NULL;
}
}
void *newModelStatsG__( xns, gv, ivs)
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
int sNo = gv->sNo;
tempGlobalStats *gs = (tempGlobalStats*)malloc( sizeof(tempGlobalStats) );
int i;
gs->NiR = (double *)malloc( sNo * sizeof(double) );
gs->NijR = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ gs->NijR[i] = (double *)malloc( sNo * sizeof(double) ); }
gs->NiiR = (double *)malloc( sNo * sizeof(double) );
gs->z1iR = (double *)malloc( sNo * sizeof(double) );
return gs;
}
void freeModelStatsG__( gs, xns, gv, ivs )
void **gs;
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
int sNo = gv->sNo;
tempGlobalStats *ggs = *gs;
int i;
free( ggs->NiR );
for( i = 0 ; i < sNo ; i++ )
{ free( ggs->NijR[i] ); }
free( ggs->NijR );
free( ggs->NiiR );
free( ggs->z1iR );
free( *gs );
*gs = NULL;
}
void initializeVbHmm__( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// an example of hyperparameter initialization
int sNo = gv->sNo;
tempParameters *p = gv->params;
int i, j;
// hyper parameter for p( pi(i) )
p->sumUPi = 0.0;
for( i = 0 ; i < sNo ; i++ ){
p->uPiArr[i] = 1.0;
p->sumUPi += p->uPiArr[i];
}
// hyper parameter for p( A(i,j) )
for( i = 0 ; i < sNo ; i++ ){
p->sumUAArr[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
if( j == i ){
p->uAMat[i][j] = 5.0;
} else {
p->uAMat[i][j] = 1.0;
}
p->sumUAArr[i] += p->uAMat[i][j];
}
}
initialize_indVars__( xn, gv, iv );
calcStatsVars__( xn, gv, iv );
maximization__( xn, gv, iv );
}
void initializeVbHmmG__( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
// an example of hyperparameter initialization
int sNo = gv->sNo, rNo = xns->R;
tempParameters *p = gv->params;
int i, j, r;
p->sumUPi = 0.0;
for( i = 0 ; i < sNo ; i++ ){
p->uPiArr[i] = 1.0;
p->sumUPi += p->uPiArr[i];
}
for( i = 0 ; i < sNo ; i++ ){
p->sumUAArr[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
if( j == i ){
p->uAMat[i][j] = 5.0;
} else {
p->uAMat[i][j] = 1.0;
}
p->sumUAArr[i] += p->uAMat[i][j];
}
}
for( r = 0 ; r < rNo ; r++ ){
initialize_indVars__( xns->xn[r], gv, ivs->indVars[r] );
}
calcStatsVarsG__( xns, gv, ivs );
maximizationG__( xns, gv, ivs );
}
void initialize_indVars__( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// an example of latent variable distribution
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
int i;
size_t n;
double sumPar;
for( n = 0 ; n < dLen ; n++ ){
sumPar = 0.0;
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] = enoise(1.0) + 1.0;
sumPar += gmMat[n][i];
}
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] /= sumPar;
}
}
}
xnDataSet *newXnDataSet__( filename )
const char *filename;
{
xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );
xn->name = (char*)malloc( strlen(filename) + 2 );
strncpy( xn->name, filename, strlen(filename)+1 );
xn->data = (tempData*)malloc( sizeof(tempData) );
tempData *d = (tempData*)xn->data;
return xn;
}
void freeXnDataSet__( xn )
xnDataSet **xn;
{
tempData *d = (tempData*)(*xn)->data;
free( (*xn)->data );
free( (*xn)->name );
free( *xn );
*xn = NULL;
}
double pTilde_z1__( i, params )
int i;
void *params;
{
// Return the value for p(z_{1i}|pi_i) for given i.
// for common HMM
tempParameters *p = (tempParameters*)params;
return exp( p->avgLnPi[i] );
}
double pTilde_zn_zn1__( i, j, params )
int i, j;
void *params;
{
// Return the value for p(z_{nj}|z_{n-1,i},theta) for given i and j.
// for common HMM
tempParameters *p = (tempParameters*)params;
return exp( p->avgLnA[i][j] );
}
double pTilde_xn_zn__( xnWv, n, i, params )
xnDataSet *xnWv;
size_t n;
int i;
void *params;
{
// Return the value for p(x_{mi}|z_{ni},phi) for given i.
// return emission probability for the model.
tempParameters *p = (tempParameters*)params;
return 0.0;
}
void calcStatsVars__( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// Execute calculation of statistics, which may be necessary for M-step.
// calculation of stats for common HMM
tempStats *s = (tempStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *Nii = s->Nii, **Nij = s->Nij, *Ni = s->Ni;
size_t n;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
Ni[i] = 1e-10;
Nii[i] = 1e-10;
for( j = 0 ; j < sNo ; j++ ){
Nij[i][j] = 1e-10;
}
for( n = 0 ; n < dLen ; n++ ){
Ni[i] += gmMat[n][i];
for( j = 0 ; j < sNo ; j++ ){
Nii[i] += xiMat[n][i][j];
Nij[i][j] += xiMat[n][i][j];
}
}
}
}
void calcStatsVarsG__( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
// Execute calculation of statistics for global analysis, which may be necessary for M-step.
// calculation of stats for global analysis of common HMM
tempGlobalStats *gs = (tempGlobalStats*)ivs->stats;
int sNo = gv->sNo, rNo = xns->R;
double **gmMat, ***xiMat;
double *NiiR = gs->NiiR, **NijR = gs->NijR, *NiR = gs->NiR, *z1iR = gs->z1iR;
size_t dLen, n;
int i, j, r;
for( i = 0 ; i < sNo ; i++ ){
NiR[i] = 1e-10;
NiiR[i] = 1e-10;
for( j = 0 ; j < sNo ; j++ ){
NijR[i][j] = 1e-10;
}
z1iR[i] = 1e-10;
}
for( r = 0 ; r < rNo ; r++ ){
dLen = xns->xn[r]->N;
gmMat = ivs->indVars[r]->gmMat;
xiMat = ivs->indVars[r]->xiMat;
for( i = 0 ; i < sNo ; i++ ){
z1iR[i] += gmMat[0][i];
for( n = 0 ; n < dLen ; n++ ){
NiR[i] += gmMat[n][i];
for( j = 0 ; j < sNo ; j++ ){
NiiR[i] += xiMat[n][i][j];
NijR[i][j] += xiMat[n][i][j];
}
}
}
}
}
void maximization__( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// Calculation of M-step, depending on the model.
// calculation of M-step for common HMM
tempParameters *p = (tempParameters*)gv->params;
tempStats *s = (tempStats*)iv->stats;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *Nii = s->Nii, **Nij = s->Nij;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );
avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );
for( j = 0 ; j < sNo ; j++ ){
avgA[i][j] = ( uAMat[i][j] + Nij[i][j] ) / ( sumUAArr[i] + Nii[i] );
avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Nii[i] );
}
}
}
void maximizationG__( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
// Calculation of M-step for global analysis, depending on the model.
// calculation of stats for global analysis of common HMM
tempParameters *p = (tempParameters*)gv->params;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
tempGlobalStats *gs = (tempGlobalStats*)ivs->stats;
double *NiiR = gs->NiiR, **NijR = gs->NijR, *z1iR = gs->z1iR, dR = (double)(xns->R);
int sNo = gv->sNo;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
avgPi[i] = ( uPiArr[i] + z1iR[i] ) / ( sumUPi + dR );
avgLnPi[i] = gsl_sf_psi( uPiArr[i] + z1iR[i] ) - gsl_sf_psi( sumUPi + dR );
for( j = 0 ; j < sNo ; j++ ){
avgA[i][j] = ( uAMat[i][j] + NijR[i][j] ) / ( sumUAArr[i] + NiiR[i] );
avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + NijR[i][j] ) - gsl_sf_psi( sumUAArr[i] + NiiR[i] );
}
}
}
double varLowerBound__( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// Calculation of lower bound, depending on the model.
// calculation of lower bound of common HMM
tempParameters *p = (tempParameters*)gv->params;
tempStats *s = (tempStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, *cn = iv->cn;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;
double *Nii = s->Nii, **Nij = s->Nij;
size_t n;
int i, j;
double lnpPi = gsl_sf_lngamma(sumUPi);
double lnpA = 0.0;
double lnpPhi = 0.0; // ln p(phi) for model-specific parameters
double lnqPi = gsl_sf_lngamma(sumUPi + 1.0);
double lnqA = 0.0;
double lnqPhi = 0.0; // ln q(phi) for model-specific parameters
for( i = 0 ; i < sNo ; i++ ){
lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);
lnqPi += (uPiArr[i]+gmMat[0][i]-1.0) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1.0));
lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);
lnpA += gsl_sf_lngamma(sumUAArr[i]);
lnqA += gsl_sf_lngamma(sumUAArr[i] + Nii[i]);
for( j = 0 ; j < sNo ; j++ ){
lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);
lnqA += (uAMat[i][j] + Nij[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+Nij[i][j]) - gsl_sf_psi(sumUAArr[i]+Nii[i]));
lnqA -= gsl_sf_lngamma( uAMat[i][j] + Nij[i][j] );
}
}
double lnpX = 0.0;
for( n = 0 ; n < dLen ; n++ ){
lnpX += log( cn[n] );
}
double val;
val = lnpPi + lnpA + lnpPhi;
val -= lnqPi + lnqA + lnqPhi;
val += lnpX;
val += log(gsl_sf_fact(sNo));
return val;
}
double varLowerBoundG__( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
// Calculation of lower bound for global analysis, depending on the model.
// calculation of lower bound for global analysis of common HMM
int sNo = gv->sNo, rNo = xns->R;
tempParameters *p = (tempParameters*)gv->params;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;
tempGlobalStats *gs = (tempGlobalStats*)ivs->stats;
double *NiiR = gs->NiiR, **NijR = gs->NijR, *z1iR = gs->z1iR, dR = (double)xns->R;
size_t n;
int i, j, r;
double lnpPi = gsl_sf_lngamma(sumUPi);
double lnpA = 0.0;
double lnpPhi = 0.0; // ln p(phi) for model-specific parameters
double lnqPi = gsl_sf_lngamma(sumUPi + dR);
double lnqA = 0.0;
double lnqPhi = 0.0; // ln q(phi) for model-specific parameters
for( i = 0 ; i < sNo ; i++ ){
lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);
lnqPi += (uPiArr[i]+z1iR[i]-1.0) * (gsl_sf_psi(uPiArr[i]+z1iR[i]) - gsl_sf_psi(sumUPi+dR));
lnqPi -= gsl_sf_lngamma(uPiArr[i] + z1iR[i]);
lnpA += gsl_sf_lngamma(sumUAArr[i]);
lnqA += gsl_sf_lngamma(sumUAArr[i] + NiiR[i]);
for( j = 0 ; j < sNo ; j++ ){
lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);
lnqA += (uAMat[i][j] + NijR[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+NijR[i][j]) - gsl_sf_psi(sumUAArr[i]+NiiR[i]));
lnqA -= gsl_sf_lngamma( uAMat[i][j] + NijR[i][j] );
}
}
double lnpX = 0.0;
for( r = 0 ; r < rNo ; r++ ){
size_t dLen = xns->xn[r]->N;
for( n = 0 ; n < dLen ; n++ ){
lnpX += log( ivs->indVars[r]->cn[n] );
}
}
double val;
val = lnpPi + lnpA + lnpPhi;
val -= lnqPi + lnqA + lnqPhi;
val += lnpX;
val += log(gsl_sf_fact(sNo));
return val;
}
void reorderParameters__( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// Reorder states in the final result, for example, in the order of intensity.
// an example for common HMM.
tempParameters *p = (tempParameters*)gv->params;
tempStats *s = (tempStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *Ni = s->Ni;
size_t n;
int i, j;
int *index = (int*)malloc( sNo * sizeof(int) );
double *store = (double*)malloc( sNo * sizeof(double) );
double **s2D = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) ); }
// index indicates order of avgPi values (0=biggest avgMu -- sNo=smallest avgMu).
for( i = 0 ; i < sNo ; i++ ){
index[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgPi[i] < avgPi[j] ){
index[i]--;
} else if( avgPi[i] == avgPi[j] ){
if( j > i )
{ index[i]--; }
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgA[i][j] = s2D[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgLnA[i][j] = s2D[i][j]; }
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ni[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ni[i] = store[i]; }
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }
for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }
}
for( n = 0 ; n < dLen ; n++ ){
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }
}
}
for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }
free( s2D );
free( store );
free( index );
}
void reorderParametersG__( xns, gv, ivs )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
{
// Reorder states in the final result, for example, in the order of intensity.
// an example for global analysis of common HMM.
size_t dLen;
int sNo = gv->sNo, rNo = xns->R;
tempParameters *p = (tempParameters*)gv->params;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
size_t n;
int i, j, r;
int *index = (int*)malloc( sNo * sizeof(int) );
double *store = (double*)malloc( sNo * sizeof(double) );
double **s2D = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) ); }
// index indicates order of avgPi values (0=biggest avgMu -- sNo=smallest avgMu).
for( i = 0 ; i < sNo ; i++ ){
index[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgPi[i] < avgPi[j] ){
index[i]--;
} else if( avgPi[i] == avgPi[j] ){
if( j > i )
{ index[i]--; }
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgA[i][j] = s2D[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgLnA[i][j] = s2D[i][j]; }
}
double *NiR = ((tempGlobalStats*)ivs->stats)->NiR;
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = NiR[i]; }
for( i = 0 ; i < sNo ; i++ ){ NiR[i] = store[i]; }
for( r = 0 ; r < rNo ; r++ ){
double **gmMat = ivs->indVars[r]->gmMat;
dLen = xns->xn[r]->N;
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }
for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }
}
}
for( r = 0 ; r < rNo ; r++ ){
double ***xiMat = ivs->indVars[r]->xiMat;
dLen = xns->xn[r]->N;
for( n = 0 ; n < dLen ; n++ ){
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }
}
}
}
for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }
free( s2D );
free( store );
free( index );
}
void output__Results( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
// Output the final result (after reordering) in any format, e.g. stdout, stderr or files.
// an example for common HMM parameters.
tempParameters *p = (tempParameters*)gv->params;
int sNo = gv->sNo;
int i, j;
fprintf(logFP, " results: K = %d \n", sNo);
fprintf(logFP, " pi: ( %g", p->avgPi[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgPi[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " A_matrix: [");
for( i = 0 ; i < sNo ; i++ ){
fprintf(logFP, " ( %g", p->avgA[i][0]);
for( j = 1 ; j < sNo ; j++ )
{ fprintf(logFP, ", %g", p->avgA[i][j]); }
fprintf(logFP, ")");
}
fprintf(logFP, " ] \n\n");
char fn[256];
FILE *fp;
size_t n;
sprintf( fn, "%s.param%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
fprintf(fp, "pi");
for( i = 0 ; i < sNo ; i++ )
{ fprintf(fp, ", A%dx", i); }
fprintf(fp, "\n");
for( i = 0 ; i < sNo ; i++ ){
fprintf(fp, "%g", p->avgPi[i]);
for( j = 0 ; j < sNo ; j++ )
{ fprintf(fp, ", %g", p->avgA[j][i]); }
fprintf(fp, "\n");
}
fclose(fp);
}
sprintf( fn, "%s.Lq%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < gv->iteration ; n++ ){
fprintf( fp, "%24.20e\n", gv->LqArr[n] );
}
fclose(fp);
}
sprintf( fn, "%s.maxS%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < xn->N ; n++ ){
fprintf( fp, "%d\n", iv->stateTraj[n] );
}
fclose(fp);
}
}
void output__ResultsG( xns, gv, ivs, logFP )
xnDataBundle *xns;
globalVars *gv;
indVarBundle *ivs;
FILE *logFP;
{
// Output the final result (after reordering) in any format, e.g. stdout, stderr or files.
// an example for parameters of global analysis of common HMM.
int sNo = gv->sNo, rNo = xns->R;
tempParameters *p = (tempParameters*)gv->params;
int i, j, r;
fprintf(logFP, " results: K = %d \n", sNo);
fprintf(logFP, " pi: ( %g", p->avgPi[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgPi[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " A_matrix: [");
for( i = 0 ; i < sNo ; i++ ){
fprintf(logFP, " ( %g", p->avgA[i][0]);
for( j = 1 ; j < sNo ; j++ )
{ fprintf(logFP, ", %g", p->avgA[i][j]); }
fprintf(logFP, ")");
}
fprintf(logFP, " ] \n\n");
char fn[256];
FILE *fp;
size_t n;
sprintf( fn, "%s.param%03d", xns->xn[0]->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
fprintf(fp, "pi");
for( i = 0 ; i < sNo ; i++ )
{ fprintf(fp, ", A%dx", i); }
fprintf(fp, "\n");
for( i = 0 ; i < sNo ; i++ ){
fprintf(fp, "%g", p->avgPi[i]);
for( j = 0 ; j < sNo ; j++ )
{ fprintf(fp, ", %g", p->avgA[j][i]); }
fprintf(fp, "\n");
}
fclose(fp);
}
sprintf( fn, "%s.Lq%03d", xns->xn[0]->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < gv->iteration ; n++ ){
fprintf( fp, "%24.20e\n", gv->LqArr[n] );
}
fclose(fp);
}
for( r = 0 ; r < rNo ; r++ ){
xnDataSet *xn = xns->xn[r];
indVars *iv = ivs->indVars[r];
sprintf( fn, "%s.maxS%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < xn->N ; n++ ){
fprintf( fp, "%d\n", iv->stateTraj[n] );
}
fclose(fp);
}
}
}
//
| {
"alphanum_fraction": 0.4891213237,
"avg_line_length": 28.6419624217,
"ext": "c",
"hexsha": "2b4d85589d332f492a8b757218096442c7aa4a27",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "okamoto-kenji/varBayes-HMM",
"max_forks_repo_path": "C/vbHmm_template.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "okamoto-kenji/varBayes-HMM",
"max_issues_repo_path": "C/vbHmm_template.c",
"max_line_length": 126,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "okamoto-kenji/varBayes-HMM",
"max_stars_repo_path": "C/vbHmm_template.c",
"max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z",
"num_tokens": 9694,
"size": 27439
} |
/*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: lymastee@hotmail.com
*
* This file is part of the gslib project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#ifndef base_type_2aa01495_7feb_4c5e_ae38_9c775c29c9f1_h
#define base_type_2aa01495_7feb_4c5e_ae38_9c775c29c9f1_h
#include <assert.h>
#include <stdint.h>
#include <gslib/config.h>
__gslib_begin__
#ifdef _GS_X86
typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;
typedef wchar_t wchar;
typedef float real32;
typedef double real;
typedef uint8_t byte;
typedef uint16_t word;
typedef uint32_t dword;
typedef uint64_t qword;
typedef uint32_t uint;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;
typedef void* addrptr;
#ifdef _UNICODE
typedef wchar gchar;
#else
typedef char gchar;
#endif
template<class t>
struct typeof { typedef void type; };
/* virtual class ptr convert tools */
template<class ccp, class bcp>
inline int virtual_bias()
{
static typeof<ccp>::type c;
static const int bias = (int)&c - (int)static_cast<bcp>(&c);
return bias;
}
template<class ccp, class bcp>
inline ccp virtual_cast(bcp p)
{
byte* ptr = (byte*)p;
ptr += virtual_bias<ccp, bcp>();
return reinterpret_cast<ccp>(ptr);
}
#endif /* end of _GS_X86 */
template<class _ty>
inline _ty gs_min(_ty a, _ty b) { return a < b ? a : b; }
template<class _ty>
inline _ty gs_max(_ty a, _ty b) { return a > b ? a : b; }
template<class _ty>
inline _ty gs_clamp(_ty v, _ty a, _ty b)
{
assert(a <= b);
return gs_min(b, gs_max(a, v));
}
template<class _ty>
inline void gs_swap(_ty& a, _ty& b)
{
auto t = a;
a = b;
b = t;
}
__gslib_end__
#endif
| {
"alphanum_fraction": 0.7071129707,
"avg_line_length": 27.0566037736,
"ext": "h",
"hexsha": "f7b1bb9d91b60d77525cb28a4471af3bb447f3c4",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/gslib/basetype.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/gslib/basetype.h",
"max_line_length": 82,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/gslib/basetype.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z",
"num_tokens": 753,
"size": 2868
} |
// Copyright András Vukics 2021. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)
/// \briefFileDefault
#ifndef CPPQEDCORE_UTILS_ODE_GSL_H_INCLUDED
#define CPPQEDCORE_UTILS_ODE_GSL_H_INCLUDED
#include "ArrayTraits.h"
#include "ODE.h"
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
#include <cstddef>
namespace cppqedutils {
namespace ode_engine {
template <typename StateType>
class ControlledErrorStepperGSL
{
public:
using state_type=StateType;
using deriv_type=state_type;
using time_type=double;
using value_type=ElementType_t<StateType>;
using stepper_category=bno::controlled_stepper_tag;
ControlledErrorStepperGSL(double epsAbs, double epsRel)
: control_{gsl_odeiv2_control_standard_new(epsAbs,epsRel,1,1), [] (auto* ptr) {if (ptr) gsl_odeiv2_control_free(ptr);}} {}
private:
using ValueVector=std::vector<double>;
using Aux_t=std::tuple<SystemFunctional_t<double,StateType>&,Extents_t<Rank_v<StateType>>>;
public:
/// Realizes part of the logic of [gsl_odeiv2_evolve_apply](http://www.gnu.org/software/gsl/doc/html/ode-initval.html#c.gsl_odeiv2_evolve_apply)
/**
* Differences:
* - First-same-as-last steppers not supported (at the moment only RKCK is supported)
* - There is no guard against the stepsize becoming infinitesimal
*/
template <typename System, typename S>
auto try_step(System sys, S&& stateInOut, double& time, double& dtTry)
{
auto totalExtent=Size<StateType>::_(stateInOut);
if (!step_) { // this means that tryStep is called for the first time
step_.reset(gsl_odeiv2_step_alloc(gsl_odeiv2_step_rkck,totalExtent), [] (auto* ptr) {if (ptr) gsl_odeiv2_step_free(ptr);});
yerr_=std::make_shared<ValueVector>(totalExtent);
dydt_out_=std::make_shared<ValueVector>(totalExtent);
}
#ifndef NDEBUG
else if (!IsStorageContiguous<StateType>::_(stateInOut)) {
throw NonContiguousStorageException{"ControlledErrorStepperGSL::tryStep"};
}
else if (yerr_->size()!=Size<StateType>::_(stateInOut) || dydt_out_->size()!=Size<StateType>::_(stateInOut)) {
throw std::runtime_error("Dimensionality mismatch in ControlledErrorStepperGSL::tryStep");
}
#endif // NDEBUG
SystemFunctional_t<double,StateType> sysVariable=sys; // it’s important to convert `sys` (which can be a lambda) to a variable of known type
Aux_t aux{sysVariable,Extents<StateType>::_(stateInOut)};
gsl_odeiv2_system dydt{ControlledErrorStepperGSL::lowLevelSystemFunction,nullptr,totalExtent,&aux};
auto step_status = gsl_odeiv2_step_apply (step_.get(), time, dtTry, Data<StateType>::_(stateInOut), yerr_->data(), nullptr, dydt_out_->data(), &dydt);
if (step_status == GSL_EFAULT || step_status == GSL_EBADFUNC) throw std::runtime_error("GSL bad step_status");
if (step_status != GSL_SUCCESS) {
dtTry *= 0.5;
return bno::fail;
}
else {
time+=dtTry;
/* const auto hadjust_status = */
gsl_odeiv2_control_hadjust (control_.get(), step_.get(), Data<StateType>::_(stateInOut), yerr_->data(), dydt_out_->data(), &dtTry);
// if (hadjust_status == GSL_ODEIV_HADJ_DEC) throw std::runtime_error{"Unexpected change of dtTry in ControlledErrorStepperGSL::tryStep"};
return bno::success;
}
}
private:
static int lowLevelSystemFunction(double t, const double* y, double* dydt, void* aux)
{
auto [highLevelSystemFunction,arrayExtents] = *static_cast<Aux_t*>(aux);
const StateType yInterface(Create_c<StateType>::_(y,arrayExtents));
StateType dydtInterface(Create<StateType>::_(dydt,arrayExtents));
highLevelSystemFunction(yInterface,dydtInterface,t);
return GSL_SUCCESS;
}
std::shared_ptr<gsl_odeiv2_step> step_;
const std::shared_ptr<gsl_odeiv2_control> control_;
// Needs to be easily copyable, as Steppers are carried around by value
std::shared_ptr<ValueVector> yerr_, dydt_out_;
};
template <typename StateType>
struct MakeControlledErrorStepper<ControlledErrorStepperGSL<StateType>>
{
static auto _(double epsRel, double epsAbs)
{
return ControlledErrorStepperWithParameters<ControlledErrorStepperGSL<StateType>>{
{epsRel,epsAbs},epsRel,epsAbs};
}
template <typename ParsBase>
static auto _(const Pars<ParsBase>& p)
{
return _(p.epsRel,p.epsAbs);
}
};
template <typename StateType>
inline const std::string StepperDescriptor<ControlledErrorStepperGSL<StateType>> = "GSL RKCK controlled stepper";
} // ode_engine
template <typename StateType>
using ODE_EngineGSL = ode_engine::Base<ode_engine::ControlledErrorStepperGSL<StateType>>;
} // cppqedutils
#endif // CPPQEDCORE_UTILS_ODE_GSL_H_INCLUDED
| {
"alphanum_fraction": 0.7347670251,
"avg_line_length": 33.1678321678,
"ext": "h",
"hexsha": "5b6fe219404a0007bde5e5f7a56f0a6c5fe891b6",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-01-28T18:29:01.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-25T10:16:35.000Z",
"max_forks_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "vukics/cppqed",
"max_forks_repo_path": "CPPQEDutils/ODE_GSL.h",
"max_issues_count": 10,
"max_issues_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b",
"max_issues_repo_issues_event_max_datetime": "2021-07-04T20:11:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-04-14T11:18:02.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "vukics/cppqed",
"max_issues_repo_path": "CPPQEDutils/ODE_GSL.h",
"max_line_length": 154,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "vukics/cppqed",
"max_stars_repo_path": "CPPQEDutils/ODE_GSL.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-29T15:12:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-02-21T14:00:54.000Z",
"num_tokens": 1284,
"size": 4743
} |
#include "cconfigspace_internal.h"
#include <stdlib.h>
#include <gsl/gsl_rng.h>
const ccs_datum_t ccs_none = CCS_NONE_VAL;
const ccs_datum_t ccs_inactive = CCS_INACTIVE_VAL;
const ccs_datum_t ccs_true = CCS_TRUE_VAL;
const ccs_datum_t ccs_false = CCS_FALSE_VAL;
const ccs_version_t ccs_version = { 0, 1, 0, 0 };
ccs_result_t
ccs_init() {
gsl_rng_env_setup();
return CCS_SUCCESS;
}
ccs_result_t
ccs_fini() {
return CCS_SUCCESS;
}
ccs_version_t
ccs_get_version() {
return ccs_version;
}
ccs_result_t
ccs_retain_object(ccs_object_t object) {
_ccs_object_internal_t *obj = (_ccs_object_internal_t *)object;
if (!obj || obj->refcount <= 0)
return -CCS_INVALID_OBJECT;
obj->refcount += 1;
return CCS_SUCCESS;
}
ccs_result_t
ccs_release_object(ccs_object_t object) {
_ccs_object_internal_t *obj = (_ccs_object_internal_t *)object;
if (!obj || obj->refcount <= 0)
return -CCS_INVALID_OBJECT;
obj->refcount -= 1;
if (obj->refcount == 0) {
if (obj->callbacks) {
_ccs_object_callback_t *cb = NULL;
while ( (cb = (_ccs_object_callback_t *)
utarray_prev(obj->callbacks, cb)) ) {
cb->callback(object, cb->user_data);
}
utarray_free(obj->callbacks);
}
CCS_VALIDATE(obj->ops->del(object));
free(object);
}
return CCS_SUCCESS;
}
ccs_result_t
ccs_object_get_type(ccs_object_t object,
ccs_object_type_t *type_ret) {
_ccs_object_internal_t *obj = (_ccs_object_internal_t *)object;
if (!obj)
return -CCS_INVALID_OBJECT;
CCS_CHECK_PTR(type_ret);
*type_ret = obj->type;
return CCS_SUCCESS;
}
ccs_result_t
ccs_object_get_refcount(ccs_object_t object,
int32_t *refcount_ret) {
_ccs_object_internal_t *obj = (_ccs_object_internal_t *)object;
if (!obj)
return -CCS_INVALID_OBJECT;
CCS_CHECK_PTR(refcount_ret);
*refcount_ret = obj->refcount;
return CCS_SUCCESS;
}
static const UT_icd _object_callback_icd = {
sizeof(_ccs_object_callback_t),
NULL,
NULL,
NULL
};
ccs_result_t
ccs_object_set_destroy_callback(ccs_object_t object,
void (*callback)(
ccs_object_t object,
void *user_data),
void *user_data) {
_ccs_object_internal_t *obj = (_ccs_object_internal_t *)object;
if (!obj)
return -CCS_INVALID_OBJECT;
if (!callback)
return -CCS_INVALID_VALUE;
if (!obj->callbacks)
utarray_new(obj->callbacks, &_object_callback_icd);
_ccs_object_callback_t cb = { callback, user_data };
utarray_push_back(obj->callbacks, &cb);
return CCS_SUCCESS;
}
| {
"alphanum_fraction": 0.6931338703,
"avg_line_length": 24.8285714286,
"ext": "c",
"hexsha": "9931f0f85ed665dad30d183061de80f4b364a553",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z",
"max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "deephyper/CCS",
"max_forks_repo_path": "src/cconfigspace.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "deephyper/CCS",
"max_issues_repo_path": "src/cconfigspace.c",
"max_line_length": 64,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "deephyper/CCS",
"max_stars_repo_path": "src/cconfigspace.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z",
"num_tokens": 717,
"size": 2607
} |
static char help[] = "1D reaction-diffusion problem with DMDA and SNES. Option prefix -rct_.\n\n";
#include <petsc.h>
typedef struct {
PetscReal rho, M, alpha, beta;
PetscBool noRinJ;
} AppCtx;
extern PetscReal f_source(PetscReal);
extern PetscErrorCode InitialAndExact(DMDALocalInfo*, PetscReal*, PetscReal*, AppCtx*);
extern PetscErrorCode FormFunctionLocal(DMDALocalInfo*, PetscReal*, PetscReal*, AppCtx*);
extern PetscErrorCode FormJacobianLocal(DMDALocalInfo*, PetscReal*, Mat, Mat, AppCtx*);
//STARTMAIN
int main(int argc,char **args) {
PetscErrorCode ierr;
DM da;
SNES snes;
AppCtx user;
Vec u, uexact;
PetscReal errnorm, *au, *auex;
DMDALocalInfo info;
ierr = PetscInitialize(&argc,&args,NULL,help); if (ierr) return ierr;
user.rho = 10.0;
user.M = PetscSqr(user.rho / 12.0);
user.alpha = user.M;
user.beta = 16.0 * user.M;
user.noRinJ = PETSC_FALSE;
ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"rct_","options for reaction",""); CHKERRQ(ierr);
ierr = PetscOptionsBool("-noRinJ","do not include R(u) term in Jacobian",
"reaction.c",user.noRinJ,&(user.noRinJ),NULL); CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
ierr = DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,9,1,1,NULL,&da); CHKERRQ(ierr);
ierr = DMSetFromOptions(da); CHKERRQ(ierr);
ierr = DMSetUp(da); CHKERRQ(ierr);
ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr);
ierr = DMCreateGlobalVector(da,&u); CHKERRQ(ierr);
ierr = VecDuplicate(u,&uexact); CHKERRQ(ierr);
ierr = DMDAVecGetArray(da,u,&au); CHKERRQ(ierr);
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
ierr = DMDAVecGetArray(da,uexact,&auex); CHKERRQ(ierr);
ierr = InitialAndExact(&info,au,auex,&user); CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da,u,&au); CHKERRQ(ierr);
ierr = DMDAVecRestoreArray(da,uexact,&auex); CHKERRQ(ierr);
ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);
ierr = SNESSetDM(snes,da); CHKERRQ(ierr);
ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,
(DMDASNESFunction)FormFunctionLocal,&user); CHKERRQ(ierr);
ierr = DMDASNESSetJacobianLocal(da,
(DMDASNESJacobian)FormJacobianLocal,&user); CHKERRQ(ierr);
ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);
ierr = SNESSolve(snes,NULL,u); CHKERRQ(ierr);
ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uexact
ierr = VecNorm(u,NORM_INFINITY,&errnorm); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"on %d point grid: |u-u_exact|_inf = %g\n",info.mx,errnorm); CHKERRQ(ierr);
VecDestroy(&u); VecDestroy(&uexact);
SNESDestroy(&snes); DMDestroy(&da);
return PetscFinalize();
}
//ENDMAIN
PetscReal f_source(PetscReal x) {
return 0.0;
}
PetscErrorCode InitialAndExact(DMDALocalInfo *info, PetscReal *u0,
PetscReal *uex, AppCtx *user) {
PetscInt i;
PetscReal h = 1.0 / (info->mx-1), x;
for (i=info->xs; i<info->xs+info->xm; i++) {
x = h * i;
u0[i] = user->alpha * (1.0 - x) + user->beta * x;
uex[i] = user->M * PetscPowReal(x + 1.0,4.0);
}
return 0;
}
//STARTFUNCTIONS
PetscErrorCode FormFunctionLocal(DMDALocalInfo *info, PetscReal *u,
PetscReal *FF, AppCtx *user) {
PetscInt i;
PetscReal h = 1.0 / (info->mx-1), x, R;
for (i=info->xs; i<info->xs+info->xm; i++) {
if (i == 0) {
FF[i] = u[i] - user->alpha;
} else if (i == info->mx-1) {
FF[i] = u[i] - user->beta;
} else { // interior location
if (i == 1) {
FF[i] = - u[i+1] + 2.0 * u[i] - user->alpha;
} else if (i == info->mx-2) {
FF[i] = - user->beta + 2.0 * u[i] - u[i-1];
} else {
FF[i] = - u[i+1] + 2.0 * u[i] - u[i-1];
}
R = - user->rho * PetscSqrtReal(u[i]);
x = i * h;
FF[i] -= h*h * (R + f_source(x));
}
}
return 0;
}
PetscErrorCode FormJacobianLocal(DMDALocalInfo *info, PetscReal *u,
Mat J, Mat P, AppCtx *user) {
PetscErrorCode ierr;
PetscInt i, col[3];
PetscReal h = 1.0 / (info->mx-1), dRdu, v[3];
for (i=info->xs; i<info->xs+info->xm; i++) {
if ((i == 0) | (i == info->mx-1)) {
v[0] = 1.0;
ierr = MatSetValues(P,1,&i,1,&i,v,INSERT_VALUES); CHKERRQ(ierr);
} else {
col[0] = i;
v[0] = 2.0;
if (!user->noRinJ) {
dRdu = - (user->rho / 2.0) / PetscSqrtReal(u[i]);
v[0] -= h*h * dRdu;
}
col[1] = i-1; v[1] = (i > 1) ? - 1.0 : 0.0;
col[2] = i+1; v[2] = (i < info->mx-2) ? - 1.0 : 0.0;
ierr = MatSetValues(P,1,&i,3,col,v,INSERT_VALUES); CHKERRQ(ierr);
}
}
ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
if (J != P) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
//ENDFUNCTIONS
| {
"alphanum_fraction": 0.5791690599,
"avg_line_length": 35.7739726027,
"ext": "c",
"hexsha": "7c735248004ace19877f7850a960f37c3b5b261c",
"lang": "C",
"max_forks_count": 46,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z",
"max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "thw1021/p4pdes",
"max_forks_repo_path": "c/ch4/reaction.c",
"max_issues_count": 52,
"max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "thw1021/p4pdes",
"max_issues_repo_path": "c/ch4/reaction.c",
"max_line_length": 99,
"max_stars_count": 115,
"max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "thw1021/p4pdes",
"max_stars_repo_path": "c/ch4/reaction.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z",
"num_tokens": 1715,
"size": 5223
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <string.h>
double likelihood(double *y_obs, double* y_model);
void my_model(double *y_init, double *x_obs, double a, double b, double c, double d);
int minimo (double *arr, int nsteps, int nburn);
double std_dev(double *arr, int n_steps, int n_burn);
int main(int argc, char **argv){
int n_steps = atoi(argv[1]);
int n_burn = atoi(argv[2]);
int npoints = n_steps;
double *x_obs;
double *y_obs;
double *a_walk;
double *b_walk;
double *c_walk;
double *d_walk;
double *l_walk;
double *y_init;
double *y_prime;
FILE *in;
double var0;
double var1;
double var2;
double var3;
double var4;
x_obs = malloc(npoints * sizeof(double));
y_obs = malloc(npoints * sizeof(double));
a_walk = malloc(npoints * sizeof(double));
b_walk = malloc(npoints * sizeof(double));
c_walk = malloc(npoints * sizeof(double));
d_walk = malloc(npoints * sizeof(double));
l_walk = malloc(npoints * sizeof(double));
y_init = malloc(npoints * sizeof(double));
y_prime = malloc(npoints * sizeof(double));
in = fopen("monthrg.dat", "r");
if(!in){
printf("problems opening the file %s\n", "monthrg.dat");
exit(1);
}
int i;
for(i=0;i<4141;i++){
fscanf(in,"%lf %lf %lf %lf %lf\n", &var0, &var1, &var2, &var3, &var4);
if (var3!=-99){
x_obs[i] = var0 + var1/12.0;
y_obs[i] = var3;
// printf("%f %f\n",x_obs[i], var3);
}
}
fclose(in);
char output1[512];
char output2[512];
char* line = "_";
char* mcmc_solar = "mcmc_solar";
char* dat = ".dat";
char name[512] = "";
strcat(name,mcmc_solar);
strcat(name,line);
strcat(name,argv[1]);
strcat(name,line);
strcat(name,argv[2]);
strcat(name,dat);
//printf("%s\n", name);
srand((unsigned)time(NULL));
FILE *fp;
fp = fopen(name, "ab+");
a_walk[0]=((double)rand() / (double) (RAND_MAX/50.0));
b_walk[0]=((double)rand() / (double) (RAND_MAX/50.0));
c_walk[0]=((double)rand() / (double) (RAND_MAX/50.0));
d_walk[0]=((double)rand() / (double) (RAND_MAX/50.0));
// printf("%f %f %f %f\n",a_walk[0], b_walk[0], c_walk[0], d_walk[0]);
my_model (y_init, x_obs, a_walk[0], b_walk[0], c_walk[0], d_walk[0]);
l_walk[0] = likelihood(y_obs, y_init);
// printf("%f\n",l_walk[0]);
int j;
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
double a_prime;
double b_prime;
double c_prime;
double d_prime;
double l_prime;
double l_init;
double gamma;
double beta;
for (j = 0; j<n_steps; j++){
a_prime =(double)gsl_ran_gaussian(r, 0.1)+a_walk[j];
b_prime =(double)gsl_ran_gaussian(r, 0.1)+b_walk[j];
c_prime =(double)gsl_ran_gaussian(r, 0.1)+c_walk[j];
d_prime =(double)gsl_ran_gaussian(r, 0.1)+d_walk[j];
// printf("%f %f %f %f\n",a_walk[j], b_walk[j], c_walk[j], d_walk[j]);
my_model(y_init, x_obs, a_walk[j], b_walk[j], c_walk[j], d_walk[j]);
my_model(y_prime, x_obs, a_prime, b_prime, c_prime, d_prime);
l_prime = likelihood(y_obs, y_prime);
l_init = likelihood(y_obs, y_init);
gamma = -l_prime + l_init;
// printf("%f\n",gamma);
if(gamma>=0.0){
a_walk[j+1] = a_prime;
b_walk[j+1] = b_prime;
c_walk[j+1] = c_prime;
d_walk[j+1] = d_prime;
l_walk[j+1] = l_prime;
}
else{
beta = ((double)rand() / (double) (RAND_MAX/50.0));
if(beta<=exp(gamma)){
a_walk[j+1] = a_prime;
b_walk[j+1] = b_prime;
c_walk[j+1] = c_prime;
d_walk[j+1] = d_prime;
l_walk[j+1] = l_prime;
}
else{
a_walk[j+1] = a_walk[j];
b_walk[j+1] = b_walk[j];
c_walk[j+1] = c_walk[j];
d_walk[j+1] = d_walk[j];
l_walk[j+1] = l_init;
}
}
// printf("%f %f %f %f\n",a_walk[j], b_walk[j], c_walk[j], d_walk[j]);
}
double *a_burned;
double *b_burned;
double *c_burned;
double *d_burned;
double *l_burned;
double *x_burned;
a_burned = malloc(npoints * sizeof(double));
b_burned = malloc(npoints * sizeof(double));
c_burned = malloc(npoints * sizeof(double));
d_burned = malloc(npoints * sizeof(double));
l_burned = malloc(npoints * sizeof(double));
int co;
for (co = 0; co < n_steps-n_burn; co++){
a_burned[co] = a_walk[n_burn + co];
b_burned[co] = b_walk[n_burn + co];
c_burned[co] = c_walk[n_burn + co];
d_burned[co] = d_walk[n_burn + co];
l_burned[co] = l_walk[n_burn + co];
fprintf(fp, "%f %f %f %f %f\n",a_burned[co], b_burned[co], c_burned[co], d_burned[co], l_burned[co]);
//printf("%f %f %f %f %f\n",a_walk[co], b_walk[co], c_walk[co], d_walk[co], l_walk[co]);
}
int max_likelihood_id = minimo(l_burned, n_steps, n_burn);
// printf("%i\n", max_likelihood_id);
double best_a = a_burned[max_likelihood_id];
double best_b = b_burned[max_likelihood_id];
double best_c = c_burned[max_likelihood_id];
double best_d = d_burned[max_likelihood_id];
// printf("%f %f %f %f\n",a_burned[max_likelihood_id], b_burned[max_likelihood_id], c_burned[max_likelihood_id], d_burned[max_likelihood_id]);
printf("a = %f +/- %f\n",best_a, std_dev(a_burned, n_steps, n_burn));
printf("b = %f +/- %f\n",best_b, std_dev(b_burned, n_steps, n_burn));
printf("c = %f +/- %f\n",best_c, std_dev(c_burned, n_steps, n_burn));
printf("d = %f +/- %f\n",best_d, std_dev(d_burned, n_steps, n_burn));
fclose(fp);
gsl_rng_free(r);
return 0;
}
double likelihood(double *y_obs, double* y_model){
double chi_squared = 0.0;
int counter;
for (counter = 0; counter < 4141; counter++){
chi_squared = chi_squared + pow((y_obs[counter]-y_model[counter]),2);
}
return (1.0/2.0)*chi_squared;
}
void my_model(double *y_init, double *x_obs, double a, double b, double c, double d){
int counter2;
double pi = 3.14159265359;
for (counter2 = 0; counter2<4141; counter2++){
y_init[counter2] = a*cos((2*pi/d)*x_obs[counter2] + b) + c;
}
}
int minimo (double *arr, int nsteps, int nburn){
int c = 0;
double min = arr[0];
int minimo = 0;
for (c = 1; c<nsteps-nburn; c++){
if (arr[c] < min){
min = arr[c];
minimo = c;
}
}
return minimo;
}
double std_dev(double *arr, int n_steps, int n_burn){
double mean = 0.0, sum_dev = 0.0;
int k;
int n = n_steps-n_burn;
for (k=0; k<n; k++){
mean+=arr[k];
}
mean = mean/n;
for (k = 0; k<n; k++){
sum_dev+=(arr[k]-mean)*(arr[k]-mean);
}
return pow(sum_dev/n,0.5);
}
| {
"alphanum_fraction": 0.589939697,
"avg_line_length": 20.2351190476,
"ext": "c",
"hexsha": "5bb8238b485f39b42d7f0f441f9814d1c2561f70",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "03a2d8dcf6119c61e9f28edcf5488e2f7b8eccef",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "HanaAsakura/JuanAguilar_hw7",
"max_forks_repo_path": "Solar/mcmc_solar.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "03a2d8dcf6119c61e9f28edcf5488e2f7b8eccef",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "HanaAsakura/JuanAguilar_hw7",
"max_issues_repo_path": "Solar/mcmc_solar.c",
"max_line_length": 144,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "03a2d8dcf6119c61e9f28edcf5488e2f7b8eccef",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "HanaAsakura/JuanAguilar_hw7",
"max_stars_repo_path": "Solar/mcmc_solar.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2316,
"size": 6799
} |
#ifndef PETSCWRAPPER_H
#define PETSCWRAPPER_H
#include <petsc.h>
#include "../TPLs/eigen-git-mirror/Eigen/Eigen"
#include <iostream>
using namespace std;
//==============================================================================
int initPETScMat(Mat * A, int squareSize, int nonZeros);
int initPETScRectMat(Mat * A, int rows, int cols, int nonZeros);
int initPETScVec(Vec * A, int size);
int eigenVecToPETScVec(Eigen::VectorXd * x_e,Vec * x_p);
int petscVecToEigenVec(Vec * x_p,Eigen::VectorXd * x_e);
//==============================================================================
#endif
| {
"alphanum_fraction": 0.543946932,
"avg_line_length": 28.7142857143,
"ext": "h",
"hexsha": "65b1fc72962dff54420fbaa7950f01a0e48dc076",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-11-02T10:28:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-02T10:28:46.000Z",
"max_forks_repo_head_hexsha": "02485438a6b58a0210eb0b2da3db8a7a37b57bb9",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "khurrumsaleem/QuasiMolto",
"max_forks_repo_path": "libs/PETScWrapper.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "02485438a6b58a0210eb0b2da3db8a7a37b57bb9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "khurrumsaleem/QuasiMolto",
"max_issues_repo_path": "libs/PETScWrapper.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "02485438a6b58a0210eb0b2da3db8a7a37b57bb9",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "khurrumsaleem/QuasiMolto",
"max_stars_repo_path": "libs/PETScWrapper.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 138,
"size": 603
} |
#ifndef __DREAM_H__
#define __DREAM_H__
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_math.h>
#include <rapidjson/document.h>
#include <rng/RngStream.h>
#include "array.h"
typedef double (*LikFun)(int chain_id, int gen, const double* state,
const void* pars, bool recalc);
typedef void (*ReportFun)(int gen, int chain_id, int n,
const double* state, double lik,
int burnIn, const void* pars);
typedef struct t_dream_pars {
int vflag; /* vebose flag */
int maxEvals; /* max number of function evaluations */
int optimAlg; /* lock variables */
int numChains;
string fn; /* input filename */
string out_fn; /* output filename */
int appendFile; /* continue from previous state */
int report_interval; /* report interval for state */
int diagnostics; /* report diagnostics at the end of the run */
int burnIn; /* number of steps for which to run an adaptive proposal size */
int recalcLik; /* recalculate likelihood of previously evaluated states */
// DREAM variables
int collapseOutliers;
int gelmanEvals;
int loopSteps;
int deltaMax;
int pCR_update;
int nCR;
double noise;
double bstar_zero;
double scaleReductionCrit;
double reenterBurnin;
int nfree;
size_t nvar;
double* varLo;
double* varHi;
double* varInit;
int* varLock;
string* varName;
char* scale;
LikFun fun;
void* funPars;
ReportFun rfun;
} dream_pars;
void dream_pars_default(dream_pars* p);
void dream_pars_init_vars(dream_pars* p, size_t n);
int dream_pars_free_vars(dream_pars* p);
size_t dream_par_by_name(const dream_pars* p, string name);
void dream_pars_read_json(dream_pars* p, rapidjson::Value& jpars);
void dream_pars_from_json(dream_pars* p, rapidjson::Value& jpars);
void dream_set_init(dream_pars* p, int n,
const double* init, const string* name, const int* lock,
const double* lo, const double* hi, const char* scale);
int dream_restore_state(const dream_pars* p, Array3D<double>& state, Array2D<double>& lik, vector<double>& pCR, int& inBurnIn);
void dream_initialize(const dream_pars* p, rng::RngStream* rng, Array2DView<double>& state, ArrayView<double>& lik);
int dream(const dream_pars* p, rng::RngStream* rng);
void check_outliers(int t, Array2D<double>& lik, vector<double>& meanlik,
vector<bool>& outliers);
void gen_CR(rng::RngStream* rng, const vector<double>& pCR,
Array2D<int>& CRm, vector<unsigned>& L);
void gelman_rubin(Array3D<double>& state, vector<double>& scaleReduction,
const int* lockVar, int first = 0, int numIter = -1,
int adjustDF = 0);
#endif
| {
"alphanum_fraction": 0.6575525175,
"avg_line_length": 32.597826087,
"ext": "h",
"hexsha": "bdfd9ef999780efd22b8d9de87e374d816c4261c",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "52846467f9ae91f7c31a8983b913cf722de93218",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gaberoo/cdream",
"max_forks_repo_path": "dream.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "52846467f9ae91f7c31a8983b913cf722de93218",
"max_issues_repo_issues_event_max_datetime": "2016-10-29T15:00:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-29T15:00:00.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gaberoo/cdream",
"max_issues_repo_path": "dream.h",
"max_line_length": 127,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "52846467f9ae91f7c31a8983b913cf722de93218",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gaberoo/cdream",
"max_stars_repo_path": "dream.h",
"max_stars_repo_stars_event_max_datetime": "2018-02-03T11:48:27.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-09-07T23:49:41.000Z",
"num_tokens": 752,
"size": 2999
} |
/* const/test.c
*
* Copyright (C) 2003, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_const.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
int
main (void)
{
gsl_ieee_env_setup ();
/* Basic check to make sure the header files are functioning */
{
double c = GSL_CONST_MKS_SPEED_OF_LIGHT;
double eps = GSL_CONST_MKS_VACUUM_PERMITTIVITY;
double mu = GSL_CONST_MKS_VACUUM_PERMEABILITY;
gsl_test_rel (c, 1.0/sqrt(eps*mu), 1e-6, "speed of light (mks)");
}
{
double ly = GSL_CONST_CGS_LIGHT_YEAR;
double c = GSL_CONST_CGS_SPEED_OF_LIGHT;
double y = 365.2425 * GSL_CONST_CGS_DAY;
gsl_test_rel (ly, c * y, 1e-6, "light year (cgs)");
}
{
double c = GSL_CONST_MKSA_SPEED_OF_LIGHT;
double eps = GSL_CONST_MKSA_VACUUM_PERMITTIVITY;
double mu = GSL_CONST_MKSA_VACUUM_PERMEABILITY;
gsl_test_rel (c, 1.0/sqrt(eps*mu), 1e-6, "speed of light (mksa)");
}
{
double ly = GSL_CONST_CGSM_LIGHT_YEAR;
double c = GSL_CONST_CGSM_SPEED_OF_LIGHT;
double y = 365.2425 * GSL_CONST_CGSM_DAY;
gsl_test_rel (ly, c * y, 1e-6, "light year (cgsm)");
}
{
double micro = GSL_CONST_NUM_MICRO;
double mega = GSL_CONST_NUM_MEGA;
double kilo = GSL_CONST_NUM_KILO;
gsl_test_rel (mega/kilo, 1/(micro*kilo), 1e-10, "kilo (mega/kilo, 1/(micro*kilo))");
}
{
double d = GSL_CONST_MKSA_DEBYE;
double c = GSL_CONST_MKSA_SPEED_OF_LIGHT;
double desu = d * c * 1000.0;
gsl_test_rel (desu, 1e-18, 1e-10, "debye (esu)");
}
{
double k = GSL_CONST_MKSA_BOLTZMANN;
double c = GSL_CONST_MKSA_SPEED_OF_LIGHT;
double h = GSL_CONST_MKSA_PLANCKS_CONSTANT_H;
double s = 2 * pow(M_PI, 5.0) * pow(k, 4.0) / (15 * pow(c, 2.0) * pow(h, 3.0));
double sigma = GSL_CONST_MKSA_STEFAN_BOLTZMANN_CONSTANT;
gsl_test_rel(s, sigma, 1e-10, "stefan boltzmann constant");
}
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.6882546652,
"avg_line_length": 27.887755102,
"ext": "c",
"hexsha": "aa5aa1c798b195718e8be428eeb2cd34ffb8eff6",
"lang": "C",
"max_forks_count": 224,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z",
"max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "utdsimmons/ohpc",
"max_forks_repo_path": "tests/libs/gsl/tests/const/test.c",
"max_issues_count": 1096,
"max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "utdsimmons/ohpc",
"max_issues_repo_path": "tests/libs/gsl/tests/const/test.c",
"max_line_length": 88,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/const/test.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z",
"num_tokens": 867,
"size": 2733
} |
/**
* APER_CHECK - create a FITS image showing the locations of
* apertures.
*/
#ifndef _APER_CHECK_H
#define _APER_CHECK_H
#include <gsl/gsl_matrix.h>
#include "aXe_grism.h"
typedef struct
{
gsl_matrix *img;
}
aXe_mask;
extern aXe_mask *
aXe_mask_init (observation * ob);
extern void
add_ap_p_to_aXe_mask (ap_pixel * ap_p, aXe_mask * mask);
extern void
mark_trace_in_aXe_mask(ap_pixel * ap_p, aXe_mask *mask);
#endif
| {
"alphanum_fraction": 0.7262443439,
"avg_line_length": 16.3703703704,
"ext": "h",
"hexsha": "1fabcc212d04301a43aeef06d2f84a86907fd198",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/aper_check.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/aper_check.h",
"max_line_length": 60,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/aper_check.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 135,
"size": 442
} |
/**
* original author: Jochen K"upper
* author: Pierre Schnizer
* created: Jan 2002
* modified: May 2009
* file: pygsl/src/statistics/longmodule.c
* $Id: charmodule.c,v 1.9 2009/05/11 08:53:03 schnizer Exp $
*
*
*"
*/
#include <Python.h>
#include <pygsl/error_helpers.h>
#include <pygsl/block_helpers.h>
#include <gsl/gsl_statistics.h>
/* include real functions for different data-types */
#define STATMOD_APPEND_PY_TYPE(X) X ## Int
#if (defined PyGSL_NUMARRAY) || (defined PyGSL_NUMERIC)
#define STATMOD_APPEND_PYC_TYPE(X) X ## CHAR
#else /* PyGSL_NUMARRAY */
#define STATMOD_APPEND_PYC_TYPE(X) X ## BYTE
#endif /* PyGSL_NUMARRAY */
#define STATMOD_FUNC_EXT(X, Y) X ## _char ## Y
#define STATMOD_PY_AS_C PyInt_AsLong
#define STATMOD_C_TYPE char
#include "functions.c"
PyGSL_STATISTICS_INIT(char, "char")
/*
* Local Variables:
* mode: c
* c-file-style: "python"
* End:
*/
| {
"alphanum_fraction": 0.7058823529,
"avg_line_length": 19.170212766,
"ext": "c",
"hexsha": "d52f8777c1837f23d006a296762460d82ca828ea",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/src/statistics/charmodule.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/src/statistics/charmodule.c",
"max_line_length": 61,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/src/statistics/charmodule.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 268,
"size": 901
} |
#include "AFS.h"
#include "cs.h"
#include "AFS_ctmc.h"
#include "sparseExp.h"
#include "adkCSparse.h"
#include "adkGSL.h"
//#include "cuba.h"
#include <gsl/gsl_blas.h>
void fillExpectedAFS_unnorm(afsStateSpace *S, double *visitMat ,gsl_vector *rates, gsl_matrix *expAFS);
//fills a sparse transition matrix for Continuous Time model
struct cs_di_sparse *fillTransitionMatrix_ctmc(afsStateSpace *S, double *topol, int *moveType, int *nzCount,
int *dim1, int *dim2, double theta1, double theta2, double mig1, double mig2){
int i, j,k;
int N = S->nstates;
double c0r[N],c1r[N],m0r[N],m1r[N],totR[N],rowSums[N], tmp;;
struct cs_di_sparse *triplet;
//now allocate new cs_sparse obj
triplet = cs_spalloc(N, N, *nzCount + N , 1, 1); //alloc sparse mat with extra space for nonzero identity mats
for(i=0;i<N;i++){
c0r[i] = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) / theta1 ;
c1r[i] = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) / theta2;
m0r[i] = S->states[i]->aCounts[0] * mig1 ;
m1r[i] = S->states[i]->aCounts[1] * mig2 ;
totR[i] = c0r[i] + c1r[i] + m0r[i] + m1r[i];
rowSums[i] = 0.0;
}
for(k=0;k<*nzCount;k++){
i = dim1[k];
j= dim2[k];
switch(moveType[k]){
case 0: //coal pop0
tmp = c0r[i] / totR[i] * topol[k];
cs_entry(triplet,i,j,tmp);
rowSums[i] += tmp;
break;
case 1: //coal pop1
tmp = c1r[i] / totR[i] * topol[k];
cs_entry(triplet,i,j,tmp);
rowSums[i] += tmp;
break;
case 2: //mig pop0
tmp = m0r[i] / totR[i] * topol[k];
cs_entry(triplet,i,j,tmp);
rowSums[i] += tmp;
break;
case 3: //mig pop1
tmp = m1r[i] / totR[i] * topol[k];
cs_entry(triplet,i,j,tmp);
rowSums[i] += tmp;
break;
}
}
//now add diagonal elements; topol pre-set to -1
for(k=0;k<N;k++){
if((rowSums[k]) != 0.0){
cs_entry(triplet,k,k,0-rowSums[k]);
*nzCount += 1;
}
}
// cs_dropzeros(triplet);
// tmat = cs_compress(triplet);
// cs_spfree(triplet);
return(triplet);
}
//this only fills a new set of arrays
void fillTransitionMatrixArray_ctmc(afsStateSpace *S, double *topol, int *moveType, int *nzCount,
int *dim1, int *dim2, double theta1, double theta2, double mig1, double mig2,double *newArray,
int *newDim1, int *newDim2){
int i, j,k, newnz;
int N = S->nstates;
double c0r[N],c1r[N],m0r[N],m1r[N],totR[N],rowSums[N], tmp;;
for(i=0;i<N;i++){
c0r[i] = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) / theta1 ;
c1r[i] = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) / theta2;
m0r[i] = S->states[i]->aCounts[0] * mig1 ;
m1r[i] = S->states[i]->aCounts[1] * mig2 ;
totR[i] = c0r[i] + c1r[i] + m0r[i] + m1r[i];
rowSums[i] = 0.0;
}
newnz=0;
for(k=0;k<*nzCount;++k){
i = dim1[k];
j= dim2[k];
switch(moveType[k]){
case 0: //coal pop0
tmp = c0r[i] / totR[i] * topol[k];
newArray[k]=tmp;
newDim1[k] = i+1;
newDim2[k] = j+1;
rowSums[i] += tmp;
newnz++;
break;
case 1: //coal pop1
tmp = c1r[i] / totR[i] * topol[k];
newArray[k]=tmp;
newDim1[k] = i+1;
newDim2[k] = j+1;
rowSums[i] += tmp;
newnz++;
break;
case 2: //mig pop0
tmp = m0r[i] / totR[i] * topol[k];
newArray[k]=tmp;
newDim1[k] = i+1;
newDim2[k] = j+1;
rowSums[i] += tmp;
newnz++;
break;
case 3: //mig pop1
tmp = m1r[i] / totR[i] * topol[k];
newArray[k]=tmp;
newDim1[k] = i+1;
newDim2[k] = j+1;
rowSums[i] += tmp;
newnz++;
break;
}
}
//now add diagonal elements; topol pre-set to -1
for(k=0;k<N;k++){
if((rowSums[k]) != 0.0){
newArray[newnz]=0-rowSums[k];
newDim1[newnz] = k+1;
newDim2[newnz] = k+1;
newnz++;
}
}
//sanity check
// for(k=0;k<newnz;k++){
// printf("row: %d col: %d val: %g\n",newDim1[k],newDim2[k],newArray[k]);
// }
*nzCount = newnz;
}
//Functions for jointly computing CTMC transitions and embedded chain
//this function returns pointer to embedded Discrete MC trans Mat in sparse form, while filling rates vector and filling
// arrays for CTMC representation
struct cs_di_sparse * fillTransitionMatrixArray_embed_ctmc(afsStateSpace *S, double *topol, int *moveType, int *nzCount,
int *dim1, int *dim2, double theta1, double theta2, double mig1, double mig2,double *newArray,
int *newDim1, int *newDim2, gsl_vector *rates){
int i, j,k, newnz, abcount=0;
int N = S->nstates,abFlag;
double c0r[N],c1r[N],m0r[N],m1r[N],totR[N],rowSums[N], tmp;;
struct cs_di_sparse *triplet, *tmat;
gsl_vector_set_zero(rates);
//allocate new cs_sparse obj
triplet = cs_spalloc(N, N, *nzCount + N , 1, 1); //alloc sparse mat with extra space for nonzero identity mats
for(i=0;i<N;i++){
c0r[i] = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) / theta1 ;
// printf("co check:%f\n",c0r[i]);
if(theta2 == 0)
c1r[i] = 0.0;
else
c1r[i] = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) / theta2;
m0r[i] = S->states[i]->aCounts[0] * mig1 ;
m1r[i] = S->states[i]->aCounts[1] * mig2 ;
totR[i] = c0r[i] + c1r[i] + m0r[i] + m1r[i];
rowSums[i] = 0.0;
if(S->states[i]->nalleles > 1 && c0r[i] >= 0 && c1r[i] >= 0 && totR[i] != 0.0)
gsl_vector_set(rates,i,1.0/totR[i]);
else
gsl_vector_set(rates,i,0);
}
newnz=0;
for(k=0;k<*nzCount;k++){
i = dim1[k];
j= dim2[k];
// printf("i: %d, j:%d, movetype: %d\n",i,j,moveType[k]);
if(S->states[i]->nalleles ==1 || S->states[j]->nalleles ==1 )abFlag=1;
// if(S->states[i]->nalleles ==1 )abFlag=1;
else abFlag = 0;
switch(moveType[k]){
case 0: //coal pop0
if(totR[i]==0)tmp=0;
else tmp = c0r[i] / totR[i] * topol[k];
newArray[k]=tmp* totR[i];
newDim1[k] = i;
newDim2[k] = j;
rowSums[i] += tmp* totR[i];
if(abFlag==0)cs_entry(triplet,i,j,tmp);
break;
case 1: //coal pop1
if(totR[i]==0)tmp=0;
else tmp = c1r[i] / totR[i] * topol[k];
newArray[k]=tmp* totR[i];
newDim1[k] = i;
newDim2[k] = j;
rowSums[i] += tmp* totR[i];
if(abFlag==0)cs_entry(triplet,i,j,tmp);
break;
case 2: //mig pop0
if(totR[i]==0)tmp=0;
else tmp = m0r[i] / totR[i] * topol[k];
newArray[k]=tmp* totR[i];
newDim1[k] = i;
newDim2[k] = j;
rowSums[i] += tmp* totR[i];
if(abFlag==0)cs_entry(triplet,i,j,tmp);
break;
case 3: //mig pop1
if(totR[i]==0)tmp=0;
else tmp = m1r[i] / totR[i] * topol[k];
newArray[k]=tmp * totR[i];
newDim1[k] = i;
newDim2[k] = j;
rowSums[i] += tmp* totR[i];
if(abFlag==0)cs_entry(triplet,i,j,tmp);
break;
case -1:
abcount+=1;
break;
}
}
newnz=*nzCount ;
//now add diagonal elements; topol pre-set to -1
for(k=0;k<N;k++){
if((rowSums[k]) != 0.0){
newArray[newnz]=0.0-rowSums[k];
newDim1[newnz] = k;
newDim2[newnz] = k;
newnz++;
}
}
tmat = cs_compress(triplet);
cs_spfree(triplet);
*nzCount = newnz;
return(tmat);
}
//fills up an AFS matrix using expected times and a precalculated visitMat
void fillExpectedAFS_ctmc(afsStateSpace *S, double *visitMat, gsl_matrix *expAFS){
int j, k, l, m1, m2, count;
double tmpRes;
m1=expAFS->size1;
m2=expAFS->size2;
gsl_matrix_set_zero(expAFS);
for(j=0;j<S->nstates;j++){
if(S->states[j]->nalleles != 1){
for(k=0;k<m1;k++){
for(l=0;l<m2;l++){
count = gsl_matrix_int_get(S->states[j]->popMats[0],k,l) + gsl_matrix_int_get(S->states[j]->popMats[1],k,l);
tmpRes = gsl_matrix_get(expAFS,k,l) + (count * visitMat[j]);
gsl_matrix_set(expAFS,k,l, tmpRes);
}
}
}
}
// tmpRes = matrixSumDouble(expAFS);
// gsl_matrix_scale(expAFS, 1.0 / tmpRes);
}
//fills up an AFS matrix using expected times and a precalculated visitMat
void fillExpectedAFS_unnorm(afsStateSpace *S, double *visitMat ,gsl_vector *rates, gsl_matrix *expAFS){
int j, k, l, m1, m2, count;
double tmpRes;
m1=expAFS->size1;
m2=expAFS->size2;
gsl_matrix_set_zero(expAFS);
for(j=0;j<S->nstates;j++){
for(k=0;k<m1;k++){
for(l=0;l<m2;l++){
count = gsl_matrix_int_get(S->states[j]->popMats[0],k,l) + gsl_matrix_int_get(S->states[j]->popMats[1],k,l);
tmpRes = gsl_matrix_get(expAFS,k,l) + (count * gsl_vector_get(rates,j) * visitMat[j]);
// printf("tmpRes[%d][%d]: %f rates[j]: %f visits[j]: %f count: %d\n",tmpRes,k,l,gsl_vector_get(rates,j),visitMat[j],count);
gsl_matrix_set(expAFS,k,l, tmpRes);
}
}
}
}
//fills up an AFS matrix using expected times and a precalculated visitMat
void fillExpectedAFS_unnorm_mat(afsStateSpace *S, double **visitMat , double *initialStateProbs, gsl_vector *rates, gsl_matrix *expAFS){
int j, k, l,i, m1, m2, count;
double tmpRes,sum;
m1=expAFS->size1;
m2=expAFS->size2;
gsl_matrix_set_zero(expAFS);
for(j=0;j<S->nstates;j++){
for(k=0;k<m1;k++){
for(l=0;l<m2;l++){
count = gsl_matrix_int_get(S->states[j]->popMats[0],k,l) + gsl_matrix_int_get(S->states[j]->popMats[1],k,l);
sum=0.0;
for(i=0;i<S->nstates;i++){
sum += visitMat[i][j] * initialStateProbs[i];
}
tmpRes = gsl_matrix_get(expAFS,k,l) + (count * gsl_vector_get(rates,j) * sum);
// printf("tmpRes[%d][%d]: %f rates[j]: %f visits[j]: %f count: %d\n",k,l,tmpRes,gsl_vector_get(rates,j),sum,count);
gsl_matrix_set(expAFS,k,l, tmpRes);
}
}
}
}
/// I believe the below is now completely unused
//fillLogAFS -- uses cxsparse library for inversion -- will replace above
// void fillLogAFS(void * p){
// struct im_lik_params * params = (struct im_lik_params *) p;
// struct expoMatObj anExpoMatObj;
// int i,j, N = params->stateSpace->nstates;
// cs *spMat, *mt, *ident, *eye, *tmpMat ,*tmpMat2;
// double timeV, sum, thetaA, theta2, mig1, mig2;
// int Na;
// gsl_vector *tmpStates;
//
//
// //initialize some vectors
// gsl_vector_set_zero(params->rates);
// tmpStates = gsl_vector_alloc(N);
//
// //For straight MLE the paramVector takes the form [N2,NA,m1,m2,t]
// theta2 = gsl_vector_get(params->paramVector,0);
// thetaA = gsl_vector_get(params->paramVector,1);
// mig1 = gsl_vector_get(params->paramVector,2);
// mig2 = gsl_vector_get(params->paramVector,3);
// timeV = gsl_vector_get(params->paramVector,4);
// // printf("params-> %f %f %f %f %f\n",theta2,thetaA,mig1,mig2,timeV);
// //fill transMat
// tmpMat= fillTransitionMatrixArray_embed_ctmc(params->stateSpace, params->topA, params->moveA,
// &(params->nnz),params->dim1, params->dim2,1.0, theta2, mig1, mig2,
// params->new, params->newdim1, params->newdim2,params->rates);
//
// //using CSparse
// // S = (I-P)^-1
//
// //add negative ident
// ident = cs_spalloc(N,N,N,1,1);
// for(i=0;i<N;i++) cs_entry(ident,i,i,1);
// eye = cs_compress(ident);
// spMat = cs_add(eye,tmpMat,1.0,-1.0);
// mt = cs_transpose(spMat,1);
//
// ////Compute Entire Inverse Mat
// for(j=0;j<N;j++){
// //create unit array for solve
// for(i=0; i<N; i++)params->b[i] = 0.0;
// params->b[j]=1.0;
// cs_lusol(0, mt, params->b, 1e-12);
// for(i=0; i<N; i++){
// params->invMat[j][i]=params->b[i];
// gsl_matrix_set(params->invMatGSL,j,i,params->b[i]);
// }
// printf("inv mat row %d complete\n",j);
// }
//
// //Get Island Time 0-INF Unnormal
// gsl_matrix_set_zero(params->expAFS);
// for(i=0; i<N; i++)params->b[i] = params->invMat[0][i];
// fillExpectedAFS_unnorm(params->stateSpace, params->b,params->rates,params->expAFS);
// // printf("////////////////////Island Time 0 - INF unnormalized\n");
// // for(i=0;i< (params->expAFS->size1) ;i++){
// // for(j=0;j< (params->expAFS->size2);j++){
// // printf("%.5f ",gsl_matrix_get(params->expAFS,i,j));
// // }
// // printf("\n");
// // }
//
// //Matrix Exponentiation to get state vector at time t
// //
//
// //push indices
// for(i=0;i<params->nnz;i++){
// params->expodim1[i]=params->newdim1[i]+1;
// params->expodim2[i]=params->newdim2[i]+1;
//
// }
// //reset expoInit
// for(i = 0;i<N;i++){
// params->expoInit[i]=0.0;
// params->expoResult[i]=0.0;
// }
// params->expoInit[0] = 1.0;
//
// //sanity check ///////
// // for(i=0;i<params->nnz;i++){
// // printf("a[%d]=%f expodim1=%d expodim2=%d \n", i,params->anExpoMatObj->a[i],params->anExpoMatObj->ai[i],params->anExpoMatObj->aj[i]);
// // }
// // printf("rank=%d nnz=%d\n", params->anExpoMatObj->rank, params->anExpoMatObj->nnz);
//
// // for(i=0;i<N;i++)printf("params->anExpoMatObj->resultSpace[%d]=%f\n",i,params->anExpoMatObj->resultSpace[i]);
// // for(i=0;i<N;i++)printf("params->anExpoMatObj->initVec[%d]=%f\n",i,params->anExpoMatObj->initVec[i]);
//
// anExpoMatObj.ai = params->expodim1;
// anExpoMatObj.aj = params->expodim2;
// anExpoMatObj.a = params->new;
// anExpoMatObj.initVec = params->expoInit;
// anExpoMatObj.resultSpace = params->expoResult;
// // sparse_exponential_single_row(N, params->nnz, anExpoMatObj.ai, anExpoMatObj.aj,
// // anExpoMatObj.a, timeV,anExpoMatObj.initVec, params->expoResult, 0);
// //state vector at time t stored in b[i]
// for(i=0; i<N; i++){
// params->b[i] = params->expoResult[i];
// // printf("params->expoResult[%d]=%f\n",i,params->expoResult[i] );
// gsl_vector_set(tmpStates,i,params->expoResult[i]);
// }
//
// gsl_blas_dgemv(CblasTrans, 1.0, params->invMatGSL,tmpStates, 0.0, params->resVec);
//
//
// for(i=0; i<N; i++){
// params->b[i] = gsl_vector_get(params->resVec,i);
// }
// gsl_matrix_set_zero(params->expAFS2);
// fillExpectedAFS_unnorm(params->stateSpace, params->b,params->rates,params->expAFS2);
//
// //now subtract older AFS (t_t - t_INF) from total AFS (t_0 - t_INF)
// /////////////////
// ///////
// // printf("////////////////////Island time0-t=%f unnormalized\n",timeV);
//
// gsl_matrix_sub(params->expAFS,params->expAFS2);
// // for(i=0;i< (params->expAFS->size1) ;i++){
// // for(j=0;j< (params->expAFS->size2);j++){
// // printf("%.5f ",gsl_matrix_get(params->expAFS,i,j));
// // }
// // printf("\n");
// // }
// // printf("////////////////////\n");
//
//
// //mapping of states already complete when params initialized
// //state vector at time t stored in st[] for largerStateSpace; use reverseMap
// for(i=0;i<N;i++)params->st[i]=0.0;
// for(i=0;i<N;i++)params->st[params->map[i]]+=params->expoResult[i];
// for(i=0; i<params->reducedStateSpace->nstates; i++){
// gsl_vector_set(params->ancStateVec,i,params->st[params->reverseMap[i]]);
// }
// Na = params->reducedStateSpace->nstates;
// //fill up ancestral transition matrix
// gsl_vector_set_zero(params->rates);
// tmpMat2= fillTransitionMatrixArray_embed_ctmc(params->reducedStateSpace, params->topA2, params->moveA2, &(params->nnzA),
// params->dim1A, params->dim2A,thetaA, 0, 0, 0,params->new, params->newdim1, params->newdim2,params->rates);
//
// ident = cs_spalloc(Na,Na,Na,1,1);
// for(i=0;i<Na;i++) cs_entry(ident,i,i,1);
// eye = cs_compress(ident);
// spMat = cs_add(eye,tmpMat2,1.0,-1.0);
// mt = cs_transpose(spMat,1);
//
// // gsl_matrix_free(invMatGSL);
// // invMatGSLA = gsl_matrix_calloc(Na,Na);
//
// for(j=0;j<Na;j++){
// //create unit array for solve
// for(i=0; i<Na; i++)params->b[i] = 0.0;
// params->b[j]=1.0;
// cs_lusol(0, mt, params->b, 1e-12);
// for(i=0; i<Na; i++){
// gsl_matrix_set(params->invMatGSLA,j,i,params->b[i]);
// }
// }
//
// //get contribution starting at st
// gsl_blas_dgemv(CblasTrans, 1.0, params->invMatGSLA, params->ancStateVec, 0.0, params->ancResVec);
// for(i=0; i<Na; i++)params->b[i] = gsl_vector_get(params->ancResVec,i);
// gsl_matrix_set_zero(params->expAFS2);
// fillExpectedAFS_unnorm(params->reducedStateSpace, params->b,params->rates,params->expAFS2);
//
// ////////////////////normalized IM AFS
// gsl_matrix_add(params->expAFS,params->expAFS2);
// sum = matrixSumDouble(params->expAFS);
// gsl_matrix_scale(params->expAFS, 1.0 / sum);
//
//
// ///////////// Replace AFS with log(AFS)
// // for(i=0;i<params->expAFS->size1;i++){
// // for(j=0;j<params->expAFS->size2;j++){
// // gsl_matrix_set(params->expAFS,i,j,log(gsl_matrix_get(params->expAFS,i,j)));
// // }
// // }
//
// //clean up
// cs_spfree(spMat);
// cs_spfree(mt);
// cs_spfree(ident);
// cs_spfree(eye);
// cs_spfree(tmpMat);
// cs_spfree(tmpMat2);
// gsl_vector_free(tmpStates);
// }
//////////////////// Uniformization Algorithm for Exponentiation
/// P. 413 from Stewart Book
void uniformizExpSparseMat(int N, int nnz, double *vals, int *dim1, int *dim2, double tSoln, double *result){
int i, k, ii;
double cosi, sigma, nu, gamma, eps,y[N],tmpY[N],scale;
struct cs_di_sparse *tmpMat, *ctmc, *ident, *eye, *new;
//stuff values into more convenient matrix
//uniformization of matrix
tmpMat = cs_spalloc(N,N,N,1,1);
ident = cs_spalloc(N,N,N,1,1);
for(i=0;i<nnz;i++)cs_entry(tmpMat,dim1[i],dim2[i],vals[i]);
ctmc=cs_compress(tmpMat);
gamma = cs_max(ctmc);
printf("gamma=%f\n------------------\n",gamma);
cs_print_adk(ctmc);
cs_scale(ctmc,1.0/gamma);
cs_print_adk(ctmc);
for(i=0;i<N;i++) cs_entry(ident,i,i,1);
eye = cs_compress(ident);
new = cs_add(eye,ctmc,1.0,1.0);
cs_print_adk(new);
//tmpMat now holds the subjugated dtmc
//step one of uniformization is to compute K, number of terms in the summation
eps=0.001;
k=0; cosi=1.0; sigma=1.0; nu = (1-eps)/exp(-1.0*gamma*tSoln);
while(sigma < nu){
k+=1;
cosi *= (gamma * tSoln)/k;
sigma += cosi;
}
printf("here is k: %d\n",k);
//initialize result;
for(i=1;i<N;i++){
result[i]=0.0;
y[i]=0.0;
tmpY[i]=0.0;
}
result[0]=1.0;y[0]=1.0;tmpY[0]=0.0;
printf("initialization done\n");
for(ii=0;ii<N;ii++) printf("tmpY[%d]=%f\n",ii,tmpY[ii]);
printf("---------------------\n");
for(ii=0;ii<N;ii++)printf("y[%d]=%f\n",ii,y[ii]);
printf("---------------------\n");
//now approximate pi(t)
int testVal;
for(i=1;i<=k;i++){
printf("k loop k=%d\n",i);
testVal=cs_gaxpy(new, y, tmpY); //tmpY now contains the answer
printf("test of gaxpy: %d\n",testVal);
for(ii=0;ii<N;ii++) printf("tmpY[%d]=%f\n",ii,tmpY[ii]);
printf("---------------------\n");
for(ii=0;ii<N;ii++)printf("y[%d]=%f\n",ii,y[ii]);
printf("---------------------\n");
cs_print_adk(tmpMat);
printf("---------------------\n");
for(ii=0;ii<N;ii++){
// printf("tmpY[%d]=%f\n",ii,tmpY[ii]);
// printf("y[%d]=%f\n",ii,y[ii]);
y[ii]=tmpY[ii] * ((gamma*tSoln)/i);
result[ii]+=y[ii];
tmpY[ii]=0;
}
}
//final scaling
scale = exp(-1.0*gamma*tSoln);
for(i=0;i<N;i++){
result[i] *= scale;
printf("result[%d]=%f\n",i,result[i]);
}
}
| {
"alphanum_fraction": 0.6046625367,
"avg_line_length": 30.4165289256,
"ext": "c",
"hexsha": "584cc885ed198151a218c36a39e48f4907416067",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dortegadelv/IMaDNA",
"max_forks_repo_path": "AFS_ctmc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dortegadelv/IMaDNA",
"max_issues_repo_path": "AFS_ctmc.c",
"max_line_length": 139,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dortegadelv/IMaDNA",
"max_stars_repo_path": "AFS_ctmc.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6973,
"size": 18402
} |
/*****************************************************************************
*
* Rokko: Integrated Interface for libraries of eigenvalue decomposition
*
* Copyright (C) 2012-2017 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*****************************************************************************/
#include <math.h>
#include <cblas.h>
#include <lapacke.h>
#include <rokko/cmatrix.h>
int imax(int x, int y) { return (x > y) ? x : y; }
int main(int argc, char** argv) {
int n = 5;
int i, j;
double norm, check;
double **a;
if (argc > 1) n = atoi(argv[1]);
// generate matrix and rhs vector
a = alloc_dmatrix(n, n);
for (j = 0; j < n; ++j) {
for (i = 0; i < n; ++i) {
mat_elem(a, i, j) = n - 0.253 * imax(i, j);
}
}
printf("Matrix A: ");
fprint_dmatrix(stdout, n, n, a);
/* calculate various norms */
norm = LAPACKE_dlange(LAPACK_COL_MAJOR, '1', n, n, mat_ptr(a), n);
printf("norm1(A) = %e\n", norm);
norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'I', n, n, mat_ptr(a), n);
printf("normI(A) = %e\n", norm);
norm = LAPACKE_dlange(LAPACK_COL_MAJOR, 'F', n, n, mat_ptr(a), n);
printf("normF(A) = %e\n", norm);
/* check of result */
check = 0;
for (j = 0; j < n; ++j) {
for (i = 0; i < n; ++i) {
check += mat_elem(a, i, j) * mat_elem(a, i, j);
}
}
if (fabs(check - norm * norm) > 1e-12 * check) {
fprintf(stderr, "Error: check error %e != %e\n", norm * norm, check);
exit(255);
}
free_dmatrix(a);
return 0;
}
| {
"alphanum_fraction": 0.5292697646,
"avg_line_length": 26.7258064516,
"ext": "c",
"hexsha": "edf4e7cf8b5a92614314f90628d089dd813185c8",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-06-01T07:10:01.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-06-16T04:22:23.000Z",
"max_forks_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "t-sakashita/rokko",
"max_forks_repo_path": "example/lapack/dlange.c",
"max_issues_count": 514,
"max_issues_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9",
"max_issues_repo_issues_event_max_datetime": "2021-06-25T09:29:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-05T14:56:54.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "t-sakashita/rokko",
"max_issues_repo_path": "example/lapack/dlange.c",
"max_line_length": 78,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "ebd49e1198c4ec9e7612ad4a9806d16a4ff0bdc9",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "t-sakashita/rokko",
"max_stars_repo_path": "example/lapack/dlange.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T19:04:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-31T18:57:48.000Z",
"num_tokens": 543,
"size": 1657
} |
/******************************************************************************* *
*
* This file is part of the General Hidden Markov Model Library,
* GHMM version __VERSION__, see http://ghmm.org
*
* Filename: ghmm/ghmm/root_finder.c
* Authors: Achim Gaedke
*
* Copyright (C) 1998-2004 Alexander Schliep
* Copyright (C) 1998-2001 ZAIK/ZPR, Universitaet zu Koeln
* Copyright (C) 2002-2004 Max-Planck-Institut fuer Molekulare Genetik,
* Berlin
*
* Contact: schliep@ghmm.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* This file is version $Revision: 2267 $
* from $Date: 2009-04-24 11:01:58 -0400 (Fri, 24 Apr 2009) $
* last change by $Author: grunau $.
*
*******************************************************************************/
#ifdef HAVE_CONFIG_H
# include "../config.h"
#endif /* */
#ifndef DO_WITH_GSL
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "ghmm_internals.h"
double ghmm_zbrent_AB (double (*func) (double, double, double, double),
double x1, double x2, double tol, double A, double B,
double eps)
{
fprintf (stderr, "Function ghmm_zbrent_AB() not implemented!\n");
exit (1);
/*
double a, b, c;
double fa, fb, fc;
a = min(x1, x2);
fa = (*func)(a);
c = max(x1, x2);
fc = (*func)(c);
b = (c - a)/2.0;
fb = (*func)(b);
while (fabs(c - a) > tol + (tol * min(fabs(a), fabs(c))))
{
r = fb/fc;
s = fb/fa;
t = fa/fc;
p = s * (t * (r - t) * (c - b) - (1.0 - r) * (b - a));
q = (t - 1.0) * (r - 1.0) * (s - 1.0);
x = b + p/q;
if (x > a && x < c)
{
/ * Accept interpolating point * /
if (x < b)
{
c = b;
fc = fb;
b = x;
fb = (*func)(b);
}
else if (x > b)
{
a = b;
fa = fb;
b = x;
fb = (*func)(b);
}
}
else
{
/ * Use bisection * /
}
}
*/
}
#else /* */
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
/* struct for function pointer and parameters except 1st one */
struct parameter_wrapper {
double (*func) (double, double, double, double);
double x2;
double x3;
double x4;
} parameter;
/* calls the given function during gsl root solving iteration
the first parameter variates, all other are kept constant
*/
double function_wrapper (double x, void *p)
{
struct parameter_wrapper *param = (struct parameter_wrapper *) p;
return param->func (x, param->x2, param->x3, param->x4);
}
/*
this interface is used in sreestimate.c
*/
double ghmm_zbrent_AB (double (*func) (double, double, double, double), double x1,
double x2, double tol, double A, double B, double eps)
{
/* initialisation of wrapper structure */
struct parameter_wrapper param;
gsl_function f;
#ifdef HAVE_GSL_INTERVAL /* gsl_interval vanished with version 0.9 */
gsl_interval x;
#endif /* */
gsl_root_fsolver * s;
double tolerance;
int success = 0;
double result = 0;
param.func = func;
param.x2 = A;
param.x3 = B;
param.x4 = eps;
f.function = &function_wrapper;
f.params = (void *) ¶m;
tolerance = tol;
/* initialisation */
#ifdef HAVE_GSL_INTERVAL
# ifdef GSL_ROOT_FSLOVER_ALLOC_WITH_ONE_ARG
x.lower = x1;
x.upper = x2;
s = gsl_root_fsolver_alloc (gsl_root_fsolver_brent);
gsl_root_fsolver_set (s, &f, x);
# else
s = gsl_root_fsolver_alloc (gsl_root_fsolver_brent, &f, x);
# endif
#else /* gsl_interval vanished with version 0.9 */
s = gsl_root_fsolver_alloc (gsl_root_fsolver_brent);
gsl_root_fsolver_set (s, &f, x1, x2);
#endif /* */
/* iteration */
do {
success = gsl_root_fsolver_iterate (s);
if (success == GSL_SUCCESS)
{
#ifdef HAVE_GSL_INTERVAL
gsl_interval new_x;
new_x = gsl_root_fsolver_interval (s);
success = gsl_root_test_interval (new_x, tolerance, tolerance);
#else /* gsl_interval vanished with version 0.9 */
double x_up;
double x_low;
(void) gsl_root_fsolver_iterate (s);
x_up = gsl_root_fsolver_x_upper (s);
x_low = gsl_root_fsolver_x_lower (s);
success = gsl_root_test_interval (x_low, x_up, tolerance, tolerance);
#endif /* */
}
} while (success == GSL_CONTINUE);
/* result */
if (success != GSL_SUCCESS)
{
gsl_error ("solver failed", __FILE__, __LINE__, success);
}
else
{
result = gsl_root_fsolver_root (s);
}
/* destruction */
gsl_root_fsolver_free (s);
return result;
}
#endif /* */
| {
"alphanum_fraction": 0.5664335664,
"avg_line_length": 26.3066037736,
"ext": "c",
"hexsha": "1f1a39c6a8a15ba660e688cd78818ceab46fb116",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z",
"max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ruslankuzmin/julia",
"max_forks_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/root_finder.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "ruslankuzmin/julia",
"max_issues_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/root_finder.c",
"max_line_length": 83,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/root_finder.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z",
"num_tokens": 1548,
"size": 5577
} |
// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/tensor.h"
#ifdef PADDLE_WITH_MKLML
#include <mkl_cblas.h>
#include <mkl_lapacke.h>
#include <mkl_vml_functions.h>
#endif
#ifdef PADDLE_USE_OPENBLAS
#include <cblas.h>
#include <lapacke.h>
#endif
#ifndef LAPACK_FOUND
extern "C" {
#include <cblas.h> // NOLINT
int LAPACKE_sgetrf(int matrix_layout, int m, int n, float* a, int lda,
int* ipiv);
int LAPACKE_dgetrf(int matrix_layout, int m, int n, double* a, int lda,
int* ipiv);
int LAPACKE_sgetri(int matrix_layout, int n, float* a, int lda,
const int* ipiv);
int LAPACKE_dgetri(int matrix_layout, int n, double* a, int lda,
const int* ipiv);
}
#endif
namespace paddle {
namespace operators {
namespace math {
template <typename DeviceContext>
class Blas {
public:
explicit Blas(const DeviceContext& context) : context_(context) {}
template <typename T>
void GEMM(CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB, int M, int N, int K,
T alpha, const T* A, const T* B, T beta, T* C) const;
template <typename T>
void GEMM(bool transA, bool transB, int M, int N, int K, T alpha, const T* A,
int lda, const T* B, int ldb, T beta, T* C, int ldc) const;
template <typename T>
void MatMul(const framework::Tensor& mat_a, bool trans_a,
const framework::Tensor& mat_b, bool trans_b, T alpha,
framework::Tensor* mat_out, T beta) const;
template <typename T>
void MatMul(const framework::Tensor& mat_a, bool trans_a,
const framework::Tensor& mat_b, bool trans_b,
framework::Tensor* mat_out) const {
MatMul(mat_a, trans_a, mat_b, trans_b, static_cast<T>(1.0), mat_out,
static_cast<T>(0.0));
}
template <typename T>
void MatMul(const framework::Tensor& mat_a, const framework::Tensor& mat_b,
framework::Tensor* mat_out) const {
this->template MatMul<T>(mat_a, false, mat_b, false, mat_out);
}
template <typename T>
void AXPY(int n, T alpha, const T* x, T* y) const;
template <typename T>
void GEMV(bool trans_a, int M, int N, T alpha, const T* A, const T* B, T beta,
T* C) const;
template <typename T>
void BatchedGEMM(CBLAS_TRANSPOSE transA, CBLAS_TRANSPOSE transB, int M, int N,
int K, T alpha, const T* A, const T* B, T beta, T* C,
int batchCount, int64_t strideA, int64_t strideB) const;
private:
const DeviceContext& context_;
};
template <typename DeviceContext, typename T>
class BlasT : private Blas<DeviceContext> {
public:
using Blas<DeviceContext>::Blas;
template <typename... ARGS>
void GEMM(ARGS... args) const {
Base()->template GEMM<T>(args...);
}
template <typename... ARGS>
void MatMul(ARGS... args) const {
Base()->template MatMul<T>(args...);
}
template <typename... ARGS>
void AXPY(ARGS... args) const {
Base()->template AXPY<T>(args...);
}
template <typename... ARGS>
void GEMV(ARGS... args) const {
Base()->template GEMV<T>(args...);
}
template <typename... ARGS>
void BatchedGEMM(ARGS... args) const {
Base()->template BatchedGEMM<T>(args...);
}
private:
const Blas<DeviceContext>* Base() const {
return static_cast<const Blas<DeviceContext>*>(this);
}
};
template <typename DeviceContext, typename T>
inline BlasT<DeviceContext, T> GetBlas(
const framework::ExecutionContext& exe_ctx) {
return BlasT<DeviceContext, T>(
exe_ctx.template device_context<DeviceContext>());
}
template <typename DeviceContext, typename T>
inline BlasT<DeviceContext, T> GetBlas(const DeviceContext& dev_ctx) {
return BlasT<DeviceContext, T>(dev_ctx);
}
} // namespace math
} // namespace operators
} // namespace paddle
#include "paddle/fluid/operators/math/blas_impl.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/operators/math/blas_impl.cu.h"
#endif
| {
"alphanum_fraction": 0.6764577894,
"avg_line_length": 30.0392156863,
"ext": "h",
"hexsha": "5cd2f855d1135e6dd8343efdaa9855d2526a3520",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0fed3db3eb7111599fbb0acb9a2831f8a91ea55c",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "abhinavarora/Paddle",
"max_forks_repo_path": "paddle/fluid/operators/math/blas.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0fed3db3eb7111599fbb0acb9a2831f8a91ea55c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "abhinavarora/Paddle",
"max_issues_repo_path": "paddle/fluid/operators/math/blas.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0fed3db3eb7111599fbb0acb9a2831f8a91ea55c",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "abhinavarora/Paddle",
"max_stars_repo_path": "paddle/fluid/operators/math/blas.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1262,
"size": 4596
} |
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
int
main (void)
{
double data[] = { -1.0, 1.0, -1.0, 1.0,
-8.0, 4.0, -2.0, 1.0,
27.0, 9.0, 3.0, 1.0,
64.0, 16.0, 4.0, 1.0 };
gsl_matrix_view m
= gsl_matrix_view_array (data, 4, 4);
gsl_vector_complex *eval = gsl_vector_complex_alloc (4);
gsl_matrix_complex *evec = gsl_matrix_complex_alloc (4, 4);
gsl_eigen_nonsymmv_workspace * w =
gsl_eigen_nonsymmv_alloc (4);
gsl_eigen_nonsymmv (&m.matrix, eval, evec, w);
gsl_eigen_nonsymmv_free (w);
gsl_eigen_nonsymmv_sort (eval, evec,
GSL_EIGEN_SORT_ABS_DESC);
{
int i, j;
for (i = 0; i < 4; i++)
{
gsl_complex eval_i
= gsl_vector_complex_get (eval, i);
gsl_vector_complex_view evec_i
= gsl_matrix_complex_column (evec, i);
printf ("eigenvalue = %g + %gi\n",
GSL_REAL(eval_i), GSL_IMAG(eval_i));
printf ("eigenvector = \n");
for (j = 0; j < 4; ++j)
{
gsl_complex z =
gsl_vector_complex_get(&evec_i.vector, j);
printf("%g + %gi\n", GSL_REAL(z), GSL_IMAG(z));
}
}
}
gsl_vector_complex_free(eval);
gsl_matrix_complex_free(evec);
return 0;
}
| {
"alphanum_fraction": 0.5466666667,
"avg_line_length": 24.1071428571,
"ext": "c",
"hexsha": "eb1a4e59d61d780812a593b5c7fc0d501a9560d3",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/eigen_nonsymm.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/eigen_nonsymm.c",
"max_line_length": 61,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/doc/examples/eigen_nonsymm.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z",
"num_tokens": 438,
"size": 1350
} |
#if !defined(PETIGABL_H)
#define PETIGABL_H
#include <petsc.h>
#include <petscblaslapack.h>
#if defined(PETSC_BLASLAPACK_UNDERSCORE)
#define sgetri_ sgetri_
#define dgetri_ dgetri_
#define qgetri_ qgetri_
#define cgetri_ cgetri_
#define zgetri_ zgetri_
#elif defined(PETSC_BLASLAPACK_CAPS)
#define sgetri_ SGETRI
#define dgetri_ DGETRI
#define qgetri_ QGETRI
#define cgetri_ CGETRI
#define zgetri_ ZGETRI
#else /* (PETSC_BLASLAPACK_C) */
#define sgetri_ sgetri
#define dgetri_ dgetri
#define qgetri_ qgetri
#define cgetri_ cgetri
#define zgetri_ zgetri
#endif
#if !defined(PETSC_USE_COMPLEX)
#if defined(PETSC_USE_REAL_SINGLE)
#define LAPACKgetri_ sgetri_
#elif defined(PETSC_USE_REAL_DOUBLE)
#define LAPACKgetri_ dgetri_
#else /* (PETSC_USE_REAL_QUAD) */
#define LAPACKgetri_ qgetri_
#endif
#else
#if defined(PETSC_USE_REAL_SINGLE)
#define LAPACKgetri_ cgetri_
#elif defined(PETSC_USE_REAL_DOUBLE)
#define LAPACKgetri_ zgetri_
#else /* (PETSC_USE_REAL_QUAD) */
#define LAPACKgetri_ wgetri_
#endif
#endif
EXTERN_C_BEGIN
extern void LAPACKgetri_(PetscBLASInt*,PetscScalar*,PetscBLASInt*,
PetscBLASInt*,PetscScalar*,PetscBLASInt*,
PetscBLASInt*);
EXTERN_C_END
#if PETSC_VERSION_LE(3,3,0)
#undef PetscBLASIntCast
#undef __FUNCT__
#define __FUNCT__ "PetscBLASIntCast"
PETSC_STATIC_INLINE PetscErrorCode PetscBLASIntCast(PetscInt a,PetscBLASInt *b)
{
PetscFunctionBegin;
#if defined(PETSC_USE_64BIT_INDICES) && !defined(PETSC_HAVE_64BIT_BLAS_INDICES)
if ((a) > PETSC_BLAS_INT_MAX) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Array too long for BLAS/LAPACK");
#endif
*b = (PetscBLASInt)(a);
PetscFunctionReturn(0);
}
#endif
#endif/*PETIGABL_H*/
| {
"alphanum_fraction": 0.7506971556,
"avg_line_length": 28.015625,
"ext": "h",
"hexsha": "31a31d4073537c615250e4bf1d6ba0f3e139411e",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2021-06-14T10:40:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-11-08T12:55:17.000Z",
"max_forks_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "otherlab/petiga",
"max_forks_repo_path": "src/petigabl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "otherlab/petiga",
"max_issues_repo_path": "src/petigabl.h",
"max_line_length": 115,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "ce8c07de8511000ee6f1cbfd3fb90fda9cb31954",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "otherlab/petiga",
"max_stars_repo_path": "src/petigabl.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T10:40:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-31T21:20:27.000Z",
"num_tokens": 622,
"size": 1793
} |
/* linalg/test_qr.c
*
* Copyright (C) 2019-2020 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_permutation.h>
static int
test_QR_decomp_dim(const gsl_matrix * m, double eps)
{
int s = 0;
const size_t M = m->size1;
const size_t N = m->size2;
size_t i, j;
gsl_matrix * qr = gsl_matrix_alloc(M, N);
gsl_matrix * a = gsl_matrix_alloc(M, N);
gsl_matrix * q = gsl_matrix_alloc(M, M);
gsl_matrix * r = gsl_matrix_alloc(M, N);
gsl_vector * d = gsl_vector_alloc(N);
gsl_matrix_memcpy(qr, m);
s += gsl_linalg_QR_decomp(qr, d);
s += gsl_linalg_QR_unpack(qr, d, q, r);
/* compute a = q r */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, q, r, 0.0, a);
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, i, j);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_vector_free(d);
gsl_matrix_free(qr);
gsl_matrix_free(a);
gsl_matrix_free(q);
gsl_matrix_free(r);
return s;
}
static int
test_QR_decomp(void)
{
int f;
int s = 0;
f = test_QR_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp m(3,5)");
s += f;
f = test_QR_decomp_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp m(5,3)");
s += f;
f = test_QR_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp hilbert(2)");
s += f;
f = test_QR_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp hilbert(3)");
s += f;
f = test_QR_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp hilbert(4)");
s += f;
f = test_QR_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp hilbert(12)");
s += f;
f = test_QR_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp vander(2)");
s += f;
f = test_QR_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp vander(3)");
s += f;
f = test_QR_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp vander(4)");
s += f;
f = test_QR_decomp_dim(vander12, 0.0005); /* FIXME: bad accuracy */
gsl_test(f, " QR_decomp vander(12)");
s += f;
return s;
}
static int
test_QR_decomp_r_eps(const gsl_matrix * m, const double eps, const char * desc)
{
int s = 0;
const size_t M = m->size1;
const size_t N = m->size2;
size_t i, j;
gsl_matrix * QR = gsl_matrix_alloc(M, N);
gsl_matrix * T = gsl_matrix_alloc(N, N);
gsl_matrix * A = gsl_matrix_alloc(M, N);
gsl_matrix * R = gsl_matrix_alloc(N, N);
gsl_matrix * Q = gsl_matrix_alloc(M, M);
gsl_matrix_view Q1 = gsl_matrix_submatrix(Q, 0, 0, M, N);
gsl_matrix_memcpy(QR, m);
s += gsl_linalg_QR_decomp_r(QR, T);
s += gsl_linalg_QR_unpack_r(QR, T, Q, R);
/* compute A = Q R */
gsl_matrix_memcpy(A, &Q1.matrix);
gsl_blas_dtrmm (CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, R, A);
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
double aij = gsl_matrix_get(A, i, j);
double mij = gsl_matrix_get(m, i, j);
gsl_test_rel(aij, mij, eps, "%s (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, M, N, i,j, aij, mij);
}
}
if (M > N)
{
gsl_matrix * R_alt = gsl_matrix_alloc(M, N);
gsl_matrix * Q_alt = gsl_matrix_alloc(M, M);
gsl_vector_view tau = gsl_matrix_diagonal(T);
/* test that Q2 was computed correctly by comparing with Level 2 algorithm */
gsl_linalg_QR_unpack(QR, &tau.vector, Q_alt, R_alt);
for (i = 0; i < M; i++)
{
for (j = 0; j < M; j++)
{
double aij = gsl_matrix_get(Q, i, j);
double bij = gsl_matrix_get(Q_alt, i, j);
gsl_test_rel(aij, bij, eps, "%s Q (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, M, N, i, j, aij, bij);
}
}
gsl_matrix_free(R_alt);
gsl_matrix_free(Q_alt);
}
gsl_matrix_free(QR);
gsl_matrix_free(T);
gsl_matrix_free(A);
gsl_matrix_free(Q);
gsl_matrix_free(R);
return s;
}
static int
test_QR_decomp_r(gsl_rng * r)
{
int s = 0;
size_t M, N;
for (M = 1; M <= 50; ++M)
{
for (N = 1; N <= M; ++N)
{
gsl_matrix * A = gsl_matrix_alloc(M, N);
create_random_matrix(A, r);
s += test_QR_decomp_r_eps(A, 1.0e6 * M * GSL_DBL_EPSILON, "QR_decomp_r random");
gsl_matrix_free(A);
}
}
s += test_QR_decomp_r_eps(m53, 1.0e2 * GSL_DBL_EPSILON, "QR_decomp_r m(5,3)");
s += test_QR_decomp_r_eps(hilb2, 1.0e2 * GSL_DBL_EPSILON, "QR_decomp_r hilbert(2)");
s += test_QR_decomp_r_eps(hilb3, 1.0e2 * GSL_DBL_EPSILON, "QR_decomp_r hilbert(3)");
s += test_QR_decomp_r_eps(hilb4, 1.0e2 * GSL_DBL_EPSILON, "QR_decomp_r hilbert(4)");
s += test_QR_decomp_r_eps(hilb12, 1.0e2 * GSL_DBL_EPSILON, "QR_decomp_r hilbert(12)");
s += test_QR_decomp_r_eps(vander2, 1.0e1 * GSL_DBL_EPSILON, "QR_decomp_r vander(2)");
s += test_QR_decomp_r_eps(vander3, 1.0e1 * GSL_DBL_EPSILON, "QR_decomp_r vander(3)");
s += test_QR_decomp_r_eps(vander4, 1.0e1 * GSL_DBL_EPSILON, "QR_decomp_r vander(4)");
return s;
}
static int
test_QR_QTmat_r_eps(const gsl_matrix * A, const gsl_matrix * B, const double eps, const char * desc)
{
int s = 0;
const size_t M = A->size1;
const size_t N = A->size2;
const size_t K = B->size2;
size_t i, j;
gsl_matrix * QR = gsl_matrix_alloc(M, N);
gsl_matrix * T = gsl_matrix_alloc(N, N);
gsl_matrix * work = gsl_matrix_alloc(N, K);
gsl_matrix * B1 = gsl_matrix_alloc(M, K);
gsl_matrix * B2 = gsl_matrix_alloc(M, K);
gsl_vector_view tau = gsl_matrix_diagonal(T);
gsl_matrix_memcpy(QR, A);
gsl_matrix_memcpy(B1, B);
gsl_matrix_memcpy(B2, B);
s += gsl_linalg_QR_decomp_r(QR, T);
/* compute Q^T B with both recursive and non-recursive methods and compare */
s += gsl_linalg_QR_QTmat_r(QR, T, B1, work);
s += gsl_linalg_QR_QTmat(QR, &tau.vector, B2);
for (i = 0; i < M; i++)
{
for (j = 0; j < K; j++)
{
double aij = gsl_matrix_get(B1, i, j);
double bij = gsl_matrix_get(B2, i, j);
gsl_test_rel(aij, bij, eps, "%s (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, M, K, i,j, aij, bij);
}
}
gsl_matrix_free(QR);
gsl_matrix_free(T);
gsl_matrix_free(B1);
gsl_matrix_free(B2);
gsl_matrix_free(work);
return s;
}
static int
test_QR_QTmat_r(gsl_rng * r)
{
int s = 0;
size_t M, N;
for (M = 1; M <= 50; ++M)
{
for (N = 1; N <= M; ++N)
{
const size_t K = GSL_MAX(N / 2, 1);
gsl_matrix * A = gsl_matrix_alloc(M, N);
gsl_matrix * B = gsl_matrix_alloc(M, K);
create_random_matrix(A, r);
create_random_matrix(B, r);
s += test_QR_QTmat_r_eps(A, B, 1.0e6 * M * GSL_DBL_EPSILON, "QR_QTmat_r random");
gsl_matrix_free(A);
gsl_matrix_free(B);
}
}
return s;
}
static int
test_QR_solve_r_eps(const gsl_matrix * A, const gsl_vector * rhs, const gsl_vector * sol,
const double eps, const char * desc)
{
int s = 0;
const size_t M = A->size1;
const size_t N = A->size2;
size_t i;
gsl_matrix * QR = gsl_matrix_alloc(M, N);
gsl_matrix * T = gsl_matrix_alloc(N, N);
gsl_vector * x = gsl_vector_alloc(N);
gsl_matrix_memcpy(QR, A);
s += gsl_linalg_QR_decomp_r(QR, T);
s += gsl_linalg_QR_solve_r(QR, T, rhs, x);
for (i = 0; i < M; i++)
{
double xi = gsl_vector_get(x, i);
double yi = gsl_vector_get(sol, i);
gsl_test_rel(xi, yi, eps, "%s (%3lu)[%lu]: %22.18g %22.18g\n",
desc, N, i, xi, yi);
}
gsl_matrix_free(QR);
gsl_matrix_free(T);
gsl_vector_free(x);
return s;
}
static int
test_QR_solve_r(gsl_rng * r)
{
int s = 0;
size_t N;
for (N = 1; N <= 50; ++N)
{
gsl_matrix * A = gsl_matrix_alloc(N, N);
gsl_vector * sol = gsl_vector_alloc(N);
gsl_vector * rhs = gsl_vector_alloc(N);
create_random_matrix(A, r);
create_random_vector(sol, r);
gsl_blas_dgemv(CblasNoTrans, 1.0, A, sol, 0.0, rhs);
s += test_QR_solve_r_eps(A, rhs, sol, 1.0e5 * N * GSL_DBL_EPSILON, "QR_solve_r random");
gsl_matrix_free(A);
gsl_vector_free(sol);
gsl_vector_free(rhs);
}
return s;
}
static int
test_QR_lssolve_r_eps(const gsl_matrix * A, const gsl_vector * b, const double eps, const char * desc)
{
int s = 0;
const size_t M = A->size1;
const size_t N = A->size2;
size_t i;
gsl_matrix * QR = gsl_matrix_alloc(M, N);
gsl_matrix * T = gsl_matrix_alloc(N, N);
gsl_vector * x = gsl_vector_alloc(M);
gsl_vector * work = gsl_vector_alloc(N);
gsl_matrix * U = gsl_matrix_alloc(M, N);
gsl_matrix * V = gsl_matrix_alloc(N, N);
gsl_vector * S = gsl_vector_alloc(N);
gsl_vector * x_svd = gsl_vector_alloc(N);
gsl_vector * residual = gsl_vector_alloc(M);
gsl_matrix_memcpy(QR, A);
s += gsl_linalg_QR_decomp_r(QR, T);
s += gsl_linalg_QR_lssolve_r(QR, T, b, x, work);
gsl_matrix_memcpy(U, A);
gsl_linalg_SV_decomp(U, V, S, work);
gsl_linalg_SV_solve(U, V, S, b, x_svd);
/* compare QR with SVD solution */
for (i = 0; i < N; i++)
{
double xi = gsl_vector_get(x, i);
double yi = gsl_vector_get(x_svd, i);
gsl_test_rel(xi, yi, eps, "%s (%3lu,%3lu)[%lu]: %22.18g %22.18g\n",
desc, M, N, i, xi, yi);
}
if (M > N)
{
gsl_vector_view x1 = gsl_vector_subvector(x, 0, N);
gsl_vector_view x2 = gsl_vector_subvector(x, N, M - N);
double norm = gsl_blas_dnrm2(&x2.vector);
double norm_expected;
/* compute residual and check || x(N+1:end) || = || b - A x || */
gsl_vector_memcpy(residual, b);
gsl_blas_dgemv(CblasNoTrans, -1.0, A, &x1.vector, 1.0, residual);
norm_expected = gsl_blas_dnrm2(residual);
gsl_test_rel(norm, norm_expected, eps, "%s rnorm (%3lu,%3lu): %22.18g %22.18g\n",
desc, M, N, norm, norm_expected);
}
gsl_matrix_free(QR);
gsl_matrix_free(T);
gsl_vector_free(x);
gsl_matrix_free(U);
gsl_matrix_free(V);
gsl_vector_free(x_svd);
gsl_vector_free(work);
gsl_vector_free(S);
gsl_vector_free(residual);
return s;
}
static int
test_QR_lssolve_r(gsl_rng * r)
{
int s = 0;
size_t M, N;
for (M = 1; M <= 30; ++M)
{
for (N = 1; N <= M; ++N)
{
gsl_matrix * A = gsl_matrix_alloc(M, N);
gsl_vector * b = gsl_vector_alloc(M);
create_random_matrix(A, r);
create_random_vector(b, r);
s += test_QR_lssolve_r_eps(A, b, 1.0e5 * M * GSL_DBL_EPSILON, "QR_lssolve_r random");
gsl_matrix_free(A);
gsl_vector_free(b);
}
}
return s;
}
static int
test_QR_UR_decomp_eps(const gsl_matrix * S, const gsl_matrix * A, const double eps, const char * desc)
{
int s = 0;
const size_t M = A->size1;
const size_t N = A->size2;
size_t i, j;
gsl_matrix * R = gsl_matrix_calloc(N, N);
gsl_matrix * V = gsl_matrix_alloc(M, N);
gsl_matrix * T = gsl_matrix_alloc(N, N);
gsl_matrix * B1 = gsl_matrix_calloc(N, N);
gsl_matrix * B2 = gsl_matrix_alloc(M, N);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, R, S);
gsl_matrix_memcpy(V, A);
s += gsl_linalg_QR_UR_decomp(R, V, T);
/*
* compute B = Q R = [ R - T R ]
* [ -V~ T R ]
*/
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, B1, T);
gsl_matrix_memcpy(B2, V);
gsl_blas_dtrmm (CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, R, B1); /* B1 = T R */
gsl_blas_dtrmm (CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, B1, B2); /* B2 = -V~ T R */
gsl_matrix_sub (B1, R); /* B1 = T R - R */
gsl_matrix_scale (B1, -1.0); /* B1 = R - T R */
/* test S = B1 */
for (i = 0; i < N; i++)
{
for (j = i; j < N; j++)
{
double aij = gsl_matrix_get(B1, i, j);
double mij = gsl_matrix_get(S, i, j);
gsl_test_rel(aij, mij, eps, "%s B1 (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, M, N, i,j, aij, mij);
}
}
/* test A = B2 */
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
double aij = gsl_matrix_get(B2, i, j);
double mij = gsl_matrix_get(A, i, j);
gsl_test_rel(aij, mij, eps, "%s B2 (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, M, N, i,j, aij, mij);
}
}
gsl_matrix_free(R);
gsl_matrix_free(V);
gsl_matrix_free(T);
gsl_matrix_free(B1);
gsl_matrix_free(B2);
return s;
}
static int
test_QR_UR_decomp(gsl_rng * r)
{
int s = 0;
size_t M, N;
for (M = 1; M <= 50; ++M)
{
for (N = 1; N <= M; ++N)
{
gsl_matrix * S = gsl_matrix_alloc(N, N);
gsl_matrix * A = gsl_matrix_alloc(M, N);
create_random_matrix(A, r);
create_random_matrix(S, r);
s += test_QR_UR_decomp_eps(S, A, 1.0e6 * M * GSL_DBL_EPSILON, "QR_UR_decomp random");
gsl_matrix_free(S);
gsl_matrix_free(A);
}
}
return s;
}
static int
test_QR_UZ_decomp_eps(const gsl_matrix * S, const gsl_matrix * A, const double eps, const char * desc)
{
int s = 0;
const size_t M = A->size1;
const size_t N = A->size2;
size_t i, j;
gsl_matrix * R = gsl_matrix_calloc(N, N);
gsl_matrix * V = gsl_matrix_alloc(M, N);
gsl_matrix * T = gsl_matrix_alloc(N, N);
gsl_matrix * B1 = gsl_matrix_calloc(N, N);
gsl_matrix * B2 = gsl_matrix_alloc(M, N);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, R, S);
gsl_matrix_memcpy(V, A);
s += gsl_linalg_QR_UZ_decomp(R, V, T);
/*
* compute B = Q R = [ R - T R ]
* [ -V~ T R ]
*/
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, B1, T);
gsl_blas_dtrmm (CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, R, B1); /* B1 = T R */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, -1.0, V, B1, 0.0, B2); /* B2 = -V~ T R */
gsl_matrix_sub (B1, R); /* B1 = T R - R */
gsl_matrix_scale (B1, -1.0); /* B1 = R - T R */
/* test S = B1 */
for (i = 0; i < N; i++)
{
for (j = i; j < N; j++)
{
double aij = gsl_matrix_get(B1, i, j);
double mij = gsl_matrix_get(S, i, j);
gsl_test_rel(aij, mij, eps, "%s B1 (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, M, N, i,j, aij, mij);
}
}
/* test A = B2 */
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
double aij = gsl_matrix_get(B2, i, j);
double mij = gsl_matrix_get(A, i, j);
gsl_test_rel(aij, mij, eps, "%s B2 (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, M, N, i,j, aij, mij);
}
}
gsl_matrix_free(R);
gsl_matrix_free(V);
gsl_matrix_free(T);
gsl_matrix_free(B1);
gsl_matrix_free(B2);
return s;
}
static int
test_QR_UZ_decomp(gsl_rng * r)
{
int s = 0;
const size_t N_max = 20;
const size_t M_max = 2*N_max;
gsl_matrix * U1 = gsl_matrix_alloc(N_max, N_max);
gsl_matrix * U2 = gsl_matrix_alloc(N_max, N_max);
gsl_matrix * A = gsl_matrix_alloc(M_max, N_max);
size_t M, N;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix_view S = gsl_matrix_submatrix(U1, 0, 0, N, N);
gsl_matrix_view T = gsl_matrix_submatrix(U2, 0, 0, N, N);
for (M = N; M <= 2*N_max; ++M)
{
gsl_matrix_view B = gsl_matrix_submatrix(A, 0, 0, M, N);
gsl_matrix_view Bu = gsl_matrix_submatrix(&B.matrix, M - N, 0, N, N);
gsl_matrix_set_zero(&B.matrix);
if (M > N)
{
gsl_matrix_view Bd = gsl_matrix_submatrix(&B.matrix, 0, 0, M - N, N);
create_random_matrix(&Bd.matrix, r);
}
create_random_matrix(&S.matrix, r);
create_random_matrix(&T.matrix, r);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &Bu.matrix, &T.matrix);
s += test_QR_UZ_decomp_eps(&S.matrix, &B.matrix, 1.0e6 * M * GSL_DBL_EPSILON,
"QR_UZ_decomp random");
}
}
gsl_matrix_free(U1);
gsl_matrix_free(U2);
gsl_matrix_free(A);
return s;
}
static int
test_QR_UU_decomp_eps(const gsl_matrix * U, const gsl_matrix * S, const double eps, const char * desc)
{
int s = 0;
const size_t N = U->size2;
size_t i, j;
gsl_matrix * R = gsl_matrix_calloc(N, N);
gsl_matrix * V = gsl_matrix_calloc(N, N);
gsl_matrix * T = gsl_matrix_alloc(N, N);
gsl_matrix * B1 = gsl_matrix_calloc(N, N);
gsl_matrix * B2 = gsl_matrix_calloc(N, N);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, R, U);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, V, S);
s += gsl_linalg_QR_UU_decomp(R, V, T);
/*
* compute B = Q R = [ R - T R ]
* [ -V~ T R ]
*/
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, B1, T);
gsl_blas_dtrmm (CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, R, B1); /* B1 = T R */
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, B2, B1); /* B2 := T R */
gsl_blas_dtrmm (CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, V, B2); /* B2 = -V~ T R */
gsl_matrix_sub (B1, R); /* B1 = T R - R */
gsl_matrix_scale (B1, -1.0); /* B1 = R - T R */
/* test U = B1 */
for (i = 0; i < N; i++)
{
for (j = i; j < N; j++)
{
double aij = gsl_matrix_get(B1, i, j);
double mij = gsl_matrix_get(U, i, j);
gsl_test_rel(aij, mij, eps, "%s B1 (%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, i, j, aij, mij);
}
}
/* test S = B2 */
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
double aij = gsl_matrix_get(B2, i, j);
double mij = gsl_matrix_get(S, i, j);
gsl_test_rel(aij, mij, eps, "%s B2 (%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, i,j, aij, mij);
}
}
gsl_matrix_free(R);
gsl_matrix_free(V);
gsl_matrix_free(T);
gsl_matrix_free(B1);
gsl_matrix_free(B2);
return s;
}
static int
test_QR_UU_decomp(gsl_rng * r)
{
int s = 0;
const size_t N_max = 50;
gsl_matrix * U = gsl_matrix_alloc(N_max, N_max);
gsl_matrix * S = gsl_matrix_alloc(N_max, N_max);
gsl_matrix * T = gsl_matrix_alloc(N_max, N_max);
size_t N;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix_view a = gsl_matrix_submatrix(U, 0, 0, N, N);
gsl_matrix_view b = gsl_matrix_submatrix(S, 0, 0, N, N);
gsl_matrix_view c = gsl_matrix_submatrix(T, 0, 0, N, N);
create_random_matrix(&c.matrix, r);
gsl_matrix_set_zero(&a.matrix);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &a.matrix, &c.matrix);
create_random_matrix(&c.matrix, r);
gsl_matrix_set_zero(&b.matrix);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &b.matrix, &c.matrix);
s += test_QR_UU_decomp_eps(&a.matrix, &b.matrix, 1.0e6 * N * GSL_DBL_EPSILON,
"QR_UU_decomp random");
}
gsl_matrix_free(U);
gsl_matrix_free(S);
gsl_matrix_free(T);
return s;
}
static int
test_QR_UU_lssolve_eps(const gsl_matrix * U, const gsl_matrix * S, const gsl_vector * b,
const double eps, const char * desc)
{
int s = 0;
const size_t N = U->size1;
const size_t M = 2 * N;
size_t i;
gsl_matrix * R = gsl_matrix_calloc(N, N);
gsl_matrix * Y = gsl_matrix_calloc(N, N);
gsl_matrix * T = gsl_matrix_alloc(N, N);
gsl_vector * x = gsl_vector_alloc(M);
gsl_vector * work = gsl_vector_alloc(N);
gsl_matrix * A = gsl_matrix_calloc(M, N);
gsl_matrix * U_svd = gsl_matrix_alloc(M, N);
gsl_matrix * V_svd = gsl_matrix_alloc(N, N);
gsl_vector * S_svd = gsl_vector_alloc(N);
gsl_vector * x_svd = gsl_vector_alloc(N);
gsl_vector * residual = gsl_vector_alloc(M);
gsl_matrix_view tmp;
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, R, U);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, Y, S);
s += gsl_linalg_QR_UU_decomp(R, Y, T);
s += gsl_linalg_QR_UU_lssolve(R, Y, T, b, x, work);
tmp = gsl_matrix_submatrix(A, 0, 0, N, N);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &tmp.matrix, U);
tmp = gsl_matrix_submatrix(A, N, 0, N, N);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &tmp.matrix, S);
gsl_matrix_memcpy(U_svd, A);
gsl_linalg_SV_decomp(U_svd, V_svd, S_svd, work);
gsl_linalg_SV_solve(U_svd, V_svd, S_svd, b, x_svd);
/* compare QR with SVD solution */
for (i = 0; i < N; i++)
{
double xi = gsl_vector_get(x, i);
double yi = gsl_vector_get(x_svd, i);
gsl_test_rel(xi, yi, eps, "%s (%3lu,%3lu)[%lu]: %22.18g %22.18g\n",
desc, M, N, i, xi, yi);
}
if (M > N)
{
gsl_vector_view x1 = gsl_vector_subvector(x, 0, N);
gsl_vector_view x2 = gsl_vector_subvector(x, N, M - N);
double norm = gsl_blas_dnrm2(&x2.vector);
double norm_expected;
/* compute residual and check || x(N+1:end) || = || b - A x || */
gsl_vector_memcpy(residual, b);
gsl_blas_dgemv(CblasNoTrans, -1.0, A, &x1.vector, 1.0, residual);
norm_expected = gsl_blas_dnrm2(residual);
gsl_test_rel(norm, norm_expected, eps, "%s rnorm (%3lu,%3lu): %22.18g %22.18g\n",
desc, M, N, norm, norm_expected);
}
gsl_matrix_free(A);
gsl_matrix_free(R);
gsl_matrix_free(Y);
gsl_matrix_free(T);
gsl_vector_free(x);
gsl_matrix_free(U_svd);
gsl_matrix_free(V_svd);
gsl_vector_free(x_svd);
gsl_vector_free(work);
gsl_vector_free(S_svd);
gsl_vector_free(residual);
return s;
}
static int
test_QR_UU_lssolve(gsl_rng * r)
{
int s = 0;
const size_t N_max = 30;
gsl_matrix * U = gsl_matrix_alloc(N_max, N_max);
gsl_matrix * S = gsl_matrix_alloc(N_max, N_max);
gsl_matrix * T = gsl_matrix_alloc(N_max, N_max);
gsl_vector * rhs = gsl_vector_alloc(2*N_max);
size_t N;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix_view a = gsl_matrix_submatrix(U, 0, 0, N, N);
gsl_matrix_view b = gsl_matrix_submatrix(S, 0, 0, N, N);
gsl_matrix_view c = gsl_matrix_submatrix(T, 0, 0, N, N);
gsl_vector_view rhsv = gsl_vector_subvector(rhs, 0, 2*N);
create_random_vector(&rhsv.vector, r);
create_random_matrix(&c.matrix, r);
gsl_matrix_set_zero(&a.matrix);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &a.matrix, &c.matrix);
create_random_matrix(&c.matrix, r);
gsl_matrix_set_zero(&b.matrix);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &b.matrix, &c.matrix);
s += test_QR_UU_lssolve_eps(&a.matrix, &b.matrix, &rhsv.vector, 1.0e4 * N * GSL_DBL_EPSILON,
"QR_UU_lssolve random");
}
gsl_matrix_free(U);
gsl_matrix_free(S);
gsl_matrix_free(T);
gsl_vector_free(rhs);
return s;
}
static int
test_QR_UD_decomp_eps(const gsl_matrix * U, const gsl_vector * D, const double eps, const char * desc)
{
int s = 0;
const size_t N = U->size2;
size_t i, j;
gsl_matrix * R = gsl_matrix_calloc(N, N);
gsl_matrix * V = gsl_matrix_calloc(N, N);
gsl_matrix * T = gsl_matrix_alloc(N, N);
gsl_matrix * B1 = gsl_matrix_calloc(N, N);
gsl_matrix * B2 = gsl_matrix_calloc(N, N);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, R, U);
s += gsl_linalg_QR_UD_decomp(R, D, V, T);
/*
* compute B = Q R = [ R - T R ]
* [ -V~ T R ]
*/
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, B1, T);
gsl_blas_dtrmm (CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, R, B1); /* B1 = T R */
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, B2, B1); /* B2 := T R */
gsl_blas_dtrmm (CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, V, B2); /* B2 = -V~ T R */
gsl_matrix_sub (B1, R); /* B1 = T R - R */
gsl_matrix_scale (B1, -1.0); /* B1 = R - T R */
/* test U = B1 */
for (i = 0; i < N; i++)
{
for (j = i; j < N; j++)
{
double aij = gsl_matrix_get(B1, i, j);
double mij = gsl_matrix_get(U, i, j);
gsl_test_rel(aij, mij, eps, "%s B1 (%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, i, j, aij, mij);
}
}
/* test S = B2 */
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
double aij = gsl_matrix_get(B2, i, j);
double mij = (i == j) ? gsl_vector_get(D, i) : 0.0;
gsl_test_rel(aij, mij, eps, "%s B2 (%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, i,j, aij, mij);
}
}
gsl_matrix_free(R);
gsl_matrix_free(V);
gsl_matrix_free(T);
gsl_matrix_free(B1);
gsl_matrix_free(B2);
return s;
}
static int
test_QR_UD_decomp(gsl_rng * r)
{
int s = 0;
const size_t N_max = 30;
gsl_matrix * U = gsl_matrix_alloc(N_max, N_max);
gsl_matrix * S = gsl_matrix_alloc(N_max, N_max);
gsl_vector * D = gsl_vector_alloc(N_max);
size_t N;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix_view a = gsl_matrix_submatrix(U, 0, 0, N, N);
gsl_matrix_view b = gsl_matrix_submatrix(S, 0, 0, N, N);
gsl_vector_view diag = gsl_vector_subvector(D, 0, N);
create_random_matrix(&b.matrix, r);
gsl_matrix_set_zero(&a.matrix);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &a.matrix, &b.matrix);
create_random_vector(&diag.vector, r);
s += test_QR_UD_decomp_eps(&a.matrix, &diag.vector, 1.0e4 * N * GSL_DBL_EPSILON,
"QR_UD_decomp random");
}
gsl_matrix_free(U);
gsl_matrix_free(S);
gsl_vector_free(D);
return s;
}
static int
test_QR_UD_lssolve_eps(const gsl_matrix * U, const gsl_vector * D, const gsl_vector * b,
const double eps, const char * desc)
{
int s = 0;
const size_t N = U->size1;
const size_t M = 2 * N;
size_t i;
gsl_matrix * R = gsl_matrix_calloc(N, N);
gsl_matrix * Y = gsl_matrix_calloc(N, N);
gsl_matrix * T = gsl_matrix_alloc(N, N);
gsl_vector * x = gsl_vector_alloc(M);
gsl_vector * work = gsl_vector_alloc(N);
gsl_matrix * A = gsl_matrix_calloc(M, N);
gsl_matrix * U_svd = gsl_matrix_alloc(M, N);
gsl_matrix * V_svd = gsl_matrix_alloc(N, N);
gsl_vector * S_svd = gsl_vector_alloc(N);
gsl_vector * x_svd = gsl_vector_alloc(N);
gsl_vector * residual = gsl_vector_alloc(M);
gsl_matrix_view tmp;
gsl_vector_view diag;
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, R, U);
s += gsl_linalg_QR_UD_decomp(R, D, Y, T);
s += gsl_linalg_QR_UD_lssolve(R, Y, T, b, x, work);
tmp = gsl_matrix_submatrix(A, 0, 0, N, N);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &tmp.matrix, U);
tmp = gsl_matrix_submatrix(A, N, 0, N, N);
diag = gsl_matrix_diagonal(&tmp.matrix);
gsl_vector_memcpy(&diag.vector, D);
gsl_matrix_memcpy(U_svd, A);
gsl_linalg_SV_decomp(U_svd, V_svd, S_svd, work);
gsl_linalg_SV_solve(U_svd, V_svd, S_svd, b, x_svd);
/* compare QR with SVD solution */
for (i = 0; i < N; i++)
{
double xi = gsl_vector_get(x, i);
double yi = gsl_vector_get(x_svd, i);
gsl_test_rel(xi, yi, eps, "%s (%3lu,%3lu)[%lu]: %22.18g %22.18g\n",
desc, M, N, i, xi, yi);
}
if (M > N)
{
gsl_vector_view x1 = gsl_vector_subvector(x, 0, N);
gsl_vector_view x2 = gsl_vector_subvector(x, N, M - N);
double norm = gsl_blas_dnrm2(&x2.vector);
double norm_expected;
/* compute residual and check || x(N+1:end) || = || b - A x || */
gsl_vector_memcpy(residual, b);
gsl_blas_dgemv(CblasNoTrans, -1.0, A, &x1.vector, 1.0, residual);
norm_expected = gsl_blas_dnrm2(residual);
gsl_test_rel(norm, norm_expected, eps, "%s rnorm (%3lu,%3lu): %22.18g %22.18g\n",
desc, M, N, norm, norm_expected);
}
gsl_matrix_free(A);
gsl_matrix_free(R);
gsl_matrix_free(Y);
gsl_matrix_free(T);
gsl_vector_free(x);
gsl_matrix_free(U_svd);
gsl_matrix_free(V_svd);
gsl_vector_free(x_svd);
gsl_vector_free(work);
gsl_vector_free(S_svd);
gsl_vector_free(residual);
return s;
}
static int
test_QR_UD_lssolve(gsl_rng * r)
{
int s = 0;
const size_t N_max = 30;
gsl_matrix * U = gsl_matrix_alloc(N_max, N_max);
gsl_matrix * S = gsl_matrix_alloc(N_max, N_max);
gsl_vector * D = gsl_vector_alloc(N_max);
gsl_vector * rhs = gsl_vector_alloc(2*N_max);
size_t N;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix_view a = gsl_matrix_submatrix(U, 0, 0, N, N);
gsl_matrix_view b = gsl_matrix_submatrix(S, 0, 0, N, N);
gsl_vector_view rhsv = gsl_vector_subvector(rhs, 0, 2*N);
gsl_vector_view diag = gsl_vector_subvector(D, 0, N);
create_random_vector(&rhsv.vector, r);
create_random_vector(&diag.vector, r);
create_random_matrix(&b.matrix, r);
gsl_matrix_set_zero(&a.matrix);
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, &a.matrix, &b.matrix);
s += test_QR_UD_lssolve_eps(&a.matrix, &diag.vector, &rhsv.vector, 1.0e4 * N * GSL_DBL_EPSILON,
"QR_UD_lssolve random");
}
gsl_matrix_free(U);
gsl_matrix_free(S);
gsl_vector_free(D);
gsl_vector_free(rhs);
return s;
}
| {
"alphanum_fraction": 0.591463613,
"avg_line_length": 28.1235132662,
"ext": "c",
"hexsha": "1c566a18bf90747a5149a8392c868d88cf877689",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_qr.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_qr.c",
"max_line_length": 103,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/test_qr.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z",
"num_tokens": 10195,
"size": 30739
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIBMINIFI_INCLUDE_UTILS_GSL_H_
#define LIBMINIFI_INCLUDE_UTILS_GSL_H_
#include <type_traits>
#include <gsl-lite/gsl-lite.hpp>
namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace gsl = ::gsl_lite;
namespace utils {
namespace detail {
template<typename T>
using remove_cvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
} // namespace detail
template<typename Container, typename T>
Container span_to(gsl::span<T> span) {
static_assert(std::is_constructible<Container, typename gsl::span<T>::iterator, typename gsl::span<T>::iterator>::value,
"The destination container must have an iterator (pointer) range constructor");
return Container(std::begin(span), std::end(span));
}
template<template<typename...> class Container, typename T>
Container<detail::remove_cvref_t<T>> span_to(gsl::span<T> span) {
static_assert(std::is_constructible<Container<detail::remove_cvref_t<T>>, typename gsl::span<T>::iterator, typename gsl::span<T>::iterator>::value,
"The destination container must have an iterator (pointer) range constructor");
return span_to<Container<detail::remove_cvref_t<T>>>(span);
}
} // namespace utils
} // namespace minifi
} // namespace nifi
} // namespace apache
} // namespace org
#endif // LIBMINIFI_INCLUDE_UTILS_GSL_H_
| {
"alphanum_fraction": 0.753968254,
"avg_line_length": 37.5789473684,
"ext": "h",
"hexsha": "9bd4f09e57313ea3c1f69eb4ae72170d5934342c",
"lang": "C",
"max_forks_count": 104,
"max_forks_repo_forks_event_max_datetime": "2022-03-01T13:39:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-04-28T15:20:51.000Z",
"max_forks_repo_head_hexsha": "87147e2dffcda6cc6e4e0510a57cc88011fda37f",
"max_forks_repo_licenses": [
"Apache-2.0",
"OpenSSL"
],
"max_forks_repo_name": "dtrodrigues/nifi-minifi-cpp",
"max_forks_repo_path": "libminifi/include/utils/gsl.h",
"max_issues_count": 688,
"max_issues_repo_head_hexsha": "87147e2dffcda6cc6e4e0510a57cc88011fda37f",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T07:58:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-28T17:52:38.000Z",
"max_issues_repo_licenses": [
"Apache-2.0",
"OpenSSL"
],
"max_issues_repo_name": "dtrodrigues/nifi-minifi-cpp",
"max_issues_repo_path": "libminifi/include/utils/gsl.h",
"max_line_length": 149,
"max_stars_count": 113,
"max_stars_repo_head_hexsha": "87147e2dffcda6cc6e4e0510a57cc88011fda37f",
"max_stars_repo_licenses": [
"Apache-2.0",
"OpenSSL"
],
"max_stars_repo_name": "dtrodrigues/nifi-minifi-cpp",
"max_stars_repo_path": "libminifi/include/utils/gsl.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-26T20:42:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-30T15:00:13.000Z",
"num_tokens": 487,
"size": 2142
} |
/* specfunc/bessel_K1.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_exp.h>
#include <gsl/gsl_sf_bessel.h>
#include "error.h"
#include "chebyshev.h"
#include "cheb_eval.c"
/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/
/* based on SLATEC besk1(), besk1e() */
/* chebyshev expansions
series for bk1 on the interval 0. to 4.00000d+00
with weighted error 7.02e-18
log weighted error 17.15
significant figures required 16.73
decimal places required 17.67
series for ak1 on the interval 1.25000d-01 to 5.00000d-01
with weighted error 6.06e-17
log weighted error 16.22
significant figures required 15.41
decimal places required 16.83
series for ak12 on the interval 0. to 1.25000d-01
with weighted error 2.58e-17
log weighted error 16.59
significant figures required 15.22
decimal places required 17.16
*/
static double bk1_data[11] = {
0.0253002273389477705,
-0.3531559607765448760,
-0.1226111808226571480,
-0.0069757238596398643,
-0.0001730288957513052,
-0.0000024334061415659,
-0.0000000221338763073,
-0.0000000001411488392,
-0.0000000000006666901,
-0.0000000000000024274,
-0.0000000000000000070
};
static cheb_series bk1_cs = {
bk1_data,
10,
-1, 1,
8
};
static double ak1_data[17] = {
0.27443134069738830,
0.07571989953199368,
-0.00144105155647540,
0.00006650116955125,
-0.00000436998470952,
0.00000035402774997,
-0.00000003311163779,
0.00000000344597758,
-0.00000000038989323,
0.00000000004720819,
-0.00000000000604783,
0.00000000000081284,
-0.00000000000011386,
0.00000000000001654,
-0.00000000000000248,
0.00000000000000038,
-0.00000000000000006
};
static cheb_series ak1_cs = {
ak1_data,
16,
-1, 1,
9
};
static double ak12_data[14] = {
0.06379308343739001,
0.02832887813049721,
-0.00024753706739052,
0.00000577197245160,
-0.00000020689392195,
0.00000000973998344,
-0.00000000055853361,
0.00000000003732996,
-0.00000000000282505,
0.00000000000023720,
-0.00000000000002176,
0.00000000000000215,
-0.00000000000000022,
0.00000000000000002
};
static cheb_series ak12_cs = {
ak12_data,
13,
-1, 1,
7
};
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int gsl_sf_bessel_K1_scaled_e(const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x <= 0.0) {
DOMAIN_ERROR(result);
}
else if(x < 2.0*GSL_DBL_MIN) {
OVERFLOW_ERROR(result);
}
else if(x <= 2.0) {
const double lx = log(x);
const double ex = exp(x);
int stat_I1;
gsl_sf_result I1;
gsl_sf_result c;
cheb_eval_e(&bk1_cs, 0.5*x*x-1.0, &c);
stat_I1 = gsl_sf_bessel_I1_e(x, &I1);
result->val = ex * ((lx-M_LN2)*I1.val + (0.75 + c.val)/x);
result->err = ex * (c.err/x + fabs(lx)*I1.err);
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_I1;
}
else if(x <= 8.0) {
const double sx = sqrt(x);
gsl_sf_result c;
cheb_eval_e(&ak1_cs, (16.0/x-5.0)/3.0, &c);
result->val = (1.25 + c.val) / sx;
result->err = c.err / sx;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
const double sx = sqrt(x);
gsl_sf_result c;
cheb_eval_e(&ak12_cs, 16.0/x-1.0, &c);
result->val = (1.25 + c.val) / sx;
result->err = c.err / sx;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
}
int gsl_sf_bessel_K1_e(const double x, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x <= 0.0) {
DOMAIN_ERROR(result);
}
else if(x < 2.0*GSL_DBL_MIN) {
OVERFLOW_ERROR(result);
}
else if(x <= 2.0) {
const double lx = log(x);
int stat_I1;
gsl_sf_result I1;
gsl_sf_result c;
cheb_eval_e(&bk1_cs, 0.5*x*x-1.0, &c);
stat_I1 = gsl_sf_bessel_I1_e(x, &I1);
result->val = (lx-M_LN2)*I1.val + (0.75 + c.val)/x;
result->err = c.err/x + fabs(lx)*I1.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return stat_I1;
}
else {
gsl_sf_result K1_scaled;
int stat_K1 = gsl_sf_bessel_K1_scaled_e(x, &K1_scaled);
int stat_e = gsl_sf_exp_mult_err_e(-x, 0.0,
K1_scaled.val, K1_scaled.err,
result);
result->err = fabs(result->val) * (GSL_DBL_EPSILON*fabs(x) + K1_scaled.err/K1_scaled.val);
return GSL_ERROR_SELECT_2(stat_e, stat_K1);
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_bessel_K1_scaled(const double x)
{
EVAL_RESULT(gsl_sf_bessel_K1_scaled_e(x, &result));
}
double gsl_sf_bessel_K1(const double x)
{
EVAL_RESULT(gsl_sf_bessel_K1_e(x, &result));
}
| {
"alphanum_fraction": 0.6028426728,
"avg_line_length": 27.6968325792,
"ext": "c",
"hexsha": "85317146756384653e10ae9432535b742c80175b",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_K1.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_K1.c",
"max_line_length": 94,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/bessel_K1.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 2031,
"size": 6121
} |
/*
** CCM - connectivity consistency mapping
**
** G.Lohmann, July 2010
*/
#include <viaio/Vlib.h>
#include <viaio/file.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <viaio/os.h>
#include <viaio/VImage.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define SQR(x) ((x) * (x))
#define ABS(x) ((x) > 0 ? (x) : -(x))
extern double VOCCC(gsl_matrix *,int,int);
extern double VICC(gsl_matrix *,int);
extern double VKendall_W(gsl_matrix *,int,int);
extern double SpearmanCorr(const float *data1,const float *data2, int n);
int metric = 1;
int verbose = 0;
VDictEntry TypeDict[] = {
{ "kendall", 0 },
{ "occc", 1 },
{ NULL }
};
double Correlation(const float *arr1,const float *arr2,int n)
{
int i;
double sx,sy,sxx,syy,sxy,rx;
double tiny=1.0e-4;
sxx = syy = sxy = sx = sy = 0;
for (i=0; i<n; i++) {
const double u = (double)arr1[i];
const double v = (double)arr2[i];
sx += u;
sy += v;
sxx += u*u;
syy += v*v;
sxy += u*v;
}
const double nx= n;
const double u = nx*sxx - sx*sx;
const double v = nx*syy - sy*sy;
rx = 0;
if (u*v > tiny)
rx = (nx*sxy - sx*sy)/sqrt(u*v);
return rx;
}
VImage VCCM(VImage **src, VImage mask, int nsubjects, int nslices,int first,int length,int type,int otype)
{
VImage map=NULL,dest=NULL;
int i,j,k,s,nvoxels,nt,len,last,b,r,c,bb,rr,cc,rad2,nrows,ncols;
double u=0,v=0;
gsl_matrix *data=NULL;
gsl_matrix_float **mat=NULL;
nrows = VImageNRows(mask);
ncols = VImageNColumns(mask);
/* count number of voxels, number of timesteps */
nvoxels = nt = 0;
for (b=0; b<nslices; b++) {
for (r=0; r<nrows; r++) {
for (c=0; c<ncols; c++) {
if (VGetPixel(mask,b,r,c) < 0.001) continue;
if (VImageNBands(src[0][b]) > nt)
nt = VImageNBands(src[0][b]);
nvoxels++;
}
}
}
/* get shortest length of time series across subjects */
nt = 99999;
for (s=0; s<nsubjects; s++) {
for (b=0; b<nslices; b++) {
for (r=0; r<nrows; r++) {
for (c=0; c<ncols; c++) {
if (VGetPixel(mask,b,r,c) < 0.001) continue;
if (VImageNBands(src[s][b]) < nt)
nt = VImageNBands(src[s][b]);
}
}
}
}
/* get time steps to include */
if (length < 1) length = nt-2;
last = first + length -1;
if (last >= nt) last = nt-1;
if (first < 0) first = 1;
nt = last - first + 1;
if (nt < 2) VError(" not enough timesteps, nt= %d",nt);
fprintf(stderr," first= %d, last= %d, ntimesteps= %d\n",
(int)first,(int)last,(int)nt);
fprintf(stderr," nsubjects= %d, nvoxels= %d\n",nsubjects,nvoxels);
fprintf(stderr," type= %s\n",TypeDict[type].keyword);
/*
** store voxel addresses
*/
map = VCreateImage(1,3,nvoxels,VIntegerRepn);
if (map == NULL) VError(" error allocating addr map");
VFillImage(map,VAllBands,0);
i = 0;
for (b=0; b<nslices; b++) {
for (r=0; r<nrows; r++) {
for (c=0; c<ncols; c++) {
if (VGetPixel(mask,b,r,c) < 0.001) continue;
if (i >= nvoxels) VError(" nvox= %d",i);
VPixel(map,0,0,i,VInteger) = b;
VPixel(map,0,1,i,VInteger) = r;
VPixel(map,0,2,i,VInteger) = c;
i++;
}
}
}
/*
** avoid casting to float, copy data to matrix
*/
mat = (gsl_matrix_float **) VCalloc(nsubjects,sizeof(gsl_matrix_float *));
if (!mat) VError(" err allocating mat");
for (s=0; s<nsubjects; s++) {
mat[s] = gsl_matrix_float_calloc(nvoxels,nt);
if (!mat[s]) VError(" err allocating mat[s]");
for (i=0; i<nvoxels; i++) {
b = VPixel(map,0,0,i,VInteger);
r = VPixel(map,0,1,i,VInteger);
c = VPixel(map,0,2,i,VInteger);
float *ptr = gsl_matrix_float_ptr(mat[s],i,0);
int k;
for (k=first; k<=last; k++) {
*ptr++ = (float) VGetPixel(src[s][b],k,r,c);
}
}
}
/*
** for each seed voxel assess intersubject consistency
*/
dest = VCreateImage(nslices,nrows,ncols,VFloatRepn);
VFillImage(dest,VAllBands,0);
VCopyImageAttrs (src[0][0], dest);
/*
** get correlation maps
*/
data = gsl_matrix_calloc(nsubjects,nvoxels);
rad2 = 3*9;
for (i=0; i<nvoxels; i++) {
if (i%10 == 0) fprintf(stderr," i: %7d of %d\r",i,nvoxels);
b = VPixel(map,0,0,i,VInteger);
r = VPixel(map,0,1,i,VInteger);
c = VPixel(map,0,2,i,VInteger);
len = 0;
for (s=0; s<nsubjects; s++) {
const float *arr1 = gsl_matrix_float_ptr(mat[s],i,0);
k = 0;
for (j=0; j<nvoxels; j++) {
if (i == j) continue;
bb = VPixel(map,0,0,j,VInteger);
rr = VPixel(map,0,1,j,VInteger);
cc = VPixel(map,0,2,j,VInteger);
/* exclude because of spatial smoothness: */
if ((SQR(b-bb) + SQR(r-rr) + SQR(c-cc)) < rad2) continue;
const float *arr2 = gsl_matrix_float_ptr(mat[s],j,0);
u = Correlation(arr1,arr2,nt);
gsl_matrix_set(data,s,k,(double)u);
k++;
}
len = k;
}
if (len >= data->size2) VError(" len= %d %d",len,data->size2);
if (type == 0)
v = VKendall_W(data,len,otype);
else if (type == 1)
v = VOCCC(data,len,verbose);
else
VError(" illegal type");
b = VPixel(map,0,0,i,VInteger);
r = VPixel(map,0,1,i,VInteger);
c = VPixel(map,0,2,i,VInteger);
VPixel(dest,b,r,c,VFloat) = v;
}
fprintf(stderr,"\n");
return dest;
}
int main (int argc, char *argv[])
{
static VArgVector in_files;
static VString out_filename;
static VString mask_filename;
static VShort type = 0;
static VShort otype = 0;
static VShort first = 2;
static VShort length = 0;
static VOptionDescRec options[] = {
{"in", VStringRepn, 0, & in_files, VRequiredOpt, NULL,"Input files" },
{"out", VStringRepn, 1, & out_filename, VRequiredOpt, NULL,"Output file" },
{"mask",VStringRepn,1,(VPointer) &mask_filename,VRequiredOpt,NULL,"Mask file"},
{"first",VShortRepn,1,(VPointer) &first,VOptionalOpt,NULL,"First timestep to use"},
{"length",VShortRepn,1,(VPointer) &length,VOptionalOpt,NULL,
"Length of time series to use, '0' to use full length"},
{"type",VShortRepn,1,(VPointer) &type,VOptionalOpt,TypeDict,"Type of metric"},
{"gauss",VShortRepn,1,(VPointer) &otype,VOptionalOpt,NULL,"Use gaussian version of kendall"},
};
VString in_filename;
VAttrList list=NULL,geolist=NULL;
int b,r,c,i=0;
float u;
char *prg = GetLipsiaName("vccm");
/*
** parse command line
*/
if (! VParseCommand (VNumber (options), options, & argc, argv)) {
VReportUsage (argv[0], VNumber (options), options, NULL);
exit (EXIT_FAILURE);
}
if (argc > 1) {
VReportBadArgs (argc, argv);
exit (EXIT_FAILURE);
}
/*
** read mask
*/
VAttrList mask_list = VReadAttrList(mask_filename,0L,TRUE,FALSE);
if (mask_list == NULL) VError(" error reading %s",mask_filename);
VImage mask = VReadImage(mask_list);
if (mask == NULL) VError(" no mask found");
/*
** read input images
*/
int nslices=0,nt=0,nrows=0,ncols=0;
int xslices=0,xnt=0,xrows=0,xcols=0;
int nsubjects = (int)in_files.number;
fprintf(stderr," nsubjects= %d\n",nsubjects);
if (nsubjects < 2) VError(" not enough input files (%d), CCM should be used on >= 2 data sets",nsubjects);
VImage **src = (VImage **) VCalloc(nsubjects,sizeof(VImage *));
for (i=0; i<nsubjects; i++) {
in_filename = ((VString *) in_files.vector)[i];
list = VReadAttrList(in_filename,0L,TRUE,FALSE);
xslices = VAttrListNumImages(list);
if (i==0) nslices = xslices;
else if (nslices != xslices) VError(" inconsistent dimensions in input files");
src[i] = VAttrListGetImages(list,nslices);
if (i==0) VImageDimensions(src[i],nslices,&nt,&nrows,&ncols);
else {
VImageDimensions(src[i],xslices,&xnt,&xrows,&xcols);
if (nrows != xrows) VError(" inconsistent dimensions in input files");
if (ncols != xcols) VError(" inconsistent dimensions in input files");
if (nt != xnt) VError(" inconsistent dimensions in input files");
}
/* use geometry info from 1st file */
if (geolist == NULL) geolist = VGetGeoInfo(list);
}
/*
** CCM
*/
VImage dest = VCCM(src,mask,nsubjects,nslices,(int)first,(int)length,(int)type,(int)otype);
/* invert to get discordant map */
VImage disc = VCreateImageLike(dest);
VFillImage(disc,VAllBands,0);
for (b=0; b<VImageNBands(dest); b++) {
for (r=0; r<VImageNRows(dest); r++) {
for (c=0; c<VImageNColumns(dest); c++) {
if (VGetPixel(mask,b,r,c) < 1) continue;
u = VPixel(dest,b,r,c,VFloat);
VPixel(disc,b,r,c,VFloat) = 1-u;
}
}
}
/*
** output
*/
VAttrList out_list = VCreateAttrList();
if (geolist != NULL) {
double *D = VGetGeoDim(geolist,NULL);
D[0] = 3; /* 3D */
D[4] = 1; /* just one timestep */
VSetGeoDim(geolist,D);
VSetGeoInfo(geolist,out_list);
}
VAppendAttr (out_list,"concordant",NULL,VImageRepn,dest);
VAppendAttr (out_list,"discordant",NULL,VImageRepn,disc);
VHistory(VNumber(options),options,prg,&list,&out_list);
FILE *fp = VOpenOutputFile (out_filename, TRUE);
if (! VWriteFile (fp, out_list)) exit (1);
fclose(fp);
fprintf (stderr, "%s: done.\n", argv[0]);
exit(0);
}
| {
"alphanum_fraction": 0.6066782307,
"avg_line_length": 26.3542857143,
"ext": "c",
"hexsha": "590f79951903b088433834e2654add7395cedf35",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/nets/vccm/vccm.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/nets/vccm/vccm.c",
"max_line_length": 108,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/nets/vccm/vccm.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z",
"num_tokens": 3152,
"size": 9224
} |
/**
*
* @file qwrapper_slaset2.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @date 2010-11-15
* @generated s Tue Jan 7 11:44:59 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_slaset2(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int M, int N,
float alpha, float *A, int LDA)
{
DAG_CORE_LASET;
QUARK_Insert_Task(quark, CORE_slaset2_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &M, VALUE,
sizeof(int), &N, VALUE,
sizeof(float), &alpha, VALUE,
sizeof(float)*M*N, A, OUTPUT,
sizeof(int), &LDA, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_slaset2_quark = PCORE_slaset2_quark
#define CORE_slaset2_quark PCORE_slaset2_quark
#endif
void CORE_slaset2_quark(Quark *quark)
{
PLASMA_enum uplo;
int M;
int N;
float alpha;
float *A;
int LDA;
quark_unpack_args_6(quark, uplo, M, N, alpha, A, LDA);
CORE_slaset2(uplo, M, N, alpha, A, LDA);
}
| {
"alphanum_fraction": 0.5185185185,
"avg_line_length": 27.4909090909,
"ext": "c",
"hexsha": "34816924cbba9f63cdd77c07c0d2a9ff9c9f6aad",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas-qwrapper/qwrapper_slaset2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_slaset2.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_slaset2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 414,
"size": 1512
} |
#ifndef H_GPC_UTILS
#define H_GPC_UTILS
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_poly.h>
/* The GSL is a pain to work with. The library DOES NOT HAVE a determinant() function
or an inv() function: you have to write your own routines. */
#define gmg gsl_matrix_get
#define gms gsl_matrix_set
void m_trans(const gsl_matrix*A, gsl_matrix*A_t);
void m_mult(const gsl_matrix*A, const gsl_matrix*B, gsl_matrix*AB);
void m_add(const gsl_matrix*A, const gsl_matrix*B, gsl_matrix*ApB);
void m_add_to(const gsl_matrix*A, gsl_matrix*B);
void m_scale(double m, gsl_matrix*A);
double m_dot(const gsl_matrix*A,const gsl_matrix*B);
void m_inv(const gsl_matrix*A, gsl_matrix*invA);
double m_det(const gsl_matrix*A);
/* Returns the real part of the roots in roots */
int poly_real_roots(unsigned int n, const double*a, double *roots);
int poly_greatest_real_root(unsigned int n, const double*a, double *root);
void m_display(const char*str, gsl_matrix*m);
#endif
| {
"alphanum_fraction": 0.7704433498,
"avg_line_length": 31.71875,
"ext": "h",
"hexsha": "40bf03269ce1d1c397ea598512cd7be679480262",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alecone/ROS_project",
"max_forks_repo_path": "src/csm/sm/lib/gpc/gpc_utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "alecone/ROS_project",
"max_issues_repo_path": "src/csm/sm/lib/gpc/gpc_utils.h",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alecone/ROS_project",
"max_stars_repo_path": "src/csm/sm/lib/gpc/gpc_utils.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 267,
"size": 1015
} |
/* eigen/schur.c
*
* Copyright (C) 2006 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_cblas.h>
#include "schur.h"
/*
* This module contains some routines related to manipulating the
* Schur form of a matrix which are needed by the eigenvalue solvers
*
* This file contains routines based on original code from LAPACK
* which is distributed under the modified BSD license. The LAPACK
* routine used is DLANV2.
*/
static inline void schur_standard_form(gsl_matrix *A, gsl_complex *eval1,
gsl_complex *eval2, double *cs,
double *sn);
/*
gsl_schur_standardize()
Wrapper function for schur_standard_form - convert a 2-by-2 eigenvalue
block to standard form and then update the Schur form and
Schur vectors.
Inputs: T - Schur form
row - row of T of 2-by-2 block to be updated
eval1 - where to store eigenvalue 1
eval2 - where to store eigenvalue 2
update_t - 1 = update the entire matrix T with the transformation
0 = do not update rest of T
Z - (optional) if non-null, accumulate transformation
*/
void
gsl_schur_standardize(gsl_matrix *T, size_t row, gsl_complex *eval1,
gsl_complex *eval2, int update_t, gsl_matrix *Z)
{
const size_t N = T->size1;
gsl_matrix_view m;
double cs, sn;
m = gsl_matrix_submatrix(T, row, row, 2, 2);
schur_standard_form(&m.matrix, eval1, eval2, &cs, &sn);
if (update_t)
{
gsl_vector_view xv, yv, v;
/*
* The above call to schur_standard_form transformed a 2-by-2 block
* of T into upper triangular form via the transformation
*
* U = [ CS -SN ]
* [ SN CS ]
*
* The original matrix T was
*
* T = [ T_{11} | T_{12} | T_{13} ]
* [ 0* | A | T_{23} ]
* [ 0 | 0* | T_{33} ]
*
* where 0* indicates all zeros except for possibly
* one subdiagonal element next to A.
*
* After schur_standard_form, T looks like this:
*
* T = [ T_{11} | T_{12} | T_{13} ]
* [ 0* | U^t A U | T_{23} ]
* [ 0 | 0* | T_{33} ]
*
* since only the 2-by-2 block of A was changed. However,
* in order to be able to back transform T at the end,
* we need to apply the U transformation to the rest
* of the matrix T since there is no way to apply a
* similarity transformation to T and change only the
* middle 2-by-2 block. In other words, let
*
* M = [ I 0 0 ]
* [ 0 U 0 ]
* [ 0 0 I ]
*
* and compute
*
* M^t T M = [ T_{11} | T_{12} U | T_{13} ]
* [ U^t 0* | U^t A U | U^t T_{23} ]
* [ 0 | 0* U | T_{33} ]
*
* So basically we need to apply the transformation U
* to the i x 2 matrix T_{12} and the 2 x (n - i + 2)
* matrix T_{23}, where i is the index of the top of A
* in T.
*
* The BLAS routine drot() is suited for this.
*/
if (row < (N - 2))
{
/* transform the 2 rows of T_{23} */
v = gsl_matrix_row(T, row);
xv = gsl_vector_subvector(&v.vector,
row + 2,
N - row - 2);
v = gsl_matrix_row(T, row + 1);
yv = gsl_vector_subvector(&v.vector,
row + 2,
N - row - 2);
gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);
}
if (row > 0)
{
/* transform the 2 columns of T_{12} */
v = gsl_matrix_column(T, row);
xv = gsl_vector_subvector(&v.vector,
0,
row);
v = gsl_matrix_column(T, row + 1);
yv = gsl_vector_subvector(&v.vector,
0,
row);
gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);
}
} /* if (update_t) */
if (Z)
{
gsl_vector_view xv, yv;
/*
* Accumulate the transformation in Z. Here, Z -> Z * M
*
* So:
*
* Z -> [ Z_{11} | Z_{12} U | Z_{13} ]
* [ Z_{21} | Z_{22} U | Z_{23} ]
* [ Z_{31} | Z_{32} U | Z_{33} ]
*
* So we just need to apply drot() to the 2 columns
* starting at index 'row'
*/
xv = gsl_matrix_column(Z, row);
yv = gsl_matrix_column(Z, row + 1);
gsl_blas_drot(&xv.vector, &yv.vector, cs, sn);
} /* if (Z) */
} /* gsl_schur_standardize() */
/*******************************************************
* INTERNAL ROUTINES *
*******************************************************/
/*
schur_standard_form()
Compute the Schur factorization of a real 2-by-2 matrix in
standard form:
[ A B ] = [ CS -SN ] [ T11 T12 ] [ CS SN ]
[ C D ] [ SN CS ] [ T21 T22 ] [-SN CS ]
where either:
1) T21 = 0 so that T11 and T22 are real eigenvalues of the matrix, or
2) T11 = T22 and T21*T12 < 0, so that T11 +/- sqrt(|T21*T12|) are
complex conjugate eigenvalues
Inputs: A - 2-by-2 matrix
eval1 - where to store eigenvalue 1
eval2 - where to store eigenvalue 2
cs - where to store cosine parameter of rotation matrix
sn - where to store sine parameter of rotation matrix
Notes: based on LAPACK routine DLANV2
*/
static inline void
schur_standard_form(gsl_matrix *A, gsl_complex *eval1, gsl_complex *eval2,
double *cs, double *sn)
{
double a, b, c, d; /* input matrix values */
double tmp;
double p, z;
double bcmax, bcmis, scale;
double tau, sigma;
double cs1, sn1;
double aa, bb, cc, dd;
double sab, sac;
a = gsl_matrix_get(A, 0, 0);
b = gsl_matrix_get(A, 0, 1);
c = gsl_matrix_get(A, 1, 0);
d = gsl_matrix_get(A, 1, 1);
if (c == 0.0)
{
/*
* matrix is already upper triangular - set rotation matrix
* to the identity
*/
*cs = 1.0;
*sn = 0.0;
}
else if (b == 0.0)
{
/* swap rows and columns to make it upper triangular */
*cs = 0.0;
*sn = 1.0;
tmp = d;
d = a;
a = tmp;
b = -c;
c = 0.0;
}
else if (((a - d) == 0.0) && (GSL_SIGN(b) != GSL_SIGN(c)))
{
/* the matrix has complex eigenvalues with a == d */
*cs = 1.0;
*sn = 0.0;
}
else
{
tmp = a - d;
p = 0.5 * tmp;
bcmax = GSL_MAX(fabs(b), fabs(c));
bcmis = GSL_MIN(fabs(b), fabs(c)) * GSL_SIGN(b) * GSL_SIGN(c);
scale = GSL_MAX(fabs(p), bcmax);
z = (p / scale) * p + (bcmax / scale) * bcmis;
if (z >= 4.0 * GSL_DBL_EPSILON)
{
/* real eigenvalues, compute a and d */
z = p + GSL_SIGN(p) * fabs(sqrt(scale) * sqrt(z));
a = d + z;
d -= (bcmax / z) * bcmis;
/* compute b and the rotation matrix */
tau = gsl_hypot(c, z);
*cs = z / tau;
*sn = c / tau;
b -= c;
c = 0.0;
}
else
{
/*
* complex eigenvalues, or real (almost) equal eigenvalues -
* make diagonal elements equal
*/
sigma = b + c;
tau = gsl_hypot(sigma, tmp);
*cs = sqrt(0.5 * (1.0 + fabs(sigma) / tau));
*sn = -(p / (tau * (*cs))) * GSL_SIGN(sigma);
/*
* Compute [ AA BB ] = [ A B ] [ CS -SN ]
* [ CC DD ] [ C D ] [ SN CS ]
*/
aa = a * (*cs) + b * (*sn);
bb = -a * (*sn) + b * (*cs);
cc = c * (*cs) + d * (*sn);
dd = -c * (*sn) + d * (*cs);
/*
* Compute [ A B ] = [ CS SN ] [ AA BB ]
* [ C D ] [-SN CS ] [ CC DD ]
*/
a = aa * (*cs) + cc * (*sn);
b = bb * (*cs) + dd * (*sn);
c = -aa * (*sn) + cc * (*cs);
d = -bb * (*sn) + dd * (*cs);
tmp = 0.5 * (a + d);
a = d = tmp;
if (c != 0.0)
{
if (b != 0.0)
{
if (GSL_SIGN(b) == GSL_SIGN(c))
{
/*
* real eigenvalues: reduce to upper triangular
* form
*/
sab = sqrt(fabs(b));
sac = sqrt(fabs(c));
p = GSL_SIGN(c) * fabs(sab * sac);
tau = 1.0 / sqrt(fabs(b + c));
a = tmp + p;
d = tmp - p;
b -= c;
c = 0.0;
cs1 = sab * tau;
sn1 = sac * tau;
tmp = (*cs) * cs1 - (*sn) * sn1;
*sn = (*cs) * sn1 + (*sn) * cs1;
*cs = tmp;
}
}
else
{
b = -c;
c = 0.0;
tmp = *cs;
*cs = -(*sn);
*sn = tmp;
}
}
}
}
/* set eigenvalues */
GSL_SET_REAL(eval1, a);
GSL_SET_REAL(eval2, d);
if (c == 0.0)
{
GSL_SET_IMAG(eval1, 0.0);
GSL_SET_IMAG(eval2, 0.0);
}
else
{
tmp = sqrt(fabs(b) * fabs(c));
GSL_SET_IMAG(eval1, tmp);
GSL_SET_IMAG(eval2, -tmp);
}
/* set new matrix elements */
gsl_matrix_set(A, 0, 0, a);
gsl_matrix_set(A, 0, 1, b);
gsl_matrix_set(A, 1, 0, c);
gsl_matrix_set(A, 1, 1, d);
} /* schur_standard_form() */
| {
"alphanum_fraction": 0.4662086892,
"avg_line_length": 28.8793565684,
"ext": "c",
"hexsha": "b2b7adb3ab3824993cca8c6542cbbc8eda929a7b",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/eigen/schur.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/eigen/schur.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/eigen/schur.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 3067,
"size": 10772
} |
#ifndef ALLVARS_H
#define ALLVARS_H
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include "core_simulation.h"
#ifdef HDF5
#include <hdf5.h>
#define MODELNAME "SAGE"
#endif
#define NDIM 3
#define ABORT(sigterm) \
do { \
printf("Error in file: %s\tfunc: %s\tline: %i\n", __FILE__, __FUNCTION__, __LINE__); \
myexit(sigterm); \
} while(0)
#define STEPS 10 /* Number of integration intervals between two snapshots */
#define MAXGALFAC 1
#define ALLOCPARAMETER 10.0
#define MAX_NODE_NAME_LEN 50
#define ABSOLUTEMAXSNAPS 1000 /* The largest number of snapshots for any simulation */
#define MAXTAGS 300 /* Max number of parameters */
#define GRAVITY 6.672e-8
#define SOLAR_MASS 1.989e33
#define SOLAR_LUM 3.826e33
#define RAD_CONST 7.565e-15
#define AVOGADRO 6.0222e23
#define BOLTZMANN 1.3806e-16
#define GAS_CONST 8.31425e7
#define C 2.9979e10
#define PLANCK 6.6262e-27
#define CM_PER_MPC 3.085678e24
#define PROTONMASS 1.6726e-24
#define HUBBLE 3.2407789e-18 /* in h/sec */
#define SEC_PER_MEGAYEAR 3.155e13
#define SEC_PER_YEAR 3.155e7
#define MAX_STRING_LEN 1024 /* Max length of a string containing a name */
// This structure contains the properties that are output
struct GALAXY_OUTPUT
{
int SnapNum;
int Type;
long long GalaxyIndex;
long long CentralGalaxyIndex;
int SAGEHaloIndex;
int SAGETreeIndex;
long long SimulationHaloIndex;
int mergeType; /* 0=none; 1=minor merger; 2=major merger; 3=disk instability; 4=disrupt to ICS */
int mergeIntoID;
int mergeIntoSnapNum;
float dT;
/* (sub)halo properties */
float Pos[3];
float Vel[3];
float Spin[3];
int Len;
float Mvir;
float CentralMvir;
float Rvir;
float Vvir;
float Vmax;
float VelDisp;
/* baryonic reservoirs */
float ColdGas;
float StellarMass;
float BulgeMass;
float HotGas;
float EjectedMass;
float BlackHoleMass;
float ICS;
/* metals */
float MetalsColdGas;
float MetalsStellarMass;
float MetalsBulgeMass;
float MetalsHotGas;
float MetalsEjectedMass;
float MetalsICS;
/* to calculate magnitudes */
float SfrDisk;
float SfrBulge;
float SfrDiskZ;
float SfrBulgeZ;
/* misc */
float DiskScaleRadius;
float Cooling;
float Heating;
float QuasarModeBHaccretionMass;
float TimeOfLastMajorMerger;
float TimeOfLastMinorMerger;
float OutflowRate;
/* infall properties */
float infallMvir;
float infallVvir;
float infallVmax;
};
/* This structure contains the properties used within the code */
struct GALAXY
{
int SnapNum;
int Type;
int GalaxyNr;
int CentralGal;
int HaloNr;
long long MostBoundID;
int mergeType; /* 0=none; 1=minor merger; 2=major merger; 3=disk instability; 4=disrupt to ICS */
int mergeIntoID;
int mergeIntoSnapNum;
float dT;
/* (sub)halo properties */
float Pos[3];
float Vel[3];
int Len;
float Mvir;
float deltaMvir;
float CentralMvir;
float Rvir;
float Vvir;
float Vmax;
/* baryonic reservoirs */
float ColdGas;
float StellarMass;
float BulgeMass;
float HotGas;
float EjectedMass;
float BlackHoleMass;
float ICS;
/* metals */
float MetalsColdGas;
float MetalsStellarMass;
float MetalsBulgeMass;
float MetalsHotGas;
float MetalsEjectedMass;
float MetalsICS;
/* to calculate magnitudes */
float SfrDisk[STEPS];
float SfrBulge[STEPS];
float SfrDiskColdGas[STEPS];
float SfrDiskColdGasMetals[STEPS];
float SfrBulgeColdGas[STEPS];
float SfrBulgeColdGasMetals[STEPS];
/* misc */
float DiskScaleRadius;
float MergTime;
double Cooling;
double Heating;
float r_heat;
float QuasarModeBHaccretionMass;
float TimeOfLastMajorMerger;
float TimeOfLastMinorMerger;
float OutflowRate;
float TotalSatelliteBaryons;
/* infall properties */
float infallMvir;
float infallVvir;
float infallVmax;
}
*Gal, *HaloGal;
/* auxiliary halo data */
struct halo_aux_data
{
int DoneFlag;
int HaloFlag;
int NGalaxies;
int FirstGalaxy;
}
*HaloAux;
extern int FirstFile; /* first and last file for processing */
extern int LastFile;
extern int Ntrees; /* number of trees in current file */
extern int NumGals; /* Total number of galaxies stored for current tree */
extern int MaxGals; /* Maximum number of galaxies allowed for current tree */
extern int FoF_MaxGals;
extern int GalaxyCounter; /* unique galaxy ID for main progenitor line in tree */
extern int LastSnapShotNr;
extern char OutputDir[MAX_STRING_LEN];
extern char FileNameGalaxies[MAX_STRING_LEN];
extern char TreeName[MAX_STRING_LEN];
extern char TreeExtension[MAX_STRING_LEN]; // If the trees are in HDF5, they will have a .hdf5 extension. Otherwise they have no extension.
extern char SimulationDir[MAX_STRING_LEN];
extern char FileWithSnapList[MAX_STRING_LEN];
extern int TotHalos;
extern int TotGalaxies[ABSOLUTEMAXSNAPS];
extern int *TreeNgals[ABSOLUTEMAXSNAPS];
extern int *FirstHaloInSnap;
extern int *TreeNHalos;
extern int *TreeFirstHalo;
#ifdef MPI
extern int ThisTask, NTask, nodeNameLen;
extern char *ThisNode;
#endif
extern double Omega;
extern double OmegaLambda;
extern double PartMass;
extern double Hubble_h;
extern double EnergySNcode, EnergySN;
extern double EtaSNcode, EtaSN;
/* recipe flags */
extern int ReionizationOn;
extern int SupernovaRecipeOn;
extern int DiskInstabilityOn;
extern int AGNrecipeOn;
extern int SFprescription;
/* recipe parameters */
extern int NParam;
extern char ParamTag[MAXTAGS][50];
extern int ParamID[MAXTAGS];
extern void *ParamAddr[MAXTAGS];
extern double RecycleFraction;
extern double Yield;
extern double FracZleaveDisk;
extern double ReIncorporationFactor;
extern double ThreshMajorMerger;
extern double BaryonFrac;
extern double SfrEfficiency;
extern double FeedbackReheatingEpsilon;
extern double FeedbackEjectionEfficiency;
extern double RadioModeEfficiency;
extern double QuasarModeEfficiency;
extern double BlackHoleGrowthRate;
extern double Reionization_z0;
extern double Reionization_zr;
extern double ThresholdSatDisruption;
extern double UnitLength_in_cm,
UnitTime_in_s,
UnitVelocity_in_cm_per_s,
UnitMass_in_g,
RhoCrit,
UnitPressure_in_cgs,
UnitDensity_in_cgs,
UnitCoolingRate_in_cgs,
UnitEnergy_in_cgs,
UnitTime_in_Megayears,
G,
Hubble,
a0, ar;
extern int ListOutputSnaps[ABSOLUTEMAXSNAPS];
extern double ZZ[ABSOLUTEMAXSNAPS];
extern double AA[ABSOLUTEMAXSNAPS];
extern double *Age;
extern int MAXSNAPS;
extern int NOUT;
extern int Snaplistlen;
extern gsl_rng *random_generator;
extern int TreeID;
extern int FileNum;
#ifdef HDF5
extern char *core_output_file;
extern size_t HDF5_dst_size;
extern size_t *HDF5_dst_offsets;
extern size_t *HDF5_dst_sizes;
extern const char **HDF5_field_names;
extern hid_t *HDF5_field_types;
extern int HDF5_n_props;
#endif
#define DOUBLE 1
#define STRING 2
#define INT 3
enum Valid_TreeTypes
{
genesis_lhalo_hdf5 = 0,
lhalo_binary = 1,
num_tree_types
};
enum Valid_TreeTypes TreeType;
#endif /* #ifndef ALLVARS_H */
| {
"alphanum_fraction": 0.7126870702,
"avg_line_length": 23.178125,
"ext": "h",
"hexsha": "e022168f45073fb9c9ac080d551d8a2b72af0898",
"lang": "C",
"max_forks_count": 20,
"max_forks_repo_forks_event_max_datetime": "2021-09-13T05:50:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-03T06:12:58.000Z",
"max_forks_repo_head_hexsha": "a341bf79f34d79242c0a520dca5efa6e0c6a0f59",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "darrencroton/SAGE",
"max_forks_repo_path": "code/core_allvars.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "a341bf79f34d79242c0a520dca5efa6e0c6a0f59",
"max_issues_repo_issues_event_max_datetime": "2020-10-12T09:18:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-01T14:25:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "darrencroton/SAGE",
"max_issues_repo_path": "code/core_allvars.h",
"max_line_length": 141,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "a341bf79f34d79242c0a520dca5efa6e0c6a0f59",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "darrencroton/sage",
"max_stars_repo_path": "code/core_allvars.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-28T12:25:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-22T01:22:18.000Z",
"num_tokens": 2143,
"size": 7417
} |
#include <bindings.cmacros.h>
#include <gsl/gsl_vector.h>
BC_INLINE2(GSL_COMPLEX_AT,gsl_vector_complex*,size_t,gsl_complex*)
BC_INLINE2(GSL_COMPLEX_FLOAT_AT,gsl_vector_complex_float*,size_t,gsl_complex_float*)
/* BC_INLINE2(GSL_COMPLEX_LONG_DOUBLE_AT,gsl_vector_complex_long_double*,size_t,gsl_complex_long_double*) */
| {
"alphanum_fraction": 0.859375,
"avg_line_length": 45.7142857143,
"ext": "c",
"hexsha": "1bc774e2264c637ccf476d69fd16773178115335",
"lang": "C",
"max_forks_count": 19,
"max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z",
"max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "flip111/bindings-dsl",
"max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/VectorsAndMatrices/Vectors.c",
"max_issues_count": 23,
"max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb",
"max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "flip111/bindings-dsl",
"max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/VectorsAndMatrices/Vectors.c",
"max_line_length": 108,
"max_stars_count": 25,
"max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "flip111/bindings-dsl",
"max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/VectorsAndMatrices/Vectors.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z",
"num_tokens": 81,
"size": 320
} |
#ifndef CTETRA_PARTIAL_H
#define CTETRA_PARTIAL_H
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_matrix.h>
#include "input.h"
#include "evcache.h"
#include "submesh.h"
double Gauss_PartialDos_Eig(double E, double sigma, int orig_index, int eig_index, EvecCache *evCache);
double Gauss_PartialDos(double E, double sigma, int orig_index, EvecCache *evCache);
double** Gauss_PartialDosList(UEInputFn UEfn, int na, int nb, int nc, double sigma, int num_bands, gsl_matrix *R, double **Es, int num_dos);
#endif //CTETRA_PARTIAL_H
| {
"alphanum_fraction": 0.7703349282,
"avg_line_length": 29.8571428571,
"ext": "h",
"hexsha": "662f5483b01301ecbd4a964e1841c0489b8a62b3",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tflovorn/ctetra",
"max_forks_repo_path": "partial.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tflovorn/ctetra",
"max_issues_repo_path": "partial.h",
"max_line_length": 140,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tflovorn/ctetra",
"max_stars_repo_path": "partial.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 184,
"size": 627
} |
/*! \file Integrate.h
* \brief header file for integrating functions or data.
*/
#ifndef INTEGRATE_H
#define INTEGRATE_H
#include <cmath>
#include <iostream>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_plain.h>
#include <gsl/gsl_monte_miser.h>
#include <gsl/gsl_monte_vegas.h>
#include <Precision.h>
#include <Function.h>
#include <Interpolate.h>
#include <Random.h>
using namespace std;
namespace Math
{
/// Integrate function f(x) from x[lower] to x[upper]. Uses some
/// algorithm I found somewhere, sometime.
Double_t IntegrateData(const Double_t x[], const Double_t f[], const int lower,
const int upper);
/// Integrate function f(x) from x[lower] to x[upper]. Uses trapeziod
/// algorithm.
Double_t IntegrateTrap(const Double_t x[], const Double_t f[], const int a,
const int b);
///uses adaptive trapezoidal rule based on numerical recipes
Double_t IntegrateTrapezoidal(const math_function * f, const Double_t a,
const Double_t b, const int n);
Double_t IntegrateQTrap(const math_function * f, const Double_t a,
const Double_t b, const Double_t epsrel, int IMAX=16);
///uses simple trapezoidal
Double_t IntegrateSimpleTrapezoidal(const math_function * f, const Double_t a,
const Double_t b, const int n);
///extended closed integration
Double_t IntegrateClosed(const math_function * f, const Double_t a,
const Double_t b, const int n);
///simpsons 3/8 rule
Double_t IntegrateSimpson(const math_function * f, const Double_t a,
const Double_t b);
///Romberg integration based on numerical recipes
Double_t IntegrateRomberg(const math_function * f, const Double_t a,
const Double_t b, const Double_t epsrel, const int n, const int K);
///integration based vegas monte carlo integrator. can also return error and chisq
///vegas monte is either gsl or NR based vegas integrator.
Double_t IntegrateVegasMonte(math_multidim_function * f, Double_t *a, Double_t *b, const int n, Double_t *error=0,Double_t*chisq=0,int interations=6);
double IntegrateVegasMonte(gsl_monte_function * f, double *a, double *b, const int n, double *error=0,double *chisq=0);
///Romberg integration based on numerical recipes but uses vegas monte carlo integrator.
Double_t IntegrateRombergMonte(math_multidim_function * f, Double_t *a,
Double_t *b, const Double_t epsrel, const int sampling, const int n, const int K, int interations=6);
///subroutine used in my nr vegas integrator.
void rebin(Double_t rc, int nd, Double_t r[], Double_t xin[], Double_t xi[]);
///numerical recipes vegas integrator. for simplicity use IntegrateVegasMonte as interface
void vegas(math_multidim_function *fxn, Double_t regn[], int ndim, int init,
unsigned long ncall, int itmx, int nprn, long int idum, Double_t *tgral, Double_t *sd,
Double_t *chi2a);
}
#endif
| {
"alphanum_fraction": 0.6868304978,
"avg_line_length": 42.8918918919,
"ext": "h",
"hexsha": "6b6ddc7f4c42287f71d2a4150e1b7eb67570744f",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-10-23T00:21:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-23T02:58:07.000Z",
"max_forks_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ICRAR/NBodylib",
"max_forks_repo_path": "src/Math/Integrate.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_issues_repo_issues_event_max_datetime": "2021-07-27T06:31:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-21T16:49:12.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ICRAR/NBodylib",
"max_issues_repo_path": "src/Math/Integrate.h",
"max_line_length": 154,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ICRAR/NBodylib",
"max_stars_repo_path": "src/Math/Integrate.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 813,
"size": 3174
} |
#ifndef __bvd_rng_h_
#define __bvd_rng_h_
#include "Cow.h"
#include <cmath>
#include <gsl/gsl_rng.h>
#include <time.h>
#include "Model_Constants.h"
#include <cmath>
#include <gsl/gsl_rng.h>
#include <time.h>
class Random_Number_Generator
{
public:
Random_Number_Generator();
Random_Number_Generator( unsigned int seed );
void init( unsigned int seed);
/// draw a random integer/double between lo (inclusive) and hi (exclusive)
/// from a uniform distribution.
int ran_unif_int( int hi , int lo=0);
double ran_unif_double( double hi, double lo=0 );
int ran_triangular_int(double lo,double hi,double mod);
double ran_triangular_double(double lo,double hi,double mod);
int ran_poisson_int(int r, double mu);
// true or false, depending on whether a calf ( age < bvd_const::age_threshold_calf ) just infected with BVD will die or not
bool will_TI_calf_die();
double time_of_death_infected_calf();
double time_of_next_infection(double rate);
Calf_Status calf_outcome_from_infection ( double time_of_pregnancy );
double time_of_abortion_due_to_infection( double time_of_pregnancy );
double time_of_rest_after_calving(int calving_number);
// true or false if a birth is a deadbirth, assuming that the infection status of neither mother nor calf are known.
// This depends on the age of the mother, as indicated in table 4.1 of the handout ("Anteil nicht lebend ausgetragener Kälber, Färsen/Kühle")
// The wording of the handout is not clear whether in the figures of the handout also abortions are included.
// In this function, abortions are *not* included.
bool is_this_a_deadbirth( bool first_pregnancy );
//How long is a calf protected by the maternal antibodies in the colostrum.
double duration_of_MA();
//Duration of an infection with BVD ( time that the infection state 'transiently infected' lasts )
double duration_of_infection();
double duration_of_pregnancy();
double staggering_first_inseminations();
int number_of_calvings();
virtual bool is_calf_female();
// double lifetime_male_calves();
double first_insemination_age();
double lifetime_PI();
double time_of_death_as_calf();
double insemination_result( bool first_pregnancy , bool* conception );
double life_expectancy_male_cow();
//It has to be decided whether a beginning pregnancy will lead to an abortion or a birth.
// Also here, pointer *birth is meant for output. if false, abortion is the case. If true birth is the case.
// The return value is the time until the event (in case of birth -> duration of pregnancy, in case of abortion -> time until abortion ).
// afaik, in the statistics we have, only the total abortion rates are given.
// We don't know yet (as of 10.12.2015) whether there is a correlation between abortion happening and the infection status of the mother or the age of the mother.
// So for now, treat it as uncorrelated. And use the total abortion rates given in the handout.
double conception_result( double age_of_mother, Infection_Status is_of_mother, bool* birth );
void getNRandomNumbersInRange(int n, int rangeLeft, int rangeRight, int* resultArray);
//double cowWellTimeOfBirth(double time);
bool bloodTestRightResult();
double removeTimeAfterFirstTest();
double removeTimeAfterSecondTest();
double retestTime();
unsigned int getSeed();
bool cowGetsASecondChance();
double timeOfFirstTest();
virtual bool vaccinationWorks();
private:
gsl_rng * generator;
unsigned int seed ;
};
#endif
| {
"alphanum_fraction": 0.7411308204,
"avg_line_length": 41.9534883721,
"ext": "h",
"hexsha": "5d79517f9986766886af7e2409de0e461d37b890",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "a42ae72ca05d966015bab92afd20130a2c6d848a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Yperidis/bvd_agent_based_model",
"max_forks_repo_path": "include/BVD_Random_Number_Generator.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "a42ae72ca05d966015bab92afd20130a2c6d848a",
"max_issues_repo_issues_event_max_datetime": "2019-11-14T05:26:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-13T12:41:23.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Yperidis/bvd_agent_based_model",
"max_issues_repo_path": "include/BVD_Random_Number_Generator.h",
"max_line_length": 163,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "a42ae72ca05d966015bab92afd20130a2c6d848a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Yperidis/bvd_agent_based_model",
"max_stars_repo_path": "include/BVD_Random_Number_Generator.h",
"max_stars_repo_stars_event_max_datetime": "2020-11-11T09:27:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-11T09:27:02.000Z",
"num_tokens": 850,
"size": 3608
} |
/*! \file vhartree.h
\brief Hartreeポテンシャルを求めるクラスの宣言
Copyright © 2015 @dc1394 All Rights Reserved.
This software is released under the BSD 2-Clause License.
*/
#ifndef _VHARTREE_H_
#define _VHARTREE_H_
#pragma once
#include "diffdata.h"
#include "property.h"
#include <memory> // for std::unique_ptr
#include <gsl/gsl_spline.h> // for gsl_interp_accel, gsl_interp_accel_free, gsl_spline, gsl_spline_free
namespace schrac {
//! A class.
/*!
Hartreeポテンシャルを求めるクラス
*/
class Vhartree final {
// #region コンストラクタ・デストラクタ
public:
//! A constructor.
/*!
唯一のコンストラクタ
\param r_mesh_ rのメッシュ
*/
Vhartree(std::vector<double> const & r_mesh);
//! A private copy constructor.
/*!
コピーコンストラクタ
*/
Vhartree(Vhartree const & rhs);
//! A destructor.
/*!
デフォルトデストラクタ
*/
~Vhartree() = default;
// #region メンバ関数
//! A public member function (const).
/*!
Hartreeポテンシャルの微分値を返す
\param r 極座標のr
\return Hartreeポテンシャルの微分値
*/
double dvhartree_dr(double r) const;
//! A public member function.
/*!
Hartreeポテンシャルが境界条件を満たすようにセットする
\param Z 原子核の電荷
*/
void set_vhartree_boundary_condition(double Z);
//! A public member function.
/*!
Hartreeポテンシャルを初期化する
*/
void vhart_init();
//! A public member function (const).
/*!
Hartreeポテンシャルの値を返す
\param r 極座標のr
\return Hartreeポテンシャルの値
*/
double vhartree(double r) const;
// #endregion メンバ関数
// #region プロパティ
public:
//! A property.
/*!
Hartreeポテンシャルが格納された可変長配列へのプロパティ
*/
Property<std::vector<double>> Vhart;
// #endregion プロパティ
// #region メンバ変数
private:
//! A private member variable.
/*!
gsl_interp_accelへのスマートポインタ
*/
std::unique_ptr<gsl_interp_accel, decltype(&gsl_interp_accel_free)> const acc_;
//! A private member variable.
/*!
rのメッシュが格納された可変長配列
*/
std::vector<double> const r_mesh_;
//! A private member variable.
/*!
gsl_interp_typeへのスマートポインタ
*/
std::unique_ptr<gsl_spline, decltype(&gsl_spline_free)> const spline_;
//! A private member variable.
/*!
Hartreeポテンシャルが格納された可変長配列
*/
std::vector<double> vhart_;
// #endregion メンバ変数
// #region 禁止されたコンストラクタ・メンバ関数
private:
//! A private constructor (deleted).
/*!
デフォルトコンストラクタ(禁止)
*/
Vhartree() = delete;
//! A private member function (deleted).
/*!
operator=()の宣言(禁止)
\param コピー元のオブジェクト(未使用)
\return コピー元のオブジェクト
*/
Vhartree & operator=(Vhartree const &) = delete;
// #endregion 禁止されたコンストラクタ・メンバ関数
};
}
#endif // _VHARTREE_H_
| {
"alphanum_fraction": 0.5311320755,
"avg_line_length": 22.5531914894,
"ext": "h",
"hexsha": "4be0331943e1053b70b04e947c46d355571318b5",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "dc1394/schrac",
"max_forks_repo_path": "src/vhartree.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "dc1394/schrac",
"max_issues_repo_path": "src/vhartree.h",
"max_line_length": 103,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "6292f61f3be3465459f216b0b71d4b87138cff93",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "dc1394/Schrac",
"max_stars_repo_path": "src/vhartree.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-04T07:10:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-31T23:35:05.000Z",
"num_tokens": 1022,
"size": 3180
} |
#pragma once
#include "Hypo/Graphics/Exports.h"
#include "Hypo/System/DataTypes/ObjPtr.h"
#include "Hypo/Window/Context/GraphicsContext.h"
#include <gsl/span>
namespace Hypo
{
enum class TextureType
{
None,
Rgb,
Rgba,
sRgb,
sRgba,
Stencil,
Depth
};
HYPO_GRAPHICS_API uInt32 GetTexturePixelSize(TextureType type);
HYPO_GRAPHICS_API uInt32 GetTextureSize(uInt32 width, uInt32 height, TextureType type);
class TextureData
{
public:
TextureData(uInt32 width, uInt32 height, TextureType type);
TextureData(uInt32 width, uInt32 height, TextureType type, std::vector<Byte> pixels);
TextureData() = default;
TextureData(const TextureData&) = default;
uInt32 GetWidth() const { return m_Width; }
uInt32 GetHeight() const { return m_Height; }
TextureType GetType()const { return m_Type; }
uInt32 GetPixelsSize() const { return m_Pixels.size(); }
const std::vector<Byte>& GetPixels() const { return m_Pixels; }
private:
uInt32 m_Width = 0;
uInt32 m_Height = 0;
TextureType m_Type = TextureType::None;
std::vector<Byte> m_Pixels;
};
HYPO_GRAPHICS_API TextureData TextureFromFile(std::string path);
}
| {
"alphanum_fraction": 0.7324675325,
"avg_line_length": 21,
"ext": "h",
"hexsha": "62f9a1c2b44d4e42106240b7f86ec072a10c2241",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "TheodorLindberg/Hypo",
"max_forks_repo_path": "HypoGraphics/src/Hypo/Graphics/Texture/TextureAsset.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "TheodorLindberg/Hypo",
"max_issues_repo_path": "HypoGraphics/src/Hypo/Graphics/Texture/TextureAsset.h",
"max_line_length": 88,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "TheodorLindberg/Hypo",
"max_stars_repo_path": "HypoGraphics/src/Hypo/Graphics/Texture/TextureAsset.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 334,
"size": 1155
} |
//Causal FIR filtering of each vector in X along dim.
//FIR impulse response is given in vector B with length Q+1.
//(I use P for IIR filter order, since same as polynomial order.)
#include <stdio.h>
#include <math.h>
#include <cblas.h>
#ifdef __cplusplus
namespace codee {
extern "C" {
#endif
int fir_s (float *Y, const float *X, const float *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim);
int fir_d (double *Y, const double *X, const double *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim);
int fir_c (float *Y, const float *X, const float *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim);
int fir_z (double *Y, const double *X, const double *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim);
int fir_s (float *Y, const float *X, const float *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim)
{
if (dim>3u) { fprintf(stderr,"error in fir_s: dim must be in [0 3]\n"); return 1; }
const size_t N = R*C*S*H;
const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;
//Initialize Y
float b = *B++;
for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = b * *X; }
X -= N; Y -= N - 1u;
if (N==0u || L==1u || Q==0u) {}
else if (L==N)
{
if (L<30000u)
{
for (size_t q=1u; q<=Q; ++q, ++B, X-=L-q+1u, Y-=L-q)
{
b = *B;
for (size_t l=q; l<L; ++l, ++X, ++Y) { *Y = fmaf(b,*X,*Y); }
}
}
else
{
for (size_t q=1u; q<=Q; ++q, ++B, ++Y) { cblas_saxpy((int)(L-q),*B,X,1,Y,1); }
}
}
else
{
const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);
const size_t BS = (iscolmajor && dim==0u) ? C*S*H : K;
const size_t V = N/L, G = V/BS;
if (K==1u && (G==1u || BS==1u))
{
if (L<30000u)
{
for (size_t v=V; v>0u; --v, B-=Q, X+=Q, ++Y)
{
for (size_t q=1u; q<=Q; ++q, ++B)
{
b = *B;
for (size_t l=q; l<L; ++l, ++X, ++Y) { *Y = fmaf(b,*X,*Y); }
if (q<Q) { X -= L-q; Y -= L-q-1u; }
}
}
}
else
{
for (size_t v=V; v>0u; --v, B-=Q, X+=L, Y+=L-Q)
{
for (size_t q=1u; q<=Q; ++q, ++B, ++Y) { cblas_saxpy((int)(L-q),*B,X,1,Y,1); }
}
}
}
else
{
Y += K - 1u;
for (size_t g=G; g>0u; --g, X+=BS*(L-1u), Y+=BS*(L-1u))
{
for (size_t bs=BS; bs>0u; --bs, ++X, B-=Q, Y-=K*Q-1u)
{
for (size_t q=1u; q<=Q; ++q, ++B, Y+=K) { cblas_saxpy((int)(L-q),*B,X,(int)K,Y,(int)K); }
}
}
}
}
return 0;
}
int fir_d (double *Y, const double *X, const double *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim)
{
if (dim>3u) { fprintf(stderr,"error in fir_d: dim must be in [0 3]\n"); return 1; }
const size_t N = R*C*S*H;
const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;
//Initialize Y
double b = *B++;
for (size_t n=N; n>0u; --n, ++X, ++Y) { *Y = b * *X; }
X -= N; Y -= N - 1u;
if (N==0u || L==1u || Q==0u) {}
else if (L==N)
{
if (L<30000u)
{
for (size_t q=1u; q<=Q; ++q, ++B, X-=L-q+1u, Y-=L-q)
{
b = *B;
for (size_t l=q; l<L; ++l, ++X, ++Y) { *Y = fma(b,*X,*Y); }
}
}
else
{
for (size_t q=1u; q<=Q; ++q, ++B, ++Y) { cblas_daxpy((int)(L-q),*B,X,1,Y,1); }
}
}
else
{
const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);
const size_t BS = (iscolmajor && dim==0u) ? C*S*H : K;
const size_t V = N/L, G = V/BS;
if (K==1u && (G==1u || BS==1u))
{
if (L<30000u)
{
for (size_t v=V; v>0u; --v, B-=Q, X+=Q, ++Y)
{
for (size_t q=1u; q<=Q; ++q, ++B)
{
b = *B;
for (size_t l=q; l<L; ++l, ++X, ++Y) { *Y = fma(b,*X,*Y); }
if (q<Q) { X -= L-q; Y -= L-q-1u; }
}
}
}
else
{
for (size_t v=V; v>0u; --v, B-=Q, X+=L, Y+=L-Q)
{
for (size_t q=1u; q<=Q; ++q, ++B, ++Y) { cblas_daxpy((int)(L-q),*B,X,1,Y,1); }
}
}
}
else
{
Y += K - 1u;
for (size_t g=G; g>0u; --g, X+=BS*(L-1u), Y+=BS*(L-1u))
{
for (size_t bs=BS; bs>0u; --bs, ++X, B-=Q, Y-=K*Q-1u)
{
for (size_t q=1u; q<=Q; ++q, ++B, Y+=K) { cblas_daxpy((int)(L-q),*B,X,(int)K,Y,(int)K); }
}
}
}
}
return 0;
}
int fir_c (float *Y, const float *X, const float *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim)
{
if (dim>3u) { fprintf(stderr,"error in fir_c: dim must be in [0 3]\n"); return 1; }
const size_t N = R*C*S*H;
const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;
float xr, xi, br, bi;
//Initialize Y
br = *B++; bi = *B++;
for (size_t n=N; n>0u; --n)
{
xr = *X++; xi = *X++;
*Y++ = br*xr - bi*xi;
*Y++ = br*xi + bi*xr;
}
X -= 2u*N; Y -= 2u*N - 2u;
if (N==0u || L==1u || Q==0u) {}
else if (L==N)
{
if (L<30000u)
{
for (size_t q=1u; q<=Q; ++q, X-=2u*(L-q+1u), Y-=2u*(L-q))
{
br = *B++; bi = *B++;
for (size_t l=q; l<L; ++l)
{
xr = *X++; xi = *X++;
*Y++ += br*xr - bi*xi;
*Y++ += br*xi + bi*xr;
}
}
}
else
{
for (size_t q=1u; q<=Q; ++q, B+=2u, Y+=2u) { cblas_caxpy((int)(L-q),B,X,1,Y,1); }
}
}
else
{
const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);
const size_t BS = (iscolmajor && dim==0u) ? C*S*H : K;
const size_t V = N/L, G = V/BS;
if (K==1u && (G==1u || BS==1u))
{
if (L<30000u)
{
for (size_t v=V; v>0u; --v, B-=2u*Q, X+=2u*Q, Y+=2u)
{
for (size_t q=1u; q<=Q; ++q)
{
br = *B++; bi = *B++;
for (size_t l=q; l<L; ++l)
{
xr = *X++; xi = *X++;
*Y++ += br*xr - bi*xi;
*Y++ += br*xi + bi*xr;
}
if (q<Q) { X -= 2u*(L-q); Y -= 2u*(L-q-1u); }
}
}
}
else
{
for (size_t v=V; v>0u; --v, X+=2u*L, B-=2u*Q, Y+=2u*(L-Q-1u))
{
for (size_t q=0u; q<=Q; ++q, B+=2u, Y+=2u) { cblas_caxpy((int)(L-q),B,X,1,Y,1); }
}
}
}
else
{
Y += 2u*K - 2u;
for (size_t g=G; g>0u; --g, X+=2u*BS*(L-1u), Y+=2u*BS*(L-1u))
{
for (size_t bs=BS; bs>0u; --bs, X+=2u, B-=2u*Q, Y-=2u*K*Q-2u)
{
for (size_t q=1u; q<=Q; ++q, B+=2u, Y+=2u*K) { cblas_caxpy((int)(L-q),B,X,(int)K,Y,(int)K); }
}
}
}
}
return 0;
}
int fir_z (double *Y, const double *X, const double *B, const size_t R, const size_t C, const size_t S, const size_t H, const int iscolmajor, const size_t Q, const size_t dim)
{
if (dim>3u) { fprintf(stderr,"error in fir_z: dim must be in [0 3]\n"); return 1; }
const size_t N = R*C*S*H;
const size_t L = (dim==0u) ? R : (dim==1u) ? C : (dim==2u) ? S : H;
double xr, xi, br, bi;
//Initialize Y
br = *B++; bi = *B++;
for (size_t n=N; n>0u; --n)
{
xr = *X++; xi = *X++;
*Y++ = br*xr - bi*xi;
*Y++ = br*xi + bi*xr;
}
X -= 2u*N; Y -= 2u*N - 2u;
if (N==0u || L==1u || Q==0u) {}
else if (L==N)
{
if (L<30000u)
{
for (size_t q=1u; q<=Q; ++q, X-=2u*(L-q+1u), Y-=2u*(L-q))
{
br = *B++; bi = *B++;
for (size_t l=q; l<L; ++l)
{
xr = *X++; xi = *X++;
*Y++ += br*xr - bi*xi;
*Y++ += br*xi + bi*xr;
}
}
}
else
{
for (size_t q=1u; q<=Q; ++q, B+=2u, Y+=2u) { cblas_zaxpy((int)(L-q),B,X,1,Y,1); }
}
}
else
{
const size_t K = (iscolmajor) ? ((dim==0u) ? 1u : (dim==1u) ? R : (dim==2u) ? R*C : R*C*S) : ((dim==0u) ? C*S*H : (dim==1u) ? S*H : (dim==2u) ? H : 1u);
const size_t BS = (iscolmajor && dim==0u) ? C*S*H : K;
const size_t V = N/L, G = V/BS;
if (K==1u && (G==1u || BS==1u))
{
if (L<30000u)
{
for (size_t v=V; v>0u; --v, B-=2u*Q, X+=2u*Q, Y+=2u)
{
for (size_t q=1u; q<=Q; ++q)
{
br = *B++; bi = *B++;
for (size_t l=q; l<L; ++l)
{
xr = *X++; xi = *X++;
*Y++ += br*xr - bi*xi;
*Y++ += br*xi + bi*xr;
}
if (q<Q) { X -= 2u*(L-q); Y -= 2u*(L-q-1u); }
}
}
}
else
{
for (size_t v=V; v>0u; --v, X+=2u*L, B-=2u*Q, Y+=2u*(L-Q-1u))
{
for (size_t q=0u; q<=Q; ++q, B+=2u, Y+=2u) { cblas_zaxpy((int)(L-q),B,X,1,Y,1); }
}
}
}
else
{
Y += 2u*K - 2u;
for (size_t g=G; g>0u; --g, X+=2u*BS*(L-1u), Y+=2u*BS*(L-1u))
{
for (size_t bs=BS; bs>0u; --bs, X+=2u, B-=2u*Q, Y-=2u*K*Q-2u)
{
for (size_t q=1u; q<=Q; ++q, B+=2u, Y+=2u*K) { cblas_zaxpy((int)(L-q),B,X,(int)K,Y,(int)K); }
}
}
}
}
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.3652573043,
"avg_line_length": 32.5545977011,
"ext": "c",
"hexsha": "7ce699d308320e9219dd92e4ecc35104e6bb5362",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-10-05T13:50:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-10-05T13:50:32.000Z",
"max_forks_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/dsp",
"max_forks_repo_path": "c/fir.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/dsp",
"max_issues_repo_path": "c/fir.c",
"max_line_length": 176,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "28880ede8ca715c2a5a9b596742070f9bda9830e",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/dsp",
"max_stars_repo_path": "c/fir.c",
"max_stars_repo_stars_event_max_datetime": "2020-08-26T09:22:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-26T09:22:40.000Z",
"num_tokens": 4114,
"size": 11329
} |
/* matrix/gsl_matrix_double.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_DOUBLE_H__
#define __GSL_MATRIX_DOUBLE_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_double.h>
#include <gsl/gsl_blas_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size1;
size_t size2;
size_t tda;
double * data;
gsl_block * block;
int owner;
} gsl_matrix;
typedef struct
{
gsl_matrix matrix;
} _gsl_matrix_view;
typedef _gsl_matrix_view gsl_matrix_view;
typedef struct
{
gsl_matrix matrix;
} _gsl_matrix_const_view;
typedef const _gsl_matrix_const_view gsl_matrix_const_view;
/* Allocation */
gsl_matrix *
gsl_matrix_alloc (const size_t n1, const size_t n2);
gsl_matrix *
gsl_matrix_calloc (const size_t n1, const size_t n2);
gsl_matrix *
gsl_matrix_alloc_from_block (gsl_block * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
gsl_matrix *
gsl_matrix_alloc_from_matrix (gsl_matrix * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
gsl_vector *
gsl_vector_alloc_row_from_matrix (gsl_matrix * m,
const size_t i);
gsl_vector *
gsl_vector_alloc_col_from_matrix (gsl_matrix * m,
const size_t j);
void gsl_matrix_free (gsl_matrix * m);
/* Views */
_gsl_matrix_view
gsl_matrix_submatrix (gsl_matrix * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_view
gsl_matrix_row (gsl_matrix * m, const size_t i);
_gsl_vector_view
gsl_matrix_column (gsl_matrix * m, const size_t j);
_gsl_vector_view
gsl_matrix_diagonal (gsl_matrix * m);
_gsl_vector_view
gsl_matrix_subdiagonal (gsl_matrix * m, const size_t k);
_gsl_vector_view
gsl_matrix_superdiagonal (gsl_matrix * m, const size_t k);
_gsl_vector_view
gsl_matrix_subrow (gsl_matrix * m, const size_t i,
const size_t offset, const size_t n);
_gsl_vector_view
gsl_matrix_subcolumn (gsl_matrix * m, const size_t j,
const size_t offset, const size_t n);
_gsl_matrix_view
gsl_matrix_view_array (double * base,
const size_t n1,
const size_t n2);
_gsl_matrix_view
gsl_matrix_view_array_with_tda (double * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_view
gsl_matrix_view_vector (gsl_vector * v,
const size_t n1,
const size_t n2);
_gsl_matrix_view
gsl_matrix_view_vector_with_tda (gsl_vector * v,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_const_view
gsl_matrix_const_submatrix (const gsl_matrix * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_const_view
gsl_matrix_const_row (const gsl_matrix * m,
const size_t i);
_gsl_vector_const_view
gsl_matrix_const_column (const gsl_matrix * m,
const size_t j);
_gsl_vector_const_view
gsl_matrix_const_diagonal (const gsl_matrix * m);
_gsl_vector_const_view
gsl_matrix_const_subdiagonal (const gsl_matrix * m,
const size_t k);
_gsl_vector_const_view
gsl_matrix_const_superdiagonal (const gsl_matrix * m,
const size_t k);
_gsl_vector_const_view
gsl_matrix_const_subrow (const gsl_matrix * m, const size_t i,
const size_t offset, const size_t n);
_gsl_vector_const_view
gsl_matrix_const_subcolumn (const gsl_matrix * m, const size_t j,
const size_t offset, const size_t n);
_gsl_matrix_const_view
gsl_matrix_const_view_array (const double * base,
const size_t n1,
const size_t n2);
_gsl_matrix_const_view
gsl_matrix_const_view_array_with_tda (const double * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_const_view
gsl_matrix_const_view_vector (const gsl_vector * v,
const size_t n1,
const size_t n2);
_gsl_matrix_const_view
gsl_matrix_const_view_vector_with_tda (const gsl_vector * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
void gsl_matrix_set_zero (gsl_matrix * m);
void gsl_matrix_set_identity (gsl_matrix * m);
void gsl_matrix_set_all (gsl_matrix * m, double x);
int gsl_matrix_fread (FILE * stream, gsl_matrix * m) ;
int gsl_matrix_fwrite (FILE * stream, const gsl_matrix * m) ;
int gsl_matrix_fscanf (FILE * stream, gsl_matrix * m);
int gsl_matrix_fprintf (FILE * stream, const gsl_matrix * m, const char * format);
int gsl_matrix_memcpy(gsl_matrix * dest, const gsl_matrix * src);
int gsl_matrix_swap(gsl_matrix * m1, gsl_matrix * m2);
int gsl_matrix_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src);
int gsl_matrix_swap_rows(gsl_matrix * m, const size_t i, const size_t j);
int gsl_matrix_swap_columns(gsl_matrix * m, const size_t i, const size_t j);
int gsl_matrix_swap_rowcol(gsl_matrix * m, const size_t i, const size_t j);
int gsl_matrix_transpose (gsl_matrix * m);
int gsl_matrix_transpose_memcpy (gsl_matrix * dest, const gsl_matrix * src);
int gsl_matrix_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src);
double gsl_matrix_max (const gsl_matrix * m);
double gsl_matrix_min (const gsl_matrix * m);
void gsl_matrix_minmax (const gsl_matrix * m, double * min_out, double * max_out);
void gsl_matrix_max_index (const gsl_matrix * m, size_t * imax, size_t *jmax);
void gsl_matrix_min_index (const gsl_matrix * m, size_t * imin, size_t *jmin);
void gsl_matrix_minmax_index (const gsl_matrix * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
int gsl_matrix_equal (const gsl_matrix * a, const gsl_matrix * b);
int gsl_matrix_isnull (const gsl_matrix * m);
int gsl_matrix_ispos (const gsl_matrix * m);
int gsl_matrix_isneg (const gsl_matrix * m);
int gsl_matrix_isnonneg (const gsl_matrix * m);
double gsl_matrix_norm1 (const gsl_matrix * m);
int gsl_matrix_add (gsl_matrix * a, const gsl_matrix * b);
int gsl_matrix_sub (gsl_matrix * a, const gsl_matrix * b);
int gsl_matrix_mul_elements (gsl_matrix * a, const gsl_matrix * b);
int gsl_matrix_div_elements (gsl_matrix * a, const gsl_matrix * b);
int gsl_matrix_scale (gsl_matrix * a, const double x);
int gsl_matrix_scale_rows (gsl_matrix * a, const gsl_vector * x);
int gsl_matrix_scale_columns (gsl_matrix * a, const gsl_vector * x);
int gsl_matrix_add_constant (gsl_matrix * a, const double x);
int gsl_matrix_add_diagonal (gsl_matrix * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
int gsl_matrix_get_row(gsl_vector * v, const gsl_matrix * m, const size_t i);
int gsl_matrix_get_col(gsl_vector * v, const gsl_matrix * m, const size_t j);
int gsl_matrix_set_row(gsl_matrix * m, const size_t i, const gsl_vector * v);
int gsl_matrix_set_col(gsl_matrix * m, const size_t j, const gsl_vector * v);
/***********************************************************************/
/* inline functions if you are using GCC */
INLINE_DECL double gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j);
INLINE_DECL void gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x);
INLINE_DECL double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j);
INLINE_DECL const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
double
gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
}
#endif
return m->data[i * m->tda + j] ;
}
INLINE_FUN
void
gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
}
#endif
m->data[i * m->tda + j] = x ;
}
INLINE_FUN
double *
gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (double *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
const double *
gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (const double *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_DOUBLE_H__ */
| {
"alphanum_fraction": 0.625399568,
"avg_line_length": 32.3324022346,
"ext": "h",
"hexsha": "c54fa59f11e354878d16cb3d30298a9ae5adedb7",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/matrix/gsl_matrix_double.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/matrix/gsl_matrix_double.h",
"max_line_length": 118,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/matrix/gsl_matrix_double.h",
"max_stars_repo_stars_event_max_datetime": "2021-06-14T11:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-14T11:51:37.000Z",
"num_tokens": 2835,
"size": 11575
} |
//
// Created by peixinho on 19/12/16.
//
#include <ml_matrix.h>
#include <cblas.h>
#include <ml_memory.h>
MlMatrix* ml_create_matrix(size_t nrow, size_t ncol) {
MlMatrix* m = NULL;
m = ml_alloc(MlMatrix);
m->nrows = nrow;
m->ncols = ncol;
m->n = nrow*ncol;
m->data = ml_alloc_array(m->n, float);
return m;
}
void mlMultMatrixIp(MlMatrix* A, MlMatrix* B, MlMatrix* M) {
double alpha = 1.0, beta = 0.0;
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, A->nrows, B->ncols, \
A->ncols, alpha, A->data, A->ncols, B->data, B->ncols, beta, \
M->data, B->ncols);
}
MlMatrix* mlMultMatrix(MlMatrix* A, MlMatrix* B) {
MlMatrix* M = ml_create_matrix(B->ncols, A->nrows);
mlMultMatrixIp(A, B, M);
return M;
}
float mlMeanMatrix(MlMatrix* m) {
float mean = 0.0f;
for (int i = 0; i < m->n; ++i) {
mean += m->data[i] / m->n;
}
return mean;
}
MlMatrix* mlMatrixSumCol(MlMatrix* m) {
MlMatrix* sum = ml_create_matrix(1, m->ncols);
for (int i = 0; i < m->nrows; ++i) {
for (int j = 0; j < m->ncols; ++j) {
ml_mat_elem(sum, 0, j) += ml_mat_elem(m, i, j);
}
}
return sum;
}
void ml_set_matrix(MlMatrix *m, float val) {
for (int i = 0; i < m->n; ++i)
m->data[i] = val;
}
void ml_free_matrix(MlMatrix *m) {
ml_free(m->data);
ml_free(m);
}
void ml_print_matrix(MlMatrix *m) {
printf("[");
for (int r = 0; r < m->nrows; ++r) {
printf("[");
for (int c = 0; c < m->ncols; ++c) {
printf("%4.2f", ml_mat_elem(m, r, c));
if(c < m->ncols-1)
printf(", ");
}
printf("]");
if(r<m->nrows-1)
printf("\n");
}
printf("]\n");
}
| {
"alphanum_fraction": 0.5262860373,
"avg_line_length": 22.6794871795,
"ext": "c",
"hexsha": "6fa07ba471da7eabc68399dfe8c0c726d31a6530",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "fa67a743a74c3e4f9922d12daf3c5e9d4a4351d4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alanpeixinho/lib-machine-learning",
"max_forks_repo_path": "src/ml_matrix.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fa67a743a74c3e4f9922d12daf3c5e9d4a4351d4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "alanpeixinho/lib-machine-learning",
"max_issues_repo_path": "src/ml_matrix.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "fa67a743a74c3e4f9922d12daf3c5e9d4a4351d4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alanpeixinho/lib-machine-learning",
"max_stars_repo_path": "src/ml_matrix.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 636,
"size": 1769
} |
//
// Created by david on 2018-11-30.
//
#ifndef DMRG_CLASS_XDMRG_FULL_FUNCTOR_H
#define DMRG_CLASS_XDMRG_FULL_FUNCTOR_H
#ifdef OpenMP_AVAILABLE
#include <omp.h>
#endif
#ifdef OpenBLAS_AVAILABLE
#include <cblas.h>
#endif
#include <Eigen/Core>
#include <unsupported/Eigen/CXX11/Tensor>
#include <general/nmspc_tensor_extra.h>
#include <general/class_tic_toc.h>
template<typename Scalar>
class class_xDMRG_full_functor {
private:
double variance;
double energy ;
double energy_lower_bound;
double energy_upper_bound;
double energy_target;
double energy_window;
public:
template <typename T>
int sgn(const T val) const {
return (T(0) < val) - (val < T(0));
}
using MatrixType_ = Eigen::Matrix<Scalar,Eigen::Dynamic, Eigen::Dynamic>;
using VectorType_ = Eigen::Matrix<Scalar,Eigen::Dynamic, 1>;
size_t counter = 0;
// const size_t shape;
void set_energy_bounds(double E_lower, double E_upper);
bool have_bounds_on_energy = false;
double get_variance(){return variance;}
double get_energy (){return energy ;}
size_t get_count (){return counter;}
Eigen::Tensor<double,4> HA_MPO;
Eigen::Tensor<double,4> HB_MPO;
Eigen::Tensor<double,3> Lblock;
Eigen::Tensor<double,3> Rblock;
Eigen::Tensor<double,4> Lblock2;
Eigen::Tensor<double,4> Rblock2;
Eigen::Tensor<double,6> HAHB;
Eigen::Tensor<double,8> HAHB2;
Eigen::DSizes<long,4> dsizes;
class_tic_toc t_lbfgs;
class_xDMRG_full_functor(
const Eigen::Tensor<Scalar,4> &HA_MPO_,
const Eigen::Tensor<Scalar,4> &HB_MPO_,
const Eigen::Tensor<Scalar,3> &Lblock_,
const Eigen::Tensor<Scalar,3> &Rblock_,
const Eigen::Tensor<Scalar,4> &Lblock2_,
const Eigen::Tensor<Scalar,4> &Rblock2_,
const Eigen::DSizes<long,4> &dsizes_
);
double get_vH2v(const Eigen::Matrix<double,Eigen::Dynamic,1> &v);
double get_vHv(const Eigen::Matrix<double,Eigen::Dynamic,1> &v);
Eigen::VectorXd get_vH2 (const Eigen::Matrix<double,Eigen::Dynamic,1> &v);
Eigen::VectorXd get_vH (const Eigen::Matrix<double,Eigen::Dynamic,1> &v);
double operator()(const Eigen::Matrix<double,Eigen::Dynamic,1> &v, Eigen::Matrix<double,Eigen::Dynamic,1> &grad);
};
#endif //DMRG_CLASS_XDMRG_FULL_FUNCTOR_H
| {
"alphanum_fraction": 0.6840764331,
"avg_line_length": 31.4,
"ext": "h",
"hexsha": "16571e13515675e2d9623457c78d9850bcc50210",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-07-16T00:27:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-07-16T00:27:56.000Z",
"max_forks_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "DavidAce/DMRG",
"max_forks_repo_path": "unused/class_xDMRG_full_functor.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "DavidAce/DMRG",
"max_issues_repo_path": "unused/class_xDMRG_full_functor.h",
"max_line_length": 117,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "e465fd903eade1bf6aa74daacd8e2cf02e9e9332",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "DavidAce/DMRG",
"max_stars_repo_path": "unused/class_xDMRG_full_functor.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-10T15:45:27.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-10-31T22:50:28.000Z",
"num_tokens": 655,
"size": 2355
} |
#pragma once
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_math.h>
#include "../Scanner/scanner.h"
#include "../Utils/Types.h"
class Expression;
typedef std::shared_ptr<Expression> expression;
typedef std::map<std::string, expression> Variables;
extern const Variables emptyVars;
typedef expression(*TransformerFunction)(expression);
class Expression: public std::enable_shared_from_this<Expression> {
public:
const Scanner::Type kind;
Expression(Scanner::Type kind);
virtual ~Expression();
virtual expression simplify();
virtual expression derivative(const std::string& var);
virtual expression integrate(const std::string& var);
virtual bool isComplex() const = 0;
virtual bool isEvaluable(const Variables& vars = emptyVars) const = 0;
virtual bool isNumber() const { return false; }
virtual expression eval(const Variables& vars = emptyVars) = 0;
virtual double value(const Variables& vars = emptyVars) const = 0;
virtual gsl_complex complex(const Variables& vars = emptyVars) const;
virtual bool equals(expression, double precision=1e-15) const = 0;
std::vector<double> array();
virtual expression at(const int index);
virtual double get(const int index);
virtual size_t shape(const int axis) const;
virtual size_t size() const;
virtual expression call(expression e);
inline expression operator()(expression e){ return call(e); }
virtual expression apply(TransformerFunction f);
inline expression operator()(TransformerFunction f){ return apply(f); }
inline bool is(Scanner::Type kind) const { return this->kind == kind; }
virtual std::string repr() const;
virtual int id() const;
expression copy();
virtual std::ostream& print(std::ostream&, const bool pretty=false) const = 0;
virtual std::ostream& postfix(std::ostream&) const = 0;
private:
struct gsl_expression_struct {
Expression* e;
const std::string var;
Variables vars;
gsl_expression_struct(Expression*, const std::string var = "x");
};
static double gsl_expression_function(double x, void* p);
std::unique_ptr<gsl_expression_struct> gsl_params;
public:
virtual gsl_function function(const std::string& var = "x");
private:
struct ExpressionIterator {
expression e;
size_t index;
ExpressionIterator(expression e, size_t index);
expression operator*();
bool operator==(const ExpressionIterator& other) const;
bool operator!=(const ExpressionIterator& other) const;
bool operator<(const ExpressionIterator& other) const;
bool operator<=(const ExpressionIterator& other) const;
bool operator>(const ExpressionIterator& other) const;
bool operator>=(const ExpressionIterator& other) const;
ExpressionIterator& operator++();
ExpressionIterator& operator--();
};
public:
ExpressionIterator begin();
ExpressionIterator end();
};
std::ostream& operator<<(std::ostream&, const expression);
#define EXPRESSION_PARTIAL_OVERRIDES \
bool isComplex() const override; \
bool isEvaluable(const Variables& vars = emptyVars) const override; \
bool equals(expression, double precision) const override; \
std::ostream& print(std::ostream&, const bool pretty = false) const override; \
std::ostream& postfix(std::ostream&) const override;
#define EXPRESSION_OVERRIDES \
EXPRESSION_PARTIAL_OVERRIDES \
expression eval(const Variables& vars = emptyVars) override; \
double value(const Variables& vars = emptyVars) const override;
| {
"alphanum_fraction": 0.6240745164,
"avg_line_length": 35.4830508475,
"ext": "h",
"hexsha": "dc8d7c71188f3ffe49006af78efdc0074d70d08e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "antoniojkim/CalcPlusPlus",
"max_forks_repo_path": "MathEngine/Expressions/Expression.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "antoniojkim/CalcPlusPlus",
"max_issues_repo_path": "MathEngine/Expressions/Expression.h",
"max_line_length": 86,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "33cede17001e0a7038f99ea40dd6f9e433cf6454",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "antoniojkim/CalcPlusPlus",
"max_stars_repo_path": "MathEngine/Expressions/Expression.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 794,
"size": 4187
} |
#pragma once
#include <Hypo/System/Exports.h>
#include <Hypo/Config.h>
#include <ostream>
#include <gsl/span>
#include <Hypo/System/Exports.h>
#include <Hypo/System/Buffer/Buffer.h>
#include <Hypo/System/Streams/MemoryStream.h>
namespace Hypo
{
class HYPO_SYSTEM_API BinaryWriter
{
public:
BinaryWriter(std::ostream& stream);
BinaryWriter& operator <<(uInt8 value);
BinaryWriter& operator <<(uInt16 value);
BinaryWriter& operator <<(uInt32 value);
BinaryWriter& operator <<(uInt64 value);
BinaryWriter& operator <<(Int8 value);
BinaryWriter& operator <<(Int16 value);
BinaryWriter& operator <<(Int32 value);
BinaryWriter& operator <<(Int64 value);
BinaryWriter& operator <<(const std::string& value);
BinaryWriter& operator <<(const char* value);
template<typename T>
BinaryWriter& operator <<(const std::vector<T>& value)
{
const uInt32 size(static_cast<uInt32>(value.size()));
*this << size;
for (auto& element : value)
{
*this << element;
}
return *this;
}
void WriteRaw(const std::string& data);
void WriteRaw(const gsl::span<uInt8>& data);
void WriteRaw(const void* data, int size);
void WriteBOM();
void Write7BitEncoded(uInt32 value);
void Write7BitEncoded(uInt64 value);
void Flush()const { m_Stream.flush(); }
bool Good()const { return m_Stream.good(); }
bool Bad()const { return m_Stream.bad(); }
bool Fail() const { return m_Stream.fail(); }
std::ostream& GetStream() const {return m_Stream;}
private:
std::ostream& m_Stream;
};
template <typename T>
class BasicMemoryBinaryWriter : public BinaryWriter
/// A convenient wrapper for using Buffer and MemoryStream with BinarWriter.
{
public:
BasicMemoryBinaryWriter(Buffer<T>& data) :
BinaryWriter(_ostr),
_data(data),
_ostr(data.begin(), data.Capacity())
{
}
~BasicMemoryBinaryWriter()
{
try
{
Flush();
}
catch (...)
{
}
}
Buffer<T>& data()
{
return _data;
}
const Buffer<T>& data() const
{
return _data;
}
const MemoryOutputStream& stream() const
{
return _ostr;
}
MemoryOutputStream& stream()
{
return _ostr;
}
private:
Buffer<T>& _data;
MemoryOutputStream _ostr;
};
typedef BasicMemoryBinaryWriter<char> MemoryBinaryWriter;
}
| {
"alphanum_fraction": 0.6742358079,
"avg_line_length": 19.9130434783,
"ext": "h",
"hexsha": "2b68a678e97bcd2da4ced438e369303d2382124f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "TheodorLindberg/Hypo",
"max_forks_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryWriter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "TheodorLindberg/Hypo",
"max_issues_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryWriter.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "67107bf14671711ab5979e2af8c7ead6ee043805",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "TheodorLindberg/Hypo",
"max_stars_repo_path": "HypoSystem/src/Hypo/System/Streams/BinaryWriter.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 656,
"size": 2290
} |
/************************************************************************
Tuple.h.h - Copyright marcello
Here you can write a license for your code, some comments or any other
information you want to have in your generated code. To to this simply
configure the "headings" directory in uml to point to a directory
where you have your heading files.
or you can just replace the contents of this file with your own.
If you want to do this, this file is located at
/usr/share/apps/umbrello/headings/heading.h
-->Code Generators searches for heading files based on the file extension
i.e. it will look for a file name ending in ".h" to include in C++ header
files, and for a file name ending in ".java" to include in all generated
java code.
If you name the file "heading.<extension>", Code Generator will always
choose this file even if there are other files with the same extension in the
directory. If you name the file something else, it must be the only one with that
extension in the directory to guarantee that Code Generator will choose it.
you can use variables in your heading files which are replaced at generation
time. possible variables are : author, date, time, filename and filepath.
just write %variable_name%
This file was generated on Sat Nov 10 2007 at 15:05:38
The original location of this file is /home/marcello/Projects/fitted/Developing/Tuple.h
**************************************************************************/
#ifndef TUPLE_H
#define TUPLE_H
#include <fstream>
#include <vector>
//#include <gsl/gsl_vector.h>
//<< Sam
typedef enum
{
L1,
L2,
Linfty
} NormType;
using namespace std;
namespace PoliFitted
{
/**
* Tuples are sequence containers representing arrays with additional functionalities.
*
* Just like arrays, tuples use contiguous storage locations for their elements, which
* means that their elements can also be accessed using offsets on regular pointers to its elements,
* and just as efficiently as in arrays.
*
* Like arrays, internally, tuples do not store information about the dimension that must be handled
* manually from outside the class.
*/
class Tuple
{
public:
/**
* Converts N vectors to a single tuple obtained by
* concatenation of the vectors (double) in the given order
* Vectors are received as sequence of const_iterator:
* v1.begin, v1.end, v2.begin, v2.end, v3.begin ...
*
* @param count final number of elements of the tuple.
Sum of size of each vector
* @param ... sequence of const_iterator (begin,end,begin,end,...)
* @return the reference of the new tuple
*/
//static Tuple* CONVERT(unsigned int count, ...);
// Constructors/Destructors
//
/**
* Empty Constructor
*/
Tuple();
/**
* Construct a tuple of specified size
* @param size the size of the tuple
*/
Tuple(unsigned int size);
/**
* Empty Destructor
*/
~Tuple();
/**
* Returns a reference to the element at position \f$pos\f$ in the tuple.
*
* Programs should never call this function with an argument \f$pos\f$ that is
* out of range, since this causes undefined behavior.
* @brief Access element
* @param pos Position of an element in the container. Notice that the first element has a position of 0 (not 1).
* @return The element at the specified position in the tuple.
*/
float& operator[](const unsigned int pos);
/**
* Returns a reference to the element at position \f$pos\f$ in the tuple.
*
* The function does not automatically check whether \f$pos\f$ is within the
* bounds of valid elements in the vector.
* Programs should never call this function with an argument \f$pos\f$ that is
* out of range, since this causes undefined behavior.
*
* @brief Access element
* @param pos Position of an element in the container. Notice that the first element has a position of 0 (not 1).
* @return The element at the specified position in the container.
*/
float& at(const unsigned int pos);
/**
* Compute a distance between the current and a given tuple. In other words,
* it computes the p-norm between tuples.
* \a p must be one of: "L1", "L2", "Linfty". "L1" is the absolute distance,
* "L2" is the Euclidean distance, and "Linfty" is the maximum norm.
* The norm is computed taking into account the first \a size elements of
* the current and given tuples.
*
* Programs should never call this function with an argument \f$size\f$ that is
* out of range for one of the two tuples, since this causes undefined behavior.
*
* @brief Distance computation
* @param t An other tuple.
* @param size the number of elements to be considered.
* @param type the norm type
* @return the \a p-norm
*/
float Distance(Tuple* t, unsigned int size, NormType type = L2);
/**
* Assigns new contents to the tuple, replacing its current contents, without modifying its size.
*
* Since the dimension of the tuple is not changed accordingly to the given array,
* the behavior is undefined when \a size is greater than the current tuple dimension.
* In this case it is necessary to call the complementary function Tuple::Resize.
*
* The tuple is filled starting from the first elements.
*
* @brief Assign elements
* @param values Array storing the new elements.
* @param size The size of the given array
*/
void SetValues(float* values, unsigned int size);
/**
* Returns a direct pointer to the memory array used internally by the tuple to store its owned elements.
*
* Because elements in the tuple are guaranteed to be stored in contiguous storage locations in the same
* order as represented by the tuple, the pointer retrieved can be offset to access any element in the array.
* @brief Access data
* @return A pointer to the first element in the array used internally by the tuple.
*/
float* GetValues();
/**
* Returns a clone of the tuple by copying the first \a input_size elements.
*
* @brief Clone object
* @param input_size the number of elements to be copied
* @return A pointer to the new tuple.
*/
Tuple* Clone(unsigned int input_size);
/**
* Resizes the container so that it contains \a new_size elements.
*
* If \a new_size is smaller than the current container size, the content is reduced to its first n elements,
* removing those beyond (and destroying them).
* If \a new_size is greater than the current container size, the content is expanded by inserting at the end
* as many elements as needed to reach a size of \a new_size.
* The value of the newly allocated portion is indeterminate.
*
* Notice that this function changes the actual content of the container by inserting or erasing elements
* from it.
*
* @brief Change size
* @param new_size New container size, expressed in number of elements.
*/
void Resize(unsigned int new_size);
template<class T>
T* GetValues(unsigned int input_size);
//gsl_vector* GetGSLVector(unsigned int input_size);
std::vector<double> ToVector(unsigned int input_size);
protected:
private:
float* mValues;
};
inline float& Tuple::at(const unsigned int pos)
{
return mValues[pos];
}
inline float& Tuple::operator[](const unsigned int pos)
{
return mValues[pos];
}
inline void Tuple::SetValues(float* values, unsigned int size)
{
for (unsigned int i = 0; i < size; i++)
{
mValues[i] = values[i];
}
}
inline float* Tuple::GetValues()
{
return mValues;
}
template<class T>
inline T* Tuple::GetValues(unsigned int input_size)
{
T* values = new T[input_size];
for (unsigned int i = 0; i < input_size; i++)
{
values[i] = (T) mValues[i];
}
return values;
}
/*inline gsl_vector* Tuple::GetGSLVector(unsigned int input_size)
{
gsl_vector* values = gsl_vector_alloc(input_size);
for (unsigned int i = 0; i < input_size; i++)
{
gsl_vector_set(values, i, mValues[i]);
}
return values;
}*/
inline std::vector<double> Tuple::ToVector(unsigned int input_size)
{
std::vector<double> values;
for (unsigned int i = 0; i < input_size; i++)
{
values.push_back(mValues[i]);
}
return values;
}
}
#endif // TUPLE_H
| {
"alphanum_fraction": 0.6733632711,
"avg_line_length": 32.053030303,
"ext": "h",
"hexsha": "d4f014027a4b32d2c226a90f4313284eb91e1407",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "akangasr/sdirl",
"max_forks_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Tuple.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "akangasr/sdirl",
"max_issues_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Tuple.h",
"max_line_length": 117,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b8b2bf34fea1b1f0c2f9961a9ad9c1ad34396f5b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "akangasr/sdirl",
"max_stars_repo_path": "cpp_models/libsrc/RLLib/util/TreeFitted/Tuple.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1963,
"size": 8462
} |
#pragma once
#include "nkg_point.h"
#include "nkg_rect.h"
#include "nk_essential.h"
#include "utility/types.h"
#include "utility/c++std/string_view.h"
#include <nuklear.h>
#include <gsl/gsl>
namespace cws80 {
// drawing
void im_draw_point(nk_command_buffer *out, f32 x, f32 y, nk_color color);
void im_fill_polygon(nk_command_buffer *out, gsl::span<const im_pointf> points, nk_color color);
void im_draw_image(nk_command_buffer *out, im_rectf rect, const im_texture &tex,
nk_color color);
void im_draw_tiled_image(nk_command_buffer *out, im_rectf rect,
const im_texture &tex, nk_color color);
void im_draw_title_box(nk_context *ctx, im_rectf bounds, cxx::string_view title,
im_rectf *content_bounds = nullptr);
void im_draw_title_box_alt(nk_context *ctx, im_rectf bounds, cxx::string_view title);
void im_draw_led_screen(nk_context *ctx, im_rectf bounds, cxx::string_view text,
im_pointf textoff);
// drawing in screen coordinates
void ims_stroke_line(nk_context *ctx, f32 x0, f32 y0, f32 x1, f32 y1,
f32 line_thickness, nk_color color);
void ims_stroke_rect(nk_context *ctx, im_rectf rect, f32 rounding,
f32 line_thickness, nk_color color);
void ims_fill_rect(nk_context *ctx, im_rectf rect, f32 rounding, nk_color color);
void ims_fill_polygon(nk_context *ctx, gsl::span<const im_pointf> points, nk_color color);
void ims_draw_image(nk_context *ctx, im_rectf rect, const im_texture &tex, nk_color color);
void ims_draw_tiled_image(nk_context *ctx, im_rectf rect, const im_texture &tex,
nk_color color);
void ims_draw_text(nk_context *ctx, im_rectf rect, const char *text, int len,
const nk_user_font *fnt, nk_color bg, nk_color fg);
void ims_push_scissor(nk_context *ctx, im_rectf rect);
//
void ims_draw_title_box(nk_context *ctx, im_rectf bounds, cxx::string_view title,
im_rectf *content_bounds = nullptr);
void ims_draw_title_box_alt(nk_context *ctx, im_rectf bounds, cxx::string_view title);
void ims_draw_led_screen(nk_context *ctx, im_rectf bounds,
cxx::string_view text, im_pointf textoff);
// text
f32 im_text_width(const nk_user_font *fnt, cxx::string_view text);
} // namespace cws80
| {
"alphanum_fraction": 0.7175965665,
"avg_line_length": 47.5510204082,
"ext": "h",
"hexsha": "2ec8cfcc17b37c699962f0082b656758d5fff1d2",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "jpcima/cws80",
"max_forks_repo_path": "sources/ui/detail/nk_draw.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "jpcima/cws80",
"max_issues_repo_path": "sources/ui/detail/nk_draw.h",
"max_line_length": 96,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "jpcima/cws80",
"max_stars_repo_path": "sources/ui/detail/nk_draw.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-03T04:21:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-20T19:27:09.000Z",
"num_tokens": 605,
"size": 2330
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <complex.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#define _USE_MATH_DEFINES
// global variables
int n = 10;
double incident(double x);
double green_function(double r1[n][3], double r2[n][3]);
int main()
{
int i, j, k;
double x, y, z;
double scatterers[n][3];
gsl_matrix * mmat = gsl_matrix_alloc (n,n);
srand((unsigned)time(NULL));
for (i = 1; i < n; i++)
{
x = 20*(double)rand()/RAND_MAX;
y = 50*(double)rand()/RAND_MAX;
z = 30*(double)rand()/RAND_MAX;
scatterers[i][0] = x;
scatterers[i][1] = y;
scatterers[i][2] = z;
printf("Scatterer %d position: %lf %lf %lf \n", i, scatterers[i][0], scatterers[i][1], scatterers[i][2]);
//double field_scatterer = incident(scatterers[i][0]);
//printf("Incident field at scatterer %d: %lf\n", i, field_scatterer);
// fixed below
double field_scatterer = incident(scatterers[i][0]);
// solving the matrix equation
gsl_matrix_set (mmat, i,i, field_scatterer);
// continue rewriting this part
// gsl_vector_view b
// = gsl_vector_view_array (field_scatterer, n);
// gsl vector set instead
// gsl_vector *total_field = gsl_vector_alloc (n);
}
double green = green_function(scatterers, scatterers);
int s;
//gsl_permutation * p = gsl_permutation_alloc (n);
//gsl_linalg_LU_decomp (&green.matrix, p, &s);
//gsl_linalg_LU_solve (&green.matrix, p, &b.vector, total_field);
//printf("Total field = \n");
//gsl_vector_fprintf (stdout, total_field, "%g");
//gsl_permutation_free (p);
// defining surface of sphere
double phi[150];
double theta[150];
int r = 500;
for (i=(M_PI-2); i < (M_PI+2); i++)
{
phi[i] =(double)(i)/((M_PI-2) - (M_PI+2));
}
for (i=(M_PI/2 - 2); i < (M_PI/2 +2); i++)
{
theta[i] = (double)(i)/((M_PI/2 - 2) - (M_PI/2 +2));
}
return 0;
}
double incident(double x)
{
double E_0 = 1.0;
return E_0*cexp(1*I*2*M_PI*x);
}
double green_function(double r1[n][3], double r2[n][3])
{
int i, j;
gsl_matrix * m = gsl_matrix_alloc (n,n);
double r[n], g[n];
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
r[n] = sqrt((r1[i][1]-r2[j][1])*(r1[i][1]-r2[j][1]) + (r1[i][2]-r2[j][2])*(r1[i][2]-r2[j][2]) + (r1[i][3] - r2[j][3])*(r1[i][3] - r2[j][3]));
if (r[n] == 0.0)
{
g[n] = 1.0;
}
else
{
g[n] = exp(1*I*2*M_PI*r[n])/(4*M_PI*r[n]);
}
gsl_matrix_set (m, i, j, g[n]);
}
}
for (i = 0; i < 100; i++)
{
for (j = 0; j < n; j++)
{
printf ("m(%d,%d) = %g\n", i, j,
gsl_matrix_get (m, i, j));
}
}
gsl_matrix_free (m);
}
| {
"alphanum_fraction": 0.5841281953,
"avg_line_length": 20.3178294574,
"ext": "c",
"hexsha": "2d0cb023b56d803ecc42b9ce3a378a2683c0212c",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "e058aefe639baf7ab8721707b94c7204b38d7462",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alula-borealis/gravitational_waves",
"max_forks_repo_path": "c_rewrite.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e058aefe639baf7ab8721707b94c7204b38d7462",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "alula-borealis/gravitational_waves",
"max_issues_repo_path": "c_rewrite.c",
"max_line_length": 144,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e058aefe639baf7ab8721707b94c7204b38d7462",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alula-borealis/gravitational_waves",
"max_stars_repo_path": "c_rewrite.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-25T12:45:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-25T12:45:47.000Z",
"num_tokens": 997,
"size": 2621
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** This file forms part of the Underworld geophysics modelling application. **
** **
** For full license and copyright information, please refer to the LICENSE.md file **
** located at the project root, or contact the authors. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <mpi.h>
#include <petsc.h>
#include <petscvec.h>
#include <petscmat.h>
#include <petscksp.h>
#include <petscpc.h>
#include <petscsnes.h>
#include <petscversion.h>
#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )
#if (PETSC_VERSION_MINOR >=6)
#include "petsc/private/kspimpl.h"
#else
#include "petsc-private/kspimpl.h" /*I "petscksp.h" I*/
#endif
#else
#include "private/kspimpl.h" /*I "petscksp.h" I*/
#endif
#include <StGermain/libStGermain/src/StGermain.h>
#include <StgDomain/libStgDomain/src/StgDomain.h>
#include <StgFEM/libStgFEM/src/StgFEM.h>
#include <PICellerator/libPICellerator/src/PICellerator.h>
#include <Underworld/libUnderworld/src/Underworld.h>
#include "Solvers/KSPSolvers/src/KSPSolvers.h"
#include "BSSCR/petsccompat.h"
#include "Test/TestKSP.h"
#include "BSSCR/BSSCR.h"
/************************************************************************/
/*** This function is called from _StokesBlockKSPInterface_Initialise **************/
/************************************************************************/
#undef __FUNCT__
#define __FUNCT__ "KSPRegisterAllKSP"
PetscErrorCode KSPRegisterAllKSP(const char path[])
{
PetscFunctionBegin;
KSPRegisterTEST(path);/* not sure if the path matters much here. everything still worked even though I had it wrong */
KSPRegisterBSSCR (path);
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.5208913649,
"avg_line_length": 37.7894736842,
"ext": "c",
"hexsha": "556a6ac4e467dc1e0ba6fada70735e7a4e9f0733",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "rbeucher/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/ksp-register.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "rbeucher/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/ksp-register.c",
"max_line_length": 122,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "rbeucher/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/ksp-register.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 622,
"size": 2154
} |
// SPDX-License-Identifier: MIT
// The MIT License (MIT)
//
// Copyright (c) 2014-2018, Institute for Software & Systems Engineering
// Copyright (c) 2018-2019, Johannes Leupolz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef PEMC_LMC_LMC_H_
#define PEMC_LMC_LMC_H_
#include <atomic>
#include <functional>
#include <gsl/span>
#include <string>
#include <vector>
#include "pemc/basic/dll_defines.h"
#include "pemc/basic/label.h"
#include "pemc/basic/model_capacity.h"
#include "pemc/basic/probability.h"
#include "pemc/basic/tsc_index.h"
#include "pemc/formula/formula.h"
namespace pemc {
struct LmcStateEntry {
TransitionIndex from;
int32_t elements;
};
// Transition = Target + Probability
struct LmcTransitionEntry {
Probability probability;
Label label;
StateIndex state;
LmcTransitionEntry() = default;
LmcTransitionEntry(Probability _probability, Label _label, StateIndex _state)
: probability(_probability), label(_label), state(_state) {}
};
class Lmc {
private:
TransitionIndex maxNumberOfTransitions = 0;
std::atomic<TransitionIndex> transitionCount{0};
std::vector<LmcTransitionEntry> transitions;
TransitionIndex initialTransitionFrom =
-1; // is uninitialized at first, but may be something else than 0
int32_t initialTransitionElements = 0;
StateIndex maxNumberOfStates = 0;
StateIndex stateCount = 0;
std::vector<LmcStateEntry> states;
std::vector<std::string> labelIdentifier;
TransitionIndex getPlaceForNewTransitionEntries(NoOfElements number);
public:
Lmc();
gsl::span<LmcStateEntry> getStates();
gsl::span<std::string> getLabelIdentifier();
void setLabelIdentifier(const std::vector<std::string>& _labelIdentifier);
std::function<bool(TransitionIndex)> createLabelBasedFormulaEvaluator(
Formula* formula);
gsl::span<LmcTransitionEntry> getTransitions();
gsl::span<LmcTransitionEntry> getInitialTransitions();
std::tuple<TransitionIndex, TransitionIndex> getInitialTransitionIndexes();
gsl::span<LmcTransitionEntry> getTransitionsOfState(StateIndex state);
std::tuple<TransitionIndex, TransitionIndex> getTransitionIndexesOfState(
StateIndex state);
TransitionIndex getPlaceForNewTransitionEntriesOfState(StateIndex stateIndex,
NoOfElements number);
TransitionIndex getPlaceForNewInitialTransitionEntries(NoOfElements number);
void setLmcTransitionEntry(TransitionIndex index,
const LmcTransitionEntry& entry);
void createStutteringState(StateIndex stutteringStateIndex);
void initialize(ModelCapacity& modelCapacity);
void finishCreation(StateIndex _stateCount);
void validate();
};
} // namespace pemc
#endif // PEMC_LMC_LMC_H_
| {
"alphanum_fraction": 0.7574636724,
"avg_line_length": 35.0462962963,
"ext": "h",
"hexsha": "f3af5af517751760124b35f66a03fd7f0e4800d8",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "joleuger/pemc",
"max_forks_repo_path": "pemc/lmc/lmc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "joleuger/pemc",
"max_issues_repo_path": "pemc/lmc/lmc.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "joleuger/pemc",
"max_stars_repo_path": "pemc/lmc/lmc.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 869,
"size": 3785
} |
/*
* Copyright (c) 1997-1999 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/* This file was automatically generated --- DO NOT EDIT */
/* Generated on Mon Mar 8 17:46:56 EST 1999 */
#include <fftw-int.h>
#include <fftw.h>
/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -twiddleinv 32 */
/*
* This function contains 434 FP additions, 208 FP multiplications,
* (or, 340 additions, 114 multiplications, 94 fused multiply/add),
* 90 stack variables, and 128 memory accesses
*/
static const fftw_real K555570233 = FFTW_KONST(+0.555570233019602224742830813948532874374937191);
static const fftw_real K831469612 = FFTW_KONST(+0.831469612302545237078788377617905756738560812);
static const fftw_real K980785280 = FFTW_KONST(+0.980785280403230449126182236134239036973933731);
static const fftw_real K195090322 = FFTW_KONST(+0.195090322016128267848284868477022240927691618);
static const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626);
static const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562);
static const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938);
/*
* Generator Id's :
* $Id: exprdag.ml,v 1.36 1999/02/19 17:22:11 athena Exp $
* $Id: fft.ml,v 1.41 1999/02/19 17:22:13 athena Exp $
* $Id: to_c.ml,v 1.24 1999/02/19 17:22:17 athena Exp $
*/
void fftwi_twiddle_32(fftw_complex *A, const fftw_complex *W, int iostride, int m, int dist)
{
int i;
fftw_complex *inout;
inout = A;
for (i = m; i > 0; i = i - 1, inout = inout + dist, W = W + 31) {
fftw_real tmp19;
fftw_real tmp387;
fftw_real tmp472;
fftw_real tmp486;
fftw_real tmp442;
fftw_real tmp456;
fftw_real tmp191;
fftw_real tmp303;
fftw_real tmp161;
fftw_real tmp403;
fftw_real tmp276;
fftw_real tmp316;
fftw_real tmp372;
fftw_real tmp400;
fftw_real tmp259;
fftw_real tmp319;
fftw_real tmp42;
fftw_real tmp455;
fftw_real tmp201;
fftw_real tmp304;
fftw_real tmp390;
fftw_real tmp437;
fftw_real tmp196;
fftw_real tmp305;
fftw_real tmp184;
fftw_real tmp401;
fftw_real tmp375;
fftw_real tmp404;
fftw_real tmp270;
fftw_real tmp317;
fftw_real tmp279;
fftw_real tmp320;
fftw_real tmp66;
fftw_real tmp395;
fftw_real tmp224;
fftw_real tmp312;
fftw_real tmp357;
fftw_real tmp396;
fftw_real tmp219;
fftw_real tmp311;
fftw_real tmp114;
fftw_real tmp410;
fftw_real tmp249;
fftw_real tmp323;
fftw_real tmp363;
fftw_real tmp407;
fftw_real tmp232;
fftw_real tmp326;
fftw_real tmp89;
fftw_real tmp393;
fftw_real tmp213;
fftw_real tmp309;
fftw_real tmp354;
fftw_real tmp392;
fftw_real tmp208;
fftw_real tmp308;
fftw_real tmp137;
fftw_real tmp408;
fftw_real tmp366;
fftw_real tmp411;
fftw_real tmp243;
fftw_real tmp324;
fftw_real tmp252;
fftw_real tmp327;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp1;
fftw_real tmp440;
fftw_real tmp6;
fftw_real tmp439;
fftw_real tmp12;
fftw_real tmp188;
fftw_real tmp17;
fftw_real tmp189;
ASSERT_ALIGNED_DOUBLE();
tmp1 = c_re(inout[0]);
tmp440 = c_im(inout[0]);
{
fftw_real tmp3;
fftw_real tmp5;
fftw_real tmp2;
fftw_real tmp4;
ASSERT_ALIGNED_DOUBLE();
tmp3 = c_re(inout[16 * iostride]);
tmp5 = c_im(inout[16 * iostride]);
tmp2 = c_re(W[15]);
tmp4 = c_im(W[15]);
tmp6 = (tmp2 * tmp3) + (tmp4 * tmp5);
tmp439 = (tmp2 * tmp5) - (tmp4 * tmp3);
}
{
fftw_real tmp9;
fftw_real tmp11;
fftw_real tmp8;
fftw_real tmp10;
ASSERT_ALIGNED_DOUBLE();
tmp9 = c_re(inout[8 * iostride]);
tmp11 = c_im(inout[8 * iostride]);
tmp8 = c_re(W[7]);
tmp10 = c_im(W[7]);
tmp12 = (tmp8 * tmp9) + (tmp10 * tmp11);
tmp188 = (tmp8 * tmp11) - (tmp10 * tmp9);
}
{
fftw_real tmp14;
fftw_real tmp16;
fftw_real tmp13;
fftw_real tmp15;
ASSERT_ALIGNED_DOUBLE();
tmp14 = c_re(inout[24 * iostride]);
tmp16 = c_im(inout[24 * iostride]);
tmp13 = c_re(W[23]);
tmp15 = c_im(W[23]);
tmp17 = (tmp13 * tmp14) + (tmp15 * tmp16);
tmp189 = (tmp13 * tmp16) - (tmp15 * tmp14);
}
{
fftw_real tmp7;
fftw_real tmp18;
fftw_real tmp470;
fftw_real tmp471;
ASSERT_ALIGNED_DOUBLE();
tmp7 = tmp1 + tmp6;
tmp18 = tmp12 + tmp17;
tmp19 = tmp7 + tmp18;
tmp387 = tmp7 - tmp18;
tmp470 = tmp12 - tmp17;
tmp471 = tmp440 - tmp439;
tmp472 = tmp470 + tmp471;
tmp486 = tmp471 - tmp470;
}
{
fftw_real tmp438;
fftw_real tmp441;
fftw_real tmp187;
fftw_real tmp190;
ASSERT_ALIGNED_DOUBLE();
tmp438 = tmp188 + tmp189;
tmp441 = tmp439 + tmp440;
tmp442 = tmp438 + tmp441;
tmp456 = tmp441 - tmp438;
tmp187 = tmp1 - tmp6;
tmp190 = tmp188 - tmp189;
tmp191 = tmp187 - tmp190;
tmp303 = tmp187 + tmp190;
}
}
{
fftw_real tmp143;
fftw_real tmp272;
fftw_real tmp159;
fftw_real tmp257;
fftw_real tmp148;
fftw_real tmp273;
fftw_real tmp154;
fftw_real tmp256;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp140;
fftw_real tmp142;
fftw_real tmp139;
fftw_real tmp141;
ASSERT_ALIGNED_DOUBLE();
tmp140 = c_re(inout[31 * iostride]);
tmp142 = c_im(inout[31 * iostride]);
tmp139 = c_re(W[30]);
tmp141 = c_im(W[30]);
tmp143 = (tmp139 * tmp140) + (tmp141 * tmp142);
tmp272 = (tmp139 * tmp142) - (tmp141 * tmp140);
}
{
fftw_real tmp156;
fftw_real tmp158;
fftw_real tmp155;
fftw_real tmp157;
ASSERT_ALIGNED_DOUBLE();
tmp156 = c_re(inout[23 * iostride]);
tmp158 = c_im(inout[23 * iostride]);
tmp155 = c_re(W[22]);
tmp157 = c_im(W[22]);
tmp159 = (tmp155 * tmp156) + (tmp157 * tmp158);
tmp257 = (tmp155 * tmp158) - (tmp157 * tmp156);
}
{
fftw_real tmp145;
fftw_real tmp147;
fftw_real tmp144;
fftw_real tmp146;
ASSERT_ALIGNED_DOUBLE();
tmp145 = c_re(inout[15 * iostride]);
tmp147 = c_im(inout[15 * iostride]);
tmp144 = c_re(W[14]);
tmp146 = c_im(W[14]);
tmp148 = (tmp144 * tmp145) + (tmp146 * tmp147);
tmp273 = (tmp144 * tmp147) - (tmp146 * tmp145);
}
{
fftw_real tmp151;
fftw_real tmp153;
fftw_real tmp150;
fftw_real tmp152;
ASSERT_ALIGNED_DOUBLE();
tmp151 = c_re(inout[7 * iostride]);
tmp153 = c_im(inout[7 * iostride]);
tmp150 = c_re(W[6]);
tmp152 = c_im(W[6]);
tmp154 = (tmp150 * tmp151) + (tmp152 * tmp153);
tmp256 = (tmp150 * tmp153) - (tmp152 * tmp151);
}
{
fftw_real tmp149;
fftw_real tmp160;
fftw_real tmp274;
fftw_real tmp275;
ASSERT_ALIGNED_DOUBLE();
tmp149 = tmp143 + tmp148;
tmp160 = tmp154 + tmp159;
tmp161 = tmp149 + tmp160;
tmp403 = tmp149 - tmp160;
tmp274 = tmp272 - tmp273;
tmp275 = tmp154 - tmp159;
tmp276 = tmp274 + tmp275;
tmp316 = tmp274 - tmp275;
}
{
fftw_real tmp370;
fftw_real tmp371;
fftw_real tmp255;
fftw_real tmp258;
ASSERT_ALIGNED_DOUBLE();
tmp370 = tmp272 + tmp273;
tmp371 = tmp256 + tmp257;
tmp372 = tmp370 + tmp371;
tmp400 = tmp370 - tmp371;
tmp255 = tmp143 - tmp148;
tmp258 = tmp256 - tmp257;
tmp259 = tmp255 - tmp258;
tmp319 = tmp255 + tmp258;
}
}
{
fftw_real tmp24;
fftw_real tmp193;
fftw_real tmp40;
fftw_real tmp199;
fftw_real tmp29;
fftw_real tmp194;
fftw_real tmp35;
fftw_real tmp198;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp21;
fftw_real tmp23;
fftw_real tmp20;
fftw_real tmp22;
ASSERT_ALIGNED_DOUBLE();
tmp21 = c_re(inout[4 * iostride]);
tmp23 = c_im(inout[4 * iostride]);
tmp20 = c_re(W[3]);
tmp22 = c_im(W[3]);
tmp24 = (tmp20 * tmp21) + (tmp22 * tmp23);
tmp193 = (tmp20 * tmp23) - (tmp22 * tmp21);
}
{
fftw_real tmp37;
fftw_real tmp39;
fftw_real tmp36;
fftw_real tmp38;
ASSERT_ALIGNED_DOUBLE();
tmp37 = c_re(inout[12 * iostride]);
tmp39 = c_im(inout[12 * iostride]);
tmp36 = c_re(W[11]);
tmp38 = c_im(W[11]);
tmp40 = (tmp36 * tmp37) + (tmp38 * tmp39);
tmp199 = (tmp36 * tmp39) - (tmp38 * tmp37);
}
{
fftw_real tmp26;
fftw_real tmp28;
fftw_real tmp25;
fftw_real tmp27;
ASSERT_ALIGNED_DOUBLE();
tmp26 = c_re(inout[20 * iostride]);
tmp28 = c_im(inout[20 * iostride]);
tmp25 = c_re(W[19]);
tmp27 = c_im(W[19]);
tmp29 = (tmp25 * tmp26) + (tmp27 * tmp28);
tmp194 = (tmp25 * tmp28) - (tmp27 * tmp26);
}
{
fftw_real tmp32;
fftw_real tmp34;
fftw_real tmp31;
fftw_real tmp33;
ASSERT_ALIGNED_DOUBLE();
tmp32 = c_re(inout[28 * iostride]);
tmp34 = c_im(inout[28 * iostride]);
tmp31 = c_re(W[27]);
tmp33 = c_im(W[27]);
tmp35 = (tmp31 * tmp32) + (tmp33 * tmp34);
tmp198 = (tmp31 * tmp34) - (tmp33 * tmp32);
}
{
fftw_real tmp30;
fftw_real tmp41;
fftw_real tmp197;
fftw_real tmp200;
ASSERT_ALIGNED_DOUBLE();
tmp30 = tmp24 + tmp29;
tmp41 = tmp35 + tmp40;
tmp42 = tmp30 + tmp41;
tmp455 = tmp30 - tmp41;
tmp197 = tmp35 - tmp40;
tmp200 = tmp198 - tmp199;
tmp201 = tmp197 + tmp200;
tmp304 = tmp200 - tmp197;
}
{
fftw_real tmp388;
fftw_real tmp389;
fftw_real tmp192;
fftw_real tmp195;
ASSERT_ALIGNED_DOUBLE();
tmp388 = tmp198 + tmp199;
tmp389 = tmp193 + tmp194;
tmp390 = tmp388 - tmp389;
tmp437 = tmp389 + tmp388;
tmp192 = tmp24 - tmp29;
tmp195 = tmp193 - tmp194;
tmp196 = tmp192 - tmp195;
tmp305 = tmp192 + tmp195;
}
}
{
fftw_real tmp166;
fftw_real tmp261;
fftw_real tmp171;
fftw_real tmp262;
fftw_real tmp260;
fftw_real tmp263;
fftw_real tmp177;
fftw_real tmp266;
fftw_real tmp182;
fftw_real tmp267;
fftw_real tmp265;
fftw_real tmp268;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp163;
fftw_real tmp165;
fftw_real tmp162;
fftw_real tmp164;
ASSERT_ALIGNED_DOUBLE();
tmp163 = c_re(inout[3 * iostride]);
tmp165 = c_im(inout[3 * iostride]);
tmp162 = c_re(W[2]);
tmp164 = c_im(W[2]);
tmp166 = (tmp162 * tmp163) + (tmp164 * tmp165);
tmp261 = (tmp162 * tmp165) - (tmp164 * tmp163);
}
{
fftw_real tmp168;
fftw_real tmp170;
fftw_real tmp167;
fftw_real tmp169;
ASSERT_ALIGNED_DOUBLE();
tmp168 = c_re(inout[19 * iostride]);
tmp170 = c_im(inout[19 * iostride]);
tmp167 = c_re(W[18]);
tmp169 = c_im(W[18]);
tmp171 = (tmp167 * tmp168) + (tmp169 * tmp170);
tmp262 = (tmp167 * tmp170) - (tmp169 * tmp168);
}
tmp260 = tmp166 - tmp171;
tmp263 = tmp261 - tmp262;
{
fftw_real tmp174;
fftw_real tmp176;
fftw_real tmp173;
fftw_real tmp175;
ASSERT_ALIGNED_DOUBLE();
tmp174 = c_re(inout[27 * iostride]);
tmp176 = c_im(inout[27 * iostride]);
tmp173 = c_re(W[26]);
tmp175 = c_im(W[26]);
tmp177 = (tmp173 * tmp174) + (tmp175 * tmp176);
tmp266 = (tmp173 * tmp176) - (tmp175 * tmp174);
}
{
fftw_real tmp179;
fftw_real tmp181;
fftw_real tmp178;
fftw_real tmp180;
ASSERT_ALIGNED_DOUBLE();
tmp179 = c_re(inout[11 * iostride]);
tmp181 = c_im(inout[11 * iostride]);
tmp178 = c_re(W[10]);
tmp180 = c_im(W[10]);
tmp182 = (tmp178 * tmp179) + (tmp180 * tmp181);
tmp267 = (tmp178 * tmp181) - (tmp180 * tmp179);
}
tmp265 = tmp177 - tmp182;
tmp268 = tmp266 - tmp267;
{
fftw_real tmp172;
fftw_real tmp183;
fftw_real tmp373;
fftw_real tmp374;
ASSERT_ALIGNED_DOUBLE();
tmp172 = tmp166 + tmp171;
tmp183 = tmp177 + tmp182;
tmp184 = tmp172 + tmp183;
tmp401 = tmp172 - tmp183;
tmp373 = tmp261 + tmp262;
tmp374 = tmp266 + tmp267;
tmp375 = tmp373 + tmp374;
tmp404 = tmp374 - tmp373;
}
{
fftw_real tmp264;
fftw_real tmp269;
fftw_real tmp277;
fftw_real tmp278;
ASSERT_ALIGNED_DOUBLE();
tmp264 = tmp260 - tmp263;
tmp269 = tmp265 + tmp268;
tmp270 = K707106781 * (tmp264 + tmp269);
tmp317 = K707106781 * (tmp264 - tmp269);
tmp277 = tmp260 + tmp263;
tmp278 = tmp268 - tmp265;
tmp279 = K707106781 * (tmp277 + tmp278);
tmp320 = K707106781 * (tmp278 - tmp277);
}
}
{
fftw_real tmp48;
fftw_real tmp215;
fftw_real tmp64;
fftw_real tmp222;
fftw_real tmp53;
fftw_real tmp216;
fftw_real tmp59;
fftw_real tmp221;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp45;
fftw_real tmp47;
fftw_real tmp44;
fftw_real tmp46;
ASSERT_ALIGNED_DOUBLE();
tmp45 = c_re(inout[2 * iostride]);
tmp47 = c_im(inout[2 * iostride]);
tmp44 = c_re(W[1]);
tmp46 = c_im(W[1]);
tmp48 = (tmp44 * tmp45) + (tmp46 * tmp47);
tmp215 = (tmp44 * tmp47) - (tmp46 * tmp45);
}
{
fftw_real tmp61;
fftw_real tmp63;
fftw_real tmp60;
fftw_real tmp62;
ASSERT_ALIGNED_DOUBLE();
tmp61 = c_re(inout[26 * iostride]);
tmp63 = c_im(inout[26 * iostride]);
tmp60 = c_re(W[25]);
tmp62 = c_im(W[25]);
tmp64 = (tmp60 * tmp61) + (tmp62 * tmp63);
tmp222 = (tmp60 * tmp63) - (tmp62 * tmp61);
}
{
fftw_real tmp50;
fftw_real tmp52;
fftw_real tmp49;
fftw_real tmp51;
ASSERT_ALIGNED_DOUBLE();
tmp50 = c_re(inout[18 * iostride]);
tmp52 = c_im(inout[18 * iostride]);
tmp49 = c_re(W[17]);
tmp51 = c_im(W[17]);
tmp53 = (tmp49 * tmp50) + (tmp51 * tmp52);
tmp216 = (tmp49 * tmp52) - (tmp51 * tmp50);
}
{
fftw_real tmp56;
fftw_real tmp58;
fftw_real tmp55;
fftw_real tmp57;
ASSERT_ALIGNED_DOUBLE();
tmp56 = c_re(inout[10 * iostride]);
tmp58 = c_im(inout[10 * iostride]);
tmp55 = c_re(W[9]);
tmp57 = c_im(W[9]);
tmp59 = (tmp55 * tmp56) + (tmp57 * tmp58);
tmp221 = (tmp55 * tmp58) - (tmp57 * tmp56);
}
{
fftw_real tmp54;
fftw_real tmp65;
fftw_real tmp220;
fftw_real tmp223;
ASSERT_ALIGNED_DOUBLE();
tmp54 = tmp48 + tmp53;
tmp65 = tmp59 + tmp64;
tmp66 = tmp54 + tmp65;
tmp395 = tmp54 - tmp65;
tmp220 = tmp48 - tmp53;
tmp223 = tmp221 - tmp222;
tmp224 = tmp220 - tmp223;
tmp312 = tmp220 + tmp223;
}
{
fftw_real tmp355;
fftw_real tmp356;
fftw_real tmp217;
fftw_real tmp218;
ASSERT_ALIGNED_DOUBLE();
tmp355 = tmp215 + tmp216;
tmp356 = tmp221 + tmp222;
tmp357 = tmp355 + tmp356;
tmp396 = tmp355 - tmp356;
tmp217 = tmp215 - tmp216;
tmp218 = tmp59 - tmp64;
tmp219 = tmp217 + tmp218;
tmp311 = tmp217 - tmp218;
}
}
{
fftw_real tmp96;
fftw_real tmp245;
fftw_real tmp112;
fftw_real tmp230;
fftw_real tmp101;
fftw_real tmp246;
fftw_real tmp107;
fftw_real tmp229;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp93;
fftw_real tmp95;
fftw_real tmp92;
fftw_real tmp94;
ASSERT_ALIGNED_DOUBLE();
tmp93 = c_re(inout[iostride]);
tmp95 = c_im(inout[iostride]);
tmp92 = c_re(W[0]);
tmp94 = c_im(W[0]);
tmp96 = (tmp92 * tmp93) + (tmp94 * tmp95);
tmp245 = (tmp92 * tmp95) - (tmp94 * tmp93);
}
{
fftw_real tmp109;
fftw_real tmp111;
fftw_real tmp108;
fftw_real tmp110;
ASSERT_ALIGNED_DOUBLE();
tmp109 = c_re(inout[25 * iostride]);
tmp111 = c_im(inout[25 * iostride]);
tmp108 = c_re(W[24]);
tmp110 = c_im(W[24]);
tmp112 = (tmp108 * tmp109) + (tmp110 * tmp111);
tmp230 = (tmp108 * tmp111) - (tmp110 * tmp109);
}
{
fftw_real tmp98;
fftw_real tmp100;
fftw_real tmp97;
fftw_real tmp99;
ASSERT_ALIGNED_DOUBLE();
tmp98 = c_re(inout[17 * iostride]);
tmp100 = c_im(inout[17 * iostride]);
tmp97 = c_re(W[16]);
tmp99 = c_im(W[16]);
tmp101 = (tmp97 * tmp98) + (tmp99 * tmp100);
tmp246 = (tmp97 * tmp100) - (tmp99 * tmp98);
}
{
fftw_real tmp104;
fftw_real tmp106;
fftw_real tmp103;
fftw_real tmp105;
ASSERT_ALIGNED_DOUBLE();
tmp104 = c_re(inout[9 * iostride]);
tmp106 = c_im(inout[9 * iostride]);
tmp103 = c_re(W[8]);
tmp105 = c_im(W[8]);
tmp107 = (tmp103 * tmp104) + (tmp105 * tmp106);
tmp229 = (tmp103 * tmp106) - (tmp105 * tmp104);
}
{
fftw_real tmp102;
fftw_real tmp113;
fftw_real tmp247;
fftw_real tmp248;
ASSERT_ALIGNED_DOUBLE();
tmp102 = tmp96 + tmp101;
tmp113 = tmp107 + tmp112;
tmp114 = tmp102 + tmp113;
tmp410 = tmp102 - tmp113;
tmp247 = tmp245 - tmp246;
tmp248 = tmp107 - tmp112;
tmp249 = tmp247 + tmp248;
tmp323 = tmp247 - tmp248;
}
{
fftw_real tmp361;
fftw_real tmp362;
fftw_real tmp228;
fftw_real tmp231;
ASSERT_ALIGNED_DOUBLE();
tmp361 = tmp245 + tmp246;
tmp362 = tmp229 + tmp230;
tmp363 = tmp361 + tmp362;
tmp407 = tmp361 - tmp362;
tmp228 = tmp96 - tmp101;
tmp231 = tmp229 - tmp230;
tmp232 = tmp228 - tmp231;
tmp326 = tmp228 + tmp231;
}
}
{
fftw_real tmp71;
fftw_real tmp204;
fftw_real tmp87;
fftw_real tmp211;
fftw_real tmp76;
fftw_real tmp205;
fftw_real tmp82;
fftw_real tmp210;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp68;
fftw_real tmp70;
fftw_real tmp67;
fftw_real tmp69;
ASSERT_ALIGNED_DOUBLE();
tmp68 = c_re(inout[30 * iostride]);
tmp70 = c_im(inout[30 * iostride]);
tmp67 = c_re(W[29]);
tmp69 = c_im(W[29]);
tmp71 = (tmp67 * tmp68) + (tmp69 * tmp70);
tmp204 = (tmp67 * tmp70) - (tmp69 * tmp68);
}
{
fftw_real tmp84;
fftw_real tmp86;
fftw_real tmp83;
fftw_real tmp85;
ASSERT_ALIGNED_DOUBLE();
tmp84 = c_re(inout[22 * iostride]);
tmp86 = c_im(inout[22 * iostride]);
tmp83 = c_re(W[21]);
tmp85 = c_im(W[21]);
tmp87 = (tmp83 * tmp84) + (tmp85 * tmp86);
tmp211 = (tmp83 * tmp86) - (tmp85 * tmp84);
}
{
fftw_real tmp73;
fftw_real tmp75;
fftw_real tmp72;
fftw_real tmp74;
ASSERT_ALIGNED_DOUBLE();
tmp73 = c_re(inout[14 * iostride]);
tmp75 = c_im(inout[14 * iostride]);
tmp72 = c_re(W[13]);
tmp74 = c_im(W[13]);
tmp76 = (tmp72 * tmp73) + (tmp74 * tmp75);
tmp205 = (tmp72 * tmp75) - (tmp74 * tmp73);
}
{
fftw_real tmp79;
fftw_real tmp81;
fftw_real tmp78;
fftw_real tmp80;
ASSERT_ALIGNED_DOUBLE();
tmp79 = c_re(inout[6 * iostride]);
tmp81 = c_im(inout[6 * iostride]);
tmp78 = c_re(W[5]);
tmp80 = c_im(W[5]);
tmp82 = (tmp78 * tmp79) + (tmp80 * tmp81);
tmp210 = (tmp78 * tmp81) - (tmp80 * tmp79);
}
{
fftw_real tmp77;
fftw_real tmp88;
fftw_real tmp209;
fftw_real tmp212;
ASSERT_ALIGNED_DOUBLE();
tmp77 = tmp71 + tmp76;
tmp88 = tmp82 + tmp87;
tmp89 = tmp77 + tmp88;
tmp393 = tmp77 - tmp88;
tmp209 = tmp71 - tmp76;
tmp212 = tmp210 - tmp211;
tmp213 = tmp209 - tmp212;
tmp309 = tmp209 + tmp212;
}
{
fftw_real tmp352;
fftw_real tmp353;
fftw_real tmp206;
fftw_real tmp207;
ASSERT_ALIGNED_DOUBLE();
tmp352 = tmp204 + tmp205;
tmp353 = tmp210 + tmp211;
tmp354 = tmp352 + tmp353;
tmp392 = tmp352 - tmp353;
tmp206 = tmp204 - tmp205;
tmp207 = tmp82 - tmp87;
tmp208 = tmp206 + tmp207;
tmp308 = tmp206 - tmp207;
}
}
{
fftw_real tmp119;
fftw_real tmp234;
fftw_real tmp124;
fftw_real tmp235;
fftw_real tmp233;
fftw_real tmp236;
fftw_real tmp130;
fftw_real tmp239;
fftw_real tmp135;
fftw_real tmp240;
fftw_real tmp238;
fftw_real tmp241;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp116;
fftw_real tmp118;
fftw_real tmp115;
fftw_real tmp117;
ASSERT_ALIGNED_DOUBLE();
tmp116 = c_re(inout[5 * iostride]);
tmp118 = c_im(inout[5 * iostride]);
tmp115 = c_re(W[4]);
tmp117 = c_im(W[4]);
tmp119 = (tmp115 * tmp116) + (tmp117 * tmp118);
tmp234 = (tmp115 * tmp118) - (tmp117 * tmp116);
}
{
fftw_real tmp121;
fftw_real tmp123;
fftw_real tmp120;
fftw_real tmp122;
ASSERT_ALIGNED_DOUBLE();
tmp121 = c_re(inout[21 * iostride]);
tmp123 = c_im(inout[21 * iostride]);
tmp120 = c_re(W[20]);
tmp122 = c_im(W[20]);
tmp124 = (tmp120 * tmp121) + (tmp122 * tmp123);
tmp235 = (tmp120 * tmp123) - (tmp122 * tmp121);
}
tmp233 = tmp119 - tmp124;
tmp236 = tmp234 - tmp235;
{
fftw_real tmp127;
fftw_real tmp129;
fftw_real tmp126;
fftw_real tmp128;
ASSERT_ALIGNED_DOUBLE();
tmp127 = c_re(inout[29 * iostride]);
tmp129 = c_im(inout[29 * iostride]);
tmp126 = c_re(W[28]);
tmp128 = c_im(W[28]);
tmp130 = (tmp126 * tmp127) + (tmp128 * tmp129);
tmp239 = (tmp126 * tmp129) - (tmp128 * tmp127);
}
{
fftw_real tmp132;
fftw_real tmp134;
fftw_real tmp131;
fftw_real tmp133;
ASSERT_ALIGNED_DOUBLE();
tmp132 = c_re(inout[13 * iostride]);
tmp134 = c_im(inout[13 * iostride]);
tmp131 = c_re(W[12]);
tmp133 = c_im(W[12]);
tmp135 = (tmp131 * tmp132) + (tmp133 * tmp134);
tmp240 = (tmp131 * tmp134) - (tmp133 * tmp132);
}
tmp238 = tmp130 - tmp135;
tmp241 = tmp239 - tmp240;
{
fftw_real tmp125;
fftw_real tmp136;
fftw_real tmp364;
fftw_real tmp365;
ASSERT_ALIGNED_DOUBLE();
tmp125 = tmp119 + tmp124;
tmp136 = tmp130 + tmp135;
tmp137 = tmp125 + tmp136;
tmp408 = tmp125 - tmp136;
tmp364 = tmp234 + tmp235;
tmp365 = tmp239 + tmp240;
tmp366 = tmp364 + tmp365;
tmp411 = tmp365 - tmp364;
}
{
fftw_real tmp237;
fftw_real tmp242;
fftw_real tmp250;
fftw_real tmp251;
ASSERT_ALIGNED_DOUBLE();
tmp237 = tmp233 - tmp236;
tmp242 = tmp238 + tmp241;
tmp243 = K707106781 * (tmp237 + tmp242);
tmp324 = K707106781 * (tmp237 - tmp242);
tmp250 = tmp233 + tmp236;
tmp251 = tmp241 - tmp238;
tmp252 = K707106781 * (tmp250 + tmp251);
tmp327 = K707106781 * (tmp251 - tmp250);
}
}
{
fftw_real tmp91;
fftw_real tmp383;
fftw_real tmp444;
fftw_real tmp446;
fftw_real tmp186;
fftw_real tmp445;
fftw_real tmp386;
fftw_real tmp435;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp43;
fftw_real tmp90;
fftw_real tmp436;
fftw_real tmp443;
ASSERT_ALIGNED_DOUBLE();
tmp43 = tmp19 + tmp42;
tmp90 = tmp66 + tmp89;
tmp91 = tmp43 + tmp90;
tmp383 = tmp43 - tmp90;
tmp436 = tmp357 + tmp354;
tmp443 = tmp437 + tmp442;
tmp444 = tmp436 + tmp443;
tmp446 = tmp443 - tmp436;
}
{
fftw_real tmp138;
fftw_real tmp185;
fftw_real tmp384;
fftw_real tmp385;
ASSERT_ALIGNED_DOUBLE();
tmp138 = tmp114 + tmp137;
tmp185 = tmp161 + tmp184;
tmp186 = tmp138 + tmp185;
tmp445 = tmp138 - tmp185;
tmp384 = tmp372 + tmp375;
tmp385 = tmp363 + tmp366;
tmp386 = tmp384 - tmp385;
tmp435 = tmp385 + tmp384;
}
c_re(inout[16 * iostride]) = tmp91 - tmp186;
c_re(inout[0]) = tmp91 + tmp186;
c_re(inout[24 * iostride]) = tmp383 - tmp386;
c_re(inout[8 * iostride]) = tmp383 + tmp386;
c_im(inout[0]) = tmp435 + tmp444;
c_im(inout[16 * iostride]) = tmp444 - tmp435;
c_im(inout[8 * iostride]) = tmp445 + tmp446;
c_im(inout[24 * iostride]) = tmp446 - tmp445;
}
{
fftw_real tmp359;
fftw_real tmp379;
fftw_real tmp450;
fftw_real tmp452;
fftw_real tmp368;
fftw_real tmp381;
fftw_real tmp377;
fftw_real tmp380;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp351;
fftw_real tmp358;
fftw_real tmp448;
fftw_real tmp449;
ASSERT_ALIGNED_DOUBLE();
tmp351 = tmp19 - tmp42;
tmp358 = tmp354 - tmp357;
tmp359 = tmp351 + tmp358;
tmp379 = tmp351 - tmp358;
tmp448 = tmp66 - tmp89;
tmp449 = tmp442 - tmp437;
tmp450 = tmp448 + tmp449;
tmp452 = tmp449 - tmp448;
}
{
fftw_real tmp360;
fftw_real tmp367;
fftw_real tmp369;
fftw_real tmp376;
ASSERT_ALIGNED_DOUBLE();
tmp360 = tmp114 - tmp137;
tmp367 = tmp363 - tmp366;
tmp368 = tmp360 - tmp367;
tmp381 = tmp360 + tmp367;
tmp369 = tmp161 - tmp184;
tmp376 = tmp372 - tmp375;
tmp377 = tmp369 + tmp376;
tmp380 = tmp376 - tmp369;
}
{
fftw_real tmp378;
fftw_real tmp451;
fftw_real tmp382;
fftw_real tmp447;
ASSERT_ALIGNED_DOUBLE();
tmp378 = K707106781 * (tmp368 + tmp377);
c_re(inout[20 * iostride]) = tmp359 - tmp378;
c_re(inout[4 * iostride]) = tmp359 + tmp378;
tmp451 = K707106781 * (tmp368 - tmp377);
c_im(inout[12 * iostride]) = tmp451 + tmp452;
c_im(inout[28 * iostride]) = tmp452 - tmp451;
tmp382 = K707106781 * (tmp380 - tmp381);
c_re(inout[28 * iostride]) = tmp379 - tmp382;
c_re(inout[12 * iostride]) = tmp379 + tmp382;
tmp447 = K707106781 * (tmp381 + tmp380);
c_im(inout[4 * iostride]) = tmp447 + tmp450;
c_im(inout[20 * iostride]) = tmp450 - tmp447;
}
}
{
fftw_real tmp391;
fftw_real tmp419;
fftw_real tmp398;
fftw_real tmp454;
fftw_real tmp422;
fftw_real tmp462;
fftw_real tmp406;
fftw_real tmp417;
fftw_real tmp457;
fftw_real tmp463;
fftw_real tmp426;
fftw_real tmp433;
fftw_real tmp413;
fftw_real tmp416;
fftw_real tmp429;
fftw_real tmp432;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp394;
fftw_real tmp397;
fftw_real tmp424;
fftw_real tmp425;
ASSERT_ALIGNED_DOUBLE();
tmp391 = tmp387 - tmp390;
tmp419 = tmp387 + tmp390;
tmp394 = tmp392 - tmp393;
tmp397 = tmp395 + tmp396;
tmp398 = K707106781 * (tmp394 - tmp397);
tmp454 = K707106781 * (tmp397 + tmp394);
{
fftw_real tmp420;
fftw_real tmp421;
fftw_real tmp402;
fftw_real tmp405;
ASSERT_ALIGNED_DOUBLE();
tmp420 = tmp395 - tmp396;
tmp421 = tmp393 + tmp392;
tmp422 = K707106781 * (tmp420 + tmp421);
tmp462 = K707106781 * (tmp420 - tmp421);
tmp402 = tmp400 - tmp401;
tmp405 = tmp403 - tmp404;
tmp406 = (K382683432 * tmp402) - (K923879532 * tmp405);
tmp417 = (K923879532 * tmp402) + (K382683432 * tmp405);
}
tmp457 = tmp455 + tmp456;
tmp463 = tmp456 - tmp455;
tmp424 = tmp400 + tmp401;
tmp425 = tmp403 + tmp404;
tmp426 = (K923879532 * tmp424) - (K382683432 * tmp425);
tmp433 = (K382683432 * tmp424) + (K923879532 * tmp425);
{
fftw_real tmp409;
fftw_real tmp412;
fftw_real tmp427;
fftw_real tmp428;
ASSERT_ALIGNED_DOUBLE();
tmp409 = tmp407 - tmp408;
tmp412 = tmp410 - tmp411;
tmp413 = (K382683432 * tmp409) + (K923879532 * tmp412);
tmp416 = (K382683432 * tmp412) - (K923879532 * tmp409);
tmp427 = tmp407 + tmp408;
tmp428 = tmp410 + tmp411;
tmp429 = (K923879532 * tmp427) + (K382683432 * tmp428);
tmp432 = (K923879532 * tmp428) - (K382683432 * tmp427);
}
}
{
fftw_real tmp399;
fftw_real tmp414;
fftw_real tmp415;
fftw_real tmp418;
ASSERT_ALIGNED_DOUBLE();
tmp399 = tmp391 - tmp398;
tmp414 = tmp406 - tmp413;
c_re(inout[30 * iostride]) = tmp399 - tmp414;
c_re(inout[14 * iostride]) = tmp399 + tmp414;
tmp415 = tmp391 + tmp398;
tmp418 = tmp416 + tmp417;
c_re(inout[22 * iostride]) = tmp415 - tmp418;
c_re(inout[6 * iostride]) = tmp415 + tmp418;
}
{
fftw_real tmp465;
fftw_real tmp466;
fftw_real tmp461;
fftw_real tmp464;
ASSERT_ALIGNED_DOUBLE();
tmp465 = tmp416 - tmp417;
tmp466 = tmp463 - tmp462;
c_im(inout[14 * iostride]) = tmp465 + tmp466;
c_im(inout[30 * iostride]) = tmp466 - tmp465;
tmp461 = tmp413 + tmp406;
tmp464 = tmp462 + tmp463;
c_im(inout[6 * iostride]) = tmp461 + tmp464;
c_im(inout[22 * iostride]) = tmp464 - tmp461;
}
{
fftw_real tmp423;
fftw_real tmp430;
fftw_real tmp431;
fftw_real tmp434;
ASSERT_ALIGNED_DOUBLE();
tmp423 = tmp419 - tmp422;
tmp430 = tmp426 - tmp429;
c_re(inout[26 * iostride]) = tmp423 - tmp430;
c_re(inout[10 * iostride]) = tmp423 + tmp430;
tmp431 = tmp419 + tmp422;
tmp434 = tmp432 + tmp433;
c_re(inout[18 * iostride]) = tmp431 - tmp434;
c_re(inout[2 * iostride]) = tmp431 + tmp434;
}
{
fftw_real tmp459;
fftw_real tmp460;
fftw_real tmp453;
fftw_real tmp458;
ASSERT_ALIGNED_DOUBLE();
tmp459 = tmp432 - tmp433;
tmp460 = tmp457 - tmp454;
c_im(inout[10 * iostride]) = tmp459 + tmp460;
c_im(inout[26 * iostride]) = tmp460 - tmp459;
tmp453 = tmp429 + tmp426;
tmp458 = tmp454 + tmp457;
c_im(inout[2 * iostride]) = tmp453 + tmp458;
c_im(inout[18 * iostride]) = tmp458 - tmp453;
}
}
{
fftw_real tmp307;
fftw_real tmp335;
fftw_real tmp338;
fftw_real tmp492;
fftw_real tmp487;
fftw_real tmp493;
fftw_real tmp314;
fftw_real tmp484;
fftw_real tmp322;
fftw_real tmp333;
fftw_real tmp342;
fftw_real tmp349;
fftw_real tmp329;
fftw_real tmp332;
fftw_real tmp345;
fftw_real tmp348;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp306;
fftw_real tmp336;
fftw_real tmp337;
fftw_real tmp485;
fftw_real tmp310;
fftw_real tmp313;
ASSERT_ALIGNED_DOUBLE();
tmp306 = K707106781 * (tmp304 - tmp305);
tmp307 = tmp303 - tmp306;
tmp335 = tmp303 + tmp306;
tmp336 = (K382683432 * tmp312) - (K923879532 * tmp311);
tmp337 = (K923879532 * tmp308) + (K382683432 * tmp309);
tmp338 = tmp336 + tmp337;
tmp492 = tmp336 - tmp337;
tmp485 = K707106781 * (tmp196 - tmp201);
tmp487 = tmp485 + tmp486;
tmp493 = tmp486 - tmp485;
tmp310 = (K382683432 * tmp308) - (K923879532 * tmp309);
tmp313 = (K382683432 * tmp311) + (K923879532 * tmp312);
tmp314 = tmp310 - tmp313;
tmp484 = tmp313 + tmp310;
}
{
fftw_real tmp318;
fftw_real tmp321;
fftw_real tmp340;
fftw_real tmp341;
ASSERT_ALIGNED_DOUBLE();
tmp318 = tmp316 - tmp317;
tmp321 = tmp319 - tmp320;
tmp322 = (K195090322 * tmp318) - (K980785280 * tmp321);
tmp333 = (K980785280 * tmp318) + (K195090322 * tmp321);
tmp340 = tmp316 + tmp317;
tmp341 = tmp319 + tmp320;
tmp342 = (K831469612 * tmp340) - (K555570233 * tmp341);
tmp349 = (K555570233 * tmp340) + (K831469612 * tmp341);
}
{
fftw_real tmp325;
fftw_real tmp328;
fftw_real tmp343;
fftw_real tmp344;
ASSERT_ALIGNED_DOUBLE();
tmp325 = tmp323 - tmp324;
tmp328 = tmp326 - tmp327;
tmp329 = (K195090322 * tmp325) + (K980785280 * tmp328);
tmp332 = (K195090322 * tmp328) - (K980785280 * tmp325);
tmp343 = tmp323 + tmp324;
tmp344 = tmp326 + tmp327;
tmp345 = (K831469612 * tmp343) + (K555570233 * tmp344);
tmp348 = (K831469612 * tmp344) - (K555570233 * tmp343);
}
{
fftw_real tmp315;
fftw_real tmp330;
fftw_real tmp331;
fftw_real tmp334;
ASSERT_ALIGNED_DOUBLE();
tmp315 = tmp307 - tmp314;
tmp330 = tmp322 - tmp329;
c_re(inout[31 * iostride]) = tmp315 - tmp330;
c_re(inout[15 * iostride]) = tmp315 + tmp330;
tmp331 = tmp307 + tmp314;
tmp334 = tmp332 + tmp333;
c_re(inout[23 * iostride]) = tmp331 - tmp334;
c_re(inout[7 * iostride]) = tmp331 + tmp334;
}
{
fftw_real tmp495;
fftw_real tmp496;
fftw_real tmp491;
fftw_real tmp494;
ASSERT_ALIGNED_DOUBLE();
tmp495 = tmp332 - tmp333;
tmp496 = tmp493 - tmp492;
c_im(inout[15 * iostride]) = tmp495 + tmp496;
c_im(inout[31 * iostride]) = tmp496 - tmp495;
tmp491 = tmp329 + tmp322;
tmp494 = tmp492 + tmp493;
c_im(inout[7 * iostride]) = tmp491 + tmp494;
c_im(inout[23 * iostride]) = tmp494 - tmp491;
}
{
fftw_real tmp339;
fftw_real tmp346;
fftw_real tmp347;
fftw_real tmp350;
ASSERT_ALIGNED_DOUBLE();
tmp339 = tmp335 - tmp338;
tmp346 = tmp342 - tmp345;
c_re(inout[27 * iostride]) = tmp339 - tmp346;
c_re(inout[11 * iostride]) = tmp339 + tmp346;
tmp347 = tmp335 + tmp338;
tmp350 = tmp348 + tmp349;
c_re(inout[19 * iostride]) = tmp347 - tmp350;
c_re(inout[3 * iostride]) = tmp347 + tmp350;
}
{
fftw_real tmp489;
fftw_real tmp490;
fftw_real tmp483;
fftw_real tmp488;
ASSERT_ALIGNED_DOUBLE();
tmp489 = tmp348 - tmp349;
tmp490 = tmp487 - tmp484;
c_im(inout[11 * iostride]) = tmp489 + tmp490;
c_im(inout[27 * iostride]) = tmp490 - tmp489;
tmp483 = tmp345 + tmp342;
tmp488 = tmp484 + tmp487;
c_im(inout[3 * iostride]) = tmp483 + tmp488;
c_im(inout[19 * iostride]) = tmp488 - tmp483;
}
}
{
fftw_real tmp203;
fftw_real tmp287;
fftw_real tmp290;
fftw_real tmp478;
fftw_real tmp473;
fftw_real tmp479;
fftw_real tmp226;
fftw_real tmp468;
fftw_real tmp254;
fftw_real tmp285;
fftw_real tmp294;
fftw_real tmp301;
fftw_real tmp281;
fftw_real tmp284;
fftw_real tmp297;
fftw_real tmp300;
ASSERT_ALIGNED_DOUBLE();
{
fftw_real tmp202;
fftw_real tmp288;
fftw_real tmp289;
fftw_real tmp469;
fftw_real tmp214;
fftw_real tmp225;
ASSERT_ALIGNED_DOUBLE();
tmp202 = K707106781 * (tmp196 + tmp201);
tmp203 = tmp191 - tmp202;
tmp287 = tmp191 + tmp202;
tmp288 = (K923879532 * tmp224) - (K382683432 * tmp219);
tmp289 = (K382683432 * tmp208) + (K923879532 * tmp213);
tmp290 = tmp288 + tmp289;
tmp478 = tmp288 - tmp289;
tmp469 = K707106781 * (tmp305 + tmp304);
tmp473 = tmp469 + tmp472;
tmp479 = tmp472 - tmp469;
tmp214 = (K923879532 * tmp208) - (K382683432 * tmp213);
tmp225 = (K923879532 * tmp219) + (K382683432 * tmp224);
tmp226 = tmp214 - tmp225;
tmp468 = tmp225 + tmp214;
}
{
fftw_real tmp244;
fftw_real tmp253;
fftw_real tmp292;
fftw_real tmp293;
ASSERT_ALIGNED_DOUBLE();
tmp244 = tmp232 - tmp243;
tmp253 = tmp249 - tmp252;
tmp254 = (K555570233 * tmp244) - (K831469612 * tmp253);
tmp285 = (K831469612 * tmp244) + (K555570233 * tmp253);
tmp292 = tmp232 + tmp243;
tmp293 = tmp249 + tmp252;
tmp294 = (K980785280 * tmp292) - (K195090322 * tmp293);
tmp301 = (K195090322 * tmp292) + (K980785280 * tmp293);
}
{
fftw_real tmp271;
fftw_real tmp280;
fftw_real tmp295;
fftw_real tmp296;
ASSERT_ALIGNED_DOUBLE();
tmp271 = tmp259 - tmp270;
tmp280 = tmp276 - tmp279;
tmp281 = (K555570233 * tmp271) + (K831469612 * tmp280);
tmp284 = (K555570233 * tmp280) - (K831469612 * tmp271);
tmp295 = tmp259 + tmp270;
tmp296 = tmp276 + tmp279;
tmp297 = (K980785280 * tmp295) + (K195090322 * tmp296);
tmp300 = (K980785280 * tmp296) - (K195090322 * tmp295);
}
{
fftw_real tmp227;
fftw_real tmp282;
fftw_real tmp283;
fftw_real tmp286;
ASSERT_ALIGNED_DOUBLE();
tmp227 = tmp203 + tmp226;
tmp282 = tmp254 + tmp281;
c_re(inout[21 * iostride]) = tmp227 - tmp282;
c_re(inout[5 * iostride]) = tmp227 + tmp282;
tmp283 = tmp203 - tmp226;
tmp286 = tmp284 - tmp285;
c_re(inout[29 * iostride]) = tmp283 - tmp286;
c_re(inout[13 * iostride]) = tmp283 + tmp286;
}
{
fftw_real tmp477;
fftw_real tmp480;
fftw_real tmp481;
fftw_real tmp482;
ASSERT_ALIGNED_DOUBLE();
tmp477 = tmp285 + tmp284;
tmp480 = tmp478 + tmp479;
c_im(inout[5 * iostride]) = tmp477 + tmp480;
c_im(inout[21 * iostride]) = tmp480 - tmp477;
tmp481 = tmp254 - tmp281;
tmp482 = tmp479 - tmp478;
c_im(inout[13 * iostride]) = tmp481 + tmp482;
c_im(inout[29 * iostride]) = tmp482 - tmp481;
}
{
fftw_real tmp291;
fftw_real tmp298;
fftw_real tmp299;
fftw_real tmp302;
ASSERT_ALIGNED_DOUBLE();
tmp291 = tmp287 + tmp290;
tmp298 = tmp294 + tmp297;
c_re(inout[17 * iostride]) = tmp291 - tmp298;
c_re(inout[iostride]) = tmp291 + tmp298;
tmp299 = tmp287 - tmp290;
tmp302 = tmp300 - tmp301;
c_re(inout[25 * iostride]) = tmp299 - tmp302;
c_re(inout[9 * iostride]) = tmp299 + tmp302;
}
{
fftw_real tmp467;
fftw_real tmp474;
fftw_real tmp475;
fftw_real tmp476;
ASSERT_ALIGNED_DOUBLE();
tmp467 = tmp301 + tmp300;
tmp474 = tmp468 + tmp473;
c_im(inout[iostride]) = tmp467 + tmp474;
c_im(inout[17 * iostride]) = tmp474 - tmp467;
tmp475 = tmp294 - tmp297;
tmp476 = tmp473 - tmp468;
c_im(inout[9 * iostride]) = tmp475 + tmp476;
c_im(inout[25 * iostride]) = tmp476 - tmp475;
}
}
}
}
static const int twiddle_order[] =
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
fftw_codelet_desc fftwi_twiddle_32_desc =
{
"fftwi_twiddle_32",
(void (*)()) fftwi_twiddle_32,
32,
FFTW_BACKWARD,
FFTW_TWIDDLE,
520,
31,
twiddle_order,
};
| {
"alphanum_fraction": 0.5732986222,
"avg_line_length": 29.3985559567,
"ext": "c",
"hexsha": "9cc6a9b711bb2fb147b85a6560e4a86996122365",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-07-09T00:20:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-07-09T00:20:49.000Z",
"max_forks_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jlprieur/jlplib",
"max_forks_repo_path": "jlp_numeric/old/fftw2_src/ftwi_32.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jlprieur/jlplib",
"max_issues_repo_path": "jlp_numeric/old/fftw2_src/ftwi_32.c",
"max_line_length": 122,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jlprieur/jlplib",
"max_stars_repo_path": "jlp_numeric/old/fftw2_src/ftwi_32.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 12675,
"size": 40717
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.