Search is not available for this dataset
text string | meta dict |
|---|---|
#ifndef __LIB_MATH_OPTIMIZER__
#define __LIB_MATH_OPTIMIZER__
#include <iostream>
#include <limits>
#include <gsl/gsl_multimin.h>
#include "math/gsl_vector.h"
#include "util/flags.h"
using std::cout;
using std::endl;
DEFINE_double(multimin_convergence_threshold,
1e-5,
"Convergence threshold for conjugate gradient.");
DEFINE_size(max_multimin_iterations,
40,
"Maximum number of conjugate gradient iterations to perform.");
class Optimizer {
public:
Optimizer(size_t size) : size_(size) {
}
void Optimize() {
gsl_multimin_function_fdf my_func;
my_func.n = size_;
my_func.f = &MultiminObjectiveWrapper;
my_func.df = &MultiminGradientWrapper;
my_func.fdf = &MultiminObjectiveGradientWrapper;
my_func.params = this;
gsl_multimin_fdfminimizer* s =
gsl_multimin_fdfminimizer_alloc(gsl_multimin_fdfminimizer_conjugate_fr, size_);
GslVector initial_guess(size_);
MultiminInitialGuess(initial_guess.mutable_ptr());
// step_size, tol
// gsl_multimin_fdfminimizer_set(s, &my_func, initial_guess.ptr(), 0.1, 1.0);
gsl_multimin_fdfminimizer_set(s, &my_func, initial_guess.ptr(), 0.01, 0.01);
size_t iter = 0;
int status;
double value = std::numeric_limits<double>::infinity();
double prev_value;
do {
prev_value = value;
iter++;
status = gsl_multimin_fdfminimizer_iterate(s);
if (status) {
cout << "Error: " << gsl_strerror(status) << endl;
break;
}
status = gsl_multimin_test_gradient(s->gradient, 1e-3);
if (status == GSL_SUCCESS) {
cout << "Minimum found." << endl;
}
value = s->f;
cout << "Iteration: " << iter << " Value: " <<
value << " dValue:" << (prev_value - value)/fabs(value) << " " <<
gsl_strerror(status) << endl;
} while (status == GSL_CONTINUE &&
iter < FLAGS_max_multimin_iterations &&
(prev_value - value) / fabs(value) > FLAGS_multimin_convergence_threshold);
MultiminResult(s->x);
gsl_multimin_fdfminimizer_free(s);
}
virtual void MultiminObjectiveGradient(const gsl_vector* x,
double* objective,
gsl_vector* gradient) = 0;
virtual void MultiminInitialGuess(gsl_vector* v) = 0;
virtual void MultiminResult(gsl_vector* x) = 0;
virtual ~Optimizer() { }
protected:
static double MultiminObjectiveWrapper(const gsl_vector* x, void* params) {
double objective;
reinterpret_cast<Optimizer*>(params)->MultiminObjectiveGradient(x, &objective, NULL);
return objective;
}
static void MultiminGradientWrapper(const gsl_vector* x, void* params, gsl_vector* g) {
reinterpret_cast<Optimizer*>(params)->MultiminObjectiveGradient(x, NULL, g);
}
static void MultiminObjectiveGradientWrapper(const gsl_vector* x,
void* params,
double* f,
gsl_vector* g) {
reinterpret_cast<Optimizer*>(params)->MultiminObjectiveGradient(x, f, g);
}
private:
size_t size_;
};
#endif // __LIB_MATH_OPTIMIZER__
| {
"alphanum_fraction": 0.6812169312,
"avg_line_length": 29.9405940594,
"ext": "h",
"hexsha": "3a948fb84c15b239fbc2d0a36badc065ff86a421",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-11-27T01:35:33.000Z",
"max_forks_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "boomsbloom/dtm-fmri",
"max_forks_repo_path": "DTM/dtm-master/lib/math/optimizer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"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": "boomsbloom/dtm-fmri",
"max_issues_repo_path": "DTM/dtm-master/lib/math/optimizer.h",
"max_line_length": 89,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "159aab87f04b745d874b53f64fd30703b4d5a70c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "boomsbloom/dtm-fmri",
"max_stars_repo_path": "DTM/dtm-master/lib/math/optimizer.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-27T01:17:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-27T01:35:30.000Z",
"num_tokens": 783,
"size": 3024
} |
/**
*
* @file testing_dgemm.c
*
* PLASMA testing routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Emmanuel Agullo
* @author Mathieu Faverge
* @date 2010-11-15
* @generated d Tue Jan 7 11:45:18 2014
*
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <plasma.h>
#include <cblas.h>
#include <lapacke.h>
#include <core_blas.h>
#include "testing_dmain.h"
#undef COMPLEX
#define REAL
static int check_solution(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K,
double alpha, double *A, int LDA,
double *B, int LDB,
double beta, double *Cref, double *Cplasma, int LDC);
int testing_dgemm(int argc, char **argv)
{
/* Check for number of arguments*/
if ( argc != 8) {
USAGE("GEMM", "alpha beta M N K LDA LDB LDC",
" - alpha : alpha coefficient\n"
" - beta : beta coefficient\n"
" - M : number of rows of matrices A and C\n"
" - N : number of columns of matrices B and C\n"
" - K : number of columns of matrix A / number of rows of matrix B\n"
" - LDA : leading dimension of matrix A\n"
" - LDB : leading dimension of matrix B\n"
" - LDC : leading dimension of matrix C\n");
return -1;
}
PLASMA_Set(PLASMA_TILE_SIZE, 128);
double alpha = (double) atol(argv[0]);
double beta = (double) atol(argv[1]);
int M = atoi(argv[2]);
int N = atoi(argv[3]);
int K = atoi(argv[4]);
int LDA = atoi(argv[5]);
int LDB = atoi(argv[6]);
int LDC = atoi(argv[7]);
double eps;
int info_solution;
int i, j, ta, tb;
int LDAxK = LDA*max(M,K);
int LDBxN = LDB*max(K,N);
int LDCxN = LDC*N;
double *A = (double *)malloc(LDAxK*sizeof(double));
#pragma omp register( [LDAxK]A )
double *B = (double *)malloc(LDBxN*sizeof(double));
#pragma omp register( [LDBxN]B )
double *C = (double *)malloc(LDCxN*sizeof(double));
#pragma omp register( [LDCxN]C )
double *Cinit = (double *)malloc(LDCxN*sizeof(double));
#pragma omp register( [LDCxN]Cinit )
double *Cfinal = (double *)malloc(LDCxN*sizeof(double));
#pragma omp register( [LDCxN]Cfinal )
/* Check if unable to allocate memory */
if ((!A)||(!B)||(!Cinit)||(!Cfinal)){
printf("Out of Memory \n ");
return -2;
}
eps = LAPACKE_dlamch_work('e');
printf("\n");
printf("------ TESTS FOR PLASMA DGEMM ROUTINE ------- \n");
printf(" Size of the Matrix %d by %d\n", M, N);
printf("\n");
printf(" The matrix A is randomly generated for each test.\n");
printf("============\n");
printf(" The relative machine precision (eps) is to be %e \n",eps);
printf(" Computational tests pass if scaled residuals are less than 10.\n");
/*----------------------------------------------------------
* TESTING DGEMM
*/
/* Initialize A, B, C */
LAPACKE_dlarnv_work(IONE, ISEED, LDAxK, A);
LAPACKE_dlarnv_work(IONE, ISEED, LDBxN, B);
LAPACKE_dlarnv_work(IONE, ISEED, LDCxN, C);
#ifdef COMPLEX
for (ta=0; ta<3; ta++) {
for (tb=0; tb<3; tb++) {
#else
for (ta=0; ta<2; ta++) {
for (tb=0; tb<2; tb++) {
#endif
for ( i = 0; i < M; i++)
for ( j = 0; j < N; j++)
Cinit[LDC*j+i] = C[LDC*j+i];
for ( i = 0; i < M; i++)
for ( j = 0; j < N; j++)
Cfinal[LDC*j+i] = C[LDC*j+i];
/* PLASMA DGEMM */
PLASMA_dgemm(trans[ta], trans[tb], M, N, K, alpha, A, LDA, B, LDB, beta, Cfinal, LDC);
/* Check the solution */
info_solution = check_solution(trans[ta], trans[tb], M, N, K,
alpha, A, LDA, B, LDB, beta, Cinit, Cfinal, LDC);
if (info_solution == 0) {
printf("***************************************************\n");
printf(" ---- TESTING DGEMM (%s, %s) ............... PASSED !\n", transstr[ta], transstr[tb]);
printf("***************************************************\n");
}
else {
printf("************************************************\n");
printf(" - TESTING DGEMM (%s, %s) ... FAILED !\n", transstr[ta], transstr[tb]);
printf("************************************************\n");
}
}
}
#ifdef _UNUSED_
}}
#endif
free(A); free(B); free(C);
free(Cinit); free(Cfinal);
return 0;
}
/*--------------------------------------------------------------
* Check the solution
*/
static int check_solution(PLASMA_enum transA, PLASMA_enum transB, int M, int N, int K,
double alpha, double *A, int LDA,
double *B, int LDB,
double beta, double *Cref, double *Cplasma, int LDC)
{
int info_solution;
double Anorm, Bnorm, Cinitnorm, Cplasmanorm, Clapacknorm, Rnorm, result;
double eps;
double beta_const;
double *work = (double *)malloc(max(K,max(M, N))* sizeof(double));
int Am, An, Bm, Bn;
beta_const = -1.0;
if (transA == PlasmaNoTrans) {
Am = M; An = K;
} else {
Am = K; An = M;
}
if (transB == PlasmaNoTrans) {
Bm = K; Bn = N;
} else {
Bm = N; Bn = K;
}
Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), Am, An, A, LDA, work);
Bnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), Bm, Bn, B, LDB, work);
Cinitnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work);
Cplasmanorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cplasma, LDC, work);
cblas_dgemm(CblasColMajor, (CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB, M, N, K,
(alpha), A, LDA, B, LDB, (beta), Cref, LDC);
Clapacknorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work);
cblas_daxpy(LDC * N, (beta_const), Cplasma, 1, Cref, 1);
Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, Cref, LDC, work);
eps = LAPACKE_dlamch_work('e');
printf("Rnorm %e, Anorm %e, Bnorm %e, Cinitnorm %e, Cplasmanorm %e, Clapacknorm %e\n",
Rnorm, Anorm, Bnorm, Cinitnorm, Cplasmanorm, Clapacknorm);
result = Rnorm / ((Anorm + Bnorm + Cinitnorm) * N * eps);
printf("============\n");
printf("Checking the norm of the difference against reference DGEMM \n");
printf("-- ||Cplasma - Clapack||_oo/((||A||_oo+||B||_oo+||C||_oo).N.eps) = %e \n",
result);
if ( isnan(Rnorm) || isinf(Rnorm) || isnan(result) || isinf(result) || (result > 10.0) ) {
printf("-- The solution is suspicious ! \n");
info_solution = 1;
}
else {
printf("-- The solution is CORRECT ! \n");
info_solution= 0 ;
}
free(work);
return info_solution;
}
int timing_dgemm(int argc, char **argv)
{
int transa; int transb;
int m, n, k;
double alpha, beta;
int lda, ldb, ldc;
double *A, *B, *C;
double *C0;
int bs, rep;
int i;
double start, end;
double elapsed;
FILE *log;
int num_threads;
//gemm transA, transB, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc
if (argc != 12) {
fprintf(stderr, "GEMMs transa transb m n k alpha lda ldb beta ldc bs rep\n");
return 1;;
}
sscanf(argv[0], "%d", &transa);
sscanf(argv[1], "%d", &transb);
if ( !transa )
transa = PlasmaNoTrans;
else
transa = PlasmaTrans;
if ( !transb )
transb = PlasmaNoTrans;
else
transb = PlasmaTrans;
sscanf(argv[2], "%d", &m);
sscanf(argv[3], "%d", &n);
sscanf(argv[4], "%d", &k);
sscanf(argv[5], "%lf", &alpha);
sscanf(argv[6], "%d", &lda);
sscanf(argv[7], "%d", &ldb);
sscanf(argv[8], "%lf", &beta);
sscanf(argv[9], "%d", &ldc);
sscanf(argv[10], "%d", &bs);
sscanf(argv[11], "%d", &rep);
int dimA = max(m,k) * lda;
int dimB = max(n,k) * ldb;
int dimC = max(m,n) * ldc;
A = malloc( dimA * sizeof(double));
#pragma omp register ([dimA]A)
B = malloc( dimB * sizeof(double));
#pragma omp register ([dimB]B)
C = malloc( dimC * sizeof(double));
#pragma omp register ([dimC]C)
LAPACKE_dlarnv(IONE, ISEED, dimA, A);
LAPACKE_dlarnv(IONE, ISEED, dimB, B);
LAPACKE_dlarnv(IONE, ISEED, dimC, C);
PLASMA_Set( PLASMA_TILE_SIZE, bs);
elapsed = 0.0;
for ( i = 0; i < rep; i++ ) {
start = gtime();
PLASMA_dgemm(transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
end = gtime();
elapsed += end - start;
}
num_threads = omp_get_max_threads();
dump_info("plasma_dgemm.log", num_threads, elapsed, rep);
free(A); free(B); free(C);
return 0;
}
| {
"alphanum_fraction": 0.5354348066,
"avg_line_length": 31.0719178082,
"ext": "c",
"hexsha": "e4f850b553d8257dad686fbc5fb910818c61b31b",
"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": "testing/testing_dgemm.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": "testing/testing_dgemm.c",
"max_line_length": 113,
"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": "testing/testing_dgemm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2839,
"size": 9073
} |
#ifndef S3DCV_DEMO_DEMO_UTILS_H
#define S3DCV_DEMO_DEMO_UTILS_H
#include <s3d/cv/disparity/disparity_analyzer_stan.h>
#include <gsl/gsl>
class BadNumberOfArgumentsException {};
class FileNotFoundException {};
/**
* Creates dataset loader from program input arguments.
*
* First input argument must be the dataset folder, e.g. 'Arch'
* Second input argument must be the dataset path e.g. '/home/you/dataset'
*
*/
inline DatasetLoaderVSG createDatasetLoader(int argc, char* argv[]) {
auto input_args = gsl::span<char*>(argv, argc);
if (input_args.size() != 3) {
throw BadNumberOfArgumentsException{};
}
const std::string datasetName = input_args[1];
const std::string datasetPath = input_args[2];
return DatasetLoaderVSG{datasetName, datasetPath};
}
inline s3d::robust::Lmeds<s3d::StanFundamentalMatrixSolver, s3d::SampsonDistanceFunction> createRansac(
s3d::Size imageSize) {
int h = imageSize.getHeight();
int w = imageSize.getWidth();
s3d::robust::Parameters params;
params.nbTrials = 500;
params.distanceThreshold = 0.01 * sqrt(h * h + w * w);
return s3d::DisparityAnalyzerSTAN::RansacAlgorithmSTAN(params);
}
#endif //S3DCV_DEMO_DEMO_UTILS_H
| {
"alphanum_fraction": 0.7391304348,
"avg_line_length": 28.4761904762,
"ext": "h",
"hexsha": "ae48d02da5524e69279c5e95f1ef2c78b417a265",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z",
"max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "hugbed/OpenS3D",
"max_forks_repo_path": "src/apps/S3DCVDemo/include/demo_utils.h",
"max_issues_count": 40,
"max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "hugbed/OpenS3D",
"max_issues_repo_path": "src/apps/S3DCVDemo/include/demo_utils.h",
"max_line_length": 103,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "hugbed/OpenS3D",
"max_stars_repo_path": "src/apps/S3DCVDemo/include/demo_utils.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z",
"num_tokens": 328,
"size": 1196
} |
#pragma once
#include <stdio.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_gamma.h>
typedef unsigned int uint;
typedef struct{
double mu;
double sigma;
} Gauss_params;
void Gauss_params_print( Gauss_params params );
void GSLfun_setup();
double GSLfun_ran_beta( double a, double b );
double GSLfun_ran_beta_Jeffreys();
uint GSLfun_ran_binomial( double p, uint n );
double GSLfun_ran_gamma( double a, double theta );
double GSLfun_ran_gaussian( Gauss_params params );
double GSLfun_ran_gaussian_pdf( double x, Gauss_params params );
double gsl_ran_flat01();
| {
"alphanum_fraction": 0.7678855326,
"avg_line_length": 21.6896551724,
"ext": "h",
"hexsha": "e9a3c06736151b5dac377836f656debacfc863b1",
"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": "02cfdcd2c56b11c5c2c31cc7e538815ab84225ab",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Kelvinthedrugger/Gaussian_Mix_model",
"max_forks_repo_path": "gauss/GSLfun.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "02cfdcd2c56b11c5c2c31cc7e538815ab84225ab",
"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": "Kelvinthedrugger/Gaussian_Mix_model",
"max_issues_repo_path": "gauss/GSLfun.h",
"max_line_length": 64,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "02cfdcd2c56b11c5c2c31cc7e538815ab84225ab",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Kelvinthedrugger/Gaussian_Mix_model",
"max_stars_repo_path": "gauss/GSLfun.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 170,
"size": 629
} |
/* psl.c
////
Provide a library of gsl functions.
Features:
- request calculation via message
- function lookup
- inlets-on-demand
Author: shakfu
Repo: https://github.com/shakfu/pd-psl.git
*/
#include <math.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_sf_airy.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_sf_clausen.h>
#include <gsl/gsl_sf_dawson.h>
#include <gsl/gsl_sf_debye.h>
#include "m_pd.h"
#include "tinyexpr.h"
// macros and defines
// ---------------------------------------------------------------------------
#define MAX_ARGS 6
#define STR_BUF_SIZE 1000
// function lookup infratructure
// ---------------------------------------------------------------------------
unsigned long hash(const char *str) {
unsigned int h = 0;
int c;
while ((c = *str++))
h += (h << 1) + c;
return h;
}
enum FUNC {
ADD = 1273,
LOG1P = 12931,
EXPM1 = 12805,
HYPOT = 13148,
HYPOT3 = 39495,
ACOSH = 11978,
ASINH = 12341,
ATANH = 12296,
LDEXP = 12829,
POW_INT = 122216,
POW_2 = 13475,
POW_3 = 13476,
POW_4 = 13477,
POW_5 = 13478,
POW_6 = 13479,
POW_7 = 13480,
POW_8 = 13481,
POW_9 = 13482,
RANDO = 13254,
FCMP = 4084,
AIRY_AI = 109980,
AIRY_BI = 109983,
BESSEL_J0 = 987963,
BESSEL_J1 = 987964,
BESSEL_JN = 988025,
BESSEL_Y0 = 988008,
BESSEL_Y1 = 988009,
BESSEL_YN = 988070,
BESSEL_I0 = 987960,
BESSEL_I1 = 987961,
BESSEL_IN = 988022,
CLAUSEN = 110879,
DAWSON = 36848,
DEBYE_1 = 109891,
DEBYE_2 = 109892,
DEBYE_3 = 109893,
DEBYE_4 = 109894,
};
// forward declarations / prototypes
// ---------------------------------------------------------------------------
typedef struct _psl t_psl;
void select_default_function(t_psl *x, t_symbol *s);
// psl class objects
// ---------------------------------------------------------------------------
static t_class *psl_class;
static t_class *psl_inlet_class;
// psl class struct (data-space)
// ---------------------------------------------------------------------------
typedef void (*unary_func)(t_psl *, t_floatarg);
typedef void (*binary_func)(t_psl *, t_floatarg, t_floatarg);
typedef void (*tri_func)(t_psl *, t_floatarg, t_floatarg, t_floatarg);
typedef struct _psl_inlet
{
t_class *x_pd; // minimal pd object.
t_psl *owner; // the owning object to forward inlet messages to.
int id; // the number of this inlet.
} t_psl_inlet;
typedef struct _psl {
t_object x_obj;
// assigned function
t_symbol *func_name;
int nargs;
// function slots
unary_func ufunc;
binary_func bfunc;
tri_func tfunc;
// param_array
t_float *arg_array;
// for expression
char expr_buffer[MAXPDSTRING];
// inlets
int inlets; // # of extra inlets in addition to default
t_psl_inlet *ins; // the inlets themselves
// outlets
t_outlet *out_f;
} t_psl;
// psl class methods (operation-space)
// ---------------------------------------------------------------------------
// typed-methods
void psl_bang(t_psl *x) {
if (x->nargs == 1 && x->inlets == 0) {
x->ufunc(x, x->arg_array[0]);
}
if (x->nargs == 2 && x->inlets == 1) {
x->bfunc(x, x->arg_array[0], x->arg_array[1]);
}
if (x->nargs == 3 && x->inlets == 2) {
x->tfunc(x, x->arg_array[0], x->arg_array[1], x->arg_array[2]);
}
}
void psl_float(t_psl *x, t_floatarg f) {
post("psl_float: %f", f);
if (x->nargs > 0) {
x->arg_array[0] = f;
psl_bang(x);
} else {
post("nothing to do: no function selected.");
outlet_float(x->out_f, f);
}
}
void psl_list(t_psl *x, t_symbol *s, int argc, t_atom *argv) {
// atom_post("psl_list: ", argc, argv);
if (s == gensym("list")) {
post("s: list");
if (argc == 0) {
return;
}
if (argc == 1) {
if (argv->a_type == A_FLOAT) {
float f = atom_getfloat(argv);
post("got float: %f", f);
x->ufunc(x, f);
return;
}
}
if (argc == 2) {
char buf[STR_BUF_SIZE];
for (int i = 0; i < argc; i++) {
atom_string((argv+i), buf, STR_BUF_SIZE);
post("arg+%i: %s", i, buf);
}
if (argv->a_type == A_FLOAT && (argv + 1)->a_type == A_FLOAT) {
float f1 = atom_getfloat(argv+0);
float f2 = atom_getfloat(argv+1);
post("f(%.2f, %.2f)", f1, f2);
x->bfunc(x, f1, f2);
return;
}
}
if (argc == 3) {
char buf[STR_BUF_SIZE];
for (int i = 0; i < argc; i++) {
atom_string((argv+i), buf, STR_BUF_SIZE);
post("arg+%i: %s", i, buf);
}
if (argv->a_type == A_FLOAT && (argv+1)->a_type == A_FLOAT && (argv+2)->a_type == A_FLOAT) {
float f1 = atom_getfloat(argv+0);
float f2 = atom_getfloat(argv+1);
float f3 = atom_getfloat(argv+2);
post("f(%.2f, %.2f, %.2f)", f1, f2, f3);
x->tfunc(x, f1, f2, f3);
return;
}
}
}
post("list body");
return;
// error:
// pd_error(x, "psl_list error: incorrect arg type");
}
void psl_symbol(t_psl *x, t_symbol *s) {
post("s: %s", s->s_name);
// local buffer
int length = strlen(s->s_name);
char *buf = (char *)malloc(length * sizeof(char));
strcpy(buf, s->s_name);
post("buf: %s", buf);
// clear expr_buffer
memset(x->expr_buffer, 0, MAXPDSTRING);
int j = 0;
for (int i = 0; i < length; i++) {
// remove escape `\` required for commas
if (buf[i] != '\\') {
x->expr_buffer[j++] = buf[i];
} else if (x->expr_buffer[j - 1] == ' ') {
j--;
}
}
x->expr_buffer[length] = '\0';
free(buf);
post("x->expr_buffer: %s", x->expr_buffer);
te_variable vars[] = {
{"hypot", gsl_hypot, TE_FUNCTION2, NULL} /* TE_FUNCTION2 used because my_sum takes two arguments. */
};
te_expr *expr = te_compile(x->expr_buffer, vars, 2, 0);
const double res = te_eval(expr);
te_free(expr);
outlet_float(x->out_f, res);
}
// message-methods
void psl_add(t_psl *x, t_floatarg f1, t_floatarg f2) {
outlet_float(x->out_f, f1+f2);
}
void psl_rando(t_psl *x, t_floatarg n, t_floatarg seed) {
post("rando: n:%.2f seed:%.2f", n, seed);
gsl_rng_env_setup();
int argc = (int)n;
int _seed = (int)seed;
gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937);
gsl_rng_set(r, _seed);
t_atom av[argc];
for (int i = 0; i < argc; i++) {
SETFLOAT(av + i, gsl_rng_uniform(r));
}
outlet_list(x->out_f, gensym("list"), argc, av);
gsl_rng_free(r);
}
void psl_airy_ai(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_airy_Ai(f, GSL_PREC_APPROX));
}
void psl_airy_bi(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_airy_Bi(f, GSL_PREC_APPROX));
}
void psl_log1p(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_log1p(f));
}
void psl_expm1(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_expm1(f));
}
void psl_hypot(t_psl *x, t_floatarg f1, t_floatarg f2) {
outlet_float(x->out_f, gsl_hypot(f1, f2));
}
void psl_hypot3(t_psl *x, t_floatarg f1, t_floatarg f2, t_floatarg f3) {
outlet_float(x->out_f, gsl_hypot3(f1, f2, f3));
}
void psl_acosh(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_acosh(f));
}
void psl_asinh(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_asinh(f));
}
void psl_atanh(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_atanh(f));
}
void psl_ldexp(t_psl *x, t_floatarg f1, t_floatarg f2) {
outlet_float(x->out_f, gsl_ldexp(f1, f2));
}
void psl_pow_int(t_psl *x, t_floatarg f1, t_floatarg f2) {
outlet_float(x->out_f, gsl_pow_int(f1, f2));
}
void psl_pow_2(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_pow_2(f));
}
void psl_pow_3(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_pow_3(f));
}
void psl_pow_4(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_pow_4(f));
}
void psl_pow_5(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_pow_5(f));
}
void psl_pow_6(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_pow_6(f));
}
void psl_pow_7(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_pow_7(f));
}
void psl_pow_8(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_pow_8(f));
}
void psl_pow_9(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_pow_9(f));
}
void psl_fcmp(t_psl *x, t_floatarg f1, t_floatarg f2, t_floatarg f3) {
outlet_float(x->out_f, gsl_fcmp(f1, f2, f3));
}
void psl_bessel_j0(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_bessel_J0(f));
}
void psl_bessel_j1(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_bessel_J1(f));
}
void psl_bessel_jn(t_psl *x, t_floatarg f1, t_floatarg f2) {
outlet_float(x->out_f, gsl_sf_bessel_Jn(f1, f2));
}
void psl_bessel_y0(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_bessel_Y0(f));
}
void psl_bessel_y1(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_bessel_Y1(f));
}
void psl_bessel_yn(t_psl *x, t_floatarg f1, t_floatarg f2) {
outlet_float(x->out_f, gsl_sf_bessel_Yn(f1, f2));
}
void psl_bessel_i0(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_bessel_I0(f));
}
void psl_bessel_i1(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_bessel_I1(f));
}
void psl_bessel_in(t_psl *x, t_floatarg f1, t_floatarg f2) {
outlet_float(x->out_f, gsl_sf_bessel_In(f1, f2));
}
void psl_clausen(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_clausen(f));
}
void psl_dawson(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_dawson(f));
}
void psl_debye_1(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_debye_1(f));
}
void psl_debye_2(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_debye_2(f));
}
void psl_debye_3(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_debye_3(f));
}
void psl_debye_4(t_psl *x, t_floatarg f) {
outlet_float(x->out_f, gsl_sf_debye_4(f));
}
// function selection
//---------------------------------------------------------------------------
// set default function from symbol
void select_default_function(t_psl *x, t_symbol *s) {
x->func_name = s;
post("func %s selected", s->s_name);
switch (hash(s->s_name)) {
case ADD:
x->nargs = 2;
x->bfunc = &psl_add;
break;
case LOG1P:
x->nargs = 1;
x->ufunc = &psl_log1p;
break;
case EXPM1:
x->nargs = 1;
x->ufunc = &psl_expm1;
break;
case HYPOT:
x->nargs = 2;
x->bfunc = &psl_hypot;
break;
case HYPOT3:
x->nargs = 3;
x->tfunc = &psl_hypot3;
break;
case ACOSH:
x->nargs = 1;
x->ufunc = &psl_acosh;
break;
case ASINH:
x->nargs = 1;
x->ufunc = &psl_asinh;
break;
case ATANH:
x->nargs = 1;
x->ufunc = &psl_atanh;
break;
case LDEXP:
x->nargs = 2;
x->bfunc = &psl_ldexp;
break;
case POW_INT:
x->nargs = 2;
x->bfunc = &psl_pow_int;
break;
case POW_2:
x->nargs = 1;
x->ufunc = &psl_pow_2;
break;
case POW_3:
x->nargs = 1;
x->ufunc = &psl_pow_3;
break;
case POW_4:
x->nargs = 1;
x->ufunc = &psl_pow_4;
break;
case POW_5:
x->nargs = 1;
x->ufunc = &psl_pow_5;
break;
case POW_6:
x->nargs = 1;
x->ufunc = &psl_pow_6;
break;
case POW_7:
x->nargs = 1;
x->ufunc = &psl_pow_7;
break;
case POW_8:
x->nargs = 1;
x->ufunc = &psl_pow_8;
break;
case POW_9:
x->nargs = 1;
x->ufunc = &psl_pow_9;
break;
case RANDO:
x->nargs = 2;
x->bfunc = &psl_rando;
break;
case FCMP:
x->nargs = 3;
x->tfunc = &psl_fcmp;
break;
case AIRY_AI:
x->nargs = 1;
x->ufunc = &psl_airy_ai;
break;
case AIRY_BI:
x->nargs = 1;
x->ufunc = &psl_airy_bi;
break;
case BESSEL_J0:
x->nargs = 1;
x->ufunc = &psl_bessel_j0;
break;
case BESSEL_J1:
x->nargs = 1;
x->ufunc = &psl_bessel_j1;
break;
case BESSEL_JN:
x->nargs = 2;
x->bfunc = &psl_bessel_jn;
break;
case BESSEL_Y0:
x->nargs = 1;
x->ufunc = &psl_bessel_y0;
break;
case BESSEL_Y1:
x->nargs = 1;
x->ufunc = &psl_bessel_y1;
break;
case BESSEL_YN:
x->nargs = 2;
x->bfunc = &psl_bessel_yn;
break;
case BESSEL_I0:
x->nargs = 1;
x->ufunc = &psl_bessel_i0;
break;
case BESSEL_I1:
x->nargs = 1;
x->ufunc = &psl_bessel_i1;
break;
case BESSEL_IN:
x->nargs = 2;
x->bfunc = &psl_bessel_in;
break;
case CLAUSEN:
x->nargs = 1;
x->ufunc = &psl_clausen;
break;
case DAWSON:
x->nargs = 1;
x->ufunc = &psl_dawson;
break;
case DEBYE_1:
x->nargs = 1;
x->ufunc = &psl_debye_1;
break;
case DEBYE_2:
x->nargs = 1;
x->ufunc = &psl_debye_2;
break;
case DEBYE_3:
x->nargs = 1;
x->ufunc = &psl_debye_3;
break;
case DEBYE_4:
x->nargs = 1;
x->ufunc = &psl_debye_4;
break;
default:
post("func selection failed, reverting to defaults");
break;
}
}
// psl-inlet funcs
// ---------------------------------------------------------------------------
static void psl_inlet_float(t_psl_inlet *x, float f)
{
x->owner->arg_array[x->id+1] = f;
// outlet_float(x->owner->out_f, x->id + f);
post("x->owner->arg_array[x->id]: %.02f", x->owner->arg_array[x->id+1]);
psl_bang(x->owner);
}
// psl class constructor
// ---------------------------------------------------------------------------
void *psl_new(t_symbol *s) {
t_psl *x = (t_psl *)pd_new(psl_class);
// initialize variables
x->nargs = 0;
x->inlets = 0;
x->ufunc = NULL;
x->bfunc = NULL;
x->tfunc = NULL;
select_default_function(x, s);
// sets x->nargs to correct number
// create inlets
x->inlets = x->nargs - 1;
x->ins = (t_psl_inlet *)getbytes(x->inlets * sizeof(*x->ins));
x->arg_array = malloc(x->inlets * sizeof(float));
for (int i=0; i < x->inlets; i++) {
x->ins[i].x_pd = psl_inlet_class;
x->ins[i].owner = x;
x->ins[i].id = i;
x->arg_array[i] = 0.0;
inlet_new((t_object *)x, &(x->ins[i].x_pd), 0, 0);
}
// initialize outlets
x->out_f = outlet_new(&x->x_obj, &s_float);
return (void *)x;
}
// psl class destructor
// ---------------------------------------------------------------------------
// TODO: not sure if this is correct!
void psl_free(t_psl *x) {
free(x->arg_array);
freebytes(x->ins, x->inlets * sizeof(*x->ins));
post("DONE");
}
// psl class setup
// ---------------------------------------------------------------------------
void psl_setup(void) {
psl_inlet_class = class_new(gensym("psl-inlet"),
0, 0,
sizeof(t_psl_inlet),
CLASS_PD,
0);
if (psl_inlet_class) {
class_addfloat(psl_inlet_class, (t_method)psl_inlet_float);
}
psl_class = class_new(gensym("psl"),
(t_newmethod)psl_new,
(t_method)psl_free, // destructor
sizeof(t_psl),
CLASS_DEFAULT,
A_DEFSYMBOL,
0);
// typed methods
class_addbang(psl_class, psl_bang);
class_addfloat(psl_class, psl_float);
class_addlist(psl_class, psl_list);
class_addsymbol(psl_class, psl_symbol);
// message methods
// class-addmethods
class_addmethod(psl_class, (t_method)psl_add, gensym("add"), A_DEFFLOAT, A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_log1p, gensym("log1p"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_expm1, gensym("expm1"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_hypot, gensym("hypot"), A_DEFFLOAT, A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_hypot3, gensym("hypot3"), A_DEFFLOAT, A_DEFFLOAT, A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_acosh, gensym("acosh"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_asinh, gensym("asinh"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_atanh, gensym("atanh"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_ldexp, gensym("ldexp"), A_DEFFLOAT, A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_pow_int, gensym("pow_int"), A_DEFFLOAT, A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_pow_2, gensym("pow_2"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_pow_3, gensym("pow_3"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_pow_4, gensym("pow_4"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_pow_5, gensym("pow_5"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_pow_6, gensym("pow_6"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_pow_7, gensym("pow_7"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_pow_8, gensym("pow_8"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_pow_9, gensym("pow_9"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_rando, gensym("rando"), A_DEFFLOAT, A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_fcmp, gensym("fcmp"), A_DEFFLOAT, A_DEFFLOAT, A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_airy_ai, gensym("airy_ai"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_airy_bi, gensym("airy_bi"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_bessel_j0, gensym("bessel_j0"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_bessel_j1, gensym("bessel_j1"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_bessel_jn, gensym("bessel_jn"), A_DEFFLOAT, A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_bessel_y0, gensym("bessel_y0"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_bessel_y1, gensym("bessel_y1"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_bessel_yn, gensym("bessel_yn"), A_DEFFLOAT, A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_bessel_i0, gensym("bessel_i0"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_bessel_i1, gensym("bessel_i1"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_bessel_in, gensym("bessel_in"), A_DEFFLOAT, A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_clausen, gensym("clausen"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_dawson, gensym("dawson"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_debye_1, gensym("debye_1"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_debye_2, gensym("debye_2"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_debye_3, gensym("debye_3"), A_DEFFLOAT, 0);
class_addmethod(psl_class, (t_method)psl_debye_4, gensym("debye_4"), A_DEFFLOAT, 0);
// create alias
class_addcreator((t_newmethod)psl_new, gensym("gsl"), A_DEFSYMBOL, 0);
// set name of default help file
class_sethelpsymbol(psl_class, gensym("help-psl"));
}
| {
"alphanum_fraction": 0.5490394338,
"avg_line_length": 27.2559055118,
"ext": "c",
"hexsha": "fe82b88a1e62f24b546326863d7cf063fa473332",
"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": "7efdc298dcd249eda11921edc4b52a004150d5ad",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "shakfu/pd-psl",
"max_forks_repo_path": "psl.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "shakfu/pd-psl",
"max_issues_repo_path": "psl.c",
"max_line_length": 111,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7efdc298dcd249eda11921edc4b52a004150d5ad",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "shakfu/pd-psl",
"max_stars_repo_path": "psl.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6749,
"size": 20769
} |
/* multifit_nlinear/mcholesky.c
*
* Copyright (C) 2015, 2016 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 module calculates the solution of the normal equations least squares
* system:
*
* [ J~^T J~ + mu D~^T D~ ] p~ = -J~^T f
*
* using the modified Cholesky decomposition. Quantities are scaled
* according to:
*
* J~ = J S
* D~ = D S
* p~ = S^{-1} p
*
* where S is a diagonal matrix and S_jj = || J_j || and J_j is column
* j of the Jacobian. This balancing transformation seems to be more
* numerically stable for some Jacobians.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_multifit_nlinear.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_permutation.h>
#include "common.c"
typedef struct
{
gsl_matrix *JTJ; /* J^T J */
gsl_matrix *work_JTJ; /* copy of J^T J */
gsl_vector *rhs; /* -J^T f, size p */
gsl_permutation *perm; /* permutation matrix for modified Cholesky */
gsl_vector *work3p; /* workspace, size 3*p */
double mu; /* current regularization parameter */
} mcholesky_state_t;
static void *mcholesky_alloc (const size_t n, const size_t p);
static int mcholesky_init(const void * vtrust_state, void * vstate);
static int mcholesky_presolve(const double mu, const void * vtrust_state, void * vstate);
static int mcholesky_solve(const gsl_vector * f, gsl_vector *x,
const void * vtrust_state, void *vstate);
static int mcholesky_solve_rhs(const gsl_vector * b, gsl_vector *x, mcholesky_state_t *state);
static int mcholesky_regularize(const double mu, const gsl_vector * diag, gsl_matrix * A,
mcholesky_state_t * state);
static void *
mcholesky_alloc (const size_t n, const size_t p)
{
mcholesky_state_t *state;
(void)n;
state = calloc(1, sizeof(mcholesky_state_t));
if (state == NULL)
{
GSL_ERROR_NULL ("failed to allocate mcholesky state", GSL_ENOMEM);
}
state->JTJ = gsl_matrix_alloc(p, p);
if (state->JTJ == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for JTJ", GSL_ENOMEM);
}
state->work_JTJ = gsl_matrix_alloc(p, p);
if (state->work_JTJ == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for JTJ workspace",
GSL_ENOMEM);
}
state->rhs = gsl_vector_alloc(p);
if (state->rhs == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for rhs", GSL_ENOMEM);
}
state->perm = gsl_permutation_alloc(p);
if (state->perm == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for perm", GSL_ENOMEM);
}
state->work3p = gsl_vector_alloc(3 * p);
if (state->work3p == NULL)
{
GSL_ERROR_NULL ("failed to allocate space for work3p", GSL_ENOMEM);
}
state->mu = -1.0;
return state;
}
static void
mcholesky_free(void *vstate)
{
mcholesky_state_t *state = (mcholesky_state_t *) vstate;
if (state->JTJ)
gsl_matrix_free(state->JTJ);
if (state->work_JTJ)
gsl_matrix_free(state->work_JTJ);
if (state->rhs)
gsl_vector_free(state->rhs);
if (state->perm)
gsl_permutation_free(state->perm);
if (state->work3p)
gsl_vector_free(state->work3p);
free(state);
}
static int
mcholesky_init(const void * vtrust_state, void * vstate)
{
const gsl_multifit_nlinear_trust_state *trust_state =
(const gsl_multifit_nlinear_trust_state *) vtrust_state;
mcholesky_state_t *state = (mcholesky_state_t *) vstate;
/* compute J^T J */
gsl_blas_dsyrk(CblasLower, CblasTrans, 1.0, trust_state->J, 0.0, state->JTJ);
return GSL_SUCCESS;
}
/*
mcholesky_presolve()
Compute the modified Cholesky decomposition of J^T J + mu D^T D.
Modified Cholesky is used in case mu = 0 and there are rounding
errors in forming J^T J which could lead to an indefinite matrix.
Inputs: mu - LM parameter
vstate - workspace
Notes:
1) On output, state->work_JTJ contains the Cholesky decomposition of
J^T J + mu D^T D
*/
static int
mcholesky_presolve(const double mu, const void * vtrust_state, void * vstate)
{
const gsl_multifit_nlinear_trust_state *trust_state =
(const gsl_multifit_nlinear_trust_state *) vtrust_state;
mcholesky_state_t *state = (mcholesky_state_t *) vstate;
gsl_matrix *JTJ = state->work_JTJ;
const gsl_vector *diag = trust_state->diag;
int status;
/* copy lower triangle of A to workspace */
gsl_matrix_tricpy(CblasLower, CblasNonUnit, JTJ, state->JTJ);
/* augment normal equations: A -> A + mu D^T D */
status = mcholesky_regularize(mu, diag, JTJ, state);
if (status)
return status;
/* compute modified Cholesky decomposition */
status = gsl_linalg_mcholesky_decomp(JTJ, state->perm, NULL);
if (status)
return status;
state->mu = mu;
return GSL_SUCCESS;
}
/*
mcholesky_solve()
Compute (J^T J + mu D^T D) x = -J^T f
Inputs: f - right hand side vector f
x - (output) solution vector
vstate - mcholesky workspace
*/
static int
mcholesky_solve(const gsl_vector * f, gsl_vector *x,
const void * vtrust_state, void *vstate)
{
const gsl_multifit_nlinear_trust_state *trust_state =
(const gsl_multifit_nlinear_trust_state *) vtrust_state;
mcholesky_state_t *state = (mcholesky_state_t *) vstate;
int status;
/* compute rhs = -J^T f */
gsl_blas_dgemv(CblasTrans, -1.0, trust_state->J, f, 0.0, state->rhs);
status = mcholesky_solve_rhs(state->rhs, x, state);
if (status)
return status;
return GSL_SUCCESS;
}
static int
mcholesky_rcond(double * rcond, void * vstate)
{
int status;
mcholesky_state_t *state = (mcholesky_state_t *) vstate;
double rcond_JTJ;
if (state->mu != 0)
{
/*
* Cholesky decomposition hasn't been computed yet, or was computed
* with mu > 0 - recompute Cholesky decomposition of J^T J
*/
/* copy lower triangle of JTJ to workspace */
gsl_matrix_tricpy(CblasLower, CblasNonUnit, state->work_JTJ, state->JTJ);
/* compute modified Cholesky decomposition */
status = gsl_linalg_mcholesky_decomp(state->work_JTJ, state->perm, NULL);
if (status)
return status;
}
status = gsl_linalg_mcholesky_rcond(state->work_JTJ, state->perm, &rcond_JTJ, state->work3p);
if (status == GSL_SUCCESS)
*rcond = sqrt(rcond_JTJ);
return status;
}
/* solve: (J^T J + mu D^T D) x = b */
static int
mcholesky_solve_rhs(const gsl_vector * b, gsl_vector *x, mcholesky_state_t *state)
{
int status;
gsl_matrix *JTJ = state->work_JTJ;
status = gsl_linalg_mcholesky_solve(JTJ, state->perm, b, x);
if (status)
return status;
return GSL_SUCCESS;
}
/* A <- A + mu D^T D */
static int
mcholesky_regularize(const double mu, const gsl_vector * diag, gsl_matrix * A,
mcholesky_state_t * state)
{
(void) state;
if (mu != 0.0)
{
size_t i;
for (i = 0; i < diag->size; ++i)
{
double di = gsl_vector_get(diag, i);
double *Aii = gsl_matrix_ptr(A, i, i);
*Aii += mu * di * di;
}
}
return GSL_SUCCESS;
}
static const gsl_multifit_nlinear_solver mcholesky_type =
{
"mcholesky",
mcholesky_alloc,
mcholesky_init,
mcholesky_presolve,
mcholesky_solve,
mcholesky_rcond,
mcholesky_free
};
const gsl_multifit_nlinear_solver *gsl_multifit_nlinear_solver_mcholesky = &mcholesky_type;
| {
"alphanum_fraction": 0.6772415483,
"avg_line_length": 27.0331125828,
"ext": "c",
"hexsha": "6f9d1b6a74af844503a7544e024b1142e1a36674",
"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/multifit_nlinear/mcholesky.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/multifit_nlinear/mcholesky.c",
"max_line_length": 95,
"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/multifit_nlinear/mcholesky.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": 2408,
"size": 8164
} |
#pragma once
#include <gsl/span>
#include "halley/core/api/audio_api.h"
#include "audio_buffer.h"
#if defined(_M_X64) || defined(__x86_64__)
#define HAS_SSE
#if !defined(__linux__)
#define HAS_AVX
#endif
#endif
#if defined(_M_IX86) || defined(__i386)
// Might not be available, but do we really care about such old processors?
#define HAS_SSE
#endif
namespace Halley
{
class AudioMixer
{
public:
virtual ~AudioMixer() {}
virtual void mixAudio(gsl::span<const AudioSamplePack> src, gsl::span<AudioSamplePack> dst, float gainStart, float gainEnd);
virtual void interleaveChannels(gsl::span<AudioSamplePack> dst, gsl::span<AudioBuffer*> src);
virtual void compressRange(gsl::span<AudioSamplePack> buffer);
static std::unique_ptr<AudioMixer> makeMixer();
};
}
| {
"alphanum_fraction": 0.7532299742,
"avg_line_length": 24.9677419355,
"ext": "h",
"hexsha": "2610a6677c681ac4e58f30f7a57a18fa0dd8c600",
"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": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "lye/halley",
"max_forks_repo_path": "src/engine/audio/src/audio_mixer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"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": "lye/halley",
"max_issues_repo_path": "src/engine/audio/src/audio_mixer.h",
"max_line_length": 126,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "lye/halley",
"max_stars_repo_path": "src/engine/audio/src/audio_mixer.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z",
"num_tokens": 208,
"size": 774
} |
#ifndef __asl234n0a2__LIBRARIES_H
#define __asl234n0a2__LIBRARIES_H
/* Standard libraries : */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <math.h>
/* wtf ? */
#include <fcntl.h>
#include <unistd.h>
#include <limits.h>
/* Sleeping-related */
#include <time.h>
#include <errno.h>
/* GNU Scientific library */
#include <gsl/gsl_rng.h>
/* Simple Direct Media layer (SDL) graphics: */
#include <SDL/SDL.h>
/* Locally defined */
/* Headers : */
#include "dynamics.h"
#include "simulation.h"
#include "display.h"
#include "parsing.h"
#include "aux_math.h"
#include "dev_random.h"
#include "mersenne_twister.h"
#include "singly_linked_list.h"
#include "datastructures.h"
#include "SDL_datastructure.h"
#include "visualization.h"
/* Constants and macros : */
#include "constants.h"
#include "probabilities.h"
#endif
| {
"alphanum_fraction": 0.6292481977,
"avg_line_length": 21.1086956522,
"ext": "h",
"hexsha": "e62eec81d9549e41d9a3e4fa7c2fcf490a45aea7",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-06-22T14:27:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-22T18:51:14.000Z",
"max_forks_repo_head_hexsha": "7174845b0614b6a20e48834d5a76579cfbf80bd6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gmagannaDevelop/TousAntiCovid",
"max_forks_repo_path": "src/libraries.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "7174845b0614b6a20e48834d5a76579cfbf80bd6",
"max_issues_repo_issues_event_max_datetime": "2021-01-17T11:51:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-25T16:51:13.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gmagannaDevelop/TousAntiCovid",
"max_issues_repo_path": "src/libraries.h",
"max_line_length": 49,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "7174845b0614b6a20e48834d5a76579cfbf80bd6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gmagannaDevelop/TousAntiCovid",
"max_stars_repo_path": "src/libraries.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-09T23:00:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-09T00:10:32.000Z",
"num_tokens": 282,
"size": 971
} |
/**
* Provides function to fit a polynomial curve to a set of data.
* Source: https://rosettacode.org/wiki/Polynomial_regression#C
*/
#ifndef _POLIFITGSL_H
#define _POLIFITGSL_H
#include <gsl/gsl_multifit.h>
#include <stdbool.h>
#include <math.h>
bool polynomialfit(int obs, int degree,
const double *dx, const double *dy, double *store); /* n, p */
#endif
| {
"alphanum_fraction": 0.7096774194,
"avg_line_length": 24.8,
"ext": "h",
"hexsha": "5a710de4ed08216e50c5940a042dec44acc8dcbb",
"lang": "C",
"max_forks_count": 15,
"max_forks_repo_forks_event_max_datetime": "2021-10-04T19:06:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-03-07T05:13:07.000Z",
"max_forks_repo_head_hexsha": "830ec0d00ee6018756330a0fcc7b9778c5cf903a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LaudateCorpus1/lane_detection",
"max_forks_repo_path": "src/polifitgsl.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "17747e85aff5fe10ceebf1bd91e03b1bd86ba0e7",
"max_issues_repo_issues_event_max_datetime": "2019-03-24T21:16:45.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-02-13T01:32:46.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Zippen-Huang/lane_detection-",
"max_issues_repo_path": "src/polifitgsl.h",
"max_line_length": 70,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "17747e85aff5fe10ceebf1bd91e03b1bd86ba0e7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Zippen-Huang/lane_detection-",
"max_stars_repo_path": "src/polifitgsl.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-12T14:43:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-06T19:05:06.000Z",
"num_tokens": 105,
"size": 372
} |
/* monte/gsl_monte_plain.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth
*
* 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.
*/
/* Plain Monte-Carlo. */
/* Author: MJB */
#ifndef __GSL_MONTE_PLAIN_H__
#define __GSL_MONTE_PLAIN_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdio.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_rng.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 dim;
double *x;
} gsl_monte_plain_state;
GSL_FUN int
gsl_monte_plain_integrate (const gsl_monte_function * f,
const double xl[], const double xu[],
const size_t dim,
const size_t calls,
gsl_rng * r,
gsl_monte_plain_state * state,
double *result, double *abserr);
GSL_FUN gsl_monte_plain_state* gsl_monte_plain_alloc(size_t dim);
GSL_FUN int gsl_monte_plain_init(gsl_monte_plain_state* state);
GSL_FUN void gsl_monte_plain_free (gsl_monte_plain_state* state);
__END_DECLS
#endif /* __GSL_MONTE_PLAIN_H__ */
| {
"alphanum_fraction": 0.6708633094,
"avg_line_length": 29.2631578947,
"ext": "h",
"hexsha": "d6203055fc77643c724d70c73a4f0549b75fc59a",
"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": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_monte_plain.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_monte_plain.h",
"max_line_length": 82,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "deps/include/gsl/gsl_monte_plain.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 543,
"size": 2224
} |
/*
** Test for irreducibility of a symmetric matrix R = X^T X,
** i.e. there is at least one positive off-diagonal entry in each row and column.
** Since R is symmetric, it suffices to show that each row has one non-negative entry.
** i.e. (X^TX v - v)_i > 0 for all i=0,...,n-1
** exclude main diagonal
**
** G.Lohmann, MPI-KYB, Nov 2018
*/
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <viaio/mu.h>
#include <viaio/option.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
extern void SignFlip(gsl_matrix_float *X);
/*
** if irreducible return 1, else return 0
*/
int Irreducible(gsl_matrix_float *X,int type)
{
size_t i;
size_t nvox = X->size1;
size_t nt = X->size2;
float u=0,tiny=1.0e-6;
/* ini */
gsl_vector_float *x = gsl_vector_float_calloc(nvox);
gsl_vector_float *y = gsl_vector_float_calloc(nvox);
gsl_vector_float *z = gsl_vector_float_calloc(nt);
for (i=0; i<nvox; i++) x->data[i] = y->data[i] = 1.0;
/* R = X^t X */
gsl_blas_sgemv (CblasTrans,1.0,X,x,0.0,z);
if (type == 7) SignFlip(X);
gsl_blas_sgemv (CblasNoTrans,1.0,X,z,0.0,y);
if (type == 7) SignFlip(X);
/* count off-diagonal entries with value '0' */
size_t n=0;
for (i=0; i<nvox; i++) {
u = y->data[i] - x->data[i]; /* subtract main diagonal */
if (fabs(u) < tiny) n++;
}
gsl_vector_float_free(x);
gsl_vector_float_free(y);
gsl_vector_float_free(z);
/* return code */
int rtcode = 0;
if (n > 0) rtcode = 0;
else rtcode = 1;
if (rtcode == 0) {
VWarning(" Matrix is not irreducible, n=%lu, nvox= %lu\n",n,nvox);
}
return rtcode;
}
| {
"alphanum_fraction": 0.6390977444,
"avg_line_length": 24.3521126761,
"ext": "c",
"hexsha": "f3d4b0b12df6f5284f751c37e70c379bd46da6b0",
"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/vecm/Irreducible.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/vecm/Irreducible.c",
"max_line_length": 86,
"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/vecm/Irreducible.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": 604,
"size": 1729
} |
#ifndef CONSTANTS_H
#define CONSTANTS_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <math.h>
#include <time.h>
#include <float.h>
#include <utils/version.h>
#include <utils/help.h>
#include <utils/error.h>
#include <gsl/gsl_statistics_double.h>
/*
* MIN macro
*/
#define MIN(a,b) (((a)<(b))?(a):(b))
/*
* MAX macro
*/
#define MAX(a,b) (((a)>(b))?(a):(b))
/*
* STR macro
*/
#define STR(a) ((a > 0)?("-"):("+"))
/*
* Default value for read_minlen parameter
*/
#define MIN_READ_LEN 0
/*
* Default value for minlen parameter
*/
#define MIN_LEN 15
/*
* Default value for maxlen parameter
*/
#define MAX_LEN 30
/*
* Default value for spacing parameter
*/
#define SPACING 20
/*
* Default value for minheight parameter
*/
#define MIN_READS 10.0f
/*
* Default value for trimming threshold parameter
*/
#define TRIM_THRESHOLD 0.05
/*
* Default value for minimum trimming parameter
*/
#define TRIM_MIN 2
/*
* Default value for maximum trimming parameter
*/
#define TRIM_MAX 20
/*
* Default value for IDR cutoff
*/
#define CUTOFF 2.0f
/*
* Default value for Replicate number
*/
#define REPLICATE_NUMBER 1
/*
* Replicate treatment options
*/
#define REPLICATE_POOL_STR "pool" // default value
#define REPLICATE_MEAN_STR "mean"
#define REPLICATE_REPLICATE_STR "replicate"
#define REPLICATE_POOL 0
#define REPLICATE_MEAN 1
#define REPLICATE_REPLICATE 2
/*
* IDR method options
*/
#define IDR_COMMON_STR "common" // default value
#define IDR_NONE_STR "none"
#define IDR_SERE_STR "sere"
#define IDR_IDR_STR "idr"
#define IDR_COMMON 0
#define IDR_NONE 1
#define IDR_SERE 2
#define IDR_IDR 3
/*
* Maximum length of a contig
*/
#define MAX_CONTIG_LENGTH 200
/*
* Maximum number of contigs
*/
#define MAX_CONTIGS 10000000
/*
* Maximum size, in chars, of an error message
*/
#define MAX_ERR_MSG 100
/*
* Maximum size, in chars, of a given path
*/
#define MAX_PATH 500
/*
* Maximum size, in chars, of the 4th field (name) in the query BED file
*/
#define MAX_FEATURE 50
/*
* Maximum number of replicates
*/
#define MAX_REPLICATES 10
/*
* Maximum number of alignments per heap
*/
#define MAX_ALIGN_HEAP 50000000
/*
* Maximum read length
*/
#define MAX_READ_LENGTH 200
/*
* Maximum profile length
*/
#define MAX_PROFILE_LENGTH 500
/*
* Maximum number of block base pairs
*/
#define MAX_BLOCK 3000
/*
* Alignment strand
*/
#define FWD_STRAND 0 // forward/watson
#define REV_STRAND 1 // reverse/crick
/*
* Alignment validity
*/
#define VALID_ALIGNMENT 1
#define INVALID_ALIGNMENT 0
/*
* Constants for npIDR method
*/
#define ABSOLUTE 0
#define CONDITIONAL 1
/*
* Path separator
*/
#ifdef __unix__
#define PATH_SEPARATOR "/"
#else
#define PATH_SEPARATOR "\\"
#endif
/*
* Output file suffixes
*/
#define PROFILES_SUFFIX "profiles.dat"
#define CONTIGS_SUFFIX "contigs.dat"
#define CROSSCOR_SUFFIX "crosscor.dat"
#define CLUSTERS_SUFFIX "clusters.neWick"
#define ANNOTATION_O_SUFFIX "annotation.bed"
#define TMPROFILES_SUFFIX "tmprofiles.dat"
/*
* Maximum N limit for gaussian white noise generation
*/
#define MAX_GNOISE_N 20
/*
* Cluster cutoff default value
*/
#define CLUSTER_CUTOFF -1.0f
/*
* Condition for existence of annotation file
*/
#define ANNOTATION_CONDITION 0
/*
* Condition for existence of additional profiles file
*/
#define ADDITIONAL_P_CONDITION 0
/*
* Default value for the feature to profile overlap percentage
*/
#define OVERLAP_FTOP 0.9
/*
* Default value for the profile to feature overlap percentage
*/
#define OVERLAP_PTOF 0.5
/*
* Maximum number of annotation files
*/
#define MAX_ANNOTATIONS 10
/*
* Condition for existence of correlations file
*/
#define CORRELATIONS_CONDITION 0
/*
* Constants for profile category
*/
#define NOVEL 0
#define KNOWN 1
/*
* Differential processing default p-value
*/
#define P_VALUE 0.01
/*
* Differential processing default overlap
*/
#define DP_FOLD_CHANGE 7
/*
* Suffix for differentially processed profiles
*/
#define DIFFPROC_PROFILE_O_SUFFIX "diffprofiles.dat"
/*
* Suffix for differentially processed clusters
*/
#define DIFFPROC_CLUSTER_O_SUFFIX "diffclusters.dat"
#endif
| {
"alphanum_fraction": 0.7184235518,
"avg_line_length": 16.453125,
"ext": "h",
"hexsha": "95cd51b66d0e1b22f968732465a91be69afb917c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-02-10T17:53:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-02-10T17:53:08.000Z",
"max_forks_repo_head_hexsha": "40846923672b19a700b84fa332ac5df07ffb86cc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "comprna/SeRPeNT",
"max_forks_repo_path": "src/include/core/constants.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "40846923672b19a700b84fa332ac5df07ffb86cc",
"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": "comprna/SeRPeNT",
"max_issues_repo_path": "src/include/core/constants.h",
"max_line_length": 72,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "40846923672b19a700b84fa332ac5df07ffb86cc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "comprna/SeRPeNT",
"max_stars_repo_path": "src/include/core/constants.h",
"max_stars_repo_stars_event_max_datetime": "2017-07-27T21:04:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-07-27T21:04:23.000Z",
"num_tokens": 1058,
"size": 4212
} |
/*
* aplowly.h
* lowly_project
*
* Created by Karim Benabed on 11/03/09.
* Copyright 2009 Institut d'Astrophysique de Paris. All rights reserved.
*
*/
#include "lowly_common.h"
#include <gsl/gsl_vector.h>
#include <gsl/gsl_vector_int.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_gamma.h>
#ifndef __APLOWLY__
#define __APLOWLY__
typedef struct {
double *data;
double *alpha,*beta,*wl,*C,*gl;
double Nl,logdets2;
int is_zero;
size_t ndim;
gsl_matrix_view C_view_container;
gsl_matrix *C_view;
gsl_vector_view gl_view_container;
gsl_vector *gl_view;
} approx_lowly;
approx_lowly* approx_lowly_init(size_t ndim,int* ell, int lmax,double *clhat, double *fsky, double *wl, double *V,double noisevar, long nside, error **err);
void free_approx_lowly(approx_lowly **self);
double approx_lowly_log_pdf(void *self, double *Cl, error **err);
double approx_zero_lowly_log_pdf(void* pelf,double* pars, error **err);
typedef struct {
double *data;
double *al,*bl,*Cm,*gl,*nl;
int *ell;
double logdets2;
int isdiag;
int nell;
} tease;
typedef struct {
double *data;
double *cl,*vl,*nl,*Cm,*gl;
int *ell;
double logdets2;
int isdiag;
int nell;
} gausslkl;
tease* tease_init(size_t nell, int* ell,double *al, double *bl, double *nl, int nlcst, double *Cm, int Cmisdiag, error **err);
void tease_free(void **ping);
double tease_log_pdf(void* ing, double* pars, error **err);
gausslkl* gausslkl_init(size_t nell, int* ell,double *al, double *bl, double *nl, int nlcst, double *Cm, int Cmisdiag, error **err);
void gausslkl_free(void **ping);
double gausslkl_log_pdf(void* ing, double* pars, error **err);
typedef struct {
double *data;
double *ldlh,*sig2,*wl;
double Nl;
size_t ndim;
} log_normal;
log_normal* log_normal_init(size_t ndim,int* ell, double *clhat, double *fsky, double *wl, double noisevar, long nside, error **err);
void free_log_normal(log_normal **self);
double log_normal_log_pdf(void *self, double *Cl, error **err);
typedef struct {
int np;
int *nb;
int *obe;
int *obv;
double *be;
double *bv;
} binlkl;
binlkl* init_binlkl(int np, int* nb, double* be, double* bv, error **err);
double binlkl_lkl(void *vbon, double *pars, error **err);
void free_binlkl(void** pvbon);
#define ZEROLKL -1e30
#define lowly_no_correlation -20 + clowly_base
#endif
| {
"alphanum_fraction": 0.7127360386,
"avg_line_length": 24.6435643564,
"ext": "h",
"hexsha": "fcd381a79f6efdbad801c3dcb734e8c69e5919ae",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-06-11T15:29:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-11T15:29:43.000Z",
"max_forks_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_forks_repo_path": "cosmosis-standard-library/likelihood/planck/pcl-1.0/src/aplowly.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"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": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_issues_repo_path": "cosmosis-standard-library/likelihood/planck/pcl-1.0/src/aplowly.h",
"max_line_length": 156,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "07e5d308c6a8641a369a3e0b8d13c4104988cd2b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra",
"max_stars_repo_path": "cosmosis-standard-library/likelihood/planck/pcl-1.0/src/aplowly.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-15T10:10:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-15T10:10:26.000Z",
"num_tokens": 792,
"size": 2489
} |
#include <stdio.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_trig.h>
#include <gsl/gsl_pow_int.h>
#include <math.h>
double sin_term(int l,int m,double phi,double theta){
double out = gsl_pow_int(-1.0,m)*gsl_sf_legendre_sphPlm(l,m,gsl_sf_cos(theta))*gsl_sf_sin(m*phi);
return out;
}
double cos_term(int l,int m, double phi, double theta){
double out= gsl_pow_int(-1.0,m)*gsl_sf_legendre_sphPlm(l,m,gsl_sf_cos(theta))*gsl_sf_cos(m*phi);
return out;
}
float acos_fast(float x) {
float negate = (float)x < 0;
x = x < 0 ? -x : x;
float ret = -0.0187293;
ret = ret * x;
ret = ret + 0.0742610;
ret = ret * x;
ret = ret - 0.2121144;
ret = ret * x;
ret = ret + 1.5707288;
ret = ret * sqrt(1.0-x);
ret = ret - 2 * negate * ret;
return negate * 3.14159265358979 + ret;
}
float fast_grf(int L, float x, float y,float z,float rands[]){
float result = 0.0;
float phi =atan2(y,x);
float theta = acos_fast(z);
float temp ;
register int l = 0;
register int m = 1;
for (l=0; l<= L;l++){
result += gsl_sf_legendre_sphPlm(l,0,gsl_sf_cos(theta))*rands[2*L*l];
temp = 0.0;
for(m=1;m<=l;m++){
temp += (1 - ((m & 1) << 1))*gsl_sf_legendre_sphPlm(l,m,gsl_sf_cos(theta))*(rands[2*m+2*L*l+l]*gsl_sf_sin(m*phi)+rands[1+2*m+2*L*l]*gsl_sf_cos(m*phi));
}
result += 1.41421*temp;
}
return result;
}
| {
"alphanum_fraction": 0.626734843,
"avg_line_length": 24.8909090909,
"ext": "c",
"hexsha": "a85e7ef4ba4b6d49d4e43c57f0eacea63fd0bd58",
"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": "1e9468084abf41cc0ae85f1b4b1254904ed2d72f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "erik-grennberg-jansson/matern_sfem",
"max_forks_repo_path": "fast_spherharms.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1e9468084abf41cc0ae85f1b4b1254904ed2d72f",
"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": "erik-grennberg-jansson/matern_sfem",
"max_issues_repo_path": "fast_spherharms.c",
"max_line_length": 157,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1e9468084abf41cc0ae85f1b4b1254904ed2d72f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "erik-grennberg-jansson/matern_sfem",
"max_stars_repo_path": "fast_spherharms.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 509,
"size": 1369
} |
#pragma once
#include "arcana/finally_scope.h"
#include "arcana/functional/inplace_function.h"
#include "arcana/sentry.h"
#include "arcana/threading/affinity.h"
#include <algorithm>
#include <tuple>
#include <vector>
#include <gsl/gsl>
namespace arcana
{
using ticket_seed = int64_t;
using ticket = gsl::final_action<
stdext::inplace_function<void(), sizeof(std::aligned_storage_t<sizeof(ticket_seed) + sizeof(void*)>)>>;
using ticket_scope = finally_scope<ticket>;
/*
An event routing class used to dispatch events to multiple listeners.
Each router class can only handle a certain fixed set of event types defined by EventTs.
*/
template<typename... EventTs>
class router
{
public:
static constexpr size_t LISTENER_SIZE = 4 * sizeof(int64_t);
template<typename EventT>
using listener_function = stdext::inplace_function<void(const EventT&), LISTENER_SIZE>;
/*
Sends an event synchronously to all listeners.
*/
template<typename EventT>
void fire(const EventT& evt)
{
GSL_CONTRACT_CHECK("thread affinity", m_affinity.check());
using event = std::decay_t<EventT>;
auto& listeners = std::get<listener_group<event>>(m_listeners);
{
auto guard = std::get<sentry<event>>(m_sentries).take();
for (listener<event>& listener : listeners)
{
if (listener.valid)
{
listener.callback(evt);
}
}
}
// if we're no longer iterating the listeners list in this stack
// remove all the unregistered listeners and add the pending ones
if (!std::get<sentry<event>>(m_sentries).is_active())
{
listeners.erase(std::remove_if(listeners.begin(),
listeners.end(),
[](const listener<event>& l) { return !l.valid; }),
listeners.end());
// move the pending listeners to the real list
// and clear the pending list
auto& pending = std::get<listener_group<event>>(m_pending);
std::move(pending.begin(), pending.end(), std::back_inserter(listeners));
pending.clear();
}
}
/*
Adds an event listener.
*/
template<typename EventT, typename T>
ticket add_listener(T&& listener)
{
auto id = internal_add_listener<EventT>(std::forward<T>(listener));
return ticket{ [id, this] { internal_remove_listener<EventT>(id); } };
}
/*
Sets the routers thread affinity. Once this is set the methods
on this instance will need to be called by that thread.
*/
void set_affinity(const affinity& aff)
{
m_affinity = aff;
}
private:
/*
Adds an event listener.
*/
template<typename EventT, typename T>
ticket_seed internal_add_listener(T&& listener)
{
GSL_CONTRACT_CHECK("thread affinity", m_affinity.check());
using event = std::decay_t<EventT>;
// if we're currently firing an event in that group we need to wait until we're done before
// adding the listener to the list
auto& listeners = std::get<sentry<event>>(m_sentries).is_active()
? std::get<listener_group<event>>(m_pending)
: std::get<listener_group<event>>(m_listeners);
auto id = m_nextId++;
listeners.emplace_back(std::forward<T>(listener), id);
return id;
}
/*
Removes an event listener by id.
*/
template<typename EventT>
void internal_remove_listener(const ticket_seed& id)
{
GSL_CONTRACT_CHECK("thread affinity", m_affinity.check());
using event = std::decay_t<EventT>;
auto& listeners = std::get<listener_group<event>>(m_listeners);
auto found = std::find_if(listeners.begin(), listeners.end(), [id](const listener<event>& listener) {
return listener.id == id;
});
if (found == listeners.end())
{
assert(false && "removing item that isn't there");
return;
}
// don't modify the collection while iterating, just disable the listener
if (std::get<sentry<event>>(m_sentries).is_active())
{
found->valid = false;
}
else
{
listeners.erase(found);
}
}
template<typename EventT>
struct listener
{
using callback_t = listener_function<EventT>;
callback_t callback;
ticket_seed id;
bool valid;
listener(callback_t&& callback, const ticket_seed& id)
: callback{ std::move(callback) }
, id{ id }
, valid{ true }
{}
listener(const callback_t& callback, const ticket_seed& id)
: callback{ callback }
, id{ id }
, valid{ true }
{}
};
template<typename EventT>
using listener_group = std::vector<listener<EventT>>;
std::tuple<listener_group<EventTs>...> m_listeners;
std::tuple<sentry<EventTs>...> m_sentries;
std::tuple<listener_group<EventTs>...> m_pending;
affinity m_affinity;
ticket_seed m_nextId;
};
}
| {
"alphanum_fraction": 0.5363357216,
"avg_line_length": 31.6864864865,
"ext": "h",
"hexsha": "e46a8a3af61089bfe53e08d1079c43ca25c1e292",
"lang": "C",
"max_forks_count": 18,
"max_forks_repo_forks_event_max_datetime": "2021-12-26T14:24:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-09T23:07:44.000Z",
"max_forks_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andrei-datcu/arcana.cpp",
"max_forks_repo_path": "Source/Shared/arcana/messaging/router.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5",
"max_issues_repo_issues_event_max_datetime": "2022-01-03T20:12:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-08-13T03:18:30.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "andrei-datcu/arcana.cpp",
"max_issues_repo_path": "Source/Shared/arcana/messaging/router.h",
"max_line_length": 113,
"max_stars_count": 65,
"max_stars_repo_head_hexsha": "3c4757cbee49b3272130bf8b72094c2c62fd36c5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andrei-datcu/arcana.cpp",
"max_stars_repo_path": "Source/Shared/arcana/messaging/router.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T15:05:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-08T01:53:22.000Z",
"num_tokens": 1163,
"size": 5862
} |
/* tsqr.c
*
* Copyright (C) 2015, 2019 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 module implements the sequential TSQR algorithm
* described in
*
* [1] Demmel, J., Grigori, L., Hoemmen, M. F., and Langou, J.
* "Communication-optimal parallel and sequential QR and LU factorizations",
* UCB Technical Report No. UCB/EECS-2008-89, 2008.
*
* The algorithm operates on a tall least squares system:
*
* [ A_1 ] x = [ b_1 ]
* [ A_2 ] [ b_2 ]
* [ ... ] [ ... ]
* [ A_k ] [ b_k ]
*
* as follows:
*
* 1. Initialize
* a. [Q_1,R_1] = qr(A_1)
* b. z_1 = Q_1^T b_1
* 2. Loop i = 2:k
* a. [Q_i,R_i] = qr( [ R_{i-1} ; A_i ] )
* b. z_i = Q_i^T [ z_{i-1} ; b_i ]
* 3. Output:
* a. R = R_k
* b. Q^T b = z_k
*
* Step 2(a) is optimized to take advantage
* of the sparse structure of the matrix
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_multilarge.h>
typedef struct
{
size_t p; /* number of columns of LS matrix */
int nblocks; /* number of blocks processed */
double rnorm; /* || b - A x || residual norm */
int svd; /* SVD of R factor has been computed */
gsl_matrix *T; /* block reflector matrix, p-by-p */
gsl_matrix *R; /* R factor, p-by-p */
gsl_vector *QTb; /* [ Q^T b ; b_i ], size p-by-1 */
gsl_vector *work; /* workspace, size p */
gsl_vector *work3; /* workspace, size 3*p */
gsl_multifit_linear_workspace * multifit_workspace_p;
} tsqr_state_t;
static void *tsqr_alloc(const size_t p);
static void tsqr_free(void *vstate);
static int tsqr_reset(void *vstate);
static int tsqr_accumulate(gsl_matrix * A, gsl_vector * b,
void * vstate);
static int tsqr_solve(const double lambda, gsl_vector * x,
double * rnorm, double * snorm,
void * vstate);
static int tsqr_rcond(double * rcond, void * vstate);
static int tsqr_lcurve(gsl_vector * reg_param, gsl_vector * rho,
gsl_vector * eta, void * vstate);
static const gsl_matrix * tsqr_R(const void * vstate);
static const gsl_vector * tsqr_QTb(const void * vstate);
static int tsqr_svd(tsqr_state_t * state);
/*
tsqr_alloc()
Allocate workspace for solving large linear least squares
problems using the TSQR approach
Inputs: p - number of columns of LS matrix
Return: pointer to workspace
*/
static void *
tsqr_alloc(const size_t p)
{
tsqr_state_t *state;
if (p == 0)
{
GSL_ERROR_NULL("p must be a positive integer",
GSL_EINVAL);
}
state = calloc(1, sizeof(tsqr_state_t));
if (!state)
{
GSL_ERROR_NULL("failed to allocate tsqr state", GSL_ENOMEM);
}
state->p = p;
state->nblocks = 0;
state->rnorm = 0.0;
state->R = gsl_matrix_alloc(p, p);
if (state->R == NULL)
{
tsqr_free(state);
GSL_ERROR_NULL("failed to allocate R matrix", GSL_ENOMEM);
}
state->QTb = gsl_vector_alloc(p);
if (state->QTb == NULL)
{
tsqr_free(state);
GSL_ERROR_NULL("failed to allocate QTb vector", GSL_ENOMEM);
}
state->T = gsl_matrix_alloc(p, p);
if (state->T == NULL)
{
tsqr_free(state);
GSL_ERROR_NULL("failed to allocate T matrix", GSL_ENOMEM);
}
state->work = gsl_vector_alloc(p);
if (state->work == NULL)
{
tsqr_free(state);
GSL_ERROR_NULL("failed to allocate workspace vector", GSL_ENOMEM);
}
state->work3 = gsl_vector_alloc(3 * p);
if (state->work3 == NULL)
{
tsqr_free(state);
GSL_ERROR_NULL("failed to allocate work3 vector", GSL_ENOMEM);
}
state->multifit_workspace_p = gsl_multifit_linear_alloc(p, p);
if (state->multifit_workspace_p == NULL)
{
tsqr_free(state);
GSL_ERROR_NULL("failed to allocate multifit workspace", GSL_ENOMEM);
}
return state;
}
static void
tsqr_free(void *vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
if (state->R)
gsl_matrix_free(state->R);
if (state->QTb)
gsl_vector_free(state->QTb);
if (state->T)
gsl_matrix_free(state->T);
if (state->work)
gsl_vector_free(state->work);
if (state->work3)
gsl_vector_free(state->work3);
if (state->multifit_workspace_p)
gsl_multifit_linear_free(state->multifit_workspace_p);
free(state);
}
static int
tsqr_reset(void *vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
gsl_matrix_set_zero(state->R);
gsl_vector_set_zero(state->QTb);
state->nblocks = 0;
state->rnorm = 0.0;
state->svd = 0;
return GSL_SUCCESS;
}
/*
tsqr_accumulate()
Add a new block of rows to the QR system
Inputs: A - new block of rows, n-by-p
b - new rhs vector n-by-1
vstate - workspace
Return: success/error
Notes:
1) On output, the upper triangular portion of state->R(1:p,1:p)
contains current R matrix
2) state->QTb(1:p) contains current Q^T b vector
3) A and b are destroyed
*/
static int
tsqr_accumulate(gsl_matrix * A, gsl_vector * b, void * vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
const size_t n = A->size1;
const size_t p = A->size2;
if (p != state->p)
{
GSL_ERROR("columns of A do not match workspace", GSL_EBADLEN);
}
else if (n != b->size)
{
GSL_ERROR("A and b have different numbers of rows", GSL_EBADLEN);
}
else if (state->nblocks == 0 && n < p)
{
GSL_ERROR ("n must be >= p", GSL_EBADLEN);
}
else if (state->nblocks == 0)
{
int status;
gsl_matrix_view R = gsl_matrix_submatrix(A, 0, 0, p, p);
gsl_vector_view QTb = gsl_vector_subvector(state->QTb, 0, p);
gsl_vector_view b1 = gsl_vector_subvector(b, 0, p);
/* this is the first matrix block A_1, compute its (dense) QR decomposition */
/* compute QR decomposition of A */
status = gsl_linalg_QR_decomp_r(A, state->T);
if (status)
return status;
/* store upper triangular R factor in state->R */
gsl_matrix_tricpy(CblasUpper, CblasNonUnit, state->R, &R.matrix);
/* compute Q^T b and keep the first p elements */
gsl_linalg_QR_QTvec_r(A, state->T, b, state->work);
gsl_vector_memcpy(&QTb.vector, &b1.vector);
if (n > p)
{
gsl_vector_view b2 = gsl_vector_subvector(b, p, n - p);
state->rnorm = gsl_blas_dnrm2(&b2.vector);
}
else
state->rnorm = 0.0;
state->nblocks = 1;
return GSL_SUCCESS;
}
else
{
int status;
/* compute QR decomposition of [ R_{i-1} ; A_i ], accounting for
* sparse structure */
status = gsl_linalg_QR_UR_decomp(state->R, A, state->T);
if (status)
return status;
/*
* Compute:
*
* Q^T [ QTb_{i-1} ] = [ QTb_{i-1} - w ]
* [ b_i ] [ b_i - V~ w ]
*
* where:
*
* w = T^T (QTb_{i-1} + V~^T b_i)
*
* p
* V = [ I ] p
* [ V~ ] n
*/
gsl_vector_memcpy(state->work, state->QTb);
gsl_blas_dgemv(CblasTrans, 1.0, A, b, 1.0, state->work); /* w := w + V~^T b */
gsl_blas_dtrmv(CblasUpper, CblasTrans, CblasNonUnit, state->T, state->work); /* w := T^T w */
gsl_vector_sub(state->QTb, state->work); /* QTb := QTb - w */
/* update residual norm */
gsl_blas_dgemv(CblasNoTrans, -1.0, A, state->work, 1.0, b); /* b := b - V~ w */
state->rnorm = gsl_hypot(state->rnorm, gsl_blas_dnrm2(b));
return GSL_SUCCESS;
}
}
/*
tsqr_solve()
Solve the least squares system:
chi^2 = || QTb - R x ||^2 + lambda^2 || x ||^2
using the SVD of R
Inputs: lambda - regularization parameter
x - (output) solution vector p-by-1
rnorm - (output) residual norm ||b - A x||
snorm - (output) solution norm ||x||
vstate - workspace
Return: success/error
*/
static int
tsqr_solve(const double lambda, gsl_vector * x,
double * rnorm, double * snorm,
void * vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
if (x->size != state->p)
{
GSL_ERROR ("solution vector does not match workspace", GSL_EBADLEN);
}
else if (lambda < 0.0)
{
GSL_ERROR ("regularization parameter should be non-negative", GSL_EINVAL);
}
else
{
if (lambda == 0.0)
{
/* solve: R x = Q^T b */
gsl_vector_memcpy(x, state->QTb);
gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit, state->R, x);
*rnorm = state->rnorm;
*snorm = gsl_blas_dnrm2(x);
}
else
{
int status;
/* compute SVD of R if not already computed */
if (state->svd == 0)
{
status = tsqr_svd(state);
if (status)
return status;
}
status = gsl_multifit_linear_solve(lambda, state->R, state->QTb, x, rnorm, snorm,
state->multifit_workspace_p);
if (status)
return status;
*rnorm = gsl_hypot(*rnorm, state->rnorm);
}
return GSL_SUCCESS;
}
}
/*
tsqr_lcurve()
Compute L-curve of least squares system
Inputs: reg_param - (output) vector of regularization parameters
rho - (output) vector of residual norms
eta - (output) vector of solution norms
vstate - workspace
Return: success/error
*/
static int
tsqr_lcurve(gsl_vector * reg_param, gsl_vector * rho,
gsl_vector * eta, void * vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
int status;
size_t i;
/* compute SVD of R if not already computed */
if (state->svd == 0)
{
status = tsqr_svd(state);
if (status)
return status;
}
status = gsl_multifit_linear_lcurve(state->QTb, reg_param, rho, eta,
state->multifit_workspace_p);
/* now add contribution to rnorm from Q2 factor */
for (i = 0; i < rho->size; ++i)
{
double *rhoi = gsl_vector_ptr(rho, i);
*rhoi = gsl_hypot(*rhoi, state->rnorm);
}
return status;
}
static const gsl_matrix *
tsqr_R(const void * vstate)
{
const tsqr_state_t *state = (const tsqr_state_t *) vstate;
return state->R;
}
static const gsl_vector *
tsqr_QTb(const void * vstate)
{
const tsqr_state_t *state = (const tsqr_state_t *) vstate;
return state->QTb;
}
static int
tsqr_rcond(double * rcond, void * vstate)
{
tsqr_state_t *state = (tsqr_state_t *) vstate;
return gsl_linalg_tri_rcond(CblasUpper, state->R, rcond, state->work3);
}
/*
tsqr_svd()
Compute the SVD of the upper triangular
R factor. This allows us to compute the upper/lower
bounds on the regularization parameter and compute
the matrix reciprocal condition number.
Inputs: state - workspace
Return: success/error
*/
static int
tsqr_svd(tsqr_state_t * state)
{
int status;
status = gsl_multifit_linear_svd(state->R, state->multifit_workspace_p);
if (status)
{
GSL_ERROR("error computing SVD of R", status);
}
state->svd = 1;
return GSL_SUCCESS;
}
static const gsl_multilarge_linear_type tsqr_type =
{
"tsqr",
tsqr_alloc,
tsqr_reset,
tsqr_accumulate,
tsqr_solve,
tsqr_rcond,
tsqr_lcurve,
tsqr_R,
tsqr_QTb,
tsqr_free
};
const gsl_multilarge_linear_type * gsl_multilarge_linear_tsqr = &tsqr_type;
| {
"alphanum_fraction": 0.6097541183,
"avg_line_length": 25.3039014374,
"ext": "c",
"hexsha": "a2b197351309ea043e1e9effb0b83623f71869f1",
"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/multilarge/tsqr.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/multilarge/tsqr.c",
"max_line_length": 104,
"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/multilarge/tsqr.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": 3585,
"size": 12323
} |
#ifndef METHODS_CWA_SMD_OPT_H
#define METHODS_CWA_SMD_OPT_H
#include <gsl/gsl_multimin.h>
#include "quartz_internal/util/gsl_converter.h"
namespace method {
namespace cwa_smd_opt {
namespace details {
inline
gsl_multimin_fdfminimizer_type * minimizer_map(const std::string type) {
if(type == "steepest_descent") {
return const_cast<gsl_multimin_fdfminimizer_type *>(gsl_multimin_fdfminimizer_steepest_descent);
} else if(type == "conjugate_pr") {
return const_cast<gsl_multimin_fdfminimizer_type *>(gsl_multimin_fdfminimizer_conjugate_pr);
} else if(type == "conjugate_fr") {
return const_cast<gsl_multimin_fdfminimizer_type *>(gsl_multimin_fdfminimizer_conjugate_fr);
} else if(type == "bfgs") {
return const_cast<gsl_multimin_fdfminimizer_type *>(gsl_multimin_fdfminimizer_vector_bfgs);
} else if(type == "bfgs2") {
return const_cast<gsl_multimin_fdfminimizer_type *>(gsl_multimin_fdfminimizer_vector_bfgs2);
} else {
throw Error("minimizer " + type + " is not implemented");
}
}
struct cwa_smd_opt_param {
arma::mat original_points;
arma::vec expectations_ref;
std::vector<math::Polynomial<double>> original_operators;
arma::vec weights;
arma::vec scaling;
long long grade;
};
inline
double penalty_function(
const arma::mat & points,
const arma::vec & expectations_ref,
const std::vector<math::Polynomial<double>> & original_operators,
const arma::vec & weights,
const arma::vec & scaling,
const long long grade) {
double result = 0;
for (arma::uword i = 0; i < original_operators.size(); i++) {
const long long the_grade = original_operators[i].grade();
if (the_grade < grade && the_grade > 0) {
const double result_from_cwa =
cwa_smd::details::expectation(original_operators[i], points, weights,
scaling);
result += std::pow(result_from_cwa - expectations_ref(i), 2);
}
}
return result;
}
inline
arma::mat penalty_function_derivative(
const arma::mat & points,
const arma::vec & expectations_ref,
const std::vector<math::Polynomial<double>> & original_operators,
const arma::vec & weights,
const arma::vec & scaling,
const long long grade
) {
arma::mat result(arma::size(points), arma::fill::zeros);
for (arma::uword i = 0; i < original_operators.size(); i++) {
const long long the_grade = original_operators[i].grade();
if (the_grade < grade && the_grade > 0) {
const double result_from_cwa =
cwa_smd::details::expectation(original_operators[i], points, weights,
scaling);
for (arma::uword j = 0; j < points.n_cols; j++) {
const arma::vec point = arma::diagmat(1.0 / scaling) * points.col(j);
for (arma::uword k = 0; k < points.n_rows / 2; k++) {
const math::Polynomial<double> x_derivative =
original_operators[i].derivative(
k) / scaling(k);
const math::Polynomial<double> p_derivative =
original_operators[i].derivative(
k + points.n_rows / 2) / scaling(k + points.n_rows / 2);
result(k, j) -=
2.0 * (result_from_cwa - expectations_ref(i)) * weights(j) *
x_derivative.at(point) / arma::sum(weights);
result(k + points.n_rows / 2, j) -=
2.0 * (result_from_cwa - expectations_ref(i)) * weights(j) *
p_derivative.at(point) / arma::sum(weights);
}
}
}
}
return -result;
}
inline
double penalty_function_gsl_wrapper(const gsl_vector * flattened_points,
void * param) {
const arma::vec arma_flattened_points = gsl::convert_vec(flattened_points);
const auto converted_param = *(cwa_smd_opt_param *) param;
const arma::mat points = arma::reshape(arma_flattened_points, arma::size(
converted_param.original_points));
return penalty_function(points,
converted_param.expectations_ref,
converted_param.original_operators,
converted_param.weights,
converted_param.scaling,
converted_param.grade);
}
inline
void penalty_function_derivative_gsl_wrapper(
const gsl_vector * flattened_points,
void * param,
gsl_vector * g) {
const arma::vec arma_flattened_points = gsl::convert_vec(flattened_points);
const auto converted_param = *(cwa_smd_opt_param *) param;
const arma::mat points = arma::reshape(arma_flattened_points, arma::size(
converted_param.original_points));
const arma::vec result =
arma::vectorise(
penalty_function_derivative(points,
converted_param.expectations_ref,
converted_param.original_operators,
converted_param.weights,
converted_param.scaling,
converted_param.grade));
const auto result_pointer = gsl::convert_vec(result);
gsl_vector_memcpy(g, result_pointer);
gsl_vector_free(result_pointer);
}
inline
void penalty_function_fdf_gsl_wrapper(
const gsl_vector * a_derivatives,
void * param,
double * f,
gsl_vector * g) {
penalty_function_derivative_gsl_wrapper(a_derivatives, param, g);
*f = penalty_function_gsl_wrapper(a_derivatives, param);
}
inline
std::tuple<arma::mat, double, double, int> cwa_optimize(const cwa_smd_opt_param input,
const double initial_step_size,
const double tolerance,
const double gradient_tolerance,
const size_t total_steps,
const std::string type) {
/* allocate memory for minimization process */
const auto minimizer_type = minimizer_map(type);
const arma::uword n = input.original_points.n_elem;
const auto penalty_function_value = penalty_function(input.original_points,
input.expectations_ref,
input.original_operators,
input.weights,
input.scaling,
input.grade);
const double gradient_module = arma::norm(
arma::vectorise(penalty_function_derivative(input.original_points,
input.expectations_ref,
input.original_operators,
input.weights,
input.scaling,
input.grade)));
if (penalty_function_value < tolerance &&
gradient_module < gradient_tolerance) {
return {input.original_points, penalty_function_value, gradient_module, 0};
}
auto minimizer_environment = gsl_multimin_fdfminimizer_alloc(minimizer_type,
n);
/* assigning function to minimizer object */
gsl_multimin_function_fdf minimizer_object;
minimizer_object.f = &penalty_function_gsl_wrapper;
minimizer_object.df = &penalty_function_derivative_gsl_wrapper;
minimizer_object.fdf = &penalty_function_fdf_gsl_wrapper;
minimizer_object.n = n;
minimizer_object.params = (void *) &input;
/* starting point */
const arma::vec flattened = arma::vectorise(input.original_points);
gsl_vector * points = gsl::convert_vec(flattened);
/* set environment */
gsl_multimin_fdfminimizer_set(minimizer_environment,
&minimizer_object, points,
initial_step_size, tolerance);
size_t iter = 0;
int status = GSL_CONTINUE;
do {
iter++;
status = gsl_multimin_fdfminimizer_iterate(minimizer_environment);
if (status) {
throw Error(gsl_strerror(status));
}
status = gsl_multimin_test_gradient(minimizer_environment->gradient,
gradient_tolerance);
if (status == GSL_SUCCESS) {
const arma::vec result = gsl::convert_vec(minimizer_environment->x);
const double f = minimizer_environment->f;
const double df = arma::norm(gsl::convert_vec(minimizer_environment->gradient));
gsl_multimin_fdfminimizer_free(minimizer_environment);
gsl_vector_free(points);
return {arma::reshape(result, arma::size(input.original_points)), f, df, iter};
}
} while (status == GSL_CONTINUE && iter < total_steps);
throw Error("fail to converge towards the solution");
}
} // namespace details
struct State {
public:
arma::mat points;
arma::vec weights;
arma::vec masses;
arma::uword grade;
arma::uvec expectation_table;
arma::vec expectations;
arma::uvec positional_indices;
arma::uvec momentum_indices;
arma::vec scaling;
// Establish an easy way to construct your State
template<typename PhaseSpaceDistribution>
State(const PhaseSpaceDistribution & initial,
const arma::uvec & grid,
const arma::mat & range,
const arma::vec & scaling,
const arma::vec & masses,
const arma::uword grade) :
points(math::space::points_generate(grid, range)),
weights(arma::real(at(initial, points))),
masses(masses),
grade(grade),
expectation_table(math::space::grids_to_table(
grade * arma::ones<arma::uvec>(points.n_rows))),
scaling(scaling) {
if (grid.n_rows != range.n_rows) {
throw Error("Different dimension between the grid and the range");
}
if (grid.n_rows != 2 * masses.n_rows) {
throw Error("Different dimension between the grid and the masses");
}
const arma::uword dimension = grid.n_elem;
const arma::uword length = std::pow(grade, dimension);
this->expectations = arma::vec(length);
this->positional_indices = arma::uvec(dimension / 2);
this->momentum_indices = arma::uvec(dimension / 2);
const arma::vec ranges = range.col(1) - range.col(0);
// exponents check in
#pragma omp parallel for
for (arma::uword i = 0; i < dimension / 2; i++) {
arma::uvec X = arma::zeros<arma::uvec>(dimension);
arma::uvec P = arma::zeros<arma::uvec>(dimension);
X(i) = 1;
P(i + dimension / 2) = 1;
this->positional_indices(i) =
math::space::indices_to_index(X, this->expectation_table);
this->momentum_indices(i) =
math::space::indices_to_index(P, this->expectation_table);
}
// expectations check in
#pragma omp parallel for
for (arma::uword i = 0; i < length; i++) {
const lvec indices =
arma::conv_to<lvec>::from(
math::space::index_to_indices(i, this->expectation_table));
this->expectations(i) =
cwa_smd::details::expectation(math::polynomial::Term(1.0, indices),
this->points, this->weights,
this->scaling);
}
}
template<typename PhaseSpaceDistribution>
State(const PhaseSpaceDistribution & initial,
const arma::uvec & grid,
const arma::mat & range,
const arma::uword grade) :
points(math::space::points_generate(grid, range)),
weights(arma::real(at(initial, points))),
masses(arma::ones<arma::vec>(grid.n_rows / 2)),
grade(grade),
expectation_table(math::space::grids_to_table(
grade * arma::ones<arma::uvec>(points.n_rows))) {
if (grid.n_rows != range.n_rows) {
throw Error("Different dimension between the grid and the range");
}
if (grid.n_rows != 2 * masses.n_rows) {
throw Error("Different dimension between the grid and the masses");
}
const auto dimension = grid.n_elem;
const auto length = std::pow(grade, dimension);
this->expectations = arma::vec(length);
this->positional_indices = arma::uvec(dimension / 2);
this->momentum_indices = arma::uvec(dimension / 2);
const arma::vec ranges = range.col(1) - range.col(0);
this->scaling = ranges;
// this->scaling = arma::ones(arma::size(ranges));
// exponents check in
for (arma::uword i = 0; i < dimension / 2; i++) {
arma::uvec X = arma::zeros<arma::uvec>(dimension);
arma::uvec P = arma::zeros<arma::uvec>(dimension);
X(i) = 1;
P(i + dimension / 2) = 1;
this->positional_indices(i) =
math::space::indices_to_index(X, this->expectation_table);
this->momentum_indices(i) =
math::space::indices_to_index(P, this->expectation_table);
}
// expectations check in
for (arma::uword i = 0; i < length; i++) {
const lvec indices =
arma::conv_to<lvec>::from(
math::space::index_to_indices(i, this->expectation_table));
this->expectations(i) =
cwa_smd::details::expectation(
math::polynomial::Term(1.0, indices),
this->points, this->weights, this->scaling);
}
}
inline
State(const arma::mat & points,
const arma::vec & weights,
const arma::vec & masses,
const arma::uvec & expectation_table,
const arma::vec & expectations,
const arma::uvec & positional_indices,
const arma::uvec & momentum_indices,
const arma::vec & scaling,
const arma::uword grade) :
points(points),
weights(weights),
masses(masses),
grade(grade),
expectation_table(expectation_table),
expectations(expectations),
positional_indices(positional_indices),
momentum_indices(momentum_indices),
scaling(scaling) {}
inline
State(const State & state) :
points(state.points),
weights(state.weights),
masses(state.masses),
grade(state.grade),
expectation_table(state.expectation_table),
expectations(state.expectations),
positional_indices(state.positional_indices),
momentum_indices(state.momentum_indices),
scaling(state.scaling) {}
inline
arma::uword dim() const {
return points.n_rows / 2;
}
inline
State normalise() const {
State state = *this;
state.weights = state.weights / arma::sum(state.weights);
return state;
}
inline
arma::vec positional_expectation() const {
return method::cwa::State(this->points, this->weights, this->masses)
.positional_expectation();
}
inline
arma::vec momentum_expectation() const {
return method::cwa::State(this->points, this->weights, this->masses)
.momentum_expectation();
}
State operator+(const State & B) const {
if (!arma::approx_equal(this->weights, B.weights, "abs_diff", 1e-16) ||
!arma::approx_equal(this->masses, B.masses, "abs_diff", 1e-16)) {
throw Error("Different cwa states are being added");
}
State state = B;
state.points += this->points;
state.expectations += this->expectations;
return state;
}
State operator*(const double B) const {
State state = *this;
state.expectations *= B;
state.points *= B;
return state;
}
template<typename T>
auto expectation(const math::Polynomial<T> & polynomial) const {
return cwa_smd::details::at_search(polynomial,
this->points,
this->weights,
this->expectations,
this->expectation_table,
this->scaling,
this->grade) *
polynomial.at(this->scaling);
}
template<typename T>
arma::vec expectation(const std::vector<math::Polynomial<T>>
& polynomials) const {
arma::vec result(polynomials.size());
#pragma omp parallel for
for (arma::uword i = 0; i < result.n_elem; i++) {
result(i) = this->expectation(polynomials[i]);
}
return result;
}
State & operator=(const State &) = default;
};
struct Operator {
public:
math::Polynomial<double> potential;
math::Polynomial<double> H;
std::vector<math::Polynomial<double>> original_operators;
std::vector<math::Polynomial<double>> operators;
Operator(const State & state,
const math::Polynomial<double> & potential) :
potential(potential),
H(hamiltonian(potential, state.masses).scale(state.scaling)),
operators() {
std::vector<math::Polynomial<double>>
op(std::pow(state.grade, state.dim() * 2));
std::vector<math::Polynomial<double>>
original_op(std::pow(state.grade, state.dim() * 2));
op[0] = math::Polynomial<double>(state.dim() * 2, 0.0);
original_op[0] = math::Polynomial<double>(state.dim() * 2, 1.0);
for (arma::uword i = 1; i < op.size(); i++) {
const auto observable =
math::Polynomial(math::polynomial::Term<double>(1.0,
math::space::index_to_indices(
i,
state.expectation_table)));
original_op[i] = observable;
const arma::uword cut_off = std::min(observable.grade(), H.grade()) / 2;
const auto moyal =
moyal_bracket(math::Polynomial(observable), H, state.scaling,
cut_off);
op[i] = moyal;
}
this->operators = op;
this->original_operators = original_op;
}
inline
PropagationType propagation_type() const {
return Classic;
}
State operator()(const State & state) const {
arma::mat p_submatrix = state.points.rows(state.dim(), 2 * state.dim() - 1);
p_submatrix.each_col() /= state.masses;
const arma::mat points_change_list =
arma::join_cols(p_submatrix,
cwa::details::force(this->potential,
state.points.rows(0, state.dim() -
1)));
arma::vec expectation_change_list =
arma::vec(arma::size(state.expectations));
#pragma omp parallel for
for (arma::uword i = 0; i < expectation_change_list.n_elem; i++) {
expectation_change_list(i) =
cwa_smd::details::at_search(this->operators[i],
state.points,
state.weights,
state.expectations,
state.expectation_table,
state.scaling,
state.grade);
}
return State(points_change_list,
state.weights,
state.masses,
state.expectation_table,
expectation_change_list,
state.positional_indices,
state.momentum_indices,
state.scaling,
state.grade);
}
};
template<typename Potential>
OperatorWrapper<Operator, State, Potential>
cwa_opt(const double initial_step_size,
const double tolerance,
const double gradient_tolerance,
const size_t total_steps,
const std::string type = "bfgs2",
const int print_level = 0) {
return [initial_step_size,
tolerance,
gradient_tolerance,
total_steps,
type,
print_level
](const Operator & cwa_smd_opt_operator,
const Potential & potential) -> Propagator<State> {
return [initial_step_size,
tolerance,
gradient_tolerance,
total_steps,
&cwa_smd_opt_operator,
type,
print_level
]
(const State & state,
const double dt) -> State {
const arma::vec & ref_expectations = state.expectations;
const arma::mat & points = state.points;
const auto & original_operators = cwa_smd_opt_operator.original_operators;
details::cwa_smd_opt_param input{points, ref_expectations,
original_operators,
state.weights, state.scaling,
(long long) state.grade};
const auto opt_result = details::cwa_optimize(input, initial_step_size,
tolerance, gradient_tolerance, total_steps, type);
const arma::mat new_points = std::get<0>(opt_result);
const double f = std::get<1>(opt_result);
const double df = std::get<2>(opt_result);
const int iter = std::get<3>(opt_result);
if(print_level > 2) {
fmt::print("f: {0:20.10f}, df: {1:20.10f}, iter: {2}", f, df, iter);
fmt::print("\n");
}
State new_state = state;
new_state.points = new_points;
return new_state;
};
};
}
} // namespace cwa
}
#endif //METHODS_CWA_SMD_OPT_H | {
"alphanum_fraction": 0.5934418495,
"avg_line_length": 33.8038277512,
"ext": "h",
"hexsha": "a9ce0d4d8eb0238a858a663f1c48f25c4947cf8c",
"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": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Walter-Feng/Quartz",
"max_forks_repo_path": "include/quartz_internal/details/methods/cwa_smd_opt.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b",
"max_issues_repo_issues_event_max_datetime": "2020-06-17T05:26:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-02-27T04:46:41.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Walter-Feng/Quartz",
"max_issues_repo_path": "include/quartz_internal/details/methods/cwa_smd_opt.h",
"max_line_length": 100,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Walter-Feng/Quartz",
"max_stars_repo_path": "include/quartz_internal/details/methods/cwa_smd_opt.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-01T01:27:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-18T09:34:46.000Z",
"num_tokens": 4720,
"size": 21195
} |
#include <math.h>
#include <stdlib.h>
#include <assert.h>
#include <cconfigspace.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#define NUM_DISTRIBS 2
#define NUM_SAMPLES 10000
void test_create_multivariate_distribution() {
const size_t num_distribs = NUM_DISTRIBS;
ccs_distribution_t distrib = NULL;
ccs_distribution_t distribs[NUM_DISTRIBS];
ccs_distribution_t distribs_ret[NUM_DISTRIBS];
ccs_result_t err = CCS_SUCCESS;
int32_t refcount;
ccs_object_type_t otype;
ccs_distribution_type_t dtype;
ccs_numeric_type_t data_types[NUM_DISTRIBS];
ccs_interval_t intervals[NUM_DISTRIBS];
size_t num_distribs_ret;
err = ccs_create_uniform_distribution(
CCS_NUM_FLOAT,
CCSF(-5.0),
CCSF(5.0),
CCS_LINEAR,
CCSF(0.0),
distribs);
assert( err == CCS_SUCCESS );
err = ccs_create_uniform_distribution(
CCS_NUM_INTEGER,
CCSI(-5),
CCSI(5),
CCS_LINEAR,
CCSI(0),
distribs + 1);
assert( err == CCS_SUCCESS );
err = ccs_create_multivariate_distribution(
num_distribs,
distribs,
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_object_get_type(distrib, &otype);
assert( err == CCS_SUCCESS );
assert( otype == CCS_DISTRIBUTION );
err = ccs_distribution_get_type(distrib, &dtype);
assert( err == CCS_SUCCESS );
assert( dtype == CCS_MULTIVARIATE );
err = ccs_distribution_get_data_types(distrib, data_types);
assert( err == CCS_SUCCESS );
assert( data_types[0] == CCS_NUM_FLOAT );
assert( data_types[1] == CCS_NUM_INTEGER );
err = ccs_distribution_get_bounds(distrib, intervals);
assert( err == CCS_SUCCESS );
assert( intervals[0].type == CCS_NUM_FLOAT );
assert( intervals[0].lower.f == -5.0 );
assert( intervals[0].lower_included == CCS_TRUE );
assert( intervals[0].upper.f == 5.0 );
assert( intervals[0].upper_included == CCS_FALSE );
assert( intervals[1].type == CCS_NUM_INTEGER );
assert( intervals[1].lower.i == -5 );
assert( intervals[1].lower_included == CCS_TRUE );
assert( intervals[1].upper.i == 5 );
assert( intervals[1].upper_included == CCS_FALSE );
err = ccs_multivariate_distribution_get_num_distributions(distrib, &num_distribs_ret);
assert( err == CCS_SUCCESS );
assert( num_distribs_ret == num_distribs );
err = ccs_multivariate_distribution_get_distributions(distrib, num_distribs, distribs_ret, &num_distribs_ret);
assert( err == CCS_SUCCESS );
assert( num_distribs_ret == num_distribs );
for (size_t i = 0; i < num_distribs; i++)
assert( distribs_ret[i] == distribs[i] );
err = ccs_object_get_refcount(distrib, &refcount);
assert( err == CCS_SUCCESS );
assert( refcount == 1 );
for (size_t i = 0; i < num_distribs; i++) {
err = ccs_release_object(distribs[i]);
assert( err == CCS_SUCCESS );
}
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
}
void test_multivariate_distribution() {
ccs_distribution_t distrib = NULL, distribs[NUM_DISTRIBS];
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_distribs = NUM_DISTRIBS;
const size_t num_samples = NUM_SAMPLES;
ccs_numeric_t samples[NUM_SAMPLES*NUM_DISTRIBS];
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_uniform_distribution(
CCS_NUM_FLOAT,
CCSF(-5.0),
CCSF(5.0),
CCS_LINEAR,
CCSF(0.0),
distribs);
assert( err == CCS_SUCCESS );
err = ccs_create_uniform_distribution(
CCS_NUM_INTEGER,
CCSI(-5),
CCSI(5),
CCS_LINEAR,
CCSI(0),
distribs + 1);
assert( err == CCS_SUCCESS );
err = ccs_create_multivariate_distribution(
num_distribs,
distribs,
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
for (size_t i = 0; i < num_samples; i++) {
assert( samples[NUM_DISTRIBS*i].f >= -5.0 );
assert( samples[NUM_DISTRIBS*i].f < 5.0 );
assert( samples[NUM_DISTRIBS*i + 1].i >= -5 );
assert( samples[NUM_DISTRIBS*i + 1].i < 5 );
}
double mean = gsl_stats_mean((double*)samples, NUM_DISTRIBS, num_samples);
assert( mean < 0.0 + 0.1 );
assert( mean > 0.0 - 0.1 );
for (size_t i = 0; i < num_distribs; i++) {
err = ccs_release_object(distribs[i]);
assert( err == CCS_SUCCESS );
}
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
void test_multivariate_distribution_strided_samples() {
ccs_distribution_t distrib = NULL, distribs[NUM_DISTRIBS];
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_distribs = NUM_DISTRIBS;
const size_t num_samples = NUM_SAMPLES;
ccs_numeric_t samples[NUM_SAMPLES*(NUM_DISTRIBS+1)];
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_uniform_distribution(
CCS_NUM_FLOAT,
CCSF(-5.0),
CCSF(5.0),
CCS_LINEAR,
CCSF(0.0),
distribs);
assert( err == CCS_SUCCESS );
err = ccs_create_uniform_distribution(
CCS_NUM_INTEGER,
CCSI(-5),
CCSI(5),
CCS_LINEAR,
CCSI(0),
distribs + 1);
assert( err == CCS_SUCCESS );
err = ccs_create_multivariate_distribution(
num_distribs,
distribs,
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_strided_samples(distrib, rng, num_samples, NUM_DISTRIBS+1, samples);
assert( err == CCS_SUCCESS );
for (size_t i = 0; i < num_samples; i++) {
assert( samples[(NUM_DISTRIBS+1)*i].f >= -5.0 );
assert( samples[(NUM_DISTRIBS+1)*i].f < 5.0 );
assert( samples[(NUM_DISTRIBS+1)*i + 1].i >= -5 );
assert( samples[(NUM_DISTRIBS+1)*i + 1].i < 5 );
}
double mean = gsl_stats_mean((double*)samples, NUM_DISTRIBS+1, num_samples);
assert( mean < 0.0 + 0.1 );
assert( mean > 0.0 - 0.1 );
for (size_t i = 0; i < num_distribs; i++) {
err = ccs_release_object(distribs[i]);
assert( err == CCS_SUCCESS );
}
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
void test_multivariate_distribution_soa_samples() {
ccs_distribution_t distrib = NULL, distribs[NUM_DISTRIBS];
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_distribs = NUM_DISTRIBS;
const size_t num_samples = NUM_SAMPLES;
ccs_numeric_t samples1[NUM_SAMPLES];
ccs_numeric_t samples2[NUM_SAMPLES];
ccs_numeric_t *samples[] = { samples1, samples2 };
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_uniform_distribution(
CCS_NUM_FLOAT,
CCSF(-5.0),
CCSF(5.0),
CCS_LINEAR,
CCSF(0.0),
distribs);
assert( err == CCS_SUCCESS );
err = ccs_create_uniform_distribution(
CCS_NUM_INTEGER,
CCSI(-5),
CCSI(5),
CCS_LINEAR,
CCSI(0),
distribs + 1);
assert( err == CCS_SUCCESS );
err = ccs_create_multivariate_distribution(
num_distribs,
distribs,
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_soa_samples(distrib, rng, num_samples, samples);
assert( err == CCS_SUCCESS );
for (size_t i = 0; i < num_samples; i++) {
assert( samples1[i].f >= -5.0 );
assert( samples1[i].f < 5.0 );
assert( samples2[i].i >= -5 );
assert( samples2[i].i < 5 );
}
double mean = gsl_stats_mean((double*)samples1, 1, num_samples);
assert( mean < 0.0 + 0.1 );
assert( mean > 0.0 - 0.1 );
for (size_t i = 0; i < num_distribs; i++) {
err = ccs_release_object(distribs[i]);
assert( err == CCS_SUCCESS );
}
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
void test_distribution_hyperparameters_sample() {
const size_t num_distribs = NUM_DISTRIBS;
ccs_distribution_t distrib = NULL, distribs[NUM_DISTRIBS];
ccs_hyperparameter_t params[NUM_DISTRIBS];
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
ccs_datum_t samples[NUM_SAMPLES*NUM_DISTRIBS];
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_uniform_distribution(
CCS_NUM_FLOAT,
CCSF(-4.0),
CCSF(4.0),
CCS_LINEAR,
CCSF(0.0),
distribs);
assert( err == CCS_SUCCESS );
err = ccs_create_uniform_distribution(
CCS_NUM_FLOAT,
CCSF(-3.0),
CCSF(5.0),
CCS_LINEAR,
CCSF(0.0),
distribs + 1);
assert( err == CCS_SUCCESS );
err = ccs_create_numerical_hyperparameter("param1", CCS_NUM_FLOAT,
CCSF(-5.0), CCSF(5.0),
CCSF(0.0), CCSF(0.0),
NULL, params);
assert( err == CCS_SUCCESS );
err = ccs_create_numerical_hyperparameter("param2", CCS_NUM_FLOAT,
CCSF(-4.0), CCSF(6.0),
CCSF(0.0), CCSF(1.0),
NULL, params + 1);
assert( err == CCS_SUCCESS );
err = ccs_create_multivariate_distribution(
num_distribs,
distribs,
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_hyperparameters_samples(distrib, rng, params, num_samples, samples);
assert( err == CCS_SUCCESS );
for (size_t i = 0; i < num_samples; i++) {
assert( samples[NUM_DISTRIBS*i].type == CCS_FLOAT );
assert( samples[NUM_DISTRIBS*i].value.f >= -5.0 );
assert( samples[NUM_DISTRIBS*i].value.f < 5.0 );
assert( samples[NUM_DISTRIBS*i + 1].type == CCS_FLOAT );
assert( samples[NUM_DISTRIBS*i + 1].value.f >= -4.0 );
assert( samples[NUM_DISTRIBS*i + 1].value.f < 6.0 );
}
double mean = gsl_stats_mean((double*)samples, NUM_DISTRIBS*2, num_samples);
assert( mean < 0.0 + 0.1 );
assert( mean > 0.0 - 0.1 );
mean = gsl_stats_mean((double*)samples + 2, NUM_DISTRIBS*2, num_samples);
assert( mean < 1.0 + 0.1 );
assert( mean > 1.0 - 0.1 );
for (size_t i = 0; i < num_distribs; i++) {
err = ccs_release_object(distribs[i]);
assert( err == CCS_SUCCESS );
err = ccs_release_object(params[i]);
assert( err == CCS_SUCCESS );
}
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
void test_distribution_hyperparameters_sample_oversampling() {
const size_t num_distribs = NUM_DISTRIBS;
ccs_distribution_t distrib = NULL, distribs[NUM_DISTRIBS];
ccs_hyperparameter_t params[NUM_DISTRIBS];
ccs_rng_t rng = NULL;
ccs_result_t err = CCS_SUCCESS;
const size_t num_samples = NUM_SAMPLES;
ccs_datum_t samples[NUM_SAMPLES*NUM_DISTRIBS];
err = ccs_rng_create(&rng);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
0.0,
4.0,
CCS_LINEAR,
CCSF(0.0),
distribs);
assert( err == CCS_SUCCESS );
err = ccs_create_normal_distribution(
CCS_NUM_FLOAT,
1.0,
4.0,
CCS_LINEAR,
CCSF(0.0),
distribs + 1);
assert( err == CCS_SUCCESS );
err = ccs_create_numerical_hyperparameter("param1", CCS_NUM_FLOAT,
CCSF(-5.0), CCSF(5.0),
CCSF(0.0), CCSF(0.0),
NULL, params);
assert( err == CCS_SUCCESS );
err = ccs_create_numerical_hyperparameter("param2", CCS_NUM_FLOAT,
CCSF(-4.0), CCSF(6.0),
CCSF(0.0), CCSF(1.0),
NULL, params + 1);
assert( err == CCS_SUCCESS );
err = ccs_create_multivariate_distribution(
num_distribs,
distribs,
&distrib);
assert( err == CCS_SUCCESS );
err = ccs_distribution_hyperparameters_samples(distrib, rng, params, num_samples, samples);
assert( err == CCS_SUCCESS );
for (size_t i = 0; i < num_samples; i++) {
assert( samples[NUM_DISTRIBS*i].type == CCS_FLOAT );
assert( samples[NUM_DISTRIBS*i].value.f >= -5.0 );
assert( samples[NUM_DISTRIBS*i].value.f < 5.0 );
assert( samples[NUM_DISTRIBS*i + 1].type == CCS_FLOAT );
assert( samples[NUM_DISTRIBS*i + 1].value.f >= -4.0 );
assert( samples[NUM_DISTRIBS*i + 1].value.f < 6.0 );
}
double mean = gsl_stats_mean((double*)samples, NUM_DISTRIBS*2, num_samples);
assert( mean < 0.0 + 0.1 );
assert( mean > 0.0 - 0.1 );
mean = gsl_stats_mean((double*)samples + 2, NUM_DISTRIBS*2, num_samples);
assert( mean < 1.0 + 0.1 );
assert( mean > 1.0 - 0.1 );
for (size_t i = 0; i < num_distribs; i++) {
err = ccs_release_object(distribs[i]);
assert( err == CCS_SUCCESS );
err = ccs_release_object(params[i]);
assert( err == CCS_SUCCESS );
}
err = ccs_release_object(distrib);
assert( err == CCS_SUCCESS );
err = ccs_release_object(rng);
assert( err == CCS_SUCCESS );
}
int main() {
ccs_init();
test_create_multivariate_distribution();
test_multivariate_distribution();
test_multivariate_distribution_strided_samples();
test_multivariate_distribution_soa_samples();
test_distribution_hyperparameters_sample();
test_distribution_hyperparameters_sample_oversampling();
ccs_fini();
return 0;
}
| {
"alphanum_fraction": 0.6592507645,
"avg_line_length": 29.592760181,
"ext": "c",
"hexsha": "0c281b110fb5542393966d4083555d8e05b174e2",
"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": "tests/test_multivariate_distribution.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": "tests/test_multivariate_distribution.c",
"max_line_length": 111,
"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": "tests/test_multivariate_distribution.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": 3818,
"size": 13080
} |
#ifndef LIBGAD
#define LIBGAD
#ifndef NOPOT
#define POTENTIAL
#endif
#include <stdio.h>
#include <math.h>
#ifndef NOGSL
#ifndef GSL
#define GSL
#endif
#endif
#ifdef GSL
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_linalg.h>
#endif
#define MIN(a, b) ((a)<(b)?(a):(b))
#define MAX(a, b) ((a)>(b)?(a):(b))
#define ABS(a) ((a) >= 0 ? (a) : -(a))
#define SQR(x) ((x)*(x))
#define OMEGA_M 0.26
#define OMEGA_L 0.74
#define HUB 0.72
#define GRAV 6.6742e-11
#define MSUN 1.989e30
#define KPC 3.085678e19 //meters
#define sec_per_yr 3.155e7
#define GALAGE(a) galage(a, OMEGA_M, OMEGA_L, HUB)
#define TIMEDIFF(a,b) timediff(a, b, OMEGA_M, OMEGA_L, HUB)
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifdef LONGIDS
typedef unsigned long long IDtype;
#else
typedef unsigned int IDtype;
#endif
typedef float fltarr[3];
struct header
{
int npart[6];
double massarr[6];
double time;
double redsh;
int flg_sfr;
int flg_fdbck;
int nall[6];
int flag_cool;
int numfiles;
double boxsize;
double omega0;
double omegal;
double hubparam;
int flg_age;
int flg_mtl;
int bytesleft[22];
};
typedef struct sphdata
{
float u;
float rho;
float nelec;
float nh;
float hsml;
float sfr;
#ifdef WINDS
float dtime;
float metals[4];
float tmax;
float n_spawn;
#endif //WINDS
#ifdef METALS
float temp;
#endif
} sphdata;
#if defined(WINDS) || defined(METALS)
typedef struct stardata
{
#ifdef WINDS
float metals[4];
float tmax;
float n_spawn;
#else
int let;
float initialmass;
#endif
} stardata;
#endif //WINDS || METALS
typedef struct gadpart
{
fltarr pos;
#ifndef NOVEL
fltarr vel;
#endif //NOVEL
float mass;
IDtype id;
short type;
#ifndef NOGAS
sphdata *sph;
float stellarage;
#endif
#ifdef POTENTIAL
float pot;
#endif
#if defined(WINDS) || defined(METALS)
stardata *sd;
#endif //WINDS
#ifdef METALS
float* metals;
#endif
} gadpart;
typedef struct gadpart_dist
{
gadpart part;
double dist;
} gadpart_dist;
int cmp_id (const void *first, const void *second);
int cmp_pointer_id(const void *a, const void *b);
int cmp_type (const void *first, const void *second);
int cmp_pos (const void *first, const void *second);
int cmp_x (const void *first, const void *second);
int cmp_y (const void *first, const void *second);
int cmp_z (const void *first, const void *second);
int cmp_dist (const void *first, const void *second);
int cmp_int (const void *first, const void *second);
int cmp_float (const void *first, const void *second);
unsigned int readgadget(char *filename, struct header *h, fltarr **p, fltarr **v, int **n, float **m);
unsigned int readgadget_part(char *filename, struct header *h,struct gadpart **part);
#ifdef LONGIDS
unsigned int writegadget(char *filename, struct header h, fltarr *p, fltarr *v, long *n, float *m);
#else
unsigned int writegadget(char *filename, struct header h, fltarr *p, fltarr *v, int *n, float *m);
#endif
unsigned int writegadget_part(char *filename, struct header h, struct gadpart *part);
unsigned int readgadget_novel(char *filename, struct header *h, fltarr **p, int **n, float **m);
unsigned int readgadget_sph(char *filename, struct header *h, fltarr **p, fltarr **v, int **n, float **m, float **u, float **rho, float **d1, float **d2, float **d3, float **d4 , float **sa);
int convertunits(struct header *head, struct gadpart *part, double convert_mass, double convert_distance);
double distance(fltarr a, fltarr b);
double distance_nopb(fltarr a, fltarr b);
double distbox(fltarr a, fltarr min, fltarr max);
double distbox_nopb(fltarr a, fltarr min, fltarr max);
void cpygadpart(gadpart * to, gadpart * from);
int gadsearch(gadpart_dist *data, double toFind, int start, int end);
double nfwfit(double *par, gadpart_dist *part, int cnt, double rv, double soft, double *rcs);
double densproffit(double *par, gadpart_dist *part, int cnt, double re, double soft, double *rcs, int type);
void calcdist(gadpart_dist *gd, int cnt, float *center);
void simplecenter(gadpart *part, int cnt, double* cm, int use);
void pcenter(gadpart_dist *part, int cnt, double, float*, int);
void findcenter(gadpart *part, int cnt, double maxdist, int use);
void simplecm(gadpart ** part, int cnt, float * cm);
double r200(gadpart_dist* pd, int cnt, double denscontrast, struct header h, int *vcnt, double *mvir);
double xoffset(gadpart_dist* pd, int cnt, float rvir, float* center);
#ifndef NOGAS
double temperature(const gadpart part);
#endif //NOGAS
void dummyfunction();
double galage(double z, double omegam, double omegal, double h);
double timediff(double z1, double z2, double omegam, double omegal, double h);
double a2z(double a);
double z2a(double z);
double angle(fltarr a, fltarr b);
double radvel(fltarr vel, fltarr rad);
struct header cphead(struct header head, gadpart* part, int cnt);
#ifdef GSL
void rotatepart(gadpart *part, int numpart, const gsl_matrix *rotmat);
void xrotate(double angle, gadpart *part, int numpart);
void yrotate(double angle, gadpart *part, int numpart);
void zrotate(double angle, gadpart *part, int numpart);
void rotategalaxy(gadpart *part, int numpart, double rad, int use, double *res, gsl_matrix **rotation);
#endif
#endif //LIBGAD
| {
"alphanum_fraction": 0.7188140966,
"avg_line_length": 27.7875647668,
"ext": "h",
"hexsha": "6fd4a442db59520e5cb3f4fb4916aadbff71e511",
"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": "libgad.h",
"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": "libgad.h",
"max_line_length": 191,
"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": "libgad.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1679,
"size": 5363
} |
/*
* This file implements a Python extension, wrapping the capabilities of the "RADAR5" FORTRAN code.
*/
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <Python.h>
#include "capsulethunk.h"
#define WITH_TCC
#ifdef WITH_TCC
#include "tcc/libtcc.h"
#endif
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
#ifdef _MSC_VER
# define GSL_DLL
# define WIN32
#endif
#ifdef WITH_GSL
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#else
#include "cspline.c"
#endif
#include "radar5.h"
#ifndef MIN
#define MIN(a,b) (((a)>(b))?(b):(a))
#endif
#ifndef MAX
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif
typedef void (*equ_c_t)(double *F, const double *Y, double X, double (*lag)(int, int, void*), void *ctx, void *params);
typedef double (*lag_c_t)(double X, const double *Y);
typedef struct
{
double *X,*Y;
ARGLAG_t ARGLAG;
PHI_t PHI;
double *RPAR;
int *IPAR;
double *PAST;
int *IPAST, *NRDS;
int lag_flag[10];
int ipos[10];
double alphas[10];
} _lag_ctx;
typedef struct params_ params_t;
struct params_
{
PyObject_HEAD
int full_output;
int xpos;
double *xvalues;
int xvalues_len;
double *array;
unsigned int array_size;
unsigned int array_pos;
unsigned int array_incr;
PyObject *py_fcn;
equ_c_t c_fcn;
PyObject *py_y0[10];
double constant_y0[10];
PyObject *py_lagfuns[10];
lag_c_t c_lagfuns[10];
double constant_lags[10];
PyThreadState *_thread_save;
int interactive;
int fail;
void *user_params;
PyObject *py_rpar;
PyObject *py_lag_callback;
#if WITH_GSL
gsl_interp_accel *spline_acc;
gsl_spline **y0_spline;
#else
cspline_t *y0_spline;
#endif
double y0_t0;
_lag_ctx *lag_ctx;
params_t *next, *prev;
};
static double _lag_c(int il, int ip, _lag_ctx *ctx)
{
int IL = il + 1, IP = ip + 1;
/* Store the result of LAGR5 for a little speedup if a delay is used for more than one variable... */
if(ctx->lag_flag[il] == 0)
{
lagr5_(&IL,ctx->X,ctx->Y,ctx->ARGLAG,ctx->PAST,&ctx->alphas[il],&ctx->ipos[il],ctx->RPAR,ctx->IPAR,ctx->PHI,ctx->IPAST,ctx->NRDS);
ctx->lag_flag[il] = 1;
}
/* Effective computation of the delayed value for this variable. */
return ylagr5_(&IP,&ctx->alphas[il],&ctx->ipos[il],ctx->PHI,ctx->RPAR,ctx->IPAR,ctx->PAST,ctx->IPAST,ctx->NRDS);
}
static PyObject *_lag_py(PyObject *self, PyObject *args)
{
int il, ip;
params_t *p = PyCapsule_GetPointer(self, NULL);
PyArg_ParseTuple(args, "ii", &il, &ip);
return PyFloat_FromDouble(_lag_c(il, ip, p->lag_ctx));
}
static void FCN(int *N, double *X, double *Y, double *F, ARGLAG_t ARGLAG, PHI_t PHI, double *RPAR, int *IPAR, double *PAST,int *IPAST, int *NRDS)
{
int i, len;
PyObject *seq;
PyObject *ret;
PyObject *y_array;
npy_intp dims[1] = {*N};
params_t *p = (params_t*)IPAR;
_lag_ctx ctx = {X,Y,ARGLAG,PHI,RPAR,IPAR,PAST,IPAST,NRDS,{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0}};
/* If it's a C function then it's easy, just run it. */
if(p->c_fcn)
{
p->c_fcn(F,Y,*X,(void*)_lag_c,&ctx,RPAR);
return;
}
if(p->fail)
return;
/* If it's a Python function, then we have to tell Python we're going to maybe modify things. */
if(!p->interactive)
{
PyEval_RestoreThread(p->_thread_save);
p->_thread_save = NULL;
}
p->lag_ctx = &ctx;
/* Create an array from Y values */
y_array = PyArray_SimpleNewFromData(1,dims,NPY_DOUBLE,Y);
/* Call the function, with following signature : func(Y, X, lagfun, params if any) */
if(p->py_rpar)
ret = PyObject_CallFunctionObjArgs(p->py_fcn, y_array, PyFloat_FromDouble(*X), p->py_lag_callback, p->py_rpar, NULL);
else
ret = PyObject_CallFunctionObjArgs(p->py_fcn, y_array, PyFloat_FromDouble(*X), p->py_lag_callback, NULL);
if(!ret)
{
PyErr_Print();
Py_DECREF(y_array);
if(!p->interactive) p->_thread_save = PyEval_SaveThread();
p->fail = 1;
return;
}
Py_DECREF(y_array);
seq = PySequence_Fast(ret, "Equation must return a sequence !");
if(!seq)
{
PyObject *a, *b, *c;
double dy;
PyErr_Fetch(&a, &b, &c);
PyErr_Clear();
dy = PyFloat_AsDouble(ret);
if(!PyErr_Occurred() && *N == 1)
{
if(a) Py_DECREF(a);
if(b) Py_DECREF(b);
if(c) Py_DECREF(c);
F[0] = dy;
goto cleanup;
}
else
{
PyErr_Restore(a, b, c);
if(!p->interactive) p->_thread_save = PyEval_SaveThread();
p->fail = 4;
return;
}
}
len = PySequence_Size(ret);
if(len != *N)
{
PySys_WriteStderr("Equation returned a sequence of wrong size (%d, expected %d)...\n",len,*N);
PyErr_SetString(PyExc_RuntimeError, "Equation function returned bad F(Y) length.");
p->fail = 5;
if(!p->interactive) p->_thread_save = PyEval_SaveThread();
Py_DECREF(ret);
return;
}
/* Give the output values to the integrator */
for(i = 0; i < *N; i++)
{
PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
F[i] = PyFloat_AsDouble(item);
}
Py_DECREF(seq);
cleanup:
Py_DECREF(ret);
if(!p->interactive) p->_thread_save = PyEval_SaveThread();
}
static double PHI(int *I, double *X, double *RPAR, int *IPAR)
{
PyObject *ret;
int i = *I - 1;
params_t *p = (params_t*)IPAR;
PyObject *fun = p->py_y0[i];
double y0;
if(fun)
{
if(!p->interactive && p->_thread_save) {
PyEval_RestoreThread(p->_thread_save);
}
ret = PyObject_CallFunction(fun, "d", *X);
if(!ret || PyErr_Occurred())
{
PyErr_Print();
p->fail = 1;
if(!p->interactive && p->_thread_save) p->_thread_save = PyEval_SaveThread();
return 0;
}
y0 = PyFloat_AsDouble(ret);
if(PyErr_Occurred())
{
PyErr_Print();
p->fail = 4;
}
Py_DECREF(ret);
if(!p->interactive && p->_thread_save) p->_thread_save = PyEval_SaveThread();
return y0;
}
else if(p->y0_spline)
{
#ifdef WITH_GSL
return gsl_spline_eval (p->y0_spline[i], *X + p->y0_t0, p->spline_acc);
#else
double y = 0;
cspline_eval(&p->y0_spline[i], *X + p->y0_t0, &y);
return y;
#endif
// fprintf(stderr,"PHI(%g->%g)[%d]=%g\n",*X,*X+p->y0_t0,i,y);
}
else
{
return p->constant_y0[i];
}
}
static double ARGLAG(int *IL, double *X, double *Y,double *RPAR, int *IPAR, PHI_t PHI, double *PAST, int *IPAST, int *NRDS)
{
PyObject *ret;
int ilag = *IL-1;
params_t *p = (params_t*)IPAR;
PyObject *pyfun = p->py_lagfuns[ilag];
lag_c_t cfun = p->c_lagfuns[ilag];
double r;
if(!pyfun)
{
if(!cfun)
{
return *X-p->constant_lags[ilag];
}
else
{
return cfun(*X,Y);
}
}
else
{
if(!p->interactive && p->_thread_save) PyEval_RestoreThread(p->_thread_save);
ret = PyObject_CallFunction(pyfun, "dd", *X, *Y);
if(!ret || PyErr_Occurred())
{
PyErr_Print();
}
r = PyFloat_AsDouble(ret);
Py_DECREF(ret);
// fprintf(stderr,"Lag %d: %p -> %f\n", ilag, fun, r);
if(!p->interactive && p->_thread_save) p->_thread_save = PyEval_SaveThread();
return r;
}
}
static void JFCN(int *N, double *X, double *Y, double *DFY, int LDFY, ARGLAG_t ARGLAG, PHI_t PHI, double *RPAR, int *IPAR, double *PAST,int *IPAST, int *NRDS)
{
fprintf(stderr,"JFCN\n");
}
static void JACLAG(int *N, double *X, double *Y, int *DFYL, ARGLAG_t ARGLAG, PHI_t PHI, int *IVE, int *IVC, int *IVL, double *RPAR, int *IPAR, double *PAST, int *IPAST, int *NRDS)
{
fprintf(stderr,"JACLAG\n");
}
static void SOLOUT(int *NR, double *XOLD, double *X, double *HSOL, double *Y, double *CONT, int *LRC, int *N, double *RPAR, int *IPAR, int *IRTRN)
{
int i;
params_t *p = (params_t*)IPAR;
double *ptr;
double *new_array;
double next_x;
if(p->interactive)
{
if(PyErr_CheckSignals())
{
p->fail = 6;
}
}
if(p->fail)
{
*IRTRN = -1;
return;
}
// fprintf(stderr,"h=%g, dx=%g\n",*HSOL,*X-*XOLD);
// fprintf(stderr,"SOLOUT %f %f / %p %d %d %d\n",*X,*Y, p->array,p->array_size,p->array_pos,p->array_incr);
if(p->xvalues)
{
if(*NR == 1)
{
ptr = p->array + p->array_pos * (*N+1);
ptr[0] = *X;
for(i = 0; i < *N; i++)
{
ptr[i + 1] = Y[i];
}
p->array_pos += 1;
p->xpos += 1;
}
next_x = p->xvalues[p->xpos];
while(*X >= next_x && p->xpos < p->xvalues_len)
{
if(p->array_size == p->array_pos)
{
p->array_size += p->array_incr;
// fprintf(stderr,"realloc %d->%d (%i)", p->array_size - p->array_incr, p->array_size , p->array_size*(*N+1)*sizeof(double));
new_array = PyMem_Realloc(p->array, p->array_size*(*N+1)*sizeof(double));
if(new_array == NULL)
{
p->fail = 2;
*IRTRN = -1;
return;
}
// fprintf(stderr," -> %p\n", new_array);
p->array = new_array;
}
ptr = p->array + p->array_pos * (*N+1);
ptr[0] = next_x;
for(i = 1; i < *N + 1; i++)
{
ptr[i] = contr5_(&i, N, &next_x, CONT, X, HSOL);
}
p->array_pos += 1;
p->xpos += 1;
next_x = p->xvalues[p->xpos];
}
}
if(p->full_output)
{
if(p->array_size == p->array_pos)
{
p->array_size += p->array_incr;
// fprintf(stderr,"realloc %d->%d (%i)", p->array_size - p->array_incr, p->array_size , p->array_size*(*N+1)*sizeof(double));
new_array = PyMem_Realloc(p->array, p->array_size*(*N+1)*sizeof(double));
if(new_array == NULL)
{
p->fail = 2;
*IRTRN = -1;
return;
}
// fprintf(stderr," -> %p\n", new_array);
p->array = new_array;
}
ptr = p->array + p->array_pos * (*N+1);
ptr[0] = *X;
for(i = 0; i < *N; i++)
{
ptr[i+1] = Y[i];
}
p->array_pos += 1;
}
}
void _tcc_error(void *opaque, const char *msg)
{
PyErr_SetString(PyExc_RuntimeError, msg);
//PySys_WriteStderr("! %s\n", msg);
}
// radar5(equ,y0,xend,[rpar],grid=grid)
static params_t *current_p = NULL;
static PyMethodDef py_lag_def = {"lag", _lag_py, METH_VARARGS, "Returns delayed values of variables inside right-hand-side function."};
static PyObject *radar5_radar5(PyObject *self, PyObject *args,PyObject *keywds)
{
PyObject *output_array = NULL;
int verbose = 0;
int NGRID = 200;
double XEND = 100;
int N = 0;
int MXST = 4*16384;
params_t par;
params_t *p = ∥
int *IPAR = (void*)p;
double X = 0;
double *Y = NULL;
double H = 1e-6;
double RTOL = 1e-6;
double ATOL = RTOL;
double ITOL = 0;
int IJAC = 0;
int MLJAC = N;
int MUJAC = 0; // not needed
int NLAGS = 0;
int NJACL = 0;
int IMAS = 0;
int IOUT = verbose ? 1 : 3;
double WORK[30];
int IWORK[30];
double *RPAR = NULL;
int IDID = 0;
int *IPAST = NULL;
int DUMMY;
int MLMAS = N;
int MUMAS = 0; // not needed
int RPAR_len = 0;
double *GRID = NULL;
int i;
int prev_interactive;
PyObject* rpar_obj=NULL;
PyObject* lagvars_obj=NULL;
PyObject* lagfuns_obj=NULL;
PyObject* equ_obj=NULL;
PyObject* y0_obj=NULL;
PyObject* xend_obj=NULL;
int full_output_flag = 0;
PyObject *py_p = NULL;
int len;
#ifdef WITH_TCC
TCCState *tcc = NULL;
#endif
/* Parse arguments */
static char *kwlist[] = {"equ", "y0", "xend", "rpar", "ngrid", "lagvars", "lags", "verbose", "mxst", "full_output", "rtol", "atol", "initial_stepsize", NULL};
memset(p,0,sizeof(params_t));
if (!PyArg_ParseTupleAndKeywords(args, keywds, "OOO|OiOOiiifff", kwlist, &equ_obj, &y0_obj, &xend_obj, &rpar_obj, &NGRID, &lagvars_obj, &lagfuns_obj, &verbose, &MXST,&full_output_flag,&RTOL,&ATOL,&H))
return NULL;
if(verbose) PySys_WriteStderr("RADAR5 wrapper (verbose = %d)\n", verbose);
/* SPECIFIED X VALUES OR XEND */
if(xend_obj)
{
PyArrayObject *xvalues = (PyArrayObject*)PyArray_ContiguousFromAny(xend_obj, NPY_DOUBLE, 0, 1);
if(xvalues == NULL)
{
PyErr_SetString(PyExc_ValueError, "Cannot parse x values.");
goto cleanup;
}
p->full_output = full_output_flag; /* Full output only if specified... */
if(PyArray_NDIM(xvalues) == 0) /* if a single value if given for X, force full output */
{
p->xvalues = NULL;
p->full_output = 1;
XEND = *(double*)PyArray_GETPTR1(xvalues, 0);
if(verbose) PySys_WriteStderr("Full output up to X=%g (all points)\n", XEND);
}
else
{
p->xvalues = (double*)PyArray_GETPTR1(xvalues, 0);
p->xvalues_len = PyArray_DIM(xvalues, 0);
p->xpos = 0;
XEND = p->xvalues[p->xvalues_len - 1];
if(verbose) PySys_WriteStderr("%s output up to X=%g (%d points)\n", p->full_output ? "Full" : "User-specified", XEND, p->xvalues_len);
}
}
/* LOADING INITIAL VALUES : */
if(y0_obj)
{
PyObject *seq = PySequence_Fast(y0_obj, "Initial values must be provided as a sequence.");
if(!seq)
return NULL;
len = PySequence_Size(y0_obj);
if(len == 2)
{
/* It might be a tuple (time, values) */
PyObject *time = PySequence_Fast_GET_ITEM(seq, 0);
PyObject *values = PySequence_Fast_GET_ITEM(seq, 1);
/* Check each of (time, values) is iterables. If it is, we suppose we can use them as array. */
if(PySequence_Check(time) && PySequence_Check(values))
{
int y0_len;
PyArrayObject *time_array = (PyArrayObject*)PyArray_ContiguousFromAny(time, NPY_DOUBLE, 1, 1);
PyArrayObject *values_array = (PyArrayObject*)PyArray_ContiguousFromAny(values, NPY_DOUBLE, 1, 2);
/* Account for format errors */
if(!time_array || !values_array)
{
PyErr_Print();
return NULL;
}
y0_len = PyArray_DIM(time_array, 0); /* Get initial sequence length */
if(PyArray_NDIM(values_array) == 1) N = 1;
else N = PyArray_DIM(values_array, 1); /* Get system dimension from initial data */
p->y0_t0 = *(double*)PyArray_GETPTR1(time_array, y0_len - 1); /* Get the final time of the initial sequence */
if(verbose) PySys_WriteStderr("Initial values array as (time->%g, [i0:%d])\n", p->y0_t0, y0_len);
#ifdef WITH_GSL
p->y0_spline = (gsl_spline**)malloc(sizeof(void*) * N);
#else
p->y0_spline = (cspline_t*)malloc(sizeof(cspline_t) * N);
#endif
for(i = 0; i < N; i++)
{
int j;
#ifdef WITH_GSL
gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline, y0_len);
#else
cspline_t *spline = &p->y0_spline[i];
cspline_init(spline);
cspline_alloc_xy(spline, y0_len);
#endif
/* Copy time data */
memcpy (spline->x, (double*)PyArray_DATA(time_array), y0_len * sizeof(double));
/* Copy variable data */
for(j = 0; j < y0_len; j++)
{
spline->y[j] = *(double*)PyArray_GETPTR2(values_array, j, i);
}
/* Initialize interpolator */
#ifdef WITH_GSL
gsl_interp_init (spline->interp, spline->x, spline->y, y0_len);
p->y0_spline[i] = spline;
#else
cspline_compute_nat (spline);
#endif
}
Py_DECREF(time_array);
Py_DECREF(values_array);
}
}
else if(len > 0 && PySequence_Check(PySequence_Fast_GET_ITEM(seq, 0)))
{
int y0_len;
/* Looks like a 2D array : time data might be its first row. This is useful to "continue" an integration, because it's the integrator output format. */
PyArrayObject *full_array = (PyArrayObject*)PyArray_ContiguousFromAny(y0_obj, NPY_DOUBLE, 2, 2);
if(PyErr_Occurred())
{
Py_DECREF(seq);
goto cleanup;
}
y0_len = PyArray_DIM(full_array, 0);
N = PyArray_DIM(full_array, 1) - 1;
p->y0_t0 = *(double*)PyArray_GETPTR2(full_array, y0_len - 1, 0);
#ifdef WITH_GSL
p->y0_spline = (gsl_spline**)malloc(sizeof(void*) * N);
#else
p->y0_spline = (cspline_t*)malloc(sizeof(cspline_t) * N);
#endif
if(verbose) PySys_WriteStderr("Initial values array as [time->%g, y0:%d]\n", p->y0_t0, y0_len);
for(i = 0; i < N; i++)
{
int j;
#ifdef WITH_GSL
gsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline, y0_len);
#else
cspline_t *spline = &p->y0_spline[i];
cspline_init(spline);
cspline_alloc_xy(spline, y0_len);
#endif
for(j = 0; j < y0_len; j++)
{
spline->x[j] = *(double*)PyArray_GETPTR2(full_array, j, 0);
spline->y[j] = *(double*)PyArray_GETPTR2(full_array, j, i + 1);
}
#ifdef WITH_GSL
gsl_interp_init (spline->interp, spline->x, spline->y, y0_len);
p->y0_spline[i] = spline;
#else
cspline_compute_nat (spline);
#endif
}
Py_DECREF(full_array);
}
if(!p->y0_spline)
{
/* Each variable is specified on its own. */
for (i = 0; i < len; i++)
{
PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
/* Check whether it's a Python function or a constant value. */
if(PyCallable_Check(item))
{
p->py_y0[i] = item;
if(verbose)
{
PyObject *repr = PyObject_Repr(item);
#if PY_MAJOR_VERSION >= 3
PySys_WriteStderr("Initial value: y[%d](t<0) = %s\n", i, PyUnicode_AsUTF8(repr));
#else
PySys_WriteStderr("Initial value: y[%d](t<0) = %s\n", i, PyString_AsString(repr));
#endif
Py_DECREF(repr);
}
}
else
{
double y0 = PyFloat_AsDouble(item);
if(PyErr_Occurred())
{
Py_DECREF(seq);
goto cleanup;
}
p->constant_y0[i] = y0;
p->py_y0[i] = NULL;
if(verbose) PySys_WriteStderr("Initial value: y[%d](t<0) = %g (constant)\n", i, y0);
}
}
N = len;
}
Py_DECREF(seq);
}
if(N == 0)
{
PyErr_SetString(PyExc_ValueError, "Could not guess system dimension from initial values.");
goto cleanup;
}
if(verbose) PySys_WriteStderr("System dimension: N = %d\n", N);
Y = (double*)malloc(N * sizeof(double));
IPAST = (int*)malloc(N * sizeof(int));
/* Set all integrator parameters to default values. */
for(i = 0; i < 30; i++)
{
WORK[i] = 0;
IWORK[i] = 0;
}
/* Load system numerical parameters. */
if(rpar_obj)
{
PyObject *seq = PySequence_Fast(rpar_obj, "Constant parameters must be provided as a sequence.");
if(!seq) goto cleanup;
RPAR_len = PySequence_Size(rpar_obj);
RPAR = malloc(sizeof(double) * RPAR_len);
for (i = 0; i < RPAR_len; i++) {
PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
RPAR[i] = PyFloat_AsDouble(item);
if(verbose) PySys_WriteStderr("Constant parameter %d : %g\n", i,RPAR[i]);
}
Py_DECREF(seq);
}
if(lagvars_obj)
{
PyObject *seq = PySequence_Fast(lagvars_obj, "Delayed variables must be provided as a sequence.");
if(!seq) goto cleanup;
len = PySequence_Size(lagvars_obj);
for (i = 0; i < len; i++) {
PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
int lagparam = PyLong_AsLong(item);
if(lagparam < 0 || lagparam >= N)
{
PyErr_SetString(PyExc_ValueError, "Invalid lag parameter");
Py_DECREF(seq);
goto cleanup;
}
IPAST[i]=lagparam+1;
if(verbose) PySys_WriteStderr("Variable %d is delayed (#%d)\n", lagparam, i);
}
IWORK[14] = i; // number of dense solution (lags)
Py_DECREF(seq);
}
else
{
/* By default, all variables are delayed */
for (i = 0; i < N; i++)
{
IPAST[i]=i+1;
}
IWORK[14] = N;
if(verbose) PySys_WriteStderr("Delayed variables unspecified: by default all %d variables are selected.\n", N);
}
if(lagfuns_obj)
{
PyObject *seq = PySequence_Fast(lagfuns_obj, "Lags must be provided as a sequence.");
if(!seq) goto cleanup;
len = PySequence_Size(lagfuns_obj);
for (i = 0; i < len; i++) {
PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
if(PyCallable_Check(item))
{
p->py_lagfuns[i]=item;
p->c_lagfuns[i]=NULL;
if(verbose)
{
PyObject *repr = PyObject_Repr(item);
#if PY_MAJOR_VERSION >= 3
PySys_WriteStderr("Lag %d is a Python function: %s\n", i, PyUnicode_AsUTF8(repr));
#else
PySys_WriteStderr("Lag %d is a Python function: %s\n", i, PyString_AsString(repr));
#endif
Py_DECREF(repr);
}
}
else if(PyNumber_Check(item))
{
double delay = PyFloat_AsDouble(item);
p->constant_lags[i]=delay;
p->py_lagfuns[i]=NULL;
p->c_lagfuns[i]=NULL;
if(verbose) PySys_WriteStderr("Lag %d is constant: %g\n", i, delay);
}
else
{
p->c_lagfuns[i]=PyCapsule_GetPointer(item, NULL);
p->py_lagfuns[i]=NULL;
if(verbose) PySys_WriteStderr("Lag %d is a raw C function: %p\n", i, p->c_lagfuns[i]);
}
}
Py_DECREF(seq);
}
/* Set RHS function, either Python or C. */
if(PyCallable_Check(equ_obj))
{
p->py_fcn = equ_obj;
p->c_fcn = NULL;
if(verbose)
{
PyObject *repr = PyObject_Repr(equ_obj);
#if PY_MAJOR_VERSION >= 3
PySys_WriteStderr("Equation is a Python function: %s\n", PyUnicode_AsUTF8(repr));
#else
PySys_WriteStderr("Equation is a Python function: %s\n", PyString_AsString(repr));
#endif
Py_DECREF(repr);
}
/* Create a Python wrapper for the function that will be used to get delayed values in RHS */
py_p = PyCapsule_New(p, NULL, NULL);
p->py_lag_callback = PyCFunction_New(&py_lag_def, py_p);
/* We need a Python version of RPAR */
if(RPAR_len > 0)
{
npy_intp dims[1] = {RPAR_len};
p->py_rpar = PyArray_SimpleNewFromData(1, dims, NPY_DOUBLE, RPAR);
}
}
#if PY_MAJOR_VERSION >= 3
else if(PyUnicode_Check(equ_obj))
{
#ifdef WITH_TCC
PyObject *str = PyUnicode_AsASCIIString(equ_obj);
if(!str)
goto cleanup;
#endif
#else
else if(PyString_Check(equ_obj))
{
PyObject *str = equ_obj;
#endif
#ifdef WITH_TCC
/* We need to provide some math functions in order to do useful stuff. */
const struct
{
const char *name;
void *ptr;
} symbols[] = {{"cos", cos}, {"sin", sin}, {"tan", tan},
{"acos", acos}, {"asin", asin}, {"atan", atan},
{"log", log}, {"pow", pow}, {"log10", log10},
{"cosh", cosh}, {"sinh", sinh}, {"tanh", tanh}};
const int nsymbols = sizeof(symbols)/sizeof(symbols[0]);
char *source = malloc(PyBytes_Size(str) + nsymbols * 128 + 128);
/* This one can be useful too. */
int pos = sprintf(source, "#define M_PI 3.14159265358979323846\n");
for(i = 0; i < nsymbols; i++)
pos += sprintf(source + pos, "double %s(double);", symbols[i].name);
sprintf(source + pos, "\n%s", PyBytes_AsString(str));
if(verbose) PySys_WriteStderr("Equation is C code, try to compile it...\n");
/* Create a minimal TCC context */
tcc = tcc_new();
tcc_set_options(tcc, "-nostdlib");
tcc_set_error_func(tcc, NULL, _tcc_error);
tcc_set_output_type(tcc, TCC_OUTPUT_MEMORY);
/* Compile the code snippet */
if(tcc_compile_string(tcc, source) < 0)
{
free(source);
goto cleanup;
}
//Py_DECREF(str);
free(source);
/* Add math symbols for the linking step. */
for(i = 0; i < nsymbols; i++)
tcc_add_symbol(tcc, symbols[i].name, symbols[i].ptr);
/* Linking */
if(tcc_relocate(tcc, TCC_RELOCATE_AUTO) < 0)
{
// PyErr_SetString(PyExc_RuntimeError, "Equation could not be compiled (relocation error).");
goto cleanup;
}
p->py_fcn = NULL;
p->c_fcn = tcc_get_symbol(tcc, "equation"); /* Get pointer to the compiled function */
if(!p->c_fcn)
{
p->c_fcn = tcc_get_symbol(tcc, "y");
if(!p->c_fcn)
{
p->c_fcn = tcc_get_symbol(tcc, "rhs");
if(!p->c_fcn)
{
PyErr_SetString(PyExc_ValueError, "No function named 'equation', 'y' or 'rhs' in provided C code.");
goto cleanup;
}
}
}
if(verbose) PySys_WriteStderr("Equation successfully compiled : %p\n", p->c_fcn);
#else
PyErr_SetString(PyExc_RuntimeError, "Equation provided as string, but we were compiled without TCC.");
goto cleanup;
#endif
}
else
{
p->py_fcn = NULL;
p->c_fcn = PyCapsule_GetPointer(equ_obj, NULL);
if(verbose) PySys_WriteStderr("Equation is a raw C function: %p\n", p->c_fcn);
}
GRID = malloc(sizeof(double) * (NGRID + 1));
if(p->xvalues)
{
p->array_size = p->xvalues_len;
}
else
{
p->array_size = NGRID; // taille initiale
}
p->array = PyMem_Malloc(p->array_size*(N+1)*sizeof(double));
if(verbose) PySys_WriteStderr("Allocate initial array (size %gkB) at %p\n", p->array_size*(N+1.)*sizeof(double)/1024, p->array);
p->array_pos = 0;
p->array_incr = p->array_size / 4; // increment taille
p->user_params = RPAR;
p->fail = 0;
p->interactive = 0;
IWORK[13] = 1; // ne pas utiliser JACLAG
/* NOTE: Black magic... */
IWORK[12] = NGRID; // WORKSPACE FOR GRID
// MXST = 1024*1024*32; //4*16384*IWORK[14]; //MAX(NGRID*IWORK[14],8192); // pourquoi c'était divisé par /N ?
IWORK[11] = MXST; // WORKSPACE FOR PAST
IWORK[1] = INT_MAX;
for(i = 0; i < NGRID; i++)
{
GRID[i] = XEND/(NGRID+1)*i;
}
/* Load initial values */
prev_interactive = p->interactive;
p->interactive = 1;
for(i=1;i<N+1;i++)
{
Y[i-1] = PHI(&i, &X, RPAR, IPAR);
if(verbose) PySys_WriteStderr("Initial value: Y[%d]=%g\n", i-1, Y[i-1]);
}
p->interactive = prev_interactive;
/* MAIN CALL TO THE INTEGRATOR AHEAD */
if(!p->interactive)
{
p->_thread_save = PyEval_SaveThread(); /* Promise Python that we are not going to mess with any of its data. */
/* This allows other threads/event loops to run during the integration. */
}
current_p = p;
radar5_(&N,FCN,PHI,ARGLAG,&X,Y,&XEND,&H, \
&RTOL,&ATOL,&ITOL, \
JFCN,&IJAC,&MLJAC,&MUJAC, \
JACLAG,&NLAGS,&NJACL, \
&IMAS,SOLOUT,&IOUT, \
WORK,IWORK,RPAR,IPAR,&IDID, \
GRID,IPAST,&DUMMY,&MLMAS,&MUMAS);
current_p = NULL;
if(!p->interactive)
{
PyEval_RestoreThread(p->_thread_save);
}
/* DONE ! */
if(verbose)
{
switch(p->fail)
{
case 1: PySys_WriteStderr("Python function produced an error.\n"); break;
case 3: PySys_WriteStderr("Computation halted by stop().\n"); break;
case 4:
case 5: PySys_WriteStderr("Python function provided wrong return type.\n"); break;
case 6: PySys_WriteStderr("Computation halted by an external signal.\n"); break;
}
}
if(p->fail == 2)
{
PyErr_SetString(PyExc_MemoryError, "Cannot grow output array.");
}
if(verbose)
{
PySys_WriteStderr("Solver output: IDID = %d (", IDID);
switch(IDID)
{
case 1: PySys_WriteStderr("Successful computation"); break;
case 2: PySys_WriteStderr("Successful computation interrupted by routine SOLOUT"); break;
case -1: PySys_WriteStderr("Non-consistent input values"); break;
case -2: PySys_WriteStderr("Too many stepsizes required (>NMAX)"); break;
case -3: PySys_WriteStderr("Stepsize becomes too small"); break;
case -4: PySys_WriteStderr("Jacobian matrix repeatedly singular"); break;
case -5: PySys_WriteStderr("Computation interrupted by routine YLAGR5"); break;
case -6: PySys_WriteStderr("The equation makes use of advanced arguments"); break;
default: PySys_WriteStderr("Unexpected return code"); break;
}
PySys_WriteStderr(")\nComputed points: %d\n", p->array_pos);
}
/* Create numpy array based on integrator output : */
{
npy_intp dims[2] = {p->array_pos, N+1};
output_array = PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE, p->array);
}
#if NPY_API_VERSION >= 9
PyArray_ENABLEFLAGS((PyArrayObject*)output_array, NPY_ARRAY_OWNDATA);
#else
((PyArrayObject*)output_array)->flags |= NPY_OWNDATA;
#endif
/* CLEANUP : */
cleanup:
if(RPAR) free(RPAR);
if(Y) free(Y);
if(IPAST) free(IPAST);
if(GRID) free(GRID);
if(p->y0_spline)
{
if(verbose) PySys_WriteStderr("Clearing initial values...\n");
for(i = 0; i < N; i++)
{
#ifdef WITH_GSL
if(p->y0_spline[i])
gsl_spline_free(p->y0_spline[i]);
#else
cspline_free(&p->y0_spline[i]);
#endif
}
free(p->y0_spline);
}
#ifdef WITH_GSL
if(p->spline_acc)
{
gsl_interp_accel_free (p->spline_acc);
}
#endif
if(p->py_lag_callback)
Py_DECREF(p->py_lag_callback);
if(py_p)
Py_DECREF(py_p);
if(p->py_rpar)
Py_DECREF(p->py_rpar);
if(p->xvalues)
Py_DECREF(p->xvalues);
#ifdef WITH_TCC
if(tcc)
tcc_delete(tcc);
#endif
return output_array;
}
static PyObject *radar5_stop(PyObject *self, PyObject *args)
{
if(current_p)
{
current_p->fail = 3;
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(radar5_doc,
"Call the RADAR5 solver, which numerically solves delayed differential equations (DDE) using an implicit collocation Runge-Kutta method based on Radau nodes.\n"
"\n"
"Beware : some functionalities are not implemented yet :\n"
" - providing custom jacobians ;\n"
" - mass matrix ;\n"
" - lots of options...\n"
"\n"
"For more extensive details, see the documentation [1]_ of the original FORTRAN code, which is the work of Nicola Guglielmi and Ernst Hairer.\n"
"More details can be found on : http://www.unige.ch/~hairer/software.html\n"
"\n"
":param equation : callable, pointer to c function, or string\n"
" Right-hand side of the equation, computing the time derivatives.\n"
" It is fundamentally a function that takes three or four arguments:\n"
" * y[i], an array containing the current values:\n"
" * t, the current time;\n"
" * lag(i,j), a function that can be called compute delayed variable i with the lag j.\n"
" * params, an extra array of user-defined parameters\n\n"
" This function can be a Python callable, but this can be quite slow when integrating large systems. For better performances, a pointer to a C function can be provided. This function can be loaded by ctypes, or be part of a C extension, etc. It must have the following signature:\n"
" void equation(double *dy, const double *y, double t, double (*lag)(int,int,void*), void* ctx, void *params)\n"
" The output derivatives should be written in dy, and the extra 'ctx' argument has to be provided as 'lag' third parameters.\n"
" For more convenience, a string containing C code can also be provided. It must contain a function called 'equation', 'equ', or 'rhs' with the same signature. It will be internally compiled using the 'tcc' compiler. Standard math function (sin, cos, ...) are made available in the global scope.\n"
"\n"
":param y0 : array, or tuple of arrays\n"
" Provides initial and past values. It can be either a constant, and in that case all t<0 values are the same. If non-constant past values are needed, they must be provided as a tuple (time, values). Missing points will be computed using a cubic spline interpolation. For a more precise control, a list of Python callable computing the past values for each variable can also be used. Finally, a single array can be used, and its first row will be considered as the time values. This is particularly useful for resuming integration from the output of another call.\n"
"\n"
":param time : array, or float\n"
" Specifies the points on which the result of the integration has to be stored. Note that this does not correspond to the integrating grid, as the solver uses an adaptative step. If a single number is provided, full output is turned on, and all output steps are stored.\n"
"\n"
":param params : array, optional\n"
" Extra parameters to be provided to the integrating function.\n"
"\n"
":param lagvars : array, optional\n"
" List of variables subjected to delay. If it is not specified, all variables are considered delayed variable. You can specifiy an empty list or tuple if no delayed variable are needed.\n"
"\n"
":param lags : array, optional\n"
" List of delays used in the equations. They can be either constant, or functions of the other variables or current time.\n"
"\n"
":param ngrid : int, optional\n"
" Changes the size of the internal grid. Might need some tuning if integration fails unexpectedly."
":param mxst : int, optional\n"
" Changes the size of the internal past storage. Might need some tuning if integration fails unexpectedly with 'MXST' related errors."
":param atol : float, optional\n"
" Changes the absolute tolerance (default is 1e-6)\n"
":param rtol : float, optional\n"
" Changes the relative tolerance (default is 1e-6)\n"
":param initial_stepsize : float, optional\n"
" Initial guess for the stepsize; for stiff equations with initial transient, H=1/(norm of F'); usually 1e-3 or 1e-5 is good. (default is 1e-6)\n"
":param verbose : bool, optional\n"
" Enable printing of troubleshooting informations."
":param full_output : bool, optional\n"
" Turns on the output of every integration step. This can make the output array much bigger than the specified times.\n"
"\n"
":return: The result of the integration, the first row of which being the \"time\" variable, and the latter the integrated components.\n"
"\n"
".. References :\n"
"[1] N. Guglielmi and E. Hairer, \"Users' Guide for the code RADAR5 - Version 2.1\", Technical Report, July 2005.\n"
);
static PyMethodDef Radar5Methods[] = {
{"radar5", (PyCFunction)radar5_radar5, METH_VARARGS|METH_KEYWORDS, radar5_doc},
{"stop", (PyCFunction)radar5_stop, METH_VARARGS, "Stop running computation."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef Radar5Def = {
PyModuleDef_HEAD_INIT,
"radar5",
NULL,
-1,
Radar5Methods
};
#define INITERROR return NULL
#else
#define INITERROR return
#endif
#if PY_MAJOR_VERSION >= 3
PyMODINIT_FUNC PyInit_radar5(void)
{
PyObject *module = PyModule_Create(&Radar5Def);
#else
PyMODINIT_FUNC initradar5(void)
{
PyObject *module = Py_InitModule("radar5", Radar5Methods);
#endif
if (module == NULL)
INITERROR;
import_array();
// TODO : add dummy integration WITH lag so integration without lag works properly...
#if PY_MAJOR_VERSION >= 3
return module;
#endif
}
| {
"alphanum_fraction": 0.6197605654,
"avg_line_length": 27.7987169206,
"ext": "c",
"hexsha": "8becc3acc80e9e2bc93a3a9e8cc53b29c5c8f2cb",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-04-27T10:14:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-27T10:14:46.000Z",
"max_forks_repo_head_hexsha": "c2c30fa8c0afa8b7d0efdc19aacdadd1e1ef092d",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "GColom/pyradar5",
"max_forks_repo_path": "wrapper.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "c2c30fa8c0afa8b7d0efdc19aacdadd1e1ef092d",
"max_issues_repo_issues_event_max_datetime": "2021-06-08T21:46:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-06-06T13:49:17.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "thoduv/pyradar5",
"max_issues_repo_path": "wrapper.c",
"max_line_length": 570,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "c2c30fa8c0afa8b7d0efdc19aacdadd1e1ef092d",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "GColom/pyradar5",
"max_stars_repo_path": "wrapper.c",
"max_stars_repo_stars_event_max_datetime": "2020-10-10T10:06:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-22T14:05:30.000Z",
"num_tokens": 10800,
"size": 34665
} |
#pragma once
#ifdef HAVE_BLAS
// HOTFIX: cblas.h from the atlas-devel package (version 3.10.1-12.el7) on CentOS 7
// does not declare the functions as `extern "C"`, which breaks name mangling.
// Note that nested `extern "C"` is valid and correct:
// https://stackoverflow.com/questions/48099828/what-happens-if-you-nest-extern-c
extern "C" {
#include <cblas.h>
}
inline int blasIgamax( int n, const float *x, int incx )
{
return cblas_isamax( n, x, incx );
}
inline int blasIgamax( int n, const double *x, int incx )
{
return cblas_idamax( n, x, incx );
}
/*inline int blasIgamin( int n, const float *x, int incx )
{
return cblas_isamin( n, x, incx );
}
inline int blasIgamin( int n, const double *x, int incx )
{
return cblas_idamin( n, x, incx );
}*/
inline float blasGasum( int n, const float *x, int incx )
{
return cblas_sasum( n, x, incx );
}
inline double blasGasum( int n, const double *x, int incx )
{
return cblas_dasum( n, x, incx );
}
inline void blasGaxpy( int n, const float alpha,
const float *x, int incx,
float *y, int incy )
{
cblas_saxpy( n, alpha, x, incx, y, incy );
}
inline void blasGaxpy( int n, const double alpha,
const double* x, int incx,
double *y, int incy )
{
cblas_daxpy( n, alpha, x, incx, y, incy );
}
inline float blasGdot( int n, const float* x, int incx,
const float* y, int incy )
{
return cblas_sdot( n, x, incx, y, incy );
}
inline double blasGdot( int n, const double* x, int incx,
const double* y, int incy )
{
return cblas_ddot( n, x, incx, y, incy );
}
inline float blasGnrm2( int n, const float* x, int incx )
{
return cblas_snrm2( n, x, incx );
}
inline double blasGnrm2( int n, const double* x, int incx )
{
return cblas_dnrm2( n, x, incx );
}
inline void blasGscal( int n, const float alpha,
float* x, int incx )
{
cblas_sscal( n, alpha, x, incx );
}
inline void blasGscal( int n, const double alpha,
double* x, int incx )
{
cblas_dscal( n, alpha, x, incx );
}
#endif
| {
"alphanum_fraction": 0.60710988,
"avg_line_length": 22.3298969072,
"ext": "h",
"hexsha": "ce30060bf399fa80c8119dc185edb84a5e3010ca",
"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": "4403b2dca895e2c32636395d6f1c1210c7afcefd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "grinisrit/tnl-dev",
"max_forks_repo_path": "src/Benchmarks/BLAS/blasWrappers.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4403b2dca895e2c32636395d6f1c1210c7afcefd",
"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": "grinisrit/tnl-dev",
"max_issues_repo_path": "src/Benchmarks/BLAS/blasWrappers.h",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "4403b2dca895e2c32636395d6f1c1210c7afcefd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "grinisrit/tnl-dev",
"max_stars_repo_path": "src/Benchmarks/BLAS/blasWrappers.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 682,
"size": 2166
} |
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_math.h>
#include <math.h>
#include <options/options.h>
#include "../csm/csm_all.h"
struct ld_noise_params {
int seed;
double sigma_xy;
double sigma_theta_deg;
const char* file_input;
const char* file_output;
int debug;
};
const char * banner =
"A simple program for adding slip to odometry \n\n"
"The 'odometry' field is set to 'true_pose' + noise.\n"
"If 'true_pose' is not available, then the 'odometry' \n"
"field is set to 'odometry' + noise.\n\n"
"Note: this program does *not* simulate the effect of \n"
"slip or odometry error in a realistic way; each scan \n"
"in the file is considered separately, the error does \n"
"not depend on the traveled distance, etc.\n\n";
int main(int argc, const char ** argv) {
sm_set_program_name(argv[0]);
struct ld_noise_params p;
options_banner(banner);
struct option* ops = options_allocate(10);
options_double(ops, "sigma_theta_deg", &p.sigma_theta_deg, 0.0,
"Std deviation of gaussian noise for theta (deg) (disabled if 0)");
options_double(ops, "sigma_xy", &p.sigma_xy, 0.0,
"Std deviation of gaussian noise for x,y (disabled if 0)");
options_int(ops, "seed", &p.seed, 0,
"Seed for random number generator (if 0, use GSL_RNG_SEED env. variable).");
options_string(ops, "in", &p.file_input, "stdin", "Input file ");
options_string(ops, "out", &p.file_output, "stdout", "Output file ");
options_int(ops, "debug", &p.debug, 0, "Shows debug information");
if(!options_parse_args(ops, argc, argv)) {
options_print_help(ops, stderr);
return -1;
}
sm_debug_write(p.debug);
gsl_rng_env_setup();
gsl_rng * rng = gsl_rng_alloc (gsl_rng_ranlxs0);
if(p.seed != 0)
gsl_rng_set(rng, (unsigned int) p.seed);
FILE * in = open_file_for_reading(p.file_input);
if(!in) return -3;
FILE * out = open_file_for_writing(p.file_output);
if(!out) return -2;
LDP ld; int count=0;
while( (ld = ld_read_smart(in))) {
count++;
if(!ld_valid_fields(ld)) {
sm_error("Invalid laser data (#%d in file)\n", count);
continue;
}
if(!any_nan(ld->true_pose, 3))
copy_d( (const double*) ld->true_pose, 3, ld->odometry);
double e[3] = {0,0,0};
if(p.sigma_xy > 0) {
e[0] = gsl_ran_gaussian(rng, p.sigma_xy);
e[1] = gsl_ran_gaussian(rng, p.sigma_xy);
}
if(p.sigma_theta_deg > 0) {
e[2] = gsl_ran_gaussian(rng, deg2rad(p.sigma_theta_deg));
}
ld->odometry[0] += e[0];
ld->odometry[1] += e[1];
ld->odometry[2] += e[2];
sm_debug("Adding noise %s.\n", friendly_pose(e));
ld_write_as_json(ld, out);
ld_free(ld);
}
return 0;
}
| {
"alphanum_fraction": 0.6656637834,
"avg_line_length": 25.0849056604,
"ext": "c",
"hexsha": "4b834823c60656a0dccba439a39335cdbe8e0458",
"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": "509223ef116f307d443e9a058923ad42f0c507e9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ozaslan/basics",
"max_forks_repo_path": "csm/sm/apps/ld_slip.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9",
"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": "ozaslan/basics",
"max_issues_repo_path": "csm/sm/apps/ld_slip.c",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "509223ef116f307d443e9a058923ad42f0c507e9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ozaslan/basics",
"max_stars_repo_path": "csm/sm/apps/ld_slip.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 848,
"size": 2659
} |
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_multimin.h>
void calcmatriceswrapper(int *Omega, int *NumTerms, int *qmax, int *pmax, int *IsTriplet, int *Ordering, int *Method, double *Alpha, double *Beta, double *Gamma, double *Energy);
void testfortran(int *x)
{
printf("%d\n", *x);
}
double test(const gsl_vector *v, void *params)
{
double a1, b1, g1, Energy;
int *p = (int*)params;
int Omega = p[0], NumTerms = p[1], qmax = p[2], pmax = p[3], IsTriplet = p[4], Ordering = p[5], Method = p[6];
a1 = gsl_vector_get(v, 0);
b1 = gsl_vector_get(v, 1);
g1 = gsl_vector_get(v, 2);
calcmatriceswrapper(&Omega, &NumTerms, &qmax, &pmax, &IsTriplet, &Ordering, &Method, &a1, &b1, &g1, &Energy);
printf("Energy: %f\n", Energy);
return Energy;
}
int optimizewavefn(int MaxIter, int Omega, int NumTerms, int qmax, int pmax, int IsTriplet, int Ordering, int Method, double alpha, double beta, double gamma)
{
int par[7] = { Omega, NumTerms, qmax, pmax, IsTriplet, Ordering, Method };
//printf("Test: %f %f %f\n", alpha, beta, gamma);
const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex; //gsl_multimin_fminimizer_nmsimplex2;
gsl_multimin_fminimizer *s = NULL;
gsl_vector *ss, *x;
gsl_multimin_function minex_func;
int iter = 0, status;
double size;
x = gsl_vector_alloc(3);
gsl_vector_set(x, 0, alpha);
gsl_vector_set(x, 1, beta);
gsl_vector_set(x, 2, gamma);
/* Set initial step sizes to 1 */
//ss = gsl_vector_alloc (2);
ss = gsl_vector_alloc(3);
gsl_vector_set_all(ss, 0.05);
/* Initialize method and iterate */
//minex_func.n = 2;
minex_func.n = 3;
minex_func.f = (void*)test;
minex_func.params = par;
//s = gsl_multimin_fminimizer_alloc (T, 2);
s = gsl_multimin_fminimizer_alloc(T, 3);
gsl_multimin_fminimizer_set(s, &minex_func, x, ss);
do
{
iter++;
status = gsl_multimin_fminimizer_iterate(s);
if (status)
break;
size = gsl_multimin_fminimizer_size(s);
status = gsl_multimin_test_size(size, 1e-5);
if (status == GSL_SUCCESS) {
printf ("converged to minimum at\n");
}
printf ("%5d %10.5e f() = %12.7f size = %.5f\n",
iter,
gsl_vector_get (s->x, 0),
gsl_vector_get (s->x, 1),
gsl_vector_get (s->x, 2),
s->fval, size);
} while (status == GSL_CONTINUE && iter < MaxIter);
gsl_vector_free(x);
gsl_vector_free(ss);
gsl_multimin_fminimizer_free(s);
return 0; //@TODO: How do I make this into a void subroutine?
}
| {
"alphanum_fraction": 0.6442718447,
"avg_line_length": 27.3936170213,
"ext": "c",
"hexsha": "b105ba92054e037bc4859a350e182e0e89dd8d65",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-09-28T22:09:05.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-28T22:09:05.000Z",
"max_forks_repo_head_hexsha": "943846d1deadbe99a98d2c2e26bcebf55986d8e7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "DentonW/Ps-H-Scattering",
"max_forks_repo_path": "D-Wave/Short/Minimize.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "943846d1deadbe99a98d2c2e26bcebf55986d8e7",
"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": "DentonW/Ps-H-Scattering",
"max_issues_repo_path": "D-Wave/Short/Minimize.c",
"max_line_length": 179,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "943846d1deadbe99a98d2c2e26bcebf55986d8e7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "DentonW/Ps-H-Scattering",
"max_stars_repo_path": "D-Wave/Short/Minimize.c",
"max_stars_repo_stars_event_max_datetime": "2017-08-02T03:50:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-02T03:50:06.000Z",
"num_tokens": 845,
"size": 2575
} |
#ifndef ppom_57c54fa0_d309_4aad_9678_16fa29f7af42_h
#define ppom_57c54fa0_d309_4aad_9678_16fa29f7af42_h
#include <rathen\config.h>
#include <gslib\tree.h>
#include <rathen\basis.h>
__rathen_begin__
class ppom
{
public:
typedef tree<object, _treenode_wrapper<object> > ppom_tree;
typedef ppom_tree::iterator iterator;
typedef ppom_tree::const_iterator const_iterator;
//typedef ;
public:
ppom() {}
public:
template<class _cst>
iterator insert(iterator i) { return _tree.insert_tail<_cst>(i); }
template<class _cst>
iterator birth(iterator i) { return _tree.birth_tail<_cst>(i); }
protected:
ppom_tree _tree;
};
__rathen_end__
#endif
| {
"alphanum_fraction": 0.7012448133,
"avg_line_length": 21.2647058824,
"ext": "h",
"hexsha": "afdbe29af857f6db3561c1fc69a9304d3bff0e3e",
"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/rathen/ppom.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/rathen/ppom.h",
"max_line_length": 71,
"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/rathen/ppom.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": 217,
"size": 723
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "eigenmap.h"
#include <cblas.h>
#include <memory.h>
static void diag(double *d, const double *w, int n_patch);
static void compute_l(double *w, int n_patch);
static void diag_similarity_transform(double *w, int n_patch);
/*
* laplacian computes the Laplacian matrix based on the weight matrix.
*
* w: the weight matrix
* n_patch: the dimension of dev_w and dev_l
* Note: the Laplacian matrix is computed in-place and overwrites w.
*/
void laplacian(double *w, int n_patch)
{
/* ---- corresponding Matlab code ----
* D = diag(sum(W));
* L = eye(n_patch) - D^(-1/2)*W*D^(-1/2);
*/
// W <- D^(-1/2) * W * D^(-1/2)
diag_similarity_transform(w, n_patch);
// L <- I - W
compute_l(w, n_patch);
}
static void diag_similarity_transform(double *w, int n_patch)
{
double *d = (double *)calloc(n_patch, sizeof(double));
int i;
diag(d, w, n_patch);
// row operations
for (i = 0; i < n_patch; i++)
cblas_dscal(n_patch, d[i], &w[i], n_patch);
// column operations
for (i = 0; i < n_patch; i++)
cblas_dscal(n_patch, d[i], &w[i * n_patch], 1);
free(d);
}
static void diag(double *d, const double *w, int n_patch)
{
int i, j;
double sum;
for (j = 0; j < n_patch; j++){
sum = 0;
for (i = 0; i < n_patch; i++)
sum += w[i + j * n_patch];
d[j] = 1 / sqrt(sum);
}
}
static void compute_l(double *w, int n_patch)
{
int N = n_patch * n_patch;
int i;
for (i = 0; i < N; i++)
w[i] = ((i % (n_patch + 1) == 0) ? 1.0 : 0.0) - w[i];
}
| {
"alphanum_fraction": 0.5698663426,
"avg_line_length": 23.5142857143,
"ext": "c",
"hexsha": "dec0d80d097b71a985dbf1e0e8f27de0e7aafdf7",
"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": "add646dbf220da2143f289f058abed172ab8a637",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "hcho3/eigenmap_gpu",
"max_forks_repo_path": "C_serial/laplacian.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "add646dbf220da2143f289f058abed172ab8a637",
"max_issues_repo_issues_event_max_datetime": "2019-08-23T14:56:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-07-30T09:43:40.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "hcho3/eigenmap_gpu",
"max_issues_repo_path": "C_serial/laplacian.c",
"max_line_length": 70,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "add646dbf220da2143f289f058abed172ab8a637",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "hcho3/eigenmap_gpu",
"max_stars_repo_path": "C_serial/laplacian.c",
"max_stars_repo_stars_event_max_datetime": "2020-12-28T06:20:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-07-06T03:40:34.000Z",
"num_tokens": 523,
"size": 1646
} |
#ifndef ALM_I_APG_H
#define ALM_I_APG_H
#include "Matrix.h"
#include "APPROX2.h"
#include <string>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <stdio.h> /* printf */
#include <time.h>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <math.h>
//This class solves problem of the form f(x)+g(x) under the constraint Mx=c;
// where f(x)=\sum_{j=1}^m lambda_f[j] \phi_j(<A_j,x>)
//and g(x)=sum_{i=1}^n g_i(x_i). We all assume that each \phi_j is 1-smooth.
// Each subproblem solves problem of the form f(x)+<Mx-c, lambda_s>+1/2beta_s\|Mx-c\|^2+g(x) by APG.
// This header file implements ASGARD_DL.
template<typename L, typename D>
class ALM_I_APG: public APPROX2<L, D>
{
private:
std::vector<D> Au;
std::vector<D> Az;
std::vector<D> Mu;
std::vector<D> Mz;
std::vector<D> Mx_s;
std::vector<D> Ax_s;
std::vector<D> lambda_f;
protected:
Matrix<L,D> data_A;
Matrix<L, D> data_M;
std::vector<D> x_s;
std::vector<D> lambda_s;
std::vector<D> M_tlambda_s;
D beta_s;
D epsilon_s;
D m_s;
D mp_s;
D m_0;
L m_1;
L m_2;
D c_s;
D eta;
D rho;
D max_Lf_s;
D max_M_s;
D Lf;
D L_m;
L val_mu_f;
L val_mu_g;
std::vector<D> dual_alpha1; //dual_alpha1[j]=gradient_of_phi_j(<A_j,x>)
std::vector<D> dual_alpha2; //dual_alpha2[j]=(<M_j,x>-c_j)
std::vector<D> baralpha1; //baralpha1=-sum_{j=1}^m_1 lambda_f[j]*dual_alpha1[j]*A_j
std::vector<D> baralpha2; //baralpha2=-sum_{j=1}^m_2 1/beta_s*dual_alpha2[j]*M_j
D residual1; //residual1=\dist(-M^\top y, \nabla f(x)+\partial g(x))
D residual2; //residual2=\|Mx-c\|
D function_value;
L print_every_N_ALM_I_APG;
D running_time_ALM_I_APG;
L nb_outer_iters;
std::vector<D> gradient_of_f;
ofstream samp_ALM_I_APG;
public:
virtual inline D gradient_of_phi_j(D, L){return D(NULL);}
virtual inline D value_of_g_i(D, L){return D(NULL);}
virtual inline D value_of_phi_j(D, L){return D(NULL);}
virtual inline D prox_of_g_i(D,D,D, L){return D(NULL);}
virtual inline D feasible_dual(std::vector<D> &,std::vector<D> &) {return D(NULL);}
virtual inline D value_of_phistar_i(D,L) {return D(NULL);}
virtual inline D value_of_g_tilde_star(D, vector<D> &,vector<D> &){return D(NULL);}
virtual inline void set_matrix_M(){}
virtual inline void set_matrix_A(){}
virtual inline D distance_to_subgradient_of_g(){return D(NULL);}
//virtual inline D distance_to_subgradient_of_g(std::vector<D> &, std::vector<D> & ){return D(NULL);}
ALM_I_APG(const char* Matrix_file, D val_lambda_f)
:data_A(), data_M()
{
}
ALM_I_APG()
:data_A(), data_M()
{
}
L get_nb_features(){
return data_A.get_d();
}
//This function computes \nabla_i f(gamma u +z)
inline D partial_i_of_f(L i){
D res=0;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
D tmp=lambda_f[j]*gradient_of_phi_j(this->gamma*Au[j]+Az[j], j);
res+=data_A.A_t[k]*tmp;
}
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
D tmp=(this->gamma*Mu[j]+Mz[j]-data_M.b[j])/beta_s+lambda_s[j];
res+=data_M.A_t[k]*tmp;
}
return res;
}
//This function computes argmin{x1 t+x2 t^2/2+g_i(x3+t)}
//inline D compute_prox(D x1, D x2, D x3, L i){
//return prox_operA_tor(x1,x2,x3,i);
//}
void compute_x(){
for(L i=0;i<this->n;i++){
this->x[i]=this->gamma*this->u[i]+this->z[i];
x_s[i]=this->x[i];
}
for(L j=0;j<m_2;j++)
Mx_s[j]=this->gamma*this->Mu[j]+this->Mz[j];
for(L j=0;j<m_1;j++)
Ax_s[j]=this->gamma*this->Au[j]+this->Az[j];
}
inline void compute_primal_value() {
D res=0;
for(L i=0;i<this->n;i++){
this->x[i]=this->gamma*this->u[i]+this->z[i];
res+=value_of_g_i(this->x[i],i);
}
for(L j=0;j<m_1;j++){
res+=lambda_f[j]*value_of_phi_j(this->gamma*Au[j]+Az[j],j);
}
for(L j=0;j<m_2;j++){
D tmp=(this->gamma*Mu[j]+Mz[j]-data_M.b[j]+beta_s*lambda_s[j]);
res+=tmp*tmp/2/beta_s;
}
this->primal_value=res;
}
inline void compute_dual_value(){
for(L j=0;j<m_1;j++){
dual_alpha1[j]=gradient_of_phi_j(this->gamma*Au[j]+Az[j], j);
}
for(L j=0;j<m_2;j++){
dual_alpha2[j]=this->gamma*Mu[j]+Mz[j]-data_M.b[j]+beta_s*lambda_s[j];
}
for(L i=0;i<this->n;i++){
baralpha1[i]=0;
for(L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++){
L j=data_A.col_idx[k];
baralpha1[i]-=dual_alpha1[j]*data_A.A_t[k]*lambda_f[j];
}
baralpha2[i]=0;
for(L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++){
L j=data_M.col_idx[k];
baralpha2[i]-=dual_alpha2[j]*data_M.A_t[k]/beta_s;
}
}
D res=0;
D scal=feasible_dual(baralpha1, baralpha2);
for(L j=0;j<m_1;j++)
{
res-=value_of_phistar_i(scal*dual_alpha1[j],j)*lambda_f[j];
}
for(L j=0;j<m_2;j++)
res-=scal*dual_alpha2[j]*(0.5*scal*dual_alpha2[j]+data_M.b[j]-beta_s*lambda_s[j])/beta_s;
res-=value_of_g_tilde_star(scal,baralpha1,baralpha2);
this->dual_value=res;
}
inline void compute_function_value() {
D res=0;
for(L i=0;i<this->n;i++){
res+=value_of_g_i(x_s[i],i);
}
for(L j=0;j<m_1;j++){
res+=lambda_f[j]*value_of_phi_j(Ax_s[j],j);
}
function_value=res;
}
D compute_prox(D x1,D x2,D x3, L i){
D res=prox_of_g_i(x1+beta_s*(x3-x_s[i]), beta_s+x2,x3,i);
if(fabs(res)>1e10)
{cout<<"larger than 1e10:"<<res<<endl;
cout<<beta_s<<"; "<<x1<<"; "<<x3<<"; "<<x_s[i]<<"; "<<i<<endl;
D res2=0;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
D tmp=lambda_f[j]*gradient_of_phi_j(this->gamma*Au[j]+Az[j], j);
res2+=data_A.A_t[k]*tmp;
cout<<"Ax["<<j<<"]="<<this->gamma*Au[j]+Az[j]<<endl;
}
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
D tmp=(this->gamma*Mu[j]+Mz[j]-data_M.b[j])/beta_s+lambda_s[j];
cout<<"Mu["<<j<<"]="<<Mu[j]<<"; gamma="<<this->gamma<<endl;
res2+=data_M.A_t[k]*tmp;
}
}
return res;
}
inline void compute_gradient_norm(){
std::vector<D> Tx(this->n,0);
this->do_single_step_prox(Tx);
D res=0;
for(L i=0;i<this->n;i++)
res+=(Tx[i]-this->x[i])*(Tx[i]-this->x[i]);
this->gradient_norm=sqrt(res);
}
inline void set_v()
{
this->v.resize(this->n,0);
D maxv=0;
D minv=std::numeric_limits<double>::max();
D sumv=0;
D sumvi1=0;
L sumw=0;
L maxw=0;
L minw=this->n;
this->sumofLi=0;
for(L j=0;j<m_1;j++)
{
sumw+=data_A.w_t[j];
maxw=max(maxw,data_A.w_t[j]);
minw=min(minw,data_A.w_t[j]);
}
cout<<"sumw="<<sumw<<"; maxw="<<maxw<<"; minw="<<minw<<endl;
for(L i=0;i<this->n;i++)
{
D vi=0;
D vi1=0;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
vi+=(1.+(data_A.w_t[j]-1.)*(this->tau-1.)/max(this->n-1.,1.))*data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];
vi1+=data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];
}
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
vi+=(1.+(data_M.w_t[j]-1.)*(this->tau-1.)/max(this->n-1.,1.))*data_M.A_t[k]*data_M.A_t[k]/beta_s;
vi1+=data_M.A_t[k]*data_M.A_t[k]/beta_s;
}
this->v[i]=vi;
sumv+=vi;
sumvi1+=vi1;
if(maxv<vi) maxv=vi;
if(minv>vi) minv=vi;
}
if(this->tau==this->n){
for(L i=0;i<this->n;i++)
this->v[i]=sumvi1;
}
this->sumofLi=sumvi1;
cout<<" max of v: "<<maxv<<" ; min of v: "<<minv<<" ; sumofv: "<<sumv<<" sumofLi="<<this->sumofLi<<endl;
}
inline void compute_m0(D beta0, D val_eta, D val_rho, L val_tau){
cout<<"beta0="<<beta0<<"val_eta="<<val_eta<<"; val_rho="<<val_rho<<"; val_tau="<<val_tau<<endl;
m_s=this->n/val_tau*20;
//D tmp7=1-val_tau/this->n*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0));
//cout<<"tmp7: "<<tmp7<<"; "<<val_tau/(this->n+0.)*sqrt(beta0/(max_Lf_s+max_M_s/beta0+beta0))<<endl;
//m_0=(2*log(val_rho)+log(val_eta)+log(2))/log(tmp7);
cout<<" m_s="<<m_s<<endl;
}
inline void rescale_Matrix(){
Lf=0;
max_Lf_s=0;
max_M_s=0;
L_m=0;
cout<<"this->n="<<this->n<<endl;
for(L i=0;i<this->n;i++)
{
D vi=0;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
Lf+=data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];
vi+=(1.+(data_A.w_t[j]-1.)*(this->tau-1.)/max(this->n-1.,1.))*data_A.A_t[k]*data_A.A_t[k]*lambda_f[j];
}
if(vi>max_Lf_s) max_Lf_s=vi;
D vi2=0;
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
L_m+=data_M.A_t[k]*data_M.A_t[k];
vi2+=(1.+(data_M.w_t[j]-1.)*(this->tau-1.)/max(this->n-1.,1.))*data_M.A_t[k]*data_M.A_t[k];
}
if(vi2>max_M_s) {max_M_s=vi2;cout<<vi2<<" ";}
}
cout<<"max_M_s"<<max_M_s<<endl;
D scal=sqrt((Lf+1)/L_m);
cout<<"scal="<<scal<<endl;
if(scal>1)
{
for(L i=0;i<this->n;i++){
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
data_M.A_t[k]*=scal;
}
}
for(L j=0;j<m_2;j++){
for (L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++)
{
data_M.A[k]*=scal;
}
}
for(L j=0;j<m_2;j++)
data_M.b[j]*=scal;
max_M_s*=scal*scal;
L_m*=scal*scal;
}
cout<<"max_M_s="<<max_M_s<<"; L_m="<<L_m<<"; max_Lf_s="<<max_Lf_s<<"; L_f="<<Lf<<endl;
}
inline void set_p(){
this->proba_vector.resize(this->n,(0.0+this->tau)/this->n);
this->max_p=(0.0+this->tau)/this->n;
}
void compute_KKT_residual(){
D res;
for(L i=0; i<this->n;i++){
res=0;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
D tmp=lambda_f[j]*gradient_of_phi_j(Ax_s[j], j);
res+=data_A.A_t[k]*tmp;
}
gradient_of_f[i]=res;
}
residual1=distance_to_subgradient_of_g();
res=0;
for(L j=0;j<m_2;j++)
res+=(Mx_s[j]-data_M.b[j])*(Mx_s[j]-data_M.b[j]);
residual2=sqrt(res);
}
void testing(){
std::vector<D> nablaf(this->n);
D res1=0;
compute_Mty();
for(L i=0;i<this->n;i++)
{
nablaf[i]=0;
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
D tmp=lambda_s[j];
nablaf[i]+=data_M.A_t[k]*tmp;
}
res1+=(nablaf[i]-M_tlambda_s[i])*(nablaf[i]-M_tlambda_s[i]);
}
//samp_ALM2<<" res1 ="<<sqrt(res1)<<endl;
}
inline void update_z_coordinate( L i, D dz){
this->z[i]+=dz;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
Az[j]+=dz*data_A.A_t[k];
}
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
Mz[j]+=dz*data_M.A_t[k];
//if(j==2869) cout<<"gamma="<<this->gamma<<"; "<<dz<<"; "<<Mz[j]<<endl;
}
}
inline void update_x_coordinate( L i, D dx){
this->x[i]+=dx;
x_s[i]=this->x[i];
L j;
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
j=data_M.col_idx[k];
Mx_s[j]+=dx*data_M.A_t[k];
}
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
j=data_A.col_idx[k];
Ax_s[j]+=dx*data_A.A_t[k];
}
}
inline void update_u_coordinate( L i, D du){
this->u[i]+=du;
for (L k = data_A.ptr_t[i]; k < data_A.ptr_t[i + 1];k++)
{
L j=data_A.col_idx[k];
Au[j]+=du*data_A.A_t[k];
}
for (L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++)
{
L j=data_M.col_idx[k];
Mu[j]+=du*data_M.A_t[k];
}
}
void compute_Au(){
for(L j=0;j<m_1;j++)
for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){
L kj=data_A.row_idx[k];
Au[j]+=this->u[kj]*data_A.A[k];
}
}
void compute_Mu(){
for(L j=0;j<m_2;j++)
for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){
L kj=data_M.row_idx[k];
Mu[j]+=this->u[kj]*data_M.A[k];
}
}
void compute_Az(){
for(L j=0;j<m_1;j++)
for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){
L kj=data_A.row_idx[k];
Az[j]+=this->z[kj]*data_A.A[k];
}
}
void compute_Mz(){
for(L j=0;j<m_2;j++)
for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){
L kj=data_M.row_idx[k];
Mz[j]+=this->z[kj]*data_M.A[k];
}
}
void compute_Au(vector<D> & x0){
for(L j=0;j<m_1;j++)
for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){
L kj=data_A.row_idx[k];
Au[j]+=x0[kj]*data_A.A[k];
}
}
void compute_Az(vector<D> & x0){
for(L j=0;j<m_1;j++)
for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){
L kj=data_A.row_idx[k];
Az[j]+=x0[kj]*data_A.A[k];
}
}
void compute_Mu(vector<D> & x0){
for(L j=0;j<m_2;j++)
for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){
L kj=data_M.row_idx[k];
Mu[j]+=x0[kj]*data_M.A[k];
}
}
void compute_Mz(vector<D> & x0){
for(L j=0;j<m_2;j++)
for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){
L kj=data_M.row_idx[k];
Mz[j]+=x0[kj]*data_M.A[k];
}
}
void compute_Mx(vector<D> & x0){
for(L j=0;j<m_2;j++)
for(L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++){
L kj=data_M.row_idx[k];
Mx_s[j]+=x0[kj]*data_M.A[k];
}
}
void compute_Ax(vector<D> & x0){
for(L j=0;j<m_1;j++)
for(L k = data_A.ptr[j]; k < data_A.ptr[j + 1];k++){
L kj=data_A.row_idx[k];
Ax_s[j]+=x0[kj]*data_A.A[k];
}
}
void compute_cs(){
c_s=0;
for(L j=0;j<m_2;j++)
c_s+=data_M.b[j]*lambda_s[j];
}
void compute_Mty(){
M_tlambda_s.clear();
M_tlambda_s.resize(this->n,0);
for(L i=0;i<this->n;i++)
{
for(L k = data_M.ptr_t[i]; k < data_M.ptr_t[i + 1];k++){
L j=data_M.col_idx[k];
M_tlambda_s[i]+=lambda_s[j]*data_M.A_t[k];
}
}
}
void update_y(){
D res=0;
D dl=0;
for(L j=0;j<m_2;j++)
{
dl=(Mx_s[j]-data_M.b[j])/beta_s;
lambda_s[j]+=dl;
res+=(Mx_s[j]-data_M.b[j])*(Mx_s[j]-data_M.b[j]);
L i;
for (L k = data_M.ptr[j]; k < data_M.ptr[j + 1];k++)
{
i=data_M.row_idx[k];
M_tlambda_s[i]+=dl*data_M.A[k];
}
}
//samp_ALM2<<"lambda_{k+1}-lambda_k"<<sqrt(res)<<endl;
}
void Initialize(D beta_0, D epsilon_0, D val_eta, D val_rho,L val_tau, vector<D> & x0,vector<D> & y0, D val_lambda_f){
cout<<"start initializing"<<endl;
set_matrix_M();
set_matrix_A();
this->tau=val_tau;
m_1=data_A.get_n();
m_2=data_M.get_n();
cout<<"m_1="<<m_1<<endl;
cout<<"m_2="<<m_2<<endl;
lambda_f.resize(m_1,val_lambda_f);
dual_alpha1.resize(m_1,0);
dual_alpha2.resize(m_2,0);
this->n=data_A.nfeatures;
baralpha1.resize(this->n,0);
baralpha2.resize(this->n,0);
gradient_of_f.resize(this->n,0);
rescale_Matrix();
beta_s=beta_0;
//if(max_Lf_s>0)
// beta_s=min(beta_0,max_M_s/max_Lf_s);
epsilon_s=epsilon_0;
compute_m0(beta_s,val_eta,val_rho,val_tau);
eta=val_eta;
rho=val_rho;
x_s.resize(this->n,0);
lambda_s.resize(m_2,0);
for(L i=0;i<this->n;i++)
x_s[i]=x0[i];
for(L j=0;j<m_2;j++)
lambda_s[j]=y0[j];
M_tlambda_s.resize(this->n,0);
compute_cs();
compute_Mty();
Au.clear();
Au.resize(m_1,0);
Az.clear();
Az.resize(m_1,0);
Ax_s.clear();
Ax_s.resize(m_1,0);
Mu.clear();
Mu.resize(m_2,0);
Mz.clear();
Mz.resize(m_2,0);
Mx_s.clear();
Mx_s.resize(m_2,0);
compute_Az(x0);
compute_Mz(x0);
compute_Ax(x0);
compute_Mx(x0);
}
void reset_everything(){
epsilon_s*=rho*rho*eta;
m_s/=eta;
beta_s*=eta;
compute_cs();
compute_Mty();
Au.clear();
Au.resize(m_1,0);
Az.clear();
Az.resize(m_1,0);
Mu.clear();
Mu.resize(m_2,0);
Mz.clear();
Mz.resize(m_2,0);
compute_Az(x_s);
compute_Mz(x_s);
}
void APPROX_restart(L K, vector<D> & x0, L val_tau, L eval, L p_N, L max_nb, D eps, string filename){
std::vector<D> tmp_x(this->n);
for(L i=0;i<this->n;i++){
tmp_x[i]=x0[i];
}
L k=0;
while(k<ceil(max_nb/(K+0.0))){
k++;
Au.clear();
Au.resize(m_1,0);
Az.clear();
Az.resize(m_1,0);
Mu.clear();
Mu.resize(m_2,0);
Mz.clear();
Mz.resize(m_2,0);
compute_Az(tmp_x);
compute_Mz(tmp_x);
cout<<"p_N="<<tmp_x[0]<<" "<<tmp_x[1]<<" "<<tmp_x[2]<<" "<<p_N<<endl;
this->APPROX_MU(tmp_x, val_tau, 0, 0, eval, p_N, K, eps, filename,1);
for(L i=0;i<this->n;i++){
tmp_x[i]=this->x[i];
}
cout<<"restarting..."<<k<<"; "<<(max_nb/(K+0.0))<<endl;
if(this->delta<eps) k=ceil(max_nb/(K+0.0))+1;
}
}
inline void compute_and_record_res(){
if(nb_outer_iters%print_every_N_ALM_I_APG==0){
compute_KKT_residual();
compute_function_value();
cout<<setprecision(9)<<"Iteration: "<<nb_outer_iters<<"; time="<<running_time_ALM_I_APG<<"; residual1="<<residual1<<" residual2="<<residual2<<"; function value="<<function_value<<endl;
samp_ALM_I_APG<<setprecision(9)<<nb_outer_iters<<" "<<running_time_ALM_I_APG<<" "<<residual1<<" "<<residual2<<" "<<function_value<<" "<<endl;
}
}
void ALM_I_APG_solve_with_APPROX(D beta_0, D epsilon_0, D eta, D rho,vector<D> & x0,vector<D> & y0, L val_tau, L max_nb_outer, L p_N_1, L p_N_2, D val_lambda_f,string filename1, string filename2, D time){
Initialize(beta_0, epsilon_0, eta, rho,val_tau, x0, y0, val_lambda_f);
nb_outer_iters=0;
string sampname2="results/APPROXMU_"+filename2;
this->samp.open(sampname2.c_str());
filename1="results/ALM2_"+filename1;
samp_ALM_I_APG.open(filename1.c_str());
running_time_ALM_I_APG=0;
print_every_N_ALM_I_APG=p_N_1;
compute_and_record_res();
D start;
start = std::clock();
std::vector<D> record_x_s(this->n);
std::vector<D> record_x_sp1(this->n);
cout<<"m0="<<ceil(m_s/this->n*val_tau)<<endl;
//D K=ceil(2*sqrt((max_Lf_s+max_M_s)/(beta_s+val_mu_g)+1));
//cout<<"restart period="<<K<<endl;
cout<<"ms="<<ceil(m_s/this->n*val_tau)<<"; beta_s="<<beta_s<<"; epsilon_s="<<epsilon_s<<endl;
this->APPROX_MU(x_s, val_tau, val_mu_f, val_mu_g, 3, p_N_2, ceil(m_s/this->n*val_tau), epsilon_s, filename2,1);
//APPROX_restart(K, x_s, val_tau, 3, p_N_2, ceil((m_s+mp_s)/this->n*val_tau), epsilon_s, filename2);
compute_x();
update_y();
nb_outer_iters++;
running_time_ALM_I_APG+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;
compute_and_record_res();
start = std::clock();
reset_everything();
running_time_ALM_I_APG+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;
while(nb_outer_iters<max_nb_outer){
start = std::clock();
cout<<"ms="<<ceil(m_s/this->n*val_tau)<<"; beta_s="<<beta_s<<"; epsilon_s"<<epsilon_s<<endl;
//D K=ceil(2*sqrt((max_Lf_s+max_M_s)/(beta_s+val_mu_g)+1));
//cout<<"restart period="<<K<<endl;
this->APPROX_MU(x_s, val_tau, val_mu_f, val_mu_g, 3, p_N_2, ceil(m_s/this->n*val_tau), epsilon_s, filename2,1);
for(L i=0;i<this->n;i++){
record_x_s[i]=x_s[i];
}
//APPROX_restart(K, x_s, val_tau, 3, p_N_2, ceil((m_s+mp_s)/this->n*val_tau), epsilon_s, filename2);
compute_x();
update_y();
nb_outer_iters++;
running_time_ALM_I_APG+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;
testing();
compute_and_record_res();
start = std::clock();
reset_everything();
running_time_ALM_I_APG+=( std::clock() - start ) / (double) CLOCKS_PER_SEC;
if (running_time_ALM_I_APG> time){
break;
}
}
}
};
#endif
| {
"alphanum_fraction": 0.5082472358,
"avg_line_length": 27.5505617978,
"ext": "h",
"hexsha": "d84f1ee1e0f2705d2aaf02942c3bf2d0abe59b07",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-15T04:23:24.000Z",
"max_forks_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_forks_repo_licenses": [
"BSD-Source-Code"
],
"max_forks_repo_name": "lifei16/supplementary_code",
"max_forks_repo_path": "IPALM/ALM_I_APG.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-Source-Code"
],
"max_issues_repo_name": "lifei16/supplementary_code",
"max_issues_repo_path": "IPALM/ALM_I_APG.h",
"max_line_length": 209,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3d5d8c281411fdfd6379480429a1fbb9b21464ff",
"max_stars_repo_licenses": [
"BSD-Source-Code"
],
"max_stars_repo_name": "lifei16/supplementary_code",
"max_stars_repo_path": "IPALM/ALM_I_APG.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7171,
"size": 22068
} |
/* ode-initval2/modnewton1.c
*
* Copyright (C) 2008, 2009, 2010 Tuomo Keskitalo
*
* 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.
*/
/* A modified Newton iteration method for solving non-linear
equations in implicit Runge-Kutta methods.
*/
/* References:
Ascher, U.M., Petzold, L.R., Computer methods for ordinary
differential and differential-algebraic equations, SIAM,
Philadelphia, 1998. ISBN 0898714125, 9780898714128
Hairer, E., Wanner, G., Solving Ordinary Differential
Equations II: Stiff and Differential-Algebraic Problems,
Springer, 1996. ISBN 3540604529, 9783540604525
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#include "odeiv_util.h"
typedef struct
{
/* iteration matrix I - h A (*) J */
gsl_matrix *IhAJ;
/* permutation for LU-decomposition */
gsl_permutation *p;
/* difference vector for kth Newton iteration */
gsl_vector *dYk;
/* scaled dYk with desired error level */
gsl_vector *dScal;
/* current Runge-Kutta points (absolute values) */
double *Yk;
/* function values at points Yk */
double *fYk;
/* right hand side of Newton iteration formula */
gsl_vector *rhs;
/* stopping criterion value from previous step */
double eeta_prev;
}
modnewton1_state_t;
static void *
modnewton1_alloc (size_t dim, size_t stage)
{
modnewton1_state_t *state =
(modnewton1_state_t *) malloc (sizeof (modnewton1_state_t));
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for modnewton1_state_t",
GSL_ENOMEM);
}
state->IhAJ = gsl_matrix_alloc (dim * stage, dim * stage);
if (state->IhAJ == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for IhAJ", GSL_ENOMEM);
}
state->p = gsl_permutation_alloc (dim * stage);
if (state->p == 0)
{
gsl_matrix_free (state->IhAJ);
free (state);
GSL_ERROR_NULL ("failed to allocate space for p", GSL_ENOMEM);
}
state->dYk = gsl_vector_alloc (dim * stage);
if (state->dYk == 0)
{
gsl_permutation_free (state->p);
gsl_matrix_free (state->IhAJ);
free (state);
GSL_ERROR_NULL ("failed to allocate space for dYk", GSL_ENOMEM);
}
state->dScal = gsl_vector_alloc (dim * stage);
if (state->dScal == 0)
{
gsl_vector_free (state->dYk);
gsl_permutation_free (state->p);
gsl_matrix_free (state->IhAJ);
free (state);
GSL_ERROR_NULL ("failed to allocate space for dScal", GSL_ENOMEM);
}
state->Yk = (double *) malloc (dim * stage * sizeof (double));
if (state->Yk == 0)
{
gsl_vector_free (state->dScal);
gsl_vector_free (state->dYk);
gsl_permutation_free (state->p);
gsl_matrix_free (state->IhAJ);
free (state);
GSL_ERROR_NULL ("failed to allocate space for Yk", GSL_ENOMEM);
}
state->fYk = (double *) malloc (dim * stage * sizeof (double));
if (state->fYk == 0)
{
free (state->Yk);
gsl_vector_free (state->dScal);
gsl_vector_free (state->dYk);
gsl_permutation_free (state->p);
gsl_matrix_free (state->IhAJ);
free (state);
GSL_ERROR_NULL ("failed to allocate space for Yk", GSL_ENOMEM);
}
state->rhs = gsl_vector_alloc (dim * stage);
if (state->rhs == 0)
{
free (state->fYk);
free (state->Yk);
gsl_vector_free (state->dScal);
gsl_vector_free (state->dYk);
gsl_permutation_free (state->p);
gsl_matrix_free (state->IhAJ);
free (state);
GSL_ERROR_NULL ("failed to allocate space for rhs", GSL_ENOMEM);
}
state->eeta_prev = GSL_DBL_MAX;
return state;
}
static int
modnewton1_init (void *vstate, const gsl_matrix * A,
const double h, const gsl_matrix * dfdy,
const gsl_odeiv2_system * sys)
{
/* Initializes the method by forming the iteration matrix IhAJ
and generating its LU-decomposition
*/
modnewton1_state_t *state = (modnewton1_state_t *) vstate;
gsl_matrix *const IhAJ = state->IhAJ;
gsl_permutation *const p = state->p;
const size_t dim = sys->dimension;
const size_t stage = A->size1;
state->eeta_prev = GSL_DBL_MAX;
/* Generate IhAJ */
{
size_t i, j, k, m;
for (i = 0; i < dim; i++)
for (j = 0; j < dim; j++)
for (k = 0; k < stage; k++)
for (m = 0; m < stage; m++)
{
size_t x = dim * k + i;
size_t y = dim * m + j;
if (x != y)
gsl_matrix_set (IhAJ, x, y,
-h * gsl_matrix_get (A, k, m) *
gsl_matrix_get (dfdy, i, j));
else
gsl_matrix_set (IhAJ, x, y,
1.0 - h * gsl_matrix_get (A, k, m) *
gsl_matrix_get (dfdy, i, j));
}
}
/* decompose */
{
int signum;
int s = gsl_linalg_LU_decomp (IhAJ, p, &signum);
if (s != GSL_SUCCESS)
return s;
}
return GSL_SUCCESS;
}
static int
modnewton1_solve (void *vstate, const gsl_matrix * A,
const double c[], const double t, const double h,
const double y0[], const gsl_odeiv2_system * sys,
double YZ[], const double errlev[])
{
/* Solves the non-linear equation system resulting from implicit
Runge-Kutta methods by a modified Newton iteration. The
modified Newton iteration with this problem is stated in the
form
IhAJ * dYk = rhs
in which IhAJ is the iteration matrix: IhAJ = (I - hA (*) J) in
which (*) is the Kronecker matrix product (size of IhAJ =
dim*stage, dim*stage), dYk is the Runge-Kutta point (Y)
difference vector for kth Newton iteration: dYk = Y(k+1) - Y(k),
and rhs = Y(k) - y0 - h * sum j=1..stage (a_j * f(Y(k)))
This function solves dYk by LU-decomposition of IhAJ with partial
pivoting.
*/
modnewton1_state_t *state = (modnewton1_state_t *) vstate;
gsl_matrix *const IhAJ = state->IhAJ;
gsl_permutation *const p = state->p;
gsl_vector *const dYk = state->dYk;
double *const Yk = state->Yk;
double *const fYk = state->fYk;
gsl_vector *const rhs = state->rhs;
double *const eeta_prev = &(state->eeta_prev);
gsl_vector *const dScal = state->dScal;
const size_t dim = sys->dimension;
const size_t stage = A->size1;
int status = GSL_CONTINUE; /* Convergence status for Newton iteration */
/* Set starting values for iteration. Use starting values of Y(k) =
y0. FIXME: Implement better initial guess described in Hairer and
Wanner.
*/
{
size_t j, m;
gsl_vector_set_zero (dYk);
for (j = 0; j < stage; j++)
for (m = 0; m < dim; m++)
Yk[j * dim + m] = y0[m];
}
/* Loop modified Newton iterations */
{
size_t iter = 0;
size_t j, m, n;
/* Maximum number of Newton iterations. */
const size_t max_iter = 7;
double dScal_norm = 0.0; /* Newton iteration step length */
double dScal_norm_prev = 0.0; /* Previous dScal_norm */
while (status == GSL_CONTINUE && iter < max_iter)
{
iter++;
/* Update Y(k) and evaluate function */
for (j = 0; j < stage; j++)
{
for (m = 0; m < dim; m++)
{
Yk[j * dim + m] += gsl_vector_get (dYk, j * dim + m);
}
{
int s = GSL_ODEIV_FN_EVAL (sys, t + c[j] * h, &Yk[j * dim],
&fYk[j * dim]);
if (s != GSL_SUCCESS)
{
return s;
}
}
}
/* Calculate rhs */
for (j = 0; j < stage; j++)
for (m = 0; m < dim; m++)
{
double sum = 0;
for (n = 0; n < stage; n++)
sum += gsl_matrix_get (A, j, n) * fYk[n * dim + m];
gsl_vector_set (rhs, j * dim + m,
-1.0 * Yk[j * dim + m] + y0[m] + h * sum);
}
/* Solve dYk */
{
int s = gsl_linalg_LU_solve (IhAJ, p, rhs, dYk);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* Evaluate convergence according to method by Hairer and
Wanner, section IV.8. The iteration step is normalized by
desired error level before calculation of the norm, to take
the tolerance on each component of y into account.
*/
{
/* relative change in two Newton iteration steps */
double theta_k;
/* transformation of theta_k */
double eeta_k = 0.0;
for (j = 0; j < stage; j++)
for (m = 0; m < dim; m++)
{
gsl_vector_set (dScal, j * dim + m,
gsl_vector_get (dYk, j * dim + m)
/ errlev[m]);
}
dScal_norm_prev = dScal_norm;
dScal_norm = gsl_blas_dnrm2 (dScal);
theta_k = dScal_norm / dScal_norm_prev;
if (iter > 1)
{
/* check for increase in step size, which indicates divergence */
if (theta_k >= 1.0)
{
return GSL_FAILURE;
}
eeta_k = theta_k / (1.0 - theta_k);
}
else
{
eeta_k = pow (GSL_MAX_DBL (*eeta_prev, GSL_DBL_EPSILON), 0.8);
}
*eeta_prev = eeta_k;
if (eeta_k * dScal_norm < 1.0)
{
status = GSL_SUCCESS;
}
}
}
}
/* No convergence reached within allowed iterations */
if (status != GSL_SUCCESS)
{
return GSL_FAILURE;
}
/* Give solution in YZ */
else
{
size_t j, m;
for (j = 0; j < stage; j++)
for (m = 0; m < dim; m++)
YZ[j * dim + m] =
Yk[j * dim + m] + gsl_vector_get (dYk, j * dim + m);
return status;
}
}
static void
modnewton1_free (void *vstate)
{
modnewton1_state_t *state = (modnewton1_state_t *) vstate;
gsl_vector_free (state->rhs);
free (state->fYk);
free (state->Yk);
gsl_vector_free (state->dScal);
gsl_vector_free (state->dYk);
gsl_permutation_free (state->p);
gsl_matrix_free (state->IhAJ);
free (state);
}
| {
"alphanum_fraction": 0.5648296772,
"avg_line_length": 26.262295082,
"ext": "c",
"hexsha": "1e2f973160c2861cd7f9cbc1f46c8697ac1466e3",
"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/ode-initval2/modnewton1.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/ode-initval2/modnewton1.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/ode-initval2/modnewton1.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": 3123,
"size": 11214
} |
/* multifit/covar.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 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 <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_multifit_nlin.h>
/* Compute the covariance matrix
cov = inv (J^T J)
by QRP^T decomposition of J
*/
int
gsl_multifit_covar (const gsl_matrix * J, double epsrel, gsl_matrix * covar)
{
double tolr;
size_t i, j, k;
size_t kmax = 0;
gsl_matrix * r;
gsl_vector * tau;
gsl_vector * norm;
gsl_permutation * perm;
size_t m = J->size1, n = J->size2 ;
if (m < n)
{
GSL_ERROR ("Jacobian be rectangular M x N with M >= N", GSL_EBADLEN);
}
if (covar->size1 != covar->size2 || covar->size1 != n)
{
GSL_ERROR ("covariance matrix must be square and match second dimension of jacobian", GSL_EBADLEN);
}
r = gsl_matrix_alloc (m, n);
tau = gsl_vector_alloc (n);
perm = gsl_permutation_alloc (n) ;
norm = gsl_vector_alloc (n) ;
{
int signum = 0;
gsl_matrix_memcpy (r, J);
gsl_linalg_QRPT_decomp (r, tau, perm, &signum, norm);
}
/* Form the inverse of R in the full upper triangle of R */
tolr = epsrel * fabs(gsl_matrix_get(r, 0, 0));
for (k = 0 ; k < n ; k++)
{
double rkk = gsl_matrix_get(r, k, k);
if (fabs(rkk) <= tolr)
{
break;
}
gsl_matrix_set(r, k, k, 1.0/rkk);
for (j = 0; j < k ; j++)
{
double t = gsl_matrix_get(r, j, k) / rkk;
gsl_matrix_set (r, j, k, 0.0);
for (i = 0; i <= j; i++)
{
double rik = gsl_matrix_get (r, i, k);
double rij = gsl_matrix_get (r, i, j);
gsl_matrix_set (r, i, k, rik - t * rij);
}
}
kmax = k;
}
/* Form the full upper triangle of the inverse of R^T R in the full
upper triangle of R */
for (k = 0; k <= kmax ; k++)
{
for (j = 0; j < k; j++)
{
double rjk = gsl_matrix_get (r, j, k);
for (i = 0; i <= j ; i++)
{
double rij = gsl_matrix_get (r, i, j);
double rik = gsl_matrix_get (r, i, k);
gsl_matrix_set (r, i, j, rij + rjk * rik);
}
}
{
double t = gsl_matrix_get (r, k, k);
for (i = 0; i <= k; i++)
{
double rik = gsl_matrix_get (r, i, k);
gsl_matrix_set (r, i, k, t * rik);
};
}
}
/* Form the full lower triangle of the covariance matrix in the
strict lower triangle of R and in w */
for (j = 0 ; j < n ; j++)
{
size_t pj = gsl_permutation_get (perm, j);
for (i = 0; i <= j; i++)
{
size_t pi = gsl_permutation_get (perm, i);
double rij;
if (j > kmax)
{
gsl_matrix_set (r, i, j, 0.0);
rij = 0.0 ;
}
else
{
rij = gsl_matrix_get (r, i, j);
}
if (pi > pj)
{
gsl_matrix_set (r, pi, pj, rij);
}
else if (pi < pj)
{
gsl_matrix_set (r, pj, pi, rij);
}
}
{
double rjj = gsl_matrix_get (r, j, j);
gsl_matrix_set (covar, pj, pj, rjj);
}
}
/* symmetrize the covariance matrix */
for (j = 0 ; j < n ; j++)
{
for (i = 0; i < j ; i++)
{
double rji = gsl_matrix_get (r, j, i);
gsl_matrix_set (covar, j, i, rji);
gsl_matrix_set (covar, i, j, rji);
}
}
gsl_matrix_free (r);
gsl_permutation_free (perm);
gsl_vector_free (tau);
gsl_vector_free (norm);
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.5249671485,
"avg_line_length": 23.6580310881,
"ext": "c",
"hexsha": "36591406a2a9b29ffdde49f20e271182bd93597a",
"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": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "skair39/structured",
"max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/multifit/covar.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"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": "skair39/structured",
"max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/multifit/covar.c",
"max_line_length": 105,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/multifit/covar.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": 1357,
"size": 4566
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016 Couchbase, 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.
*/
/** \file
* This file is internal to the inner workings of
* Phosphor and is not intended for public consumption.
*/
#pragma once
#include <array>
#include <iterator>
#include <memory>
#include <thread>
#include <type_traits>
#include <vector>
#include <functional>
#include <gsl_p/iterator.h>
#include "phosphor/platform/core.h"
#include "trace_event.h"
namespace phosphor {
#ifndef PHOSPHOR_CHUNK_PAGE_COUNT
#define PHOSPHOR_CHUNK_PAGE_COUNT 1
#endif
/**
* TraceChunk represents an array of TraceEvents
*
* The TraceChunk should be used from a single thread to
* store various events.
*/
class PHOSPHOR_API TraceChunk {
public:
static constexpr auto chunk_page_count = PHOSPHOR_CHUNK_PAGE_COUNT;
static constexpr auto page_size = 4096;
static constexpr auto array_offset = 64;
static constexpr auto chunk_size =
(((page_size * chunk_page_count) - array_offset) /
sizeof(TraceEvent));
using event_array = std::array<TraceEvent, chunk_size>;
using const_iterator = event_array::const_iterator;
/**
* Constructor for a TraceChunk
*/
TraceChunk() = default;
/**
* Reset the state of the TraceChunk
*
* This should be called before the TraceChunk is first used
* as TraceChunk is a trivial type and requires initialisation.
*/
void reset();
/**
* Used for adding TraceEvents to the chunk
*
* @return A reference to a TraceEvent to be replaced
*/
TraceEvent& addEvent();
/**
* Used for reviewing TraceEvents in the chunk
*
* Valid indexes are from 0 to `count()`. There is no
* bounds checking.
*
* @return A const reference to a TraceEvent in the chunk
* that can be used to review the event data
*/
const TraceEvent& operator[](const int index) const;
/**
* Determine if the chunk is full
*
* @return true if the chunk is full (and should be replaced)
* or false otherwise.
*/
bool isFull() const;
/**
* Determine up to which index of events is initialised
*
* @return The number of initialised events in the chunk
*/
size_t count() const;
/**
* @return Const iterator to the start of the chunk
*/
const_iterator begin() const;
/**
* @return Const iterator to the last initialised event in the chunk
*/
const_iterator end() const;
private:
unsigned short next_free;
event_array chunk;
};
// Forward decl
class StatsCallback;
/**
* Abstract base-class for a buffer of TraceEvents
*
* The TraceBuffer loans out TraceChunks to individual
* threads to reduce lock-contention on event logging.
*
* This class is *not* thread-safe and should only be directly
* interacted either with the global lock owned by the TraceLog
* or after tracing has been finished.
*
* A trace buffer can be iterated over using C++11 style range
* iteration:
*
* for(const auto& event : trace_buffer) {
* std::cout << event << std::endl;
* }
*
* Alternatively more complex iteration can be accomplished by
* using the iterators returned by TraceBuffer::begin() and
* TraceBuffer::end().
*
* Iteration should not be attempted while chunks are loaned out.
*/
class TraceBuffer {
public:
/**
* Virtual destructor to allow subclasses to be cleaned up
* properly.
*/
virtual ~TraceBuffer() = default;
/**
* Used for getting a TraceChunk to add events to
*
* @return A pointer to a TraceChunk to insert events into or
* nullptr if the buffer is full.
*/
virtual TraceChunk* getChunk() = 0;
/**
* Used for returning a TraceChunk once full
*
* For some buffer implementations this *may* be a no-op
* but for others which might reuse chunks this can be
* used to only reuse chunks that have been finished with.
*
* @param chunk The chunk to be returned
*/
virtual void returnChunk(TraceChunk& chunk) = 0;
/**
* Determine if there are no remaining chunks left to be
* used
*
* @return true if there are no chunks left or false
* otherwise
*/
virtual bool isFull() const = 0;
/**
* Callback for retrieving stats from the Buffer implementation
*
* Implementations MUST supply the following stats as minimum:
*
* - buffer_name <cstring_span>: Textual representation of buffer type
* - buffer_is_full <bool>: True if the buffer is full
* - buffer_chunk_count <size_t>: Chunks that are returned or loaned
* - buffer_loaned_chunks <size_t>: Currently loaned chunks
* - buffer_total_loaned <size_t>: Count of all chunks ever loaned
* - buffer_size <size_t>: Max number of chunks that fit in the buffer
* - buffer_generation <size_t>: Generation number of the buffer
*
* On a non-rotating buffer, if buffer_chunk_count is equal to
* buffer-size then that must suggest the buffer is full and
* there are no more chunks to be loaned. On a rotating buffer
* it suggests that chunks are being reused.
*
* Buffer implementations may include other relevant stats but
* end-users SHOULD NOT assume the existence of those stats.
*/
virtual void getStats(StatsCallback& addStats) const = 0;
/**
* Used for accessing TraceChunks in the buffer
*
* Valid indexes are from 0 to `count()`. There is no
* bounds checking.
*
* @return A const reference to a TraceEvent in the chunk
* that can be used to review the event data
* @throw std::logic_error if chunks are currently loaned
* out to chunk tenants.
*/
virtual const TraceChunk& operator[](const int index) const = 0;
/**
* Used for determining the number of chunks in the buffer
*
* @return Number of chunks currently in the buffer
*/
virtual size_t chunk_count() const = 0;
/**
* @return The generation number of the TraceBuffer
*/
virtual size_t getGeneration() const = 0;
/**
* Const bi-directional iterator over the TraceChunks in a TraceBuffer
*
* Usage:
*
* chunk_iterator it = buffer.chunk_start();
* std::cout << *(it->start()) << std::endl;
*
* for(const auto& chunk : buffer.chunks()) {
* for(const auto& event : chunk) {
* std::cout << event << std::endl;
* }
* }
*/
class PHOSPHOR_API chunk_iterator
: public std::iterator<std::bidirectional_iterator_tag,
TraceChunk> {
using const_reference = const TraceChunk&;
using const_pointer = const TraceChunk*;
using _self = chunk_iterator;
public:
chunk_iterator() = default;
chunk_iterator(const TraceBuffer& buffer_);
chunk_iterator(const TraceBuffer& buffer_, size_t index_);
const_reference operator*() const;
const_pointer operator->() const;
chunk_iterator& operator++();
bool operator==(const chunk_iterator& other) const;
bool operator!=(const chunk_iterator& other) const;
protected:
const TraceBuffer& buffer;
size_t index;
};
/**
* @return A const iterator to the first chunk of the TraceBuffer
*/
virtual chunk_iterator chunk_begin() const = 0;
/**
* @return A const iterator to after the last chunk of the TraceBuffer
*/
virtual chunk_iterator chunk_end() const = 0;
/**
* Const iterator over a TraceBuffer, implements required methods of
* a bi-directional iterator.
*
* Usage:
*
* event_iterator it = trace_buffer.start();
* std::cout << *it << std::endl;
* std::cout << *(++it) << std::endl;
*
* for(const auto& event : trace_buffer) {
* std::cout << event << std::endl;
* }
*
* For resource efficiency event_iterator does not have
* post-increment
*/
using event_iterator = gsl_p::multidimensional_iterator<chunk_iterator>;
/**
* @return A const iterator to the first event of the TraceBuffer
*/
virtual event_iterator begin() const = 0;
/**
* @return A const iterator to after the last event of the TraceBuffer
*/
virtual event_iterator end() const = 0;
/**
* Helper class that can be used to create for-range loops over
* the chunks of the TraceBuffer
*
* for(const auto& chunk : TraceBuffer::chunk_iterable(buffer) {
* // Do something with every chunk
* }
*/
class PHOSPHOR_API chunk_iterable {
public:
/**
* @param buffer_ The buffer to iterate over
*/
chunk_iterable(const TraceBuffer& buffer_) : buffer(buffer_) {}
/**
* @return A const iterator to the first chunk of the buffer
*/
chunk_iterator begin() {
return buffer.chunk_begin();
}
/**
* @return A const iterator to after the last chunk of the buffer
*/
chunk_iterator end() {
return buffer.chunk_end();
}
private:
const TraceBuffer& buffer;
};
/**
* Helper function for creating a chunk_iterable over the buffer
*
* for(const auto& chunk : buffer.chunks() {
* // Do something with every chunk
* }
*
* @return An iterable over the class
*/
chunk_iterable chunks() const {
return chunk_iterable(*this);
}
};
using buffer_ptr = std::unique_ptr<TraceBuffer>;
/**
* Interface for a TraceBuffer factory
*/
using trace_buffer_factory =
std::function<buffer_ptr(size_t generation, size_t buffer_size)>;
PHOSPHOR_API
buffer_ptr make_fixed_buffer(size_t generation, size_t buffer_size);
PHOSPHOR_API
buffer_ptr make_ring_buffer(size_t generation, size_t buffer_size);
}
| {
"alphanum_fraction": 0.5732704138,
"avg_line_length": 32.2472826087,
"ext": "h",
"hexsha": "213ef2bd7f3893661f0e612f7b823eccdc3b7ac5",
"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": "ef090fa5b331dd94301cd8562b24c78c0c2030f1",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Chippiewill/Phosphor",
"max_forks_repo_path": "include/phosphor/trace_buffer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1",
"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": "Chippiewill/Phosphor",
"max_issues_repo_path": "include/phosphor/trace_buffer.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ef090fa5b331dd94301cd8562b24c78c0c2030f1",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Chippiewill/Phosphor",
"max_stars_repo_path": "include/phosphor/trace_buffer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2508,
"size": 11867
} |
#include <stdio.h>
#include <math.h>
#include "mf.h"
#include <gsl/gsl_integration.h>
//****************************the functions are listed below**********
double func1 (double y, double T) //The self-consistent equation f(y)=0
{
double res = tanh(3*y/T)-y;
return res;
}
double func2 (double y, double T) //The free energy per site
{
double res = 0.5*3*y*y-T*log(2*cosh(3*y)/T);
return res;
}
//*****************************************************************************
int main()
{
FILE *fp;
int anyi;
if((fp=fopen(filename,"w"))==NULL)
{
printf("cannot open the file: %s\n",filename);
printf("Please input an integer to end the program:");
scanf("%d",&anyi);
return 0;
}
FILE *ffp;
if((ffp=fopen(filename2,"w"))==NULL)
{
printf("cannot open the file: %s\n",filename2);
printf("Please input an integer to end the program:");
scanf("%d",&anyi);
return 0;
}
double tem0; //judge indicator
double T_step; //the step of Temperature
T_step = (T_high-T_low)/(N_T-1); //note N_T is the tatal points of T
// printf("The temperature step is %lf\n",T_step);
double y_1;
double y_2;
double tem_1;
double tem_2;
double T = T_low;
int i,j; //loop indicator
for(i=0;i<N_T;i++)
{
T = T_low + i*T_step;
y_1=1e-1;
y_2=1e7;
tem_1 = func1(y_1, T);
tem_2 = func1(y_2, T);
//if(tem_1<0||tem_2>0)
if(tem_1*tem_2>0)
{
printf("The two points in the boundary isn't good! Give up them now. Do it, baby!\n");
return 0;
}
//******************************************
for(j=10;j>1;j++)
{
tem_1 = func1(y_1, T);
tem_2 = func1(y_2, T);
tem0 = func1((y_1+y_2)/2.,T);
// printf("tem_1:%lf\ttem_2:%lf\n",tem_1,tem_2);
if((tem_1<precision&&tem_1>=0)||(tem_1>-precision&&tem_1<=0))
{
fprintf(fp,"%lf\t%lf\n",T,y_1);
fprintf(ffp,"%lf\t%lf\t%lf\n",T,func2(y_1,T),func2(-y_1,T));
j=0;
}
if((tem_2<precision&&tem_2>=0)||(tem_2>-precision&&tem_2<=0))
{
fprintf(fp,"%lf\t%lf\n",T,y_2);
fprintf(ffp,"%lf\t%lf\t%lf\n",T,func2(y_2,T),func2(-y_2,T));
j=0;
}
if(tem_1*tem0>0)
{
y_1 = (y_1+y_2)/2;
}
if(tem_2*tem0>0)
{
y_2 = (y_1+y_2)/2;
}
printf("%lf\n",(y_1+y_2)/2); //the mediate point value
}
}
return 1;
}
| {
"alphanum_fraction": 0.5466138962,
"avg_line_length": 22.0776699029,
"ext": "c",
"hexsha": "7d96771b9a332defd4200e442c4daa3d75ff192a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-03-08T13:02:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-30T23:57:04.000Z",
"max_forks_repo_head_hexsha": "d4883ff670a7131161de53bcbff7947851403635",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "PostQuantum/Buckyball-Ising-Model",
"max_forks_repo_path": "q1/1_mean-field/m-eq/mf.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d4883ff670a7131161de53bcbff7947851403635",
"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": "PostQuantum/Buckyball-Ising-Model",
"max_issues_repo_path": "q1/1_mean-field/m-eq/mf.c",
"max_line_length": 89,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "d4883ff670a7131161de53bcbff7947851403635",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "PostQuantum/Buckyball-Ising-Model",
"max_stars_repo_path": "q1/1_mean-field/m-eq/mf.c",
"max_stars_repo_stars_event_max_datetime": "2020-03-13T03:00:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-10T01:23:24.000Z",
"num_tokens": 839,
"size": 2274
} |
/**
*
* @file core_ztsrfb.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 Hatem Ltaief
* @author Mathieu Faverge
* @author Azzam Haidar
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <cblas.h>
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex64_t
*
* CORE_ztsrfb applies a complex block reflector H or its transpose H' to a
* complex rectangular matrix formed by coupling two tiles A1 and A2,
* from either the left or the right.
*
*******************************************************************************
*
* @param[in] side
* @arg PlasmaLeft : apply Q or Q**H from the Left;
* @arg PlasmaRight : apply Q or Q**H from the Right.
*
* @param[in] trans
* @arg PlasmaNoTrans : No transpose, apply Q;
* @arg PlasmaConjTrans : ConjTranspose, apply Q**H.
*
* @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] M1
* The number of columns of the tile A1. M1 >= 0.
*
* @param[in] N1
* The number of rows of the tile A1. N1 >= 0.
*
* @param[in] M2
* The number of columns of the tile A2. M2 >= 0.
*
* @param[in] N2
* The number of rows of the tile A2. N2 >= 0.
*
* @param[in] K
* The order of the matrix T (= the number of elementary
* reflectors whose product defines the block reflector).
*
* @param[in,out] A1
* On entry, the M1-by-N1 tile A1.
* On exit, A1 is overwritten by the application of Q.
*
* @param[in] LDA1
* The leading dimension of the array A1. LDA1 >= max(1,N1).
*
* @param[in,out] A2
* On entry, the M2-by-N2 tile A2.
* On exit, A2 is overwritten by the application of Q.
*
* @param[in] LDA2
* The leading dimension of the tile A2. LDA2 >= max(1,N2).
*
* @param[in] V
* (LDV,K) if STOREV = 'C'
* (LDV,M2) if STOREV = 'R' and SIDE = 'L'
* (LDV,N2) if STOREV = 'R' and SIDE = 'R'
* The matrix V.
*
* @param[in] LDV
* The leading dimension of the array V.
* If STOREV = 'C' and SIDE = 'L', LDV >= max(1,M2);
* if STOREV = 'C' and SIDE = 'R', LDV >= max(1,N2);
* if STOREV = 'R', LDV >= K.
*
* @param[out] 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] WORK
*
* @param[in] LDWORK
* The dimension of the array WORK.
*
*******************************************************************************
*
* @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_ztsrfb = PCORE_ztsrfb
#define CORE_ztsrfb PCORE_ztsrfb
#endif
int
CORE_ztsrfb(PLASMA_enum side, PLASMA_enum trans, int direct, int storev,
int M1, int N1, int M2, int N2, int K,
PLASMA_Complex64_t *A1, int LDA1,
PLASMA_Complex64_t *A2, int LDA2,
const PLASMA_Complex64_t *V, int LDV,
const PLASMA_Complex64_t *T, int LDT,
PLASMA_Complex64_t *WORK, int LDWORK)
{
static PLASMA_Complex64_t zone = 1.0;
static PLASMA_Complex64_t mzone = -1.0;
int j;
/* Check input arguments */
if (M1 < 0) {
coreblas_error(5, "Illegal value of M1");
return -5;
}
if (N1 < 0) {
coreblas_error(6, "Illegal value of N1");
return -6;
}
if ( (M2 < 0) ||
( (M2 != M1) && (side == PlasmaRight) ) ){
coreblas_error(7, "Illegal value of M2");
return -7;
}
if ( (N2 < 0) ||
( (N2 != N1) && (side == PlasmaLeft) ) ){
coreblas_error(8, "Illegal value of N2");
return -8;
}
if (K < 0) {
coreblas_error(9, "Illegal value of K");
return -9;
}
/* Quick return */
if ((M1 == 0) || (N1 == 0) || (M2 == 0) || (N2 == 0) || (K == 0))
return PLASMA_SUCCESS;
if (storev == PlasmaColumnwise) {
if (direct == PlasmaForward) {
if (side == PlasmaLeft) {
/*
* B = A1 + V' * A2
*/
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,
lapack_const(PlasmaUpperLower),
K, N1,
A1, LDA1, WORK, LDWORK);
cblas_zgemm(
CblasColMajor, CblasConjTrans, CblasNoTrans,
K, N2, M2,
CBLAS_SADDR(zone), V, LDV,
A2, LDA2,
CBLAS_SADDR(zone), WORK, LDWORK);
/*
* A2 = A2 - V*T*B -> B = T*B, A2 = A2 - V*B
*/
cblas_ztrmm(
CblasColMajor, CblasLeft, CblasUpper,
(CBLAS_TRANSPOSE)trans, CblasNonUnit, K, N2,
CBLAS_SADDR(zone), T, LDT, WORK, LDWORK);
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans,
M2, N2, K,
CBLAS_SADDR(mzone), V, LDV,
WORK, LDWORK,
CBLAS_SADDR(zone), A2, LDA2);
/*
* A1 = A1 - B
*/
for(j = 0; j < N1; j++) {
cblas_zaxpy(
K, CBLAS_SADDR(mzone),
&WORK[LDWORK*j], 1,
&A1[LDA1*j], 1);
}
}
/*
* Columnwise / Forward / Right
*/
else {
/*
* B = A1 + A2 * V
*/
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,
lapack_const(PlasmaUpperLower),
M1, K,
A1, LDA1, WORK, LDWORK);
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans,
M2, K, N2,
CBLAS_SADDR(zone), A2, LDA2,
V, LDV,
CBLAS_SADDR(zone), WORK, LDWORK);
/*
* A2 = A2 - B*T*V' -> B = B*T, A2 = A2 - B*V'
*/
cblas_ztrmm(
CblasColMajor, CblasRight, CblasUpper,
(CBLAS_TRANSPOSE)trans, CblasNonUnit, M1, K,
CBLAS_SADDR(zone), T, LDT, WORK, LDWORK);
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasConjTrans,
M2, N2, K,
CBLAS_SADDR(mzone), WORK, LDWORK,
V, LDV,
CBLAS_SADDR(zone), A2, LDA2);
/*
* A1 = A1 - B
*/
for(j = 0; j < K; j++) {
cblas_zaxpy(
M1, CBLAS_SADDR(mzone),
&WORK[LDWORK*j], 1,
&A1[LDA1*j], 1);
}
}
}
else {
coreblas_error(3, "Not implemented (ColMajor / Backward / Left or Right)");
return PLASMA_ERR_NOT_SUPPORTED;
}
}
else {
if (direct == PlasmaForward) {
/*
* Rowwise / Forward / Left
*/
if (side == PlasmaLeft) {
/*
* B = A1 + V * A2
*/
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,
lapack_const(PlasmaUpperLower),
K, N1,
A1, LDA1, WORK, LDWORK);
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans,
K, N2, M2,
CBLAS_SADDR(zone), V, LDV,
A2, LDA2,
CBLAS_SADDR(zone), WORK, LDWORK);
/*
* A2 = A2 - V'*T*B -> B = T*B, A2 = A2 - V'*B
*/
cblas_ztrmm(
CblasColMajor, CblasLeft, CblasUpper,
(CBLAS_TRANSPOSE)trans, CblasNonUnit, K, N2,
CBLAS_SADDR(zone), T, LDT, WORK, LDWORK);
cblas_zgemm(
CblasColMajor, CblasConjTrans, CblasNoTrans,
M2, N2, K,
CBLAS_SADDR(mzone), V, LDV,
WORK, LDWORK,
CBLAS_SADDR(zone), A2, LDA2);
/*
* A1 = A1 - B
*/
for(j=0; j<N1; j++) {
cblas_zaxpy(
K, CBLAS_SADDR(mzone),
&WORK[LDWORK*j], 1,
&A1[LDA1*j], 1);
}
}
/*
* Rowwise / Forward / Right
*/
else {
/*
* B = A1 + A2 * V'
*/
LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,
lapack_const(PlasmaUpperLower),
M1, K,
A1, LDA1, WORK, LDWORK);
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasConjTrans,
M2, K, N2,
CBLAS_SADDR(zone), A2, LDA2,
V, LDV,
CBLAS_SADDR(zone), WORK, LDWORK);
/*
* A2 = A2 - B*T*V -> B = B*T, A2 = A2 - B*V'
*/
cblas_ztrmm(
CblasColMajor, CblasRight, CblasUpper,
(CBLAS_TRANSPOSE)trans, CblasNonUnit, M1, K,
CBLAS_SADDR(zone), T, LDT, WORK, LDWORK);
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans,
M2, N2, K,
CBLAS_SADDR(mzone), WORK, LDWORK,
V, LDV,
CBLAS_SADDR(zone), A2, LDA2);
/*
* A1 = A1 - B
*/
for(j = 0; j < K; j++) {
cblas_zaxpy(
M1, CBLAS_SADDR(mzone),
&WORK[LDWORK*j], 1,
&A1[LDA1*j], 1);
}
}
}
else {
coreblas_error(3, "Not implemented (RowMajor / Backward / Left or Right)");
return PLASMA_ERR_NOT_SUPPORTED;
}
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.4319758136,
"avg_line_length": 32.7871720117,
"ext": "c",
"hexsha": "022273d071b019fcdac0a4d8308451c8ee9e25f6",
"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_ztsrfb.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_ztsrfb.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_ztsrfb.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3055,
"size": 11246
} |
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mpfr.h>
#include <petsc.h>
#include "ellipsoid/ellipsoid.h"
#include "ellipsoid/ellSolv.h"
#include "sphere/sphere.h"
#include "sphere/sphSolv.h"
#include "constants.h"
#include "testProblem.h"
//compares ellipsoidal and spherical
//has ellipsoidal distribution of charges just inside ellipsoidal boundary
//computes the solution at two point, one inside smallest enclosing sphere where spherical diverges
//other solution point is outside of sphere and ellipse to compare convergence
#undef __FUNCT__
#define __FUNCT__ "EllVsSphConvergence"
PetscErrorCode EllVsSphConvergence()
{
PetscErrorCode ierr;
//semi-axes of ellipsoid
PetscReal a = 3.0;
PetscReal b = 2.5;
PetscReal c = 1.2;
//sphere radius
PetscReal sphRad = 3;
//dielecric permitivities both set to 1
const PetscReal eps1 = 1.0;
const PetscReal eps2 = 1.0;
//charges placed on ellipsoid with sem-axes smaller by epsilon
PetscReal epsilon = .5;
//interior charge XYZ and magnitude
const PetscInt SQRT_NUM_CHARGES = 3;
Vec chargeXYZ;
Vec chargeMag;
//maximum expansion order for test
const PetscInt MAX_N = 20;
//solutions vector
const PetscInt NUM_SOL_PTS = 2;
Vec ellSolutions[MAX_N], sphSolutions[MAX_N];
Vec ellError[MAX_N], sphError[MAX_N];
Vec exactSolution;
Vec solXYZ;
//solution point inside of sphere
PetscReal sol1X = .1;
PetscReal sol1Y = .1;
PetscReal sol1Z = 1.5;
//solution point outside of sphere
PetscReal sol2X = 2.1;
PetscReal sol2Y = 2.6;
PetscReal sol2Z = 1;
//pointer for accessing petsc vectors
PetscScalar *vecPt;
PetscFunctionBegin;
//create, set charge magnitudes to 1
ierr = VecCreateSeq(PETSC_COMM_SELF, SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, &chargeMag);CHKERRQ(ierr);
ierr = VecSet(chargeMag, 1.0);CHKERRQ(ierr);
//create, set charge XYZ values to be on a-eps,b-eps,c-eps ellipsoid
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, &chargeXYZ);CHKERRQ(ierr);
ierr = VecGetArray(chargeXYZ, &vecPt);CHKERRQ(ierr);
PetscReal pu, pv;
for(PetscInt i=0; i<SQRT_NUM_CHARGES; ++i) {
for(PetscInt j=0; j<SQRT_NUM_CHARGES; ++j) {
pu = i*2.0*PETSC_PI/(SQRT_NUM_CHARGES-1);
pv = j*PETSC_PI/(SQRT_NUM_CHARGES-1);
PetscInt ind = i*SQRT_NUM_CHARGES + j;
//there is a slight issue with on-axes coordinate transforms which is what the +.01 is for
vecPt[3*ind + 0] = (a-epsilon)*PetscCosReal(pu)*PetscSinReal(pv) +.01;
vecPt[3*ind + 1] = (b-epsilon)*PetscSinReal(pu)*PetscSinReal(pv) + .01;
vecPt[3*ind + 2] = (c-epsilon)*PetscCosReal(pv) + .01;
printf("pu: %3.3f pv: %3.3f\n", pu, pv);
}
}
ierr = VecRestoreArray(chargeXYZ, &vecPt);CHKERRQ(ierr);
//set solution points vector
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*NUM_SOL_PTS, &solXYZ);CHKERRQ(ierr);
ierr = VecGetArray(solXYZ, &vecPt);CHKERRQ(ierr);
vecPt[0] = sol1X; vecPt[1] = sol1Y; vecPt[2] = sol1Z;
vecPt[3] = sol2X; vecPt[4] = sol2Y; vecPt[5] = sol2Z;
ierr = VecRestoreArray(solXYZ, &vecPt);CHKERRQ(ierr);
//caulculate exact solution
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_SOL_PTS, &exactSolution);CHKERRQ(ierr);
ierr = CoulombExact(eps1, chargeXYZ, chargeMag, solXYZ, exactSolution);CHKERRQ(ierr);
//initialize solutions and error vectors
for(PetscInt k=0; k<MAX_N; ++k) {
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_SOL_PTS, ellSolutions+k);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_SOL_PTS, sphSolutions+k);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_SOL_PTS, ellError+k);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_SOL_PTS, sphError+k);CHKERRQ(ierr);
}
//compute solutions for expansions up to order MAX_N
for(PetscInt k=1; k<=MAX_N; ++k) {
printf("N = %d\n", k);
printf("calculating ellipsoidal solution...\n");
ierr = CalcEllipsoidCoulombPotential(a, b, c, eps1, eps2, SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, chargeXYZ, chargeMag, NUM_SOL_PTS, solXYZ, k, ellSolutions[k-1]);CHKERRQ(ierr);
printf("calculating spherical solution...\n");
ierr = CalcSphericalCoulombPotential(1.0, eps1, eps2, SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, chargeXYZ, chargeMag, NUM_SOL_PTS, solXYZ, k, sphSolutions[k-1]);CHKERRQ(ierr);
}
//compute errors
printf("Computing errors...\n");
for(PetscInt k=0; k<MAX_N; ++k) {
ierr = VecCopy(exactSolution, ellError[k]);CHKERRQ(ierr);
ierr = VecCopy(exactSolution, sphError[k]);CHKERRQ(ierr);
ierr = VecAXPY(ellError[k], -1.0, ellSolutions[k]);CHKERRQ(ierr);
ierr = VecAXPY(sphError[k], -1.0, sphSolutions[k]);CHKERRQ(ierr);
ierr = VecAbs(ellError[k]);CHKERRQ(ierr);
ierr = VecAbs(sphError[k]);CHKERRQ(ierr);
}
for(PetscInt k=0; k<MAX_N; ++k) {
ierr = VecGetArrayRead(ellError[k], &vecPt);
printf("Error[%d] = %4.4e\n", k, vecPt[0]);
ierr = VecRestoreArrayRead(ellError[k], &vecPt);
}
printf("Exact: \n");
ierr = VecView(exactSolution, PETSC_VIEWER_STDOUT_SELF);
printf("Ell: \n");
ierr = VecView(ellSolutions[MAX_N-1], PETSC_VIEWER_STDOUT_SELF);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "runTest1"
void runTest1() {
const int nCharges = 1;
EllipsoidalSystem e;
initEllipsoidalSystem(&e, 3.0, 2.0, 1.0, 64);
//grid dimensions
int nx = 10;
int ny = 10;
int nz = 2;
int nPoints = nx*ny*nz;
double xa = -5;
double xb = 5;
double ya = -5;
double yb = 5;
double za = -3;
double zb = 3;
double xh = (xb - xa)/(nx-1);
double yh = (yb - ya)/(ny-1);
double zh = (zb - za)/(nz-1);
double charges[nCharges];
for(int i=0; i<nCharges; ++i)
charges[i] = 1.0;
//source charges
SPoint sPoints[nCharges];
Point ePoints[nCharges];
sPoints[0].x1 = 2.02;
sPoints[0].x2 = -0.4;
sPoints[0].x3 = -.463;
ePoints[0].x1 = sPoints[0].x1;
ePoints[0].x2 = sPoints[0].x2;
ePoints[0].x3 = sPoints[0].x3;
//permitivity constants
double e1 = 1.0;
double e2 = 1.0;
printf("entering\n");
//solution vector
SPoint *rs = (SPoint*) malloc(sizeof(SPoint)*nPoints);
Point *re = (Point*) malloc(sizeof(Point) *nPoints);
SPoint *ro = (SPoint*) malloc(sizeof(SPoint)*nPoints);
double *exact = (double*) malloc(sizeof(double)*nPoints);
for(int i=0; i<nx; ++i) {
for(int j=0; j<ny; ++j) {
for(int k=0; k<nz; ++k) {
int index = k*ny*nx + j*nx + i;
rs[index].x1 = xa + i*xh;
rs[index].x2 = ya + j*yh;
rs[index].x3 = za + k*zh;
printf("rs[3] = %15.15f\n", rs[index].x3);
re[index].x1 = rs[index].x1;
re[index].x2 = rs[index].x2;
re[index].x3 = rs[index].x3;
ro[index].x1 = re[index].x1;
ro[index].x2 = re[index].x2;
ro[index].x3 = re[index].x3;
exact[index] = 0.0;
for(int num=0; num<nCharges; ++num)
exact[index] += charges[num]/(e1*sqrt((sPoints[num].x1 - ro[index].x1)*(sPoints[num].x1 - ro[index].x1) +
(sPoints[num].x2 - ro[index].x2)*(sPoints[num].x2 - ro[index].x2) +
(sPoints[num].x3 - ro[index].x3)*(sPoints[num].x3 - ro[index].x3)));
}
}
}
printf("exiting\n");
//convert to spherical/ellipsoidal coordinates
for(int i=0; i<nCharges; ++i) {
cartesianToSpherical(sPoints+i);
cartesianToEllipsoidal(&e, ePoints+i);
}
//convert to spherical/ellipsoidal coordinates
for(int i=0; i<nPoints; ++i) {
cartesianToSpherical(rs + i);
cartesianToEllipsoidal(&e, re + i);
}
//set up problem
SProblem sProblem = {.positions = sPoints, .charges = charges, .nCharges = nCharges, .e1 = e1, .e2 = e2, .b = 3.0};
Problem eProblem = {.positions = ePoints, .charges = charges, .nCharges = nCharges, .e1 = e1, .e2 = e2, .e = &e};
double *ssolution = (double*) malloc(sizeof(double)*nPoints);
double *esolution = (double*) malloc(sizeof(double)*nPoints);
calcCoulombSphericalGrid(&sProblem, 14, rs, nPoints, ssolution);
calcCoulombEllipsoidalGrid(&eProblem, 14, re, nPoints, esolution);
//add coulomb inside for plotting. Add later to calculation
for(int i=0; i<nPoints; ++i) {
for(int k=0; k<nCharges; ++k) {
//if inside sphere
//
//if(
}
}
printf("exact[0] = %15.15f\n", exact[0]);
//compare errors
double *sError = (double*) malloc(sizeof(double)*nPoints);
double *eError = (double*) malloc(sizeof(double)*nPoints);
for(int i=0; i<nx; ++i) {
for(int j=0; j<ny; ++j) {
for(int k=0; k<nz; ++k) {
int index = k*ny*nx + j*nx + i;
sError[index] = fabs(ssolution[index] - exact[index]);
eError[index] = fabs(esolution[index] - exact[index]);
if(i==1)
printf("%d - s: %4.4e e: %4.4e\n", i, sError[index], eError[index]);
}
}
}
}
#undef __FUNCT__
#define __FUNCT__ "RunArg"
PetscErrorCode RunArg()
{
PetscErrorCode ierr;
char buff[64];
int npts;
double a, b, c;
double *xyz;
double *chargeValues;
double *solution;
double freeEnergy;
PetscFunctionBegin;
//constants
const double q = ELECTRON_CHARGE;
const double Na = AVOGADRO_NUMBER;
const double JperC = 4.184; /* Jouled/Calorie */
const double cf = Na * (q*q/EPSILON_0)/JperC * (1e10/1000) * 1/4/PETSC_PI; /* kcal ang/mol */
FILE *fp = fopen("ellArgData.txt", "r");
// READ NUMBER OF POINTS
fscanf(fp, "%s", buff); //skip "size: "
fscanf(fp, "%d", &npts);
//initialize local charges/coordinates arrays
xyz = (double*) malloc(sizeof(double)*3*npts);
chargeValues = (double*) malloc(sizeof(double)*npts);
// READ A,B,C ELLIPSOID VALUES
fscanf(fp, "%s", buff); //skip "a: "
fscanf(fp, "%lf", &a); //read a value
fscanf(fp, "%s", buff); //skip "b: "
fscanf(fp, "%lf", &b); //read b value
fscanf(fp, "%s", buff); //skip "c: "
fscanf(fp, "%lf", &c);
// READ CHARGE X,Y,Z AND CHARGE DATA
for(int i=0; i<npts; ++i) {
fscanf(fp, "%lf", xyz+3*i+0); //read x coordinate
fscanf(fp, "%lf", xyz+3*i+1); //read y coordinate
fscanf(fp, "%lf", xyz+3*i+2); //read z coordinate
fscanf(fp, "%lf", chargeValues+i); //read charge
printf("%lf %lf %lf %lf\n", xyz[3*i+0], xyz[3*i+1], xyz[3*i+2], chargeValues[i]);
}
fclose(fp);
//initialize ellipsoidal system
EllipsoidalSystem e;
initEllipsoidalSystem(&e, a, b, c, 64);
//set charge positions and calculation points to be the same
Point *solPoints = (Point*) malloc(sizeof(Point)*npts);
Point *chargePoints = (Point*) malloc(sizeof(Point)*npts);
for(int i=0; i<npts; ++i) {
solPoints[i].x1 = xyz[3*i+0];
solPoints[i].x2 = xyz[3*i+1];
solPoints[i].x3 = xyz[3*i+2];
solPoints[i].type = 'c';
chargePoints[i] = solPoints[i];
}
//convert to ellipsoidal coordinates
for(int i=0; i<npts; ++i) {
cartesianToEllipsoidal(&e, solPoints+i);
cartesianToEllipsoidal(&e, chargePoints+i);
}
//initialize ellipsoidal problem context
Problem prob;
prob.e = &e;
prob.positions = chargePoints;
prob.charges = chargeValues;
prob.nCharges = npts;
prob.e1 = 4.0;
prob.e2 = 80.0;
//solution vector
solution = (double*) malloc(sizeof(double)*npts);
//calculate potential on solPoints
calcCoulombEllipsoidalGrid(&prob, 10, solPoints, npts, solution);
printf("wow!\n");
for(int i=0; i<npts; ++i)
printf("solution[%d] = %15.15f\n", i, solution[i]);
for(int i=0; i<npts; ++i)
printf("chargeValues[%d] = %15.15f\n", i, chargeValues[i]);
//calculate free energy
freeEnergy = 0;
for(int i=0; i<npts; ++i) {
freeEnergy += solution[i]*chargeValues[i];
printf("freeEnergy[%d] = %15.15f\n", i, freeEnergy*.5*cf);
}
printf("\n");
printf("Free energy: %15.15f\n", freeEnergy*.5*cf);
free(xyz);
free(chargeValues);
free(solPoints);
free(solution);
free(chargePoints);
PetscFunctionReturn(0);
}
/* DOESN'T DO ANYTHING YET */
#undef __FUNCT__
#define __FUNCT__ "RunArgWorkPrec"
PetscErrorCode RunArgWorkPrec()
{
PetscErrorCode ierr;
char buff[64];
int npts;
double a, b, c;
double *xyz;
double *chargeValues;
double *solution;
double freeEnergy;
PetscFunctionBegin;
//constants
const double q = ELECTRON_CHARGE;
const double Na = AVOGADRO_NUMBER;
const double JperC = 4.184; /* Jouled/Calorie */
const double cf = Na * (q*q/EPSILON_0)/JperC * (1e10/1000) * 1/4/PETSC_PI; /* kcal ang/mol */
FILE *fp = fopen("ellArgData.txt", "r");
// READ NUMBER OF POINTS
fscanf(fp, "%s", buff); //skip "size: "
fscanf(fp, "%d", &npts);
//initialize local charges/coordinates arrays
xyz = (double*) malloc(sizeof(double)*3*npts);
chargeValues = (double*) malloc(sizeof(double)*npts);
// READ A,B,C ELLIPSOID VALUES
fscanf(fp, "%s", buff); //skip "a: "
fscanf(fp, "%lf", &a); //read a value
fscanf(fp, "%s", buff); //skip "b: "
fscanf(fp, "%lf", &b); //read b value
fscanf(fp, "%s", buff); //skip "c: "
fscanf(fp, "%lf", &c);
// READ CHARGE X,Y,Z AND CHARGE DATA
for(int i=0; i<npts; ++i) {
fscanf(fp, "%lf", xyz+3*i+0); //read x coordinate
fscanf(fp, "%lf", xyz+3*i+1); //read y coordinate
fscanf(fp, "%lf", xyz+3*i+2); //read z coordinate
fscanf(fp, "%lf", chargeValues+i); //read charge
printf("%lf %lf %lf %lf\n", xyz[3*i+0], xyz[3*i+1], xyz[3*i+2], chargeValues[i]);
}
fclose(fp);
//initialize ellipsoidal system
EllipsoidalSystem e;
initEllipsoidalSystem(&e, a, b, c, 64);
//set charge positions and calculation points to be the same
Point *solPoints = (Point*) malloc(sizeof(Point)*npts);
Point *chargePoints = (Point*) malloc(sizeof(Point)*npts);
for(int i=0; i<npts; ++i) {
solPoints[i].x1 = xyz[3*i+0];
solPoints[i].x2 = xyz[3*i+1];
solPoints[i].x3 = xyz[3*i+2];
solPoints[i].type = 'c';
chargePoints[i] = solPoints[i];
}
//convert to ellipsoidal coordinates
for(int i=0; i<npts; ++i) {
cartesianToEllipsoidal(&e, solPoints+i);
cartesianToEllipsoidal(&e, chargePoints+i);
}
//initialize ellipsoidal problem context
Problem prob;
prob.e = &e;
prob.positions = chargePoints;
prob.charges = chargeValues;
prob.nCharges = npts;
prob.e1 = 4.0;
prob.e2 = 80.0;
//solution vector
solution = (double*) malloc(sizeof(double)*npts);
//calculate potential on solPoints
calcCoulombEllipsoidalGrid(&prob, 10, solPoints, npts, solution);
printf("wow!\n");
for(int i=0; i<npts; ++i)
printf("solution[%d] = %15.15f\n", i, solution[i]);
for(int i=0; i<npts; ++i)
printf("chargeValues[%d] = %15.15f\n", i, chargeValues[i]);
//calculate free energy
freeEnergy = 0;
for(int i=0; i<npts; ++i) {
freeEnergy += solution[i]*chargeValues[i];
printf("freeEnergy[%d] = %15.15f\n", i, freeEnergy*.5*cf);
}
free(xyz);
free(chargeValues);
free(solPoints);
free(solution);
free(chargePoints);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "RunArgTester"
PetscErrorCode RunArgTester()
{
PetscErrorCode ierr;
char buff[64];
int npts;
double a, b, c;
double *xyz;
double *chargeValues;
double *solution;
double freeEnergy;
PetscFunctionBegin;
//constants
const double q = ELECTRON_CHARGE;
const double Na = AVOGADRO_NUMBER;
const double JperC = 4.184; /* Jouled/Calorie */
const double cf = Na * (q*q/EPSILON_0)/JperC * (1e10/1000) * 1/4/PETSC_PI; /* kcal ang/mol */
FILE *fp = fopen("../../pointbem/src/ellData.txt", "r");
// READ NUMBER OF POINTS
fscanf(fp, "%s", buff); //skip "size: "
fscanf(fp, "%d", &npts);
//initialize local charges/coordinates arrays
xyz = (double*) malloc(sizeof(double)*3*npts);
chargeValues = (double*) malloc(sizeof(double)*npts);
// READ A,B,C ELLIPSOID VALUES
fscanf(fp, "%s", buff); //skip "a: "
fscanf(fp, "%lf", &a); //read a value
fscanf(fp, "%s", buff); //skip "b: "
fscanf(fp, "%lf", &b); //read b value
fscanf(fp, "%s", buff); //skip "c: "
fscanf(fp, "%lf", &c);
// READ CHARGE X,Y,Z AND CHARGE DATA
for(int i=0; i<npts; ++i) {
fscanf(fp, "%lf", xyz+3*i+0); //read x coordinate
fscanf(fp, "%lf", xyz+3*i+1); //read y coordinate
fscanf(fp, "%lf", xyz+3*i+2); //read z coordinate
fscanf(fp, "%lf", chargeValues+i); //read charge
printf("%lf %lf %lf %lf\n", xyz[3*i+0], xyz[3*i+1], xyz[3*i+2], chargeValues[i]);
}
fclose(fp);
//initialize ellipsoidal system
EllipsoidalSystem e;
initEllipsoidalSystem(&e, a, b, c, 64);
//set charge positions and calculation points to be the same
Point *solPoints = (Point*) malloc(sizeof(Point)*npts);
Point *chargePoints = (Point*) malloc(sizeof(Point)*npts);
for(int i=0; i<npts; ++i) {
solPoints[i].x1 = xyz[3*i+0];
solPoints[i].x2 = xyz[3*i+1];
solPoints[i].x3 = xyz[3*i+2];
solPoints[i].type = 'c';
chargePoints[i] = solPoints[i];
}
Vec valsbef; //testing
PetscScalar* valsbefArray; //testing
ierr = VecCreateSeq(PETSC_COMM_SELF, npts, &valsbef); CHKERRQ(ierr); //testing
ierr = VecGetArray(valsbef, &valsbefArray); CHKERRQ(ierr); //testing
//convert to ellipsoidal coordinates
for(int i=0; i<npts; ++i) {
cartesianToEllipsoidal(&e, solPoints+i);
ierr = CalcSolidInteriorHarmonic(&e, solPoints[i].x1, solPoints[i].x2, solPoints[i].x3, 2, 3, valsbefArray+i); //testing
cartesianToEllipsoidal(&e, chargePoints+i);
}
ierr = VecRestoreArray(valsbef, &valsbefArray); CHKERRQ(ierr); //testing
Vec ellPoints, vals; //testing
PetscScalar* ellPointsArray; //testing
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*npts, &ellPoints); CHKERRQ(ierr); //testing
ierr = VecGetArray(ellPoints, &ellPointsArray); CHKERRQ(ierr); //testing
for(PetscInt i=0; i<npts; ++i) { //testing
ellPointsArray[3*i+0] = solPoints[i].x1; //testing
ellPointsArray[3*i+1] = solPoints[i].x2; //testing
ellPointsArray[3*i+2] = solPoints[i].x3; //testing
}
ierr = VecRestoreArray(ellPoints, &ellPointsArray); CHKERRQ(ierr); //testing
ierr = VecCreateSeq(PETSC_COMM_SELF, npts, &vals); CHKERRQ(ierr); //testing
ierr = CalcSolidInteriorHarmonicVec(&e, ellPoints, 2, 3, vals); //testing
PetscReal diff, val1, val2; //testing
diff = 0;
for(PetscInt i=0; i<npts; ++i) { //testing
ierr = VecGetValues(vals, 1, &i, &val1); CHKERRQ(ierr); //testing
ierr = VecGetValues(valsbef, 1, &i, &val2); CHKERRQ(ierr); //testing
diff += PetscSqrtReal(PetscAbsReal(val1 - val2)); //testing
}
printf("Solid Harmonic Error: %3.3e\n", diff); //testing
//initialize ellipsoidal problem context
Problem prob;
prob.e = &e;
prob.positions = chargePoints;
prob.charges = chargeValues;
prob.nCharges = npts;
prob.e1 = 4.0;
prob.e2 = 80.0;
/* ---------------------------- */
/* NOW WE TEST THE Gnp FUNCTION */
/* ---------------------------- */
PetscInt NMAX = 5;
PetscInt count = 0;
for(PetscInt n=0; n<=NMAX; ++n) {
for(PetscInt p=0; p<2*n+1; ++p)
count++;
}
Vec srcCharges, GnpVals, GnpValsOld, BnpVals, BnpValsOld, CnpVals, CnpValsOld;
Vec errorV;
ierr = VecCreateSeq(PETSC_COMM_SELF, npts, &srcCharges);CHKERRQ(ierr); //testing
ierr = VecCreateSeq(PETSC_COMM_SELF, count, &GnpValsOld);CHKERRQ(ierr); //testing
ierr = VecCreateSeq(PETSC_COMM_SELF, count, &BnpVals);CHKERRQ(ierr); //testing
ierr = VecCreateSeq(PETSC_COMM_SELF, count, &BnpValsOld);CHKERRQ(ierr); //testing
ierr = VecCreateSeq(PETSC_COMM_SELF, count, &CnpVals);CHKERRQ(ierr); //testing
ierr = VecCreateSeq(PETSC_COMM_SELF, count, &CnpValsOld);CHKERRQ(ierr); //testing
ierr = VecCreateSeq(PETSC_COMM_SELF, count, &errorV);CHKERRQ(ierr); //testing
for(PetscInt i=0; i<npts; ++i)
ierr = VecSetValues(srcCharges, 1, &i, chargeValues+i, INSERT_VALUES);CHKERRQ(ierr); //testing
ierr = VecAssemblyBegin(srcCharges);CHKERRQ(ierr); ierr = VecAssemblyEnd(srcCharges);CHKERRQ(ierr); //testing
//WOULD ACTUALLY USE CHARGE POINTS, NOT TARGET POINTS
//Calculate values with new function
ierr = CalcCoulombEllCoefs(&e, npts, ellPoints, srcCharges, NMAX, &GnpVals);CHKERRQ(ierr); //testing
ierr = CalcReactAndExtCoefsFromCoulomb(&e, prob.e1, prob.e2, NMAX, GnpVals, BnpVals, CnpVals);CHKERRQ(ierr);
//Calculate values with old function
PetscReal GnpOld, BnpOld, CnpOld;
count = 0;
for(PetscInt n=0; n<=NMAX; ++n) {
for(PetscInt p=0; p<2*n+1; ++p) {
GnpOld = calcGnp(&e, chargePoints, chargeValues, npts, n, p);
calcBnpAndCnpFromGnp(&prob, n, p, GnpOld, &BnpOld, &CnpOld);
ierr = VecSetValues(GnpValsOld, 1, &count, &GnpOld, INSERT_VALUES);CHKERRQ(ierr);
ierr = VecSetValues(BnpValsOld, 1, &count, &BnpOld, INSERT_VALUES);CHKERRQ(ierr);
ierr = VecSetValues(CnpValsOld, 1, &count, &CnpOld, INSERT_VALUES);CHKERRQ(ierr);
count++;
}
}
ierr = VecAssemblyBegin(GnpValsOld);CHKERRQ(ierr); ierr = VecAssemblyEnd(GnpValsOld);CHKERRQ(ierr);
ierr = VecAssemblyBegin(BnpValsOld);CHKERRQ(ierr); ierr = VecAssemblyEnd(BnpValsOld);CHKERRQ(ierr);
ierr = VecAssemblyBegin(CnpValsOld);CHKERRQ(ierr); ierr = VecAssemblyEnd(CnpValsOld);CHKERRQ(ierr);
PetscReal GnpErr, BnpErr, CnpErr;
ierr = VecWAXPY(errorV, -1.0, GnpVals, GnpValsOld);CHKERRQ(ierr);
ierr = VecNorm(errorV, NORM_2, &GnpErr);
ierr = VecWAXPY(errorV, -1.0, BnpVals, BnpValsOld);CHKERRQ(ierr);
ierr = VecNorm(errorV, NORM_2, &BnpErr);
ierr = VecWAXPY(errorV, -1.0, CnpVals, CnpValsOld);CHKERRQ(ierr);
ierr = VecNorm(errorV, NORM_2, &CnpErr);
printf("GnpErr: %3.3e\n", GnpErr);
printf("BnpErr: %3.3e\n", BnpErr);
printf("CnpErr: %3.3e\n", CnpErr);
//solution vector
solution = (double*) malloc(sizeof(double)*npts);
//calculate potential on solPoints
calcCoulombEllipsoidalGrid(&prob, 10, solPoints, npts, solution);
printf("wow!\n");
for(int i=0; i<npts; ++i)
printf("solution[%d] = %15.15f\n", i, solution[i]);
for(int i=0; i<npts; ++i)
printf("chargeValues[%d] = %15.15f\n", i, chargeValues[i]);
//calculate free energy
freeEnergy = 0;
for(int i=0; i<npts; ++i) {
freeEnergy += solution[i]*chargeValues[i];
printf("freeEnergy[%d] = %15.15f\n", i, freeEnergy*.5*cf);
}
free(xyz);
free(chargeValues);
free(solPoints);
free(solution);
free(chargePoints);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CoulombExact"
PetscErrorCode CoulombExact(PetscReal eps1, Vec srcXYZ, Vec srcMag, Vec tarXYZ, Vec sol)
{
PetscErrorCode ierr;
PetscReal srcX, srcY, srcZ;
PetscReal tarX, tarY, tarZ;
PetscReal dx2, dy2, dz2;
PetscReal val, mag;
const PetscScalar *srcXYZArray;
const PetscScalar *srcMagArray;
const PetscScalar *tarXYZArray;
PetscScalar *solArray;
PetscInt nSrc, nTar;
PetscInt i, k;
PetscFunctionBeginUser;
ierr = VecGetSize(srcMag, &nSrc);CHKERRQ(ierr);
ierr = VecGetSize(sol, &nTar);CHKERRQ(ierr);
ierr = VecGetArrayRead(srcXYZ, &srcXYZArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(tarXYZ, &tarXYZArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(srcMag, &srcMagArray);CHKERRQ(ierr);
ierr = VecGetArray (sol , &solArray );CHKERRQ(ierr);
for(i=0; i<nTar; ++i) {
/* get target X,Y,Z */
tarX = tarXYZArray[3*i+0];
tarY = tarXYZArray[3*i+1];
tarZ = tarXYZArray[3*i+2];
for(k=0; k<nSrc; ++k) {
/* get source X,Y,Z */
srcX = srcXYZArray[3*k+0];
srcY = srcXYZArray[3*k+1];
srcZ = srcXYZArray[3*k+2];
mag = srcMagArray[k];
dx2 = (tarX-srcX)*(tarX-srcX);
dy2 = (tarY-srcY)*(tarY-srcY);
dz2 = (tarZ-srcZ)*(tarZ-srcZ);
val = mag/(eps1*PetscSqrtReal(dx2 + dy2 + dz2));
solArray[i] += val;
}
}
ierr = VecRestoreArrayRead(srcXYZ, &srcXYZArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(tarXYZ, &tarXYZArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(srcMag, &srcMagArray);CHKERRQ(ierr);
ierr = VecRestoreArray (sol , &solArray );CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "CoulombExactZeroInside"
PetscErrorCode CoulombExactZeroInside(PetscReal a, PetscReal b, PetscReal c, PetscReal eps1, Vec srcXYZ, Vec srcMag, Vec tarXYZ, Vec sol)
{
PetscErrorCode ierr;
PetscReal srcX, srcY, srcZ;
PetscReal tarX, tarY, tarZ;
PetscReal dx2, dy2, dz2;
PetscReal val, mag;
const PetscScalar *srcXYZArray;
const PetscScalar *srcMagArray;
const PetscScalar *tarXYZArray;
PetscScalar *solArray;
PetscInt nSrc, nTar;
PetscInt i, k;
PetscFunctionBeginUser;
ierr = VecGetSize(srcMag, &nSrc);CHKERRQ(ierr);
ierr = VecGetSize(sol, &nTar);CHKERRQ(ierr);
ierr = VecZeroEntries(sol);CHKERRQ(ierr);
ierr = VecGetArrayRead(srcXYZ, &srcXYZArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(tarXYZ, &tarXYZArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(srcMag, &srcMagArray);CHKERRQ(ierr);
ierr = VecGetArray (sol , &solArray );CHKERRQ(ierr);
for(i=0; i<nTar; ++i) {
/* get target X,Y,Z */
tarX = tarXYZArray[3*i+0];
tarY = tarXYZArray[3*i+1];
tarZ = tarXYZArray[3*i+2];
for(k=0; k<nSrc; ++k) {
/* get source X,Y,Z */
srcX = srcXYZArray[3*k+0];
srcY = srcXYZArray[3*k+1];
srcZ = srcXYZArray[3*k+2];
mag = srcMagArray[k];
dx2 = (tarX-srcX)*(tarX-srcX);
dy2 = (tarY-srcY)*(tarY-srcY);
dz2 = (tarZ-srcZ)*(tarZ-srcZ);
val = mag/(eps1*PetscSqrtReal(dx2 + dy2 + dz2));
solArray[i] += val;
}
if((tarX*tarX)/(a*a) + (tarY*tarY)/(b*b) + (tarZ*tarZ)/(c*c) <= 1)
solArray[i] = 0;
}
ierr = VecRestoreArrayRead(srcXYZ, &srcXYZArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(tarXYZ, &tarXYZArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(srcMag, &srcMagArray);CHKERRQ(ierr);
ierr = VecRestoreArray (sol , &solArray );CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "RandomEllipsoidPoints"
PetscErrorCode RandomEllipsoidPoints(PetscReal a, PetscReal b, PetscReal c, Vec xyz)
{
PetscErrorCode ierr;
PetscReal r, theta, phi;
PetscReal x, y, z;
const PetscReal theta_min = 0;
const PetscReal theta_max = 2*PETSC_PI;
const PetscReal phi_min = 0;
const PetscReal phi_max = PETSC_PI;
const PetscReal r_min = 0;
const PetscReal r_max = 1;
PetscScalar *xyzArray;
PetscInt nvals;
PetscFunctionBegin;
/* petsc random object */
PetscRandom rnd1, rnd2;
ierr = PetscRandomCreate(PETSC_COMM_WORLD, &rnd1);CHKERRQ(ierr);
ierr = PetscRandomCreate(PETSC_COMM_WORLD, &rnd2);CHKERRQ(ierr);
ierr = PetscRandomSetInterval(rnd1, .1, 1.0);CHKERRQ(ierr);
ierr = PetscRandomSetInterval(rnd2, .8, .9);CHKERRQ(ierr);
ierr = PetscRandomSetFromOptions(rnd1);CHKERRQ(ierr);
ierr = PetscRandomSetFromOptions(rnd2);CHKERRQ(ierr);
srand(time(NULL));
ierr = PetscRandomSetSeed(rnd1, rand());
ierr = PetscRandomSetSeed(rnd2, rand());
ierr = PetscRandomSeed(rnd1);CHKERRQ(ierr);
ierr = PetscRandomSeed(rnd2);CHKERRQ(ierr);
ierr = VecGetSize(xyz, &nvals);CHKERRQ(ierr);
nvals = nvals/3;
ierr = VecGetArray(xyz, &xyzArray);CHKERRQ(ierr);
for(PetscInt i=0; i<nvals; ++i) {
ierr = PetscRandomGetValue(rnd2, &r);CHKERRQ(ierr);
ierr = PetscRandomGetValue(rnd1, &theta);CHKERRQ(ierr);
ierr = PetscRandomGetValue(rnd1, &phi);CHKERRQ(ierr);
//r = r_min + (r_max-r_min)*i/(nvals-1);
//theta = theta_min + (theta_max-theta_min)*i/(nvals-1);
//phi = phi_min + (phi_max-phi_min)*i/(nvals-1);
r = r_min + (r_max-r_min)*r;
theta = theta_min + (theta_max-theta_min)*theta;
phi = phi_min + (phi_max-phi_min)*phi;
x = a*r*PetscCosReal(theta)*PetscSinReal(phi);
y = b*r*PetscSinReal(theta)*PetscSinReal(phi);
z = c*r*PetscCosReal(phi);
xyzArray[3*i+0] = x;
xyzArray[3*i+1] = y;
xyzArray[3*i+2] = z;
if(nvals==1) {
xyzArray[3*i+0] = .1;
xyzArray[3*i+1] = .2;
xyzArray[3*i+2] = .4;
}
/*if(nvals==2) {
xyzArray[0] = .1;
xyzArray[1] = .2;
xyzArray[2] = .4;
xyzArray[3] = .1;
xyzArray[4] = .2;
xyzArray[5] = .3;
}*/
}
ierr = VecRestoreArray(xyz, &xyzArray);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "RandomMag"
PetscErrorCode RandomMag(Vec mags)
{
PetscErrorCode ierr;
PetscInt nMag, i;
PetscReal val;
PetscRandom rnd;
PetscScalar *magsArray;
PetscFunctionBegin;
ierr = VecGetSize(mags, &nMag);CHKERRQ(ierr);
/* petsc random object */
ierr = PetscRandomCreate(PETSC_COMM_WORLD, &rnd);CHKERRQ(ierr);
ierr = PetscRandomSetInterval(rnd, -1.0, 1.0);CHKERRQ(ierr);
ierr = PetscRandomSetFromOptions(rnd);CHKERRQ(ierr);
ierr = VecGetArray(mags, &magsArray);CHKERRQ(ierr);
for(i=0; i<nMag; ++i) {
ierr = PetscRandomGetValue(rnd, &val);CHKERRQ(ierr);
magsArray[i] = val;
}
ierr = VecRestoreArray(mags, &magsArray);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "SphereLimitExample"
PetscErrorCode SphereLimitExample()
{
PetscErrorCode ierr;
const PetscInt NUM_DELTAS = 14;
const PetscReal DELTAS[14] = {1.3, 1.0, .5, .25, .15, .05, .01, .005, .001, .0005, .0001, .00005, .00001, .000005};
const PetscInt Nmax = 10;
const PetscReal eps1 = 4.0;
const PetscReal eps2 = 80.0;
Vec srcXYZ[NUM_DELTAS], srcMag[NUM_DELTAS], solution[NUM_DELTAS];
PetscScalar *srcXYZArray, *srcMagArray;
PetscReal a, b, c;
PetscReal delta;
PetscReal *freeE;
PetscInt i;
PetscLogEvent events[NUM_DELTAS];
char tText[40] = "Free energy with delta=%8.8f";
char eText[40];
EllipsoidalSystem ells[NUM_DELTAS];
PetscFunctionBegin;
ierr = PetscMalloc1(sizeof(PetscReal)*NUM_DELTAS, &freeE);
for(i=0; i<NUM_DELTAS; ++i) {
/* get size of delta and set a,b,c */
delta = DELTAS[i];
a = 1.0 + delta;
b = 1.0 + (delta/5.0);
c = 1.0 + (delta/10.0);
/* init ellipsoidal system */
ierr = initEllipsoidalSystem(ells+i, a, b, c, 64);CHKERRQ(ierr);
/* initialize xyz and solution vectors */
ierr = VecCreateSeq(PETSC_COMM_SELF, 3, srcXYZ+i);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, 1, srcMag+i);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, 1, solution+i);CHKERRQ(ierr);
ierr = VecZeroEntries(srcXYZ[i]);CHKERRQ(ierr);
ierr = VecGetArray(srcMag[i], &srcMagArray);CHKERRQ(ierr);
srcMagArray[0] = 1.0; // set only charge to have magnitude 1.0
ierr = VecRestoreArray(srcMag[i], &srcMagArray);CHKERRQ(ierr);
/* register events for flop counting */
sprintf(eText, tText, delta);
ierr = PetscLogEventRegister((const char*) eText, 0, events+i);CHKERRQ(ierr);
}
/* solutions */
for(i=0; i<NUM_DELTAS; ++i) {
printf("calculating solution with delta=%8.8f\n", DELTAS[i]);
ierr = PetscLogEventBegin(events[i], 0, 0, 0, 0);CHKERRQ(ierr);
ierr = CalcEllipsoidFreeEnergy(ells+i, eps1, eps2, 1, srcXYZ[i], srcMag[i], 1e-5, Nmax, solution[i], freeE+i);CHKERRQ(ierr);
printf("freeE: %15.15f\n", freeE[i]);
ierr = PetscLogEventEnd(events[i], 0, 0, 0, 0);CHKERRQ(ierr);
}
FILE *fp = fopen("out/sphConv.txt", "w");
fprintf(fp, "delta error");
PetscReal err;
PetscReal exact = 1./eps2 - 1./eps1;
for(i=0; i<NUM_DELTAS; ++i) {
err = PetscAbsReal((exact - freeE[i])/exact);
fprintf(fp, "%4.4e %4.4e\n", DELTAS[i], err);
ierr = VecDestroy(srcXYZ+i);CHKERRQ(ierr);
ierr = VecDestroy(srcMag+i);CHKERRQ(ierr);
ierr = VecDestroy(solution+i);CHKERRQ(ierr);
}
fclose(fp);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "ChargeFlopsExample"
PetscErrorCode ChargeFlopsExample(PetscInt Nmax)
{
PetscErrorCode ierr;
const PetscInt NUM_SOLUTIONS = 10;
const PetscInt CHARGE_START = 100;
const PetscInt CHARGE_INC = 50;
Vec srcXYZ[NUM_SOLUTIONS], srcMag[NUM_SOLUTIONS], solution[NUM_SOLUTIONS];
PetscInt i;
PetscInt chargeNums[NUM_SOLUTIONS];
PetscLogEvent events[NUM_SOLUTIONS];
PetscInt charges;
char tText[30] = "Free energy with %d charges";
char eText[30];
PetscInt tempNum;
EllipsoidalSystem e;
PetscFunctionBegin;
const PetscReal eps1 = 4.0;
const PetscReal eps2 = 4.0;
const PetscReal a = 3.0;
const PetscReal b = 2.0;
const PetscReal c = 1.0;
ierr = initEllipsoidalSystem(&e, a, b, c, 64);CHKERRQ(ierr);
/* create the vector with charge numbers to use */
for(i=0; i < NUM_SOLUTIONS; ++i) {
charges = CHARGE_START + CHARGE_INC*i;
chargeNums[i] = charges;
/* initialize xyz and solution vectors */
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*charges, srcXYZ+i);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, charges, srcMag+i);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, charges, solution+i);CHKERRQ(ierr);
/* generate random points and magnitudes */
ierr = RandomEllipsoidPoints(a, b, c, srcXYZ[i]);CHKERRQ(ierr);
ierr = RandomMag(srcMag[i]);CHKERRQ(ierr);
/* register events for flop counting */
sprintf(eText, tText, charges);
ierr = PetscLogEventRegister((const char*) eText, 0, events+i);CHKERRQ(ierr);
}
PetscReal freeE;
for(i=0; i < NUM_SOLUTIONS; ++i) {
printf("calculating solution %d/%d\n", i+1, NUM_SOLUTIONS);
ierr = PetscLogEventBegin(events[i], 0, 0, 0, 0);CHKERRQ(ierr);
ierr = CalcEllipsoidFreeEnergy(&e, eps1, eps2, chargeNums[i], srcXYZ[i], srcMag[i], 1e-5, Nmax, solution[i], &freeE);CHKERRQ(ierr);
ierr = PetscLogEventEnd(events[i], 0, 0, 0, 0);CHKERRQ(ierr);
}
//ierr = EasyExample(Nmax, nSrc, nx, xl, xr, ny, yl, yr, zConst);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "WorkPrecExample"
PetscErrorCode WorkPrecExample()
{
PetscErrorCode ierr;
const PetscInt NUM_SOLUTIONS = 45;
const PetscInt EXACT_NUM = NUM_SOLUTIONS+10;
const PetscInt NUM_CHARGES = 4;
Vec srcXYZ, srcMag;
Vec potential[NUM_SOLUTIONS];
Vec potExact;
Vec solution;
PetscScalar *solutionArray;
PetscReal exact;
PetscInt i;
PetscLogEvent events[NUM_SOLUTIONS];
const PetscInt Nmin = 0;
const PetscInt Nstep = 1;
PetscInt N;
char tText[30] = "Free energy with Nmax = %d";
char eText[30];
PetscInt tempNum;
EllipsoidalSystem e;
PetscFunctionBegin;
const PetscReal eps1 = 4.0;
const PetscReal eps2 = 80.0;
const PetscReal a = 3.0;
const PetscReal b = 2.0;
const PetscReal c = 1.0;
ierr = initEllipsoidalSystem(&e, a, b, c, 64);CHKERRQ(ierr);
/* create charge vectors and initialize with random values */
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*NUM_CHARGES, &srcXYZ);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_CHARGES, &srcMag);CHKERRQ(ierr);
ierr = RandomEllipsoidPoints(a, b, c, srcXYZ);CHKERRQ(ierr);
printf("######\nXYZ\n#######\n");
ierr = VecView(srcXYZ, PETSC_VIEWER_STDOUT_SELF);CHKERRQ(ierr);
ierr = RandomMag(srcMag);CHKERRQ(ierr);
ierr = VecSet(srcMag, 1.0);CHKERRQ(ierr);
//ierr = VecScale(srcMag, 1./NUM_CHARGES);CHKERRQ(ierr); //scale charge magnitudes so total energy is more normalized
for(i=0; i<NUM_SOLUTIONS; ++i) {
/* register events for flop counting */
N = Nmin + Nstep*i;
sprintf(eText, tText, N);
ierr = PetscLogEventRegister((const char*) eText, 0, events+i);CHKERRQ(ierr);
/* create potential vectors */
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_CHARGES, potential+i);CHKERRQ(ierr);
}
/* create free energy solution vector */
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_SOLUTIONS, &solution);CHKERRQ(ierr);
ierr = VecGetArray(solution, &solutionArray);CHKERRQ(ierr);
/* approximate solutions */
for(i=0; i < NUM_SOLUTIONS; ++i) {
N = Nmin + Nstep*i;
printf("calculating solution %d/%d\n", i+1, NUM_SOLUTIONS);
printf("NNNNN = %d\n", N);
ierr = PetscLogEventBegin(events[i], 0, 0, 0, 0);CHKERRQ(ierr);
ierr = CalcEllipsoidFreeEnergy(&e, eps1, eps2, NUM_CHARGES, srcXYZ, srcMag, 1e-16, N, potential[i], solutionArray+i);CHKERRQ(ierr);
//ierr = VecView(solution, PETSC_VIEWER_STDOUT_SELF);CHKERRQ(ierr);
ierr = VecView(potential[i], PETSC_VIEWER_STDOUT_SELF);CHKERRQ(ierr);
ierr = PetscLogEventEnd(events[i], 0, 0, 0, 0);CHKERRQ(ierr);
}
/* exact(ish) solution */
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_CHARGES, &potExact);CHKERRQ(ierr);
printf("calculating exact solution\n");
ierr = CalcEllipsoidFreeEnergy(&e, eps1, eps2, NUM_CHARGES, srcXYZ, srcMag, 1e-16, EXACT_NUM, potExact, &exact);CHKERRQ(ierr);
FILE *fp = fopen("out/workprec.txt", "w");
fprintf(fp, "work precision\n");
PetscReal errVal;
PetscEventPerfInfo info;
//* calculate error for approximate solutions */
for(PetscInt i=0; i < NUM_SOLUTIONS; ++i) {
errVal = PetscAbsReal((solutionArray[i] - exact)/(exact));
ierr = PetscLogEventGetPerfInfo(PETSC_DETERMINE, events[i], &info);CHKERRQ(ierr);
fprintf(fp, "%4.4e %4.4e\n", info.flops, errVal);
printf("approx: %15.15f\n", solutionArray[i]);
}
printf("exact: %15.15f\n", exact);
fclose(fp);
ierr = VecRestoreArray(solution, &solutionArray);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "InitGrid"
PetscErrorCode InitGrid(PetscInt nx, PetscReal xl, PetscReal xr, PetscInt ny, PetscReal yl, PetscReal yr, PetscReal zConst, Vec *xyz)
{
PetscErrorCode ierr;
PetscInt i, j;
PetscReal xh, yh;
PetscInt index;
PetscScalar *xyzArray;
PetscFunctionBegin;
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*nx*ny, xyz);CHKERRQ(ierr);
xh = (xr - xl)/(nx - 1);
yh = (yr - yl)/(ny - 1);
ierr = VecGetArray(*xyz, &xyzArray);CHKERRQ(ierr);
for(i=0; i < nx; ++i) {
for(j=0; j<ny; ++j) {
index = 3*(i*ny + j);
xyzArray[index+0] = xl + xh*i;
xyzArray[index+1] = yl + yh*j;
xyzArray[index+2] = zConst;
}
}
ierr = VecRestoreArray(*xyz, &xyzArray);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "GridSolution"
/*
Example is of a some charges
*/
PetscErrorCode GridSolution(PetscInt Nmax, PetscInt nSrc, PetscInt nx, PetscReal xl, PetscReal xr, PetscInt ny, PetscReal yl, PetscReal yr, PetscReal zConst, Vec *xvals, Vec *yvals, Vec *sol)
{
PetscErrorCode ierr;
Vec sourceXYZ, sourceMag, tarXYZ, solution;
PetscReal xh, yh;
PetscReal xc, yc;
PetscReal randVal;
PetscInt ind;
PetscFunctionBegin;
const PetscReal eps1 = 4.0;
const PetscReal eps2 = 4.0;
const PetscReal a = 3.0;
const PetscReal b = 2.0;
const PetscReal c = 1.0;
// initialize XYZ and solution vectors
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*nSrc , &sourceXYZ);CHKERRQ(ierr);
//ierr = VecCreateSeq(PETSC_COMM_SELF, 3*nx*ny, &tarXYZ); CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, nx*ny , &solution); CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, nSrc , &sourceMag);CHKERRQ(ierr);
xh = (xr - xl) / (nx - 1);
yh = (yr - yl) / (ny - 1);
ierr = RandomEllipsoidPoints(a, b, c, sourceXYZ);CHKERRQ(ierr);
// populate source vec with points
for(PetscInt k=0; k<nSrc; ++k) {
ind = 3*k;
ierr = VecSetValue(sourceMag, k , 1.0 , INSERT_VALUES);CHKERRQ(ierr);
}
ierr = VecAssemblyBegin(sourceMag);CHKERRQ(ierr); ierr = VecAssemblyEnd(sourceMag);CHKERRQ(ierr);
ierr = InitGrid(nx, xl, xr, ny, yl, yr, zConst, &tarXYZ);
// calculate the solvation potential
ierr = CalcEllipsoidTester( a , b , c,
eps1, eps2,
nSrc, sourceXYZ, sourceMag,
nx*ny, tarXYZ,
Nmax, solution); CHKERRQ(ierr);
/*
FILE *fp = fopen("solvPlot.txt", "w");
fprintf(fp, "xh: %4.4e\n", xh);
fprintf(fp, "yh: %4.4e\n", yh);
const PetscScalar *solutionArray;
ierr = VecGetArrayRead(solution, &solutionArray);CHKERRQ(ierr);
PetscInt index = 0;
for(PetscInt i=0; i<nx; ++i) {
for(PetscInt j=0; j<ny; ++j) {
index = i*ny + j;
fprintf(fp, "%4.4f ", solutionArray[index]);
}
fprintf(fp, "\n");
}
ierr = VecRestoreArrayRead(solution, &solutionArray);CHKERRQ(ierr);
*/
if(xvals != NULL) {
ierr = VecCreateSeq(PETSC_COMM_WORLD, nx, xvals);CHKERRQ(ierr);
for(PetscInt i=0; i<nx; ++i)
ierr = VecSetValue(*xvals, i, xl + i*xh, INSERT_VALUES);CHKERRQ(ierr);
ierr = VecAssemblyBegin(*xvals);CHKERRQ(ierr); ierr = VecAssemblyEnd(*xvals);CHKERRQ(ierr);
}
if(yvals != NULL) {
ierr = VecCreateSeq(PETSC_COMM_WORLD, nx, yvals);CHKERRQ(ierr);
for(PetscInt i=0; i<ny; ++i)
ierr = VecSetValue(*yvals, i, yl + i*yh, INSERT_VALUES);CHKERRQ(ierr);
ierr = VecAssemblyBegin(*yvals);CHKERRQ(ierr); ierr = VecAssemblyEnd(*yvals);CHKERRQ(ierr);
}
if(sol != NULL) {
ierr = VecDuplicate(solution, sol);CHKERRQ(ierr);
ierr = VecCopy(solution, *sol);CHKERRQ(ierr);
}
ierr = VecDestroy(&sourceXYZ);CHKERRQ(ierr);
ierr = VecDestroy(&tarXYZ);CHKERRQ(ierr);
ierr = VecDestroy(&solution);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "SubtractCoulombInside"
PetscErrorCode SubtractCoulombInside(PetscReal a, PetscReal b, PetscReal c, Vec tarXYZ, Vec solution, Vec solutionEx, Vec ncSolution)
{
PetscErrorCode ierr;
const PetscScalar *tarXYZArray, *solutionArray, *solutionExArray;
PetscScalar *ncSolutionArray;
PetscInt nTar;
PetscInt i;
PetscReal x, y, z;
PetscFunctionBegin;
ierr = VecGetSize(solution, &nTar);CHKERRQ(ierr);
ierr = VecGetArrayRead(tarXYZ, &tarXYZArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(solution, &solutionArray);CHKERRQ(ierr);
ierr = VecGetArrayRead(solutionEx, &solutionExArray);CHKERRQ(ierr);
ierr = VecGetArray(ncSolution, &ncSolutionArray);CHKERRQ(ierr);
for(i=0; i<nTar; ++i) {
x = tarXYZArray[3*i+0];
y = tarXYZArray[3*i+1];
z = tarXYZArray[3*i+2];
if( ((x*x)/(a*a)) + ((y*y)/(b*b)) + ((z*z)/(c*c)) <= 1) {
ncSolutionArray[i] = solutionArray[i];
}
else {
ncSolutionArray[i] = solutionArray[i] - solutionExArray[i];
}
}
ierr = VecRestoreArrayRead(tarXYZ, &tarXYZArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(solution, &solutionArray);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(solutionEx, &solutionExArray);CHKERRQ(ierr);
ierr = VecRestoreArray(ncSolution, &ncSolutionArray);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "GridAnimation"
PetscErrorCode GridAnimation()
{
const PetscInt NUM_SOLUTIONS = 8;
PetscErrorCode ierr;
Vec sourceXYZ, sourceMag, tarXYZ;
Vec solution[NUM_SOLUTIONS], solutionEx[NUM_SOLUTIONS], ncSolution[NUM_SOLUTIONS];
Vec errorVec[NUM_SOLUTIONS];
Vec xOut, yOut, zOut;
PetscReal xh, yh;
PetscReal xc, yc;
PetscReal randVal;
PetscInt ind;
PetscFunctionBegin;
PetscReal eps1 = 2.0;
PetscReal eps2 = 20.0;
PetscInt nSrc = 5;
PetscInt nx = 15;
PetscReal xl = -5.13;
PetscReal xr = 5.13;
PetscInt ny = 15;
PetscReal yl = -4.02;
PetscReal yr = 4.02;
PetscReal zConst = .1;
xh = (xr-xl)/ny;
yh = (yr-yl)/ny;
const PetscReal a = 3.0;
const PetscReal b = 2.0;
const PetscReal c = 1.0;
// initialize source XYZ, mag
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*nSrc , &sourceXYZ);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, nSrc , &sourceMag);CHKERRQ(ierr);
// initialize solution vectors
for(PetscInt i=0; i < NUM_SOLUTIONS; ++i) {
ierr = VecCreateSeq(PETSC_COMM_SELF, nx*ny , solution+i); CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, nx*ny , solutionEx+i);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, nx*ny , ncSolution+i);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, nx*ny , errorVec+i);CHKERRQ(ierr);
}
ierr = RandomEllipsoidPoints(a, b, c, sourceXYZ);CHKERRQ(ierr); // on z=0
//ierr = RandomMag(sourceMag); CHKERRQ(ierr);
ierr = VecSet(sourceMag, 1.0);CHKERRQ(ierr);
ierr = InitGrid(nx, xl, xr, ny, yl, yr, zConst, &tarXYZ);CHKERRQ(ierr); //zConst = 0
//Vec tester;
//ierr = VecDuplicate(tarXYZ, &tester);
PetscReal err;
// calculate the solvation potential
for(PetscInt i=0; i < NUM_SOLUTIONS; ++i) {
printf("wow\n");
ierr = CoulombExact(eps1, sourceXYZ, sourceMag, tarXYZ, solutionEx[i]);
//ierr = VecCopy(tarXYZ, tester);
printf("eps: %15.15f\n", eps1);
ierr = CalcEllipsoidTester( a , b , c,
eps1, eps2,
nSrc, sourceXYZ, sourceMag,
nx*ny, tarXYZ,
i, solution[i]); CHKERRQ(ierr);
ierr = SubtractCoulombInside(a, b, c, tarXYZ, solution[i], solutionEx[i], ncSolution[i]);CHKERRQ(ierr);
PetscInt zero = 0;
PetscReal sol0, solEx0;
ierr = VecGetValues(solution[i], 1, &zero, &sol0);CHKERRQ(ierr);
ierr = VecGetValues(solutionEx[i], 1, &zero, &solEx0);CHKERRQ(ierr);
//ierr = VecAXPY(tester, -1.0, tarXYZ);CHKERRQ(ierr);
//ierr = VecView(solutionEx[i], PETSC_VIEWER_STDOUT_SELF);CHKERRQ(ierr);
//ierr = VecView(solution[i], PETSC_VIEWER_STDOUT_SELF);CHKERRQ(ierr);
ierr = VecCopy(solutionEx[i], errorVec[i]);CHKERRQ(ierr);
ierr = VecAXPY(errorVec[i], -1.0, solution[i]);
ierr = VecNorm(errorVec[i], NORM_2, &err);
printf("\n");
printf("the error on %d is %15.15f\n", i, err*xh*yh);
}
/* subtract coulomb from solution inside */
char fname[20] = "out/sol%d.txt";
char fnameEx[20] = "out/solEx%d.txt";
char fnameErr[20] = "out/solErr%d.txt";
char fnameS[20];
char fnameExS[20];
char fnameErrS[20];
for(PetscInt i=0; i < NUM_SOLUTIONS; ++i) {
sprintf(fnameS, fname, i);
sprintf(fnameExS, fnameEx, i);
sprintf(fnameErrS, fnameErr, i);
ierr = WriteToFile((const char*) fnameS, ny, ncSolution[i]);CHKERRQ(ierr);
ierr = WriteToFile((const char*) fnameExS, ny, solutionEx[i]);CHKERRQ(ierr);
ierr = WriteToFile((const char*) fnameErrS, ny, errorVec[i]);CHKERRQ(ierr);
}
ierr = VecCreateSeq(PETSC_COMM_SELF, nx, &xOut);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, ny, &yOut);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, 1, &zOut);CHKERRQ(ierr);
xh = (xr - xl) / (nx - 1);
yh = (yr - yl) / (ny - 1);
for(PetscInt i=0; i<nx; ++i) {
ierr = VecSetValue(xOut, i, xl + xh*i, INSERT_VALUES);CHKERRQ(ierr);
}
for(PetscInt i=0; i<ny; ++i) {
ierr = VecSetValue(yOut, i, yl + yh*i, INSERT_VALUES);CHKERRQ(ierr);
}
ierr = VecSetValue(zOut, 0, zConst, INSERT_VALUES);CHKERRQ(ierr);
ierr = VecAssemblyBegin(xOut);CHKERRQ(ierr); ierr = VecAssemblyEnd(xOut);CHKERRQ(ierr);
ierr = VecAssemblyBegin(yOut);CHKERRQ(ierr); ierr = VecAssemblyEnd(yOut);CHKERRQ(ierr);
ierr = VecAssemblyBegin(zOut);CHKERRQ(ierr); ierr = VecAssemblyEnd(zOut);CHKERRQ(ierr);
ierr = WriteToFile((const char*) "out/xVals.txt", 1, xOut);CHKERRQ(ierr);
ierr = WriteToFile((const char*) "out/yVals.txt", 1, yOut);CHKERRQ(ierr);
ierr = WriteToFile((const char*) "out/zVals.txt", 1, zOut);CHKERRQ(ierr);
/* output source xyz values */
ierr = WriteToFile((const char*) "out/chargeXYZ.txt", 3, sourceXYZ);CHKERRQ(ierr);
ierr = WriteToFile((const char*) "out/chargeMag.txt", 1, sourceMag);CHKERRQ(ierr);
FILE *fp = fopen("out/otherinfo.txt", "w");
fprintf(fp, "%6.6f %6.6f %6.6f\n", a, b, c);
fclose(fp);
ierr = VecDestroy(&sourceXYZ);CHKERRQ(ierr);
ierr = VecDestroy(&tarXYZ);CHKERRQ(ierr);
for(PetscInt i=0; i < NUM_SOLUTIONS; ++i) {
ierr = VecDestroy(solution+i);CHKERRQ(ierr);
ierr = VecDestroy(solutionEx+i);CHKERRQ(ierr);
ierr = VecDestroy(ncSolution+i);CHKERRQ(ierr);
}
ierr = VecDestroy(&sourceMag);CHKERRQ(ierr);
ierr = VecDestroy(&xOut);CHKERRQ(ierr);
ierr = VecDestroy(&yOut);CHKERRQ(ierr);
ierr = VecDestroy(&zOut);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "numChargesPlot"
PetscErrorCode numChargesPlot(PetscInt nMin, PetscInt nMax, PetscInt nStep)
{
PetscErrorCode ierr;
PetscInt Nmax = 4;
//PetscInt nSrc = 20;
PetscInt nx = 7;
PetscReal xl = -4.6;
PetscReal xr = 4.6;
PetscInt ny = 7;
PetscReal yl = -4.6;
PetscReal yr = 4.6;
PetscReal zConst = .1;
PetscInt nSource;
PetscLogStage *chargeStages;
PetscStageLog stageLog;
PetscFunctionBegin;
PetscInt count = 0;
for(nSource = nMin; nSource <= nMax; nSource += nStep) {
count++;
}
ierr = PetscMalloc1(sizeof(PetscLogStage)*count, &chargeStages);
char bStr[40] = "Num Charges: %d";
char indvStr[40];
count = 0;
for(nSource = nMin; nSource <= nMax; nSource += nStep) {
sprintf(indvStr, bStr, nSource);
ierr = PetscLogStageRegister(indvStr, chargeStages+count);CHKERRQ(ierr);
count++;
}
count = 0;
for(nSource = nMin; nSource <= nMax; nSource += nStep) {
printf("wow\n");
ierr = PetscLogStagePush(chargeStages[count]);CHKERRQ(ierr);
ierr = GridSolution(Nmax, nSource, nx, xl, xr, ny, yl, yr, zConst, NULL, NULL, NULL);CHKERRQ(ierr);
ierr = PetscLogStagePop();CHKERRQ(ierr);
count++;
}
ierr = PetscLogGetStageLog(&stageLog);CHKERRQ(ierr);
count = 0;
for(nSource = nMin; nSource <= nMax; nSource += nStep) {
ierr = PetscPrintf(PETSC_COMM_WORLD, "n = %d\nflops = %4.4e\n", nSource, stageLog->stageInfo[chargeStages[count]].perfInfo.flops);CHKERRQ(ierr);
count++;
}
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "WriteToFile"
PetscErrorCode WriteToFile(const char *fname, PetscInt rowsize, Vec values)
{
PetscErrorCode ierr;
PetscInt k;
PetscInt nPts;
const PetscScalar *valuesArray;
PetscFunctionBegin;
ierr = VecGetSize(values, &nPts);CHKERRQ(ierr);
ierr = VecGetArrayRead(values, &valuesArray);CHKERRQ(ierr);
FILE *fp = fopen(fname, "w");
for(k=0; k < nPts; ++k) {
fprintf(fp, "%4.4f ", valuesArray[k]);
if((k+1)%rowsize == 0)
fprintf(fp, "\n");
}
fclose(fp);
ierr = VecRestoreArrayRead(values, &valuesArray);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "SolutionAnimation"
PetscErrorCode SolutionAnimation()
{
PetscErrorCode ierr;
Vec x1, y1, s0, s1, s2, s3;
PetscFunctionBegin;
PetscInt nSrc = 10;
PetscInt nx = 15;
PetscReal xl = -4.6;
PetscReal xr = 4.6;
PetscInt ny = 15;
PetscReal yl = -4.6;
PetscReal yr = 4.6;
PetscReal zConst = .1;
ierr = GridSolution(0, nSrc, nx, xl, xr, ny, yl, yr, zConst, &x1, &y1, &s0);CHKERRQ(ierr);
ierr = WriteToFile((const char*) "out/sol0.txt", ny, s0);CHKERRQ(ierr);
ierr = GridSolution(1, nSrc, nx, xl, xr, ny, yl, yr, zConst, &x1, &y1, &s1);CHKERRQ(ierr);
ierr = WriteToFile((const char*) "out/sol1.txt", ny, s1);CHKERRQ(ierr);
ierr = GridSolution(2, nSrc, nx, xl, xr, ny, yl, yr, zConst, &x1, &y1, &s2);CHKERRQ(ierr);
ierr = WriteToFile((const char*) "out/sol2.txt", ny, s2);CHKERRQ(ierr);
ierr = GridSolution(3, nSrc, nx, xl, xr, ny, yl, yr, zConst, &x1, &y1, &s3);CHKERRQ(ierr);
ierr = WriteToFile((const char*) "out/sol3.txt", ny, s3);CHKERRQ(ierr);
ierr = WriteToFile((const char*) "out/xVals.txt", 1, x1);CHKERRQ(ierr);
ierr = WriteToFile((const char*) "out/yVals.txt", 1, y1);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "testLame"
PetscErrorCode testLame()
{
PetscErrorCode ierr;
PetscInt n, p;
PetscInt Nmax;
PetscReal Fnp;
PetscReal Enp;
PetscReal a, b, c;
PetscReal cval;
PetscInt signm, signn;
EllipsoidalSystem e;
PetscFunctionBegin;
cval = .3;
signm = -1;
signn = 1;
a = 3.0; b = 2.0; c = 1.0;
initEllipsoidalSystem(&e, a, b, c, 64);
FILE *fp = fopen("newellout.txt", "w");
Nmax = 6;
for(n=0; n < Nmax; ++n) {
for(p=0; p < 2*n+1; ++p) {
ierr = calcLame(&e, n, p, cval, signm, signn, &Enp);CHKERRQ(ierr);
fprintf(fp, "%d %d %15.15f\n", n, p, Enp);
}
}
fclose(fp);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "main"
PetscErrorCode main( int argc, char **argv )
{
PetscErrorCode ierr;
PetscFunctionBeginUser;
//initialize Petsc
ierr = PetscInitialize(&argc, &argv, NULL, NULL); CHKERRQ(ierr);
ierr = PetscLogDefaultBegin(); CHKERRQ(ierr);
//ierr = EllVsSphConvergence();CHKERRQ(ierr);
//testSphericalCoordinates();
//runTest1();
//testLegendre();
//runTest4();
//test4sphere();
//RunArg();
//ierr = RunArgTester(); CHKERRQ(ierr);
//PetscErrorCode GridSolution(PetscInt Nmax, PetscInt nSrc, PetscInt nx, PetscReal xl, PetscReal xr, PetscInt ny, PetscReal yl, PetscReal yr, PetscReal zConst)
/*
PetscInt Nmax = 4;
PetscInt nSrc = 25;
PetscInt nx = 15;
PetscReal xl = -5.23;
PetscReal xr = 5.23;
PetscInt ny = 15;
PetscReal yl = -4.45;
PetscReal yr = 4.45;
PetscReal zConst = .1;
PetscReal eps1 = 4.0;
PetscReal eps2 = 80.0;
*/
//ierr = GridSolution(Nmax, nSrc, nx, xl, xr, ny, yl, yr, zConst, NULL, NULL);CHKERRQ(ierr);
//ierr = SolutionAnimation(); //<---- total crap
//runTest1();
//testLame();
// ierr = runTest1();CHKERRQ(ierr);
//ierr = RunArg();
//ierr = GridAnimation();CHKERRQ(ierr);
//ierr = ChargeFlopsExample(10);CHKERRQ(ierr);
ierr = WorkPrecExample();CHKERRQ(ierr);
//ierr = SphereLimitExample();CHKERRQ(ierr);
//ierr = numChargesPlot(100, 500, 100);
ierr = PetscFinalize();CHKERRQ(ierr);
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.6603802252,
"avg_line_length": 32.6631513648,
"ext": "c",
"hexsha": "8d6409be8e14edfd955f29390e07f6ab11513adc",
"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": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "tom-klotz/ellipsoid-solvation",
"max_forks_repo_path": "src/testProblem.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"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": "tom-klotz/ellipsoid-solvation",
"max_issues_repo_path": "src/testProblem.c",
"max_line_length": 191,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "tom-klotz/ellipsoid-solvation",
"max_stars_repo_path": "src/testProblem.c",
"max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z",
"num_tokens": 17522,
"size": 52653
} |
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Andreas Bertsch $
// $Authors: $
// --------------------------------------------------------------------------
//
#ifndef OPENMS_MATH_STATISTICS_GAMMADISTRIBUTIONFITTER_H
#define OPENMS_MATH_STATISTICS_GAMMADISTRIBUTIONFITTER_H
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/DPosition.h>
#include <vector>
// gsl includes
#include <gsl/gsl_rng.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multifit_nlin.h>
namespace OpenMS
{
namespace Math
{
/**
@brief Implements a fitter for the Gamma distribution.
This class fits a Gamma distribution to a number of data points.
The results as well as the initial guess are specified using the struct
GammaDistributionFitResult.
The formula with the fitted parameters can be transformed into a
gnuplot formula using getGnuplotFormula() after fitting.
The implementation is done using GSL fitting algorithms.
@ingroup Math
*/
class OPENMS_DLLAPI GammaDistributionFitter
{
public:
/// struct to represent the parameters of a gamma distribution
struct GammaDistributionFitResult
{
public:
GammaDistributionFitResult() :
b(1.0),
p(5.0)
{
}
GammaDistributionFitResult(const GammaDistributionFitResult & rhs) :
b(rhs.b),
p(rhs.p)
{
}
GammaDistributionFitResult & operator=(const GammaDistributionFitResult & rhs)
{
if (this != &rhs)
{
b = rhs.b;
p = rhs.p;
}
return *this;
}
/// parameter b of the gamma distribution
double b;
/// parameter p of the gamma distribution
double p;
};
/// Default constructor
GammaDistributionFitter();
/// Destructor
virtual ~GammaDistributionFitter();
/// sets the gamma distribution start parameters b and p for the fitting
void setInitialParameters(const GammaDistributionFitResult & result);
/**
@brief Fits a gamma distribution to the given data points
@param points Input parameter which represents the point used for the fitting
@exception Exception::UnableToFit is thrown if fitting cannot be performed
*/
GammaDistributionFitResult fit(std::vector<DPosition<2> > & points);
/// returns the gnuplot formula of the fitted gamma distribution
const String & getGnuplotFormula() const;
protected:
static int gammaDistributionFitterf_(const gsl_vector * x, void * params, gsl_vector * f);
static int gammaDistributionFitterdf_(const gsl_vector * x, void * params, gsl_matrix * J);
static int gammaDistributionFitterfdf_(const gsl_vector * x, void * params, gsl_vector * f, gsl_matrix * J);
void printState_(size_t iter, gsl_multifit_fdfsolver * s);
GammaDistributionFitResult init_param_;
String gnuplot_formula_;
private:
/// Copy constructor (not implemented)
GammaDistributionFitter(const GammaDistributionFitter & rhs);
/// assignment operator (not implemented)
GammaDistributionFitter & operator=(const GammaDistributionFitter & rhs);
};
}
}
#endif
| {
"alphanum_fraction": 0.6473163304,
"avg_line_length": 35.2617449664,
"ext": "h",
"hexsha": "3735ac8d1ebcfc79caba3ad0fa5450ac61b5fcf2",
"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": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_forks_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_forks_repo_name": "kreinert/OpenMS",
"max_forks_repo_path": "src/openms/include/OpenMS/MATH/STATISTICS/GammaDistributionFitter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_issues_repo_name": "kreinert/OpenMS",
"max_issues_repo_path": "src/openms/include/OpenMS/MATH/STATISTICS/GammaDistributionFitter.h",
"max_line_length": 114,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3",
"max_stars_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_stars_repo_name": "open-ms/all-svn-branches",
"max_stars_repo_path": "include/OpenMS/MATH/STATISTICS/GammaDistributionFitter.h",
"max_stars_repo_stars_event_max_datetime": "2018-05-23T03:43:10.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-05-23T03:43:10.000Z",
"num_tokens": 1049,
"size": 5254
} |
#pragma once
#include "utility/types.h"
#include <gsl/gsl>
#include <array>
namespace cws80 {
extern std::array<gsl::span<const u8>, 11> extra_bank_data;
} // namespace cws80
| {
"alphanum_fraction": 0.7150837989,
"avg_line_length": 16.2727272727,
"ext": "h",
"hexsha": "670e17db220dc4c839ad8e643e9ffc6f2bcd0ae3",
"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/cws/cws80_data_banks.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/cws/cws80_data_banks.h",
"max_line_length": 59,
"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/cws/cws80_data_banks.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": 52,
"size": 179
} |
/* Simple Travelling Salesman Problem heuristics.
*
* Krzysztof Chalupka, 2017.
*/
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_vector_double.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
#include "../utils/utils.h"
#include "../datastructures/datastructures.h"
int *tsp_bs(gsl_vector **, int); /* brute-force search */
int *tsp_nn(gsl_vector **, int); /* nearest-neighbor */
int *tsp_cp(gsl_vector **, int); /* closest-pair */
double pathlen(gsl_vector **, int *, int); /* path length of a permutation. */
double pathlen(gsl_vector **data, int *path, int n){
/* Compute the length of the path defined by the vectors
* in `data`, traversed in order given in `path`,
* and closing the loop by traversing path[n-1] -- path[0]
* at the end.
*/
int i;
double total = 0.;
for (i = 0; i < n-1; i++)
total += vector_dist(data[path[i]], data[path[i+1]]);
if (n > 0)
total += vector_dist(data[path[n-1]], data[path[0]]);
return total;
}
int *tsp_nn(gsl_vector **data, int n)
{
/* Solve the TSP using the nearest-neighbor heuristic. */
if (n == 0)
return NULL;
int i, j, best_id;
int usedup = 0; /* Flag already-used elements. */
gsl_vector *current = data[0];
double cur_dist;
double best_dist;
int *nn_path = (int *) calloc(n, sizeof(int));
nn_path[0] = 0;
usedup |= 1;
for (i = 1; i < n; i++){
best_dist = 0;
for (j = 1; j < n; j++){
if (!(usedup & (2 << (j-1)))){
cur_dist = vector_dist(current, data[j]);
if (cur_dist < best_dist || best_dist == 0){
best_dist = cur_dist;
best_id = j;
}
}
}
current = data[best_id];
nn_path[i] = best_id;
usedup |= (2 << (best_id-1));
}
return nn_path;
}
int *tsp_cp(gsl_vector **data, int n)
{
/* Solve the TSP using the closest pair heuristic. */
int i, j, ch1_id, ch2_id, best_ch1, best_ch2;
int match_flag;
double dist, best_dist;
dlist_node *node;
int *best_path = (int *) calloc(n, sizeof(int));
/* Create an array where each element corresponds to a chain. */
dlist **chains = (dlist **) calloc(n, sizeof(dlist *));
for (i = 0; i < n; i++){
chains[i] = dlist_new(data[i]);
}
/* Merge the chains according to the heuristic. */
for (i = 0; i < n-1; i++){
/* Find the smallest-distance chain ends pair. */
best_dist = 0.;
for (ch1_id = 0; ch1_id < n; ch1_id++){
if (chains[ch1_id] == NULL){
continue;
}
for (ch2_id = 0; ch2_id < n; ch2_id++){
if (chains[ch2_id] == NULL || ch1_id == ch2_id){
continue;
}
dist = vector_dist(chains[ch1_id]->head->item,
chains[ch2_id]->head->item);
if (dist < best_dist || best_dist == 0){
/* Heads match. */
best_dist = dist;
best_ch1 = ch1_id;
best_ch2 = ch2_id;
match_flag = 0;
}
dist = vector_dist(chains[ch1_id]->head->item,
chains[ch2_id]->tail->item);
if (dist < best_dist || best_dist == 0){
/* Head1 matches tail2. */
best_dist = dist;
best_ch1 = ch1_id;
best_ch2 = ch2_id;
match_flag = 1;
}
dist = vector_dist(chains[ch1_id]->tail->item,
chains[ch2_id]->head->item);
if (dist < best_dist || best_dist == 0){
/* Tail1 matches head2. */
best_dist = dist;
best_ch1 = ch1_id;
best_ch2 = ch2_id;
match_flag = 2;
}
dist = vector_dist(chains[ch1_id]->tail->item,
chains[ch2_id]->head->item);
if (dist < best_dist || best_dist == 0){
/* Tail1 matches tail2. */
best_dist = dist;
best_ch1 = ch1_id;
best_ch2 = ch2_id;
match_flag = 3;
}
}
}
printf("Iter %d, best match (%d, %d) %f\n",
i, best_ch1, best_ch2, best_dist);
/* Merge the smallest-distance chain ends. */
if (match_flag == 0){
/* Heads match: push ch2 to the front of ch1 in reverse-order. */
while(chains[best_ch2]->head){
dlist_insert(chains[best_ch1],
chains[best_ch2]->head->item);
dlist_delete(chains[best_ch2], chains[best_ch2]->head);
}
}
else if (match_flag == 1){
/* Head1 to tail2 match: push ch2 to the front of ch1 in-order. */
while(chains[best_ch2]->tail){
dlist_insert(chains[best_ch1],
chains[best_ch2]->tail->item);
dlist_delete(chains[best_ch2], chains[best_ch2]->tail);
}
}
else if (match_flag == 2){
/* Head2 to tail1 match: push ch2 to the end of ch1 in-order. */
while(chains[best_ch2]->head){
dlist_insert_tail(chains[best_ch1],
chains[best_ch2]->head->item);
dlist_delete(chains[best_ch2], chains[best_ch2]->head);
}
}
else if (match_flag == 3){
/* Tails match: push ch2 to the end of ch1 in reverse-order. */
while(chains[best_ch2]->tail){
dlist_insert_tail(chains[best_ch1],
chains[best_ch2]->tail->item);
dlist_delete(chains[best_ch2], chains[best_ch2]->tail);
}
}
chains[best_ch2] = NULL;
}
/* All the chains except for one should be null. The non-null
chain contains the best (heuristic) path. */
for (i = 0; i < n; i++)
if (chains[i])
node = chains[i]->head;
for(i = 0; node; i++){
for (j = 0; j < n; j++)
if (data[j] == node->item)
best_path[i] = j;
node = node->next;
}
return best_path;
}
int *tsp_bs(gsl_vector **data, int n)
{
/* Find the shortest loop between `n` points. stored in `data`. */
if (n == 0)
return NULL;
double best_dist = 0;
double cur_dist = 0;
int i_perm, i_iter;
int *cur_path;
int *best_path = calloc(n, sizeof(int));
int **perm = permutations(n);
for (i_iter = 0; i_iter < factorial(n); i_iter++){
/* Retrieve the permutation into an array. */
cur_path = perm[i_iter];
/* Compute the path length corresponding to this permutation. */
printf("Iter %d, permutation ", i_iter);
print_intarray(cur_path, n);
cur_dist = pathlen(data, cur_path, n);
printf(" dist %.10f.\n", cur_dist);
/* Save best pathlen to-date. */
if (best_dist > cur_dist || best_dist == 0){
best_dist = cur_dist;
for (i_perm = 0; i_perm < n; i_perm++)
best_path[i_perm] = cur_path[i_perm];
}
}
printf("\n");
free(cur_path);
free(perm);
return best_path;
}
int main(){
char *fname;
int npoints;
int *bestpath;
gsl_vector **vecs;
/* Load data into a vector array. */
fname = "tsp.dat";
npoints = get_nlines(fname);
vecs = load_vectors_from_file("tsp.dat", npoints);
/* Compute the best path using the brute-force method. */
bestpath = tsp_bs(vecs, npoints);
printf("Best path (brute-force) len = %f, for path ",
pathlen(vecs, bestpath, npoints));
print_intarray(bestpath, npoints);
printf("\n");
/* Compute the best path using the nearest-neighbor heuristic. */
bestpath = tsp_nn(vecs, npoints);
printf("Best path (nearest-neighbor) len = %f, for path ",
pathlen(vecs, bestpath, npoints));
print_intarray(bestpath, npoints);
printf("\n");
/* Compute the best path using the closest-pairs heuristic. */
bestpath = tsp_cp(vecs, npoints);
printf("Best path (closest-pair) len = %f, for path ",
pathlen(vecs, bestpath, npoints));
print_intarray(bestpath, npoints);
printf("\n");
return 0;
}
| {
"alphanum_fraction": 0.6146891084,
"avg_line_length": 27.2310606061,
"ext": "c",
"hexsha": "0c1b4638feb1dfde5d7b05b79eff1d1950ebcc23",
"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": "99176322b83d120f0ceb83dbba254a6e15f95264",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kjchalup/algorithm_design",
"max_forks_repo_path": "skiena/chap1/ex1_26.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264",
"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": "kjchalup/algorithm_design",
"max_issues_repo_path": "skiena/chap1/ex1_26.c",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "99176322b83d120f0ceb83dbba254a6e15f95264",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kjchalup/algorithm_design",
"max_stars_repo_path": "skiena/chap1/ex1_26.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2224,
"size": 7189
} |
#include "lah.h"
#ifdef HAVE_LAPACK /* Use a LAPACK package to do the heavy work */
#include <cblas.h>
lah_Return lah_matMul(lah_MatOp transA, lah_MatOp transB,
lah_value alpha, lah_value beta,
lah_mat *C, lah_mat const *A, lah_mat const *B)
{
CBLAS_TRANSPOSE transA_cblas = CblasNoTrans;
CBLAS_TRANSPOSE transB_cblas = CblasNoTrans;
if (C == NULL || A == NULL || B == NULL )
return lahReturnParameterError;
/*
order = LAH_CBLAS_LAYOUT(C);
if (order == CblasColMajor)
{
lda = A->nR;
ldb = B->nR;
ldc = C->nR;
}
else
{
lda = A->nC;
ldb = B->nC;
ldc = C->nC;
}
*/
if (transA != lahNorm)
transA_cblas = CblasTrans;
if (transB != lahNorm)
transB_cblas = CblasTrans;
GEMM(LAH_CBLAS_LAYOUT, transA_cblas, transB_cblas, C->nR, C->nC, A->nC, beta,
A->data, LAH_LEADING_DIM(A), B->data, LAH_LEADING_DIM(B), alpha, C->data, LAH_LEADING_DIM(C));
return lahReturnOk;
}
#else /* fallback to primitive linear algebra subroutines */
#include <stdlib.h>
/* Computes the general Matrix mulitplikation of form:
* C = alpha*C + beta*op(A)*op(B)
* similar to the BLAS routine ?gemm.
* op(A) = A for transA=lahNorm or op(A) = At for transA = lahTrans */
lah_Return lah_matMul(lah_MatOp transA, lah_MatOp transB,
lah_value alpha, lah_value beta,
lah_mat *C, const lah_mat *A, const lah_mat *B)
{
lah_index c, r, i;
lah_value *res, *value1, *value2;
lah_value temp;
if (C == NULL || A == NULL || B == NULL)
{
return lahReturnParameterError;
}
/* NOTE: lah_matMul calls itself with an transposed view of
* the corresponding kop_mat and sets transA resp. transB
* to lahNorm (else we would have an endless recursion)
*/
if (transA == lahTrans)
{
/* Call lah_matMul again with transposed */
lah_mat *At = lah_matTrans(A);
lah_Return result = lah_matMul(lahNorm, transB, alpha,
beta, C, At, B);
free(At);
return result;
}
if (transB == lahTrans)
{
/* Call lah_matMul again with transposed of B */
lah_mat *Bt = lah_matTrans(B);
lah_Return result = lah_matMul(transA, lahNorm, alpha,
beta, C, A, Bt);
free(Bt);
return result;
}
if (C->nR != A->nR || C->nC != B->nC || A->nC != B->nR)
{
return lahReturnParameterError;
}
for (c = 0; c < C->nC; c++)
{
for (r = 0; r < C->nR; r++)
{
res = C->data + C->incRow * r + c * C->incCol;
value1 = A->data + r * A->incRow;
value2 = B->data + c * B->incCol;
temp = 0;
for (i = 0; i < A->nC; i++, value1 += A->incCol, value2 += B->incRow)
{
temp += *value1 * *value2;
}
*res = alpha * *res + beta * temp;
}
}
return lahReturnOk;
}
#endif /* endif primitive implementation */
| {
"alphanum_fraction": 0.525625,
"avg_line_length": 29.0909090909,
"ext": "c",
"hexsha": "8b557c819577de15b32342c39f13397450769f62",
"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": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "maj0e/linear-algebra-helpers",
"max_forks_repo_path": "Source/lah_matMul.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa",
"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": "maj0e/linear-algebra-helpers",
"max_issues_repo_path": "Source/lah_matMul.c",
"max_line_length": 103,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bdac65b0714d69eb03ae73b2b09a2a84ebb5f3aa",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "maj0e/linear-algebra-helpers",
"max_stars_repo_path": "Source/lah_matMul.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 936,
"size": 3200
} |
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mpfr.h>
#include <petsc.h>
#include "../ellipsoid/ellipsoid.h"
#include "../ellipsoid/ellSolv.h"
#include "../sphere/sphere.h"
#include "../sphere/sphSolv.h"
#include "../constants.h"
#include "testFunctions.h"
//compares ellipsoidal and spherical
//has ellipsoidal distribution of charges just inside ellipsoidal boundary
//computes the solution at two point, one inside smallest enclosing sphere where spherical diverges
//other solution point is outside of sphere and ellipse to compare convergence
#undef __FUNCT__
#define __FUNCT__ "main"
PetscErrorCode main(int argc, char **argv)
{
PetscErrorCode ierr;
//semi-axes of ellipsoid
PetscReal a = 3.0;
PetscReal b = 2.5;
PetscReal c = 1.2;
//sphere radius
PetscReal sphRad = 3;
//dielecric permitivities both set to 1
const PetscReal eps1 = 1.0;
const PetscReal eps2 = 1.0;
//charges placed on ellipsoid with sem-axes smaller by epsilon
PetscReal epsilon = .5;
//interior charge XYZ and magnitude
const PetscInt SQRT_NUM_CHARGES = 3;
Vec chargeXYZ;
Vec chargeMag;
//maximum expansion order for test
const PetscInt MAX_N = 25;
//solutions vector
const PetscInt NUM_SOL_PTS = 2;
Vec ellSolutions[MAX_N], sphSolutions[MAX_N];
Vec ellError[MAX_N], sphError[MAX_N];
Vec exactSolution;
Vec solXYZ;
//solution point inside of sphere
PetscReal sol1X = .1;
PetscReal sol1Y = .1;
PetscReal sol1Z = 1.5;
//solution point outside of sphere
PetscReal sol2X = 2.1;
PetscReal sol2Y = 2.6;
PetscReal sol2Z = 1;
//pointer for accessing petsc vectors
PetscScalar *vecPt, *vecPt2;
PetscFunctionBeginUser;
//initialize petsc
ierr = PetscInitialize(&argc, &argv, NULL, NULL);CHKERRQ(ierr);
ierr = PetscLogDefaultBegin();CHKERRQ(ierr);
//create, set charge magnitudes to 1
ierr = VecCreateSeq(PETSC_COMM_SELF, SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, &chargeMag);CHKERRQ(ierr);
ierr = VecSet(chargeMag, 1.0);CHKERRQ(ierr);
//create, set charge XYZ values to be on a-eps,b-eps,c-eps ellipsoid
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, &chargeXYZ);CHKERRQ(ierr);
ierr = VecGetArray(chargeXYZ, &vecPt);CHKERRQ(ierr);
PetscReal pu, pv;
for(PetscInt i=0; i<SQRT_NUM_CHARGES; ++i) {
for(PetscInt j=0; j<SQRT_NUM_CHARGES; ++j) {
pu = i*2.0*PETSC_PI/(SQRT_NUM_CHARGES-1);
pv = j*PETSC_PI/(SQRT_NUM_CHARGES-1);
PetscInt ind = i*SQRT_NUM_CHARGES + j;
//there is a slight issue with on-axes coordinate transforms which is what the +.01 is for
vecPt[3*ind + 0] = (a-epsilon)*PetscCosReal(pu)*PetscSinReal(pv) +.01;
vecPt[3*ind + 1] = (b-epsilon)*PetscSinReal(pu)*PetscSinReal(pv) + .01;
vecPt[3*ind + 2] = (c-epsilon)*PetscCosReal(pv) + .01;
printf("pu: %3.3f pv: %3.3f\n", pu, pv);
}
}
ierr = VecRestoreArray(chargeXYZ, &vecPt);CHKERRQ(ierr);
//set solution points vector
ierr = VecCreateSeq(PETSC_COMM_SELF, 3*NUM_SOL_PTS, &solXYZ);CHKERRQ(ierr);
ierr = VecGetArray(solXYZ, &vecPt);CHKERRQ(ierr);
vecPt[0] = sol1X; vecPt[1] = sol1Y; vecPt[2] = sol1Z;
vecPt[3] = sol2X; vecPt[4] = sol2Y; vecPt[5] = sol2Z;
ierr = VecRestoreArray(solXYZ, &vecPt);CHKERRQ(ierr);
//caulculate exact solution
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_SOL_PTS, &exactSolution);CHKERRQ(ierr);
ierr = CoulombExact(eps1, chargeXYZ, chargeMag, solXYZ, exactSolution);CHKERRQ(ierr);
//initialize solutions and error vectors
for(PetscInt k=0; k<MAX_N; ++k) {
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_SOL_PTS, ellSolutions+k);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_SOL_PTS, sphSolutions+k);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_SOL_PTS, ellError+k);CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, NUM_SOL_PTS, sphError+k);CHKERRQ(ierr);
}
//compute solutions for expansions up to order MAX_N
for(PetscInt k=1; k<=MAX_N; ++k) {
printf("N = %d\n", k);
printf("calculating ellipsoidal solution...\n");
ierr = CalcEllipsoidCoulombPotential(a, b, c, eps1, eps2, SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, chargeXYZ, chargeMag, NUM_SOL_PTS, solXYZ, k, ellSolutions[k-1]);CHKERRQ(ierr);
printf("calculating spherical solution...\n");
ierr = CalcSphericalCoulombPotential(1.0, eps1, eps2, SQRT_NUM_CHARGES*SQRT_NUM_CHARGES, chargeXYZ, chargeMag, NUM_SOL_PTS, solXYZ, k, sphSolutions[k-1]);CHKERRQ(ierr);
}
//compute errors
printf("Computing errors...\n");
for(PetscInt k=0; k<MAX_N; ++k) {
ierr = VecCopy(exactSolution, ellError[k]);CHKERRQ(ierr);
ierr = VecCopy(exactSolution, sphError[k]);CHKERRQ(ierr);
ierr = VecAXPY(ellError[k], -1.0, ellSolutions[k]);CHKERRQ(ierr);
ierr = VecAXPY(sphError[k], -1.0, sphSolutions[k]);CHKERRQ(ierr);
ierr = VecAbs(ellError[k]);CHKERRQ(ierr);
ierr = VecAbs(sphError[k]);CHKERRQ(ierr);
}
FILE *fp = fopen("out/ex1.txt", "w");
for(PetscInt k=0; k<MAX_N; ++k) {
ierr = VecGetArrayRead(ellError[k], &vecPt);
ierr = VecGetArrayRead(sphError[k], &vecPt2);
printf("Error[%d] = %4.4e\n", k, vecPt[0]);
fprintf(fp, "%4.4e %4.4e %4.4e %4.4e\n", vecPt[0], vecPt2[0], vecPt[1], vecPt2[1]);
ierr = VecRestoreArrayRead(ellError[k], &vecPt);
ierr = VecRestoreArrayRead(sphError[k], &vecPt2);
}
printf("Exact: \n");
ierr = VecView(exactSolution, PETSC_VIEWER_STDOUT_SELF);
printf("Ell: \n");
ierr = VecView(ellSolutions[MAX_N-1], PETSC_VIEWER_STDOUT_SELF);
ierr = PetscFinalize();CHKERRQ(ierr);
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.7015059161,
"avg_line_length": 38.7361111111,
"ext": "c",
"hexsha": "c3918264637cb45ef1a34739e786e5d7727a5e9c",
"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": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "tom-klotz/ellipsoid-solvation",
"max_forks_repo_path": "src/examples/ex1.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"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": "tom-klotz/ellipsoid-solvation",
"max_issues_repo_path": "src/examples/ex1.c",
"max_line_length": 176,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2bcaab45a9096ae078711b4f4e1495c2bead16a0",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "tom-klotz/ellipsoid-solvation",
"max_stars_repo_path": "src/examples/ex1.c",
"max_stars_repo_stars_event_max_datetime": "2016-11-05T20:15:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-11-05T20:15:01.000Z",
"num_tokens": 1829,
"size": 5578
} |
/**
*
* @file core_dormqr.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 Hatem Ltaief
* @author Mathieu Faverge
* @author Jakub Kurzak
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:46 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_double
*
* CORE_dormqr overwrites the general complex M-by-N tile C with
*
* SIDE = 'L' SIDE = 'R'
* TRANS = 'N': Q * C C * Q
* TRANS = 'C': Q**T * C C * Q**T
*
* where Q is a complex unitary matrix defined as the product of k
* elementary reflectors
*
* Q = H(1) H(2) . . . H(k)
*
* as returned by CORE_dgeqrt. Q is of order M if SIDE = 'L' and of order N
* if SIDE = 'R'.
*
*******************************************************************************
*
* @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 : Transpose, apply Q**T.
*
* @param[in] M
* The number of rows of the tile C. M >= 0.
*
* @param[in] N
* The number of columns of the tile C. N >= 0.
*
* @param[in] K
* The number of elementary reflectors whose product defines
* the matrix Q.
* If SIDE = PlasmaLeft, M >= K >= 0;
* if SIDE = PlasmaRight, N >= K >= 0.
*
* @param[in] IB
* The inner-blocking size. IB >= 0.
*
* @param[in] A
* Dimension: (LDA,K)
* The i-th column must contain the vector which defines the
* elementary reflector H(i), for i = 1,2,...,k, as returned by
* CORE_dgeqrt in the first k columns of its array argument A.
*
* @param[in] LDA
* The leading dimension of the array A.
* If SIDE = PlasmaLeft, LDA >= max(1,M);
* if SIDE = PlasmaRight, LDA >= max(1,N).
*
* @param[in] T
* The IB-by-K triangular factor T 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 >= IB.
*
* @param[in,out] C
* On entry, the M-by-N tile C.
* On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q.
*
* @param[in] LDC
* The leading dimension of the array C. LDC >= max(1,M).
*
* @param[in,out] WORK
* On exit, if INFO = 0, WORK(1) returns the optimal LDWORK.
*
* @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_dormqr = PCORE_dormqr
#define CORE_dormqr PCORE_dormqr
#endif
int CORE_dormqr(PLASMA_enum side, PLASMA_enum trans,
int M, int N, int K, int IB,
const double *A, int LDA,
const double *T, int LDT,
double *C, int LDC,
double *WORK, int LDWORK)
{
int i, kb;
int i1, i3;
int nq, nw;
int ic = 0;
int jc = 0;
int ni = N;
int mi = M;
/* Check input arguments */
if ((side != PlasmaLeft) && (side != PlasmaRight)) {
coreblas_error(1, "Illegal value of side");
return -1;
}
/*
* NQ is the order of Q and NW is the minimum dimension of WORK
*/
if (side == PlasmaLeft) {
nq = M;
nw = N;
}
else {
nq = N;
nw = M;
}
if ((trans != PlasmaNoTrans) && (trans != PlasmaTrans)) {
coreblas_error(2, "Illegal value of trans");
return -2;
}
if (M < 0) {
coreblas_error(3, "Illegal value of M");
return -3;
}
if (N < 0) {
coreblas_error(4, "Illegal value of N");
return -4;
}
if ((K < 0) || (K > nq)) {
coreblas_error(5, "Illegal value of K");
return -5;
}
if ((IB < 0) || ( (IB == 0) && ((M > 0) && (N > 0)) )) {
coreblas_error(6, "Illegal value of IB");
return -6;
}
if ((LDA < max(1,nq)) && (nq > 0)) {
coreblas_error(8, "Illegal value of LDA");
return -8;
}
if ((LDC < max(1,M)) && (M > 0)) {
coreblas_error(12, "Illegal value of LDC");
return -12;
}
if ((LDWORK < max(1,nw)) && (nw > 0)) {
coreblas_error(14, "Illegal value of LDWORK");
return -14;
}
/* Quick return */
if ((M == 0) || (N == 0) || (K == 0))
return PLASMA_SUCCESS;
if (((side == PlasmaLeft) && (trans != PlasmaNoTrans))
|| ((side == PlasmaRight) && (trans == PlasmaNoTrans))) {
i1 = 0;
i3 = IB;
}
else {
i1 = ( ( K-1 ) / IB )*IB;
i3 = -IB;
}
for(i = i1; (i >- 1) && (i < K); i+=i3 ) {
kb = min(IB, K-i);
if (side == PlasmaLeft) {
/*
* H or H' is applied to C(i:m,1:n)
*/
mi = M - i;
ic = i;
}
else {
/*
* H or H' is applied to C(1:m,i:n)
*/
ni = N - i;
jc = i;
}
/*
* Apply H or H'
*/
LAPACKE_dlarfb_work(LAPACK_COL_MAJOR,
lapack_const(side),
lapack_const(trans),
lapack_const(PlasmaForward),
lapack_const(PlasmaColumnwise),
mi, ni, kb,
&A[LDA*i+i], LDA,
&T[LDT*i], LDT,
&C[LDC*jc+ic], LDC,
WORK, LDWORK);
}
return PLASMA_SUCCESS;
}
| {
"alphanum_fraction": 0.4717440728,
"avg_line_length": 27.9909090909,
"ext": "c",
"hexsha": "c8807d89a39481c8d2cb16dfa232e6104a8c9ec3",
"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_dormqr.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_dormqr.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/core_dormqr.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1793,
"size": 6158
} |
/* multiroots/fdjac.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 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 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.
*/
#include <config.h>
#include <gsl/gsl_multiroots.h>
int
gsl_multiroot_fdjacobian (gsl_multiroot_function * F,
const gsl_vector * x, const gsl_vector * f,
double epsrel, gsl_matrix * jacobian)
{
const size_t n = x->size;
const size_t m = f->size;
const size_t n1 = jacobian->size1;
const size_t n2 = jacobian->size2;
if (m != n1 || n != n2)
{
GSL_ERROR ("function and jacobian are not conformant", GSL_EBADLEN);
}
{
size_t i,j;
gsl_vector *x1, *f1;
x1 = gsl_vector_alloc (n);
if (x1 == 0)
{
GSL_ERROR ("failed to allocate space for x1 workspace", GSL_ENOMEM);
}
f1 = gsl_vector_alloc (m);
if (f1 == 0)
{
gsl_vector_free (x1);
GSL_ERROR ("failed to allocate space for f1 workspace", GSL_ENOMEM);
}
gsl_vector_memcpy (x1, x); /* copy x into x1 */
for (j = 0; j < n; j++)
{
double xj = gsl_vector_get (x, j);
double dx = epsrel * fabs (xj);
if (dx == 0)
{
dx = epsrel;
}
gsl_vector_set (x1, j, xj + dx);
{
int status = GSL_MULTIROOT_FN_EVAL (F, x1, f1);
if (status != GSL_SUCCESS)
{
return GSL_EBADFUNC;
}
}
gsl_vector_set (x1, j, xj);
for (i = 0; i < m; i++)
{
double g1 = gsl_vector_get (f1, i);
double g0 = gsl_vector_get (f, i);
gsl_matrix_set (jacobian, i, j, (g1 - g0) / dx);
}
}
gsl_vector_free (x1);
gsl_vector_free (f1);
}
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6065643649,
"avg_line_length": 24.1855670103,
"ext": "c",
"hexsha": "acb773fe05fdfff3fd6c4865e97c103be2228201",
"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/multiroots/fdjac.c",
"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/multiroots/fdjac.c",
"max_line_length": 74,
"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/multiroots/fdjac.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": 683,
"size": 2346
} |
// Copyright The Authors 2018.
// Distributed under the 3-Clause BSD License.
// (See accompanying file LICENSE or copy at
// https://opensource.org/licenses/BSD-3-Clause)
#pragma once
#include <array> // for std::array
#include <bitset> // for std::bitset
#include <cstdint> // for standard int types
#include <cstring> // for std::memcpy
#include <iosfwd> // for implementation of operator<<
#include <iterator> // for std::reverse_iterator
#include <string> // for std::string
#include <gsl/gsl> // for gsl::span
#include <codec/base16.h> // for hex enc/decoding
#include <common/assert.h> // for assertions
#include <crypto/random.h> // for random block generation
namespace blocxxi {
namespace crypto {
namespace detail {
/// Forward declarations for utility conversion function between host and
/// network (big endian) byte orders.
/// Avoid including header files of boost and pulling all its bloat here.
std::uint32_t HostToNetwork(std::uint32_t);
std::uint32_t NetworkToHost(std::uint32_t);
/// Count the number of leading zero bits in a buffer of contiguous 32-bit
/// integers.
int CountLeadingZeroBits(gsl::span<std::uint32_t const> buf);
} // namespace detail
/*!
Represents a N bits hash digest or any other kind of N bits sequence.
The structure is 32-bit aligned and must be at least 32-bits wide. It
has almost the same semantics of std::array<> except that it will never be
zero-length (size() is always > 0). It offers a number of additional
convenience methods, such as bitwise arithemtics, comparisons etc.
*/
template <unsigned int BITS>
class Hash {
static_assert(BITS % 32 == 0, "Hash size in bits must be a multiple of 32");
static_assert(BITS > 0, "Hash size in bits must be greater than 0");
public:
using value_type = std::uint8_t;
using pointer = uint8_t *;
using const_pointer = std::uint8_t const *;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = std::uint8_t &;
using const_reference = std::uint8_t const &;
using iterator = pointer;
using const_iterator = const_pointer;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
///@name Constructors and Factory methods
//@{
/// Initializes the hash with all '0' bits
Hash() : storage_({}) {}
Hash(const Hash &other) = default;
Hash &operator=(const Hash &rhs) = default;
Hash(Hash &&) noexcept = default;
Hash &operator=(Hash &&rhs) noexcept = default;
virtual ~Hash() = default;
/*!
\brief Construct a Hash by assigning content from the provided sequence of
bytes.
> The source sequence can be smaller than the hash size but it __cannot be
> bigger__.
In the case it is smaller, the hash will be padded (leading bytes)
with 0. The last byte in the source sequence will be the LSB of the hash
(last byte in the hash).
In the case it is bigger, result is undefined and, if assertions are enabled,
this would be considered as a fatal error.
\param buf source sequence of bytes.
*/
explicit Hash(gsl::span<std::uint8_t const> buf) noexcept : storage_({}) {
auto src_size = buf.size();
ASAP_ASSERT_PRECOND(src_size <= Size());
auto start = begin();
if (Size() > src_size) {
// Pad with zeros and adjust the start
std::memset(Data(), 0, Size() - src_size);
start += Size() - src_size;
}
Assign(buf, start);
}
/// \brief Returns an all-1 hash, i.e. the biggest value representable by an N
/// bit number (N/8 bytes).
static Hash Max() noexcept {
Hash h;
h.storage_.fill(0xffffffffU);
return h;
}
/// \brief Returns an all-0 hash, i.e. the smallest value representable by an
/// N bit number (N/8 bytes).
static Hash Min() noexcept {
return Hash();
// all bits are already 0
}
static Hash<BITS> FromHex(const std::string &src, bool reverse = false) {
Hash<BITS> hash;
codec::hex::Decode(gsl::make_span<>(src),
gsl::make_span<>(hash.Data(), hash.Size()), reverse);
return hash;
}
static Hash<BITS> RandomHash() {
Hash<BITS> hash;
hash.Randomize();
return hash;
}
//@}
/// @name Checked element access
/// access specified element with bounds checking.
//@{
/*!
Returns a reference to the element at specified location `pos`, with
bounds checking.
\param pos position of the element to return
\exception std::out_of_range if !(pos < size()).
*/
reference At(size_type pos) {
if (Size() <= pos) {
throw std::out_of_range("Hash<BITS> index out of range");
}
return reinterpret_cast<pointer>(storage_.data())[pos];
}
const_reference At(size_type pos) const {
if (Size() <= pos) {
throw std::out_of_range("Hash<BITS> index out of range");
}
return reinterpret_cast<const_pointer>(storage_.data())[pos];
};
//@}
/// @name Unchecked element access
/// access specified element __without__ bounds checking.
//@{
/// Returns a reference to the element at specified location pos. No bounds
/// checking is performed.
reference operator[](size_type pos) noexcept {
ASAP_ASSERT_PRECOND(pos < Size());
return reinterpret_cast<pointer>(storage_.data())[pos];
}
const_reference operator[](size_type pos) const noexcept {
ASAP_ASSERT_PRECOND(pos < Size());
return reinterpret_cast<pointer>(storage_.data())[pos];
}
/// Returns a reference to the first element in the container.
reference Front() { return reinterpret_cast<pointer>(storage_.data())[0]; }
const_reference Front() const {
return reinterpret_cast<const_pointer>(storage_.data())[0];
}
/// Returns reference to the last element in the container.
reference Back() {
return reinterpret_cast<pointer>(storage_.data())[Size() - 1];
}
const_reference Back() const {
return reinterpret_cast<const_pointer>(storage_.data())[Size() - 1];
}
/// Returns pointer to the underlying array serving as element storage. The
/// pointer is such that range [Data(); Data() + Size()) is always a valid
/// range.
pointer Data() noexcept { return reinterpret_cast<pointer>(storage_.data()); }
const_pointer Data() const noexcept {
return reinterpret_cast<const_pointer>(storage_.data());
}
//@}
/// @name Iterators
//@{
/// Returns an iterator to the first element of the container.
iterator begin() noexcept {
return reinterpret_cast<pointer>(storage_.data());
}
const_iterator begin() const noexcept {
return reinterpret_cast<const_pointer>(storage_.data());
}
const_iterator cbegin() const noexcept { return begin(); }
/// Returns an iterator to the element following the last element of the
/// container. This element acts as a placeholder; attempting to access it
/// results in undefined behavior.
iterator end() noexcept {
return reinterpret_cast<pointer>(storage_.data()) + Size();
}
const_iterator end() const noexcept {
return reinterpret_cast<const_pointer>(storage_.data()) + Size();
}
const_iterator cend() const noexcept { return end(); }
/// Returns a reverse iterator to the first element of the reversed container.
/// It corresponds to the last element of the non-reversed container.
reverse_iterator rbegin() noexcept { return reverse_iterator(end()); }
const_reverse_iterator rbegin() const noexcept {
return const_reverse_iterator(end());
}
const_reverse_iterator crbegin() const noexcept { return rbegin(); }
/// Returns a reverse iterator to the element following the last element of
/// the reversed container. It corresponds to the element preceding the first
/// element of the non-reversed container. This element acts as a placeholder,
/// attempting to access it results in undefined behavior.
reverse_iterator rend() noexcept { return reverse_iterator(begin()); }
const_reverse_iterator rend() const noexcept {
return const_reverse_iterator(begin());
}
const_reverse_iterator crend() const noexcept { return rend(); }
//@}
// Capacity
/// The size of the hash in bytes.
constexpr static std::size_t Size() { return BITS / 8; };
/// The size of the hash in bytes.
constexpr static std::size_t BitSize() { return BITS; };
// Operations
/// Set all bits to 0.
void Clear() { storage_.fill(0); }
/// Return true if all bits are set to 0.
bool IsAllZero() const {
for (auto v : storage_)
if (v != 0) return false;
return true;
}
/// Exchanges the contents of the container with those of other. Does not
/// cause iterators and references to associate with the other container.
void swap(Hash &other) noexcept { storage_.swap(other.storage_); }
/// Count leading zero bits.
int LeadingZeroBits() const {
return detail::CountLeadingZeroBits(gsl::make_span(storage_));
}
/// @name Comparison operators
/// The important thing to note here is that only two of these operators
/// actually do anything, the others are just forwarding their arguments to
/// either of these two to do the actual work (== and <). Therefore only these
/// two are implemented as friends.
//@{
/// \brief Checks if the contents of `lhs` and `rhs` are equal, that is,
/// whether each element in `lhs` compares equal with the element in `rhs` at
/// the same position.
friend bool operator==(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {
return std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
/// \brief Compares the contents of `lhs` and `rhs` lexicographically. The
/// comparison is performed by a function equivalent to
/// `std::lexicographical_compare`.
friend bool operator<(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {
for (std::size_t i = 0; i < SIZE_DWORD; ++i) {
std::uint32_t const native_lhs = detail::NetworkToHost(lhs.storage_[i]);
std::uint32_t const native_rhs = detail::NetworkToHost(rhs.storage_[i]);
if (native_lhs < native_rhs) return true;
if (native_lhs > native_rhs) return false;
}
return false;
}
//@}
/// In-place bitwise XOR with the given other hash.
Hash &operator^=(Hash const &other) noexcept {
for (std::size_t i = 0; i < SIZE_DWORD; ++i)
storage_[i] ^= other.storage_[i];
return *this;
}
/*!
Starting at the given position in the hash, assign contents from the given
sequence of bytes.
> Data represented by the span is expected to be organized in network byte
> order (i.e. the byte returned by span.first() is the MSB (Most Significant
> Byte) and therefore will go into the MSB of the Hash).
The _span_ size can be smaller than the remaining space after _start_ in
the hash but it __cannot be bigger__. If this is not true, result is undefined
and, if assertions are enabled, this would be considered as a fatal error.
\param buf source sequence of bytes.
\param start position at which to assign the sequence in the hash.
*/
void Assign(gsl::span<std::uint8_t const> buf, iterator start) noexcept {
size_type src_size = buf.size();
size_type dst_size = end() - start;
ASAP_ASSERT_PRECOND(src_size <= dst_size);
std::memcpy(start, buf.data(), std::min(src_size, dst_size));
}
// TODO: Replace the parameters with a span
void Randomize() { random::GenerateBlock(Data(), Size()); }
const std::string ToHex() const {
return codec::hex::Encode(gsl::make_span<>(Data(), Size()), false, true);
}
std::bitset<BITS> ToBitSet() const {
std::bitset<BITS> bs; // [0,0,...,0]
int shift_left = BITS;
for (uint32_t num_part : storage_) {
shift_left -= 32;
num_part = detail::HostToNetwork(num_part);
std::bitset<BITS> bs_part(num_part);
bs |= bs_part << shift_left;
}
return bs;
}
std::string ToBitStringShort(std::size_t length = 32U) const {
auto truncate = false;
if (length < BITS) { truncate = true; length -= 3; }
auto str = ToBitSet().to_string().substr(0, length);
if (truncate) str.append("...");
return str;
}
private:
/// The size of the underlying data buffer in terms of 32-bit DWORD
static constexpr std::size_t SIZE_DWORD = BITS / 32;
/// The underlying data buffer is built as an array of unsigned 32-bit
/// integers to facilitate the math operations. Note however that iteration
/// over the Hash and random access to the data should always be presented as
/// if it were a byte array layed out in network order (big endian).
///
/// > First DWORD is the most significant 4 bytes.
std::array<std::uint32_t, SIZE_DWORD> storage_;
};
/// @name Comparison operators
/// Additional Comparison operators (not needing to be friend)
//@{
template <unsigned int BITS>
inline bool operator!=(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {
return !(lhs == rhs);
}
template <unsigned int BITS>
inline bool operator>(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {
return rhs < lhs;
}
template <unsigned int BITS>
inline bool operator<=(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {
return !(lhs > rhs);
}
template <unsigned int BITS>
inline bool operator>=(const Hash<BITS> &lhs, const Hash<BITS> &rhs) {
return !(lhs < rhs);
}
//@}
/// Bitwise XOR
template <unsigned int BITS>
inline Hash<BITS> operator^(Hash<BITS> lhs, Hash<BITS> const &rhs) noexcept {
return lhs.operator^=(rhs);
}
// Specialized algorithms
/// Exchanges the contents of one with other. Does not cause
/// iterators and references to associate with the other container.
template <unsigned int BITS>
inline void swap(Hash<BITS> &lhs, Hash<BITS> &rhs) {
lhs.swap(rhs);
}
/// Dump the hex-encoded contents of the hash to the stream.
template <unsigned int BITS>
inline std::ostream &operator<<(std::ostream &out, Hash<BITS> const &hash) {
out << hash.ToHex();
return out;
}
using Hash512 = Hash<512>; // 64 bytes
using Hash256 = Hash<256>; // 32 bytes
using Hash160 = Hash<160>; // 20 bytes
} // namespace crypto
} // namespace blocxxi
| {
"alphanum_fraction": 0.6851588093,
"avg_line_length": 34.1654501217,
"ext": "h",
"hexsha": "6f9142b78a1d6110024b642855721feb469decad",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-11-27T19:37:05.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-07-13T17:55:31.000Z",
"max_forks_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "canhld94/blocxxi",
"max_forks_repo_path": "crypto/include/crypto/hash.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a",
"max_issues_repo_issues_event_max_datetime": "2020-09-03T09:50:56.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-20T08:39:12.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "canhld94/blocxxi",
"max_issues_repo_path": "crypto/include/crypto/hash.h",
"max_line_length": 80,
"max_stars_count": 24,
"max_stars_repo_head_hexsha": "e0e1e629334a7959c3fb9c38567f9cf28e2cf44a",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "canhld94/blocxxi",
"max_stars_repo_path": "crypto/include/crypto/hash.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-12T07:08:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-17T22:10:41.000Z",
"num_tokens": 3490,
"size": 14042
} |
#ifndef INCLUDED_TELEPATH_LAPACK_DRIVERS_LLS_H
#define INCLUDED_TELEPATH_LAPACK_DRIVERS_LLS_H
#include <lapacke.h>
namespace telepath{
template< typename T >
auto posv( int matrix_order, char uplo, std::size_t n, std::size_t nrhs,
T* a, std::size_t lda, T* b, std::size_t ldb );
template<>
inline auto posv<float>( int matrix_order, char uplo, std::size_t n,
std::size_t nrhs, float* a, std::size_t lda, float* b,
std::size_t ldb ){
return LAPACKE_sposv( matrix_order, uplo, n, nrhs, a, lda, b, ldb );
}
template<>
inline auto posv<double>( int matrix_order, char uplo, std::size_t n,
std::size_t nrhs, double* a, std::size_t lda, double* b,
std::size_t ldb ){
return LAPACKE_dposv( matrix_order, uplo, n, nrhs, a, lda, b, ldb );
}
template<>
inline auto posv<std::complex<float> >( int matrix_order, char uplo,
std::size_t n, std::size_t nrhs, std::complex<float>* a,
std::size_t lda, std::complex<float>* b, std::size_t ldb ){
return LAPACKE_cposv( matrix_order, uplo, n, nrhs, a, lda, b, ldb );
}
template<>
inline auto posv<std::complex<double> >( int matrix_order, char uplo,
std::size_t n, std::size_t nrhs, std::complex<double>* a,
std::size_t lda, std::complex<double>* b, std::size_t ldb ){
return LAPACKE_zposv( matrix_order, uplo, n, nrhs, a, lda, b, ldb );
}
inline auto posv( int matrix_order, char uplo, std::size_t n,
std::size_t nrhs, double* a, std::size_t lda, double* b,
std::size_t ldb, double* x, std::size_t ldx, lapack_int* iter ){
return LAPACKE_dsposv( matrix_order, uplo, n, nrhs, a, lda, b, ldb,
x, ldx, iter );
}
inline auto posv( int matrix_order, char uplo, std::size_t n,
std::size_t nrhs, std::complex<double>* a, std::size_t lda,
std::complex<double>* b, std::size_t ldb, std::complex<double>* x,
std::size_t ldx, lapack_int* iter ){
return LAPACKE_zcposv( matrix_order, uplo, n, nrhs, a, lda, b, ldb,
x, ldx, iter );
}
template< typename T >
auto gelsd( int matrix_order, std::size_t m, std::size_t n,
std::size_t nrhs, T* a, std::size_t lda, T* b, std::size_t ldb,
T* s, T rcond, lapack_int* rank );
template<>
inline auto gelsd<double>( int matrix_order, std::size_t m, std::size_t n,
std::size_t nrhs, double* a, std::size_t lda, double* b,
std::size_t ldb,double* s, double rcond, lapack_int* rank ){
return LAPACKE_dgelsd( matrix_order, m, n, nrhs, a, lda, b, ldb,
s, rcond, rank );
}
template<>
inline auto gelsd<float>( int matrix_order, std::size_t m, std::size_t n,
std::size_t nrhs, float* a, std::size_t lda, float* b,
std::size_t ldb,float* s, float rcond, lapack_int* rank ){
return LAPACKE_sgelsd( matrix_order, m, n, nrhs, a, lda, b, ldb,
s, rcond, rank );
}
template<>
inline auto gelsd<std::complex<double> >( int matrix_order, std::size_t m,
std::size_t n, std::size_t nrhs, std::complex<double>* a,
std::size_t lda, std::complex<double>* b, std::size_t ldb,
std::complex<double>* s, std::complex<double> rcond, lapack_int* rank ){
return LAPACKE_zgelsd( matrix_order, m, n, nrhs, a, lda, b, ldb,
s, rcond, rank );
}
template<>
inline auto gelsd<std::complex<float> >( int matrix_order, std::size_t m,
std::size_t n, std::size_t nrhs, std::complex<float>* a,
std::size_t lda, std::complex<float>* b, std::size_t ldb,
std::complex<float>* s, std::complex<float> rcond, lapack_int* rank ){
return LAPACKE_cgelsd( matrix_order, m, n, nrhs, a, lda, b, ldb,
s, rcond, rank );
}
} //namespace telepath
#endif
| {
"alphanum_fraction": 0.6141670991,
"avg_line_length": 43.7954545455,
"ext": "h",
"hexsha": "3f7f85cd1d6aa0b8957b57350774fdf52261e105",
"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": "636f7345b6479d5c48dbf03cb17343b14c305c7c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tbepler/telepath",
"max_forks_repo_path": "include/telepath/lapack/drivers/lls.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c",
"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": "tbepler/telepath",
"max_issues_repo_path": "include/telepath/lapack/drivers/lls.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tbepler/telepath",
"max_stars_repo_path": "include/telepath/lapack/drivers/lls.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1207,
"size": 3854
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_fit.h>
#include "cosmocalc.h"
static double linear_corrfunc_integ_funct(double k, void *p);
static double linear_corrfunc_integ_funct(double k, void *p)
{
double r = ((double*)p)[0];
double a = ((double*)p)[1];
return linear_powspec(k,a)*k/r;
}
double linear_corrfunc_exact(double r, double a)
{
double I0;
double abserr,p[2];
gsl_integration_workspace *workspace;
gsl_function F;
gsl_integration_qawo_table *wf;
gsl_integration_workspace *cycle_workspace;
#define WORKSPACE_NUM 70
#define ABSERR 1e-3
workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);
cycle_workspace = gsl_integration_workspace_alloc((size_t) WORKSPACE_NUM);
wf = gsl_integration_qawo_table_alloc(r,1.0,GSL_INTEG_SINE,(size_t) WORKSPACE_NUM);
F.function = &linear_corrfunc_integ_funct;
p[0] = r;
p[1] = a;
F.params = p;
gsl_integration_qawf(&F,1e-8,ABSERR,(size_t) WORKSPACE_NUM,workspace,cycle_workspace,wf,&I0,&abserr);
gsl_integration_qawo_table_free(wf);
gsl_integration_workspace_free(cycle_workspace);
gsl_integration_workspace_free(workspace);
#undef ABSERR
#undef WORKSPACE_NUM
return I0/2.0/M_PI/M_PI;
}
double linear_corrfunc(double r, double a)
{
static int initFlag = 1;
static int currCosmoNum;
static gsl_spline *cosmocalc_linear_corrfunc_spline = NULL;
static gsl_interp_accel *cosmocalc_linear_corrfunc_acc = NULL;
double linear_corrfunc_table[COSMOCALC_LINEAR_CORRFUNC_TABLE_LENGTH];
double r_table[COSMOCALC_LINEAR_CORRFUNC_TABLE_LENGTH];
long i;
double gf;
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
for(i=0;i<COSMOCALC_LINEAR_CORRFUNC_TABLE_LENGTH;++i)
{
r_table[i] = log(CF_R_MAX/CF_R_MIN)/(COSMOCALC_LINEAR_CORRFUNC_TABLE_LENGTH-1.0)*((double) i) + log(CF_R_MIN);
linear_corrfunc_table[i] = linear_corrfunc_exact(exp(r_table[i]),1.0);
}
//init the spline and accelerators
if(cosmocalc_linear_corrfunc_spline != NULL)
gsl_spline_free(cosmocalc_linear_corrfunc_spline);
cosmocalc_linear_corrfunc_spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_LINEAR_CORRFUNC_TABLE_LENGTH));
gsl_spline_init(cosmocalc_linear_corrfunc_spline,r_table,linear_corrfunc_table,(size_t) (COSMOCALC_LINEAR_CORRFUNC_TABLE_LENGTH));
if(cosmocalc_linear_corrfunc_acc != NULL)
gsl_interp_accel_reset(cosmocalc_linear_corrfunc_acc);
else
cosmocalc_linear_corrfunc_acc = gsl_interp_accel_alloc();
}
gf = growth_function(a);
if(r < CF_R_MIN)
return 0.0;
else if(r < CF_R_MAX)
return gsl_spline_eval(cosmocalc_linear_corrfunc_spline,log(r),cosmocalc_linear_corrfunc_acc)*gf*gf;
else
return 0.0;
}
| {
"alphanum_fraction": 0.7569209993,
"avg_line_length": 30.8541666667,
"ext": "c",
"hexsha": "8ad9b788e2ce11e71ccfa1c6700eec11bbe5374e",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z",
"max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "beckermr/cosmocalc",
"max_forks_repo_path": "src/linear_corrfunc.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "beckermr/cosmocalc",
"max_issues_repo_path": "src/linear_corrfunc.c",
"max_line_length": 136,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "beckermr/cosmocalc",
"max_stars_repo_path": "src/linear_corrfunc.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 881,
"size": 2962
} |
/***
* Copyright 2019 The Katla Authors
*
* 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 KATLA_POSIX_FILE_H
#define KATLA_POSIX_FILE_H
#include "katla/core/core.h"
#include <optional>
#include <gsl/span>
#include <fcntl.h>
namespace katla {
class PosixFile {
public:
enum class OpenFlags : int {
ReadOnly = O_RDONLY,
WriteOnly = O_WRONLY,
ReadWrite = O_RDWR,
Create = O_CREAT,
Exclusive = O_EXCL,
Truncate = O_TRUNC,
Append = O_APPEND,
NonBlocking = O_NONBLOCK,
Sync = O_SYNC,
Async = O_ASYNC,
#if defined(O_TMPFILE)
TmpFile = O_TMPFILE
#endif
};
PosixFile();
~PosixFile();
outcome::result<void> create(std::string_view filePath, OpenFlags flags);
outcome::result<void> open(std::string_view filePath, OpenFlags flags);
outcome::result<void> close();
outcome::result<ssize_t> read(gsl::span<std::byte> &buffer);
outcome::result<ssize_t> write(gsl::span<std::byte> &buffer);
static outcome::result<std::string> absolutePath(std::string path);
outcome::result<size_t> size();
private:
int m_fd;
};
inline PosixFile::OpenFlags operator|(PosixFile::OpenFlags lhs, PosixFile::OpenFlags rhs) {
using T = std::underlying_type_t<PosixFile::OpenFlags>;
return static_cast<PosixFile::OpenFlags>(static_cast<T>(lhs) | static_cast<T>(rhs));
}
inline PosixFile::OpenFlags &operator|=(PosixFile::OpenFlags &lhs, PosixFile::OpenFlags rhs) {
lhs = lhs | rhs;
return lhs;
}
}
#endif // KATLA_POSIX_FILE_H
| {
"alphanum_fraction": 0.6335844041,
"avg_line_length": 28.5696202532,
"ext": "h",
"hexsha": "2e730124a33c4055d787c1e497e16ca904b75795",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-26T13:32:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-26T13:32:36.000Z",
"max_forks_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "plok/katla",
"max_forks_repo_path": "core/posix-file.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223",
"max_issues_repo_issues_event_max_datetime": "2021-11-16T14:21:56.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-25T14:33:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "plok/katla",
"max_issues_repo_path": "core/posix-file.h",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aaaeb8baf041bba7259275beefc71c8452a16223",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "plok/katla",
"max_stars_repo_path": "core/posix-file.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 546,
"size": 2257
} |
/* ============================================================ *
* halomodel.h *
* Martin Kilbinger 2006-2009 *
* ============================================================ */
#ifndef __HALOMODEL_H
#define __HALOMODEL_H
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <string.h>
#include <fftw3.h>
#include <gsl/gsl_sf_erf.h>
#include "io.h"
#include "errorlist.h"
#include "config.h"
#include "maths.h"
#include "cosmo.h"
#include "nofz.h"
#define hm_base -1900
#define hm_hodtype hm_base + 1
#define hm_Mmin hm_base + 2
#define hm_pofk hm_base + 3
#define hm_nfw hm_base + 4
#define hm_par hm_base + 5
#define hm_overflow hm_base + 6
#define hm_io hm_base + 7
#define hm_zbin hm_base + 8
#define hm_alpha hm_base + 9
#define hm_negative hm_base + 10
#define hm_zmean_2h hm_base + 11
#define hm_halo_bias hm_base + 12
#define hm_undef hm_base + 13
#define hm_gsl_int hm_base + 14
/* Ranges of interpolation tables */
#define k_max_HOD 3336.0
/* Present critical density [M_sol h^2 / Mpc^3] */
#define rho_c0 2.7754e11
/* Mass limits for integration over mass functions */
#define logMmin (3.0*log(10.0))
#define logMmax (16.0*log(10.0))
/* Number of steps for scale-factor-integration (redshift) */
#define Na_hm 20
/* Bit-coded power spectrum types */
typedef enum {pofk_undef=-1, pl=1, pnl=2, p1hdm=4, p2hdm=8, pthdm=16, p1hg=32, p2hg=64, pthg=128,
p1hgcs=256, p1hgss=512, pstellar=1024} pofk_t;
/* Halo mass function type */
typedef enum {ps, st, st2, j01} massfct_t;
#define smassfct_t(i) ( \
i==ps ? "ps" : \
i==st ? "st" : \
i==st2 ? "st2" : \
i==j01 ? "j01" : \
"")
#define Nmassfct_t 4
/* Halo bias type */
typedef enum {halo_bias_sc, halo_bias_tinker05, halo_bias_tinker10} halo_bias_t;
#define shalo_bias_t(i) ( \
i==halo_bias_sc ? "halo_bias_sc" : \
i==halo_bias_tinker05 ? "halo_bias_tinker05" : \
i==halo_bias_tinker10 ? "halo_bias_tinker10" : \
"")
#define Nhalo_bias_t 3
/* HOD (Halo occupation distribution) type */
#define Nhod_t 5
typedef enum {hod_none, hamana04, berwein02, berwein02_hexcl, leauthaud11} hod_t;
#define shod_t(i) ( \
i==hod_none ? "hod_none" : \
i==hamana04 ? "hamana04" : \
i==berwein02 ? "berwein02" : \
i==berwein02_hexcl ? "berwein02_hexcl" :\
i==leauthaud11 ? "leauthaud11" : \
"")
/* ---------------------------------------------------------------- *
* Global variables and functions *
* ---------------------------------------------------------------- */
double FFTLog_TMP;
typedef struct FFTLog_complex
{
double re;
double im;
double amp;
double arg;
} FFTLog_complex;
typedef struct {
int N;
fftw_plan p_forward;
fftw_plan p_backward;
fftw_complex *an;
fftw_complex *ak;
fftw_complex *cm;
fftw_complex *um;
fftw_complex *cmum;
double min;
double max;
double q;
double mu;
double kr;
} FFTLog_config;
typedef struct {
cosmo *cosmo;
redshift_t *redshift;
double zmin, zmax;
/* Dark matter halo profile */
double c0; /* concentration parameter */
double alpha_NFW; /* density slope */
double beta_NFW; /* concentration slope as fct of mass */
massfct_t massfct; /* halo mass function */
halo_bias_t halo_bias; /* Halo bias */
/* Mass function parameters (Sheth&Torman). Do not set manually, they are set *
* in set_massfct() according to enum massfct. */
double nmz_a; /* Called q in CS02 */
double nmz_p; /* a=1, p=1/2 is Press-Schechter mass fct. */
/* HOD (halo occupation distribution) parameters */
hod_t hod; /* HOD type */
double M1, M0, sigma_log_M;
double M_min;
double alpha;
double pi_max;
double eta; /* central galaxy proportion */
/* galaxy-galaxy lensing and wp(rp) */
double log10Mhalo;
double coord_phys;
/* For Leauthaud11 model */
double beta,delta,gamma,Mstar0;
double beta_sat,B_sat,beta_cut,B_cut;
double x; /* any parameter to propagate if needed */
double Mstellar_min, Mstellar_max;
double fcen1, fcen2;
/* Precomputed stuff */
double A; /* Mass function normalisation */
double Mstar; /* M_*(a=1.0) */
interTable2D *Pthdm;
interTable *xir;
interTable *xi_dm;
interTable2D *rhohat;
splineTable* sigRsqr;
double a_xir;
/* FFTLOG flag - OBSOLETE */
int FFTLog;
} cosmo_hm;
typedef struct {
cosmo *cosmo;
cosmo_hm *model;
double a, r, k, ng, ngp, eps, c;
double logMlim, bias_fac, Mh, Mstellar, Mstellar_min, Mstellar_max;
double M, r_vir, *kk;
error **err;
double logrmin, logrmax, rp, xi;
gsl_interp_accel *acc;
gsl_spline *spline;
int i, j, type, asymptotic, logintegrate;
double (*bias_func)(double, void *);
} cosmo_hm_params;
typedef struct gsl_int_params
{
void *params;
funcwithpars func;
error **err;
} gsl_int_params;
typedef struct {
double *z;
double *fac;
double *ypn; /* for spline interpolation */
double zm; /* average weighted redshift*/
int nbins;
} nz_t;
cosmo_hm* init_parameters_hm(double OMEGAM, double OMEGADE, double W0_DE, double W1_DE,
double *W_POLY_DE, int N_POLY_DE,
double H100, double OMEGAB, double OMEGANUMASS,
double NEFFNUMASS, double NORM, double NSPEC,
int Nzbin, const int *Nnz, const nofz_t *nofz, double *par_nz,
double zmin, double zmax,
nonlinear_t NONLINEAR, transfer_t TRANSFER, growth_t GROWTH,
de_param_t DEPARAM, norm_t normmode,
double C0, double ALPHANFW, double BETANFW, massfct_t MASSFCT, halo_bias_t HALO_BIAS,
double M_min, double M1, double M0, double sigma_log_M, double alpha,
double Mstar0, double beta, double delta, double gamma, double B_cut, double B_sat,
double beta_cut, double beta_sat, double Mstellar_min, double Mstellar_max, double eta,
double fcen1, double fcen2,
hod_t HOD, double pi_max, error **err);
cosmo_hm* copy_parameters_hm_only(cosmo_hm* source, error **err);
cosmo_hm *copy_parameters_hm(cosmo_hm *source, error **err);
void read_cosmological_parameters_hm(cosmo_hm **model, FILE *F, error **err);
cosmo_hm *set_cosmological_parameters_to_default_hm(error **err);
void free_parameters_hm(cosmo_hm** model);
void set_massfct(massfct_t massfct, double *nmz_a, double *nmz_p, error **err);
void dump_param_only_hm(cosmo_hm* model, FILE *F);
void dump_param_hm(cosmo_hm* model, FILE *F, error **err);
double sm2_rtbis(double (*func)(double, void *, error **), double x1, double x2,
double xacc, void *param, error **err);
/* From nrcomplex.h,c */
#ifndef _DCOMPLEX_DECLARE_T_
typedef struct DCOMPLEX {double r,i;} dcomplex;
#define _DCOMPLEX_DECLARE_T_
#endif /* _DCOMPLEX_DECLARE_T_ */
dcomplex Complex(double re, double im);
dcomplex Cadd(dcomplex a, dcomplex b);
dcomplex Cmul(dcomplex a, dcomplex b);
dcomplex Cdiv(dcomplex a, dcomplex b);
dcomplex RCmul(double x, dcomplex a);
void sm2_cisi(double x, double *ci, double *si, error **err);
double delta_c(cosmo *model, double a, error **err);
double bis_Mstar(double logM, void *param, error **err);
double bis_Mstar_a(double logM, void *param, error **err);
double Mstar(cosmo_hm *model, error **err);
double Mstar_a(cosmo_hm *model, double a, error **err);
double concentration(cosmo_hm *model, double Mh, double a, error **err);
double Delta_vir(cosmo_hm *model, double a);
double dsigma_R_sqr_dR(cosmo_hm *model, double R, error **err);
double nufnu(cosmo_hm *model, double nu, int asymptotic, error **err);
double nufnu_j01(double x);
double sigma_R_sqr(cosmo_hm *model, double R, error **err);
double sigmasqr_M(cosmo_hm *model, double M, error **err);
double dsigma_m1_dlnM(cosmo_hm *model, double M, error **err);
double dnu_dlnM(cosmo_hm *model, double M, double a, error **err);
double dn_dlnM_lnM(double logM, void *intpar, error **err);
double dn_dlnM_uf(double M, cosmo_hm *model, double a, error **err);
double dn_dlnM(double M, void *intpar, error **err);
double r_vir(cosmo_hm *model, double M, double a, error **err);
double M_vir(cosmo_hm *model, double r_vir, double a, error **err);
double Delta_h(cosmo_hm *model, double a, error **err);
double rho_crit(cosmo_hm *model, double a, error **err);
double rho_crit_halo(cosmo_hm *model, double a, error **err);
double Omega_m_halo(cosmo_hm *model, double a, error **err);
double rho_halo(cosmo_hm *model, double r, double a, double Mh, double c, error **err);
double DeltaSigma_WB2000(cosmo_hm *model, double r, const double a, const double M, double c, double Delta, error **err);
double g_inf(double x, error **err);
double g_sup(double x, error **err);
double int_for_rhohat(double, void *, error **err);
double rhohat_halo(cosmo_hm *model, double k, double M, double a, double c, error **err);
double halo_bias(cosmo_hm *model, double M, double a, int k, error **err);
double bias(cosmo_hm *model, double M, double a, int k, error **err);
double bias_tinker(cosmo_hm *model, double M, double a, error **err);
double bias_tinker10(cosmo_hm *model, double M, double a, error **err);
double int_for_bias_norm(double logM, void *intpar, error **err);
double bias_norm(cosmo_hm *model, double a, error **err);
double int_for_M_ij(double, void *, error **);
double M_ij(cosmo_hm *model, int i, int j, double a, const double *k, error **err);
double P1h_dm(cosmo_hm *model, double a, double k, error **err);
double P2h_dm(cosmo_hm *model, double a, double k, error **err);
double xi_dm_NL_OBSOLETE(cosmo_hm *model, double a, double r, error **err); // non-linear DM xi
double int_for_xi_dm_NL_OBSOLETE(double k, void *intpar, error **err); // non-linear DM xi
#define CHANGE(fct) int change_##fct(cosmo_hm*, cosmo_hm*)
/* ---------------------------------------------------------------- *
* Utils *
* ---------------------------------------------------------------- */
double int_gsl(funcwithpars func,void *params, double a, double b, double eps, error **err);
double integrand_gsl(double x,void *p);
CHANGE(massfct);
CHANGE(massfct_params);
CHANGE(halo_bias);
CHANGE(sigma_R_sqr);
CHANGE(Mstar);
CHANGE(rhohat_halo);
CHANGE(Pth);
#undef CHANGE
#endif
| {
"alphanum_fraction": 0.6379454732,
"avg_line_length": 32.8654434251,
"ext": "h",
"hexsha": "d2add04fcf6646f471973cc0fdaf3ac0bad48ce3",
"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": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "danielgruen/ccv",
"max_forks_repo_path": "src/nicaea_2.5/halomodel/include/halomodel.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"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": "danielgruen/ccv",
"max_issues_repo_path": "src/nicaea_2.5/halomodel/include/halomodel.h",
"max_line_length": 123,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "danielgruen/ccv",
"max_stars_repo_path": "src/nicaea_2.5/halomodel/include/halomodel.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z",
"num_tokens": 3151,
"size": 10747
} |
/*
* Copyright 2017 RIS.
* Authored by Ron Dahlgren <ron@red83.net>
*/
#include "greatest.h"
#include "entities/entities.h"
#include <stdlib.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
// Alloc and free
TEST test_entity_alloc_and_free()
{
double l, r;
gsl_matrix* identity = gsl_matrix_alloc(4,4);
gsl_matrix_set_identity(identity);
entity_info* new_entity = NULL;
// A newly alloc'd entity should have an identity transform
new_entity = entities.entity_alloc();
ASSERT_FALSE(new_entity == NULL);
ASSERT_FALSE(new_entity->transform == NULL);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
l = gsl_matrix_get(identity, i, j);
r = new_entity->transform[i * 4 + j];
ASSERT_EQ(l, r);
}
}
// function pointers should all be set to null
new_entity->initialize = NULL;
new_entity->terminate = NULL;
new_entity->pre_update = NULL;
new_entity->post_update = NULL;
entities.entity_free(new_entity);
PASS();
}
int pre_update_calls;
int post_update_calls;
void pre_update(double d, entity_info* info) {
pre_update_calls++;
}
void post_update(double d, entity_info* info) {
post_update_calls++;
}
TEST test_update_transforms()
{
pre_update_calls = 0;
post_update_calls = 0;
// initialize the entity manager
entities.initialize();
// Allocate some entities
entity_info* alfred = entities.entity_alloc();
// alfred has no callbacks
entity_info* bryce = entities.entity_alloc();
// bryce has pre
bryce->pre_update = pre_update;
entity_info* charles = entities.entity_alloc();
// charles has post
charles->post_update = post_update;
entity_info* danny = entities.entity_alloc();
// danny has both
danny->pre_update = pre_update;
danny->post_update = post_update;
// Associate them with the entity manager
entities.add_entity(alfred);
entities.add_entity(bryce);
entities.add_entity(charles);
entities.add_entity(danny);
// do an update pass
entities.update(1);
// call backs should have fired
ASSERT_EQ(pre_update_calls, 2);
ASSERT_EQ(post_update_calls, 2);
// remove them from the entity manager
entities.remove_entity(alfred);
entities.remove_entity(bryce);
entities.remove_entity(charles);
entities.remove_entity(danny);
// do an update pass
entities.update(1);
// No callbacks should have fired
ASSERT_EQ(pre_update_calls, 2);
ASSERT_EQ(post_update_calls, 2);
// free everything
entities.entity_free(alfred);
entities.entity_free(bryce);
entities.entity_free(charles);
entities.entity_free(danny);
entities.terminate();
PASS();
}
static void
init_entities(void *data)
{
entities.initialize();
}
static void
destroy_entities(void *data)
{
entities.terminate();
}
SUITE(entity_test_suite) {
SET_SETUP(init_entities, NULL);
SET_TEARDOWN(init_entities, NULL);
RUN_TEST(test_entity_alloc_and_free);
RUN_TEST(test_update_transforms);
}
GREATEST_MAIN_DEFS();
int main(int argc, char** argv) {
GREATEST_MAIN_BEGIN();
RUN_SUITE(entity_test_suite);
GREATEST_MAIN_END();
}
| {
"alphanum_fraction": 0.7199738903,
"avg_line_length": 24.125984252,
"ext": "c",
"hexsha": "3ff01fa3afae9b4d2ce3318e05a22d7b218d9c9f",
"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": "2cc34f384cedce9626e76be8ea22e5967db1b69b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "influenza/c8",
"max_forks_repo_path": "tests/check_entities.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b",
"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": "influenza/c8",
"max_issues_repo_path": "tests/check_entities.c",
"max_line_length": 61,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2cc34f384cedce9626e76be8ea22e5967db1b69b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "influenza/c8",
"max_stars_repo_path": "tests/check_entities.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 792,
"size": 3064
} |
#ifndef __INC_MULTIVARSUPPORT__
#define __INC_MULTIVARSUPPORT__
#include "multi_modelstruct.h"
#include "emulator_struct.h"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
struct multi_modelstruct;
struct emulator_struct;
typedef struct multi_emulator {
int nt;
int nr;
int nparams;
int nmodel_points;
int nregression_fns;
int nthetas;
multi_modelstruct *model;
emulator_struct **emu_struct_array;
} multi_emulator;
multi_emulator *alloc_multi_emulator(multi_modelstruct *model);
void free_multi_emulator(multi_emulator *e);
void estimate_multi(multi_modelstruct *m, FILE* outfp);
void emulate_point_multi(multi_emulator *emu, gsl_vector *the_point,
gsl_vector *the_mean,
gsl_vector *the_variance);
void emulate_point_multi_covar(multi_emulator *emu, gsl_vector *the_point,
gsl_vector *the_mean, gsl_vector *the_variance,
gsl_matrix *the_covar);
void emulate_point_multi_pca(multi_emulator *emu, gsl_vector *the_point,
gsl_vector *the_mean,
gsl_vector *the_variance);
#endif
| {
"alphanum_fraction": 0.7509157509,
"avg_line_length": 23.7391304348,
"ext": "h",
"hexsha": "835d2f6d380d50f7796782d888536763fb1689dc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jackdawjackdaw/emulator",
"max_forks_repo_path": "src/multivar_support.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004",
"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": "jackdawjackdaw/emulator",
"max_issues_repo_path": "src/multivar_support.h",
"max_line_length": 74,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jackdawjackdaw/emulator",
"max_stars_repo_path": "src/multivar_support.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 260,
"size": 1092
} |
/* Siconos-Numerics, Copyright INRIA 2005-2018.
* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
* Siconos is a free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Siconos 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Siconos; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr
*/
#ifndef SiconosBlas_H
#define SiconosBlas_H
#include "SiconosConfig.h"
#if defined(__cplusplus)
extern "C"
{
#endif
// tells include-what-you-use to keep this file
// and not to suggest cblas.h or alike.
// IWYU pragma: begin_exports
#if defined(HAS_MKL_CBLAS)
#include <mkl_cblas.h>
#elif defined(HAS_MATLAB_BLAS)
#include <blas.h>
#define cblas_daxpy daxpy
#define cblas_dcopy dcopy
#define cblas_ddot ddot
#define cblas_dgemm dgemm
#define cblas_dgemv dgemv
#define cblas_dnrm2 dnrm2
#define cblas_dscal dscal
#else
#include <cblas.h>
#endif
// IWYU pragma: end_exports
#ifdef __cplusplus
}
#undef restrict
#define restrict __restrict
#endif
static inline double* NMD_row_rmajor(double* restrict mat, unsigned ncols, unsigned rindx)
{
return &mat[rindx*ncols];
}
static inline void NMD_copycol_rmajor(int nrows, double* col, double* restrict mat, int ncols, unsigned cindx)
{
cblas_dcopy(nrows, col, 1, &mat[cindx], ncols);
}
static inline void NMD_dense_gemv(int nrows, int ncols, double alpha, double* restrict mat, double* restrict y, double beta, double* restrict x)
{
cblas_dgemv(CblasColMajor, CblasTrans, ncols, nrows, alpha, mat, ncols, y, 1, beta, x, 1);
}
#endif // SiconosBlas_H
| {
"alphanum_fraction": 0.7597583643,
"avg_line_length": 29.4794520548,
"ext": "h",
"hexsha": "06878852c3ac21672d9a191ce8bed3f8d4f19ec9",
"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": "649f09d6db7bbd84c2418de74eb9453c0131f070",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "fperignon/sandbox",
"max_forks_repo_path": "externals/blas_lapack/SiconosBlas.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070",
"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": "fperignon/sandbox",
"max_issues_repo_path": "externals/blas_lapack/SiconosBlas.h",
"max_line_length": 144,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "fperignon/sandbox",
"max_stars_repo_path": "externals/blas_lapack/SiconosBlas.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 594,
"size": 2152
} |
#ifndef __FUNCTIONLIB_H__
#define __FUNCTIONLIB_H__
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_poly.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#endif
///////////////////////// Definition of the structures, mainly used as parameters for functions ///////////////////////
///////////Meaning of Words:////////////////////
//
// coef ---> coefficient
// transl ---> tranlation
// stddev ---> standard deviation
// magnif ---> magnification of the variable,
// e.g.: sin(2x) where 2 is the magnification
//
// in all functions the combination of magnification
// and translation is interpreted as
// f( magnif( x - transl) ).
//
////////////////////////////////////////////////
//struct of chained list describing a compound function of several terms multiplying together, where ID refers to the type of funcion (in other words the 'true' struct the pointer 'target' is referring to) . 'flag' signifies this term is 'multiplying' (value 1) or 'dividing' (other value) the whole term.
typedef struct MulMap
{
void * NEXT;
void * target;
int ID;
int flag;
}MulMap;
//struct of chained list describing a series of multiplied compound function summed up together, where flag means the term is summing (value 1) or subtracting (other value) to the whole term (though coef in each struct describing the functions has the ability to describe this)
typedef struct SumMap
{
void *NEXT;
void *MulMaphead;
int flag;
}SumMap;
typedef struct intresult
{
double result;
double error;
}intresult;
//ID: 1
typedef struct PolyFunc
{
int length;
double* coef;
double transl;
double magnif;
}PolyFunc;
//ID: 2
typedef struct GaussianFunc
{
double mean;
double stddev;
double coef;
}GaussianFunc;
//ID: 3
typedef struct SinCosFunc
{
double* sincoef;
double* coscoef;
double transl;
double magnif;
int length;
}SinCosFunc;
//ID: 4
typedef struct Exp
{
double coef;
double transl;
double magnif;
}Exp;
//ID: 5
typedef struct Log
{
double coef;
double magnif;
double base;
double transl;
}Log;
//ID: 6
typedef struct LegendreP
{
int l;
double coef;
double magnif;
double transl;
}LegendreP;
//ID: 7
typedef struct Rect
{
double a;
double b;
double height;
}Rect;
double IDMapping(double x, int ID, void * param);
double FunctionMultiply(double x, void * HeadMulMap);
double FunctionSum(double x,void * summap);
double Combination(int n,int r);
double PolyFunction(double x, void * param);
double GaussianFunction(double x,void * param);
double SinCosFunction(double x,void * param);
double Exponential(double x,void * param);
double Logarithm(double x,void * param);
//Series of functions to help create the structs
void FuncStructConstruct(FILE * inputfile,void * target, int ID);
void MulMapConstruct(FILE * inputfile, MulMap * headpointer);
void SumMapConstruct(FILE * inputfile, SumMap * headpointer);
//Series of functions to help free the memory taken by the structs
void FuncStructDelete(void* target, int ID);
void MulMapDelete(void * target);
void SumMapDelete(void * target);
void OrthoPolyCoefGen(gsl_matrix * target,int rows,int columns,double a,double b);
void PolynomialTranslationCoef(gsl_vector * target,PolyFunc * param,int vectorlength);
void LegendrePCoefficient(PolyFunc * target, LegendreP * param);
//GSL trifles
void gsl_vector_complex_convert(gsl_vector * source, gsl_vector_complex * target, int length);
void gsl_matrix_complex_convert(gsl_matrix * source, gsl_matrix_complex * target, int rows, int columns);
void gsl_vector_poly_convert(PolyFunc * target,gsl_vector * source, int vectorlength);
void gsl_vector_complex_extract(gsl_vector_complex * source, gsl_vector * real, gsl_vector * imag, int length);
void gsl_matrix_complex_extract(gsl_vector_complex * source, gsl_matrix * real,gsl_matrix * imag, int rows, int columns);
void gsl_vector_complex_combine(gsl_vector * real, gsl_vector * imag, gsl_vector_complex * target);
void gsl_matrix_complex_combine(gsl_matrix * real,gsl_matrix * imag, gsl_matrix_complex * target);
void gsl_matrix_diag(gsl_matrix * target, gsl_vector * diag, int length);
void gsl_matrix_complex_diag(gsl_matrix_complex * target, gsl_vector_complex * diag, int length);
void gsl_matrix_mul(gsl_matrix * A, gsl_matrix *B, gsl_matrix * Result,int Acolumn,int Arow,int Bcolumn);
void gsl_matrix_complex_mul(gsl_matrix_complex * A, gsl_matrix_complex *B, gsl_matrix_complex * Result,int Acolumn,int Arow,int Bcolumn);
double gsl_vector_inner_product(gsl_vector * A, gsl_vector * B,int length);
gsl_complex gsl_vector_complex_product(gsl_vector_complex * A, gsl_vector_complex * B, int length);
gsl_complex gsl_vector_complex_inner_product(gsl_vector_complex * A, gsl_vector_complex * B, int length);
void gsl_vector_transform(gsl_vector * vec,gsl_matrix * trf,int length);
void gsl_vector_complex_transform(gsl_vector_complex * vec, gsl_matrix_complex * trf,int length);
void gsl_matrix_unitmatrix(gsl_matrix * m,int length);
void gsl_matrix_complex_unitmatrix(gsl_matrix_complex * m,int length);
void gsl_vector_complex_conjugate(gsl_vector_complex * v, int length);
void gsl_matrix_complex_conjugate(gsl_matrix_complex * m, int rows, int columns);
void gsl_vector_poly_convert(PolyFunc * target,gsl_vector * source, int vectorlength); | {
"alphanum_fraction": 0.7409290096,
"avg_line_length": 31.3461538462,
"ext": "h",
"hexsha": "2e72d039fb7e61285b1283c2655ea4bed90315a3",
"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": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Walter-Feng/HomebrewLib",
"max_forks_repo_path": "FunctionLib.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43",
"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": "Walter-Feng/HomebrewLib",
"max_issues_repo_path": "FunctionLib.h",
"max_line_length": 305,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "4ba1f21a03e63155a7cd11336b1b588beb2d9e43",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Walter-Feng/HomebrewLib",
"max_stars_repo_path": "FunctionLib.h",
"max_stars_repo_stars_event_max_datetime": "2019-05-27T12:45:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-27T12:45:50.000Z",
"num_tokens": 1391,
"size": 5705
} |
/*
* Simultaneous ML fitting of N 3D Gaussian kernels against a volumetric image
* MATLAB interface in df_mlfitN.c
*
* TODO:
* - how to handle background, still as a constant over the
* patch?
* - bg not handled yet.
*
*/
#include <assert.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_statistics.h>
#include "blit3.h"
#include "mlfit.h"
#ifndef verbose
#define verbose 1
#endif
// When low on bugs, uncomment the following lines for speed
// Try with valgrind and cmocka first ...
//
// replace gsl_vector_get(v,i) by v->data[i*v->stride]
// #define GSL_RANGE_CHECK_OFF
// Globals
uint32_t maxIterations = 5000;
double convCriteria = 1e-6;
// Headers
int localizeDot(double *, size_t, double *, double *);
int localize(double *, size_t, size_t, size_t, double *, size_t, size_t, double *);
double matrix_get(double * , size_t, size_t, size_t, double *);
double my_f (const gsl_vector *, void *);
int unit_tests(void);
// Optimization constants
typedef struct {
double * V; // Volumetric image
double * W; // Temporary space for model during iterations
double * D; // dots, x,y,z, nphot, sigmax, sigmay, sigmaz
size_t Vm, Vn, Vp;
size_t Dm, Dn;
double * bg;
} optParams;
double my_f (const gsl_vector *v, void *params)
// The function to optimize. mlsimplex controls/varies the variables
// in v. params are to set up the context
{
optParams *p = (optParams *) params;
// Size of volumetric image
const size_t Vm = p->Vm; // Size of image
const size_t Vn = p->Vn;
const size_t Vp = p->Vp;
const size_t Dn = p->Dn; // number of dots
const size_t Dm = p->Dm; // and number of features
double * D = p->D;
const double * restrict V = p->V; // Volumetric data to fit against
double * W = p->W; // Pre allocated memory for the model
double * bg = p->bg;
#if verbose > 0
printf("-> my_f, %d dots\n", (int) Dn);
#endif
// Get the other parameters ...
double photsum = 0;
// Copy the cordinates and nphot at the current iteration to D
for(size_t dd = 0; dd<Dn; dd++)
{
#if verbose > 0
printf("%lu: (%.1f %.1f %.1f) %.0f (%.1f %.1f %.1f)\n", dd, D[Dm*dd+0],D[Dm*dd+1], D[Dm*dd+2], D[Dm*dd+3], D[Dm*dd+4], D[Dm*dd+5], D[Dm*dd+6]);
#endif
D[Dm*dd+0] = gsl_vector_get(v, 4*dd+0); // x
D[Dm*dd+1] = gsl_vector_get(v, 4*dd+1); // y
D[Dm*dd+2] = gsl_vector_get(v, 4*dd+2); // z
D[Dm*dd+3] = gsl_vector_get(v, 4*dd+3); // nphot
#if verbose>0
printf("%lu: xyz (%.1f %.1f %.1f) %.0f (%.1f %.1f %.1f)\n", dd, D[Dm*dd+0],D[Dm*dd+1], D[Dm*dd+2], D[Dm*dd+3], D[Dm*dd+4], D[Dm*dd+5], D[Dm*dd+6]);
#endif
if(D[Dm*dd+3]<0)
return INFINITY;
photsum = photsum + D[7*dd+3];
}
#if verbose > 0
printf("phosum of dot parameters: %f\n", photsum);
#endif
// Copy background map to model
memcpy(W, bg, sizeof(double)*Vm*Vn*Vp);
// memset(W, 0, sizeof(double)*Vm*Vn*Vp); // W = 0;
blit3g(W, Vm, Vn, Vp, D, Dn, mid_point,0);
// set bg as well with blit3(g)
for(size_t kk = 0; kk<Vn*Vm*Vp; kk++) {
//W[kk]++;
}
double vmin = 10e99;
double vmax = -10e99;
double wmin = 10e99;
double wmax = -10e99;
double diffmax = 0;
for(size_t kk = 0; kk<Vn*Vm*Vp; kk++)
{
vmin = GSL_MIN(vmin, V[kk]);
vmax = GSL_MAX(vmax, V[kk]);
wmin = GSL_MIN(wmin, W[kk]);
wmax = GSL_MAX(wmax, W[kk]);
diffmax = GSL_MAX(diffmax, fabs(V[kk]-W[kk]));
}
#if verbose>0
printf("V -- min: %f max %f\n", vmin, vmax);
printf("W -- min: %f max %f\n", wmin, wmax);
printf("diffmax: %f\n", diffmax);
#endif
/*
* from LL2PG.m
* model = x(3)+x(4)*gaussianInt2([x(1), x(2)], x(5), (size(patch, 1)-1)/2);
* mask = disk2d((size(patch,1)-1)/2);
* %L = -sum(sum(-(patch-model).^2./model - .5*log(model)));
* L = -sum(sum(mask.*(-(patch-model).^2./model - .5*log(model))));
*/
double E = 0;
for (size_t kk=0; kk<Vm*Vn*Vp; kk++) {
//E+= (V[kk]-W[kk])*(V[kk]-W[kk])/V[kk] - .5*log(W[kk]);
E+= (V[kk]-W[kk])*(V[kk]-W[kk]);
}
// E = -E;
/* Quadratic
* for (size_t kk=0; kk<Rw*Rw; kk++)
* E+= (GI[kk]-R[kk])*(GI[kk]-R[kk]);
*/
#if verbose >0
printf("E: %f\n", E);
#endif
return E;
}
double matrix_get(double * V, size_t Vm, size_t Vn, size_t Vp, double * D)
// Safely get V(D), i.e. check bounds. Returns 0 if outside
//
{
double x = D[0];
double y = D[1];
double z = D[2];
if(x<0)
return 0;
if(x>Vm-1)
return 0;
if(y<0)
return 0;
if(y>Vn-1)
return 0;
if(z<0)
return 0;
if(z>Vp-1)
return 1;
size_t pos = (size_t) nearbyint(x) + nearbyint(y)*Vm + nearbyint(z)*Vm*Vn;
assert(pos<Vm*Vn*Vp);
return V[pos];
}
int localize(double * V, size_t Vm, size_t Vn, size_t Vp,
double * D, size_t Dm, size_t Dn, double * F)
// Localization for a dot roughly centered in V of size Vm x Vm
// D[0], D[1], D[3] are the global coordinates of the dot
// F are the fitted coordinates
{
// avoid crashing matlab
gsl_set_error_handler_off();
#if verbose > 0
printf("-> Localize\n");
printf("V: %lu %lu %lu\n", Vm, Vn, Vp);
printf("D: %lu %lu\n", Dm, Dn);
#endif
assert(Dm == 7); // x y z nphot sigmax sigmay sigmaz
// Non-optimized parameters
optParams par;
par.V = V;
par.Vm = Vm;
par.Vn = Vn;
par.Vp = Vp;
par.Dn = Dn;
par.Dm = Dm;
par.W = malloc(Vm*Vn*Vp*sizeof(double));
assert(par.W != NULL);
par.D = D;
par.bg = malloc(Vm*Vn*Vp*sizeof(double));
#if verbose > 0
printf("Estimating local background\n");
#endif
// Estimating a constant from the surroundings of the first dot
// printf("Vm: %lu %Vn: %lu Vp: %lu, D: %f %f %f\n", Vm, Vn, Vp, D[0], D[1], D[2]);
double bg = estimateBGV(V, Vm, Vn, Vp, D);
#if verbose>0
printf("Background estimated to %f\n", bg);
#endif
printf("Background estimated to %f\n", bg);
for(size_t kk=0; kk<Vm*Vn*Vp; kk++)
par.bg[kk] = bg;
const gsl_multimin_fminimizer_type *T =
gsl_multimin_fminimizer_nmsimplex2;
gsl_multimin_fminimizer *s = NULL;
gsl_vector *ss, *x;
gsl_multimin_function minex_func;
size_t iter = 0;
int status;
double size;
/* Starting point */
#if verbose > 0
printf("Setting up starting vector\n");
#endif
const int nf = 4; // # of features to be optimized: x, y, z, nphot
int nParameters = nf*Dn;
x = gsl_vector_alloc (nParameters);
for(size_t dd = 0; dd<Dn; dd++)
{
gsl_vector_set(x, dd*nf+0, D[dd*Dm+0]); // x position
gsl_vector_set(x, dd*nf+1, D[dd*Dm+1]); // y position
gsl_vector_set(x, dd*nf+2, D[dd*Dm+2]); // z position
// number of photons
// Since the blitting is scaled by the central pixel, the number
// of photons can be estimated as the central value of each peak -
// background from the surrounding
double nphot = gsl_max(0, matrix_get(V, Vm, Vn, Vp, D+ dd*Dm)-par.bg[0]);
printf("nphot: %f\n", nphot);
gsl_vector_set(x, dd*nf+3, nphot);
}
#if verbose > 0
printf("Setting up initial step sizes\n");
#endif
/* Set initial step sizes */
ss = gsl_vector_alloc(nParameters);
gsl_vector_set_all(ss, 0.01);
for(size_t dd = 0; dd<Dn; dd++)
{
gsl_vector_set(ss, dd*nf+3, 5); // Number of photons
}
#if verbose > 0
printf("Testing the fitting with the initial data\n");
#endif
my_f(x,(void*) &par);
/* Initialize method and iterate */
minex_func.n = nParameters;
minex_func.f = my_f;
minex_func.params = ∥
#if verbose > 0
printf("Allocating for the solver\n");
#endif
s = gsl_multimin_fminimizer_alloc (T, nParameters);
#if verbose > 0
printf("Initializing solver\n");
#endif
gsl_multimin_fminimizer_set (s, &minex_func, x, ss);
do
{
iter++;
#if verbose>0
printf("----------------------------- Iteration: %lu\n", iter);
#endif
status = gsl_multimin_fminimizer_iterate(s);
if (status)
break;
size = gsl_multimin_fminimizer_size(s);
status = gsl_multimin_test_size(size, convCriteria);
if (status == GSL_SUCCESS)
{
#if verbose > 0
printf ("converged to minimum at\n");
printf ("%5lu x:%10.3e y:%10.3e z:%10.3e NP:%6.1f f() = %7.3f size = %10.3e\n",
iter,
gsl_vector_get (s->x, 0),
gsl_vector_get (s->x, 1),
gsl_vector_get (s->x, 2),
gsl_vector_get (s->x, 3),
s->fval, size);
#endif
}
}
while (status == GSL_CONTINUE && iter < maxIterations);
for(size_t dd = 0; dd<Dn; dd++)
{
F[5*dd+0] = gsl_vector_get (s->x, nf*dd+0); // x
F[5*dd+1] = gsl_vector_get (s->x, nf*dd+1); // y
F[5*dd+2] = gsl_vector_get (s->x, nf*dd+2); // z
F[5*dd+3] = gsl_vector_get (s->x, nf*dd+3); // nphot
F[5*dd+4] = status; // status
}
gsl_vector_free(x);
gsl_vector_free(ss);
gsl_multimin_fminimizer_free (s);
free(par.W);
free(par.bg);
return status;
}
#ifndef _MAIN
#define _MAIN
int unit_tests(){
double * V; // image
int Vm = 102; int Vn = 107; int Vp = 60;
double * D; // list of dots
size_t Dm = 7; // number of features of the dots
size_t Dn = 10; // number of dots
double * F; // fitted dots
printf("Image size: %dx%dx%d\n", Vm, Vn, Vp);
printf("Localizing %lu dots\n", Dn);
V = malloc(Vm*Vn*Vp*sizeof(double));
D = malloc(Dm*Dn*sizeof(double));
F = malloc(5*Dn*sizeof(double));
// Initialize the data
for(int kk=0; kk<Vm*Vn*Vp; kk++)
V[kk] = rand_range(2,9);
for(uint32_t kk=0; kk<Dn; kk++)
{
size_t pos = kk*Dm;
D[pos] = rand_range(6, Vm-7);
D[pos+1] = rand_range(6, Vn-7);
D[pos+2] = rand_range(6, Vp-7);
D[pos+3] = 1000;
D[pos+4] = 1.2;
D[pos+5] = 1.2;
D[pos+6] = 1.4;
if(D[pos] < 6)
D[pos] = 6;
if(D[pos+1] < 6)
D[pos+1] = 6;
if(D[pos+2] < 6)
D[pos+2] = 6;
#if verbose > 0
printf("D %03d %f %f %f\n", kk, D[pos], D[pos+1], D[pos+2]);
#endif
}
for(uint32_t kk=0; kk<Dn; kk++)
{
size_t pos = nearbyint(D[kk*7]) + nearbyint(D[kk*7+1])*Vm + nearbyint(D[kk*7+2])*Vm*Vn;
assert(pos<(size_t) Vm*Vn*Vp);
assert(pos>0);
V[pos] = 5;
}
// Run the optimization
localize(V, Vm, Vn, Vp, D, Dm, Dn, F);
// In next version, also supply clustering information
#if verbose >0
for(size_t kk = 0; kk<Dm; kk++)
{
size_t Dpos = kk*7;
size_t Fpos = kk*5;
printf("%6lu (%f, %f, %f) -> (%f, %f, %f)\n", kk,
D[Dpos], D[Dpos+1], D[Dpos+2],
F[Fpos], F[Fpos+1], F[Fpos+2]);
}
#endif
free(F);
free(D);
free(V);
return 0;
}
int main(int argc, char ** argv)
// For testing, not used any more, see the MATLAB interface in
// df_mlfit.c
{
printf("%s\n", argv[0]);
if(argc == 1)
return unit_tests();
return 0;
}
#endif
| {
"alphanum_fraction": 0.5878359528,
"avg_line_length": 25.2417840376,
"ext": "c",
"hexsha": "5b9b3227349a6f10925df2d6ae24dbdd43bdb80c",
"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": "8fe0ab3610ff5473bccbac169795a0d1b72c1938",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "elgw/dotter",
"max_forks_repo_path": "common/mex/mlfitN.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938",
"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": "elgw/dotter",
"max_issues_repo_path": "common/mex/mlfitN.c",
"max_line_length": 159,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8fe0ab3610ff5473bccbac169795a0d1b72c1938",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "elgw/dotter",
"max_stars_repo_path": "common/mex/mlfitN.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-15T08:20:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-15T08:20:13.000Z",
"num_tokens": 3943,
"size": 10753
} |
#include <gsl/gsl_math.h>
#include <gsl/gsl_cblas.h>
#include "cblas.h"
void
cblas_zgeru (const enum CBLAS_ORDER order, const int M, const int N,
const void *alpha, const void *X, const int incX, const void *Y,
const int incY, void *A, const int lda)
{
#define BASE double
#include "source_geru.h"
#undef BASE
}
| {
"alphanum_fraction": 0.6725663717,
"avg_line_length": 24.2142857143,
"ext": "c",
"hexsha": "d0f4b96d59b7c1eac62faf07dcb6828dc7e8608e",
"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/cblas/zgeru.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/cblas/zgeru.c",
"max_line_length": 77,
"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/cblas/zgeru.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": 101,
"size": 339
} |
/* -*- Mode: c++ -*- */
// copyright (c) 2006-2010 by Christos Dimitrakakis
// <christos.dimitrakakis@gmail.com>
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#ifndef MATRIX_H
#define MATRIX_H
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <exception>
#include <iostream>
#include <stdexcept>
#include <vector>
#include "Vector.h"
#include "real.h"
//#include <atlas/cblas.h>
#undef REFERENCE_ACCESS
#define ACCURACY_LIMIT 1e-12
/** \brief An n-by-m dimensional matrix.
TODO: Use the BLAS interface for some / most routines.
*/
class Matrix {
public:
/// Check bounds?
enum BoundsCheckingStatus { NO_CHECK_BOUNDS = 0, CHECK_BOUNDS = 1 };
#ifdef NDEBUG
static Matrix Null(int rows, int columns,
enum BoundsCheckingStatus check = NO_CHECK_BOUNDS);
static Matrix Unity(int rows, int columns,
enum BoundsCheckingStatus check = NO_CHECK_BOUNDS);
Matrix(int rows = 1, int columns = 1,
enum BoundsCheckingStatus check = NO_CHECK_BOUNDS);
Matrix(int rows, int columns, real* y,
enum BoundsCheckingStatus check = NO_CHECK_BOUNDS);
explicit Matrix(const Vector& v,
enum BoundsCheckingStatus check_ = NO_CHECK_BOUNDS);
#else
static Matrix Null(int rows, int columns,
enum BoundsCheckingStatus check = CHECK_BOUNDS);
static Matrix Unity(int rows, int columns,
enum BoundsCheckingStatus check = CHECK_BOUNDS);
Matrix(int rows = 1, int columns = 1,
enum BoundsCheckingStatus check = CHECK_BOUNDS);
Matrix(int rows, int columns, real* y,
enum BoundsCheckingStatus check = CHECK_BOUNDS);
explicit Matrix(const Vector& v,
enum BoundsCheckingStatus check_ = CHECK_BOUNDS);
#endif
Matrix(const Matrix& rhs, bool clone = true);
~Matrix();
void Resize(int rows_, int columns_);
Matrix AddRow(const Vector& rhs);
Matrix AddColumn(const Vector& rhs);
Matrix& operator=(const Matrix& rhs);
bool operator==(const Matrix& rhs) const;
bool operator!=(const Matrix& rhs) const;
Matrix operator+(const Matrix& rhs);
Matrix& operator+=(const Matrix& rhs);
Matrix operator-(const Matrix& rhs);
Matrix& operator-=(const Matrix& rhs);
Matrix& operator*=(const real& rhs);
Matrix operator*(const Matrix& rhs);
Matrix operator*(const real& rhs);
Matrix operator+(const real& rhs);
Matrix operator-(const real& rhs);
Matrix operator/(const real& rhs);
/// Matrix inversion (defaults to GSL with LU)
Matrix Inverse(real epsilon = ACCURACY_LIMIT) const {
return GSL_Inverse();
// return Inverse_LU();
}
Vector SVD_Solve(const Vector& b) const;
Matrix GSL_Inverse() const;
/** Matrix inversion using the Cholesky decomposition.
First call Cholesky with accuracy epsilon to obtain $\fL,
L'\f$ such that \f$A = LL'\f$. Then solve for \f$X = A^{-1}\f$:
\f[
LL'X = I,
\f]
by dynamic programming.
*/
Matrix Inverse_Cholesky(real epsilon = ACCURACY_LIMIT) const {
Matrix U = Cholesky(epsilon);
Matrix L(U, false);
L.Transpose();
return Inverse(L, U);
}
/** Matrix inversion using the LU decomposition.
First call LUDecomposition with accuracy epsilon to obtain $\fL,
U\f$ such that \f$A = LU\f$. Then solve for \f$X = A^{-1}\f$:
\f[
LUX = I,
\f]
by dynamic programming.
*/
Matrix Inverse_LU(real epsilon = ACCURACY_LIMIT) const {
real det;
Matrix tmp(*this);
std::vector<Matrix> A = tmp.LUDecomposition(det, epsilon);
return Inverse(A[0], A[1]);
}
Matrix Inverse(const Matrix& L, const Matrix& U) const;
bool isSymmetric() const;
bool isTriangular() const;
bool isUpperTriangular() const;
bool isLowerTriangular() const;
real det() const;
real tr() const;
real L1Norm() const;
real L2Norm() const;
Matrix Multiple(const Matrix& rhs) const;
Matrix Kron(const Matrix& rhs) const;
real ColumnSum(int c) const;
real RowSum(int r) const;
real compute_det_triangular() const;
real gaussian_elimination_forward(real epsilon = ACCURACY_LIMIT);
std::vector<Matrix> QRDecomposition() const;
std::vector<Matrix> LUDecomposition(real& determinant,
real epsilon = ACCURACY_LIMIT);
Matrix Cholesky(real epsilon = ACCURACY_LIMIT) const;
void Cholesky(Matrix& chol, real epsilon = ACCURACY_LIMIT) const;
void Clear();
void Transpose();
Vector getColumn(int c) const;
Vector getRow(int r) const;
void setColumn(int c, const Vector& x);
void setRow(int r, const Vector& x);
void SortRow(int r);
void SortColumn(int r);
int Rows() const;
int Columns() const;
Vector Vec() const;
void Vec(const Vector& x);
Vector RowMax() const;
Vector ColumnMax() const;
Vector RowMin() const;
Vector ColumnMin() const;
real& operator()(int i, int j);
const real& operator()(int i, int j) const;
void print(FILE* f) const;
friend Matrix operator*(const real& lhs, const Matrix& rhs);
friend Matrix operator*(const Vector& lhs, const Matrix& rhs);
friend Vector operator*(const Matrix& lhs, const Vector& rhs);
protected:
int rows; ///< number of rows in the matrix
int columns; ///< number of columns in the matrix
real* x; ///< data
#ifdef REFERENCE_ACCESS
real** x_list; ///< data pointers
void MakeReferences();
#endif
const enum BoundsCheckingStatus checking_bounds;
bool transposed;
bool clear_data;
const real& qGet(int i, int j);
void qSet(int i, int j, real v);
};
Matrix operator*(const real& lhs, const Matrix& rhs);
Matrix operator*(const Vector& lhs, const Matrix& rhs);
Vector operator*(const Matrix& lhs, const Vector& rhs);
real Mahalanobis2(const Vector& x, const Matrix& A, const Vector& y);
/// Kronecker product
inline Matrix Kron(const Matrix& lhs, const Matrix& rhs) {
return lhs.Kron(rhs);
}
inline Matrix OuterProduct(const Vector& lhs, const Vector& rhs) {
Matrix R(lhs.n, rhs.n);
MatrixProduct(lhs, rhs, R);
return R;
}
Matrix Transpose(const Matrix& rhs);
/// In-place transpose matrix
inline void Matrix::Transpose() { transposed = !transposed; }
inline int Matrix::Rows() const {
if (transposed) {
return columns;
}
return rows;
}
inline int Matrix::Columns() const {
if (transposed) {
return rows;
}
return columns;
}
inline real& Matrix::operator()(int i, int j) {
if (transposed) {
int tmp = i;
i = j;
j = tmp;
}
if (checking_bounds) {
if (i < 0 || j < 0 || i >= rows || j >= columns) {
fprintf(stderr, "bad access: (%d, %d) on a %d x %d matrix\n", i, j, rows,
columns);
fflush(stderr);
throw std::out_of_range("matrix index out of range");
}
}
#ifdef REFERENCE_ACCESS
return x_list[i][j];
#else
return x[i * columns + j];
#endif
}
inline const real& Matrix::operator()(int i, int j) const {
if (transposed) {
int tmp = i;
i = j;
j = tmp;
}
if (checking_bounds) {
if (i < 0 || j < 0 || i >= rows || j >= columns) {
fprintf(stderr, "bad access: (%d, %d) on a %d x %d matrix\n", i, j, rows,
columns);
fflush(stderr);
throw std::out_of_range("matrix index out of range");
}
}
#ifdef REFERENCE_ACCESS
return x_list[i][j];
#else
return x[i * columns + j];
#endif
}
#if 0
inline const real& Matrix::qGet(int i, int j) {
#ifdef REFERENCE_ACCESS
return x_list[i][j];
#else
return x[i * columns + j];
#endif
}
inline void Matrix::qSet(int i, int j, real v) {
#ifdef REFERENCE_ACCESS
x_list[i][j] = v;
#else
x[i * columns + j] = v;
#endif
}
#endif
#endif
| {
"alphanum_fraction": 0.6319951338,
"avg_line_length": 29.5683453237,
"ext": "h",
"hexsha": "1e907875c8c4681aa5b38d42c1d47b81767bace3",
"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": "6b303e49017f8054f43c6c840686fcc632205e4e",
"max_forks_repo_licenses": [
"OLDAP-2.3"
],
"max_forks_repo_name": "litlpoet/beliefbox",
"max_forks_repo_path": "src/core/Matrix.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6b303e49017f8054f43c6c840686fcc632205e4e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"OLDAP-2.3"
],
"max_issues_repo_name": "litlpoet/beliefbox",
"max_issues_repo_path": "src/core/Matrix.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6b303e49017f8054f43c6c840686fcc632205e4e",
"max_stars_repo_licenses": [
"OLDAP-2.3"
],
"max_stars_repo_name": "litlpoet/beliefbox",
"max_stars_repo_path": "src/core/Matrix.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2091,
"size": 8220
} |
#pragma once
#include <type_traits>
#include <vector>
#include <gsl-lite/gsl-lite.hpp>
namespace thrustshift {
/*! \brief Make multiple spans from a range of objects which contain ranges.
*
* \param r
* \param get_range This functor must **not** return a copy of any object
*
* ```cpp
* struct S {
*
* std::vector<int> v;
* };
* ...
*
* std::vector<S> ss;
* // fill ss
*
* //// WRONG
* auto spans_with_invalid_ptrs = make_spans_from_ranges(ss, [](const auto& e) { return e.v; });
*
* //// CORRECT
* auto spans = make_spans_from_ranges(ss, [](const auto& e) { return gsl_lite::make_span(e.v); });
* ```
*
* The wrong lambda is returning a copy of member vector `v`, which is then deallocated.
*
*/
template <class T, class RangeOfRanges, class GetRangeCallback>
std::vector<gsl_lite::span<T>> make_spans_from_ranges(
RangeOfRanges&& r,
GetRangeCallback&& get_range) {
std::vector<gsl_lite::span<T>> spans(r.size());
for (size_t i = 0; i < spans.size(); ++i) {
spans[i] =
gsl_lite::make_span(get_range(r[i]).data(), get_range(r[i]).size());
}
return spans;
}
template <class T, class RangeOfRanges>
std::vector<gsl_lite::span<T>> make_spans_from_ranges(RangeOfRanges&& r) {
auto get_range = [](auto& c) { return gsl_lite::make_span(c); };
return make_spans_from_ranges<T>(std::forward<RangeOfRanges>(r), get_range);
}
template <class T, class RangeOfPtrs>
std::vector<gsl_lite::span<T>> make_spans_from_ptrs(RangeOfPtrs&& r, size_t N) {
std::vector<gsl_lite::span<T>> spans(r.size());
for (size_t i = 0; i < spans.size(); ++i) {
spans[i] = gsl_lite::make_span(r[i].get(), N);
}
return spans;
}
template <typename T>
gsl_lite::span<T> subtract(gsl_lite::span<T>& pool, size_t size_of_new_span) {
gsl_Expects(pool.size() >= size_of_new_span);
auto piece = pool.first(size_of_new_span);
pool = pool.subspan(size_of_new_span);
return piece;
}
} // namespace thrustshift
| {
"alphanum_fraction": 0.6690647482,
"avg_line_length": 27.0277777778,
"ext": "h",
"hexsha": "5575027af1769917a14da2a250db544e7aa37830",
"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": "763805f862e3121374286c927dd6949960bffb84",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pauleonix/thrustshift",
"max_forks_repo_path": "include/thrustshift/span-utility.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pauleonix/thrustshift",
"max_issues_repo_path": "include/thrustshift/span-utility.h",
"max_line_length": 100,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pauleonix/thrustshift",
"max_stars_repo_path": "include/thrustshift/span-utility.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z",
"num_tokens": 559,
"size": 1946
} |
/******************************************\
* OpenMP/SSE/BLAS Optimized Matrix Library *
* *
* by *
* Elliott Forney *
* 3.9.2010 *
\******************************************/
/*
* Libraries
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
// cblas
#include <cblas.h>
// OpenMP
#include <omp.h>
// SSE 4.1 intrinsics
#include <smmintrin.h>
// SSE 2 intrinsics
// #include <pmmintrin.h>
//
#include "errcheck.h"
#include "matrix.h"
/*
* Macros
*/
//** Debugging level
#define DEBUG 0
//** Initialization
// max number of chars per line in input table
#define line_buff_size 1024
//** Access
// row major indexing
// expects stride and data to be set
#define data_at(r,c) data[r*stride+c]
//** Addition/Subtraction
// when number of values in matrix is
// larger than add_lim use big kernel
#define add_lim 10000
//** Transpose
#define trans_lim 22500
//#define trans_tile 64
/*
* Global variables
*/
unsigned rand_state = 8;
/*
* Function prototypes
*/
//
void build_drc(matrix *m);
// sigmoid function
float phi(const float v);
// derivative of sigmoid function given phi(v)
float phi_prime(const float z);
// addition kernel for small matrices
void add_small(float *a, float *b, float *c, const unsigned n);
// addition kernel for big matrices
void add_big(float *m, float *b, float *c, const unsigned n);
// subtraction kernel for small matrices
void sub_small(float *a, float *b, float *c, const unsigned n);
// subtraction kernel for big matrices
void sub_big(float *a, float *b, float *c, const unsigned n);
// pointwise square kernel for small matrices
void sqr_small(float *a, float *b, const unsigned n);
// pointwise square kernel for big matrices
void sqr_big(float *a, float *b, const unsigned n);
// scalar multiply kernel for small matrices
void scl_small(float *a, float b, float *c, const unsigned n);
// scalar multiply kernel for big matrices
void scl_big(float *a, float b, float *c, const unsigned n);
// scalar multiplication & pointwise addition kernel for small matrices
void scl_add_small(float *a, float b, float *c, float *d, const unsigned n);
// scalar multiplication & pointwise addition kernel for big matrices
void scl_add_big(float *a, float b, float *c, float *d, const unsigned n);
// pointwise multiplication for small matrices
void pmult_small(float *a, float *b, float *c, const unsigned n);
// pointwise multiplication for big matrices
void pmult_big(float *a, float *b, float *c, const unsigned n);
/*
* Function bodies
*/
// build row-col indices for double index
void build_drc(matrix *m)
{
// not done/needed yet
}
// sigmoid function
float phi(const float v)
{
// recommended by Lecun, find citation!!
const float scl = 2.0f/3.0f;
return 1.7159f * tanh( scl * v );
}
// derivative of sigmoid function given phi(v)
float phi_prime(const float z)
{
const float scl = 2.0f/3.0f;
return scl * (1.7159f - z*z);
}
// addition kernel for small matrices
void add_small(float *a, float *b, float *c, const unsigned n)
{
// pointer to last destination
const float *a_end = a+n;
// loop through each value in destination
while (a < a_end)
{
// four values from b and c into sse registers
__m128 mm_v1 = _mm_load_ps(b);
__m128 mm_v2 = _mm_load_ps(c);
// add our sse vectors
mm_v1 = _mm_add_ps(mm_v1, mm_v2);
// store result into a
_mm_store_ps(a, mm_v1);
// increment pointers by 4
a += 4; b += 4; c += 4;
}
}
// addition kernel for big matrices
void add_big(float *a, float *b, float *c, const unsigned n)
{
unsigned i;
// loop through a, b and c by 4 in parallel
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
// load four values into sse registers
__m128 mm_v1 = _mm_load_ps(b+i); // what if they have different strides!!! :(
__m128 mm_v2 = _mm_load_ps(c+i);
// add our sse vectors
mm_v1 = _mm_add_ps(mm_v1, mm_v2);
// store result into a
_mm_store_ps(a+i, mm_v1);
}
}
// subtraction kernel for small matrices
void sub_small(float *a, float *b, float *c, const unsigned n)
{
const float *a_end = a+n;
while (a < a_end)
{
__m128 mm_v1 = _mm_load_ps(b);
__m128 mm_v2 = _mm_load_ps(c);
mm_v1 = _mm_sub_ps(mm_v1, mm_v2);
_mm_store_ps(a, mm_v1);
a += 4; b += 4; c += 4;
}
}
// subtraction kernel for big matrices
void sub_big(float *a, float *b, float *c, const unsigned n)
{
unsigned i;
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
__m128 mm_v1 = _mm_load_ps(b+i);
__m128 mm_v2 = _mm_load_ps(c+i);
mm_v1 = _mm_sub_ps(mm_v1, mm_v2);
_mm_store_ps(a+i, mm_v1);
}
}
// pointwise square kernel for small matrices
void sqr_small(float *a, float *b, const unsigned n)
{
const float *a_end = a+n;
while (a < a_end)
{
__m128 mm_v = _mm_load_ps(b);
mm_v = _mm_mul_ps(mm_v, mm_v);
_mm_store_ps(a, mm_v);
a += 4; b += 4;
}
}
// pointwise square kernel for big matrices
void sqr_big(float *a, float *b, const unsigned n)
{
unsigned i;
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
__m128 mm_v = _mm_load_ps(b+i);
mm_v = _mm_mul_ps(mm_v, mm_v);
_mm_store_ps(a+i, mm_v);
}
}
// scalar multiplication kernel for small matrices
void scl_small(float *a, float b, float *c, const unsigned n)
{
const float *a_end = a+n;
__m128 mm_s = _mm_set1_ps(b);
while (a < a_end)
{
__m128 mm_v = _mm_load_ps(c);
mm_v = _mm_mul_ps(mm_s, mm_v);
_mm_store_ps(a, mm_v);
a += 4; c += 4;
}
}
// scalar multiplication kernel for big matrices
void scl_big(float *a, float b, float *c, const unsigned n)
{
unsigned i;
const __m128 mm_s = _mm_set1_ps(b);
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
__m128 mm_v = _mm_load_ps(c+i);
mm_v = _mm_mul_ps(mm_s, mm_v);
_mm_store_ps(a+i, mm_v);
}
}
// scalar multiplication & pointwise addition kernel for small matrices
void scl_add_small(float *a, float b, float *c, float *d, unsigned n)
{
const float *a_end = a+n;
__m128 mm_s = _mm_set1_ps(b);
while (a < a_end)
{
__m128 mm_v1 = _mm_load_ps(c);
__m128 mm_v2 = _mm_load_ps(d);
mm_v1 = _mm_mul_ps(mm_s, mm_v1);
mm_v1 = _mm_add_ps(mm_v1, mm_v2);
_mm_store_ps(a, mm_v1);
a += 4; c += 4; d += 4;
}
}
// scalar multiplication & pointwise addition kernel for big matrices
void scl_add_big(float *a, float b, float *c, float *d, unsigned n)
{
unsigned i;
const __m128 mm_s = _mm_set1_ps(b);
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
__m128 mm_v1 = _mm_load_ps(c+i);
__m128 mm_v2 = _mm_load_ps(d+i);
mm_v1 = _mm_mul_ps(mm_s, mm_v1);
mm_v1 = _mm_add_ps(mm_v1, mm_v2);
_mm_store_ps(a+i, mm_v1);
}
}
// pointwise multiplication kernel for small matrices
void pmult_small(float *a, float *b, float *c, const unsigned n)
{
// pointer to last destination
const float *a_end = a+n;
// loop through each value in destination
while (a < a_end)
{
// four values from b and c into sse registers
__m128 mm_v1 = _mm_load_ps(b);
__m128 mm_v2 = _mm_load_ps(c);
// mult our sse vectors
mm_v1 = _mm_mul_ps(mm_v1, mm_v2);
// store result into a
_mm_store_ps(a, mm_v1);
// increment pointers by 4
a += 4; b += 4; c += 4;
}
}
// pointwise multiplication kernel for big matrices
void pmult_big(float *a, float *b, float *c, const unsigned n)
{
unsigned i;
// loop through a, b and c by 4 in parallel
#pragma omp parallel for
for (i = 0; i < n; i += 4)
{
// load four values into sse registers
__m128 mm_v1 = _mm_load_ps(b+i);
__m128 mm_v2 = _mm_load_ps(c+i);
// mult our sse vectors
mm_v1 = _mm_mul_ps(mm_v1, mm_v2);
// store result into a
_mm_store_ps(a+i, mm_v1);
}
}
/*
* External function bodies
*/
//** Initialization & Destruction
// initialize matrix m of size r by c
void matrix_init(matrix *m, const unsigned r, const unsigned c)
{
// set matrix dimensions
m->r = r;
m->c = c;
// zero pad to nearest mult of 64, lcm 4 for sse, 64 for trans
// leave one extra row/col to append bias terms
// m->rstride = r + (64 - (r % 64)); // lcm(trans_tile, 4)
// m->cstride = c + (64 - (c % 64));
// 64 tiles speeds up transpose but hurts everything else
m->rstride = r + (4 - (r % 4));
m->cstride = c + (4 - (c % 4));
// allocate space for matrix, 16 byte aligned
m->cpu_data = (float*)_mm_malloc((m->rstride)*(m->cstride)*
sizeof(float), 16);
if (m->cpu_data == NULL)
errcheck_cpu();
// allocate space for last column holder
m->cv = (float*)malloc((m->r)*sizeof(float));
if (m->cv == NULL)
errcheck_cpu();
// zero out data for padding
memset(m->cpu_data, '\0', (m->rstride)*(m->cstride)*sizeof(float));
memset(m->cv, '\0', (m->r)*sizeof(float));
// build row-col indices
build_drc(m);
}
// initialize matrix m from ascii table
void matrix_init_file(matrix *m, char *file_name)
{
// will need to do this dynamically if
// we ever want to handle big tables!!!
float table_data[line_buff_size][line_buff_size];
unsigned r = 0, c = 0;
// open file & setup input buffer
FILE *table = fopen(file_name, "r");
char line_buffer[line_buff_size];
// check if we were even able to open table file
if (file_name == NULL)
errcheck_cpu();
// buckle-up, don't drink and code
memset(table_data, '\0', line_buff_size*line_buff_size*sizeof(float));
// for each line in table (row)
while (fgets(line_buffer, line_buff_size, table))
{
if (DEBUG > 5)
printf("line buffer: %s\n", line_buffer);
// set up string tokenizer on input buffer
char *cur_val = strtok(line_buffer, " "); // Note reentrant or thread safe!!
// don't increment num rows on blank line
if (cur_val != NULL)
{
c = 0; // new row, reset col counter
// for each token (col)
while (cur_val != NULL)
{
// convert from char to float
table_data[r][c] = atof(cur_val);
if (DEBUG > 5)
printf("converting %d %d %f\n", r, c, table_data[r][c]);
// get next token
cur_val = strtok(NULL, " ");
++c; // increment num cols
}
++r; // increment num rows
}
}
// close file descriptor
fclose(table);
// initialize m
matrix_init(m, r, c);
// setup for data_at
unsigned mr, mc;
float *data = m->cpu_data;
const unsigned stride = m->cstride;
// loop through collected data and put into m
for (mr = 0; mr < r; ++mr)
for (mc = 0; mc < c; ++mc)
data_at(mr,mc) = table_data[mr][mc];
}
// load zeros into matrix m
void matrix_load_zero(matrix m)
{
float *data = m.cpu_data;
const float *data_end = data + (m.rstride*m.cstride);
// loop through all values and set to zero
// memset?
while (data < data_end)
*(data++) = 0.0f;
}
// load values from an array
void matrix_load_array(matrix m, float *v)
{
unsigned r, c, i = 0;
// set data and stride for data_at
float *data = m.cpu_data;
const unsigned stride = m.cstride;
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
data_at(r,c) = v[i++];
}
// load values from the random uniform distribution
void matrix_load_runif(matrix m, float min, float max)
{
unsigned r, c;
// set data and stride for data_at
float *data = m.cpu_data;
const unsigned stride = m.cstride;
const float range = max - min;
// needs work to be multithreaded!
// set each non-padding value from random uniform
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
data_at(r,c) = rand_r(&rand_state) * range / RAND_MAX + min;
}
void matrix_load_testa(matrix m, unsigned n)
{
unsigned r, c;
// set data and stride for data_at
float *data = m.cpu_data;
const unsigned stride = m.cstride;
#pragma omp parallel for private(c)
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
//data_at(r,c) = (float)n * (float)r*c;
data_at(r,c) = (float)n;
}
void matrix_load_testb(matrix m)
{
unsigned r, c;
// set data and stride for data_at
float *data = m.cpu_data;
const unsigned stride = m.cstride;
#pragma omp parallel for private(c)
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
//data_at(r,c) = (float)r;
data_at(r,c) = 1.0f;
}
void matrix_load_testc(matrix m)
{
unsigned r, c;
// set data and stride for data_at
float *data = m.cpu_data;
const unsigned stride = m.cstride;
#pragma omp parallel for private(c)
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
//data_at(r,c) = (float)c;
data_at(r,c) = 1.0f;
}
// copy values to an array
void matrix_unload_array(matrix m, float *v)
{
unsigned r, c, i = 0;
float *data = m.cpu_data;
const unsigned stride = m.cstride;
for (r = 0; r < m.r; ++r)
for (c = 0; c < m.c; ++c)
v[i++] = data_at(r,c);
}
// write values to a file
void matrix_unload_file(matrix m, char *file_name)
{
unsigned r, c;
float *data = m.cpu_data;
const unsigned stride = m.cstride;
// open file for writing
FILE *table = fopen(file_name, "w");
// check if we were even able to open table file
if (file_name == NULL)
errcheck_cpu();
for (r = 0; r < m.r; ++r)
{
for (c = 0; c < m.c-1; ++c)
fprintf(table, "%.16f ", data_at(r,c));
fprintf(table, "%.16f\n", data_at(r,c));
}
fclose(table);
}
// destroy matrix m
void matrix_dest(matrix *m)
{
// free matrix data
free(m->cpu_data);
free(m->cv);
// free row/col indices
//free(m->drc);
// set everything to zero for safety
m->r = 0;
m->c = 0;
m->rstride = 0;
m->cstride = 0;
m->cpu_data = NULL;
}
//** Synchronization
// wait for asynchronous calls to finish
void matrix_wait()
{
// nada
}
//** Addition/Subtraction
// a = b + c
void matrix_add(matrix a, matrix b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (a.r != b.r) || (b.r != c.r) ) {
fprintf(stderr, __FILE__ " %d: "
"Rows don't match for addition!\n", __LINE__);
exit(CPU_ERROR);
}
if ( (a.c != b.c) || (b.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Cols don't match for addition!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
/* naive
unsigned i;
float *aval = a.cpu_data;
float *bval = b.cpu_data;
float *cval = c.cpu_data;
for (i = 0; i < n; ++i)
aval[i] = bval[i] + cval[i]; */
if (n < add_lim)
add_small(a.cpu_data, b.cpu_data, c.cpu_data, n);
else
add_big(a.cpu_data, b.cpu_data, c.cpu_data, n);
}
// a = b - c
void matrix_sub(matrix a, matrix b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (a.r != b.r) || (b.r != c.r) ) {
fprintf(stderr, __FILE__ " %d: "
"Rows don't match for subtraction!\n", __LINE__);
exit(CPU_ERROR);
}
if ( (a.c != b.c) || (b.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Cols don't match for subtraction!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
if (n < add_lim)
sub_small(a.cpu_data, b.cpu_data, c.cpu_data, n);
else
sub_big(a.cpu_data, b.cpu_data, c.cpu_data, n);
}
//** Multiplication
// a = b * c
void matrix_mult(matrix a, matrix b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (b.c != c.r) || (a.r != b.r) || (a.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Dimensions don't match for multiplication!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
// use cblas for multiplication, not going to beat this.. for now ;)
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
b.r, c.c, b.c, 1.0f,
b.cpu_data, b.cstride, c.cpu_data, c.cstride,
0.0f, a.cpu_data, a.cstride);
}
// a = phi(b * c)
void matrix_mult_phi(matrix a, matrix b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (b.c != c.r) || (a.r != b.r) || (a.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Dimensions don't match for mult_phi!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
// use cblas for multiplication, not going to beat this.. for now ;)
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
b.r, c.c, b.c, 1.0f,
b.cpu_data, b.cstride, c.cpu_data, c.cstride,
0.0f, a.cpu_data, a.cstride);
// apply phi
unsigned row, col;
float *adata = a.cpu_data;
const unsigned astride = a.cstride;
// need to optimize small kern and put into functions
if ((a.r*a.cstride) < add_lim)
{
const __m128 mm_s1 = _mm_set1_ps(1.7159f);
const __m128 mm_s2 = _mm_set1_ps(2.0f/3.0f);
for (row = 0; row < a.r; ++row)
for (col = 0; col < a.c; col += 4)
{
unsigned i;
const unsigned base = row*astride+col;
// inside scalar mult
__m128 mm_v = _mm_load_ps(adata+base);
mm_v = _mm_mul_ps(mm_v, mm_s2);
_mm_store_ps(adata+base, mm_v);
// apply tanh
for (i = base; i < base+4; ++i)
adata[i] = tanh(adata[i]);
// outside scalar mult
mm_v = _mm_load_ps(adata+base);
mm_v = _mm_mul_ps(mm_v, mm_s1);
_mm_store_ps(adata+base, mm_v);
}
}
else
{
const __m128 mm_s1 = _mm_set1_ps(1.7159f);
const __m128 mm_s2 = _mm_set1_ps(2.0f/3.0f);
#pragma omp parallel for private(col)
for (row = 0; row < a.r; ++row)
for (col = 0; col < a.c; col += 4)
{
unsigned i;
const unsigned base = row*astride+col;
// inside scalar mult
__m128 mm_v = _mm_load_ps(adata+base);
mm_v = _mm_mul_ps(mm_v, mm_s2);
_mm_store_ps(adata+base, mm_v);
// apply tanh
for (i = base; i < base+4; ++i)
adata[i] = tanh(adata[i]);
// outside scalar mult
mm_v = _mm_load_ps(adata+base);
mm_v = _mm_mul_ps(mm_v, mm_s1);
_mm_store_ps(adata+base, mm_v);
}
}
/*
unsigned i;
#pragma omp parallel for
for (i = 0; i < a.r*a.cstride; ++i)
adata[i] = phi(adata[i]);
*/
}
//** Transpose
// a = b^T
void matrix_trans(matrix a, matrix b)
{
#ifndef NO_ERRCHECK
if ( (a.r != b.c) || (a.c != b.r) ) {
fprintf(stderr, __FILE__ " %d: "
"Source and destination dimensions don't match for transpose!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
unsigned r, c;
float *adata = a.cpu_data;
float *bdata = b.cpu_data;
const unsigned astride = a.cstride;
const unsigned bstride = b.cstride;
// need to seperate into smaller functions
if ((a.r*a.c) < trans_lim)
{
for (r = 0; r < a.r; r += 4)
for (c = 0; c < a.c; c += 4)
{
// load 4x4 tile
float *base = bdata + c*bstride+r;
__m128 mm_v1 = _mm_load_ps(base );
__m128 mm_v2 = _mm_load_ps(base + bstride);
__m128 mm_v3 = _mm_load_ps(base + 2*bstride);
__m128 mm_v4 = _mm_load_ps(base + 3*bstride);
// transpose 4x4 tile
_MM_TRANSPOSE4_PS(mm_v1, mm_v2, mm_v3, mm_v4);
// store 4x4 tile back into a
base = adata + r*astride+c;
_mm_store_ps(base, mm_v1);
_mm_store_ps(base + astride, mm_v2);
_mm_store_ps(base + 2*astride, mm_v3);
_mm_store_ps(base + 3*astride, mm_v4);
}
}
else
{
#pragma omp parallel for private(c)
for (r = 0; r < a.r; r += 4)
for (c = 0; c < a.c; c += 4)
{
// load 4x4 tile
float *base = bdata + c*bstride+r;
__m128 mm_v1 = _mm_load_ps(base );
__m128 mm_v2 = _mm_load_ps(base + bstride);
__m128 mm_v3 = _mm_load_ps(base + 2*bstride);
__m128 mm_v4 = _mm_load_ps(base + 3*bstride);
// transpose 4x4 tile
_MM_TRANSPOSE4_PS(mm_v1, mm_v2, mm_v3, mm_v4);
// store 4x4 tile back into a
base = adata + r*astride+c;
_mm_store_ps(base, mm_v1);
_mm_store_ps(base + astride, mm_v2);
_mm_store_ps(base + 2*astride, mm_v3);
_mm_store_ps(base + 3*astride, mm_v4);
}
}
/* tiled version, fast but big tiles hurt everything else
#pragma omp parallel for private(tc,r,c)
for (tr = 0; tr < a.r; tr += trans_tile)
for (tc = 0; tc < a.c; tc += trans_tile)
for (r = tr; r < tr+trans_tile; r += 4)
for (c = tc; c < tc+trans_tile; c += 4)
{
// load 4x4 tile
float *base = bdata + c*bstride+r;
__m128 mm_v1 = _mm_load_ps(base );
__m128 mm_v2 = _mm_load_ps(base + bstride);
__m128 mm_v3 = _mm_load_ps(base + 2*bstride);
__m128 mm_v4 = _mm_load_ps(base + 3*bstride);
// transpose 4x4 tile
_MM_TRANSPOSE4_PS(mm_v1, mm_v2, mm_v3, mm_v4);
// store 4x4 tile back into a
base = adata + r*astride+c;
_mm_store_ps(base, mm_v1);
_mm_store_ps(base + astride, mm_v2);
_mm_store_ps(base + 2*astride, mm_v3);
_mm_store_ps(base + 3*astride, mm_v4);
} */
}
//** Pointwise miscellaneous
// a = b^2
void matrix_sqr(matrix a, matrix b)
{
#ifndef NO_ERRCHECK
if ( (a.r != b.r) || (a.c != b.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Source and destination dimensions don't match for square!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
if (n < add_lim)
sqr_small(a.cpu_data, b.cpu_data, n);
else
sqr_big(a.cpu_data, b.cpu_data, n);
}
// scalar multiplication a = b*c
void matrix_scl(matrix a, float b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (a.r != c.r) || (a.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Source and destination dimensions don't match for scale!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
if (n < add_lim)
scl_small(a.cpu_data, b, c.cpu_data, n);
else
scl_big(a.cpu_data, b, c.cpu_data, n);
}
// scalar multiplication & pointwise addition a = b.*c+d
void matrix_scl_add(matrix a, float b, matrix c, matrix d)
{
#ifndef NO_ERRCHECK
if ( (a.r != c.r) || (a.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Source and destination dimensions don't match for scl_add!\n", __LINE__);
exit(CPU_ERROR);
}
if ( (a.r != d.r) || (a.c != d.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Source and destination dimensions don't match for scl_add!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
if (n < add_lim)
scl_add_small(a.cpu_data, b, c.cpu_data, d.cpu_data, n);
else
scl_add_big(a.cpu_data, b, c.cpu_data, d.cpu_data, n);
}
// pointwise multiplication a = b.*c
void matrix_pmult(matrix a, matrix b, matrix c)
{
#ifndef NO_ERRCHECK
if ( (a.r != b.r) || (b.r != c.r) ) {
fprintf(stderr, __FILE__ " %d: "
"Rows don't match for pmult!\n", __LINE__);
exit(CPU_ERROR);
}
if ( (a.c != b.c) || (b.c != c.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Cols don't match for pmult!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned n = a.r * a.cstride;
if (n < add_lim)
pmult_small(a.cpu_data, b.cpu_data, c.cpu_data, n);
else
pmult_big(a.cpu_data, b.cpu_data, c.cpu_data, n);
}
//
void matrix_phi_prime(matrix a, matrix b)
{
unsigned r, c;
const unsigned astride = a.cstride;
const unsigned bstride = b.cstride;
float *adata = a.cpu_data;
float *bdata = b.cpu_data;
const __m128 mm_s1 = _mm_set1_ps(2.0f/3.0f);
const __m128 mm_s2 = _mm_set1_ps(1.7159f);
// need to optimize small kern and put into functions
if ((a.r*a.cstride) < add_lim)
{
for (r = 0; r < a.r; ++r)
for (c = 0; c < a.c; c += 4)
{
__m128 mm_v1 = _mm_load_ps(bdata + r*bstride+c);
mm_v1 = _mm_mul_ps(mm_v1, mm_v1);
mm_v1 = _mm_sub_ps(mm_s2, mm_v1);
mm_v1 = _mm_mul_ps(mm_s1, mm_v1);
_mm_store_ps(adata + r*astride+c, mm_v1);
}
}
else
{
#pragma omp parallel for private(c)
for (r = 0; r < a.r; ++r)
for (c = 0; c < a.c; c += 4)
{
__m128 mm_v1 = _mm_load_ps(bdata + r*bstride+c);
mm_v1 = _mm_mul_ps(mm_v1, mm_v1);
mm_v1 = _mm_sub_ps(mm_s2, mm_v1);
mm_v1 = _mm_mul_ps(mm_s1, mm_v1);
_mm_store_ps(adata + r*astride+c, mm_v1);
}
}
// const float scl = 2.0f/3.0f;
// return scl * (1.7159f - z*z);
/*
#pragma omp parallel for private(c)
for (r = 0; r < a.r; ++r)
for (c = 0; c < a.c; ++c)
adata[r*astride + c] =
phi_prime(bdata[r*bstride + c]);
*/
}
// a = b .* phi_prime(c)
void matrix_pmult_phi_prime(matrix a, matrix b, matrix c)
{
unsigned i;
float *adata = a.cpu_data;
float *bdata = b.cpu_data;
float *cdata = c.cpu_data;
const __m128 mm_s1 = _mm_set1_ps(2.0f/3.0f);
const __m128 mm_s2 = _mm_set1_ps(1.7159f);
#pragma omp parallel for
for (i = 0; i < a.r*a.cstride; i += 4)
{
__m128 mm_v1 = _mm_load_ps(bdata+i);
__m128 mm_v2 = _mm_load_ps(cdata+i);
mm_v2 = _mm_mul_ps(mm_v2, mm_v2);
mm_v2 = _mm_sub_ps(mm_s2, mm_v2);
mm_v2 = _mm_mul_ps(mm_s1, mm_v2);
mm_v2 = _mm_mul_ps(mm_v1, mm_v2);
_mm_store_ps(adata + i, mm_v2);
}
}
//
void matrix_delta(matrix delta, matrix y, matrix g)
{
unsigned r, c;
#ifndef NO_ERRCHECK
if ( (delta.r != y.r) || (y.r != g.r) ) {
fprintf(stderr, __FILE__ " %d: "
"Rows don't match for delta!\n", __LINE__);
exit(CPU_ERROR);
}
if ( (delta.c != y.c) || (y.c != g.c) ) {
fprintf(stderr, __FILE__ " %d: "
"Cols don't match for delta!\n", __LINE__);
exit(CPU_ERROR);
}
#endif
const unsigned dstride = delta.cstride;
const unsigned gstride = g.cstride;
const unsigned ystride = y.cstride;
float *ddata = delta.cpu_data;
float *gdata = g.cpu_data;
float *ydata = y.cpu_data;
// need to optimize small kern and put into functions
if ((delta.r*delta.cstride) < add_lim)
{
const __m128 mm_s = _mm_set1_ps(2.0f/(g.r*g.c));
for (r = 0; r < delta.r; ++r)
for (c = 0; c < delta.c; c += 4)
{
__m128 mm_v1 = _mm_load_ps(gdata + r*gstride+c);
__m128 mm_v2 = _mm_load_ps(ydata + r*ystride+c);
mm_v1 = _mm_sub_ps(mm_v2, mm_v1);
mm_v1 = _mm_mul_ps(mm_v1, mm_s);
_mm_store_ps(ddata + r*dstride+c, mm_v1);
}
}
else
{
const __m128 mm_s = _mm_set1_ps(2.0f/(g.r*g.c));
#pragma omp parallel for private (c)
for (r = 0; r < delta.r; ++r)
for (c = 0; c < delta.c; c += 4)
{
__m128 mm_v1 = _mm_load_ps(gdata + r*gstride+c);
__m128 mm_v2 = _mm_load_ps(ydata + r*ystride+c);
mm_v1 = _mm_sub_ps(mm_v2, mm_v1);
mm_v1 = _mm_mul_ps(mm_v1, mm_s);
_mm_store_ps(ddata + r*dstride+c, mm_v1);
}
}
/*
const float denom = 2.0f / (g.r*g.c);
#pragma omp parallel for private(c)
for (r = 0; r < delta.r; ++r)
for (c = 0; c < delta.c; ++c)
{
const float gval = gdata[r*gstride + c];
const float yval = ydata[r*ystride + c];
// wow, sse could be used all over here!
ddata[r*dstride + c] =
(yval - gval) * denom;
}
*/
}
//** Combination/Separation
// remove last row of m
void matrix_r0(matrix *m)
{
--(m->r);
float *data = (m->cpu_data)+((m->r)*(m->cstride));
const float *data_end = data + m->c;
while (data < data_end)
*(data++) = 0.0f;
}
// append a row of 1's to m
void matrix_r1(matrix *m)
{
float *data = (m->cpu_data)+((m->r)*(m->cstride));
const float *data_end = data + m->c;
while (data < data_end)
*(data++) = 1.0f;
++(m->r);
}
//** Error measurement
// rmse between values of actual and approx
float matrix_rmse(matrix actual, matrix approx)
{
// if dims don't match throw error!
unsigned r, c;
const unsigned stride = actual.cstride;
const unsigned len = actual.r*actual.c;
float *d1 = actual.cpu_data;
float *d2 = approx.cpu_data;
float err = 0.0f;
// need to use omp, maybe reduction?
for (r = 0; r < actual.r; ++r)
for (c = 0; c < actual.c; ++c)
{
const unsigned i = r*stride+c;
err += (d1[i] - d2[i])*(d1[i] - d2[i]);
}
return sqrt(err/len);
}
// remove and save last col of m
void matrix_c0v(matrix *m)
{
unsigned r;
const unsigned stride = m->cstride;
const unsigned c = --(m->c);
float *data = m->cpu_data;
for (r = 0; r < m->r; ++r)
{
float *cur = data + r*stride+c;
m->cv[r] = *cur;
*cur = 0.0f;
}
}
// restore last col of m
void matrix_cv(matrix *m)
{
unsigned r;
const unsigned stride = m->cstride;
const unsigned c = (m->c)++;
float *data = m->cpu_data;
for (r = 0; r < m->r; ++r)
data[r*stride+c] = m->cv[r];
}
//** Output
// print m to standard out
void matrix_print(matrix m)
{
unsigned r, c;
const unsigned stride = m.cstride;
float *data = m.cpu_data;
// print each value to stdout
for (r = 0; r < m.r; ++r)
{
for (c = 0; c < m.c; ++c)
printf("%f ", data_at(r,c));
printf("\n");
}
}
// print m including padding to standard out
void matrix_print_padded(matrix m)
{
unsigned r, c;
// set data and stride for data_at
const unsigned stride = m.cstride;
float *data = m.cpu_data;
// print each value to stdout
for (r = 0; r < m.rstride; ++r)
{
for (c = 0; c < m.cstride; ++c)
printf("%f ", data_at(r,c));
printf("\n");
}
}
| {
"alphanum_fraction": 0.5875151352,
"avg_line_length": 23.3009404389,
"ext": "c",
"hexsha": "b90d5299087b8c463ea453769a0deb79bbc46efc",
"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": "75028a7e42e4a02460f20f1aa82c289801de1b05",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "idfah/badger",
"max_forks_repo_path": "matrix_cpu/matrix.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "75028a7e42e4a02460f20f1aa82c289801de1b05",
"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": "idfah/badger",
"max_issues_repo_path": "matrix_cpu/matrix.c",
"max_line_length": 90,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "75028a7e42e4a02460f20f1aa82c289801de1b05",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "idfah/badger",
"max_stars_repo_path": "matrix_cpu/matrix.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9605,
"size": 29732
} |
/*
Copyright (C) 2019-2021 Jan BOON (Kaetemi) <jan.boon@kaetemi.be>
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.
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.
*/
/*
Polyverse OÜ base include file for C++.
*/
#pragma once
#ifndef SEV_PLATFORM_H
#define SEV_PLATFORM_H
// Use C math defines for M_PI
#define _USE_MATH_DEFINES
#ifdef _WIN32
// Include Win32.
// Ensure malloc is included before anything else,
// There are some odd macros that may conflict otherwise.
// Include STL algorithm to ensure std::min and std::max
// are used everywhere, instead of min and max macros.
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0600
#ifdef __cplusplus
#define NOMINMAX
#endif /* __cplusplus */
#include <malloc.h>
#ifdef __cplusplus
#include <algorithm>
using std::max;
using std::min;
#endif /* __cplusplus */
#include <Windows.h>
#ifdef _MSC_VER
// #include <codeanalysis\sourceannotations.h>
#endif
#endif /* _WIN32 */
// C++
#ifdef __cplusplus
// Require C++17
#if defined(_MSC_VER) && (!defined(_HAS_CXX17) || !_HAS_CXX17)
static_assert(false, "C++17 is required");
#endif
// Define null, with color highlight
#ifndef null
constexpr decltype(nullptr) null = nullptr;
#define null null
#endif
// Include STL string and allow string literals.
// Always use sv suffix when declaring string literals.
// Ideally, assign them as `constexpr std::string_view`.
#include <string>
#include <string_view>
using namespace std::string_literals;
using namespace std::string_view_literals;
// Include GSL
// auto _ = gsl::finally([&] { delete xyz; });
#include <gsl/util>
// The usual
#include <functional>
// Force inline
#ifdef _MSC_VER
# define SEV_FORCE_INLINE __forceinline
#else
# define SEV_FORCE_INLINE inline __attribute__((always_inline))
#endif
#if defined(_DEBUG) && !defined(NDEBUG)
#define SEV_DEBUG
#else
#define SEV_RELEASE
#endif
// Include debug_break
#include <debugbreak.h>
#define SEV_RELEASE_BREAK() debug_break()
#ifdef SEV_DEBUG
#define SEV_DEBUG_BREAK() debug_break()
#define SEV_ASSERT(cond) do { if (!(cond)) SEV_DEBUG_BREAK(); } while (false)
#define SEV_VERIFY(cond) do { if (!(cond)) SEV_DEBUG_BREAK(); } while (false)
#else
#define SEV_DEBUG_BREAK() do { } while (false)
#define SEV_ASSERT(cond) do { } while (false)
#define SEV_VERIFY(cond) do { cond; } while (false)
#endif
// Library export decl
#ifdef _MSC_VER
# define SEV_DECL_EXPORT __declspec(dllexport)
# define SEV_DECL_IMPORT __declspec(dllimport)
#else
# define SEV_DECL_EXPORT
# define SEV_DECL_IMPORT
#endif
#if defined(SEV_LIB_EXPORT)
#ifdef _MSC_VER
#endif
# define SEV_LIB SEV_DECL_EXPORT
#elif defined(SEV_LIB_STATIC)
# define SEV_LIB
#else
# define SEV_LIB SEV_DECL_IMPORT
#endif
#endif /* __cplusplus */
#endif /* SEV_PLATFORM_H */
/* end of file */
| {
"alphanum_fraction": 0.7678743961,
"avg_line_length": 28.3561643836,
"ext": "h",
"hexsha": "c33021f6b0af5912f7a285f701e29681805971e6",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-14T20:01:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-14T20:01:08.000Z",
"max_forks_repo_head_hexsha": "72cfb0494a1ca5a5a0b637237d82937c8efd670c",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "kaetemi/libsev",
"max_forks_repo_path": "sev/platform.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "72cfb0494a1ca5a5a0b637237d82937c8efd670c",
"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": "kaetemi/libsev",
"max_issues_repo_path": "sev/platform.h",
"max_line_length": 78,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "72cfb0494a1ca5a5a0b637237d82937c8efd670c",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "kaetemi/libsev",
"max_stars_repo_path": "sev/platform.h",
"max_stars_repo_stars_event_max_datetime": "2020-08-16T04:32:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-16T04:32:32.000Z",
"num_tokens": 971,
"size": 4140
} |
//! \file openmc_driver.h
//! Driver to initialize and run OpenMC in stages
#ifndef ENRICO_OPENMC_DRIVER_H
#define ENRICO_OPENMC_DRIVER_H
#include "cell_instance.h"
#include "geom.h"
#include "neutronics_driver.h"
#include "openmc/tallies/tally.h"
#include <gsl/gsl>
#include <mpi.h>
#include <vector>
namespace enrico {
//! Driver to initialize and run OpenMC in stages
class OpenmcDriver : public NeutronicsDriver {
public:
//! One-time initalization of OpenMC and member variables
//! \param comm An existing MPI communicator used to inialize OpenMC
explicit OpenmcDriver(MPI_Comm comm);
//! One-time finalization of OpenMC
~OpenmcDriver();
//! Create energy production tallies for a list of materials
//! \param[in] materials Indices into OpenMC's materials array
void create_tallies(gsl::span<int32_t> materials);
xt::xtensor<double, 1> heat_source(double power) const final;
//! Initialization required in each Picard iteration
void init_step() final;
//! Runs OpenMC for one Picard iteration
void solve_step() final;
//! Writes OpenMC output for given timestep and iteration
//! \param timestep timestep index
//! \param iteration iteration index
void write_step(int timestep, int iteration) final;
//! Finalization required in each Picard iteration
void finalize_step() final;
// Data
openmc::Tally* tally_; //!< Fission energy deposition tally
int32_t index_filter_; //!< Index in filters arrays for material filter
std::vector<CellInstance> cells_; //!< Array of cell instances
};
} // namespace enrico
#endif // ENRICO_OPENMC_DRIVER_H
| {
"alphanum_fraction": 0.7349693252,
"avg_line_length": 28.5964912281,
"ext": "h",
"hexsha": "98e26d2d80ad91e8427c5cb46669e09487d1f000",
"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": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sphamil/enrico",
"max_forks_repo_path": "include/enrico/openmc_driver.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb",
"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": "sphamil/enrico",
"max_issues_repo_path": "include/enrico/openmc_driver.h",
"max_line_length": 84,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7a346c14d113c0068382fdd5ae82f6c7d253c9eb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sphamil/enrico",
"max_stars_repo_path": "include/enrico/openmc_driver.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 393,
"size": 1630
} |
#pragma once
#include "datastructures/MortonIndex.h"
#include <fstream>
#include <gsl/gsl>
#include <iostream>
#include <string>
struct OctreeIndexFileHeader
{
const char magic[4] = { 'i', 'n', 'd', 'x' };
uint32_t levels_per_index;
size_t num_indices;
};
template<unsigned int MaxLevels>
void
write_octree_indices_to_file(const std::string& file_path,
gsl::span<MortonIndex<MaxLevels>> indices)
{
OctreeIndexFileHeader header;
header.levels_per_index = MaxLevels;
header.num_indices = indices.size();
std::ofstream fs{ file_path, std::ios::out | std::ios::binary };
if (!fs.is_open()) {
std::cerr << "Could not write index file " << file_path << std::endl;
return;
}
fs.write(reinterpret_cast<char const*>(&header), sizeof(OctreeIndexFileHeader));
for (auto idx : indices) {
const auto idx_val = idx.get();
fs.write(reinterpret_cast<char const*>(&idx_val), sizeof(idx_val));
}
fs.flush();
fs.close();
}
template<unsigned int MaxLevels>
std::vector<MortonIndex<MaxLevels>>
read_octree_indices_from_file(const std::string& file_path)
{
std::ifstream fs{ file_path, std::ios::in | std::ios::binary };
if (!fs.is_open()) {
std::cerr << "Could not read index file " << file_path << std::endl;
return {};
}
fs.unsetf(std::ios::skipws);
fs.seekg(0, std::ios::end);
auto fileSize = fs.tellg();
fs.seekg(0, std::ios::beg);
std::vector<char> rawData;
rawData.reserve(fileSize);
rawData.insert(rawData.begin(), std::istream_iterator<char>(fs), std::istream_iterator<char>());
const auto& header = *reinterpret_cast<OctreeIndexFileHeader const*>(rawData.data());
if (header.levels_per_index != MaxLevels) {
std::cerr << "Reading octree index file with indices that contain " << header.levels_per_index
<< " levels but requested to read into MortonIndexs with " << MaxLevels
<< " levels instead!" << std::endl;
return {};
}
auto indices_begin = rawData.data() + sizeof(OctreeIndexFileHeader);
const auto indices_end = rawData.data() + rawData.size();
using IndexType_t = typename MortonIndex<MaxLevels>::Store_t;
const auto index_binary_size = sizeof(IndexType_t);
std::vector<MortonIndex<MaxLevels>> indices;
indices.reserve(header.num_indices);
for (; indices_begin < indices_end; indices_begin += index_binary_size) {
indices.emplace_back(*reinterpret_cast<IndexType_t const*>(indices_begin));
}
return indices;
} | {
"alphanum_fraction": 0.6870474658,
"avg_line_length": 29.5952380952,
"ext": "h",
"hexsha": "2c78a086922c31a5bb727ef5cf6307ec5c3b3f5e",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-08T11:45:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-03T13:50:42.000Z",
"max_forks_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "igd-geo/schwarzwald",
"max_forks_repo_path": "schwarzwald/core/tiling/OctreeIndexWriter.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T06:28:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-25T08:37:30.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "igd-geo/schwarzwald",
"max_issues_repo_path": "schwarzwald/core/tiling/OctreeIndexWriter.h",
"max_line_length": 98,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "e3e041f87c93985394444ee056ce8ba7ae62194b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "igd-geo/schwarzwald",
"max_stars_repo_path": "schwarzwald/core/tiling/OctreeIndexWriter.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-13T00:15:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-06T14:16:31.000Z",
"num_tokens": 626,
"size": 2486
} |
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <php.h>
#include <cblas.h>
#include "kernel/operators.h"
/**
* Sets the number of threads to use when parallel processesing.
*
* @param return_value
* @param threads
*/
void tensor_set_num_threads(zval * return_value, zval * threads)
{
int n = zephir_get_intval(threads);
openblas_set_num_threads(n);
RETURN_TRUE;
}
/**
* Return the number of threads to use when parallel processesing.
*
* @param return_value
*/
void tensor_get_num_threads(zval * return_value)
{
long threads = openblas_get_num_threads();
RETURN_LONG(threads);
}
| {
"alphanum_fraction": 0.7090620032,
"avg_line_length": 17.9714285714,
"ext": "c",
"hexsha": "d4be6ae2b1cf6e48d1663e0c6c311317a5d0b67f",
"lang": "C",
"max_forks_count": 20,
"max_forks_repo_forks_event_max_datetime": "2022-03-02T08:34:22.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-12-16T11:11:22.000Z",
"max_forks_repo_head_hexsha": "1f1e7611dfa720eed73b7cf4dcf21a2e6238b0f1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "cmb69/Tensor",
"max_forks_repo_path": "ext/include/settings.c",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "1f1e7611dfa720eed73b7cf4dcf21a2e6238b0f1",
"max_issues_repo_issues_event_max_datetime": "2022-01-28T03:36:39.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-07-04T07:40:37.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "cmb69/Tensor",
"max_issues_repo_path": "ext/include/settings.c",
"max_line_length": 66,
"max_stars_count": 118,
"max_stars_repo_head_hexsha": "1f1e7611dfa720eed73b7cf4dcf21a2e6238b0f1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "cmb69/Tensor",
"max_stars_repo_path": "ext/include/settings.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T13:23:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-10-21T06:54:21.000Z",
"num_tokens": 152,
"size": 629
} |
/* population genetics tools- mainly for working with site frequency spectrum
/
/
/ Andrew Kern
*/
#include "stdio.h"
#include <math.h>
#include "snpFile.h"
#include "popGenTools.h"
#include "numerical.h"
#include "assert.h"
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sf.h>
/* function for sfs generation -- stationary solution for snp frequency density*/
double my_f(double q, void * p){
struct my_f_params * params = (struct my_f_params *) p;
double beta = params->beta;
int i = params->i;
int n = params->n;
return ((1.0 - exp(-2.0 * beta * (1.0 - q))) / (1.0 - exp(-2.0 * beta))) * (2.0 / (q * (1.0 - q))) * gsl_ran_binomial_pdf(i, q, n);
}
/* integral of f over allele freq */
double my_F(double beta, void * p){
struct my_F_params * params = (struct my_F_params *) p;
struct my_f_params fParams;
gsl_function f;
//gsl_integration_workspace * w = gsl_integration_workspace_alloc (100000);
double result,error;
size_t size= 1000;
if (beta == 0){
//gsl_integration_workspace_free(w);
return 1.0 / params->i;
}
else{
fParams.beta = beta;
fParams.i = params->i;
fParams.n = params->n;
f.function = &(my_f);
f.params = &fParams;
//adaptive integration-- slow and steady
// gsl_integration_qags(&f,0.0,1.0,1e-5,1e-5, 100000,w, &result,&error);
//non-adaptive version is rougher and faster
gsl_integration_qng(&f, 0.0, 1.0, 1e-2,1e-2,&result,&error,&size);
// gsl_integration_workspace_free(w);
return result;
}
}
/* integral of f over allele freq using numerical recipes integration */
double my_F2(double beta, void * p){
struct my_F_params * params = (struct my_F_params *) p;
struct my_f_params fParams;
double result;
if (beta == 0){
return 1.0 / params->i;
}
else{
fParams.beta = beta;
fParams.i = params->i;
fParams.n = params->n;
result = d_qromb2(&my_f, 0.0, 1.0, &fParams);
return result;
}
}
/* integral of f over allele freq-- using adaptive integration */
double my_FAdapt(double beta, void * p){
struct my_F_params * params = (struct my_F_params *) p;
struct my_f_params fParams;
gsl_function f;
double result,error;
size_t size= 100;
if (beta == 0){
return 1.0 / params->i;
}
else{
fParams.beta = beta;
fParams.i = params->i;
fParams.n = params->n;
f.function = &(my_f);
f.params = &fParams;
//adaptive integration-- slow and steady
gsl_integration_qags(&f,0.0,1.0,1e-3,1e-3,size,params->w, &result,&error);
return result;
}
}
/* this returns the prob of SNP freq i given n and beta */
double snpProb(double beta, void * p){
struct my_F_params * params = (struct my_F_params *) p;
struct my_F_params tempParams;
long double tot;
int i;
gsl_function F;
/* add up total prob space */
tot = 0.0;
tempParams.n = params->n;
for(i = 1; i < params->n ; i++){
tempParams.i = i;
tempParams.w = params->w;
F.function = &my_F;
F.params = &tempParams;
tot += GSL_FN_EVAL(&F, beta);
}
/* reset parameters */
F.function = &my_FAdapt;
F.params = params;
return GSL_FN_EVAL(&F, beta) / tot ;
}
/* trying to speedup the snpProb routine with a lookup of the denominators (in snpProb_params) */
double snpProbDenomLookup(double beta, void * p){
struct my_snpProb_params * params = (struct my_snpProb_params *) p;
struct my_F_params tempParams;
gsl_function F;
/* set parameters */
tempParams.n = params->n;
tempParams.i = params->i;
tempParams.w = params->w;
F.function = &my_FAdapt;
F.params = &tempParams;
return GSL_FN_EVAL(&F, beta) / params->denom ;
}
/* sampleSize vector - returns a vector of 1s or 0s depending on sample sizes in the data */
gsl_vector *sampleSizeVector(struct snp data[], int snpNumber, int maxSampleSize){
gsl_vector *bools;
int i;
//alloc and initialize bools vector
bools = gsl_vector_alloc(maxSampleSize + 1);
gsl_vector_set_zero(bools);
//go through data, set each sampleSize value to 1
for(i = 0; i < snpNumber; i++){
gsl_vector_set(bools,data[i].n, 1);
}
return(bools);
}
/* sampleSize vector - returns a vector of 1s or 0s depending on sample sizes in the data */
void sampleSizeVectorFill(struct snp data[], int snpNumber, int maxSampleSize, gsl_vector *bools){
int i;
//initialize bools vector
gsl_vector_set_zero(bools);
//go through data, set each sampleSize value to 1
for(i = 0; i < snpNumber; i++){
gsl_vector_set(bools,data[i].n, 1);
}
}
/* returns a vector of snpProbDenominators from i = 2 to n, 1 indexed */
gsl_vector *makeSnpProbDenomVector(double beta, int maxSampleSize, gsl_vector *sampleSizeVector){
gsl_vector *probs;
int i, j, test;
double tot;
struct my_F_params tempParams;
gsl_function F;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (1000);
probs = gsl_vector_alloc(maxSampleSize + 1);
tempParams.w = w;
/* go from n = 2 to maxSampleSize, calc total prob space for each, put in vector probs */
for(j = 2; j < maxSampleSize + 1; j++){
//check if sampleSize is included
test = gsl_vector_get(sampleSizeVector,j);
if (test){
tot = 0.0;
tempParams.n = j;
for(i = 1; i < j ; i++){
tempParams.i = i;
F.function = &my_FAdapt;
F.params = &tempParams;
tot += GSL_FN_EVAL(&F, beta);
}
gsl_vector_set(probs, j, tot);
}
}
gsl_integration_workspace_free(w);
return probs;
}
/* snpProbDenom - returns denom for snpProb */
double snpProbDenom(double beta, int sampleSize){
int i;
double tot;
struct my_F_params tempParams;
gsl_function F;
tot = 0.0;
tempParams.n = sampleSize;
for(i = 1; i < sampleSize ; i++){
tempParams.i = i;
F.function = &my_F;
F.params = &tempParams;
tot += GSL_FN_EVAL(&F, beta);
}
return(tot);
}
/* snpProbMatrix- returns a matrix of log snpProbs. matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1) */
gsl_matrix *snpProbMatrix(double beta, int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools){
gsl_vector *denoms;
gsl_matrix *probs;
struct my_snpProb_params FParams;
gsl_function f;
int i, j;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//get denoms
denoms = makeSnpProbDenomVector(beta,maxSampleSize, sampleSizeVector);
FParams.w = gsl_integration_workspace_alloc(1000);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//have sample size i?
if (gsl_vector_get(sampleSizeVector, i)){
//go through freqs
for(j = 1; j < maxSampleSize; j++){
//have freq j?
if(gsl_matrix_get(sfsBools, i, j)){
//calc prob
FParams.i = j;
FParams.n = i;
FParams.denom = gsl_vector_get(denoms,i);
f.function = &snpProbDenomLookup;
f.params = &FParams;
gsl_matrix_set(probs, i, j, log(GSL_FN_EVAL(&f, beta)));
}
}
}
}
gsl_vector_free(denoms);
gsl_integration_workspace_free(FParams.w);
return(probs);
}
/* snpProbMatrix- returns a matrix of snpProbs. matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1) */
gsl_matrix *snpProbMatrixNotLog(double beta, int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools){
gsl_vector *denoms;
gsl_matrix *probs;
struct my_snpProb_params FParams;
gsl_function f;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (100000);
int i, j;
FParams.w = w;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//get denoms
denoms = makeSnpProbDenomVector(beta,maxSampleSize, sampleSizeVector);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//have sample size i?
if (gsl_vector_get(sampleSizeVector, i)){
//go through freqs
for(j = 1; j < maxSampleSize; j++){
//have freq j?
if(gsl_matrix_get(sfsBools, i, j)){
//calc prob
FParams.i = j;
FParams.n = i;
FParams.denom = gsl_vector_get(denoms,i);
f.function = &snpProbDenomLookup;
f.params = &FParams;
gsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, beta));
}
}
}
}
gsl_vector_free(denoms);
return(probs);
}
/* snpProbMatrixNotLogFull- returns a matrix of snpProbs. matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1). All freqs/samplesizes included */
gsl_matrix *snpProbMatrixNotLogFull(double beta, int maxSampleSize, gsl_vector *sampleSizeVector){
gsl_vector *denoms;
gsl_matrix *probs;
struct my_snpProb_params FParams;
gsl_function f;
int i, j;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//get denoms
denoms = makeSnpProbDenomVector(beta,maxSampleSize, sampleSizeVector);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//check for sampleSize
if (gsl_vector_get(sampleSizeVector,i)){
//go through freqs
for(j = 1; j < maxSampleSize; j++){
//calc prob
FParams.i = j;
FParams.n = i;
FParams.denom = gsl_vector_get(denoms,i);
f.function = &snpProbDenomLookup;
f.params = &FParams;
gsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, beta));
}
}
}
gsl_vector_free(denoms);
return(probs);
}
/* snpProbVectorNotLog- returns a vector of log snpProbs at specified sampleSize columns represent freqs (1 to max -1) */
gsl_vector *snpProbVectorNotLog(double beta, int sampleSize){
double denom;
gsl_vector *probs;
struct my_snpProb_params FParams;
gsl_function f;
int i;
//alloc probs
probs = gsl_vector_alloc(sampleSize);
gsl_vector_set_zero(probs);
//get denoms
denom = snpProbDenom(beta, sampleSize);
//go through freqs
for(i = 1; i < sampleSize; i++){
FParams.i = i;
FParams.n = sampleSize;
FParams.denom = denom;
f.function = &snpProbDenomLookup;
f.params = &FParams;
gsl_vector_set(probs, i, GSL_FN_EVAL(&f, beta));
}
return(probs);
}
gsl_vector *snpProbVectorNotLogPre(double beta, int sampleSize, gsl_vector *probs){
double denom;
struct my_snpProb_params FParams;
gsl_function f;
int i;
gsl_vector_set_zero(probs);
//get denoms
denom = snpProbDenom(beta, sampleSize);
//go through freqs
for(i = 1; i < sampleSize; i++){
FParams.i = i;
FParams.n = sampleSize;
FParams.denom = denom;
f.function = &snpProbDenomLookup;
f.params = &FParams;
gsl_vector_set(probs, i, GSL_FN_EVAL(&f, beta));
}
return(probs);
}
/* likelihood function for SFS given the data; p here contains the data and the weights */
double my_lik(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
struct my_F_params FParams;
gsl_function f;
double lik;
int i;
lik = 0;
for(i = 0; i < params->snpNumber; i++){
FParams.i = params->data[i].i;
FParams.n = params->data[i].n;
f.function = &snpProb;
f.params = &FParams;
lik += log(GSL_FN_EVAL(&f, beta));
}
return -lik;
}
/* likelihood function for SFS where each SNP has independent selection coeff */
double sfsLikBetaVector(gsl_vector *betas, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
struct my_F_params FParams;
gsl_function f;
double lik;
int i;
lik = 0;
for(i = 0; i < params->snpNumber; i++){
FParams.i = params->data[i].i;
FParams.n = params->data[i].n;
FParams.w = params->w;
f.function = &snpProb;
f.params = &FParams;
// printf("here lik:%f beta:%f i: %d n: %d\n",lik,gsl_vector_get(betas, i),FParams.i,FParams.n);
lik += log(GSL_FN_EVAL(&f, gsl_vector_get(betas, i)));
}
return -lik;
}
/*likelihood from Bustamante et al. 2001 */
double bustaLik(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
struct my_F_params FParams;
gsl_function f;
double lik;
int i;
lik = 0;
for(i = 0; i < params->snpNumber; i++){
FParams.i = params->data[i].i;
FParams.n = params->data[i].n;
f.function = &snpProb;
f.params = &FParams;
lik += log(GSL_FN_EVAL(&f, beta));
}
return -lik;
}
/* weighted likelihood function for SFS given the data; here contains the data and the weights */
double weightedLik(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
struct my_F_params FParams;
gsl_function f;
double lik;
int i;
lik = 0;
for(i = 0; i < params->snpNumber; i++){
FParams.i = params->data[i].i;
FParams.n = params->data[i].n;
f.function = &snpProb;
f.params = &FParams;
lik += gsl_vector_get(params->weights, i) * log(GSL_FN_EVAL(&f, beta));
}
return -lik;
}
/* weighted likelihood function for SFS given the data; here contains the data and the weights and uses the snpProbLookup routine */
double weightedLikLook(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
double lik;
int i;
gsl_matrix *probs;
//make prob matrix (note this is in logs)
probs = snpProbMatrix(beta, params->maxSampleSize, params->sampleSizeVector, params->sfsBools);
//now go and tally likelihood
lik = 0;
for(i = 0; i < params->snpNumber; i++){
lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_vector_get(params->weights,i);
}
gsl_matrix_free(probs);
return -lik;
}
/* Folded SFS version of above; weighted likelihood function for SFS given the data; here contains the data and the weights and uses the snpProbLookup routine */
double weightedLikLookFolded(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
double lik;
int i;
gsl_matrix *probs;
//make prob matrix (note this is in logs)
probs = snpProbMatrix(beta, params->maxSampleSize, params->sampleSizeVector, params->sfsBools);
//now go and tally likelihood
lik = 0;
for(i = 0; i < params->snpNumber; i++){
lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_vector_get(params->weights,i);
lik += gsl_matrix_get(probs,params->data[i].n, params->data[i].n - params->data[i].i) * gsl_vector_get(params->weights,i);
}
gsl_matrix_free(probs);
return -lik;
}
/* PRF log Likelihood */
double prfLik(double beta, void * p){
struct prfLik_params * params = (struct prfLik_params *) p;
double lik;
double term1, term2,theta;
int i;
struct my_F_params tempParams;
gsl_function F;
double fTerm = 0.;
theta = gsl_vector_get(params->betas,1);
term1 = term2 = 0;
for(i = 1; i < params->maxSampleSize;i++){
tempParams.i = i;
tempParams.n = params->maxSampleSize;
F.function = &my_F;
F.params = &tempParams;
fTerm = GSL_FN_EVAL(&F,beta);
term1 += gsl_matrix_get(params->sfsCounts,params->maxSampleSize,i) * log( theta* fTerm) ;
term2 += fTerm;
}
return((term1 - (theta * term2)) * -1);
}
double weightedLikLookCI(double beta, void * p){
struct my_likCI_params *params = (struct my_likCI_params *) p;
struct my_lik_params likParams;
gsl_function l;
double result;
likParams.data = params->data;
likParams.snpNumber = params->snpNumber;
likParams.sampleSizeVector = params->sampleSizeVector;
likParams.maxSampleSize = params->maxSampleSize;
likParams.weights = params->weights;
likParams.sfsBools = params->sfsBools;
l.function = &weightedLikLook;
l.params = &likParams;
result = GSL_FN_EVAL(&l, beta) - (params->lMax) - (params->logUnits) ;
// printf("%f\t%f\t%f\n",params->lMax,GSL_FN_EVAL(&l, beta),result);
return result;
}
double weightedLikLookCIFolded(double beta, void * p){
struct my_likCI_params *params = (struct my_likCI_params *) p;
struct my_lik_params likParams;
gsl_function l;
double result;
likParams.data = params->data;
likParams.snpNumber = params->snpNumber;
likParams.sampleSizeVector = params->sampleSizeVector;
likParams.maxSampleSize = params->maxSampleSize;
likParams.weights = params->weights;
likParams.sfsBools = params->sfsBools;
l.function = &weightedLikLookFolded;
l.params = &likParams;
result = GSL_FN_EVAL(&l, beta) - (params->lMax) - (params->logUnits) ;
// printf("%f\t%f\t%f\n",params->lMax,GSL_FN_EVAL(&l, beta),result);
return result;
}
/* wrapper for my_lik for use in mnbrak */
double likWrap(double beta){
gsl_function f;
f.function = &my_lik;
f.params = NULL;
return GSL_FN_EVAL(&f, beta);
}
/* wrapper for my_lik for use in mnbrak */
double wlikWrap(double beta, void * p){
gsl_function f;
struct my_lik_params * params = (struct my_lik_params *) p;
f.function = &weightedLik;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
/* wrapper for my_lik for use in mnbrak */
double wlikWrapLook(double beta, void * p){
gsl_function f;
struct my_lik_params * params = (struct my_lik_params *) p;
f.function = &weightedLikLook;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
double wlikWrapLookFolded(double beta, void * p){
gsl_function f;
struct my_lik_params * params = (struct my_lik_params *) p;
f.function = &weightedLikLookFolded;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
double wlikCIWrapLook(double beta, void * p){
gsl_function f;
struct my_likCI_params * params = (struct my_likCI_params *) p;
f.function = &weightedLikLookCI;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
/* wrapper for prfLik for use in mnbrak */
double prfLikWrap(double beta, void * p){
gsl_function f;
struct prfLik_params * params = (struct prfLik_params *) p;
f.function = &prfLik;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
/*error checking function for likelihood function */
void printProfile(double min, double max, void * p){
gsl_function f;
struct my_lik_params *params = (struct my_lik_params *) p;
int i;
f.function = &weightedLikLook;
f.params = params;
for(i = min; i < max; i++){
printf("%d\t%f\n",i, GSL_FN_EVAL(&f, i));
}
}
/* get ML estimate of beta using likelihood function; BRENT method for gsl */
double ml_est(double * lik_beta_hat){
int status;
int iter = 0;
int max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc;
gsl_function L;
/* get minimum bracket */
ax = -10.0;
bx = 0.0;
cx = 10.0;
mnbrak(&ax, &bx, &cx, &fa, &fb, &fc, &my_lik);
/* check if there is a minimum, if not return inf */
if (fa == fb || fc == fb || ax > cx){
*lik_beta_hat = fa;
return 666.0;
}
else{
/* do mimization */
L.function = &my_lik;
//should have param line here but no params....
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_min_fminimizer_free(s);
return m;
}
}
/* get weighted ML estimate of beta using likelihood function; BRENT method for gsl */
double weighted_ml_est(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, min;
gsl_function L;
struct my_lik_params * params = (struct my_lik_params *) p;
// get minimum bracket
ax = -10.0;
bx = 1.0;
cx = 10;
L.function = &weightedLik;
L.params = params;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrap, bx, params);
//check if there is a minimum, if not return 666
if (fa == fb || fc == fb || ax > cx){
min = fa;
if(fb < min){
min = fb;
}
if(fc < min){
min = fc;
}
*lik_beta_hat = min;
return 666.0;
}
else{
// do mimization
//initialize lik function
L.function = &weightedLik;
L.params = params;
//min routine
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
gsl_min_fminimizer_free(s);
return m;
}
}
double weighted_ml_est_lookup(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 1000;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, dummy;
gsl_function L;
struct my_lik_params * params = (struct my_lik_params *) p;
// get minimum bracket
ax = -20.0;
bx = -1.0;
cx = 20000;
L.function = &weightedLikLook;
L.params = params;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLook, bx, params);
//swap bounds if needed
if (cx < ax){
dummy = cx;
cx = ax;
ax = dummy;
}
if (fb == fc){
return HUGE_VAL;
}
// do mimization
//initialize lik function
L.function = &weightedLikLook;
L.params = params;
//min routine
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.01, 0.01);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
gsl_min_fminimizer_free(s);
return m;
}
/* same as above but outputs 666 on minimization error */
double weighted_ml_est_lookup_errReport(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, dummy;
gsl_function L;
struct my_lik_params * params = (struct my_lik_params *) p;
// get minimum bracket
ax = -20.0;
bx = -1.0;
cx = 20;
L.function = &weightedLikLook;
L.params = params;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLook, bx, params);
//swap bounds if needed
if (cx < ax){
dummy = cx;
cx = ax;
ax = dummy;
}
//check for error
if (fb >= fc || fb >= fa){
return(666.0);
}
// do mimization
//initialize lik function
L.function = &weightedLikLook;
L.params = params;
//min routine
s = params->min;
gsl_set_error_handler_off ();
status = gsl_min_fminimizer_set(s, &L, bx, ax, cx);
if (status == GSL_EINVAL){
return(666);
}
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.01, 0.01);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
//gsl_min_fminimizer_free(s);
return m;
}
/* get weighted ML lower CI beta using weightedLikLookCI method; BRENT method for gsl */
double weighted_ml_CILower_lookup(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
double m, a, b, ax, cx;
gsl_function L;
struct my_likCI_params * params = (struct my_likCI_params *) p;
// get minimum bracket
ax = -50.0;
cx = params->beta_hat;
// do root finding
//initialize lik function
L.function = &weightedLikLookCI;
L.params = params;
//min routine
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(s, &L, ax, cx);
do{
iter++;
status = gsl_root_fsolver_iterate(s);
m = gsl_root_fsolver_root(s);
a = gsl_root_fsolver_x_lower(s);
b = gsl_root_fsolver_x_upper(s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_root_fsolver_free(s);
return m;
}
/* get weighted ML upper CI beta using weightedLikLookCI method; BRENT method for gsl */
double weighted_ml_CIUpper_lookup(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
double m, a, b, ax, cx;
gsl_function L;
struct my_likCI_params * params = (struct my_likCI_params *) p;
// get minimum bracket
cx = 100.0;
ax = params->beta_hat;
// do root finding
//initialize lik function
L.function = &weightedLikLookCI;
L.params = params;
//min routine
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(s, &L, ax, cx);
do{
iter++;
status = gsl_root_fsolver_iterate(s);
m = gsl_root_fsolver_root(s);
a = gsl_root_fsolver_x_lower(s);
b = gsl_root_fsolver_x_upper(s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_root_fsolver_free(s);
return m;
}
//Folded Version
double weighted_ml_est_lookup_folded(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 1000;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, dummy;
gsl_function L;
struct my_lik_params * params = (struct my_lik_params *) p;
// get minimum bracket
ax = -20.0;
bx = -1.0;
cx = 20000;
L.function = &weightedLikLook;
L.params = params;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLookFolded, bx, params);
//swap bounds if needed
if (cx < ax){
dummy = cx;
cx = ax;
ax = dummy;
}
if (fb == fc){
return HUGE_VAL;
}
// do mimization
//initialize lik function
L.function = &weightedLikLook;
L.params = params;
//min routine
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.01, 0.01);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
gsl_min_fminimizer_free(s);
return m;
}
/* get weighted ML lower CI beta using weightedLikLookCI method; BRENT method for gsl */
double weighted_ml_CILower_lookupFolded(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
double m, a, b, ax, cx;
gsl_function L;
struct my_likCI_params * params = (struct my_likCI_params *) p;
// get minimum bracket
ax = -50.0;
cx = params->beta_hat;
// do root finding
//initialize lik function
L.function = &weightedLikLookCIFolded;
L.params = params;
//min routine
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(s, &L, ax, cx);
do{
iter++;
status = gsl_root_fsolver_iterate(s);
m = gsl_root_fsolver_root(s);
a = gsl_root_fsolver_x_lower(s);
b = gsl_root_fsolver_x_upper(s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_root_fsolver_free(s);
return m;
}
/* get weighted ML upper CI beta using weightedLikLookCI method; BRENT method for gsl */
double weighted_ml_CIUpper_lookupFolded(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
double m, a, b, ax, cx;
gsl_function L;
struct my_likCI_params * params = (struct my_likCI_params *) p;
// get minimum bracket
cx = 100.0;
ax = params->beta_hat;
// do root finding
//initialize lik function
L.function = &weightedLikLookCIFolded;
L.params = params;
//min routine
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc(T);
gsl_root_fsolver_set(s, &L, ax, cx);
do{
iter++;
status = gsl_root_fsolver_iterate(s);
m = gsl_root_fsolver_root(s);
a = gsl_root_fsolver_x_lower(s);
b = gsl_root_fsolver_x_upper(s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
gsl_root_fsolver_free(s);
return m;
}
//ML estimation using PRF likelihood model
double ml_prf(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, dummy;
gsl_function L;
struct prfLik_params * params = (struct prfLik_params *) p;
// get minimum bracket
ax = -10.0;
bx = 0.0;
cx = 10;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &prfLikWrap, bx, params);
//swap bounds if needed
if (cx < ax){
dummy = cx;
cx = ax;
ax = dummy;
}
if (fb == fc){
return HUGE_VAL;
}
// do mimization
//initialize lik function
L.function = &prfLik;
L.params = params;
//min routine
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
gsl_min_fminimizer_free(s);
return m;
}
/* summarizeSFS- returns a matrix of counts which summarize the SFS conditional
upon sampleSize. rows = sampleSize, column = freqs */
gsl_matrix *summarizeSFS(int maxSampleSize, struct snp data[], int snpNumber){
gsl_matrix *counts;
int i;
//alloc matrix of size maxSampleSize by maxSampleSize
counts = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize + 1);
gsl_matrix_set_zero(counts);
assert(counts != NULL);
//gsl_matrix_set_zero(counts);
//go through data, fill up matrix
for(i = 0; i < snpNumber; i++){
gsl_matrix_set(counts, data[i].n, data[i].i, gsl_matrix_get(counts, data[i].n, data[i].i) + 1);
}
return(counts);
}
/* summarizeSFSFill- fills a matrix of counts which summarize the SFS conditional
upon sampleSize. rows = sampleSize, column = freqs */
void summarizeSFSFill(gsl_matrix *counts, struct snp data[], int snpNumber){
int i;
//fill matrix of size maxSampleSize by maxSampleSize
gsl_matrix_set_zero(counts);
assert(counts != NULL);
gsl_matrix_set_zero(counts);
//go through data, fill up matrix
for(i = 0; i < snpNumber; i++){
gsl_matrix_set(counts, data[i].n, data[i].i, gsl_matrix_get(counts, data[i].n, data[i].i) + 1);
}
}
/* summarizeSFSFill- fills a matrix of counts which summarize the SFS conditional
upon sampleSize. rows = sampleSize, column = freqs */
int summarizeSFSFillFromTo(gsl_matrix *counts, struct snp data[], int snpNumber, int from, int to, int startPos){
int i;
//fill matrix of size maxSampleSize by maxSampleSize
gsl_matrix_set_zero(counts);
assert(counts != NULL);
gsl_matrix_set_zero(counts);
//go through data, fill up matrix
i = startPos;
while(data[i].pos < to){
if(data[i].pos >= from)
gsl_matrix_set(counts, data[i].n, data[i].i, gsl_matrix_get(counts, data[i].n, data[i].i) + 1);
i++;
}
return(i);
}
/* summarizeSFS- returns a matrix of booleans which summarize the SFS conditional
upon sampleSize. rows = sampleSize, column = freqs */
gsl_matrix *summarizeSFSBool(int maxSampleSize, struct snp data[], int snpNumber){
gsl_matrix *counts;
int i;
//alloc matrix of size maxSampleSize by maxSampleSize
counts = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize + 1);
gsl_matrix_set_zero(counts);
assert(counts != NULL);
gsl_matrix_set_zero(counts);
//go through data, fill up matrix
for(i = 0; i < snpNumber; i++){
gsl_matrix_set(counts, data[i].n, data[i].i, 1);
}
return(counts);
}
/* summarizeSFSBoolFill- fills a matrix of booleans which summarize the SFS conditional
upon sampleSize. rows = sampleSize, column = freqs */
void summarizeSFSBoolFill(gsl_matrix *counts, struct snp data[], int snpNumber){
int i;
//fill matrix of size maxSampleSize by maxSampleSize
//counts = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize + 1);
gsl_matrix_set_zero(counts);
assert(counts != NULL);
gsl_matrix_set_zero(counts);
//go through data, fill up matrix
for(i = 0; i < snpNumber; i++){
gsl_matrix_set(counts, data[i].n, data[i].i, 1);
}
}
/* simulateSiteFreq- returns an int representing the frequency of
of a site (unfolded), i, in sampleSize n, conditional on sel.
coeff. beta , also needs a pointer to a gsl random number generator */
int simulateSiteFreq(int sampleSize, double alpha, void *r){
int i;
double sum, probs[sampleSize - 1], rand;
gsl_function p;
struct my_F_params simParams;
gsl_rng * rn = (gsl_rng *) r;
simParams.n = sampleSize;
/* put probs in vector */
for(i = 0; i < sampleSize - 1; i++){
simParams.i = i + 1;
p.function = &snpProb;
p.params = &simParams;
probs[i] = GSL_FN_EVAL(&p, alpha);
}
/* choose frequency */
rand = gsl_rng_uniform(rn);
sum = 0;
for(i = 0; i < sampleSize - 1; i++){
sum += probs[i];
if (rand <= sum){
return(i+1);
}
}
return(666);
}
/* ascertainment stuff -- following Nielsen et al. 2004 */
/* simpleAscertain-- Nielsen et al. 2004 eqn 2 *, returns the prob of ascertainment
given a sample freq */
double simpleAscertain(double sampleFreq, void * p){
struct my_F_params * params = (struct my_F_params *) p;
double sampleSize, ascSize,tmpSampleFreq;
double num1 = 0.0;
double num2 = 0.0;
sampleSize = params->n;
ascSize = params->ascSize;
tmpSampleFreq = (int) sampleFreq;
//test for weirdness
if (sampleFreq < ascSize){
num1 = 0;
}
else{
num1 = gsl_sf_choose(sampleFreq, ascSize);
}
if ((sampleSize -sampleFreq) < ascSize){
num2 = 0;
}
else{
num2 = gsl_sf_choose(sampleSize - sampleFreq, ascSize);
}
return(1.0 - ((num1 + num2) / gsl_sf_choose(sampleSize, ascSize)));
}
/* outgroupAscertain-- equivalent to Nielsen et al. 2004 eqn 2,
returns the prob of ascertainment given a sample freq, but
is for use when ascertainment was based on single outgroup comparisons
(e.g. divergence between reference genomes). specifically this
calculates the prob of sampling only ancestral alleles.
IMPORTANT- sampleFreq here is derived allele freq */
double outgroupAscertain(double sampleFreq, void * p){
struct my_F_params * params = (struct my_F_params *) p;
int sampleSize, ascSize, derived;
double num = 0.0;
sampleSize = params->n;
ascSize = params->ascSize;
derived = params->derivedFlag;
if(derived){
num = xchoosey( sampleFreq, ascSize);
}
else{
num = xchoosey((sampleSize - sampleFreq), ascSize);
}
return(num /xchoosey(sampleSize, ascSize));
}
/*same as above for case where ascSamp is not subset of sample */
double outgroupAscertain2(double sampleFreq, void * p){
struct my_F_params * params = (struct my_F_params *) p;
int sampleSize, ascSize,ascFreq, derived, N, j;
double num = 0.0, denom = 0.0;
sampleSize = params->n;
ascSize = params->ascSize;
ascFreq = params->ascFreq;
derived = params->derivedFlag;
N = sampleSize + ascSize;
j = sampleFreq + ascFreq;
//was ascertainment for derived?
if(derived == 1){
num = xchoosey(j,sampleFreq) * xchoosey((N-j), sampleSize - sampleFreq);
}
else{
num = xchoosey((N-j), (sampleSize - sampleFreq)) * xchoosey(j, sampleFreq);
}
// printf("num: %f\n", num );
// printf("N: %d j: %d sampleSize: %d ascSize: %d derivedFlag: %d\n",N,j, sampleSize,ascSize,derived);
denom = xchoosey(N, sampleSize);
if (denom == 0 || num == 0){
return(0);
}
// printf("oaVal: %f\n",num)/denom;
return(num / denom);
}
/* probAscertainmentGivenModel-- Nielsen et al. 2005 eqn 8
returns the prob of ascertainment given the model */
double probAscertainmentGivenModel(double beta, void *p){
struct my_F_params * params = (struct my_F_params *) p;
struct my_F_params tempParams;
long double tot, tmpres, tmpres2;
int i=1;
gsl_function F, G;
/* add up total prob space */
tot = 0.0;
tempParams.n = params->n;
tempParams.ascSize = params->ascSize;
for(i = 1; i < params->n ; i++){
tempParams.i = i;
F.function = &(snpProb);
F.params = &tempParams;
tmpres = 0.0;
tmpres = GSL_FN_EVAL(&F, beta);
G.function = &simpleAscertain;
G.params = &tempParams;
tmpres2 = GSL_FN_EVAL(&G, i) ;
tot += tmpres * tmpres2;
}
return(tot) ;
}
/* probAscertainmentGivenModel-- Nielsen et al. 2005 eqn 8
returns the prob of ascertainment given the model */
double probOutgroupAscertainmentGivenModel(double beta, void *p){
struct my_F_params * params = (struct my_F_params *) p;
struct my_F_params tempParams;
long double tot, tmpres, tmpres2;
int i=1;
gsl_function F, G;
/* add up total prob space */
tot = 0.0;
tempParams.n = params->n;
tempParams.ascSize = params->ascSize;
for(i = 1; i < params->n ; i++){
tempParams.i = i;
F.function = &(snpProb);
F.params = &tempParams;
tmpres = 0.0;
tmpres = GSL_FN_EVAL(&F, beta);
G.function = &outgroupAscertain;
G.params = &tempParams;
tmpres2 = GSL_FN_EVAL(&G, i) ;
tot += tmpres * tmpres2;
}
return(tot) ;
}
/* probAscertainmentGivenModelLookup-- Nielsen et al. 2005 eqn 8
returns the prob of ascertainment given the model, lookup version
requires snpProb matrix and ascProb matrix */
double probAscertainmentGivenModelLookup(double beta, int sampSize, gsl_matrix *snpProbs, gsl_matrix *ascProbs){
long double tot;
int i=1;
/* add up total prob space */
tot = 0.0;
for(i = 1; i < sampSize ; i++){
tot += gsl_matrix_get(snpProbs, sampSize, i) * gsl_matrix_get(ascProbs, sampSize, i);
}
return(tot) ;
}
/* probAscertainmentGivenModelHemiLookup-- same
as above but expects vector not matrix of snpProbs */
double probAscertainmentGivenModelHemiLookup(double beta, int sampSize, gsl_vector *snpProbs, gsl_matrix *ascProbs){
long double tot;
int i=1;
/* add up total prob space */
tot = 0.0;
for(i = 1; i < sampSize ; i++){
tot += gsl_vector_get(snpProbs, i) * gsl_matrix_get(ascProbs, sampSize, i);
}
return(tot) ;
}
/* ascSize vector - returns a vector of 1s or 0s depending on ascertainment sample sizes in the data */
gsl_vector *ascSizeVector(struct snp data[], int snpNumber, int maxSampleSize){
gsl_vector *bools;
int i;
//alloc and initialize bools vector
bools = gsl_vector_alloc(maxSampleSize + 1);
gsl_vector_set_zero(bools);
//go through data, set each sampleSize value to 1
for(i = 0; i < snpNumber; i++){
gsl_vector_set(bools,data[i].ascSize, 1);
}
return(bools);
}
/* snpAscMatrix- returns a matrix of simpleAscertainment probs. matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1). Currently this only supports a single ascertainment size */
gsl_matrix *snpAscMatrix(int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools, \
int ascSize){
gsl_matrix *probs;
struct my_F_params FParams;
gsl_function f;
int i, j;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//have sample size i?
if (gsl_vector_get(sampleSizeVector, i)){
//go through freqs
for(j = 1; j < maxSampleSize; j++){
//have freq j?
if(gsl_matrix_get(sfsBools, i, j)){
//calc prob
FParams.i = j;
FParams.n = i;
FParams.ascSize = ascSize;
f.function = &simpleAscertain;
f.params = &FParams;
gsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, j));
}
}
}
}
return(probs);
}
/* snpOutgroupAscMatrix- returns a matrix of outgroupAscertainment probs.
matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1).
Currently this only supports a single ascertainment size. Also has inelegance
of calculating derived or anscertral matrix */
gsl_matrix *snpOutgroupAscMatrix(int maxSampleSize, gsl_vector *sampleSizeVector, int ascSize, int derived, \
int runMode){
gsl_matrix *probs;
struct my_F_params FParams;
gsl_function f;
int i, j;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//have sample size i?
if (gsl_vector_get(sampleSizeVector, i)){
//go through freqs
for(j = 1; j < i; j++){
//calc prob
FParams.i = j;
FParams.n = i;
FParams.ascSize = ascSize;
FParams.ascFreq = derived;
FParams.derivedFlag = derived;
if(runMode == 0){
f.function = &outgroupAscertain;
}
else{
f.function = &outgroupAscertain2;
}
f.params = &FParams;
gsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, j));
}
}
}
return(probs);
}
gsl_matrix *snpOutgroupAscMatrixPre(int maxSampleSize, gsl_vector *sampleSizeVector, int ascSize, int derived, \
int runMode, gsl_matrix *probs){
struct my_F_params FParams;
gsl_function f;
int i, j;
gsl_matrix_set_zero(probs);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//have sample size i?
if (gsl_vector_get(sampleSizeVector, i)){
//go through freqs
for(j = 1; j < i; j++){
//calc prob
FParams.i = j;
FParams.n = i;
FParams.ascSize = ascSize;
FParams.ascFreq = derived;
FParams.derivedFlag = derived;
if(runMode == 0){
f.function = &outgroupAscertain;
}
else{
f.function = &outgroupAscertain2;
}
f.params = &FParams;
gsl_matrix_set(probs, i, j, GSL_FN_EVAL(&f, j));
}
}
}
return(probs);
}
/*estimateAscSFS-- ML estimates of SFS, given ascertainment. returns
a matrix of probs. matrix is maxSampleSize+1 by maxSampleSize. rows represent
variable sampleSizes (2 to max), columns represent freqs (1 to max -1). Currently this only supports a single ascertainment size */
gsl_matrix *estimateAscSFS(int maxSampleSize, gsl_vector *sampleSizeVector, gsl_matrix *sfsBools, \
int ascSize, gsl_matrix *sfsSummary){
gsl_matrix *probs, *ascProbs;
int i, j;
double ssTmp, p_hat;
double xij;
//alloc probs
probs = gsl_matrix_alloc(maxSampleSize + 1, maxSampleSize);
gsl_matrix_set_zero(probs);
//calculate ascProbs
ascProbs = snpAscMatrix(maxSampleSize, sampleSizeVector, sfsBools, \
ascSize);
//go through sampleSizes
for(i = 2; i <= maxSampleSize; i++){
//have sample size i?
if (gsl_vector_get(sampleSizeVector, i)){
//go through freqs to tally up denom at sampleSize
ssTmp = 0.0;
for(j = 1; j < maxSampleSize; j++){
xij = gsl_matrix_get(sfsSummary, i, j);
if (xij > 0){
ssTmp += xij / gsl_matrix_get(ascProbs, i, j);
}
}
//go back through freqs to assign p_hats at sampleSize
for(j = 1; j < maxSampleSize; j++){
xij = gsl_matrix_get(sfsSummary, i, j);
p_hat = (double) xij / gsl_matrix_get(ascProbs, i, j);
gsl_matrix_set(probs, i, j, p_hat / ssTmp);
}
}
}
return(probs);
}
/* weighted likelihood function for SFS given the data and ascertainment; here contains the data and the weights and uses the snpProbLookup routine */
double weightedLikLookAsc(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
double lik, num;
int i;
gsl_matrix *probs, *ascProbs;
gsl_vector *ascDenoms;
//make prob matrix (note this is in logs)
probs = snpProbMatrix(beta, params->maxSampleSize, params->sampleSizeVector, params->sfsBools);
//make ascProb matrix (NOT in logs!)
ascProbs = snpAscMatrix(params->maxSampleSize, params->sampleSizeVector, params->sfsBools, params->ascSize);
//make vector of denoms
ascDenoms = gsl_vector_alloc(params->maxSampleSize + 1);
gsl_vector_set_zero(ascDenoms);
for(i = params->ascSize; i <= params->maxSampleSize; i++){
gsl_vector_set(ascDenoms,i,probAscertainmentGivenModelLookup(beta, i, probs, ascProbs));
}
//now go and tally likelihood
lik = 0;
num = 0;
for(i = 0; i < params->snpNumber; i++){
lik += gsl_matrix_get(probs,params->data[i].n,params->data[i].i) \
+ log(gsl_matrix_get(ascProbs,params->data[i].n,params->data[i].i)) \
- log(gsl_vector_get(ascDenoms, params->data[i].n));
}
gsl_matrix_free(probs);
gsl_matrix_free(ascProbs);
gsl_vector_free(ascDenoms);
return -lik;
}
/* weighted likelihood function for SFS given the data and outgroup ascertainment; here contains the data and the weights and uses the snpProbLookup routine */
double weightedLikLookOutgroupAsc(double beta, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
double lik, num;
int i;
gsl_matrix *probs, *ascProbsDerived, *ascProbsAncestral;
gsl_vector *ascDenomsDerived, *ascDenomsAncestral;
//make prob matrix
probs = snpProbMatrixNotLogFull(beta, params->maxSampleSize, params->sampleSizeVector);
//make ascProb matrices, one for derived one for ancestral
ascProbsAncestral = snpOutgroupAscMatrix(params->maxSampleSize, params->sampleSizeVector, \
params->ascSize, 0, params->runMode);
ascProbsDerived = snpOutgroupAscMatrix(params->maxSampleSize, params->sampleSizeVector, \
params->ascSize, 1, params->runMode);
//make vectors of denoms- derived, ancestral
ascDenomsDerived = gsl_vector_alloc(params->maxSampleSize + 1);
ascDenomsAncestral = gsl_vector_alloc(params->maxSampleSize + 1);
gsl_vector_set_zero(ascDenomsDerived);
gsl_vector_set_zero(ascDenomsAncestral);
for(i = params->ascSize; i <= params->maxSampleSize; i++){
gsl_vector_set(ascDenomsDerived,i,probAscertainmentGivenModelLookup(beta, i, probs, ascProbsDerived));
gsl_vector_set(ascDenomsAncestral,i,probAscertainmentGivenModelLookup(beta, i, probs, ascProbsAncestral));
}
//now go and tally likelihood
lik = 0;
num = 0;
for(i = 0; i < params->snpNumber; i++){
if(params->data[i].derivedFlag == 1){
num = (gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_matrix_get(ascProbsDerived,params->data[i].n,params->data[i].i)) \
/ gsl_vector_get(ascDenomsDerived, params->data[i].n);
}
else{
num = (gsl_matrix_get(probs,params->data[i].n,params->data[i].i) * gsl_matrix_get(ascProbsAncestral,params->data[i].n,params->data[i].i)) \
/ gsl_vector_get(ascDenomsAncestral, params->data[i].n);
}
lik += log(num);
}
gsl_matrix_free(probs);
gsl_matrix_free(ascProbsDerived);
gsl_matrix_free(ascProbsAncestral);
gsl_vector_free(ascDenomsDerived);
gsl_vector_free(ascDenomsAncestral);
return -lik;
}
/* wrapper for my_lik for use in mnbrak */
double wlikWrapLookAsc(double beta, void * p){
gsl_function f;
struct my_lik_params * params = (struct my_lik_params *) p;
f.function = &weightedLikLookAsc;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
/* wrapper for my_lik for use in mnbrak */
double wlikWrapLookOutgroupAsc(double beta, void * p){
gsl_function f;
struct my_lik_params * params = (struct my_lik_params *) p;
f.function = &weightedLikLookOutgroupAsc;
f.params = params;
return GSL_FN_EVAL(&f, beta);
}
/* get weighted ML estimate of beta using likelihood function (lookup) conditional on ascertainment
; BRENT method for gsl */
double weighted_ml_est_lookup_asc(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, dummy;
gsl_function L;
struct my_lik_params * params = (struct my_lik_params *) p;
// get minimum bracket
ax = -20.0;
bx = -1.0;
cx = 20;
L.function = &weightedLikLookAsc;
L.params = params;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLookAsc, bx, params);
//swap bounds if needed
if (cx < ax){
dummy = cx;
cx = ax;
ax = dummy;
}
// do mimization
//initialize lik function
L.function = &weightedLikLookAsc;
L.params = params;
//min routine
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
gsl_min_fminimizer_free(s);
return m;
}
/* get weighted ML estimate of beta using likelihood function (lookup) conditional on outgroup ascertainment
; BRENT method for gsl */
double weighted_ml_est_lookup_outgroup_asc(double * lik_beta_hat, void * p){
int status;
int iter = 0;
int max_iter = 100;
const gsl_min_fminimizer_type *T;
gsl_min_fminimizer *s;
double m, a, b, ax, bx, cx, fa, fb, fc, dummy;
gsl_function L;
struct my_lik_params * params = (struct my_lik_params *) p;
// get minimum bracket
ax = -20.0;
bx = -1.0;
cx = 20;
L.function = &weightedLikLookOutgroupAsc;
L.params = params;
mnbrak2(&ax, &bx, &cx, &fa, &fb, &fc, &wlikWrapLookOutgroupAsc, bx, params);
//swap bounds if needed
if (cx < ax){
dummy = cx;
cx = ax;
ax = dummy;
}
// do mimization
//initialize lik function
L.function = &weightedLikLookOutgroupAsc;
L.params = params;
//min routine
T = gsl_min_fminimizer_brent;
s = gsl_min_fminimizer_alloc(T);
gsl_min_fminimizer_set(s, &L, bx, ax, cx);
do{
iter++;
status = gsl_min_fminimizer_iterate(s);
m = gsl_min_fminimizer_x_minimum (s);
a = gsl_min_fminimizer_x_lower (s);
b = gsl_min_fminimizer_x_upper (s);
status = gsl_min_test_interval (a, b, 0.001, 0.0);
}
while (status == GSL_CONTINUE && iter < max_iter);
*lik_beta_hat = gsl_min_fminimizer_f_minimum(s);
gsl_min_fminimizer_free(s);
return m;
}
/* likelihood function for SFS where each SNP has
independent selection coeff and outgroup ascertainment */
double sfsLikBetaVectorOutgroupAsc(gsl_vector *betas, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
double pSNP, pAsc, pAscModel,lik, tmp;
int i;
gsl_matrix *ascProbsDerived, *ascProbsAncestral;
gsl_vector *snpProbs;
lik = 0;
//make ascProb matrix
ascProbsAncestral = snpOutgroupAscMatrix(params->maxSampleSize, params->sampleSizeVector, \
params->ascSize, 0, params->runMode);
ascProbsDerived = snpOutgroupAscMatrix(params->maxSampleSize, params->sampleSizeVector, \
params->ascSize, 1, params->runMode);
//go through snps
for(i = 0; i < params->snpNumber; i++){
//create vector of snpProbs, find pSNP_i
snpProbs = snpProbVectorNotLog(gsl_vector_get(betas, i), params->data[i].n);
pSNP = gsl_vector_get(snpProbs, params->data[i].i);
//lookup pAsc_i
if(params->data[i].derivedFlag){
pAsc = gsl_matrix_get(ascProbsDerived, params->data[i].n, params->data[i].i);
//get pAscModel
pAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \
snpProbs, ascProbsDerived);
}
else{
pAsc = gsl_matrix_get(ascProbsAncestral, params->data[i].n, params->data[i].i);
//get pAscModel
pAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \
snpProbs, ascProbsAncestral);
}
tmp = pSNP * pAsc / pAscModel;
lik += log(tmp);
gsl_vector_free(snpProbs);
}
gsl_matrix_free(ascProbsAncestral);
gsl_matrix_free(ascProbsDerived);
return -lik;
}
double sfsLikBetaVectorOutgroupAscPre(gsl_vector *betas, gsl_matrix *ascProbsAncestral,gsl_matrix *ascProbsDerived, gsl_vector *snpProbs, void * p){
struct my_lik_params * params = (struct my_lik_params *) p;
double pSNP, pAsc, pAscModel,lik, tmp;
int i;
lik = 0.0;
//make ascProb matrix
ascProbsAncestral = snpOutgroupAscMatrixPre(params->maxSampleSize, params->sampleSizeVector, \
params->ascSize, 0, params->runMode,ascProbsAncestral);
ascProbsDerived = snpOutgroupAscMatrixPre(params->maxSampleSize, params->sampleSizeVector, \
params->ascSize, 1, params->runMode,ascProbsDerived);
//go through snps
for(i = 0; i < params->snpNumber; i++){
//create vector of snpProbs, find pSNP_i
snpProbs = snpProbVectorNotLogPre(gsl_vector_get(betas, i), params->data[i].n,snpProbs);
pSNP = gsl_vector_get(snpProbs, params->data[i].i);
//lookup pAsc_i
if(params->data[i].derivedFlag){
pAsc = gsl_matrix_get(ascProbsDerived, params->data[i].n, params->data[i].i);
//get pAscModel
pAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \
snpProbs, ascProbsDerived);
}
else{
pAsc = gsl_matrix_get(ascProbsAncestral, params->data[i].n, params->data[i].i);
//get pAscModel
pAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \
snpProbs, ascProbsAncestral);
}
tmp = pSNP * pAsc / pAscModel;
lik += log(tmp);
// printf("%f\n",lik);
}
return(-lik);
}
//classical summary stats
//tajimas theta_pi
double theta_pi(struct snp *data, int sites){
int i;
double n,p, sum;
sum = 0.0;
for(i=0;i<sites;i++){
n = (double) data[i].n;
p = (double) data[i].i / n;
sum += (n / (n-1.0)) * (2.0 * p * (1.0 - p));
}
return(sum);
}
//this simply counts size with 0 < i < sampleSize
int segSites(struct snp *data, int sites){
int i, count = 0;
//go thru sites
for(i=0;i<sites;i++){
//check if monomorphic ##note I'm doing zero and n
if (data[i].i != 0 && data[i].i != data[i].n)
count++;
}
return(count);
}
/*
double theta_w(int segSites, int n){
return((double)segSites / a1f(n));
}
//harmonic sum for Waterson's theta
double a1f(int n){
int i;
double sum = 0;
for(i=1;i<n;i++){
sum += 1.0 / (double) i;
}
return(sum);
}
/*
//tajd
double tajd(int nsam, int segsites, double sumk){
double a1, a2, b1, b2, c1, c2, e1, e2;
if( segsites == 0 ) return( 0.0) ;
a1 = a1f(nsam);
a2 = a2f(nsam);
b1 = b1f(nsam);
b2 = b2f(nsam);
c1 = c1f(a1, b1);
c2 = c2f(nsam, a1, a2, b2);
e1 = e1f(a1, c1);
e2 = e2f(a1, a2, c2);
return( (sumk - (segsites/a1))/sqrt((e1*segsites) + ((e2*segsites)*(segsites
-1))) ) ;
}
double a2f(int nsam) {
double a2;
int i;
a2 = 0.0;
for (i=1; i<=nsam-1; i++) a2 += 1.0/(i*i);
return (a2);
}
double b1f(int nsam){
double b1;
b1 = (nsam + 1.0)/(3.0*(nsam-1.0));
return (b1);
}
double b2f(int nsam){
double b2;
b2 = (2*(nsam*nsam + nsam + 3.0))/(9*nsam*(nsam - 1));
return (b2);
}
double e1f(double a1f, double c1){
double e1;
e1 = c1/a1f;
return (e1);
}
double e2f(double a1f, double a2, double c2){
double e2;
e2 = c2/((a1f*a1f)+a2);
return (e2);
}
double c1f(double a1f, double b1){
double c1;
c1 = b1 - (1/a1f);
return (c1);
}
double c2f(int nsam, double a1f, double a2, double b2){
double c2;
c2 = b2 - ((nsam+2)/(a1f*nsam)) + (a2/(a1f * a1f));
return (c2);
}
*/
/////////
/////
//// MPI stuff
//MPI version of above for parallel processing
double sfsLikBetaVectorMPI(gsl_vector *betas, void * p, int myrank, int mprocs, MPI_Comm comm){
struct my_lik_params * params = (struct my_lik_params *) p;
struct my_F_params FParams;
gsl_function f;
double lik, final;
int snpNumber = params->snpNumber;
int i, start, end, window;
//initialize; where am i?
lik = 0.;
window = ceil((float)snpNumber / mprocs);
start = myrank * window;
end = start + window;
FParams.w = params->w;
f.function = &snpProb;
for(i = start; i < end && i < snpNumber; i++){
FParams.i = params->data[i].i;
FParams.n = params->data[i].n;
f.params = &FParams;
// printf("here lik:%f beta:%f i: %d n: %d\n",lik,gsl_vector_get(betas, i),FParams.i,FParams.n);
lik += log(GSL_FN_EVAL(&f, gsl_vector_get(betas, i)));
}
MPI_Reduce(&lik,&final,1, MPI_DOUBLE,MPI_SUM,0,comm);
return -final;
}
double sfsLikBetaVectorOutgroupAscPreMPI(gsl_vector *betas, gsl_matrix *ascProbsAncestral,gsl_matrix *ascProbsDerived, \
gsl_vector *snpProbs, void * p,int myrank, int mprocs, MPI_Comm comm){
struct my_lik_params * params = (struct my_lik_params *) p;
double pSNP, pAsc, pAscModel,lik, tmp, final;
int i,start, end, window,snpNumber;
//initialization; window for proc to process
lik = 0;
snpNumber = params->snpNumber;
window = ceil((float)snpNumber / mprocs);
start = myrank * window;
end = start + window;
//currently every process calculates the matrices below-- could be faster
//make ascProb matrix
ascProbsAncestral = snpOutgroupAscMatrixPre(params->maxSampleSize, params->sampleSizeVector, \
params->ascSize, 0, params->runMode,ascProbsAncestral);
ascProbsDerived = snpOutgroupAscMatrixPre(params->maxSampleSize, params->sampleSizeVector, \
params->ascSize, 1, params->runMode,ascProbsDerived);
//go through snps
for(i = start; i < end && i < snpNumber; i++){
//create vector of snpProbs, find pSNP_i
snpProbs = snpProbVectorNotLogPre(gsl_vector_get(betas, i), params->data[i].n,snpProbs);
pSNP = gsl_vector_get(snpProbs, params->data[i].i);
//lookup pAsc_i
if(params->data[i].derivedFlag){
pAsc = gsl_matrix_get(ascProbsDerived, params->data[i].n, params->data[i].i);
//get pAscModel
pAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \
snpProbs, ascProbsDerived);
}
else{
pAsc = gsl_matrix_get(ascProbsAncestral, params->data[i].n, params->data[i].i);
//get pAscModel
pAscModel = probAscertainmentGivenModelHemiLookup(gsl_vector_get(betas, i),params->data[i].n, \
snpProbs, ascProbsAncestral);
}
tmp = pSNP * pAsc / pAscModel;
lik += log(tmp);
}
MPI_Reduce(&lik,&final,1, MPI_DOUBLE,MPI_SUM,0,comm);
return -final;
}
| {
"alphanum_fraction": 0.6834106709,
"avg_line_length": 27.6447305675,
"ext": "c",
"hexsha": "0c801aba44d08ecc4cccf4ca72a818022bb06e98",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-09-15T10:37:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-15T10:37:33.000Z",
"max_forks_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andrewkern/pgLib",
"max_forks_repo_path": "popGenTools.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0",
"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": "andrewkern/pgLib",
"max_issues_repo_path": "popGenTools.c",
"max_line_length": 161,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "59765d9ed9e683731eb8213986c00875b9ceeab0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andrewkern/pgLib",
"max_stars_repo_path": "popGenTools.c",
"max_stars_repo_stars_event_max_datetime": "2018-09-16T05:43:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-15T10:37:29.000Z",
"num_tokens": 18103,
"size": 57971
} |
#pragma once
#include "icode_generator.h"
#include <halley/data_structures/hash_map.h>
#include <gsl/gsl>
#include "halley/file/path.h"
namespace YAML
{
class Node;
}
namespace Halley
{
class ComponentSchema;
class SystemSchema;
class MessageSchema;
class CustomTypeSchema;
class Codegen
{
struct Stats
{
int written = 0;
int skipped = 0;
std::vector<Path> files;
};
static bool doNothing(float, String) { return true; }
public:
using ProgressReporter = std::function<bool(float, String)>;
static void run(Path inDir, Path outDir);
explicit Codegen(bool verbose = false);
void loadSources(std::vector<std::pair<String, gsl::span<const gsl::byte>>> files, ProgressReporter progress = &doNothing);
void validate(ProgressReporter progress = &doNothing);
void process();
bool writeFile(Path path, const char* data, size_t dataSize, bool stub) const;
void writeFiles(Path directory, const CodeGenResult& files, Stats& stats) const;
std::vector<Path> generateCode(Path directory, ProgressReporter progress = &doNothing);
private:
void addSource(String name, gsl::span<const gsl::byte> data);
void addComponent(YAML::Node rootNode);
void addSystem(YAML::Node rootNode);
void addMessage(YAML::Node rootNode);
void addType(YAML::Node rootNode);
String getInclude(String typeName) const;
bool verbose;
HashMap<String, ComponentSchema> components;
HashMap<String, SystemSchema> systems;
HashMap<String, MessageSchema> messages;
HashMap<String, CustomTypeSchema> types;
};
} | {
"alphanum_fraction": 0.7396103896,
"avg_line_length": 26.1016949153,
"ext": "h",
"hexsha": "40011135ea81da0e8f1dd88ecae13dfd47c84c4d",
"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": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "lye/halley",
"max_forks_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"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": "lye/halley",
"max_issues_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h",
"max_line_length": 125,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "16b6c9783e4b21377f902a9d02366c1f19450a21",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "lye/halley",
"max_stars_repo_path": "src/tools/tools/include/halley/tools/codegen/codegen.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-27T20:23:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-27T20:23:45.000Z",
"num_tokens": 371,
"size": 1540
} |
/* min/brent.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 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 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.
*/
/* brent.c -- brent minimum finding algorithm */
#include <config.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_min.h>
#include "min.h"
typedef struct
{
double d, e, v, w;
double f_v, f_w;
}
brent_state_t;
static int brent_init (void *vstate, gsl_function * f, double x_minimum, double f_minimum, double x_lower, double f_lower, double x_upper, double f_upper);
static int brent_iterate (void *vstate, gsl_function * f, double *x_minimum, double * f_minimum, double * x_lower, double * f_lower, double * x_upper, double * f_upper);
static int
brent_init (void *vstate, gsl_function * f, double x_minimum, double f_minimum, double x_lower, double f_lower, double x_upper, double f_upper)
{
brent_state_t *state = (brent_state_t *) vstate;
const double golden = 0.3819660; /* golden = (3 - sqrt(5))/2 */
double v = x_lower + golden * (x_upper - x_lower);
double w = v;
double f_vw;
x_minimum = 0 ; /* avoid warnings about unused varibles */
f_minimum = 0 ;
f_lower = 0 ;
f_upper = 0 ;
state->v = v;
state->w = w;
state->d = 0;
state->e = 0;
SAFE_FUNC_CALL (f, v, &f_vw);
state->f_v = f_vw;
state->f_w = f_vw;
return GSL_SUCCESS;
}
static int
brent_iterate (void *vstate, gsl_function * f, double *x_minimum, double * f_minimum, double * x_lower, double * f_lower, double * x_upper, double * f_upper)
{
brent_state_t *state = (brent_state_t *) vstate;
const double x_left = *x_lower;
const double x_right = *x_upper;
const double z = *x_minimum;
double d = state->e;
double e = state->d;
double u, f_u;
const double v = state->v;
const double w = state->w;
const double f_v = state->f_v;
const double f_w = state->f_w;
const double f_z = *f_minimum;
const double golden = 0.3819660; /* golden = (3 - sqrt(5))/2 */
const double w_lower = (z - x_left);
const double w_upper = (x_right - z);
const double tolerance = GSL_SQRT_DBL_EPSILON * fabs (z);
double p = 0, q = 0, r = 0;
const double midpoint = 0.5 * (x_left + x_right);
if (fabs (e) > tolerance)
{
/* fit parabola */
r = (z - w) * (f_z - f_v);
q = (z - v) * (f_z - f_w);
p = (z - v) * q - (z - w) * r;
q = 2 * (q - r);
if (q > 0)
{
p = -p;
}
else
{
q = -q;
}
r = e;
e = d;
}
if (fabs (p) < fabs (0.5 * q * r) && p < q * w_lower && p < q * w_upper)
{
double t2 = 2 * tolerance ;
d = p / q;
u = z + d;
if ((u - x_left) < t2 || (x_right - u) < t2)
{
d = (z < midpoint) ? tolerance : -tolerance ;
}
}
else
{
e = (z < midpoint) ? x_right - z : -(z - x_left) ;
d = golden * e;
}
if (fabs (d) >= tolerance)
{
u = z + d;
}
else
{
u = z + ((d > 0) ? tolerance : -tolerance) ;
}
state->e = e;
state->d = d;
SAFE_FUNC_CALL(f, u, &f_u);
if (f_u <= f_z)
{
if (u < z)
{
*x_upper = z;
*f_upper = f_z;
}
else
{
*x_lower = z;
*f_lower = f_z;
}
state->v = w;
state->f_v = f_w;
state->w = z;
state->f_w = f_z;
*x_minimum = u;
*f_minimum = f_u;
return GSL_SUCCESS;
}
else
{
if (u < z)
{
*x_lower = u;
*f_lower = f_u;
return GSL_SUCCESS;
}
else
{
*x_upper = u;
*f_upper = f_u;
return GSL_SUCCESS;
}
if (f_u <= f_w || w == z)
{
state->v = w;
state->f_v = f_w;
state->w = u;
state->f_w = f_u;
return GSL_SUCCESS;
}
else if (f_u <= f_v || v == z || v == w)
{
state->v = u;
state->f_v = f_u;
return GSL_SUCCESS;
}
}
return GSL_FAILURE;
}
static const gsl_min_fminimizer_type brent_type =
{"brent", /* name */
sizeof (brent_state_t),
&brent_init,
&brent_iterate};
const gsl_min_fminimizer_type *gsl_min_fminimizer_brent = &brent_type;
| {
"alphanum_fraction": 0.5576619273,
"avg_line_length": 22.6071428571,
"ext": "c",
"hexsha": "499e01590d0bacfeb41eaef3ca784e0d5c5db947",
"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/min/brent.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/min/brent.c",
"max_line_length": 169,
"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/min/brent.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": 1559,
"size": 5064
} |
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_math.h>
#include "gsl_cblas.h"
#include "tests.h"
void
test_ger (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int M = 1;
int N = 1;
int lda = 1;
float alpha = 1.0f;
float A[] = { -0.515f };
float X[] = { 0.611f };
int incX = -1;
float Y[] = { -0.082f };
int incY = -1;
float A_expected[] = { -0.565102f };
cblas_sger(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], flteps, "sger(case 1390)");
}
};
};
{
int order = 102;
int M = 1;
int N = 1;
int lda = 1;
float alpha = 1.0f;
float A[] = { -0.515f };
float X[] = { 0.611f };
int incX = -1;
float Y[] = { -0.082f };
int incY = -1;
float A_expected[] = { -0.565102f };
cblas_sger(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], flteps, "sger(case 1391)");
}
};
};
{
int order = 101;
int M = 1;
int N = 1;
int lda = 1;
double alpha = 1;
double A[] = { -0.809 };
double X[] = { -0.652 };
int incX = -1;
double Y[] = { 0.712 };
int incY = -1;
double A_expected[] = { -1.273224 };
cblas_dger(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], dbleps, "dger(case 1392)");
}
};
};
{
int order = 102;
int M = 1;
int N = 1;
int lda = 1;
double alpha = 1;
double A[] = { -0.809 };
double X[] = { -0.652 };
int incX = -1;
double Y[] = { 0.712 };
int incY = -1;
double A_expected[] = { -1.273224 };
cblas_dger(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[i], A_expected[i], dbleps, "dger(case 1393)");
}
};
};
{
int order = 101;
int M = 1;
int N = 1;
int lda = 1;
float alpha[2] = {0.0f, 0.0f};
float A[] = { -0.651f, 0.856f };
float X[] = { -0.38f, -0.235f };
int incX = -1;
float Y[] = { -0.627f, 0.757f };
int incY = -1;
float A_expected[] = { -0.651f, 0.856f };
cblas_cgeru(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[2*i], A_expected[2*i], flteps, "cgeru(case 1394) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, "cgeru(case 1394) imag");
};
};
};
{
int order = 101;
int M = 1;
int N = 1;
int lda = 1;
float alpha[2] = {0.0f, 0.0f};
float A[] = { -0.651f, 0.856f };
float X[] = { -0.38f, -0.235f };
int incX = -1;
float Y[] = { -0.627f, 0.757f };
int incY = -1;
float A_expected[] = { -0.651f, 0.856f };
cblas_cgerc(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[2*i], A_expected[2*i], flteps, "cgerc(case 1395) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, "cgerc(case 1395) imag");
};
};
};
{
int order = 102;
int M = 1;
int N = 1;
int lda = 1;
float alpha[2] = {0.0f, 0.0f};
float A[] = { -0.651f, 0.856f };
float X[] = { -0.38f, -0.235f };
int incX = -1;
float Y[] = { -0.627f, 0.757f };
int incY = -1;
float A_expected[] = { -0.651f, 0.856f };
cblas_cgeru(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[2*i], A_expected[2*i], flteps, "cgeru(case 1396) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, "cgeru(case 1396) imag");
};
};
};
{
int order = 102;
int M = 1;
int N = 1;
int lda = 1;
float alpha[2] = {0.0f, 0.0f};
float A[] = { -0.651f, 0.856f };
float X[] = { -0.38f, -0.235f };
int incX = -1;
float Y[] = { -0.627f, 0.757f };
int incY = -1;
float A_expected[] = { -0.651f, 0.856f };
cblas_cgerc(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[2*i], A_expected[2*i], flteps, "cgerc(case 1397) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, "cgerc(case 1397) imag");
};
};
};
{
int order = 101;
int M = 1;
int N = 1;
int lda = 1;
double alpha[2] = {-1, 0};
double A[] = { -0.426, 0.757 };
double X[] = { -0.579, -0.155 };
int incX = -1;
double Y[] = { 0.831, 0.035 };
int incY = -1;
double A_expected[] = { 0.049724, 0.90607 };
cblas_zgeru(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[2*i], A_expected[2*i], dbleps, "zgeru(case 1398) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, "zgeru(case 1398) imag");
};
};
};
{
int order = 101;
int M = 1;
int N = 1;
int lda = 1;
double alpha[2] = {-1, 0};
double A[] = { -0.426, 0.757 };
double X[] = { -0.579, -0.155 };
int incX = -1;
double Y[] = { 0.831, 0.035 };
int incY = -1;
double A_expected[] = { 0.060574, 0.86554 };
cblas_zgerc(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[2*i], A_expected[2*i], dbleps, "zgerc(case 1399) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, "zgerc(case 1399) imag");
};
};
};
{
int order = 102;
int M = 1;
int N = 1;
int lda = 1;
double alpha[2] = {-1, 0};
double A[] = { -0.426, 0.757 };
double X[] = { -0.579, -0.155 };
int incX = -1;
double Y[] = { 0.831, 0.035 };
int incY = -1;
double A_expected[] = { 0.049724, 0.90607 };
cblas_zgeru(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[2*i], A_expected[2*i], dbleps, "zgeru(case 1400) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, "zgeru(case 1400) imag");
};
};
};
{
int order = 102;
int M = 1;
int N = 1;
int lda = 1;
double alpha[2] = {-1, 0};
double A[] = { -0.426, 0.757 };
double X[] = { -0.579, -0.155 };
int incX = -1;
double Y[] = { 0.831, 0.035 };
int incY = -1;
double A_expected[] = { 0.060574, 0.86554 };
cblas_zgerc(order, M, N, alpha, X, incX, Y, incY, A, lda);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(A[2*i], A_expected[2*i], dbleps, "zgerc(case 1401) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, "zgerc(case 1401) imag");
};
};
};
}
| {
"alphanum_fraction": 0.484939759,
"avg_line_length": 23.3802816901,
"ext": "c",
"hexsha": "d0e86501835479f71f436ca6ab93e280a71d6e35",
"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/cblas/test_ger.c",
"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/cblas/test_ger.c",
"max_line_length": 82,
"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/cblas/test_ger.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": 2812,
"size": 6640
} |
/**
*
* @file qwrapper_zgemm_tile.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 Mark Gates
* @date 2010-11-15
* @precisions normal z -> c d s
*
**/
#include <cblas.h>
#include "common.h"
/***************************************************************************//**
*
* Version of zgemm for tile storage, to avoid dependency problem when
* computations are done within the tile. alpha and beta are passed as
* pointers so they can depend on runtime values.
*
* @param[in] Alock
* Pointer to tile owning submatrix A.
*
* @param[in] Block
* Pointer to tile owning submatrix B.
*
* @param[in] Clock
* Pointer to tile owning submatrix C.
*
**/
void QUARK_CORE_zgemm_tile(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum transA, PLASMA_enum transB,
int m, int n, int k, int nb,
const PLASMA_Complex64_t *alpha, const PLASMA_Complex64_t *A, int lda,
const PLASMA_Complex64_t *B, int ldb,
const PLASMA_Complex64_t *beta, PLASMA_Complex64_t *C, int ldc,
const PLASMA_Complex64_t *Alock,
const PLASMA_Complex64_t *Block,
const PLASMA_Complex64_t *Clock)
{
DAG_CORE_GEMM;
QUARK_Insert_Task(quark, CORE_zgemm_tile_quark, task_flags,
sizeof(PLASMA_enum), &transA, VALUE,
sizeof(PLASMA_enum), &transB, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(int), &k, VALUE,
sizeof(PLASMA_Complex64_t), alpha, INPUT,
sizeof(PLASMA_Complex64_t)*nb*nb, A, NODEP, /* input; see Alock */
sizeof(int), &lda, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, B, NODEP, /* input; see Block */
sizeof(int), &ldb, VALUE,
sizeof(PLASMA_Complex64_t), beta, INPUT,
sizeof(PLASMA_Complex64_t)*nb*nb, C, NODEP, /* inout; see Clock */
sizeof(int), &ldc, VALUE,
sizeof(PLASMA_Complex64_t)*nb*nb, Alock, INPUT,
sizeof(PLASMA_Complex64_t)*nb, Block, INPUT,
sizeof(PLASMA_Complex64_t)*nb, Clock, INOUT,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_zgemm_tile_quark = PCORE_zgemm_tile_quark
#define CORE_zgemm_tile_quark PCORE_zgemm_tile_quark
#endif
void CORE_zgemm_tile_quark(Quark *quark)
{
PLASMA_enum transA, transB;
int m, n, k, lda, ldb, ldc;
const PLASMA_Complex64_t *alpha, *beta;
const PLASMA_Complex64_t *A, *B;
PLASMA_Complex64_t *C;
quark_unpack_args_13( quark, transA, transB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc );
cblas_zgemm(
CblasColMajor,
(CBLAS_TRANSPOSE)transA, (CBLAS_TRANSPOSE)transB,
m, n, k,
CBLAS_SADDR(*alpha), A, lda,
B, ldb,
CBLAS_SADDR(*beta), C, ldc );
}
| {
"alphanum_fraction": 0.5243553009,
"avg_line_length": 39.2134831461,
"ext": "c",
"hexsha": "3591660ff9d13b95ba0f97259a08d3997f9455e0",
"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_zgemm_tile.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_zgemm_tile.c",
"max_line_length": 97,
"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_zgemm_tile.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 922,
"size": 3490
} |
/*
file includeDef.h
list of headers and definitions used by the program OmegaMaxEnt (main source files: OmegaMaxEnt_main.cpp, OmegaMaxEnt_data.h, OmegaMaxEnt_data.cpp, graph_2D.h, graph_2D.cpp, generique.h, generique.cpp)
Copyright (C) 2015 Dominic Bergeron (dominic.bergeron@usherbrooke.ca)
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, see <http://www.gnu.org/licenses/>.
*/
#ifndef INCLUDEDEF_H
#define INCLUDEDEF_H
#include "fftw3.h"
#include <cmath>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <complex>
#include <string>
#include <cstring>
#include <ctime>
#include <limits>
#include <stdio.h>
#include <sys/stat.h>
#include <random>
#include <gsl/gsl_linalg.h>
#include "armadillo"
#ifndef PI
#define PI acos((double)-1.0)
#endif
#ifndef EPSILON
#define EPSILON numeric_limits<double>::epsilon()
#endif
#ifndef DBL_MIN
#define DBL_MIN numeric_limits<double>::min()
#endif
#ifndef DBL_MAX
#define DBL_MAX numeric_limits<double>::max()
#endif
#ifndef INF
#define INF numeric_limits<double>::infinity()
#endif
using namespace std;
typedef complex<double> dcomplex;
typedef unsigned int uint;
#endif
| {
"alphanum_fraction": 0.7656707674,
"avg_line_length": 25.1029411765,
"ext": "h",
"hexsha": "19e883c7ecabed1be5c53fbc70e52a595a4a3dcb",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2019-12-07T11:11:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-12-17T22:31:23.000Z",
"max_forks_repo_head_hexsha": "bbb8a7fa8520e3e8a5a57dd662ab93ff6809b369",
"max_forks_repo_licenses": [
"Naumen",
"Condor-1.1",
"MS-PL"
],
"max_forks_repo_name": "amstremblay/OmegaMaxEnt",
"max_forks_repo_path": "cpp/includeDef.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bbb8a7fa8520e3e8a5a57dd662ab93ff6809b369",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Naumen",
"Condor-1.1",
"MS-PL"
],
"max_issues_repo_name": "amstremblay/OmegaMaxEnt",
"max_issues_repo_path": "cpp/includeDef.h",
"max_line_length": 202,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "bbb8a7fa8520e3e8a5a57dd662ab93ff6809b369",
"max_stars_repo_licenses": [
"Naumen",
"Condor-1.1",
"MS-PL"
],
"max_stars_repo_name": "amstremblay/OmegaMaxEnt",
"max_stars_repo_path": "cpp/includeDef.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-18T14:44:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-01-12T14:18:50.000Z",
"num_tokens": 402,
"size": 1707
} |
/*
NAME:
normalize_row
PURPOSE:
normalize a row (or column) of a matrix given as logs
CALLING SEQUENCE:
normalize_row(gsl_matrix * q, int row,bool isrow,bool noweight,
double weight)
INPUT:
q - matrix
row - row to be normalized
isrow - is it a row or a column
noweight - add a weight to all of the values?
weight - weight to be added to all of the values
OUTPUT:
normalization factor (i.e. logsum)
REVISION HISTORY:
2008-09-21 - Written Bovy
2010-04-01 - Added noweight and weight inputs to allow the qij to have
weights - Bovy
*/
#include <math.h>
#include <gsl/gsl_matrix.h>
#include "proj_gauss_mixtures.h"
double normalize_row(gsl_matrix * q, int row, bool isrow,
bool noweight, double weight){
double loglike;
if (isrow)
loglike = logsum(q,row,true);
else
loglike = logsum(q,row,false);
int dd;
if (isrow)
for (dd = 0; dd != q->size2; ++dd) {
if ( noweight )
gsl_matrix_set(q,row,dd,gsl_matrix_get(q,row,dd)-loglike);
else
gsl_matrix_set(q,row,dd,gsl_matrix_get(q,row,dd)-loglike+weight);
}
else
for (dd = 0; dd != q->size1; ++dd) {
if ( noweight )
gsl_matrix_set(q,dd,row,gsl_matrix_get(q,dd,row)-loglike);
else
gsl_matrix_set(q,dd,row,gsl_matrix_get(q,dd,row)-loglike+weight);
}
if ( ! noweight ) loglike*= exp(weight);
return loglike;
}
| {
"alphanum_fraction": 0.6280991736,
"avg_line_length": 27.3962264151,
"ext": "c",
"hexsha": "db4155cfa0a2f192873f0c3a1f4fc61875da99b0",
"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/normalize_row.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/normalize_row.c",
"max_line_length": 76,
"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/normalize_row.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 433,
"size": 1452
} |
#pragma once
#include <list>
#include <gsl/gsl_math.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include "../../../Utils/Random.h"
#include "../../Expression.h"
#include "../RandomDistributionDirectory.h"
double rand_Gauss(const std::list<expression>& args, const Variables& vars){
if (args.size() == 1){
double sigma = args.front()->value(vars);
return gsl_ran_gaussian(rng.get(), sigma);
}
return GSL_NAN;
}
double pdf_Gauss(double x, const std::list<expression>& args, const Variables& vars){
if (args.size() == 1){
double sigma = args.front()->value(vars);
return gsl_ran_gaussian_pdf(x, sigma);
}
return GSL_NAN;
}
double cdf_P_Gauss(double x, const std::list<expression>& args, const Variables& vars){
if (args.size() == 1){
double sigma = args.front()->value(vars);
return gsl_cdf_gaussian_P(x, sigma);
}
return GSL_NAN;
}
double cdf_Q_Gauss(double x, const std::list<expression>& args, const Variables& vars){
if (args.size() == 1){
double sigma = args.front()->value(vars);
return gsl_cdf_gaussian_Q(x, sigma);
}
return GSL_NAN;
}
double cdf_Pinv_Gauss(double x, const std::list<expression>& args, const Variables& vars){
if (args.size() == 1){
double sigma = args.front()->value(vars);
return gsl_cdf_gaussian_Pinv(x, sigma);
}
return GSL_NAN;
}
double cdf_Qinv_Gauss(double x, const std::list<expression>& args, const Variables& vars){
if (args.size() == 1){
double sigma = args.front()->value(vars);
return gsl_cdf_gaussian_Qinv(x, sigma);
}
return GSL_NAN;
}
| {
"alphanum_fraction": 0.6404088996,
"avg_line_length": 27.262295082,
"ext": "h",
"hexsha": "cb12506585de1e57bdf3f6dc6e5b916cc61840c9",
"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/RandomDistributionExpressions/Distributions/Gauss.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/RandomDistributionExpressions/Distributions/Gauss.h",
"max_line_length": 90,
"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/RandomDistributionExpressions/Distributions/Gauss.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 436,
"size": 1663
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include <iosfwd>
#include <vector>
#include <algorithm>
#include <string>
#include <cstring>
#include <gsl/gsl>
#include "onnxruntime_config.h"
#ifndef DISABLE_ABSEIL
// Need to include abseil inlined_vector.h header directly here
// as hash tables cause CUDA 10.2 compilers to fail. inlined_vector.h is fine.
#ifdef _MSC_VER
#pragma warning(push)
// C4127: conditional expression is constant
#pragma warning(disable : 4127)
// C4324: structure was padded due to alignment specifier
// Usage of alignas causes some internal padding in places.
#pragma warning(disable : 4324)
#endif
#include <absl/container/inlined_vector.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // DISABLE_ABSEIL
namespace onnxruntime {
#ifdef __GNUC__
#pragma GCC diagnostic push
#ifdef HAS_NULL_DEREFERENCE
#pragma GCC diagnostic ignored "-Wnull-dereference"
#endif
#endif
constexpr size_t kTensorShapeSmallBufferElementsSize = 5;
#ifndef DISABLE_ABSEIL
// Use this type to build a shape and then create TensorShape.
using TensorShapeVector = absl::InlinedVector<int64_t, kTensorShapeSmallBufferElementsSize>;
#else
class TensorShapeVector : public std::vector<int64_t> {
using Base = std::vector<int64_t>;
public:
using Base::Base;
};
#endif // DISABLE_ABSEIL
inline TensorShapeVector ToShapeVector(const gsl::span<const int64_t>& span) {
TensorShapeVector out;
out.reserve(span.size());
out.assign(span.begin(), span.end());
return out;
}
inline gsl::span<const int64_t> ToConstSpan(const TensorShapeVector& vec) {
return gsl::make_span(vec);
}
class TensorShape {
// We use negative numbers for unknown symbolic dimension. Each negative
// number represents a unique symbolic dimension.
public:
TensorShape() = default;
TensorShape(const TensorShape& other) : TensorShape(other.GetDims()) {}
TensorShape& operator=(const TensorShape& other);
TensorShape& operator=(const gsl::span<const int64_t>& dims) {
*this = TensorShape(dims);
return *this;
}
TensorShape(TensorShape&& other) noexcept { operator=(std::move(other)); }
TensorShape& operator=(TensorShape&& other) noexcept;
TensorShape(gsl::span<const int64_t> dims);
TensorShape(const TensorShapeVector& dims) : TensorShape(gsl::make_span(dims)) {}
TensorShape(std::initializer_list<int64_t> dims) : TensorShape(gsl::make_span(dims.begin(), dims.end())) {}
TensorShape(const int64_t* dimension_sizes, size_t dimension_count) : TensorShape(gsl::span<const int64_t>(dimension_sizes, dimension_count)) {}
TensorShape(const std::vector<int64_t>& dims, size_t start, size_t end) : TensorShape(gsl::span<const int64_t>(&dims[start], end - start)) {}
// Create a TensorShape that points to an existing buffer internally. As no copy is made, 'data' must remain valid for the life of the TensorShape
static const TensorShape FromExistingBuffer(const std::vector<int64_t>& data) {
return TensorShape(External{}, gsl::span<int64_t>(const_cast<int64_t*>(data.data()), data.size()));
}
/**
Return the dimension specified by <idx>.
*/
int64_t operator[](size_t idx) const { return values_[idx]; }
int64_t& operator[](size_t idx) { return values_[idx]; }
bool operator==(const TensorShape& other) const noexcept { return GetDims() == other.GetDims(); }
bool operator!=(const TensorShape& other) const noexcept { return !(*this == other); }
size_t NumDimensions() const noexcept {
return values_.size();
}
/**
Copy dims into an array with given size
*/
void CopyDims(int64_t* dims, size_t num_dims) const {
memcpy(dims, values_.data(), sizeof(int64_t) * std::min(num_dims, NumDimensions()));
}
/**
Copy dims from a specific start dim into an array with given size
`start_dim` is expected to be in the inclusive range [0, NumDimensions() - 1]
and this function does no checks to ensure that
*/
void CopyDims(int64_t* dims, size_t start_dim, size_t num_dims) const {
memcpy(dims, values_.data() + start_dim, sizeof(int64_t) * std::min(num_dims, NumDimensions() - start_dim));
}
/**
Return underlying vector representation.
*/
gsl::span<const int64_t> GetDims() const { return values_; }
TensorShapeVector AsShapeVector() const {
return ToShapeVector(values_);
}
/**
* Return the total number of elements. Returns 1 for an empty (rank 0) TensorShape.
*
* May return -1
*/
int64_t Size() const;
/**
Return the total number of elements up to the specified dimension.
If the dimension interval is empty (dimension == 0), return 1.
@param dimension Return size up to this dimension. Value must be between 0 and this->NumDimensions(), inclusive.
*/
int64_t SizeToDimension(size_t dimension) const;
/**
Return the total number of elements from the specified dimension to the end of the tensor shape.
If the dimension interval is empty (dimension == this->NumDimensions()), return 1.
@param dimension Return size from this dimension to the end. Value must be between 0 and this->NumDimensions(),
inclusive.
*/
int64_t SizeFromDimension(size_t dimension) const;
/**
Return a new TensorShape of the dimensions from dimstart to dimend.
*/
TensorShape Slice(size_t dimstart, size_t dimend) const;
/**
Return a new TensorShape of the dimensions from dimstart to end.
*/
TensorShape Slice(size_t dimstart) const { return Slice(dimstart, values_.size()); }
/**
output dimensions nicely formatted
*/
std::string ToString() const;
/**
Calculate size between start and end.
Assumes start and end are between 0 and this->NumDimensions(), inclusive, and that
start < end.
*/
int64_t SizeHelper(size_t start, size_t end) const;
/**
empty shape or 1D shape (1) is regarded as scalar tensor
*/
bool IsScalar() const {
size_t len = values_.size();
return len == 0 || (len == 1 && values_[0] == 1);
}
private:
struct External {};
TensorShape(External, gsl::span<int64_t> buffer) : values_{buffer} {}
void Allocate(size_t size);
gsl::span<int64_t> values_;
int64_t small_buffer_[kTensorShapeSmallBufferElementsSize];
std::unique_ptr<int64_t[]> allocated_buffer_;
friend struct ProviderHostImpl; // So that the shared provider interface can access Allocate
};
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
// operator<< to nicely output to a stream
std::ostream& operator<<(std::ostream& out, const TensorShape& shape);
} // namespace onnxruntime
| {
"alphanum_fraction": 0.7193592262,
"avg_line_length": 32.7574257426,
"ext": "h",
"hexsha": "36b8110e3e0283a883b97c4992b872493af16af7",
"lang": "C",
"max_forks_count": 140,
"max_forks_repo_forks_event_max_datetime": "2019-05-06T18:02:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-12-03T21:15:28.000Z",
"max_forks_repo_head_hexsha": "6f85d3e5c81c919022ac4a77e5a051da8518b15d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mszhanyi/onnxruntime",
"max_forks_repo_path": "include/onnxruntime/core/framework/tensor_shape.h",
"max_issues_count": 440,
"max_issues_repo_head_hexsha": "6f85d3e5c81c919022ac4a77e5a051da8518b15d",
"max_issues_repo_issues_event_max_datetime": "2019-05-06T20:47:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-03T21:09:56.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "mszhanyi/onnxruntime",
"max_issues_repo_path": "include/onnxruntime/core/framework/tensor_shape.h",
"max_line_length": 148,
"max_stars_count": 669,
"max_stars_repo_head_hexsha": "6f85d3e5c81c919022ac4a77e5a051da8518b15d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mszhanyi/onnxruntime",
"max_stars_repo_path": "include/onnxruntime/core/framework/tensor_shape.h",
"max_stars_repo_stars_event_max_datetime": "2019-05-06T19:42:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-03T22:00:31.000Z",
"num_tokens": 1624,
"size": 6617
} |
/* permutation/init.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 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 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 <gsl/gsl_errno.h>
#include <gsl/gsl_permutation.h>
gsl_permutation *
gsl_permutation_alloc (const size_t n)
{
gsl_permutation * p;
if (n == 0)
{
GSL_ERROR_VAL ("permutation length n must be positive integer",
GSL_EDOM, 0);
}
p = (gsl_permutation *) malloc (sizeof (gsl_permutation));
if (p == 0)
{
GSL_ERROR_VAL ("failed to allocate space for permutation struct",
GSL_ENOMEM, 0);
}
p->data = (size_t *) malloc (n * sizeof (size_t));
if (p->data == 0)
{
free (p); /* exception in constructor, avoid memory leak */
GSL_ERROR_VAL ("failed to allocate space for permutation data",
GSL_ENOMEM, 0);
}
p->size = n;
return p;
}
gsl_permutation *
gsl_permutation_calloc (const size_t n)
{
size_t i;
gsl_permutation * p = gsl_permutation_alloc (n);
if (p == 0)
return 0;
/* initialize permutation to identity */
for (i = 0; i < n; i++)
{
p->data[i] = i;
}
return p;
}
void
gsl_permutation_init (gsl_permutation * p)
{
const size_t n = p->size ;
size_t i;
/* initialize permutation to identity */
for (i = 0; i < n; i++)
{
p->data[i] = i;
}
}
void
gsl_permutation_free (gsl_permutation * p)
{
free (p->data);
free (p);
}
| {
"alphanum_fraction": 0.6350364964,
"avg_line_length": 22.1414141414,
"ext": "c",
"hexsha": "570794facdf34b9ca3c44389e068e9124593957e",
"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/permutation/init.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/permutation/init.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/permutation/init.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": 605,
"size": 2192
} |
#pragma once
#include "halley/net/connection/iconnection.h"
#include "halley/net/connection/network_packet.h"
#ifdef _MSC_VER
#pragma warning(disable: 4834)
#endif
#define BOOST_SYSTEM_NO_DEPRECATED
#define BOOST_ERROR_CODE_HEADER_ONLY
#include <boost/asio.hpp>
#include <deque>
#include <array>
#include <string>
#include <gsl/gsl>
namespace Halley
{
class NetworkService;
using UDPEndpoint = boost::asio::ip::udp::endpoint;
using UDPSocket = boost::asio::ip::udp::socket;
class AsioUDPConnection : public IConnection
{
public:
AsioUDPConnection(UDPSocket& socket, UDPEndpoint remote);
void close() override;
ConnectionStatus getStatus() const override { return status; }
void send(OutboundNetworkPacket&& packet) override;
bool receive(InboundNetworkPacket& packet) override;
bool matchesEndpoint(const UDPEndpoint& remoteEndpoint) const;
void onReceive(gsl::span<const gsl::byte> data);
void setError(const std::string& cs);
void open(short connectionId);
void onOpen(short connectionId);
void terminateConnection();
short getConnectionId() const { return connectionId; }
private:
UDPSocket& socket;
UDPEndpoint remote;
ConnectionStatus status;
short connectionId;
std::deque<OutboundNetworkPacket> pendingSend;
std::deque<InboundNetworkPacket> pendingReceive;
std::array<gsl::byte, 2048> sendBuffer;
std::string error;
void sendNext();
};
}
| {
"alphanum_fraction": 0.7602836879,
"avg_line_length": 24.7368421053,
"ext": "h",
"hexsha": "ae9f510babd73f060e6f9874e86f0e298b1cdec9",
"lang": "C",
"max_forks_count": 193,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z",
"max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sunhay/halley",
"max_forks_repo_path": "src/plugins/asio/src/asio_udp_connection.h",
"max_issues_count": 53,
"max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "sunhay/halley",
"max_issues_repo_path": "src/plugins/asio/src/asio_udp_connection.h",
"max_line_length": 64,
"max_stars_count": 3262,
"max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sunhay/halley",
"max_stars_repo_path": "src/plugins/asio/src/asio_udp_connection.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z",
"num_tokens": 348,
"size": 1410
} |
//! \file heat_driver.h
//! Driver for Magnolia's heat transfer solver
#ifndef ENRICO_SURROGATE_HEAT_DRIVER_H
#define ENRICO_SURROGATE_HEAT_DRIVER_H
#include "driver.h"
#include "pugixml.hpp"
#include "xtensor/xtensor.hpp"
#include <gsl/gsl>
#include <mpi.h>
#include <cstddef>
namespace enrico {
class SurrogateHeatDriver : public Driver {
public:
//! Initializes heat-fluids surrogate with the given MPI communicator.
//!
//! \param comm The MPI communicator used to initialze the surrogate
//! \param node XML node containing settings for surrogate
explicit SurrogateHeatDriver(MPI_Comm comm, pugi::xml_node node);
//! Solves the heat-fluids surrogate solver
void solve_step() final;
//! Number of rings in fuel and clad
//! \return Number of rings
std::size_t n_rings() { return n_fuel_rings_ + n_clad_rings_; }
//! Write data to VTK
void write_step(int timestep, int iteration) final;
xt::xtensor<double, 1> temperature() const;
double temperature(int pin, int axial, int ring) const;
// Data on fuel pins
xt::xtensor<double, 2> pin_centers_; //!< (x,y) values for center of fuel pins
xt::xtensor<double, 1> z_; //!< Bounding z-values for axial segments
std::size_t n_pins_; //!< number of fuel pins
std::size_t n_axial_; //!< number of axial segments
// Dimensions for a single fuel pin axial segment
double clad_outer_radius_; //!< clad outer radius in [cm]
double clad_inner_radius_; //!< clad inner radius in [cm]
double pellet_radius_; //!< fuel pellet radius in [cm]
std::size_t n_fuel_rings_{20}; //!< number of fuel rings
std::size_t n_clad_rings_{2}; //!< number of clad rings
// solver variables and settings
double tol_; //!< tolerance on convergence
xt::xtensor<double, 3> source_; //!< heat source for each (axial segment, ring)
xt::xtensor<double, 1> r_grid_clad_; //!< radii of each clad ring in [cm]
xt::xtensor<double, 1> r_grid_fuel_; //!< radii of each fuel ring in [cm]
// visualization
std::string viz_basename_{
"heat_surrogate"}; //!< base filename for visualization files (default: magnolia)
std::string viz_iterations_{
"none"}; //!< visualization iterations to write (none, all, final)
std::string viz_data_{"all"}; //!< visualization data to write
std::string viz_regions_{"all"}; //!< visualization regions to write
size_t vtk_radial_res_{20}; //!< radial resolution of resulting vtk files
private:
//! Create internal arrays used for heat equation solver
void generate_arrays();
//!< temperature in [K] for each (axial segment, ring)
xt::xtensor<double, 3> temperature_;
}; // end SurrogateHeatDriver
} // namespace enrico
#endif //ENRICO_SURROGATE_HEAT_DRIVER_H
| {
"alphanum_fraction": 0.691841824,
"avg_line_length": 35.5316455696,
"ext": "h",
"hexsha": "2ccb7c9b6bc2a2b6a09f1b6241497563624fbdd2",
"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": "991880628a4bd3c2695d475f3f37edf5b13f85dc",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "aprilnovak/enrico",
"max_forks_repo_path": "include/enrico/surrogate_heat_driver.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "991880628a4bd3c2695d475f3f37edf5b13f85dc",
"max_issues_repo_issues_event_max_datetime": "2019-12-11T16:51:18.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-11T16:51:18.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "aprilnovak/enrico",
"max_issues_repo_path": "include/enrico/surrogate_heat_driver.h",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "991880628a4bd3c2695d475f3f37edf5b13f85dc",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "aprilnovak/enrico",
"max_stars_repo_path": "include/enrico/surrogate_heat_driver.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 723,
"size": 2807
} |
/**
*
* @file qwrapper_cpotrf.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
* @author Mathieu Faverge
* @author Jakub Kurzak
* @date 2010-11-15
* @generated c Tue Jan 7 11:44:56 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_clauum(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int n, int nb,
PLASMA_Complex32_t *A, int lda)
{
DAG_CORE_LAUUM;
QUARK_Insert_Task(quark, CORE_clauum_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex32_t)*nb*nb, A, INOUT,
sizeof(int), &lda, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_clauum_quark = PCORE_clauum_quark
#define CORE_clauum_quark PCORE_clauum_quark
#endif
void CORE_clauum_quark(Quark *quark)
{
PLASMA_enum uplo;
int N;
PLASMA_Complex32_t *A;
int LDA;
quark_unpack_args_4(quark, uplo, N, A, LDA);
LAPACKE_clauum_work(LAPACK_COL_MAJOR, lapack_const(uplo), N, A, LDA);
}
| {
"alphanum_fraction": 0.5538983051,
"avg_line_length": 27.8301886792,
"ext": "c",
"hexsha": "494b454edeb49adc857f24cd4bc80ff77efa54bc",
"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_clauum.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_clauum.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_clauum.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 424,
"size": 1475
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gbpLib.h>
#include <gbpMath.h>
#include <gbpCosmo_core.h>
#include <gbpCosmo_NFW_etc.h>
#include <gsl/gsl_sf_expint.h>
void set_NFW_params(double M, double z, int mode, cosmo_info **cosmo, double *c_vir, double *R_vir) {
if(mode != NFW_MODE_DEFAULT)
SID_exit_error("Unknown mode (%d) in set_NFW_params()", SID_ERROR_LOGIC, mode);
switch(ADaPS_exist(*cosmo, "M_WDM")) {
case GBP_FALSE: {
double Omega_M = ((double *)ADaPS_fetch(*cosmo, "Omega_M"))[0];
double h_Hubble = ((double *)ADaPS_fetch(*cosmo, "h_Hubble"))[0];
// Mass-concentration from Munoz-Cuartas et al 2010
double w = 0.029;
double m = 0.097;
double alpha = -110.001;
double beta = 2469.720;
double gamma = 16.885;
double a_z = w * z - m;
double b_z = alpha / (z + gamma) + beta / pow(z + gamma, 2.);
double Delta = Delta_vir(z, *cosmo);
Delta = 200.;
(*c_vir) = take_alog10(a_z * take_log10(M / (M_SOL / h_Hubble)) + b_z);
(*R_vir) = R_Delta_z(M, Delta, z, *cosmo); // Bullock et al '01
} break;
case GBP_TRUE:
SID_exit_error("ENS not working.", SID_ERROR_LOGIC);
//(*c_vir)=c_ENS(M,z,*cosmo); // Eke, Navarro and Steinmetz
//(*R_vir)=R_Delta_z(M,200.,z,*cosmo); // R_200
break;
}
}
| {
"alphanum_fraction": 0.5534173855,
"avg_line_length": 37.675,
"ext": "c",
"hexsha": "14afb97a0feffd044bed945a05c378f03218da14",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/set_NFW_params.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/set_NFW_params.c",
"max_line_length": 101,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/set_NFW_params.c",
"max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z",
"num_tokens": 464,
"size": 1507
} |
#ifndef NewtonRaphsonSolver_H
#define NewtonRaphsonSolver_H
#include <stdio.h>
#include <iostream>
#include <vector>
#include <gsl/gsl_linalg.h>
#include "Node.h"
#include "ShapeBase.h"
//#include <omp.h>
/**
* The Newton-Raphson solver class
* */
class NewtonRaphsonSolver{
private:
size_t nDim; ///< Dimension of the space (3D)
size_t nNodes; ///< Number of nodes of the system
double threshold; ///< Convergence threshold for iterations
public:
NewtonRaphsonSolver(int nDim, int nNodes); ///< Constructer of the N-R solver
~NewtonRaphsonSolver(); ///< Desturctor of the N-R solver
gsl_matrix* un; ///< The initial positions of the nodes, as calculated at the end of previous step "n"
gsl_matrix* ge; ///< The matrix containing elastic forces on each node, size (nDim*nNodes,1). Organisation is [Node0,x ; Node0,y ; Node0,z; ... ; Noden,x ; Noden,y ; Noden,z]
gsl_matrix* gvInternal; ///< The matrix containing internal viscous forces on each node, size (nDim*nNodes,1). Organisation is [Node0,x ; Node0,y ; Node0,z; ... ; Noden,x ; Noden,y ; Noden,z]
gsl_matrix* gvExternal; ///< The matrix containing external viscous forces on each node, size (nDim*nNodes,1). Organisation is [Node0,x ; Node0,y ; Node0,z; ... ; Noden,x ; Noden,y ; Noden,z]
gsl_matrix* gExt; ///< The matrix containing external forces on each node (currently includes packing forces), size (nDim*nNodes,1). Organisation is [Node0,x ; Node0,y ; Node0,z; ... ; Noden,x ; Noden,y ; Noden,z]
gsl_vector* gSum; ///< The matrix containing sum of NewtonRaphsonSolver#ge, NewtonRaphsonSolver#gvInternal, NewtonRaphsonSolver#gvExternal, NewtonRaphsonSolver#gExt. Organisation is [Node0,x ; Node0,y ; Node0,z; ... ; Noden,x ; Noden,y ; Noden,z]
gsl_matrix* uk; ///< The matrix storing the position of each node at iteration "k". Initiated in function NewtonRaphsonSolver#initialteUkMatrix at the beginning of each step, and updated by function NewtonRaphsonSolver#updateUkInIteration during the iteartions.
gsl_matrix* displacementPerDt; ///< The displacement per time step of each node in current iteration "k", from its position at the end of the last time step "n"
gsl_vector* deltaU; ///< The incremental change in positions as calculated in current iteration, resulting from the imbalance of elastic, viscous and any other external forces acting on each nodes. The solver minimises this value, convergence occurs when all incremental movements for all nodes sufficiently close to zero.
gsl_matrix* K; ///< The Jacobian matrix, derivative of sum of forces acting on each node with respect to displacements.
bool boundNodesWithSlaveMasterDefinition; ///< The boolean stating if there are degrees of freedom slave to other nodes (masters).
std::vector< std::vector<int> > slaveMasterList; ///< The 2D integer vector storing the slave-master degrees of freedom couples, such that array [i][0] = slave to array[i][1], each i representing one dim of node position ( z of node 2 is DoF i=8);
void setMatricesToZeroAtTheBeginningOfIteration(); ///< The function setting the calculation matrices to zero at the beginning of each iteration.
void setMatricesToZeroInsideIteration(); ///< The function setting the relevant matrices to zero at each iteration.
void constructUnMatrix(const std::vector<std::unique_ptr<Node> > &Nodes); ///< This function constructs NewtonRaphsonSolver#un matrix at the beginning of the iterations.
void initialteUkMatrix(); ///< This function initiates NewtonRaphsonSolver#uk matrix at the beginning of the iterations, it is initiated to be equal to NewtonRaphsonSolver#un.
void calculateBoundKWithSlavesMasterDoF(); ///< This function updates the Jacobian of the system, NewtonRaphsonSolver#K, to reflect degrees of freedom binding.
void equateSlaveDisplacementsToMasters(); ///< This function moves the slaves of bound couples with a displacement equivalent to the masters'.
void calculateDisplacementMatrix(double dt); ///< This function calculates the displacement of each node in current iteration "k", from their positions at the end of the previous step "n" (NewtonRaphsonSolver#uk - NewtonRaphsonSolver#un)
void calcutateFixedK(const std::vector <std::unique_ptr<Node>>& Nodes); ///< This function updates the Jacobian to account for nodes that are fixed in certain dimensions in space, as part of boundary conditions.
void calculateForcesAndJacobianMatrixNR(const std::vector <std::unique_ptr<Node>>& Nodes, const std::vector <std::unique_ptr<ShapeBase>>& Elements, double dt ); ///< This function calculates elemental forces and Jacobians, later to be combined in NewtonRaphsonSolver#K and NewtonRaphsonSolver#gSum
void writeForcesTogeAndgvInternal(const std::vector <std::unique_ptr<Node>>& Nodes, const std::vector <std::unique_ptr<ShapeBase>>& Elements, std::vector<std::array<double,3>>& SystemForces); ///< This function writes the values of elemental elastic (ShapeBase#ge) and internal viscous forces (ShapeBase#gvInternal) into the system elastic and internal viscous forces, NewtonRaphsonSolver#ge, and NewtonRaphsonSolver#gvInternal, respectively.
void writeImplicitElementalKToJacobian(const std::vector <std::unique_ptr<ShapeBase>>& Elements); ///< This function writes the elemental values for elastic part of the Jacobian - stiffness matrix - (ShapeBase#TriPointKe) and for viscous part of Jacobian (ShapeBase#TriPointKv) into the system Jacobian NewtonRaphsonSolver#K.
void calculateExternalViscousForcesForNR(const std::vector <std::unique_ptr<Node>>& Nodes); ///< This function calculates the external viscous forces acting on each node, the values are sotred in NewtonRaphsonSolver#gvExternal
void addImplicitKViscousExternalToJacobian(const std::vector <std::unique_ptr<Node>>& Nodes, double dt); ///< This function adds the external related terms of the Jacobian to the system Jacobian NewtonRaphsonSolver#K.
void checkJacobianForAblatedNodes(std::vector <int> & AblatedNodes); ///< This functions checks the Jacobian to ensure the diagonal terms are non-zero for ablated nodes.
void calculateSumOfInternalForces(); ///< This function adds the ealsticity and viscosity related forces (NewtonRaphsonSolver#ge, NewtonRaphsonSolver#gvInternal, NewtonRaphsonSolver#gvExternal) to sum of forces, NewtonRaphsonSolver#gSum.
void addExernalForces();
void solveForDeltaU(); ///< This function solves for the displacements within the N-R step.
//raw pointers necessary for Pardiso
int solveWithPardiso(double* a, double*b, int* ia, int* ja, const int n_variables);
void constructiaForPardiso(int* ia, const int nmult, std::vector<int> &ja_vec, std::vector<double> &a_vec);
void writeKinPardisoFormat(const int nNonzero, std::vector<int> &ja_vec, std::vector<double> &a_vec, int* ja, double* a);
void writeginPardisoFormat(double* b, const int n);
bool checkConvergenceViaDeltaU(); ///< Check for cenvergence with the norm of displacements vector,against the threshold NewtonRaphsonSolver#threshold.
bool checkConvergenceViaForce(); ///< Check for cenvergence with the norm of forces vector,against the threshold NewtonRaphsonSolver#threshold.
void updateUkInIteration(); ///< Calulate the nodal displacemetns at the kth iteration of NR dolver.
void displayMatrix(gsl_matrix* mat, std::string matname);
void displayMatrix(gsl_vector* mat, std::string matname);
bool checkIfCombinationExists(int dofSlave, int dofMaster);
void checkMasterUpdate(int& dofMaster, int& masterId); ///< This function takes a degree of freedom number as input. This DOF is supposed to be a master. If, the dof is already a slave to another dof, then update the masetr dof. Anything that would be bound to the input dof can be bound to the already existing master of the input dof.
bool checkIfSlaveIsAlreadyMasterOfOthers(int dofSlave, int dofMaster); ///< This function checks if the slave DOF is already master of others, if so, updates the master of said slave to the new master the current slave will be bound to.
void updateElementPositions(const std::vector<std::unique_ptr<Node> > &Nodes, const std::vector <std::unique_ptr<ShapeBase>>& Elements);
};
#endif
| {
"alphanum_fraction": 0.7098153985,
"avg_line_length": 113.8974358974,
"ext": "h",
"hexsha": "05d8e24ea7e66df11abdca4f5c5965d109536b92",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-07-28T12:26:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-05-06T11:38:53.000Z",
"max_forks_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "meldatozluoglu/TissueFolding_Lite",
"max_forks_repo_path": "TissueFolding/SourceCode/NewtonRaphsonSolver.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "meldatozluoglu/TissueFolding_Lite",
"max_issues_repo_path": "TissueFolding/SourceCode/NewtonRaphsonSolver.h",
"max_line_length": 447,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "2b436d7004a75c73f44202f31826557f5fb9f900",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "meldatozluoglu/TissueFolding_Lite",
"max_stars_repo_path": "TissueFolding/SourceCode/NewtonRaphsonSolver.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-25T16:18:45.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-06-18T14:13:41.000Z",
"num_tokens": 2064,
"size": 8884
} |
/* statistics/test_robust.c
*
* 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.
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_ieee_utils.h>
int test_robust (void);
/* random vector in [-1,1] */
static int
random_array(const size_t n, double * x, gsl_rng * r)
{
size_t i;
for (i = 0; i < n; ++i)
x[i] = 2.0 * gsl_rng_uniform(r) - 1.0;
return 0;
}
/* calculate MAD statistic for input vector using slow/naive algorithm */
static double
slow_MAD(const size_t n, const double x[])
{
double *work = malloc(n * sizeof(double));
double median, mad;
size_t i;
for (i = 0; i < n; ++i)
work[i] = x[i];
gsl_sort(work, 1, n);
median = gsl_stats_median_from_sorted_data(work, 1, n);
for (i = 0; i < n; ++i)
work[i] = fabs(x[i] - median);
gsl_sort(work, 1, n);
mad = gsl_stats_median_from_sorted_data(work, 1, n);
free(work);
return mad;
}
/* calculate S_n statistic for input vector using slow/naive algorithm */
static double
slow_Sn0(const size_t n, const double x[])
{
double *work1 = malloc(n * sizeof(double));
double *work2 = malloc(n * sizeof(double));
double Sn;
size_t i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
work1[j] = fabs(x[i] - x[j]);
/* find himed_j | x_i - x_j | */
gsl_sort(work1, 1, n);
work2[i] = work1[n / 2];
}
/* find lomed_i { himed_j | x_i - x_j | } */
gsl_sort(work2, 1, n);
Sn = work2[(n + 1) / 2 - 1];
free(work1);
free(work2);
return Sn;
}
/* calculate Q_n statistic for input vector using slow/naive algorithm */
static double
slow_Qn0(const size_t n, const double x[])
{
const size_t wsize = n * (n - 1) / 2;
const size_t n_2 = n / 2;
const size_t k = ((n_2 + 1) * n_2) / 2;
double *work;
double Qn;
size_t idx = 0;
size_t i, j;
if (n < 2)
return (0.0);
work = malloc(wsize * sizeof(double));
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
work[idx++] = fabs(x[i] - x[j]);
}
gsl_sort(work, 1, idx);
Qn = work[k - 1];
free(work);
return Qn;
}
static int
test_median(const double tol, const size_t n, gsl_rng * r)
{
double * x = malloc(n * sizeof(double));
double median1, median2;
random_array(n, x, r);
median1 = gsl_stats_median(x, 1, n);
gsl_sort(x, 1, n);
median2 = gsl_stats_median_from_sorted_data(x, 1, n);
gsl_test_rel(median1, median2, tol, "test_median n=%zu", n);
free(x);
return 0;
}
static int
test_mad(const double tol, const size_t n, gsl_rng * r)
{
double * x = malloc(n * sizeof(double));
double * work = malloc(n * sizeof(double));
double mad1, mad2;
random_array(n, x, r);
mad1 = slow_MAD(n, x);
gsl_sort(x, 1, n);
mad2 = gsl_stats_mad0(x, 1, n, work);
gsl_test_rel(mad1, mad2, tol, "test_mad n=%zu", n);
free(x);
free(work);
return 0;
}
static int
test_Sn(const double tol, const size_t n, gsl_rng * r)
{
double * x = malloc(n * sizeof(double));
double * work = malloc(n * sizeof(double));
double Sn1, Sn2;
random_array(n, x, r);
/* compute S_n with slow/naive algorithm */
Sn1 = slow_Sn0(n, x);
/* compute S_n with efficient algorithm */
gsl_sort(x, 1, n);
Sn2 = gsl_stats_Sn0_from_sorted_data(x, 1, n, work);
gsl_test_rel(Sn2, Sn1, tol, "test_Sn n=%zu", n);
free(x);
free(work);
return 0;
}
static int
test_Qn(const double tol, const size_t n, gsl_rng * r)
{
double * x = malloc(n * sizeof(double));
double * work = malloc(3 * n * sizeof(double));
int * work_int = malloc(5 * n * sizeof(int));
double Qn1, Qn2;
random_array(n, x, r);
/* compute Q_n with slow/naive algorithm */
Qn1 = slow_Qn0(n, x);
/* compute Q_n with efficient algorithm */
gsl_sort(x, 1, n);
Qn2 = gsl_stats_Qn0_from_sorted_data(x, 1, n, work, work_int);
gsl_test_rel(Qn2, Qn1, tol, "test_Qn n=%zu", n);
free(x);
free(work);
free(work_int);
return 0;
}
int
test_robust (void)
{
const double tol = 1.0e-12;
gsl_rng * r = gsl_rng_alloc(gsl_rng_default);
test_median(GSL_DBL_EPSILON, 1, r);
test_median(GSL_DBL_EPSILON, 2, r);
test_median(GSL_DBL_EPSILON, 3, r);
test_median(GSL_DBL_EPSILON, 100, r);
test_median(GSL_DBL_EPSILON, 101, r);
test_median(GSL_DBL_EPSILON, 500, r);
test_median(GSL_DBL_EPSILON, 501, r);
test_mad(GSL_DBL_EPSILON, 1, r);
test_mad(GSL_DBL_EPSILON, 2, r);
test_mad(GSL_DBL_EPSILON, 3, r);
test_mad(GSL_DBL_EPSILON, 100, r);
test_mad(GSL_DBL_EPSILON, 101, r);
test_mad(GSL_DBL_EPSILON, 500, r);
test_mad(GSL_DBL_EPSILON, 501, r);
test_Sn(tol, 1, r);
test_Sn(tol, 2, r);
test_Sn(tol, 3, r);
test_Sn(tol, 100, r);
test_Sn(tol, 101, r);
test_Sn(tol, 500, r);
test_Sn(tol, 501, r);
test_Qn(tol, 1, r);
test_Qn(tol, 2, r);
test_Qn(tol, 3, r);
test_Qn(tol, 4, r);
test_Qn(tol, 5, r);
test_Qn(tol, 100, r);
test_Qn(tol, 101, r);
test_Qn(tol, 500, r);
test_Qn(tol, 501, r);
gsl_rng_free(r);
return 0;
}
| {
"alphanum_fraction": 0.6368753198,
"avg_line_length": 21.8768656716,
"ext": "c",
"hexsha": "b8535ae69df899d5ba7f0bbee8f4e77a3dd41270",
"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/statistics/test_robust.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/statistics/test_robust.c",
"max_line_length": 81,
"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/statistics/test_robust.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": 2010,
"size": 5863
} |
#pragma once
#include <vector>
#include <gsl/span>
#include "Mouse.h"
#include "Joystick.h"
#include "JoystickButton.h"
#include "Keyboard.h"
#include "RawInput.h"
#include "Xbox360Controller.h"
namespace qvr
{
class JoystickAxisThreshold
{
public:
JoystickAxisThreshold(
const qvr::JoystickAxis axis,
const float threshold,
const bool trueAboveThreshold)
: mJoystickAxis(axis)
, mThreshold(threshold)
, mTrueAboveThreshold(trueAboveThreshold)
{}
JoystickAxisThreshold(
const Xbox360Controller::Axis axis,
const float threshold,
const bool trueAboveThreshold)
: JoystickAxisThreshold(
Xbox360Controller::ToJoystickAxis(axis),
threshold,
trueAboveThreshold)
{
}
bool IsActive(const qvr::Joystick& joystick) const
{
const float v = joystick.GetPosition(mJoystickAxis);
if (mTrueAboveThreshold)
{
return v > mThreshold;
}
return v < mThreshold;
}
bool JustActive(const qvr::Joystick& joystick) const
{
const float current = joystick.GetPosition(mJoystickAxis);
const float previous = joystick.GetPreviousPosition(mJoystickAxis);
if (mTrueAboveThreshold)
{
return current > mThreshold && previous < mThreshold;
}
return current < mThreshold && previous > mThreshold;
}
private:
const qvr::JoystickAxis mJoystickAxis;
const float mThreshold;
const bool mTrueAboveThreshold;
};
}
class BinaryInput
{
public:
enum class Type
{
KeyboardKey,
MouseButton,
JoystickButton,
JoystickAxisThreshold
};
BinaryInput(qvr::KeyboardKey key)
: mType(Type::KeyboardKey)
, mKeyboardKey(key)
{}
BinaryInput(qvr::MouseButton mouseButton)
: mType(Type::MouseButton)
, mMouseButton(mouseButton)
{}
BinaryInput(qvr::JoystickButton joystickButton)
: mType(Type::JoystickButton)
, mJoystickButton(joystickButton)
{}
BinaryInput(qvr::JoystickAxisThreshold joystickAxisThreshold)
: mType(Type::JoystickAxisThreshold)
, mJoystickAxisThreshold(joystickAxisThreshold)
{}
bool IsActive(const qvr::RawInputDevices& devices) const
{
const auto joystickIndex = qvr::JoystickIndex(0);
const qvr::Joystick* joystick = devices.GetJoysticks().GetJoystick(joystickIndex);
switch (mType)
{
case Type::KeyboardKey:
return devices.GetKeyboard().IsDown(mKeyboardKey);
case Type::MouseButton:
return devices.GetMouse().IsDown(mMouseButton);
// TODO: Which joysticks?
case Type::JoystickButton:
if (joystick) {
return joystick->IsDown(mJoystickButton);
}
break;
case Type::JoystickAxisThreshold:
if (joystick) {
return mJoystickAxisThreshold.IsActive(*joystick);
}
break;
}
return false;
}
bool JustActive(const qvr::RawInputDevices& devices) const
{
const auto joystickIndex = qvr::JoystickIndex(0);
const qvr::Joystick* joystick = devices.GetJoysticks().GetJoystick(joystickIndex);
switch (mType)
{
case Type::KeyboardKey:
return devices.GetKeyboard().JustDown(mKeyboardKey);
case Type::MouseButton:
return devices.GetMouse().JustDown(mMouseButton);
// TODO: Which joysticks?
case Type::JoystickButton:
if (joystick) {
return joystick->JustDown(mJoystickButton);
}
break;
case Type::JoystickAxisThreshold:
if (joystick) {
return mJoystickAxisThreshold.JustActive(*joystick);
}
break;
}
return false;
}
private:
const Type mType;
union
{
const qvr::KeyboardKey mKeyboardKey;
const qvr::MouseButton mMouseButton;
const qvr::JoystickButton mJoystickButton;
const qvr::JoystickAxisThreshold mJoystickAxisThreshold;
};
};
inline bool AnyActive(const qvr::RawInputDevices& devices, const gsl::span<const BinaryInput> inputs) {
for (const BinaryInput input : inputs) {
if (input.IsActive(devices)) {
return true;
}
}
return false;
}
inline bool AnyJustActive(const qvr::RawInputDevices& devices, const gsl::span<const BinaryInput> inputs) {
for (const BinaryInput input : inputs) {
if (input.JustActive(devices)) {
return true;
}
}
return false;
} | {
"alphanum_fraction": 0.7355684396,
"avg_line_length": 22.2865168539,
"ext": "h",
"hexsha": "0b48cdba36166935ae972cae2ec8d7839d9e4611",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2020-03-19T10:08:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-22T14:47:57.000Z",
"max_forks_repo_head_hexsha": "c8ef9591117bdfc8d6fa509ae53451e0807f5686",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "rachelnertia/Quiver",
"max_forks_repo_path": "Source/Quiver/Quiver/Input/BinaryInput.h",
"max_issues_count": 46,
"max_issues_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4",
"max_issues_repo_issues_event_max_datetime": "2018-10-13T14:46:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-10-26T21:21:51.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "rachelnertia/Quarrel",
"max_issues_repo_path": "External/Quiver/Source/Quiver/Quiver/Input/BinaryInput.h",
"max_line_length": 107,
"max_stars_count": 39,
"max_stars_repo_head_hexsha": "69616179fc71305757549c7fcaccc22707a91ba4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "rachelnertia/Quarrel",
"max_stars_repo_path": "External/Quiver/Source/Quiver/Quiver/Input/BinaryInput.h",
"max_stars_repo_stars_event_max_datetime": "2020-03-31T22:19:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-10-22T15:47:39.000Z",
"num_tokens": 1072,
"size": 3967
} |
/**
* APER_CHECK - create a FITS image showing the locations of
* apertures.
*/
#include "aper_check.h"
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_vector.h>
#include "spce_output.h"
void mark_trace_in_aXe_mask(ap_pixel * ap_p, aXe_mask *mask)
{
gsl_vector_int *trace_inds;
int i, ind;
trace_inds = (gsl_vector_int *) get_trace_inds (ap_p);
for (i = 0; i < (int)trace_inds->size; i++)
{
ind = gsl_vector_int_get (trace_inds, i);
fprintf(stderr,"%d %d\n",ap_p[ind].p_x,ap_p[ind].p_y);
}
gsl_vector_int_free(trace_inds);
}
/**
Function to create and return a gsl array of the same size as the grism
part of n observation structure.
@param ob a pointer to an observation structure
@return a pointer to a newly allocated aXe_mask structure
*/
aXe_mask *
aXe_mask_init (observation * ob)
{
aXe_mask *mask;
long i,j;
double v;
/* Allocated space for the mask array */
mask = (aXe_mask *) malloc (sizeof (aXe_mask));
if (!mask)
{
aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Out of memory.");
}
/* Create the GSL image array */
mask->img = gsl_matrix_alloc (ob->grism->size1, ob->grism->size2);
// fprintf(stderr,"%ld %ld\n",ob->grism->size1,ob->grism->size2);
/* Initialise the mask array */
for (i=0;i<(int)ob->grism->size1;i++) {
for (j=0;j<(int)ob->grism->size2;j++) {
v = gsl_matrix_get(ob->grism,i,j);
gsl_matrix_set(mask->img, i,j, v);
}
}
//gsl_matrix_set_all (mask->img, 1.0);
return mask;
}
/**
* This function sets all the pixels listed in an ap_pixel list
* in an aXe_mask to 0.0
@param a pointer to a ap_pixel array
@param mask an existing aXe_mask structure
*/
void
add_ap_p_to_aXe_mask (ap_pixel * ap_p, aXe_mask * mask)
{
ap_pixel *cur_p;
if (ap_p==NULL) return;
for (cur_p = ap_p; cur_p->p_x != -1; cur_p++)
{
/* Loop over pixels which are valid */
if (!isnan (cur_p->count))
{
// fprintf(stderr,"%d %d\n",cur_p->p_x, cur_p->p_y);
gsl_matrix_set (mask->img, cur_p->p_x, cur_p->p_y, 0.0);
}
}
}
| {
"alphanum_fraction": 0.6271028037,
"avg_line_length": 22.2916666667,
"ext": "c",
"hexsha": "517b06b836f99c5525417164105e68bc35d561b6",
"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.c",
"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.c",
"max_line_length": 74,
"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.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 674,
"size": 2140
} |
/* bspline/gsl_bspline.h
*
* Copyright (C) 2006 Patrick Alken
* Copyright (C) 2008 Rhys Ulerich
*
* 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_BSPLINE_H__
#define __GSL_BSPLINE_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.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 k; /* spline order */
size_t km1; /* k - 1 (polynomial order) */
size_t l; /* number of polynomial pieces on interval */
size_t nbreak; /* number of breakpoints (l + 1) */
size_t n; /* number of bspline basis functions (l + k - 1) */
gsl_vector *knots; /* knots vector */
gsl_vector *deltal; /* left delta */
gsl_vector *deltar; /* right delta */
gsl_vector *B; /* temporary spline results */
/* bspline derivative parameters */
gsl_matrix *A; /* work matrix */
gsl_matrix *dB; /* temporary derivative results */
} gsl_bspline_workspace;
GSL_FUN gsl_bspline_workspace *
gsl_bspline_alloc(const size_t k, const size_t nbreak);
GSL_FUN void gsl_bspline_free(gsl_bspline_workspace *w);
GSL_FUN size_t gsl_bspline_ncoeffs(gsl_bspline_workspace * w);
GSL_FUN size_t gsl_bspline_order(gsl_bspline_workspace * w);
GSL_FUN size_t gsl_bspline_nbreak(gsl_bspline_workspace * w);
GSL_FUN double gsl_bspline_breakpoint(size_t i, gsl_bspline_workspace * w);
GSL_FUN double gsl_bspline_greville_abscissa(size_t i, gsl_bspline_workspace *w);
GSL_FUN int
gsl_bspline_knots(const gsl_vector *breakpts, gsl_bspline_workspace *w);
GSL_FUN int gsl_bspline_knots_uniform(const double a, const double b,
gsl_bspline_workspace *w);
GSL_FUN int
gsl_bspline_knots_greville(const gsl_vector *abscissae,
gsl_bspline_workspace *w,
double *abserr);
GSL_FUN int
gsl_bspline_eval(const double x, gsl_vector *B,
gsl_bspline_workspace *w);
GSL_FUN int
gsl_bspline_eval_nonzero(const double x,
gsl_vector *Bk,
size_t *istart,
size_t *iend,
gsl_bspline_workspace *w);
GSL_FUN int
gsl_bspline_deriv_eval(const double x,
const size_t nderiv,
gsl_matrix *dB,
gsl_bspline_workspace *w);
GSL_FUN int
gsl_bspline_deriv_eval_nonzero(const double x,
const size_t nderiv,
gsl_matrix *dB,
size_t *istart,
size_t *iend,
gsl_bspline_workspace *w);
__END_DECLS
#endif /* __GSL_BSPLINE_H__ */
| {
"alphanum_fraction": 0.664484023,
"avg_line_length": 32.0840336134,
"ext": "h",
"hexsha": "ecaa2dfa84ca8687d72e7f81c462dabc3c1e141b",
"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": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_bspline.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/gsl/gsl_bspline.h",
"max_line_length": 81,
"max_stars_count": null,
"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/gsl/gsl_bspline.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 946,
"size": 3818
} |
/*
NAME:
proj_gauss_mixtures
PURPOSE:
runs the full projected gaussian mixtures algorithms, with
regularization and split and merge
CALLING SEQUENCE:
proj_gauss_mixtures(struct datapoint * data, int N,
struct gaussian * gaussians, int K,bool * fixamp, bool * fixmean,
bool * fixcovar, double * avgloglikedata, double tol,
long long int maxiter, bool likeonly, double w, int splitnmerge,
bool keeplog, FILE *logfile, FILE *convlogfile, bool noproj,
bool diagerrs,noweight)
INPUT:
data - the data
N - number of datapoints
gaussians - model gaussians (initial conditions)
K - number of model gaussians
fixamp - fix the amplitude?
fixmean - fix the mean?
fixcovar - fix the covar?
tol - proj_EM convergence limit
maxiter - maximum number of iterations in each proj_EM
likeonly - only compute the likelihood?
w - regularization paramter
splitnmerge - split 'n' merge depth (how far down the list to go)
keeplog - keep a log in a logfile?
logfile - pointer to the logfile
convlogfile - pointer to the convlogfile
noproj - don't perform any projections
diagerrs - the data->SS errors-squared are diagonal
noweight - don't use data-weights
OUTPUT:
updated model gaussians
avgloglikedata - average log likelihood of the data
REVISION HISTORY:
2008-08-21 Written Bovy
2010-03-01 Added noproj option - Bovy
2010-04-01 Added noweight option - Bovy
*/
#ifdef _OPENMP
#include <omp.h>
#endif
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include "proj_gauss_mixtures.h"
void proj_gauss_mixtures(struct datapoint * data, int N,
struct gaussian * gaussians, int K,
bool * fixamp, bool * fixmean, bool * fixcovar,
double * avgloglikedata, double tol,
long long int maxiter, bool likeonly, double w,
int splitnmerge, bool keeplog, FILE *logfile,
FILE *convlogfile, bool noproj, bool diagerrs,
bool noweight){
//Allocate some memory
struct gaussian * startgaussians;
startgaussians = gaussians;
int d = (gaussians->VV)->size1;//dim of mm
//Only give copies of the fix* vectors to the EM algorithm
bool *fixamp_tmp, *fixmean_tmp,*fixcovar_tmp;
fixamp_tmp = (bool *) malloc(K * sizeof (bool) );
fixmean_tmp = (bool *) malloc(K * sizeof (bool) );
fixcovar_tmp = (bool *) malloc(K * sizeof (bool) );
int kk;
for (kk = 0; kk != K; ++kk){
*(fixamp_tmp++) = *(fixamp++);
*(fixmean_tmp++) = *(fixmean++);
*(fixcovar_tmp++) = *(fixcovar++);
}
fixamp -= K;
fixamp_tmp -= K;
fixmean -= K;
fixmean_tmp -= K;
fixcovar -= K;
fixcovar_tmp -= K;
//allocate the newalpha, newmm and newVV matrices
#ifdef _OPENMP
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
newgaussians = (struct gaussian *) malloc(K * nthreads * sizeof (struct gaussian) );
startnewgaussians = newgaussians;
int ll;
for (kk=0; kk != K*nthreads; ++kk){
newgaussians->alpha = 0.0;
newgaussians->mm = gsl_vector_calloc (d);
newgaussians->VV = gsl_matrix_calloc (d,d);
++newgaussians;
}
newgaussians= startnewgaussians;
double oldavgloglikedata;
//allocate the q_ij matrix
qij = gsl_matrix_alloc(N,K);
double * qstarij = (double *) malloc(N * sizeof (double) );
I = gsl_matrix_alloc(d,d);
gsl_matrix_set_identity(I);//Unit matrix
gsl_matrix_scale(I,w);//scaled to w
//Also take care of the bbij's and the BBij's
bs = (struct modelbs *) malloc(nthreads * K * sizeof (struct modelbs) );
for (kk = 0; kk != nthreads*K; ++kk){
bs->bbij = gsl_vector_alloc (d);
bs->BBij = gsl_matrix_alloc (d,d);
++bs;
}
bs -= nthreads*K;
//splitnmerge
int maxsnm = K*(K-1)*(K-2)/2;
int * snmhierarchy = (int *) malloc(maxsnm*3* sizeof (int) );
int j,k,l;
struct gaussian * oldgaussians = (struct gaussian *) malloc(K * sizeof (struct gaussian) );
gsl_matrix * oldqij = gsl_matrix_alloc(N,K);
for (kk=0; kk != K; ++kk){
oldgaussians->mm = gsl_vector_calloc (d);
oldgaussians->VV = gsl_matrix_calloc (d,d);
++oldgaussians;
}
oldgaussians -= K;
//create temporary file to hold convergence info
FILE *tmpconvfile;
char * tmpfilename= tmpnam(NULL);;
if (keeplog)
tmpconvfile= fopen(tmpfilename,"w+");
//proj_EM
if (keeplog)
fprintf(logfile,"#Initial proj_EM\n");
//printf("Where's the segmentation fault?\n");
proj_EM(data,N,gaussians,K,fixamp_tmp,fixmean_tmp,fixcovar_tmp,
avgloglikedata,tol,maxiter,likeonly,w,
keeplog,logfile,convlogfile,noproj,diagerrs,noweight);
if (keeplog){
fprintf(logfile,"\n");
fprintf(convlogfile,"\n");
}
//reset fix* vectors
for (kk = 0; kk != K; ++kk){
*(fixamp_tmp++) = *(fixamp++);
*(fixmean_tmp++) = *(fixmean++);
*(fixcovar_tmp++) = *(fixcovar++);
}
fixamp -= K;
fixamp_tmp -= K;
fixmean -= K;
fixmean_tmp -= K;
fixcovar -= K;
fixcovar_tmp -= K;
//Run splitnmerge
randgen = gsl_rng_alloc(gsl_rng_mt19937);
bool weretrying = true;
if (likeonly || splitnmerge == 0 || K < 3)
;
else {
while (weretrying){
weretrying = false; /* this is set back to true if an improvement is found */
//store avgloglike from normal EM and model parameters
oldavgloglikedata = *avgloglikedata;
gsl_matrix_memcpy(oldqij,qij);
for (kk=0; kk != K; ++kk){
oldgaussians->alpha = gaussians->alpha;
gsl_vector_memcpy(oldgaussians->mm,gaussians->mm);
gsl_matrix_memcpy(oldgaussians->VV,gaussians->VV);
++oldgaussians;
++gaussians;
}
gaussians -= K;
oldgaussians -= K;
//Then calculate the splitnmerge hierarchy
calc_splitnmerge(data,N,gaussians,K,qij,snmhierarchy);
//Then go through this hierarchy
kk=0;
while (kk != splitnmerge && kk != maxsnm){
//splitnmerge
j = *(snmhierarchy++);
k = *(snmhierarchy++);
l = *(snmhierarchy++);
splitnmergegauss(gaussians,K,oldqij,j,k,l);
//partial EM
//Prepare fixed vectors for partial EM
for (ll = 0; ll != K; ++ll){
*(fixamp_tmp++) = (ll != j && ll != k && ll != l);
*(fixmean_tmp++) = (ll != j && ll != k && ll != l);
*(fixcovar_tmp++) = (ll != j && ll != k && ll != l);
}
fixamp_tmp -= K;
fixmean_tmp -= K;
fixcovar_tmp -= K;
if (keeplog)
fprintf(logfile,"#Merging %i and %i, splitting %i\n",j,k,l);
proj_EM(data,N,gaussians,K,fixamp_tmp,fixmean_tmp,fixcovar_tmp,
avgloglikedata,tol,maxiter,likeonly,w,keeplog,logfile,
tmpconvfile,noproj,diagerrs,noweight);
//reset fix* vectors
for (ll = 0; ll != K; ++ll){
*(fixamp_tmp++) = *(fixamp++);
*(fixmean_tmp++) = *(fixmean++);
*(fixcovar_tmp++) = *(fixcovar++);
}
fixamp -= K;
fixamp_tmp -= K;
fixmean -= K;
fixmean_tmp -= K;
fixcovar -= K;
fixcovar_tmp -= K;
//Full EM
if (keeplog){
fprintf(logfile,"#full EM:\n");
fprintf(tmpconvfile,"\n");
}
proj_EM(data,N,gaussians,K,fixamp_tmp,fixmean_tmp,fixcovar_tmp,
avgloglikedata,tol,maxiter,likeonly,w,keeplog,logfile,
tmpconvfile,noproj,diagerrs,noweight);
if (keeplog){
fprintf(logfile,"\n");
fprintf(tmpconvfile,"\n");
}
//reset fix* vectors
for (ll = 0; ll != K; ++ll){
*(fixamp_tmp++) = *(fixamp++);
*(fixmean_tmp++) = *(fixmean++);
*(fixcovar_tmp++) = *(fixcovar++);
}
fixamp -= K;
fixamp_tmp -= K;
fixmean -= K;
fixmean_tmp -= K;
fixcovar -= K;
fixcovar_tmp -= K;
//Better?
if (*avgloglikedata > oldavgloglikedata){
if (keeplog){
fprintf(logfile,"#accepted\n");
//Copy tmpfile into convfile
fseek(tmpconvfile,0,SEEK_SET);
while (feof(tmpconvfile) == 0)
fputc(fgetc(tmpconvfile),convlogfile);
fseek(convlogfile,-1,SEEK_CUR);
fclose(tmpconvfile);
tmpconvfile= fopen(tmpfilename,"w+");
}
weretrying = true;
++kk;
break;
}
else {
if (keeplog){
fprintf(logfile,"#didn't improve likelihood\n");
fclose(tmpconvfile);
tmpconvfile= fopen(tmpfilename,"w+");
}
//revert back to the older solution
*avgloglikedata = oldavgloglikedata;
/* gsl_matrix_memcpy(qij,oldqij);*/
for (ll=0; ll != K; ++ll){
gaussians->alpha = oldgaussians->alpha;
gsl_vector_memcpy(gaussians->mm,oldgaussians->mm);
gsl_matrix_memcpy(gaussians->VV,oldgaussians->VV);
++oldgaussians;
++gaussians;
}
gaussians -= K;
oldgaussians -= K;
}
++kk;
}
snmhierarchy -= 3*kk;
}
}
if (keeplog){
fclose(tmpconvfile);
fprintf(convlogfile,"\n");
}
//Compute some criteria to set the number of Gaussians and print these to the logfile
int ii;
int npc,np;
double pc,aic,mdl;
if (keeplog){
//Partition coefficient
pc=0.;
for (ii=0; ii != N; ++ii)
for (kk=0; kk != K; ++kk)
pc += pow(exp(gsl_matrix_get(qij,ii,kk)),2);
pc /= N;
fprintf(logfile,"Partition coefficient \t=\t%f\n",pc);
//Akaike's information criterion
npc = 1 + d + d * (d - 1) / 2;
np = K * npc;
aic= -2 * ((double) N - 1. - npc - 100)* *avgloglikedata + 3 * np;
fprintf(logfile,"AIC \t\t\t=\t%f\n",aic);
//MDL
mdl = - *avgloglikedata * N + 0.5 * np * log(N);
fprintf(logfile,"MDL \t\t\t=\t%f\n",mdl);
}
//Free memory
gsl_matrix_free(I);
gsl_matrix_free(qij);
for (kk = 0; kk != nthreads*K; ++kk){
gsl_vector_free(bs->bbij);
gsl_matrix_free(bs->BBij);
++bs;
}
bs -= nthreads*K;
free(bs);
for (kk=0; kk != K*nthreads; ++kk){
gsl_vector_free(newgaussians->mm);
gsl_matrix_free(newgaussians->VV);
++newgaussians;
}
newgaussians= startnewgaussians;
free(newgaussians);
gsl_rng_free(randgen);
gsl_matrix_free(oldqij);
for (kk=0; kk != K; ++kk){
gsl_vector_free(oldgaussians->mm);
gsl_matrix_free(oldgaussians->VV);
++oldgaussians;
}
oldgaussians -= K;
free(oldgaussians);
free(qstarij);
free(snmhierarchy);
free(fixamp_tmp);
free(fixmean_tmp);
free(fixcovar_tmp);
return;
}
| {
"alphanum_fraction": 0.6318664945,
"avg_line_length": 29.2645348837,
"ext": "c",
"hexsha": "f6a12a3f2dc22da5cbafc7f4dd6d46d9df4bc5c6",
"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/proj_gauss_mixtures.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/proj_gauss_mixtures.c",
"max_line_length": 93,
"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/proj_gauss_mixtures.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3173,
"size": 10067
} |
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/matrix/gsl_matrix.h>
#define BASE_DOUBLE
#include <gsl/templates_on.h>
#include <gsl/matrix/minmax_source.c>
#include <gsl/templates_off.h>
#undef BASE_DOUBLE
| {
"alphanum_fraction": 0.7692307692,
"avg_line_length": 20.0909090909,
"ext": "c",
"hexsha": "9309cfe66fcf1a601458ae15dba4d50b80fe4e40",
"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": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/minmax.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"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": "MontyThibault/centre-of-mass-awareness",
"max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/minmax.c",
"max_line_length": 37,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/minmax.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 60,
"size": 221
} |
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#include <sys/time.h>
#include <inttypes.h>
#include <omp.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_heapsort.h>
#include "MZC3D64.h"
#include "MZC2D64.h"
#include "sph_data_types.h"
#include "sph_linked_list.h"
int safe_free_box(linkedListBox *box){
kh_destroy(0, box->hbegin);
kh_destroy(1, box->hend);
free(box);
return 0;
}
int compare_int64_t(const void *p,const void *q){
int64_t *data1,*data2;
data1 = (int64_t*)p;
data2 = (int64_t*)q;
if(data1[0] < data2[0])
return -1;
else if(data1[0] == data2[0])
return 0;
else
return 1;
}
#define safe_check_alloc(ptr,N,dtype) { \
(ptr) = (dtype*)malloc((N)*sizeof(dtype));\
if((ptr)==NULL){ \
success=0; \
goto finishlabel; \
} \
}
#define safe_check__aligned_alloc(ptr,alignment,N,dtype) { \
(ptr) = (dtype*)aligned_alloc(alignment,(N)*sizeof(dtype));\
if((ptr)==NULL){ \
success=0; \
goto finishlabel; \
} \
}
#define safe_free(ptr) { \
if(ptr != NULL)\
free(ptr); \
}
int SPHparticle_SoA_malloc(int N,SPHparticle **lsph){
int success=1;
(*lsph) = (SPHparticle*)malloc(1*sizeof(SPHparticle));
if(lsph==NULL){
success = 0;
goto finishlabel;
}
(*lsph)->x = NULL; (*lsph)->y = NULL; (*lsph)->z = NULL;
(*lsph)->ux = NULL; (*lsph)->uy = NULL; (*lsph)->uz = NULL;
(*lsph)->Fx = NULL; (*lsph)->Fy = NULL; (*lsph)->Fz = NULL;
(*lsph)->nu = NULL; (*lsph)->rho= NULL;
(*lsph)->id = NULL; (*lsph)->hash= NULL;
const int alignment = 32;
safe_check__aligned_alloc((*lsph)->x , alignment, N ,double);
safe_check__aligned_alloc((*lsph)->y , alignment, N ,double);
safe_check__aligned_alloc((*lsph)->z , alignment, N ,double);
safe_check__aligned_alloc((*lsph)->ux , alignment, N ,double);
safe_check__aligned_alloc((*lsph)->uy , alignment, N ,double);
safe_check__aligned_alloc((*lsph)->uz , alignment, N ,double);
safe_check__aligned_alloc((*lsph)->Fx , alignment, N ,double);
safe_check__aligned_alloc((*lsph)->Fy , alignment, N ,double);
safe_check__aligned_alloc((*lsph)->Fz , alignment, N ,double);
safe_check__aligned_alloc((*lsph)->nu , alignment, N ,double);
safe_check__aligned_alloc((*lsph)->rho , alignment, N ,double);
safe_check__aligned_alloc((*lsph)->id , alignment, N ,int64_t);
safe_check__aligned_alloc((*lsph)->hash, alignment,2*N,int64_t);
/*
safe_check_alloc((*lsph)->x , N ,double);
safe_check_alloc((*lsph)->y , N ,double);
safe_check_alloc((*lsph)->z , N ,double);
safe_check_alloc((*lsph)->ux , N ,double);
safe_check_alloc((*lsph)->uy , N ,double);
safe_check_alloc((*lsph)->uz , N ,double);
safe_check_alloc((*lsph)->Fx , N ,double);
safe_check_alloc((*lsph)->Fy , N ,double);
safe_check_alloc((*lsph)->Fz , N ,double);
safe_check_alloc((*lsph)->nu , N ,double);
safe_check_alloc((*lsph)->rho , N ,double);
safe_check_alloc((*lsph)->id , N ,int64_t);
safe_check_alloc((*lsph)->hash,2*N,int64_t);*/
finishlabel:
if(success)
return 0;
else{
if(*lsph==NULL)
return 1;
safe_free((*lsph)->x); safe_free((*lsph)->y); safe_free((*lsph)->z);
safe_free((*lsph)->ux); safe_free((*lsph)->uy); safe_free((*lsph)->uz);
safe_free((*lsph)->Fx); safe_free((*lsph)->Fy); safe_free((*lsph)->Fz);
safe_free((*lsph)->nu); safe_free((*lsph)->rho);
safe_free((*lsph)->id); safe_free((*lsph)->hash);
return 1;
}
}
int SPHparticleSOA_safe_free(int N,SPHparticle **lsph){
if(*lsph==NULL)
return 1;
safe_free((*lsph)->x); safe_free((*lsph)->y); safe_free((*lsph)->z);
safe_free((*lsph)->ux); safe_free((*lsph)->uy); safe_free((*lsph)->uz);
safe_free((*lsph)->Fx); safe_free((*lsph)->Fy); safe_free((*lsph)->Fz);
safe_free((*lsph)->nu); safe_free((*lsph)->rho);
safe_free((*lsph)->id); safe_free((*lsph)->hash);
free((*lsph));
return 0;
}
int arg_parse(int argc, char **argv, int64_t *N, double *h,
linkedListBox *box){
bool intern_h = true;
box->Xmin = -1.0; box->Ymin = -1.0; box->Zmin = -1.0;
box->Xmax = 2.0; box->Ymax = 2.0; box->Zmax = 2.0;
if(argc%2==0){
printf("wrong number of arguments!\n");
printf("Maybe an option is missing a value?\n");
}
for(int i=1;i<argc;i+=2){
if( strcmp(argv[i],"-N") == 0 ){
*N = (int64_t) atol(argv[i+1]);
printf("N particles = %ld\n",*N);
}
else if( strcmp(argv[i],"-h") == 0 ){
*h = atof(argv[i+1]);
printf("h = %lf\n",*h);
intern_h = false;
}
else if( strcmp(argv[i],"-Xmin") == 0 ){
box->Xmin = atof(argv[i+1]);
printf("Xmin = %lf\n",box->Xmin);
}
else if( strcmp(argv[i],"-Ymin") == 0 ){
box->Ymin = atof(argv[i+1]);
printf("Ymin = %lf\n",box->Ymin);
}
else if( strcmp(argv[i],"-Zmin") == 0 ){
box->Zmin = atof(argv[i+1]);
printf("Zmin = %lf\n",box->Zmin);
}
else if( strcmp(argv[i],"-Xmax") == 0 ){
box->Xmax = atof(argv[i+1]);
printf("Xmax = %lf\n",box->Xmax);
}
else if( strcmp(argv[i],"-Ymax") == 0 ){
box->Ymax = atof(argv[i+1]);
printf("Ymax = %lf\n",box->Ymax);
}
else if( strcmp(argv[i],"-Zmax") == 0 ){
box->Zmax = atof(argv[i+1]);
printf("Zmax = %lf\n",box->Zmax);
}
else if( strcmp(argv[i],"-Nx") == 0 ){
box->Nx = atol(argv[i+1]);
printf("Nx = %d\n",box->Nx);
}
else if( strcmp(argv[i],"-Ny") == 0 ){
box->Ny = atol(argv[i+1]);
printf("Ny = %d\n",box->Ny);
}
else if( strcmp(argv[i],"-Nz") == 0 ){
box->Nz = atol(argv[i+1]);
printf("Nz = %d\n",box->Nz);
}
else{
printf("unknown option: %s %s\n",argv[i],argv[i+1]);
}
}
if(intern_h){
box->Nx = (int)( (box->Xmax-box->Xmin)/(2*(*h)) );
box->Ny = (int)( (box->Ymax-box->Ymin)/(2*(*h)) );
box->Nz = (int)( (box->Zmax-box->Zmin)/(2*(*h)) );
}
box->N = (box->Nx)*(box->Ny)*(box->Nz);
double min_val = fmin((box->Xmax-box->Xmin)/box->Nx,fmin((box->Ymax-box->Ymin)/box->Ny,(box->Zmax-box->Zmin)/box->Nz));
box->width = (int)( 0.5 + 2*(*h)/min_val );
box->hbegin = kh_init(0);
box->hend = kh_init(1);
return 0;
}
int gen_unif_rdn_pos(int64_t N, int seed, SPHparticle *lsph){
const gsl_rng_type *T=NULL;
gsl_rng *r=NULL;
if(lsph==NULL)
return 1;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
gsl_rng_set(r,seed);
for(int64_t i=0;i<N;i+=1){
lsph->x[i] = gsl_rng_uniform(r);
lsph->y[i] = gsl_rng_uniform(r);
lsph->z[i] = gsl_rng_uniform(r);
lsph->ux[i] = 0.0; lsph->Fx[i] = 0.0;
lsph->uy[i] = 0.0; lsph->Fy[i] = 0.0;
lsph->uz[i] = 0.0; lsph->Fz[i] = 0.0;
lsph->nu[i] = 1.0/N;
lsph->rho[i] = 0.0;
lsph->id[i] = (int64_t) i;
lsph->hash[2*i+0] = (int64_t) 0;
lsph->hash[2*i+1] = (int64_t) i;
}
gsl_rng_free(r);
return 0;
}
int gen_unif_rdn_pos_box(int64_t N, int seed, linkedListBox *box,SPHparticle *lsph){
const gsl_rng_type *T=NULL;
gsl_rng *r=NULL;
if(lsph==NULL)
return 1;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
gsl_rng_set(r,seed);
for(int64_t i=0;i<N;i+=1){
lsph->x[i] = gsl_rng_uniform(r)*(box->Xmax-box->Xmin) + box->Xmin;
lsph->y[i] = gsl_rng_uniform(r)*(box->Ymax-box->Ymin) + box->Ymin;
lsph->z[i] = gsl_rng_uniform(r)*(box->Zmax-box->Zmin) + box->Zmin;
lsph->ux[i] = 0.0; lsph->Fx[i] = 0.0;
lsph->uy[i] = 0.0; lsph->Fy[i] = 0.0;
lsph->uz[i] = 0.0; lsph->Fz[i] = 0.0;
lsph->nu[i] = 1.0/N;
lsph->rho[i] = 0.0;
lsph->id[i] = (int64_t) i;
lsph->hash[2*i+0] = (int64_t) 0;
lsph->hash[2*i+1] = (int64_t) i;
}
gsl_rng_free(r);
return 0;
}
int print_time_stats(int runs, double *times){
double t[5], dt[5], total_time, dtotal_time;
printf("fast neighbour search / SoA / outer-openMP / symmetric load balanced\n");
total_time = 0.;
for(int k=0;k<5;k+=1){
t[k]=0.; dt[k]=0.;
for(int run=0;run<runs;run+=1)
t[k] += times[5*run+k];
t[k] /= runs;
for(int run=0;run<runs;run+=1)
dt[k] += (times[5*run+k]-t[k])*(times[5*run+k]-t[k]);
dt[k] /= runs;
dt[k] = sqrt(dt[k]);
total_time += t[k];
}
dtotal_time = 0.;
for(int run=0;run<runs;run+=1){
double rgm = 0.;
for(int k=0;k<5;k+=1)
rgm += times[5*run+k];
dtotal_time += (rgm-total_time)*(rgm-total_time);
}
dtotal_time /= runs;
dtotal_time = sqrt(dtotal_time);
printf("compute_hash_MC3D calc time : %.5lf +- %.6lf s : %.3lg%% +- %.3lg%%\n",t[0],dt[0],100*t[0]/total_time,100*dt[0]/total_time);
printf("qsort calc time : %.5lf +- %.6lf s : %.3lg%% +- %.3lg%%\n",t[1],dt[1],100*t[1]/total_time,100*dt[1]/total_time);
printf("reorder_lsph_SoA calc time : %.5lf +- %.6lf s : %.3lg%% +- %.3lg%%\n",t[2],dt[2],100*t[2]/total_time,100*dt[2]/total_time);
printf("setup_interval_hashtables calc time : %.5lf +- %.6lf s : %.3lg%% +- %.3lg%%\n",t[3],dt[3],100*t[3]/total_time,100*dt[3]/total_time);
printf("compute_density_3d load balanced calc time : %.5lf +- %.6lf s : %.3lg%% +- %.3lg%%\n",t[4],dt[4],100*t[4]/total_time,100*dt[4]/total_time);
printf("compute_density_3d load balanced total time : %.5lf +- %.6lf s : %.3lf%%\n",total_time,dtotal_time,100.);
return 0;
}
int compute_hash_MC3D(int64_t N, SPHparticle *lsph, linkedListBox *box){
if(lsph==NULL)
return 1;
if(box==NULL)
return 1;
const double etax = box->Nx/(box->Xmax - box->Xmin);
const double etay = box->Ny/(box->Ymax - box->Ymin);
const double etaz = box->Nz/(box->Zmax - box->Zmin);
for(int64_t i=0;i<N;i+=1){
uint32_t kx,ky,kz;
kx = (uint32_t)(etax*(lsph->x[i] - box->Xmin));
ky = (uint32_t)(etay*(lsph->y[i] - box->Ymin));
kz = (uint32_t)(etaz*(lsph->z[i] - box->Zmin));
if((kx<0)||(ky<0)||(kz<0))
return 1;
else if((kx>=box->Nx)||(ky>=box->Nx)||(kz>=box->Nx))
return 1;
else{
lsph->hash[2*i] = ullMC3Dencode(kx,ky,kz);
}
}
return 0;
}
int compute_hash_MC2D(int64_t N, SPHparticle *lsph, linkedListBox *box){
if(lsph==NULL)
return 1;
if(box==NULL)
return 1;
const double etax = box->Nx/(box->Xmax - box->Xmin);
const double etay = box->Ny/(box->Ymax - box->Ymin);
for(int64_t i=0;i<N;i+=1){
uint32_t kx,ky;
kx = (uint32_t)(etax*(lsph->x[i] - box->Xmin));
ky = (uint32_t)(etay*(lsph->y[i] - box->Ymin));
if((kx<0)||(ky<0))
return 1;
else if((kx>=box->Nx)||(ky>=box->Nx))
return 1;
else
lsph->hash[2*i] = ullMC2Dencode(kx,ky);
}
return 0;
}
#define swap_loop(N,lsph,temp_swap,member,type) for(int64_t i=0;i<(N);i+=1) \
(temp_swap)[i] = (lsph)->member[(lsph)->hash[2*i+1]];\
memcpy((lsph)->member,temp_swap,(N)*sizeof(type))
int reorder_lsph_SoA(int N, SPHparticle *lsph, void *swap_arr){
int64_t *int64_temp_swap = (int64_t *)swap_arr;
swap_loop(N,lsph,int64_temp_swap,id ,int64_t);
double *double_temp_swap = (double *)swap_arr;
swap_loop(N,lsph,double_temp_swap,nu ,double);
swap_loop(N,lsph,double_temp_swap,rho,double);
swap_loop(N,lsph,double_temp_swap,x ,double);
swap_loop(N,lsph,double_temp_swap,y ,double);
swap_loop(N,lsph,double_temp_swap,z ,double);
swap_loop(N,lsph,double_temp_swap,ux ,double);
swap_loop(N,lsph,double_temp_swap,uy ,double);
swap_loop(N,lsph,double_temp_swap,uz ,double);
swap_loop(N,lsph,double_temp_swap,Fx ,double);
swap_loop(N,lsph,double_temp_swap,Fy ,double);
swap_loop(N,lsph,double_temp_swap,Fz ,double);
return 0;
}
int setup_interval_hashtables(int64_t N,SPHparticle *lsph,linkedListBox *box){
int ret;
int64_t hash0 = lsph->hash[2*0];
khiter_t kbegin,kend;
if(lsph==NULL)
return 1;
if(box==NULL)
return 1;
kbegin = kh_put(0, box->hbegin, lsph->hash[2*0], &ret); kh_value(box->hbegin, kbegin) = (int64_t)0;
for(int64_t i=0;i<N;i+=1){
lsph->hash[i] = lsph->hash[2*i];
if(lsph->hash[i] == hash0)
continue;
hash0 = lsph->hash[i];
kend = kh_put(1, box->hend , lsph->hash[i-1], &ret); kh_value(box->hend , kend) = i;
kbegin = kh_put(0, box->hbegin, lsph->hash[i ], &ret); kh_value(box->hbegin, kbegin) = i;
}
// TODO: possible bug? verify 2*(N-1) instead of N-1
kend = kh_put(1, box->hend , lsph->hash[2*(N-1)], &ret); kh_value(box->hend , kend) = N;
return 0;
}
int neighbour_hash_3d(int64_t hash,int64_t *nblist,int width, linkedListBox *box){
int idx=0,kx=0,ky=0,kz=0;
kx = ullMC3DdecodeX(hash);
ky = ullMC3DdecodeY(hash);
kz = ullMC3DdecodeZ(hash);
for(int ix=-width;ix<=width;ix+=1){
for(int iy=-width;iy<=width;iy+=1){
for(int iz=-width;iz<=width;iz+=1){
if((kx+ix<0)||(ky+iy<0)||(kz+iz<0))
nblist[idx++] = -1;
else if( (kx+ix>=box->Nx)||(ky+iy>=box->Ny)||(kz+iz>=box->Nz) )
nblist[idx++] = -1;
else if( kh_get(0, box->hbegin, ullMC3Dencode(kx+ix,ky+iy,kz+iz)) == kh_end(box->hbegin) )
nblist[idx++] = -1;
else
nblist[idx++] = ullMC3Dencode(kx+ix,ky+iy,kz+iz);
}
}
}
return 0;
}
int neighbour_hash_2d(int64_t hash,int64_t *nblist,int width, linkedListBox *box){
int idx=0,kx=0,ky=0;
kx = ullMC2DdecodeX(hash);
ky = ullMC2DdecodeY(hash);
for(int ix=-width;ix<=width;ix+=1){
for(int iy=-width;iy<=width;iy+=1){
if((kx+ix<0)||(ky+iy<0))
nblist[idx++] = -1;
else if((kx+ix>=box->Nx)||(ky+iy>=box->Ny))
nblist[idx++] = -1;
else if( kh_get(0, box->hbegin, ullMC2Dencode(kx+ix,ky+iy)) == kh_end(box->hbegin) )
nblist[idx++] = -1;
else
nblist[idx++] = ullMC2Dencode(kx+ix,ky+iy);
}
}
return 0;
}
int print_boxes_populations(linkedListBox *box){
khiter_t kbegin,kend;
for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){
if (kh_exist(box->hbegin, kbegin)){
kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));
printf("hash - (begin,end) = %lu - (%lu,%lu): %ld\n",
kh_key(box->hbegin, kbegin),
kh_value(box->hbegin, kbegin),
kh_value(box->hend, kend),
((int64_t)kh_value(box->hend, kend))-((int64_t)kh_value(box->hbegin, kbegin)));
}
}
return 0;
}
int print_neighbour_list_MC3D(int64_t Nmax,unsigned int width,unsigned int stride,SPHparticle *lsph,linkedListBox *box){
int64_t nblist[(2*width+1)*(2*width+1)*(2*width+1)];
for(int64_t i=0;i<Nmax;i+=(int64_t)stride){
int res = neighbour_hash_3d(lsph->hash[i],nblist,width,box);
if(res!=0)
printf("invalid neighbour_hash_3d calculation\n");
printf("origin hash %lu : (%d,%d,%d) \n",lsph->hash[i],ullMC3DdecodeX(lsph->hash[i]),
ullMC3DdecodeY(lsph->hash[i]),
ullMC3DdecodeZ(lsph->hash[i]));
for(unsigned int j=0;j<(2*width+1)*(2*width+1)*(2*width+1);j+=1){
if(nblist[j]>=0)
printf(" neighbour hash %lu : (%d,%d,%d) \n",nblist[j],ullMC3DdecodeX(nblist[j]),
ullMC3DdecodeY(nblist[j]),
ullMC3DdecodeZ(nblist[j]));
else
printf("no neighbour here\n");
}
printf("\n\n");
}
return 0;
}
int print_neighbour_list_MC2D(int64_t Nmax,unsigned int width,unsigned int stride,SPHparticle *lsph,linkedListBox *box){
int64_t nblist[(2*width+1)*(2*width+1)];
for(int64_t i=0;i<Nmax;i+=(int64_t)stride){
int res = neighbour_hash_2d(lsph->hash[i],nblist,width,box);
if(res!=0)
printf("invalid neighbour_hash_3d calculation\n");
printf("origin hash %lu : (%d,%d) \n",lsph->hash[i],ullMC2DdecodeX(lsph->hash[i]),
ullMC2DdecodeY(lsph->hash[i]));
for(unsigned int j=0;j<(2*width+1)*(2*width+1);j+=1){
if(nblist[j]>=0)
printf(" neighbour hash %lu : (%d,%d) \n",nblist[j],ullMC3DdecodeX(lsph->hash[i]),
ullMC3DdecodeY(lsph->hash[i]));
else
printf("no neighbour here\n");
}
printf("\n\n");
}
return 0;
}
int print_neighbour_list_MC3D_lsph_file(int64_t Nmax,unsigned int width,unsigned int stride,SPHparticle *lsph,linkedListBox *box){
FILE *fp;
int64_t nblist[(2*width+1)*(2*width+1)*(2*width+1)];
fp = fopen("data/nblist_MC3D.csv","w");
const double etax = box->Nx/(box->Xmax - box->Xmin);
const double etay = box->Ny/(box->Ymax - box->Ymin);
const double etaz = box->Nz/(box->Zmax - box->Zmin);
for(int64_t i=0;i<Nmax;i+=(int64_t)stride){
uint32_t kx,ky,kz;
int res = neighbour_hash_3d(lsph->hash[i],nblist,width,box);
if(res!=0)
printf("invalid neighbour_hash_3d calculation\n");
kx = (uint32_t)(etax*(lsph->x[i] - box->Xmin));
ky = (uint32_t)(etay*(lsph->y[i] - box->Ymin));
kz = (uint32_t)(etaz*(lsph->z[i] - box->Zmin));
fprintf(fp,"base hash %lu : (%d,%d,%d) \n",lsph->hash[i],kx,ky,kz);
fprintf(fp,"origin hash %lu : (%d,%d,%d) \n",lsph->hash[i],ullMC3DdecodeX(lsph->hash[i]),
ullMC3DdecodeY(lsph->hash[i]),
ullMC3DdecodeZ(lsph->hash[i]));
for(unsigned int j=0;j<(2*width+1)*(2*width+1)*(2*width+1);j+=1)
if(nblist[j]>=0){
fprintf(fp," %lu:(%d,%d,%d)",nblist[j],ullMC3DdecodeX(nblist[j]),
ullMC3DdecodeY(nblist[j]),
ullMC3DdecodeZ(nblist[j]));
if(j<(2*width+1)*(2*width+1)*(2*width+1)-1)
fprintf(fp,",");
}
fprintf(fp,"\n\n");
}
fclose(fp);
return 0;
}
int print_neighbour_list_MC3D_lsph_ids_file(int N, SPHparticle *lsph, linkedListBox *box){
int res;
khiter_t kbegin,kend;
int64_t node_hash=-1,node_begin=0, node_end=0;
int64_t nb_begin= 0, nb_end = 0;
int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];
FILE *fp = fopen("data/nblist_ll.json","w");
fprintf(fp,"{\n");
for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){
if (kh_exist(box->hbegin, kbegin)){
kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin));
node_hash = kh_key(box->hbegin, kbegin);
node_begin = kh_value(box->hbegin, kbegin);
node_end = kh_value(box->hend, kend);
res = neighbour_hash_3d(node_hash,nblist,box->width,box);
if(res!=0)
printf("invalid neighbour_hash_3d calculation\n");
for(int64_t ii=node_begin;ii<node_end;ii+=1){
fprintf(fp,"\"%ld\":[",lsph->id[ii]);
for(int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){
if(nblist[j]>=0){
//nb_hash = nblist[j];
nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) );
nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) );
for(int64_t jj=nb_begin;jj<nb_end;jj+=1)
fprintf(fp,"%ld, ",lsph->id[jj]);
}
}
if((kbegin==kh_end(box->hbegin)-1)&&(ii==node_end-1))
fprintf(fp,"-1]\n");
else
fprintf(fp,"-1],\n");
}
}
}
fprintf(fp,"}");
fflush(fp);
fclose(fp);
return 0;
}
int print_neighbour_list_MC2D_lsph_file(int64_t Nmax,unsigned int width,unsigned int stride,SPHparticle *lsph,linkedListBox *box){
FILE *fp;
int64_t nblist[(2*width+1)*(2*width+1)];
fp = fopen("data/nblist_MC2D.csv","w");
const double etax = box->Nx/(box->Xmax - box->Xmin);
const double etay = box->Ny/(box->Ymax - box->Ymin);
for(int64_t i=0;i<Nmax;i+=(int64_t)stride){
uint32_t kx,ky;
int res = neighbour_hash_2d(lsph->hash[i],nblist,width,box);
if(res!=0)
printf("invalid neighbour_hash_3d calculation\n");
kx = (uint32_t)(etax*(lsph->x[i] - box->Xmin));
ky = (uint32_t)(etay*(lsph->y[i] - box->Ymin));
fprintf(fp,"base hash %lu : (%d,%d) \n",lsph->hash[i],kx,ky);
fprintf(fp,"origin hash %lu : (%d,%d) \n",lsph->hash[i],ullMC2DdecodeX(lsph->hash[i]),
ullMC2DdecodeY(lsph->hash[i]));
for(unsigned int j=0;j<(2*width+1)*(2*width+1);j+=1)
if(nblist[j]>=0){
fprintf(fp," %lu:(%d,%d)",nblist[j], ullMC2DdecodeX(nblist[j]),
ullMC2DdecodeY(nblist[j]));
if(j<(2*width+1)*(2*width+1)-1)
fprintf(fp,",");
}
fprintf(fp,"\n\n");
}
fclose(fp);
return 0;
}
/*
int main(){
int j=0,numThreads=6,err;
int64_t N = 100000;
double S=0.,S2=0.;
linkedListBox *box;
SPHparticle *lsph;
lsph = (SPHparticle*)malloc(N*sizeof(SPHparticle));
err = gen_unif_rdn_pos( N,123123123,lsph);
box = (linkedListBox*)malloc(1*sizeof(linkedListBox));
box->Nx = box->Ny = box->Nz = 10;
box->N = (box->Nx)*(box->Ny)*(box->Nz);
box->Xmin.x = 0.0; box->Xmin.y = 0.0; box->Xmin.z = 0.0;
box->Xmax.x = 1.0; box->Xmax.y = 1.0; box->Xmax.z = 1.0;
box->hbegin = kh_init(0);
box->hend = kh_init(1);
err = compute_hash_MC3D(N,lsph,box);
qsort(lsph,N,sizeof(SPHparticle),compare_SPHparticle);
err = setup_interval_hashtables(N,lsph,box);
//print_boxes_populations(box);
//print_neighbour_list_MC3D(N,1,N/13,lsph,box);
print_neighbour_list_MC3D_lsph_file(N,1,1,lsph,box);
free(lsph);
safe_free_box(box);
return 0;
}*/
////////////////////////////////////////////////////////////////////
// https://stackoverflow.com/questions/16007640/openmp-parallel-quicksort
#define TASK_SIZE 24
int64_t partition(int64_t * a, int64_t p, int64_t r)
{
int64_t lt[2*(r-p)];
int64_t gt[2*(r-p)];
int64_t i;
int64_t j;
int64_t key0 = a[2*r+0];
int64_t key1 = a[2*r+1];
int64_t lt_n = 0;
int64_t gt_n = 0;
for(i = p; i < r; i++){
if(a[2*i] < a[2*r]){
lt[2*lt_n+0] = a[2*i+0];
lt[2*lt_n+1] = a[2*i+1];
lt_n++;
}else{
gt[2*gt_n+0] = a[2*i+0];
gt[2*gt_n+1] = a[2*i+1];
gt_n++;
}
}
for(i = 0; i < lt_n; i++){
a[2*(p + i)+0] = lt[2*i+0];
a[2*(p + i)+1] = lt[2*i+1];
}
a[2*(p + lt_n)+0] = key0;
a[2*(p + lt_n)+1] = key1;
for(j = 0; j < gt_n; j++){
a[2*(p + lt_n + j + 1)+0] = gt[2*j+0];
a[2*(p + lt_n + j + 1)+1] = gt[2*j+1];
}
return p + lt_n;
}
void quicksort_omp(int64_t * a, int64_t p, int64_t r)
{
int64_t div;
if(p < r){
div = partition(a, p, r);
#pragma omp task shared(a) if(r - p > TASK_SIZE)
quicksort_omp(a, p, div - 1);
#pragma omp task shared(a) if(r - p > TASK_SIZE)
quicksort_omp(a, div + 1, r);
}
}
| {
"alphanum_fraction": 0.5632059549,
"avg_line_length": 29.892626132,
"ext": "c",
"hexsha": "fe79d2911e73e0fbebdc5f0eff2108f30cec1c01",
"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": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "jhelsas/sphalerite",
"max_forks_repo_path": "src/sph_linked_list.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"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": "jhelsas/sphalerite",
"max_issues_repo_path": "src/sph_linked_list.c",
"max_line_length": 150,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d85b53e82f4dafc4740ddeda52860258db972f9b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "jhelsas/sphalerite",
"max_stars_repo_path": "src/sph_linked_list.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8163,
"size": 23107
} |
/*
* Kabsch's algorithm: compute least-square-best transformation
* Copyright (C) 2003, Arno Formella (formella@ei.uvigo.es)
*
* 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.
*
* This is a gsl-based implementation of Kabsch's algorithm presented in:
*
* W. Kabsch, A solution for the best rotation to relate two sets of vectors,
* Acta Cryst. (1976), A32, 922-923
*
* W. Kabsch, A discussion of the solution for the best rotation to relate
* two sets of vectors, Acta Cryst. (1978), A34, 827-828
*
* The code is C++-robust.
*
* More information about GSL
* ==========================
*
* The project homepage is http://www.gnu.org/software/gsl/
* The development site is http://sources.redhat.com/gsl/
*/
#ifndef KABSCH_H
#define KABSCH_H
#include <gsl/gsl_vector_double.h>
#include <gsl/gsl_matrix_double.h>
#if defined(__cplusplus)
extern "C" {
#endif
/*
preconditions:
size > 0
X and Y point to (size x 3)-matrices specifying 3D points x_i and y_i
U points to a (3 x 3)-matrix
t points to a (3)-vector
s points to double
postconditions if return 1:
X and Y will be centralized at their respective origins
U will hold the rotation
t will hold the translation
s will hold the scaling value
such that:
sum_i (U * s * x_i + t - y_i)^2 is minimal
postconditions if return 0:
X and Y will be centralized at their respective origins
U will hold the identity
t will hold the difference vector of the centroids t = cy -cx
s will hold 1.0
note:
if s == NULL, no scaling is computed
*/
int kabsch(
unsigned int size,
gsl_matrix *X,
gsl_matrix *Y,
gsl_matrix *U,
gsl_vector *t,
double *s
);
#if defined(__cplusplus)
}
#endif
#endif
| {
"alphanum_fraction": 0.6878664862,
"avg_line_length": 28.4230769231,
"ext": "h",
"hexsha": "3220d18d336d58b95c951f767f4584b3639f25c4",
"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": "73091be81d16441a8c866286577ba7c9a555caaf",
"max_forks_repo_licenses": [
"Xnet",
"X11"
],
"max_forks_repo_name": "robpearc/FoldDesign",
"max_forks_repo_path": "bin/EvoDesignX/src/kabsch.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "73091be81d16441a8c866286577ba7c9a555caaf",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Xnet",
"X11"
],
"max_issues_repo_name": "robpearc/FoldDesign",
"max_issues_repo_path": "bin/EvoDesignX/src/kabsch.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "73091be81d16441a8c866286577ba7c9a555caaf",
"max_stars_repo_licenses": [
"Xnet",
"X11"
],
"max_stars_repo_name": "robpearc/FoldDesign",
"max_stars_repo_path": "bin/EvoDesignX/src/kabsch.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 592,
"size": 2217
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_movstat.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_statistics.h>
double
func(const size_t n, double x[], void * params)
{
const double alpha = *(double *) params;
gsl_sort(x, 1, n);
return gsl_stats_trmean_from_sorted_data(alpha, x, 1, n);
}
int
main(void)
{
const size_t N = 1000; /* length of time series */
const size_t K = 11; /* window size */
double alpha = 0.1; /* trimmed mean parameter */
gsl_vector *x = gsl_vector_alloc(N); /* input vector */
gsl_vector *y = gsl_vector_alloc(N); /* filtered output vector for alpha1 */
gsl_rng *r = gsl_rng_alloc(gsl_rng_default);
gsl_movstat_workspace *w = gsl_movstat_alloc(K);
gsl_movstat_function F;
size_t i;
double sum = 0.0;
/* generate input signal */
for (i = 0; i < N; ++i)
{
double ui = gsl_ran_gaussian(r, 1.0);
double outlier = (gsl_rng_uniform(r) < 0.01) ? 10.0*GSL_SIGN(ui) : 0.0;
sum += ui;
gsl_vector_set(x, i, sum + outlier);
}
/* apply moving window function */
F.function = func;
F.params = α
gsl_movstat_apply(GSL_MOVSTAT_END_PADVALUE, &F, x, y, w);
/* print results */
for (i = 0; i < N; ++i)
{
double xi = gsl_vector_get(x, i);
double yi = gsl_vector_get(y, i);
printf("%f %f\n", xi, yi);
}
gsl_vector_free(x);
gsl_vector_free(y);
gsl_rng_free(r);
gsl_movstat_free(w);
return 0;
}
| {
"alphanum_fraction": 0.6186599875,
"avg_line_length": 24.196969697,
"ext": "c",
"hexsha": "5a603140a8f25975ee921cf3b1d327a9fdf692d5",
"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/doc/examples/movstat3.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/doc/examples/movstat3.c",
"max_line_length": 79,
"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/doc/examples/movstat3.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": 490,
"size": 1597
} |
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <Python.h>
#include <numpy/arrayobject.h>
void mark_debug (void)
{
static int number;
printf("---> Mark %d <---\n", number);
fflush(stdout);
number++;
}
void label_debug (const char * label)
{
printf("---> Mark %s <---\n", label);
fflush(stdout);
}
/* =========================== Pure-C source code =========================== */
/* Regularization workspace */
struct rglz_wksp {
double lamb; /* Lambda value */
gsl_vector *Ldiag; /* Pointer to vector with diagonal values of the
* regularization matrix L. */
const gsl_vector *Y; /* Pointer to original Y */
gsl_vector *Ys; /* Ponter to Y vector of the standard form. */
const gsl_matrix *X; /* Pointer to original X matrix */
gsl_matrix *Xs; /* Pointer to X matrix of the standard form. */
gsl_multifit_linear_workspace *lwksp; /* Pointer to GSL workspace where SVDs are stored. */
/* L-curve data */
struct lcurve {
gsl_vector *reg_param;
gsl_vector *rho;
gsl_vector *eta;
} lcurve;
};
typedef struct rglz_wksp rglz_wksp;
/* Allocate and initialize inner variables of a regularization workspace. */
rglz_wksp * rglz_init(const double *Ldiag, const int p,
const gsl_vector *Y, const gsl_matrix *X, const gsl_vector *W,
gsl_multifit_linear_workspace *lwksp)
{
rglz_wksp *rw;
/* Allocate space for the workspace */
rw = (rglz_wksp*) malloc(sizeof(rglz_wksp));
rw->lamb = 0.0; /* Initial value */
rw->lcurve.reg_param = NULL;
rw->lcurve.rho = NULL;
rw->lcurve.eta = NULL;
/* Allocate space for the standard-form matrixes */
rw->Xs = gsl_matrix_alloc(X->size1, X->size2);
rw->Ys = gsl_vector_alloc(Y->size);
/* Initialize the regularization weights Ldiag */
rw->Ldiag = gsl_vector_alloc(p);
for (int i = 0; i < p; i++)
gsl_vector_set(rw->Ldiag, i, Ldiag[i]);
/* Convert the system to standard form */
gsl_multifit_linear_wstdform1(rw->Ldiag, X, W, Y, rw->Xs, rw->Ys, lwksp);
/* Calculate SVD of standard-form matrix Xs */
gsl_multifit_linear_svd(rw->Xs, lwksp);
rw->lwksp = lwksp;
rw->X = X;
rw->Y = Y;
return rw;
}
void rglz_estimate_lambda(rglz_wksp *rw, const int lcsize)
{
size_t idx; /* Temporary index to store corner of the L-curve */
/* Allocate vectors */
rw->lcurve.reg_param = gsl_vector_alloc(lcsize);
rw->lcurve.rho = gsl_vector_alloc(lcsize);
rw->lcurve.eta = gsl_vector_alloc(lcsize);
/* Create Lcurve */
gsl_multifit_linear_lcurve(rw->Y, rw->lcurve.reg_param, rw->lcurve.rho, rw->lcurve.eta, rw->lwksp);
#ifdef PRINT_LCURVE
for (int i = 0; i < lcsize; i++)
{
printf("%12.4e%12.4e\n",
gsl_vector_get(rw->lcurve.rho, i),
gsl_vector_get(rw->lcurve.eta, i));
}
#endif
/* Estimate corner */
gsl_multifit_linear_lcorner(rw->lcurve.rho, rw->lcurve.eta, &idx);
/* Set lambda estimate */
rw->lamb = gsl_vector_get(rw->lcurve.reg_param, idx);
fprintf(stdout, "From gslpy_ridge: lambda = %.4e\n", rw->lamb);
}
void rglz_solve(gsl_vector *c, double *rnorm, double *snorm, rglz_wksp *rw)
{
/* Solve in standard form */
gsl_multifit_linear_solve(rw->lamb, rw->Xs, rw->Ys, c, rnorm, snorm, rw->lwksp);
/* Convert back to original parameters */
gsl_multifit_linear_genform1(rw->Ldiag, c, c, rw->lwksp);
return;
}
inline void rglz_set_lambda(rglz_wksp *rw, const int lamb)
{
rw->lamb = lamb;
}
void rglz_close(rglz_wksp *rw)
{
gsl_vector_free(rw->Ldiag);
gsl_matrix_free(rw->Xs);
gsl_vector_free(rw->Ys);
if (rw->lcurve.reg_param != NULL)
gsl_vector_free(rw->lcurve.reg_param);
if (rw->lcurve.rho != NULL)
gsl_vector_free(rw->lcurve.rho);
if (rw->lcurve.eta != NULL)
gsl_vector_free(rw->lcurve.eta);
free(rw);
}
int
gslpy_ridge_regression(const gsl_vector * y,
const gsl_matrix * X,
const gsl_vector * w,
const double lambda,
const double * L,
const unsigned long Lcurve_size,
gsl_vector * coefs)
{
unsigned long n_samples = X->size1;
unsigned long n_features = X->size2;
double snorm;
double chisq;
gsl_multifit_linear_workspace
* gmlw = gsl_multifit_linear_alloc(n_samples, n_features);
rglz_wksp * rw = rglz_init(L, n_features, y, X, w, gmlw);
/* If the user specified gamma, do not attempt to optimize it. */
if (lambda >= 0)
rglz_set_lambda(rw, lambda);
else
rglz_estimate_lambda(rw, Lcurve_size);
rglz_solve(coefs, &chisq, &snorm, rw);
rglz_close(rw);
gsl_multifit_linear_free(gmlw);
return 0;
}
/* ============================= Python wrapper ============================= */
static PyObject*
gslpy_ridge_fit(PyObject* self, PyObject* args, PyObject* kwargs)
{
static char * keywords[] = {
"X",
"y",
"sample_weight",
"lamb",
"ldiag",
"lcurve_size",
NULL,
};
PyArrayObject
*X=NULL,
*y=NULL,
*w=NULL,
*Ldiag=NULL,
*coefs=NULL;
/* Negative lambda means that lambda is optimized */
double lambda = -1;
unsigned long Lcurve_size = 10000;
/* Flag to check if things are set */
int wei_set = 0;
int L_set = 0;
/* GSL stuff */
gsl_vector * g_y;
gsl_matrix * g_X;
gsl_vector * g_w;
gsl_vector * g_coefs;
if (!PyArg_ParseTupleAndKeywords(args,
kwargs,
"O!O!|O!dO!k",
keywords,
&PyArray_Type, &X,
&PyArray_Type, &y,
&PyArray_Type, &w,
&lambda,
&PyArray_Type, &Ldiag,
&Lcurve_size)) {
return NULL;
}
/* If weights are not given, set them as 1 */
if (w == NULL)
{
wei_set = 1;
w = (PyArrayObject*) PyArray_ZEROS(PyArray_NDIM(y),
PyArray_DIMS(y),
NPY_DOUBLE,
0);
npy_double * w_data = PyArray_DATA(w);
for (npy_intp i = 0; i < PyArray_SIZE(w); ++i)
w_data[i] = 1.0;
}
/* If Ldiag is not given, set it to identity. */
if (Ldiag == NULL)
{
npy_intp Lshape[] = {PyArray_DIM(X,1)};
L_set = 1;
Ldiag = (PyArrayObject*) PyArray_ZEROS(1,
Lshape,
NPY_DOUBLE,
0);
for (npy_intp i = 0; i < PyArray_DIM(X, 1); i++)
((double *) PyArray_DATA(Ldiag))[i] = 1.0;
}
/* Convert PyArray objects to gsl types */
g_y = gsl_vector_calloc(PyArray_DIM(y, 0));
g_w = gsl_vector_calloc(PyArray_DIM(w, 0));
g_X = gsl_matrix_calloc(PyArray_DIMS(X)[0], PyArray_DIMS(X)[1]);
g_coefs = gsl_vector_calloc(PyArray_DIM(X, 1));
for (npy_intp i = 0; i < (npy_intp) g_y->size; i++)
{
gsl_vector_set(g_y, i, ((double *) PyArray_DATA(y))[i]);
gsl_vector_set(g_w, i, ((double *) PyArray_DATA(w))[i]);
}
for (npy_intp i = 0; i < PyArray_SIZE(X); i++)
g_X->data[i] = ((double *) PyArray_DATA(X))[i];
/* Run regression */
gslpy_ridge_regression(g_y, g_X,
g_w, lambda,
(double *) PyArray_DATA(Ldiag),
Lcurve_size, g_coefs);
/* Convert g_coefs back to a Python object */
/* Local scope just to delete ``coefs_shape``after. */
{
npy_intp coefs_shape[] = {g_coefs->size, 1};
coefs = (PyArrayObject *) PyArray_ZEROS(2,
coefs_shape,
NPY_DOUBLE,
0);
for (npy_intp i = 0; i < (npy_intp) g_coefs->size; i++)
((double *) PyArray_DATA(coefs))[i] = gsl_vector_get(g_coefs, i);
}
if (wei_set)
Py_XDECREF(w);
if (L_set)
Py_XDECREF(Ldiag);
gsl_matrix_free(g_X);
gsl_vector_free(g_y);
gsl_vector_free(g_w);
gsl_vector_free(g_coefs);
return (PyObject *) coefs;
}
/* =========================== Python boilerplate =========================== */
PyDoc_STRVAR(module_doc,
"Ridge regression model methods using the GNU Scientific Library.");
PyDoc_STRVAR(fit_doc,
"Fits a ridge regression model to data.\n"
"fit(X, y, sample_weights=None, lambda=None, ldiag=None, Lcurve_size=10000).\n");
PyMethodDef methods[] = {
{
"fit",
(PyCFunction) gslpy_ridge_fit,
METH_VARARGS | METH_KEYWORDS,
fit_doc,
},
{NULL},
};
PyModuleDef gslpyridge_module = {
PyModuleDef_HEAD_INIT,
"gslpyridge",
module_doc,
-1,
methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_gslpyridge(void)
{
import_array();
return PyModule_Create(&gslpyridge_module);
}
| {
"alphanum_fraction": 0.6051323546,
"avg_line_length": 25.3695014663,
"ext": "c",
"hexsha": "48dfd79b48030d702a6eac0045f1439c4f3d1075",
"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": "6c4a508cd656a8cdf05ab3db19680e6239296a88",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mssm-labmmol/profiler",
"max_forks_repo_path": "profilerTools/gslpy_ridge/gslpy_ridge.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6c4a508cd656a8cdf05ab3db19680e6239296a88",
"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": "mssm-labmmol/profiler",
"max_issues_repo_path": "profilerTools/gslpy_ridge/gslpy_ridge.c",
"max_line_length": 103,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "6c4a508cd656a8cdf05ab3db19680e6239296a88",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mssm-labmmol/profiler",
"max_stars_repo_path": "profilerTools/gslpy_ridge/gslpy_ridge.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-10T13:40:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-21T13:06:09.000Z",
"num_tokens": 2592,
"size": 8651
} |
#include "constants.h"
#include "artisoptions.h"
#ifndef TYPES_H
#define TYPES_H
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <time.h>
#ifndef __CUDA_ARCH__
#include <gsl/gsl_rng.h>
#endif
//#include <gsl/gsl_sf_expint.h>
struct time
{
double start; // time at start of this timestep.
double width; // Width of timestep.
double mid; // Mid time in step - computed logarithmically.
double gamma_dep; // cmf gamma ray energy deposition rate
double positron_dep; // cmf positron energy deposition rate
double electron_dep; // cmf positron energy deposition rate
double alpha_dep; // cmf positron energy deposition rate
double cmf_lum; // cmf luminosity light curve
int pellet_decays; // Number of pellets that decay in this time step.
};
/// Coolinglist
///============================================================================
enum coolingtype {
COOLINGTYPE_FF = 880,
COOLINGTYPE_FB = 881,
COOLINGTYPE_COLLEXC = 882,
COOLINGTYPE_COLLION = 883,
};
typedef struct cellhistorycoolinglist_t
{
enum coolingtype type;
int element;
int ion;
int level;
int upperlevel;
} cellhistorycoolinglist_t;
/*enum heatingtype {
HEATINGTYPE_FF = 884,
HEATINGTYPE_BF = 885,
HEATINGTYPE_COLLDEEXC = 886,
HEATINGTYPE_COLLRECOMB = 887,
};*/
typedef struct heatingcoolingrates
{
double cooling_collisional;
double cooling_fb;
double cooling_ff;
double cooling_adiabatic;
double heating_collisional;
double heating_bf;
double heating_ff;
double heating_dep;
double nt_frac_heating; // = heatingrates.gamma / total_gamma_deposition, = get_nt_frac_heating(modelgridindex) when T_e solver runs
} heatingcoolingrates_t;
/// PHIXSLIST
typedef struct fullphixslist_t
{
double nu_edge;
int element;
int ion;
int level;
int phixstargetindex;
int index_in_groundphixslist;
} fullphixslist_t;
typedef struct groundphixslist_t
{
double nu_edge;
//double photoion_contr;
double gamma_contr;
//double stimrecomb_contr;
//double bfheating_contr;
int element;
int ion;
int level;
int phixstargetindex;
} groundphixslist_t;
typedef struct phixslist_t
{
groundphixslist_t *groundcont;
double *kappa_bf_contr;
#if (DETAILED_BF_ESTIMATORS_ON)
double *gamma_contr;
#endif
} phixslist_t;
enum packet_type {
TYPE_ESCAPE = 32,
TYPE_RADIOACTIVE_PELLET = 100,
TYPE_GAMMA = 10,
TYPE_RPKT = 11,
TYPE_KPKT = 12,
TYPE_MA = 13,
TYPE_NTLEPTON = 20,
TYPE_PRE_KPKT = 120,
TYPE_GAMMA_KPKT = 121,
};
enum cell_boundary {
NEG_X = 101,
POS_X = 102,
NEG_Y = 103,
POS_Y = 104,
NEG_Z = 105,
POS_Z = 106,
NONE = 107,
};
typedef struct mastate_t
{
int element; /// macro atom of type element (this is an element index)
int ion; /// in ionstage ion (this is an ion index)
int level; /// and level=level (this is a level index)
int activatingline; /// Linelistindex of the activating line for bb activated MAs, -99 else.
} mastate_t;
typedef struct packet
{
int where; /// The grid cell that the packet is in.
enum packet_type type; /// Identifies the type of packet (k-, r-, etc.)
enum cell_boundary last_cross; /// To avoid rounding errors on cell crossing.
int interactions;/// debug: number of interactions the packet undergone
int nscatterings; /// records number of electron scatterings a r-pkt undergone since it was emitted
int last_event; /// debug: stores information about the packets history
double pos[3]; /// Position of the packet (x,y,z).
double dir[3]; /// Direction of propagation. (x,y,z). Always a unit vector.
double e_cmf; /// The energy the packet carries in the co-moving frame.
double e_rf; /// The energy the packet carries in the rest frame.
double nu_cmf; /// The frequency in the co-moving frame.
double nu_rf; /// The frequency in the rest frame.
int next_trans; /// This keeps track of the next possible line interaction of a rpkt by storing
/// its linelist index (to overcome numerical problems in propagating the rpkts).
int emissiontype; /// records how the packet was emitted if it is a r-pkt
double em_pos[3]; /// Position of the packet (x,y,z).
int em_time;
double prop_time; // internal clock to track how far in time the packet has been propagated
int absorptiontype; /// records linelistindex of the last absorption
/// negative values give ff-abs (-1), bf-abs (-2), compton scattering of gammas (-3),
/// photoelectric effect of gammas (-4), pair production of gammas (-5)
/// decaying pellets of the 52Fe chain (-6) and pellets which decayed before the
/// onset of the simulation (-7)
/// decay of a positron pellet (-10)
int trueemissiontype; // emission type coming from a kpkt to rpkt (last thermal emission)
int trueem_time;
double absorptionfreq; /// records nu_cmf of packet at last absorption
double absorptiondir[3]; /// Direction of propagation (x,y,z) when a packet was last absorbed in a line. Always a unit vector.
//short timestep;
double stokes[3]; //I, Q and U Stokes parameters
double pol_dir[3]; //unit vector which defines the coordinate system against which Q and U are measured; should always be perpendicular to dir
double tdecay; /// Time at which pellet decays.
enum packet_type escape_type; /// Flag to tell us in which form it escaped from the grid.
int escape_time; /// Time at which is passes out of the grid.
/// Pos, dir, where, e_rf, nu_rf should all remain set at the exit point.
int scat_count; /// WHAT'S THAT???
int number; /// A unique number to identify which packet caused potential troubles.
bool originated_from_particlenotgamma; // first-non-pellet packet type was gamma
int pellet_decaytype; // index into decay::decaytypes
int pellet_nucindex; // nuclide index of the decaying species
float trueemissionvelocity;
mastate_t mastate;
} PKT;
enum ma_action {
/// Radiative deexcitation rate from this level.
MA_ACTION_RADDEEXC = 0,
/// Collisional deexcitation rate from this level.
MA_ACTION_COLDEEXC = 1,
/// Radiative recombination from this level.
MA_ACTION_RADRECOMB = 2,
/// Collisional recombination rate from this level.
MA_ACTION_COLRECOMB = 3,
/// Rate for internal downward transitions to same ionisation stage.
MA_ACTION_INTERNALDOWNSAME = 4,
/// Rate for internal upward transitions to same ionisation stage.
MA_ACTION_INTERNALDOWNLOWER = 5,
/// Rate for internal downward transitions to lower ionisation stage.
MA_ACTION_INTERNALUPSAME = 6,
/// Rate for internal upward transitions to higher ionisation stage.
MA_ACTION_INTERNALUPHIGHER = 7,
/// Rate for internal upward transitions to higher ionisation stage due to non-thermal collisions.
MA_ACTION_INTERNALUPHIGHERNT = 8,
MA_ACTION_COUNT = 9,
};
/// GRID
///============================================================================
typedef struct compositionlist_entry
{
float abundance; /// Abundance of the element (by mass!).
float *groundlevelpop; /// Pointer to an array of floats which contains the groundlevel populations
/// of all included ionisation stages for the element.
float *partfunct; /// Pointer to an array of floats which contains the partition functions
/// of all included ionisation stages for the element.
//float *ltepartfunct; /// Pointer to an array of floats which contains the LTE partition functions
// /// of all included ionisation stages for the element.
} compositionlist_entry;
typedef struct gridcell
{
double pos_init[3]; /// Initial co-ordinates of inner most corner of cell.
// int xyz[3]; /// Integer position of cell in grid.
int modelgridindex;
} CELL;
typedef struct mgicooling_t
{
double *contrib;
} mgicooling_t;
#define NSYN 1 /* number of frequency points in syn calculation */
enum ray_status {
ACTIVE = 1,
WAITING = 2,
FINISHED = 3,
};
typedef struct syn_ray
{
double tstart; /* time at which the ray enters the grid */
double rstart[3]; /* vector position at which the ray enters the grid */
double pos[3]; /* current position of the ray */
double nu_rf[NSYN]; /*rest frame frequencies of rays */
double nu_rf_init[NSYN]; /*rest frame frequencies of rays at start - for a test only */
double nu_cmf[NSYN]; /*cmf freqencies */
double e_rf[NSYN]; /*rest frame energy of rays */
double e_cmf[NSYN]; /* cmf energies of rays */
int where; /* the grid cell the ray is in */
int lindex[NSYN]; /* array of ray positions in the line list */
enum cell_boundary last_cross; /* last boundary crossed */
enum ray_status status; /*WAITING, then ACTIVE then FINISHED*/
} RAY;
/// ATOMIC DATA
///============================================================================
typedef struct phixstarget_entry
{
double *spontrecombcoeff;
#if (!NO_LUT_PHOTOION)
double *corrphotoioncoeff;
#endif
#if (!NO_LUT_BFHEATING)
double *bfheating_coeff;
#endif
double *bfcooling_coeff;
double probability; // fraction of phixs cross section leading to this final level
int levelindex; // index of upper ion level after photoionisation
} phixstarget_entry;
typedef struct levellist_entry
{
double epsilon; /// Excitation energy of this level relative to the neutral ground level.
int *uptrans_lineindicies; /// Allowed upward transitions from this level
int *downtrans_lineindicies; /// Allowed downward transitions from this level
int nuptrans;
int ndowntrans;
double phixs_threshold; /// Energy of first point in the photion_xs table
phixstarget_entry *phixstargets; /// pointer to table of target states and probabilities
float *photoion_xs; /// Pointer to a lookup-table providing photoionisation cross-sections for this level.
int nphixstargets; /// length of phixstargets array:
float stat_weight; /// Statistical weight of this level.
int cont_index; /// Index of the continuum associated to this level. Negative number.
#if (!NO_LUT_PHOTOION || !NO_LUT_BFHEATING)
int closestgroundlevelcont;
#endif
bool metastable; ///
// double photoion_xs_nu_edge; /// nu of the first grid point in the photoion_xs lookup-table.
//double *spontrecombcoeff_E;
//double *photoioncoeff_below;
//double *photoioncoeff_above;
//double *corrphotoioncoeff_above;
//double *bfheating_coeff_above;
//double *stimulated_bfcooling_coeff;
//double *stimulated_recomb_coeff;
//float *modified_spontrecombcoeff;
//float *stimrecombcoeff;
//float *modified_stimrecombcoeff;
///float population;
///float sahafact;
///float spontaneousrecomb_ratecoeff;
///float modifiedspontaneousrecomb_ratecoeff;
///float corrphotoion_ratecoeff;
///float modifiedcorrphotoion_ratecoeff;
/// time dependent macroatom event rates
//double rad_deexc; /// Radiative deexcitation rate from this level.
//double internal_down_same; /// Rate for internal downward transitions within the same ionisation stage.
//double internal_up_same; /// Rate for internal upward transitions within the same ionisation stage.
} levellist_entry;
typedef struct ionlist_entry
{
levellist_entry *levels; /// Carries information for each level: 0,1,...,nlevels-1
int ionstage; /// Which ionisation stage: XI=0, XII=1, XIII=2, ...
int nlevels; /// Number of levels for this ionisation stage
int nlevels_nlte; /// number of nlte levels for this ion
int first_nlte; /// index into nlte_pops array of a grid cell
int ionisinglevels; /// Number of levels which have a bf-continuum
int maxrecombininglevel; /// level index of the highest level with a non-zero recombination rate
int nlevels_groundterm;
int coolingoffset;
int ncoolingterms;
int uniqueionindex;
float *Alpha_sp;
double ionpot; /// Ionisation threshold to the next ionstage
//int nbfcontinua;
//ionsphixslist_t *phixslist;
} ionlist_entry;
typedef struct elementlist_entry
{
ionlist_entry *ions; /// Carries information for each ion: 0,1,...,nions-1
int nions; /// Number of ions for the current element
int anumber; /// Atomic number
// int uppermost_ion; /// Highest ionisation stage which has a decent population for a given cell
/// Be aware that this must not be used outside of the update_grid routine
/// and their daughters. Neither it will work with OpenMP threads.
float abundance; ///
float mass; /// Atomic mass number in multiple of MH
} elementlist_entry;
typedef struct linelist_entry
{
double nu; /// Frequency of the line transition
float einstein_A;
float osc_strength;
float coll_str;
int elementindex; /// It's a transition of element (not its atomic number,
/// but the (x-1)th element included in the simulation.
int ionindex; /// The same for the elements ion
int upperlevelindex; /// And the participating upper
int lowerlevelindex; /// and lower levels
bool forbidden;
} linelist_entry;
typedef struct bflist_t
{
int elementindex;
int ionindex;
int levelindex;
int phixstargetindex;
} bflist_t;
typedef struct nne_solution_paras
{
int cellnumber;
} nne_solution_paras;
typedef struct gslintegration_paras
{
double nu_edge;
double T;
float *photoion_xs;
} gslintegration_paras;
typedef struct rpkt_cont_opacity_struct
{
double nu; // frequency at which opacity was calculated
double total;
double es;
double ff;
double bf;
double ffheating;
//double bfheating;
int modelgridindex;
bool recalculate_required; // e.g. when cell or timestep has changed
} rpkt_cont_opacity_struct;
/// Cell history
///============================================================================
// typedef struct coolinglist_contributions
// {
// double contribution;
// } coolinglist_contributions;
typedef struct
{
double corrphotoioncoeff;
#if (SEPARATE_STIMRECOMB)
double stimrecombcoeff;
#endif
} chphixstargets_struct;
typedef struct chlevels_struct
{
double processrates[MA_ACTION_COUNT];
chphixstargets_struct *chphixstargets;
double bfheatingcoeff;
} chlevels_struct;
typedef struct chions_struct
{
chlevels_struct *chlevels; /// Pointer to the ions levellist.
} chions_struct;
typedef struct chelements_struct
{
chions_struct *chions; /// Pointer to the elements ionlist.
} chelements_struct;
typedef struct cellhistory_struct
{
double *cooling_contrib; /// Cooling contributions by the different processes.
chelements_struct *chelements; /// Pointer to a nested list which helds compositional
/// information for all the elements=0,1,...,nelements-1
int cellnumber; /// Identifies the cell the data is valid for.
int bfheating_mgi;
} cellhistory_struct;
#endif //TYPES_H
| {
"alphanum_fraction": 0.6651720871,
"avg_line_length": 35.5044843049,
"ext": "h",
"hexsha": "0bd872176b11b5d49a40cbe7822782a177e75f43",
"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": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "artis-mcrt/artis",
"max_forks_repo_path": "types.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_issues_repo_issues_event_max_datetime": "2021-11-17T15:03:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-11-17T09:37:45.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "artis-mcrt/artis",
"max_issues_repo_path": "types.h",
"max_line_length": 144,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "artis-mcrt/artis",
"max_stars_repo_path": "types.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-10T21:56:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-12T12:09:31.000Z",
"num_tokens": 3786,
"size": 15835
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_interp.h>
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "spce_PET.h"
#include "inout_aper.h"
#include "trace_conf.h"
#include "aper_conf.h"
#include "spc_sex.h"
#include "disp_conf.h"
#include "spc_wl_calib.h"
#include "spce_binning.h"
#include "spc_optimum.h"
#include "spc_spc.h"
#include "fringe_conf.h"
#include "spc_resp.h"
#include "spc_FITScards.h"
#define AXE_IMAGE_PATH "AXE_IMAGE_PATH"
#define AXE_OUTPUT_PATH "AXE_OUTPUT_PATH"
#define AXE_DRIZZLE_PATH "AXE_DRIZZLE_PATH"
#define AXE_CONFIG_PATH "AXE_CONFIG_PATH"
int
main (int argc, char *argv[])
{
char *opt;
char grism_file[MAXCHAR];
char grism_file_path[MAXCHAR];
char aper_file[MAXCHAR];
char aper_file_path[MAXCHAR];
char obj_PET_file[MAXCHAR];
char obj_PET_file_path[MAXCHAR];
char bck_PET_file[MAXCHAR];
char bck_PET_file_path[MAXCHAR];
char conf_file[MAXCHAR];
char conf_file_path[MAXCHAR];
char SPC_file[MAXCHAR];
char SPC_file_path[MAXCHAR];
char SPC_opt_file[MAXCHAR];
char SPC_opt_file_path[MAXCHAR];
char WHT_file[MAXCHAR];
char WHT_file_path[MAXCHAR];
char label[MAXCHAR];
int i, index, dobck = 0, noflux = 1;
object **oblist;
FITScards *cards;
ap_pixel *obj_PET = NULL, *bck_PET = NULL;
observation *obs;
//tracestruct *trace;
aperture_conf *conf;
spectrum *obj_spec = NULL, *bck_spec = NULL, *sobj_spec = NULL;
spectrum *resp;
response_function *resp_func;
calib_function *wl_calibration;
fitsfile *OPET_ptr, *BPET_ptr;
int f_status = 0;
fitsfile *SPC_ptr, *SPC_opt_ptr, *WHT_ptr;
gsl_matrix *weights;
drzstamp *modvar;
int obj_aperID, obj_beamID, objindex;
int bck_aperID, bck_beamID;
char table[MAXCHAR], table_path[MAXCHAR];
//char comment[FLEN_COMMENT];
int empty;
int drizzle;
int quant_cont=0;
int opt_weights=0;
int for_grism=0;
int smooth_conv=0;
d_point smooth_params;
double exptime;
double sky_cps;
drzstamp_dim dimension;
gsl_matrix *coverage = NULL;
if (((argc < 3))
|| (opt = get_online_option ("help", argc, argv)))
{
fprintf (stdout,
"aXe_PET2SPC Version %s:\n"
" aXe task that produces 1-D, binned spectra using information\n"
" contained in a OPET and a BPET. A 1-D spectrum is generated\n"
" for each beam in each of both the OPET and the BPET files\n"
" The binned background spectra of each beam (order) is then\n"
" subtraced from the corresponding spectra form the OPET. Th\ne"
" background subtraction (and reading a BPET altogether can be\n"
" avoided by using the -noBPET option\n"
" An SPC file, a multi-extension FITS file containing binned\n"
" spectra is produced. Each extension (named after the beam ID,\n"
" e.g. 11B for aperture (object) 11,beam (order) B) contains the\n"
" following columns:\n"
"\n"
" LAMBDA ; the wavelength (in A)\n"
" TCOUNT ; the total number of counts (in DN)\n"
" TERROR ; the error in TERRORS (in DN)\n"
" BCOUNT ; the estimated number of counts from the\n"
" background (in DN)\n"
" BERROR ; the error in BCOUNTS (in DN)\n"
" COUNT ; the estimated number of counts from the\n"
" object (in DN)\n"
" ERROR ; the error in COUNTS (in DN)\n"
" FLUX ; the estimated flux (in erg/s/cm^2/A)\n"
" FERROR ; the error in FLUX (in erg/s/cm^s/A)\n"
" WEIGHT ; weight (in pixels)\n"
"\n"
" Input FITS mages are looked for in $AXE_IMAGE_PATH\n"
" aXe config file is looked for in $AXE_CONFIG_PATH\n"
" All outputs are writen to $AXE_OUTPUT_PATH\n"
"\n"
"Usage:\n"
" aXe_PET2SPC [g/prism image filename] [aXe config file name] [options]\n"
"\n"
"Options:\n"
" -noBPET - to disable the use of a BPET file\n"
" -noflux - to disable the flux calibration\n"
" -drz - use $AXE_DRIZZLE_PATH to locate the grism-, OAF-\n"
" - and PET-files instead of $AXE_IMAGE/OUTPUT_PATH\n"
" -in_AF=[string] - overwrite the default input Aperture File name\n"
" -OPET=[string] - overwrite the default input Object PET file name\n"
" -BPET=[string] - overwrite the default input Background PET\n"
" file name\n"
" -out_SPC=[string] - overwrite the default output SPC file name\n"
"\n"
"Example:\n"
" ./aXe_PET2SPC slim_grism.fits SLIM.conf.A.0\n"
"\n",RELEASE);
exit (1);
}
// make a general opening statement
fprintf (stdout, "aXe_PET2SPC: Starting...\n");
// get the name of the flt-file
index = 0;
strcpy (grism_file, argv[++index]);
if ((opt = get_online_option ("drz", argc, argv)))
{
build_path (AXE_DRIZZLE_PATH, grism_file, grism_file_path);
drizzle=1;
}
else
{
build_path (AXE_IMAGE_PATH, grism_file, grism_file_path);
drizzle=0;
}
// get the name of the configuration file
strcpy (conf_file, argv[++index]);
build_path (AXE_CONFIG_PATH, conf_file, conf_file_path);
// load the configuration file
conf = get_aperture_descriptor (conf_file_path);
// Determine where the various extensions are in the FITS file
get_extension_numbers(grism_file_path, conf,conf->optkey1,conf->optval1);
// Build aperture file name
replace_file_extension (grism_file, aper_file, ".fits",
".OAF", conf->science_numext);
if (drizzle)
build_path (AXE_DRIZZLE_PATH, aper_file, aper_file_path);
else
build_path (AXE_OUTPUT_PATH, aper_file, aper_file_path);
// Build object PET file name
replace_file_extension (grism_file, obj_PET_file, ".fits",
".PET.fits", conf->science_numext);
// make the total filename
if (drizzle)
build_path (AXE_DRIZZLE_PATH, obj_PET_file, obj_PET_file_path);
else
build_path (AXE_OUTPUT_PATH, obj_PET_file, obj_PET_file_path);
// Build background PET file name
replace_file_extension (grism_file, bck_PET_file, ".fits",
".BCK.PET.fits", conf->science_numext);
// make the total filename
if (drizzle)
build_path (AXE_DRIZZLE_PATH, bck_PET_file, bck_PET_file_path);
else
build_path (AXE_OUTPUT_PATH, bck_PET_file, bck_PET_file_path);
// make a non-standard AF name if necessary
if ((opt = get_online_option ("in_AF", argc, argv)))
{
strcpy(aper_file,opt);
strcpy(aper_file_path,opt);
}
// make a non-standard PET name if necessary
if ((opt = get_online_option ("OPET", argc, argv)))
{
strcpy(obj_PET_file,opt);
strcpy(obj_PET_file_path,opt);
}
// make a non-standard BPET name if necessary
if ((opt = get_online_option ("BPET", argc, argv)))
{
strcpy(bck_PET_file,opt);
strcpy(bck_PET_file_path,opt);
}
// set the flagg for no background subtraction
if ((opt = get_online_option ("noBPET",argc,argv)))
{
dobck = 0;
strcpy(bck_PET_file,"None");
strcpy(bck_PET_file_path, "None");
}
else
{
dobck = 1;
}
// set the flagg for flux
if ((opt = get_online_option ("noflux",argc,argv)))
noflux = 1;
else
noflux = 0;
// check for the weights flagg,
// set the file name if the flagg is set
if ((opt = get_online_option ("opt_weights",argc,argv)))
opt_weights = 1;
else
opt_weights = 0;
// read the trigger for smoothing the sensitivity
if ((opt = get_online_option ("smooth_conv",argc,argv)))
smooth_conv = 1;
else
smooth_conv = 0;
if ((opt = get_online_option ("out_SPC", argc, argv)))
{
strcpy (SPC_file, opt);
strcpy (SPC_file_path, opt);
if (opt_weights)
{
replace_file_extension (SPC_file, SPC_opt_file, ".fits",
"_opt.SPC.fits", -1);
replace_file_extension (SPC_file_path, SPC_opt_file_path, ".fits",
"_opt.SPC.fits", -1);
replace_file_extension (SPC_opt_file, WHT_file, ".SPC.fits",
".WHT.fits", -1);
replace_file_extension (SPC_opt_file_path, WHT_file_path, ".SPC.fits",
".WHT.fits", -1);
}
}
else
{
replace_file_extension (obj_PET_file, SPC_file, ".PET.fits",
".SPC.fits", -1);
if (drizzle)
build_path (AXE_DRIZZLE_PATH, SPC_file, SPC_file_path);
else
build_path (AXE_OUTPUT_PATH, SPC_file, SPC_file_path);
if (opt_weights)
{
replace_file_extension (obj_PET_file, SPC_opt_file, ".PET.fits",
"_opt.SPC.fits", -1);
replace_file_extension (SPC_opt_file, WHT_file, ".SPC.fits",
".WHT.fits", -1);
if (drizzle)
{
build_path (AXE_DRIZZLE_PATH, SPC_opt_file, SPC_opt_file_path);
build_path (AXE_DRIZZLE_PATH, WHT_file, WHT_file_path);
}
else
{
build_path (AXE_OUTPUT_PATH, SPC_opt_file, SPC_opt_file_path);
build_path (AXE_OUTPUT_PATH, WHT_file, WHT_file_path);
}
}
}
// check the configuration file for the smoothin keywords
if (!check_conf_for_smoothing(conf, smooth_conv))
aXe_message(aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PET2SP: Either the configuration file %s does not contain\n"
"the necessary keywords for the smoothing (POBJSIZE, SMFACTOR),\n"
"or one of these keywords has an unreasonable value < 0.0!\n",
conf_file_path);
// give feedback onto the screen:
// report on input and output
// and also on specific parameter
fprintf (stdout, "aXe_PET2SPC: Input configuration file name: %s\n",
conf_file_path);
fprintf (stdout, "aXe_PET2SPC: Input Object Aperture file name: %s\n",
aper_file_path);
fprintf (stdout, "aXe_PET2SPC: Input Object PET file name: %s\n",
obj_PET_file_path);
if (dobck)
fprintf (stdout, "aXe_PET2SPC: Input Background PET file name: %s\n",
bck_PET_file_path);
fprintf (stdout, "aXe_PET2SPC: Output SPC file name: %s\n",
SPC_file_path);
if (opt_weights)
{
fprintf (stdout, "aXe_PET2SPC: Computing optimal weights.\n");
fprintf (stdout, "aXe_PET2SPC: Optimized SPC file name: %s\n",
SPC_opt_file_path);
fprintf (stdout, "aXe_PET2SPC: Output WHT file name: %s\n",
WHT_file_path);
}
if (!noflux)
{
fprintf (stdout, "aXe_PET2SPC: Performing flux calibration.\n");
if (smooth_conv)
fprintf (stdout, "aXe_PET2SPC: Using smoothed sensitivity curves.\n");
}
fprintf (stdout, "\n\n");
//
// try to get the descriptor 'exptime' from the 'sci'-extension
//
exptime = (double)get_float_from_keyword(grism_file_path, conf->science_numext, conf->exptimekey);
if (isnan(exptime))
exptime = (double)get_float_from_keyword(grism_file_path, 1, conf->exptimekey);
if (isnan(exptime))
exptime = 1.0;
//
// try to get the descriptor 'SKY_CPS' from the 'sci'-extension
//
sky_cps = (double)get_float_from_keyword(grism_file_path, conf->science_numext, "SKY_CPS");
if (isnan(sky_cps))
sky_cps = 0.0;
// Open the OPET file for reading
fits_open_file (&OPET_ptr, obj_PET_file_path, READONLY, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PET2SPC: Could not open file: %s\n",
obj_PET_file_path);
}
// check whether the contamination is quantitative
quant_cont = check_quantitative_contamination(OPET_ptr);
if (opt_weights && !quant_cont)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PET2SPC: The optimal extractions needs quantitative contamination! "
" Please re-run aXe with Gauss or Fluxcube contamination!");
obs = load_dummy_observation ();
/* Loading the object list */
fprintf (stdout, "aXe_PET2SPC: Loading object aperture list...");
oblist = file_to_object_list_seq (aper_file_path, obs);
fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist));
if (dobck)
{
// Open the file for reading
fits_open_file (&BPET_ptr, bck_PET_file_path, READONLY, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PET2SP: Could not open file: %s\n",
bck_PET_file_path);
}
}
/* Copy the header info from the grism image */
SPC_ptr = create_SPC_opened (SPC_file_path,1);
cards = get_FITS_cards_opened(OPET_ptr);
put_FITS_cards_opened(SPC_ptr, cards);
free_FITScards(cards);
if (opt_weights)
{
cards = get_FITS_cards_opened(OPET_ptr);
// open the WHT file and add the header keywords
WHT_ptr = create_FITSimage_opened (WHT_file_path, 1);
put_FITS_cards_opened(WHT_ptr, cards);
// open the opt_SPC and add the header keywords
SPC_opt_ptr = create_SPC_opened (SPC_opt_file_path,1);
put_FITS_cards_opened(SPC_opt_ptr, cards);
// delete the header keywords
free_FITScards(cards);
}
// do something only if there
// exist valid objects
i = 0;
if (oblist!=NULL)
{
// turn until the end of the PET is reached
while (1)
{
empty=0;
// Get the PET for this object
obj_PET = get_ALL_from_next_in_PET(OPET_ptr, &obj_aperID, &obj_beamID);
// load the background PET if requested
if (dobck)
{
bck_PET = get_ALL_from_next_in_PET(BPET_ptr, &bck_aperID, &bck_beamID);
if ((bck_aperID!=obj_aperID)||(bck_beamID!=obj_beamID))
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"Background PET and Object PET extensions are not"
" in the same order and cannot be combined.\n");
}
// end of PET reached: the break condition
if ((obj_aperID==-1) && (obj_beamID==-1))
break;
// signal an empty PET
if (obj_PET==NULL)
empty=1;
// give feedback to the screen
fprintf (stdout, "aXe_PET2SPC: BEAM %d; %d%c\n", i, obj_aperID, BEAM(obj_beamID));fflush(stdout);
// identify the object which matches the PET
objindex = find_object_in_object_list(oblist,obj_aperID);
// look whether we are for grisms or prisms
for_grism = check_for_grism (conf_file_path, obj_beamID);
wl_calibration = get_calfunc_for_beam(oblist[objindex]->beams[obj_beamID], for_grism, conf_file_path, conf);
// compute the object spectrum
obj_spec = bin_naive (obj_PET, oblist[objindex]->beams[obj_beamID].width,
oblist[objindex]->beams[obj_beamID].orient, quant_cont);
// check for the existence of a background PET
if (dobck)
{
// compute the background spectrum
bck_spec = bin_naive (bck_PET,
oblist[objindex]->beams[bck_beamID].width,
oblist[objindex]->beams[bck_beamID].orient, quant_cont);
}
else
{
// create a dummy background spectrum
bck_spec = empty_counts_spectrum_copy(obj_spec);
}
// subtract the background spectrum from the
// object (or forground) spectrum
sobj_spec = subtract_spectra (obj_spec, bck_spec);
if(!noflux)
{
get_troughput_table_name(conf_file_path,
oblist[objindex]->beams[obj_beamID].ID,
table);
if (strcmp(table,"None"))
{
build_path (AXE_CONFIG_PATH, table, table_path);
resp=get_response_function_from_FITS(table_path,2);
resp_func = create_response_function(table_path);
if (resp->spec_len <2)
{
aXe_message (aXe_M_WARN1, __FILE__, __LINE__,
"Throughput table %s contains only %d"
" values. No sensitivity curve was applied.\n",
table_path,resp->spec_len);
}
else
{
fprintf(stdout,"aXe_PET2SPC: Applying sensitivity contained in %s\n",table_path);
smooth_params = get_smooth_pars_for_beam(conf, smooth_conv, oblist[objindex]->beams[obj_beamID]);
if (smooth_params.x > 0.0)
{
// apply a smoothed flux conversion
apply_smoothed_response(wl_calibration, for_grism, quant_cont, resp_func, smooth_params, sobj_spec);
}
else
{
// apply a normal flux conversion
apply_response_function(sobj_spec, resp, quant_cont);
}
}
// free the memory of the
// response functions
free_spectrum(resp);
free_response_function(resp_func);
}
}
if (empty!=1)
{
add_spectra_to_SPC_opened (SPC_ptr, obj_spec, bck_spec,
sobj_spec, oblist[objindex]->ID, oblist[objindex]->beams[obj_beamID].ID);
/* Copy header from OPET extension into this SPC extension */
cards = get_FITS_cards_opened(OPET_ptr);
put_FITS_cards_opened(SPC_ptr,cards);
free_FITScards(cards);
}
free_spectrum (bck_spec);
free_spectrum (sobj_spec);
free_spectrum (obj_spec);
if (opt_weights)
{
// get the dimension in trace length
// and crossdispersion
dimension = get_all_dims(obj_PET, bck_PET,
oblist[objindex]->beams[obj_beamID], dobck);
// check for empty PET
if (!dimension.resolution)
{
// create dummies in case of empty PET's
weights = get_default_weight();
modvar = get_default_modvar();
}
else
{
// prepare the PET's by computing the inverse variance.
// Also the trace distances are shifted by 0.5
// to get a sampling comparable to the unweighted
// extraction
prepare_inv_variance(obj_PET, bck_PET, dobck, conf, exptime, sky_cps, 0.0);
// compute the inverse variance and the profile
// image in the trace distance - crossdispersion plane
modvar = compute_modvar(obj_PET, oblist[objindex]->beams[obj_beamID], dimension);
// compute the optimal weights
weights = comp_allweight(modvar);
}
if (dimension.resolution && empty != 1)
{
sprintf (label, "WHT_%d%c", obj_aperID, BEAM (obj_beamID));
gsl_to_FITSimage_opened (weights, WHT_ptr ,0,label);
// make and store the default header
cards = beam_to_FITScards(oblist[objindex],obj_beamID);
put_FITS_cards_opened(WHT_ptr,cards);
free_FITScards(cards);
}
// create the optimal weighted
// foreground spectrum
obj_spec = bin_optimal (obj_PET,oblist[objindex]->beams[obj_beamID],
quant_cont, weights, dimension, coverage);
// check for the presence of a background PET
if (dobck)
{
// create the optimal weighted
// background spectrum
bck_spec = bin_optimal (bck_PET,oblist[objindex]->beams[obj_beamID],
quant_cont, weights, dimension, coverage);
}
else
{
// make a dummy background spectrum
bck_spec = empty_counts_spectrum_copy(obj_spec);
}
// release memory
gsl_matrix_free(weights);
free_drzstamp(modvar);
// subtract the background spectrum from the
// object (or forground) spectrum
sobj_spec = subtract_spectra (obj_spec, bck_spec);
if(!noflux)
{
get_troughput_table_name(conf_file_path,
oblist[objindex]->beams[obj_beamID].ID,
table);
if (strcmp(table,"None"))
{
build_path (AXE_CONFIG_PATH, table, table_path);
resp=get_response_function_from_FITS(table_path,2);
resp_func = create_response_function(table_path);
if (resp->spec_len <2)
{
aXe_message (aXe_M_WARN1, __FILE__, __LINE__,
"Throughput table %s contains only %d"
" values. No sensitivity curve was applied.\n",
table_path,resp->spec_len);
}
else
{
fprintf(stdout,"aXe_PET2SPC: Applying sensitivity contained in %s\n",table_path);
smooth_params = get_smooth_pars_for_beam(conf, smooth_conv, oblist[objindex]->beams[obj_beamID]);
if (smooth_params.x > 0.0)
{
apply_smoothed_response(wl_calibration, for_grism, quant_cont, resp_func, smooth_params, sobj_spec);
}
else
{
apply_response_function(sobj_spec, resp, quant_cont);
}
}
// free the memory
free_spectrum(resp);
free_response_function(resp_func);
}
}
if (empty!=1)
{
add_spectra_to_SPC_opened (SPC_opt_ptr, obj_spec, bck_spec,
sobj_spec, oblist[objindex]->ID, oblist[objindex]->beams[obj_beamID].ID);
/* Copy header from OPET extension into this SPC extension */
cards = get_FITS_cards_opened(OPET_ptr);
put_FITS_cards_opened(SPC_opt_ptr,cards);
free_FITScards(cards);
}
free_spectrum (bck_spec);
free_spectrum (sobj_spec);
free_spectrum (obj_spec);
}
// free memory
free_calib (wl_calibration);
if (bck_PET!=NULL)
free (bck_PET);
if (obj_PET!=NULL)
free (obj_PET);
i++;
}
}
fits_close_file (SPC_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PET2SPC: " "Error closing SPC: %s\n",
SPC_file_path);
}
if (opt_weights)
{
fits_close_file (WHT_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PET2SPC: " "Error closing WHT: %s\n",
WHT_file_path);
}
fits_close_file (SPC_opt_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_PET2SPC: " "Error closing PSC: %s\n",
SPC_opt_file_path);
}
}
if (oblist!=NULL)
free_oblist (oblist);
fprintf (stdout, "aXe_PET2SPC: Done...\n");
exit (0);
}
| {
"alphanum_fraction": 0.6432796433,
"avg_line_length": 30.6100278552,
"ext": "c",
"hexsha": "2e926747ed2bac65b89812abcde527e874862a71",
"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/aXe_PET2SPC.c",
"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/aXe_PET2SPC.c",
"max_line_length": 112,
"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/aXe_PET2SPC.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6242,
"size": 21978
} |
/**
*
* @file qwrapper_claset2.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 c Tue Jan 7 11:44:59 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_claset2(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int M, int N,
PLASMA_Complex32_t alpha, PLASMA_Complex32_t *A, int LDA)
{
DAG_CORE_LASET;
QUARK_Insert_Task(quark, CORE_claset2_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &M, VALUE,
sizeof(int), &N, VALUE,
sizeof(PLASMA_Complex32_t), &alpha, VALUE,
sizeof(PLASMA_Complex32_t)*M*N, A, OUTPUT,
sizeof(int), &LDA, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_claset2_quark = PCORE_claset2_quark
#define CORE_claset2_quark PCORE_claset2_quark
#endif
void CORE_claset2_quark(Quark *quark)
{
PLASMA_enum uplo;
int M;
int N;
PLASMA_Complex32_t alpha;
PLASMA_Complex32_t *A;
int LDA;
quark_unpack_args_6(quark, uplo, M, N, alpha, A, LDA);
CORE_claset2(uplo, M, N, alpha, A, LDA);
}
| {
"alphanum_fraction": 0.5421383648,
"avg_line_length": 28.9090909091,
"ext": "c",
"hexsha": "d6c9fe9c19ec5dc11ca21b10790d8f1d6d9d1a9c",
"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_claset2.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_claset2.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_claset2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 452,
"size": 1590
} |
/* matrix/gsl_matrix_ushort.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_USHORT_H__
#define __GSL_MATRIX_USHORT_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#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_ushort.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;
unsigned short * data;
gsl_block_ushort * block;
int owner;
} gsl_matrix_ushort;
typedef struct
{
gsl_matrix_ushort matrix;
} _gsl_matrix_ushort_view;
typedef _gsl_matrix_ushort_view gsl_matrix_ushort_view;
typedef struct
{
gsl_matrix_ushort matrix;
} _gsl_matrix_ushort_const_view;
typedef const _gsl_matrix_ushort_const_view gsl_matrix_ushort_const_view;
/* Allocation */
GSL_FUN gsl_matrix_ushort *
gsl_matrix_ushort_alloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_ushort *
gsl_matrix_ushort_calloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_ushort *
gsl_matrix_ushort_alloc_from_block (gsl_block_ushort * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_FUN gsl_matrix_ushort *
gsl_matrix_ushort_alloc_from_matrix (gsl_matrix_ushort * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_FUN gsl_vector_ushort *
gsl_vector_ushort_alloc_row_from_matrix (gsl_matrix_ushort * m,
const size_t i);
GSL_FUN gsl_vector_ushort *
gsl_vector_ushort_alloc_col_from_matrix (gsl_matrix_ushort * m,
const size_t j);
GSL_FUN void gsl_matrix_ushort_free (gsl_matrix_ushort * m);
/* Views */
GSL_FUN _gsl_matrix_ushort_view
gsl_matrix_ushort_submatrix (gsl_matrix_ushort * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_ushort_view
gsl_matrix_ushort_row (gsl_matrix_ushort * m, const size_t i);
GSL_FUN _gsl_vector_ushort_view
gsl_matrix_ushort_column (gsl_matrix_ushort * m, const size_t j);
GSL_FUN _gsl_vector_ushort_view
gsl_matrix_ushort_diagonal (gsl_matrix_ushort * m);
GSL_FUN _gsl_vector_ushort_view
gsl_matrix_ushort_subdiagonal (gsl_matrix_ushort * m, const size_t k);
GSL_FUN _gsl_vector_ushort_view
gsl_matrix_ushort_superdiagonal (gsl_matrix_ushort * m, const size_t k);
GSL_FUN _gsl_vector_ushort_view
gsl_matrix_ushort_subrow (gsl_matrix_ushort * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_ushort_view
gsl_matrix_ushort_subcolumn (gsl_matrix_ushort * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_ushort_view
gsl_matrix_ushort_view_array (unsigned short * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_ushort_view
gsl_matrix_ushort_view_array_with_tda (unsigned short * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_ushort_view
gsl_matrix_ushort_view_vector (gsl_vector_ushort * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_ushort_view
gsl_matrix_ushort_view_vector_with_tda (gsl_vector_ushort * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_ushort_const_view
gsl_matrix_ushort_const_submatrix (const gsl_matrix_ushort * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_ushort_const_view
gsl_matrix_ushort_const_row (const gsl_matrix_ushort * m,
const size_t i);
GSL_FUN _gsl_vector_ushort_const_view
gsl_matrix_ushort_const_column (const gsl_matrix_ushort * m,
const size_t j);
GSL_FUN _gsl_vector_ushort_const_view
gsl_matrix_ushort_const_diagonal (const gsl_matrix_ushort * m);
GSL_FUN _gsl_vector_ushort_const_view
gsl_matrix_ushort_const_subdiagonal (const gsl_matrix_ushort * m,
const size_t k);
GSL_FUN _gsl_vector_ushort_const_view
gsl_matrix_ushort_const_superdiagonal (const gsl_matrix_ushort * m,
const size_t k);
GSL_FUN _gsl_vector_ushort_const_view
gsl_matrix_ushort_const_subrow (const gsl_matrix_ushort * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_ushort_const_view
gsl_matrix_ushort_const_subcolumn (const gsl_matrix_ushort * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_ushort_const_view
gsl_matrix_ushort_const_view_array (const unsigned short * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_ushort_const_view
gsl_matrix_ushort_const_view_array_with_tda (const unsigned short * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_ushort_const_view
gsl_matrix_ushort_const_view_vector (const gsl_vector_ushort * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_ushort_const_view
gsl_matrix_ushort_const_view_vector_with_tda (const gsl_vector_ushort * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_FUN void gsl_matrix_ushort_set_zero (gsl_matrix_ushort * m);
GSL_FUN void gsl_matrix_ushort_set_identity (gsl_matrix_ushort * m);
GSL_FUN void gsl_matrix_ushort_set_all (gsl_matrix_ushort * m, unsigned short x);
GSL_FUN int gsl_matrix_ushort_fread (FILE * stream, gsl_matrix_ushort * m) ;
GSL_FUN int gsl_matrix_ushort_fwrite (FILE * stream, const gsl_matrix_ushort * m) ;
GSL_FUN int gsl_matrix_ushort_fscanf (FILE * stream, gsl_matrix_ushort * m);
GSL_FUN int gsl_matrix_ushort_fprintf (FILE * stream, const gsl_matrix_ushort * m, const char * format);
GSL_FUN int gsl_matrix_ushort_memcpy(gsl_matrix_ushort * dest, const gsl_matrix_ushort * src);
GSL_FUN int gsl_matrix_ushort_swap(gsl_matrix_ushort * m1, gsl_matrix_ushort * m2);
GSL_FUN int gsl_matrix_ushort_swap_rows(gsl_matrix_ushort * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_ushort_swap_columns(gsl_matrix_ushort * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_ushort_swap_rowcol(gsl_matrix_ushort * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_ushort_transpose (gsl_matrix_ushort * m);
GSL_FUN int gsl_matrix_ushort_transpose_memcpy (gsl_matrix_ushort * dest, const gsl_matrix_ushort * src);
GSL_FUN unsigned short gsl_matrix_ushort_max (const gsl_matrix_ushort * m);
GSL_FUN unsigned short gsl_matrix_ushort_min (const gsl_matrix_ushort * m);
GSL_FUN void gsl_matrix_ushort_minmax (const gsl_matrix_ushort * m, unsigned short * min_out, unsigned short * max_out);
GSL_FUN void gsl_matrix_ushort_max_index (const gsl_matrix_ushort * m, size_t * imax, size_t *jmax);
GSL_FUN void gsl_matrix_ushort_min_index (const gsl_matrix_ushort * m, size_t * imin, size_t *jmin);
GSL_FUN void gsl_matrix_ushort_minmax_index (const gsl_matrix_ushort * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_FUN int gsl_matrix_ushort_isnull (const gsl_matrix_ushort * m);
GSL_FUN int gsl_matrix_ushort_ispos (const gsl_matrix_ushort * m);
GSL_FUN int gsl_matrix_ushort_isneg (const gsl_matrix_ushort * m);
GSL_FUN int gsl_matrix_ushort_isnonneg (const gsl_matrix_ushort * m);
GSL_FUN int gsl_matrix_ushort_add (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);
GSL_FUN int gsl_matrix_ushort_sub (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);
GSL_FUN int gsl_matrix_ushort_mul_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);
GSL_FUN int gsl_matrix_ushort_div_elements (gsl_matrix_ushort * a, const gsl_matrix_ushort * b);
GSL_FUN int gsl_matrix_ushort_scale (gsl_matrix_ushort * a, const double x);
GSL_FUN int gsl_matrix_ushort_add_constant (gsl_matrix_ushort * a, const double x);
GSL_FUN int gsl_matrix_ushort_add_diagonal (gsl_matrix_ushort * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_FUN int gsl_matrix_ushort_get_row(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t i);
GSL_FUN int gsl_matrix_ushort_get_col(gsl_vector_ushort * v, const gsl_matrix_ushort * m, const size_t j);
GSL_FUN int gsl_matrix_ushort_set_row(gsl_matrix_ushort * m, const size_t i, const gsl_vector_ushort * v);
GSL_FUN int gsl_matrix_ushort_set_col(gsl_matrix_ushort * m, const size_t j, const gsl_vector_ushort * v);
/***********************************************************************/
/* inline functions if you are using GCC */
GSL_FUN INLINE_DECL unsigned short gsl_matrix_ushort_get(const gsl_matrix_ushort * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL void gsl_matrix_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short x);
GSL_FUN INLINE_DECL unsigned short * gsl_matrix_ushort_ptr(gsl_matrix_ushort * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL const unsigned short * gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
unsigned short
gsl_matrix_ushort_get(const gsl_matrix_ushort * 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_ushort_set(gsl_matrix_ushort * m, const size_t i, const size_t j, const unsigned short 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
unsigned short *
gsl_matrix_ushort_ptr(gsl_matrix_ushort * 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 (unsigned short *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
const unsigned short *
gsl_matrix_ushort_const_ptr(const gsl_matrix_ushort * 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 unsigned short *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_USHORT_H__ */
| {
"alphanum_fraction": 0.6543335761,
"avg_line_length": 38.2451253482,
"ext": "h",
"hexsha": "580e059e5db7b907fc6d545b58094df5e965435e",
"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": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "deps/include/gsl/gsl_matrix_ushort.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"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": "berkus/music-cs",
"max_issues_repo_path": "deps/include/gsl/gsl_matrix_ushort.h",
"max_line_length": 135,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "deps/include/gsl/gsl_matrix_ushort.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3395,
"size": 13730
} |
/* ode-initval2/cscal.c
*
* Copyright (C) 2002, 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 <string.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_odeiv2.h>
#include "control_utils.c"
typedef struct
{
double eps_abs;
double eps_rel;
double a_y;
double a_dydt;
double *scale_abs;
}
sc_control_state_t;
static void *
sc_control_alloc (void)
{
sc_control_state_t *s =
(sc_control_state_t *) malloc (sizeof (sc_control_state_t));
if (s == 0)
{
GSL_ERROR_NULL ("failed to allocate space for sc_control_state",
GSL_ENOMEM);
}
return s;
}
static int
sc_control_init (void *vstate,
double eps_abs, double eps_rel, double a_y, double a_dydt)
{
sc_control_state_t *s = (sc_control_state_t *) vstate;
if (eps_abs < 0)
{
GSL_ERROR ("eps_abs is negative", GSL_EINVAL);
}
else if (eps_rel < 0)
{
GSL_ERROR ("eps_rel is negative", GSL_EINVAL);
}
else if (a_y < 0)
{
GSL_ERROR ("a_y is negative", GSL_EINVAL);
}
else if (a_dydt < 0)
{
GSL_ERROR ("a_dydt is negative", GSL_EINVAL);
}
s->eps_rel = eps_rel;
s->eps_abs = eps_abs;
s->a_y = a_y;
s->a_dydt = a_dydt;
return GSL_SUCCESS;
}
static int
sc_control_hadjust (void *vstate, size_t dim, unsigned int ord,
const double y[], const double yerr[], const double yp[],
double *h)
{
sc_control_state_t *state = (sc_control_state_t *) vstate;
const double eps_abs = state->eps_abs;
const double eps_rel = state->eps_rel;
const double a_y = state->a_y;
const double a_dydt = state->a_dydt;
const double *scale_abs = state->scale_abs;
const double S = 0.9;
const double h_old = *h;
double rmax = DBL_MIN;
size_t i;
for (i = 0; i < dim; i++)
{
const double D0 =
eps_rel * (a_y * fabs (y[i]) + a_dydt * fabs (h_old * yp[i]))
+ eps_abs * scale_abs[i];
const double r = fabs (yerr[i]) / fabs (D0);
rmax = GSL_MAX_DBL (r, rmax);
}
if (rmax > 1.1)
{
/* decrease step, no more than factor of 5, but a fraction S more
than scaling suggests (for better accuracy) */
double r = S / pow (rmax, 1.0 / ord);
if (r < 0.2)
r = 0.2;
*h = r * h_old;
return GSL_ODEIV_HADJ_DEC;
}
else if (rmax < 0.5)
{
/* increase step, no more than factor of maxscale */
double r = S / pow (rmax, 1.0 / (ord + 1.0));
const double maxscale = 4.9;
if (r > maxscale)
r = maxscale;
if (r < 1.0) /* don't allow any decrease caused by S<1 */
r = 1.0;
*h = r * h_old;
return GSL_ODEIV_HADJ_INC;
}
else
{
/* no change */
return GSL_ODEIV_HADJ_NIL;
}
}
static int
sc_control_errlevel (void *vstate, const double y, const double dydt,
const double h, const size_t ind, double *errlev)
{
sc_control_state_t *state = (sc_control_state_t *) vstate;
const double eps_abs = state->eps_abs;
const double eps_rel = state->eps_rel;
const double a_y = state->a_y;
const double a_dydt = state->a_dydt;
const double *scale_abs = state->scale_abs;
*errlev = eps_rel * (a_y * fabs (y) + a_dydt * fabs (h * dydt))
+ eps_abs * scale_abs[ind];
if (*errlev <= 0.0)
{
GSL_ERROR ("errlev <= zero", GSL_ESANITY);
}
return GSL_SUCCESS;
}
static void
sc_control_free (void *vstate)
{
sc_control_state_t *state = (sc_control_state_t *) vstate;
free (state->scale_abs);
free (state);
}
static const gsl_odeiv2_control_type sc_control_type = { "scaled", /* name */
&sc_control_alloc,
&sc_control_init,
&sc_control_hadjust,
&sc_control_errlevel,
&control_set_driver_null,
&sc_control_free
};
const gsl_odeiv2_control_type *gsl_odeiv2_control_scaled = &sc_control_type;
gsl_odeiv2_control *
gsl_odeiv2_control_scaled_new (double eps_abs, double eps_rel,
double a_y, double a_dydt,
const double scale_abs[], size_t dim)
{
gsl_odeiv2_control *c =
gsl_odeiv2_control_alloc (gsl_odeiv2_control_scaled);
int status = gsl_odeiv2_control_init (c, eps_abs, eps_rel, a_y, a_dydt);
if (status != GSL_SUCCESS)
{
gsl_odeiv2_control_free (c);
GSL_ERROR_NULL ("error trying to initialize control", status);
}
{
sc_control_state_t *s = (sc_control_state_t *) c->state;
s->scale_abs = (double *) malloc (dim * sizeof (double));
if (s->scale_abs == 0)
{
free (s);
GSL_ERROR_NULL ("failed to allocate space for scale_abs", GSL_ENOMEM);
}
memcpy (s->scale_abs, scale_abs, dim * sizeof (double));
}
return c;
}
| {
"alphanum_fraction": 0.633580873,
"avg_line_length": 24.5377777778,
"ext": "c",
"hexsha": "cfec4180b69aaad5289ac2925e615a1d8b11d01c",
"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": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "igormcoelho/optstats",
"max_forks_repo_path": "thirdparty/gsl-2.7/ode-initval2/cscal.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4",
"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": "igormcoelho/optstats",
"max_issues_repo_path": "thirdparty/gsl-2.7/ode-initval2/cscal.c",
"max_line_length": 82,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6d95cf06fbb96b1cc047fa570690c6eb3d21ece4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "igormcoelho/optstats",
"max_stars_repo_path": "thirdparty/gsl-2.7/ode-initval2/cscal.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1600,
"size": 5521
} |
/*
* Gates.h
*
* Created on: 28 Jan 2019
* Author: jobinrjohnson
*/
#ifndef IMPLEMENTATION_GATES_H_
#define IMPLEMENTATION_GATES_H_
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_math.h>
#define ccout std::cout
#define cendl std::endl
#include <qubit.h>
#define GATE_HARDAMARD 1
#define GATE_PAULI_X 2
#define GATE_PAULI_Y 6
#define GATE_PAULI_Z 7
#define GATE_CNOT 3
#define GATE_SWAP 4
#define GATE_T 5
#include <iostream>
class Gates
{
protected:
gsl_matrix_complex *get_gate_matrix(int);
public:
Gates();
virtual ~Gates();
static bool get_measure(Qubit &q)
{
// TODO Better random and measure implementation
gsl_vector_complex *state = q.get_state();
double amp_0 = gsl_complex_abs2(gsl_vector_complex_get(state, 0));
const gsl_rng_type *T;
gsl_rng *r;
gsl_rng_env_setup();
gsl_rng_default_seed = time(NULL);
T = gsl_rng_default;
r = gsl_rng_alloc(T);
double u = gsl_rng_uniform(r);
gsl_rng_free(r);
if (u >= amp_0)
{
return true;
}
return false;
}
};
#endif /* IMPLEMENTATION_GATES_H_ */
| {
"alphanum_fraction": 0.7146574154,
"avg_line_length": 16.2394366197,
"ext": "h",
"hexsha": "bf3a46b18bb669a777940ea12d2d420a7ac0b29e",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-11-12T08:04:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-06T09:04:35.000Z",
"max_forks_repo_head_hexsha": "fc2b45229acb82c87b6f50b567611d8d8abd4dd4",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "jobinrjohnson/QSim",
"max_forks_repo_path": "implementation/include/gates.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fc2b45229acb82c87b6f50b567611d8d8abd4dd4",
"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": "jobinrjohnson/QSim",
"max_issues_repo_path": "implementation/include/gates.h",
"max_line_length": 68,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "fc2b45229acb82c87b6f50b567611d8d8abd4dd4",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "jobinrjohnson/QSim",
"max_stars_repo_path": "implementation/include/gates.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-05T20:22:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-03T18:58:37.000Z",
"num_tokens": 354,
"size": 1153
} |
#include <stdlib.h>
#include <gsl/gsl_statistics_double.h>
#include <hdf5.h>
#include <hdf5_hl.h>
#include "qdm.h"
qdm_ijk *
qdm_ijk_alloc(
size_t size1,
size_t size2,
size_t size3
)
{
qdm_ijk *t = malloc(sizeof(qdm_ijk));
t->size1 = size1;
t->size2 = size2;
t->size3 = size3;
t->data = malloc(sizeof(double) * size1 * size2 * size3);
t->owner = true;
return t;
}
qdm_ijk *
qdm_ijk_calloc(
size_t size1,
size_t size2,
size_t size3
)
{
qdm_ijk *t = malloc(sizeof(qdm_ijk));
t->size1 = size1;
t->size2 = size2;
t->size3 = size3;
t->data = calloc(sizeof(double), size1 * size2 * size3);
t->owner = true;
return t;
}
void
qdm_ijk_free(
qdm_ijk *t
)
{
if (t == NULL) {
return;
}
if (t->owner) {
free(t->data);
}
free(t);
}
qdm_ijk_view
qdm_ijk_view_array(
double *base,
size_t size1,
size_t size2,
size_t size3
)
{
qdm_ijk_view v = {
.ijk = {
.size1 = size1,
.size2 = size2,
.size3 = size3,
.data = base,
.owner = false,
},
};
return v;
}
gsl_vector_view
qdm_ijk_get_k(
qdm_ijk *t,
size_t i,
size_t j
)
{
return gsl_vector_view_array_with_stride(
&t->data[i * t->size2 + j],
t->size1 * t->size2,
t->size3
);
}
gsl_matrix_view
qdm_ijk_get_ij(
qdm_ijk *t,
size_t k
)
{
return gsl_matrix_view_array(
&t->data[k * t->size1 * t->size2],
t->size1,
t->size2
);
}
double
qdm_ijk_get(
qdm_ijk *t,
size_t i,
size_t j,
size_t k
)
{
gsl_matrix_view ij = qdm_ijk_get_ij(t, k);
return gsl_matrix_get(&ij.matrix, i, j);
}
gsl_matrix *
qdm_ijk_cov(
qdm_ijk *t
)
{
size_t d = t->size1 * t->size2;
size_t dr = 0;
gsl_matrix *r = gsl_matrix_calloc(d, d);
for (size_t i0 = 0; i0 < t->size1; i0++) {
for (size_t j0 = 0; j0 < t->size2; j0++) {
gsl_vector_view k0 = qdm_ijk_get_k(t, i0, j0);
/* TODO: When we have time (and if it matters), this is symmetric and we
* don't need to do a bunch of these if we get a little clever about
* copying the mirror'd results.
*/
for (size_t ip = 0; ip < t->size1; ip++) {
for (size_t jp = 0; jp < t->size2; jp++) {
gsl_vector_view kp = qdm_ijk_get_k(t, ip, jp);
double cov = gsl_stats_covariance(
k0.vector.data,
k0.vector.stride,
kp.vector.data,
kp.vector.stride,
kp.vector.size
);
gsl_matrix_set(r, dr, ip * t->size2 + jp, cov);
}
}
dr++;
}
}
return r;
}
int
qdm_ijk_write(
hid_t id,
const char *name,
const qdm_ijk *t
)
{
int status = 0;
hid_t datatype = -1;
hid_t dataspace = -1;
hid_t dataset = -1;
if (t == NULL) {
goto cleanup;
}
datatype = H5Tcopy(H5T_NATIVE_DOUBLE);
status = H5Tset_order(datatype, H5T_ORDER_LE);
if (status != 0) {
goto cleanup;
}
hsize_t dims[3] = {
t->size3,
t->size1,
t->size2,
};
dataspace = H5Screate_simple(3, dims, NULL);
if (dataspace < 0) {
status = dataspace;
goto cleanup;
}
dataset = H5Dcreate(id, name, datatype, dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
if (dataset < 0) {
status = dataset;
goto cleanup;
}
status = H5Dwrite(dataset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, t->data);
if (status != 0) {
goto cleanup;
}
cleanup:
if (dataset >= 0) {
H5Dclose(dataset);
}
if (dataspace >= 0) {
H5Sclose(dataspace);
}
if (datatype >= 0) {
H5Tclose(datatype);
}
H5Oflush(id);
return status;
}
int
qdm_ijk_read(
hid_t id,
const char *name,
qdm_ijk **t
)
{
int status = 0;
int rank = 0;
status = H5LTget_dataset_ndims(id, name, &rank);
if (status < 0) {
return status;
}
if (rank != 3) {
return -1;
}
hsize_t dims[3];
status = H5LTget_dataset_info(id, name, dims, NULL, NULL);
if (status < 0) {
return status;
}
size_t size3 = dims[0];
size_t size1 = dims[1];
size_t size2 = dims[2];
qdm_ijk *tmp = qdm_ijk_alloc(size1, size2, size3);
status = H5LTread_dataset_double(id, name, tmp->data);
if (status < 0) {
qdm_ijk_free(tmp);
return status;
}
*t = tmp;
return status;
}
| {
"alphanum_fraction": 0.5718931475,
"avg_line_length": 15.7116788321,
"ext": "c",
"hexsha": "3f9e3e8d99c929acdc462fcb93ce404dd8f69315",
"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": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "src/ijk.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "src/ijk.c",
"max_line_length": 92,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "src/ijk.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1501,
"size": 4305
} |
//**************************************************************************\
//* This file is property of and copyright by the ALICE Project *\
//* ALICE Experiment at CERN, All rights reserved. *\
//* *\
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\
//* for The ALICE HLT Project. *\
//* *\
//* Permission to use, copy, modify and distribute this software and its *\
//* documentation strictly for non-commercial purposes is hereby granted *\
//* without fee, provided that the above copyright notice appears in all *\
//* copies and that both the copyright notice and this permission notice *\
//* appear in the supporting documentation. The authors make no claims *\
//* about the suitability of this software for any purpose. It is *\
//* provided "as is" without express or implied warranty. *\
//**************************************************************************
/// \file GPUQA.h
/// \author David Rohr
#ifndef GPUQA_H
#define GPUQA_H
#include "GPUQAConfig.h"
struct AliHLTTPCClusterMCWeight;
class TH1F;
class TH2F;
class TCanvas;
class TPad;
class TLegend;
class TPad;
class TH1;
class TFile;
class TH1D;
typedef short int Color_t;
#if !defined(GPUCA_BUILD_QA) || defined(GPUCA_GPUCODE)
namespace GPUCA_NAMESPACE
{
namespace gpu
{
class GPUChainTracking;
class GPUQA
{
public:
GPUQA(GPUChainTracking* rec) {}
~GPUQA() = default;
typedef structConfigQA configQA;
int InitQA() { return 1; }
void RunQA(bool matchOnly = false) {}
int DrawQAHistograms() { return 1; }
void SetMCTrackRange(int min, int max) {}
bool SuppressTrack(int iTrack) const { return false; }
bool SuppressHit(int iHit) const { return false; }
bool HitAttachStatus(int iHit) const { return false; }
int GetMCTrackLabel(unsigned int trackId) const { return -1; }
bool clusterRemovable(int cid, bool prot) const { return false; }
static bool QAAvailable() { return false; }
};
} // namespace gpu
} // namespace GPUCA_NAMESPACE
#else
#include "GPUTPCDef.h"
#include <cmath>
#ifdef GPUCA_TPC_GEOMETRY_O2
#include <gsl/span>
#endif
namespace o2
{
class MCCompLabel;
}
class AliHLTTPCClusterMCLabel;
namespace GPUCA_NAMESPACE
{
namespace gpu
{
class GPUChainTracking;
class GPUTPCMCInfo;
class GPUQA
{
public:
GPUQA(GPUChainTracking* rec);
~GPUQA();
typedef GPUQAConfig configQA;
int InitQA();
void RunQA(bool matchOnly = false);
int DrawQAHistograms();
void SetMCTrackRange(int min, int max);
bool SuppressTrack(int iTrack) const;
bool SuppressHit(int iHit) const;
bool HitAttachStatus(int iHit) const;
int GetMCTrackLabel(unsigned int trackId) const;
bool clusterRemovable(int cid, bool prot) const;
static bool QAAvailable() { return true; }
private:
struct additionalMCParameters {
float pt, phi, theta, eta, nWeightCls;
};
struct additionalClusterParameters {
int attached, fakeAttached, adjacent, fakeAdjacent;
float pt;
};
void SetAxisSize(TH1F* e);
void SetLegend(TLegend* l);
double* CreateLogAxis(int nbins, float xmin, float xmax);
void ChangePadTitleSize(TPad* p, float size);
void DrawHisto(TH1* histo, char* filename, char* options);
void doPerfFigure(float x, float y, float size);
void GetName(char* fname, int k);
template <class T>
T* GetHist(T*& ee, std::vector<TFile*>& tin, int k, int nNewInput);
#ifdef GPUCA_TPC_GEOMETRY_O2
using mcLabels_t = gsl::span<const o2::MCCompLabel>;
using mcLabel_t = o2::MCCompLabel;
using mcLabelI_t = mcLabel_t;
using mcInfo_t = GPUTPCMCInfo;
mcLabels_t GetMCLabel(unsigned int i);
mcLabel_t GetMCLabel(unsigned int i, unsigned int j);
#else
using mcLabels_t = AliHLTTPCClusterMCLabel;
using mcLabel_t = AliHLTTPCClusterMCWeight;
struct mcLabelI_t {
int getTrackID() const { return AbsLabelID(track); }
int getEventID() const { return 0; }
bool isFake() const { return track < 0; }
bool isValid() const { return track != MC_LABEL_INVALID; }
void invalidate() { track = MC_LABEL_INVALID; }
void setFakeFlag(bool v = true) { track = v ? FakeLabelID(track) : AbsLabelID(track); }
void setNoise() { track = MC_LABEL_INVALID; }
bool operator==(const mcLabel_t& l);
bool operator!=(const mcLabel_t& l) { return !(*this == l); }
mcLabelI_t() = default;
mcLabelI_t(const mcLabel_t& l);
int track = MC_LABEL_INVALID;
};
using mcInfo_t = GPUTPCMCInfo;
const mcLabels_t& GetMCLabel(unsigned int i);
const mcLabel_t& GetMCLabel(unsigned int i, unsigned int j);
const mcInfo_t& GetMCTrack(const mcLabelI_t& label);
static int FakeLabelID(const int id);
static int AbsLabelID(const int id);
#endif
template <class T>
static auto& GetMCTrackObj(T& obj, const mcLabelI_t& l);
unsigned int GetNMCCollissions();
unsigned int GetNMCTracks(int iCol);
unsigned int GetNMCLabels();
const mcInfo_t& GetMCTrack(unsigned int iTrk, unsigned int iCol);
const mcInfo_t& GetMCTrack(const mcLabel_t& label);
int GetMCLabelNID(const mcLabels_t& label);
int GetMCLabelNID(unsigned int i);
int GetMCLabelID(unsigned int i, unsigned int j);
int GetMCLabelCol(unsigned int i, unsigned int j);
static int GetMCLabelID(const mcLabels_t& label, unsigned int j);
static int GetMCLabelID(const mcLabel_t& label);
float GetMCLabelWeight(unsigned int i, unsigned int j);
float GetMCLabelWeight(const mcLabels_t& label, unsigned int j);
float GetMCLabelWeight(const mcLabel_t& label);
bool mcPresent();
static bool MCComp(const mcLabel_t& a, const mcLabel_t& b);
GPUChainTracking* mTracking;
const configQA& mConfig;
//-------------------------: Some compile time settings....
static const constexpr bool PLOT_ROOT = 0;
static const constexpr bool FIX_SCALES = 0;
static const constexpr bool PERF_FIGURE = 0;
static const constexpr float FIXED_SCALES_MIN[5] = {-0.05, -0.05, -0.2, -0.2, -0.5};
static const constexpr float FIXED_SCALES_MAX[5] = {0.4, 0.7, 5, 3, 6.5};
static const constexpr float LOG_PT_MIN = -1.;
const char* str_perf_figure_1 = "ALICE Performance 2018/03/20";
// const char* str_perf_figure_2 = "2015, MC pp, #sqrt{s} = 5.02 TeV";
const char* str_perf_figure_2 = "2015, MC Pb-Pb, #sqrt{s_{NN}} = 5.02 TeV";
//-------------------------
std::vector<mcLabelI_t> mTrackMCLabels;
#ifdef GPUCA_TPC_GEOMETRY_O2
std::vector<std::vector<int>> mTrackMCLabelsReverse;
std::vector<std::vector<int>> mRecTracks;
std::vector<std::vector<int>> mFakeTracks;
std::vector<std::vector<additionalMCParameters>> mMCParam;
std::vector<std::vector<mcInfo_t>> mMCInfos;
std::vector<int> mNColTracks;
#else
std::vector<int> mTrackMCLabelsReverse[1];
std::vector<int> mRecTracks[1];
std::vector<int> mFakeTracks[1];
std::vector<additionalMCParameters> mMCParam[1];
#endif
std::vector<additionalClusterParameters> mClusterParam;
int mNTotalFakes = 0;
TH1F* mEff[4][2][2][5][2]; // eff,clone,fake,all - findable - secondaries - y,z,phi,eta,pt - work,result
TCanvas* mCEff[6];
TPad* mPEff[6][4];
TLegend* mLEff[6];
TH1F* mRes[5][5][2]; // y,z,phi,lambda,pt,ptlog res - param - res,mean
TH2F* mRes2[5][5];
TCanvas* mCRes[7];
TPad* mPRes[7][5];
TLegend* mLRes[6];
TH1F* mPull[5][5][2]; // y,z,phi,lambda,pt,ptlog res - param - res,mean
TH2F* mPull2[5][5];
TCanvas* mCPull[7];
TPad* mPPull[7][5];
TLegend* mLPull[6];
static constexpr int N_CLS_HIST = 8;
static constexpr int N_CLS_TYPE = 3;
enum CL_types { CL_attached = 0,
CL_fake = 1,
CL_att_adj = 2,
CL_fakeAdj = 3,
CL_tracks = 4,
CL_physics = 5,
CL_prot = 6,
CL_all = 7 };
TH1D* mClusters[N_CLS_TYPE * N_CLS_HIST - 1]; // attached, fakeAttached, attach+adjacent, fakeAdjacent, physics, protected, tracks, all / count, rel, integral
TCanvas* mCClust[N_CLS_TYPE];
TPad* mPClust[N_CLS_TYPE];
TLegend* mLClust[N_CLS_TYPE];
long long int mNRecClustersRejected = 0, mNRecClustersTube = 0, mNRecClustersTube200 = 0, mNRecClustersLoopers = 0, mNRecClustersLowPt = 0, mNRecClusters200MeV = 0, mNRecClustersPhysics = 0, mNRecClustersProt = 0, mNRecClustersUnattached = 0, mNRecClustersTotal = 0, mNRecClustersHighIncl = 0,
mNRecClustersAbove400 = 0, mNRecClustersFakeRemove400 = 0, mNRecClustersFullFakeRemove400 = 0, mNRecClustersBelow40 = 0, mNRecClustersFakeProtect40 = 0;
double mNRecClustersUnaccessible = 0;
TH1F* mTracks;
TCanvas* mCTracks;
TPad* mPTracks;
TLegend* mLTracks;
TH1F* mNCl;
TCanvas* mCNCl;
TPad* mPNCl;
TLegend* mLNCl;
int mNEvents = 0;
bool mQAInitialized = false;
std::vector<std::vector<int>> mcEffBuffer;
std::vector<std::vector<int>> mcLabelBuffer;
std::vector<std::vector<bool>> mGoodTracks;
std::vector<std::vector<bool>> mGoodHits;
static constexpr float Y_MAX = 40;
static constexpr float Z_MAX = 100;
static constexpr float PT_MIN = GPUCA_MIN_TRACK_PT_DEFAULT;
static constexpr float PT_MIN2 = 0.1;
static constexpr float PT_MIN_PRIM = 0.1;
static constexpr float PT_MIN_CLUST = GPUCA_MIN_TRACK_PT_DEFAULT;
static constexpr float PT_MAX = 20;
static constexpr float ETA_MAX = 1.5;
static constexpr float ETA_MAX2 = 0.9;
static constexpr float MIN_WEIGHT_CLS = 40;
static constexpr float FINDABLE_WEIGHT_CLS = 70;
static constexpr int MC_LABEL_INVALID = -1e9;
static constexpr bool CLUST_HIST_INT_SUM = false;
static constexpr const int COLORCOUNT = 12;
Color_t* mColorNums;
static const constexpr char* EFF_TYPES[4] = {"Rec", "Clone", "Fake", "All"};
static const constexpr char* FINDABLE_NAMES[2] = {"", "Findable"};
static const constexpr char* PRIM_NAMES[2] = {"Prim", "Sec"};
static const constexpr char* PARAMETER_NAMES[5] = {"Y", "Z", "#Phi", "#lambda", "Relative #it{p}_{T}"};
static const constexpr char* PARAMETER_NAMES_NATIVE[5] = {"Y", "Z", "sin(#Phi)", "tan(#lambda)", "q/#it{p}_{T} (curvature)"};
static const constexpr char* VSPARAMETER_NAMES[6] = {"Y", "Z", "Phi", "Eta", "Pt", "Pt_log"};
static const constexpr char* EFF_NAMES[3] = {"Efficiency", "Clone Rate", "Fake Rate"};
static const constexpr char* EFFICIENCY_TITLES[4] = {"Efficiency (Primary Tracks, Findable)", "Efficiency (Secondary Tracks, Findable)", "Efficiency (Primary Tracks)", "Efficiency (Secondary Tracks)"};
static const constexpr double SCALE[5] = {10., 10., 1000., 1000., 100.};
static const constexpr double SCALE_NATIVE[5] = {10., 10., 1000., 1000., 1.};
static const constexpr char* XAXIS_TITLES[5] = {"#it{y}_{mc} (cm)", "#it{z}_{mc} (cm)", "#Phi_{mc} (rad)", "#eta_{mc}", "#it{p}_{Tmc} (GeV/#it{c})"};
static const constexpr char* AXIS_TITLES[5] = {"#it{y}-#it{y}_{mc} (mm) (Resolution)", "#it{z}-#it{z}_{mc} (mm) (Resolution)", "#phi-#phi_{mc} (mrad) (Resolution)", "#lambda-#lambda_{mc} (mrad) (Resolution)", "(#it{p}_{T} - #it{p}_{Tmc}) / #it{p}_{Tmc} (%) (Resolution)"};
static const constexpr char* AXIS_TITLES_NATIVE[5] = {"#it{y}-#it{y}_{mc} (mm) (Resolution)", "#it{z}-#it{z}_{mc} (mm) (Resolution)", "sin(#phi)-sin(#phi_{mc}) (Resolution)", "tan(#lambda)-tan(#lambda_{mc}) (Resolution)", "q*(q/#it{p}_{T} - q/#it{p}_{Tmc}) (Resolution)"};
static const constexpr char* AXIS_TITLES_PULL[5] = {"#it{y}-#it{y}_{mc}/#sigma_{y} (Pull)", "#it{z}-#it{z}_{mc}/#sigma_{z} (Pull)", "sin(#phi)-sin(#phi_{mc})/#sigma_{sin(#phi)} (Pull)", "tan(#lambda)-tan(#lambda_{mc})/#sigma_{tan(#lambda)} (Pull)",
"q*(q/#it{p}_{T} - q/#it{p}_{Tmc})/#sigma_{q/#it{p}_{T}} (Pull)"};
static const constexpr char* CLUSTER_NAMES[N_CLS_HIST] = {"Correctly attached clusters", "Fake attached clusters", "Attached + adjacent clusters", "Fake adjacent clusters", "Clusters of reconstructed tracks", "Used in Physics", "Protected", "All clusters"};
static const constexpr char* CLUSTER_TITLES[N_CLS_TYPE] = {"Clusters Pt Distribution / Attachment", "Clusters Pt Distribution / Attachment (relative to all clusters)", "Clusters Pt Distribution / Attachment (integrated)"};
static const constexpr char* CLUSTER_NAMES_SHORT[N_CLS_HIST] = {"Attached", "Fake", "AttachAdjacent", "FakeAdjacent", "FoundTracks", "Physics", "Protected", "All"};
static const constexpr char* CLUSTER_TYPES[N_CLS_TYPE] = {"", "Ratio", "Integral"};
static const constexpr int COLORS_HEX[COLORCOUNT] = {0xB03030, 0x00A000, 0x0000C0, 0x9400D3, 0x19BBBF, 0xF25900, 0x7F7F7F, 0xFFD700, 0x07F707, 0x07F7F7, 0xF08080, 0x000000};
static const constexpr int CONFIG_DASHED_MARKERS = 0;
static const constexpr float AXES_MIN[5] = {-Y_MAX, -Z_MAX, 0.f, -ETA_MAX, PT_MIN};
static const constexpr float AXES_MAX[5] = {Y_MAX, Z_MAX, 2.f * M_PI, ETA_MAX, PT_MAX};
static const constexpr int AXIS_BINS[5] = {51, 51, 144, 31, 50};
static const constexpr int RES_AXIS_BINS[] = {1017, 113}; // Consecutive bin sizes, histograms are binned down until the maximum entry is 50, each bin size should evenly divide its predecessor.
static const constexpr float RES_AXES[5] = {1., 1., 0.03, 0.03, 1.0};
static const constexpr float RES_AXES_NATIVE[5] = {1., 1., 0.1, 0.1, 5.0};
static const constexpr float PULL_AXIS = 10.f;
int mMCTrackMin = -1, mMCTrackMax = -1;
};
inline bool GPUQA::SuppressTrack(int iTrack) const { return (mConfig.matchMCLabels.size() && !mGoodTracks[mNEvents][iTrack]); }
inline bool GPUQA::SuppressHit(int iHit) const { return (mConfig.matchMCLabels.size() && !mGoodHits[mNEvents - 1][iHit]); }
inline bool GPUQA::HitAttachStatus(int iHit) const { return (mClusterParam.size() && mClusterParam[iHit].fakeAttached ? (mClusterParam[iHit].attached ? 1 : 2) : 0); }
} // namespace gpu
} // namespace GPUCA_NAMESPACE
#endif
#endif
| {
"alphanum_fraction": 0.675948461,
"avg_line_length": 42.462006079,
"ext": "h",
"hexsha": "851c2c184bb9931083de09b7087cd6b7975626a9",
"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": "e81490f640ad6f2a6189f679de96b07a94304b58",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "mpoghos/AliRoot",
"max_forks_repo_path": "GPU/GPUTracking/Standalone/qa/GPUQA.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e81490f640ad6f2a6189f679de96b07a94304b58",
"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": "mpoghos/AliRoot",
"max_issues_repo_path": "GPU/GPUTracking/Standalone/qa/GPUQA.h",
"max_line_length": 295,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e81490f640ad6f2a6189f679de96b07a94304b58",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mpoghos/AliRoot",
"max_stars_repo_path": "GPU/GPUTracking/Standalone/qa/GPUQA.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4221,
"size": 13970
} |
#pragma once
#include <cstdint>
#include <array>
#include <gsl/gsl>
#include "halley/data_structures/maybe.h"
#include "halley/maths/vector2.h"
#include "halley/maths/colour.h"
#include "halley/file_formats/image.h"
namespace Halley {
enum class AsepriteBlendMode;
enum class AsepriteDepth
{
RGBA32,
Greyscale16,
Indexed8
};
struct AsepriteCel
{
public:
Vector2i pos;
Vector2i size;
uint16_t layer = 0;
uint16_t linkedFrame = 0;
uint8_t opacity = 255;
bool linked = false;
Bytes rawData;
std::unique_ptr<Image> imgData;
void loadImage(AsepriteDepth depth, const Vector<uint32_t>& palette);
void drawAt(Image& image, uint8_t opacity, AsepriteBlendMode blendMode) const;
};
struct AsepriteFrame
{
public:
AsepriteFrame(uint16_t duration);
uint16_t duration;
Vector<AsepriteCel> cels;
};
enum class AsepriteLayerType
{
Normal,
Group
};
enum class AsepriteBlendMode
{
Normal,
Multiply,
Screen,
Overlay,
Darken,
Lighten,
ColorDodge,
ColorBurn,
HardLight,
SoftLight,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
Addition,
Subtract,
Divide
};
struct AsepriteLayer
{
AsepriteLayerType type = AsepriteLayerType::Normal;
AsepriteBlendMode blendMode = AsepriteBlendMode::Normal;
int childLevel = 0;
bool visible = true;
bool editable = true;
bool lockMovement = false;
bool background = false;
bool preferLinkedCels = false;
bool layerGroupDisplaysCollapsed = false;
bool referenceLayer = false;
uint8_t opacity = 255;
String layerName;
OptionalLite<uint32_t> parentIdx;
bool visibleInHierarchy = true;
};
enum class AsepriteAnimationDirection
{
Forward,
Reverse,
PingPong
};
struct AsepriteTag
{
int fromFrame = -1;
int toFrame = -1;
AsepriteAnimationDirection animDirection = AsepriteAnimationDirection::Forward;
String name;
};
class AsepriteFile {
public:
AsepriteFile();
void load(gsl::span<const gsl::byte> data);
const Vector<AsepriteTag>& getTags() const;
std::map<String, std::unique_ptr<Image>> makeGroupFrameImages(int frameNumber, bool groupSeparated);
const AsepriteFrame& getFrame(int n) const;
size_t getNumberOfFrames() const;
private:
void addFrame(uint16_t duration);
void addChunk(uint16_t chunkType, gsl::span<const gsl::byte> data);
void addLayerChunk(gsl::span<const gsl::byte> span);
void addCelChunk(gsl::span<const gsl::byte> span);
void addCelExtraChunk(gsl::span<const gsl::byte> span);
void addPaletteChunk(gsl::span<const gsl::byte> span);
void addTagsChunk(gsl::span<const gsl::byte> span);
void postProcessLayers();
template <typename T>
void readData(T& dst, gsl::span<const gsl::byte>& data) const
{
if (data.size() < T::size) {
throw Exception("Insufficient data to decode Aseprite entry", HalleyExceptions::Tools);
}
memcpy(&dst, data.data(), T::size);
data = data.subspan(T::size);
}
String readString(gsl::span<const gsl::byte>& data) const
{
if (data.size() < 2) {
throw Exception("Insufficient data to decode Aseprite entry", HalleyExceptions::Tools);
}
uint16_t size;
memcpy(&size, data.data(), 2);
data = data.subspan(2);
if (data.size() < size) {
throw Exception("Insufficient data to decode Aseprite entry", HalleyExceptions::Tools);
}
String result = String(reinterpret_cast<const char*>(data.data()), size);
data = data.subspan(size);
return result;
}
AsepriteCel* getCelAt(int frameNumber, int layerNumber);
size_t getBPP() const;
Vector2i size;
uint32_t flags;
AsepriteDepth colourDepth;
uint8_t transparentEntry;
uint16_t numOfColours;
Vector<AsepriteFrame> frames;
Vector<AsepriteLayer> layers;
Vector<AsepriteTag> tags;
Vector<uint32_t> paletteBg;
Vector<uint32_t> paletteTransparent;
};
}
| {
"alphanum_fraction": 0.7071097372,
"avg_line_length": 22.0568181818,
"ext": "h",
"hexsha": "ecafbd28aa2d680db7e63122915a3750eb04933b",
"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": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "amrezzd/halley",
"max_forks_repo_path": "src/tools/tools/src/sprites/aseprite_file.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4",
"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": "amrezzd/halley",
"max_issues_repo_path": "src/tools/tools/src/sprites/aseprite_file.h",
"max_line_length": 102,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "amrezzd/halley",
"max_stars_repo_path": "src/tools/tools/src/sprites/aseprite_file.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1124,
"size": 3882
} |
#if !defined(PETIGA_H)
#define PETIGA_H
/*
#include <petscconf.h>
#undef PETSC_STATIC_INLINE
#define PETSC_STATIC_INLINE static __inline
*/
#include <petsc.h>
#include <petsc-private/petscimpl.h>
#include <petscts2.h>
typedef ISLocalToGlobalMapping LGMap;
#define LGMap LGMap
/* ---------------------------------------------------------------- */
typedef struct _p_IGA *IGA;
typedef struct _n_IGAAxis *IGAAxis;
typedef struct _n_IGARule *IGARule;
typedef struct _n_IGABasis *IGABasis;
typedef struct _n_IGAForm *IGAForm;
typedef struct _n_IGAElement *IGAElement;
typedef struct _n_IGAPoint *IGAPoint;
/* ---------------------------------------------------------------- */
struct _n_IGAAxis {
PetscInt refct;
/**/
PetscInt p; /* polynomial order */
PetscInt m; /* last knot index */
PetscReal *U; /* knot vector */
/**/
PetscBool periodic; /* periodicity */
PetscInt nnp,nel; /* bases, spans */
PetscInt *span; /* span indices */
};
PETSC_EXTERN PetscErrorCode IGAAxisCreate(IGAAxis *axis);
PETSC_EXTERN PetscErrorCode IGAAxisDestroy(IGAAxis *axis);
PETSC_EXTERN PetscErrorCode IGAAxisReset(IGAAxis axis);
PETSC_EXTERN PetscErrorCode IGAAxisReference(IGAAxis axis);
PETSC_EXTERN PetscErrorCode IGAAxisCopy(IGAAxis base,IGAAxis axis);
PETSC_EXTERN PetscErrorCode IGAAxisDuplicate(IGAAxis base,IGAAxis *axis);
PETSC_EXTERN PetscErrorCode IGAAxisSetPeriodic(IGAAxis axis,PetscBool periodic);
PETSC_EXTERN PetscErrorCode IGAAxisGetPeriodic(IGAAxis axis,PetscBool *periodic);
PETSC_EXTERN PetscErrorCode IGAAxisSetDegree(IGAAxis axis,PetscInt p);
PETSC_EXTERN PetscErrorCode IGAAxisGetDegree(IGAAxis axis,PetscInt *p);
PETSC_EXTERN PetscErrorCode IGAAxisSetKnots(IGAAxis axis,PetscInt m,const PetscReal U[]);
PETSC_EXTERN PetscErrorCode IGAAxisGetKnots(IGAAxis axis,PetscInt *m,PetscReal *U[]);
PETSC_EXTERN PetscErrorCode IGAAxisGetLimits(IGAAxis axis,PetscReal *Ui,PetscReal *Uf);
PETSC_EXTERN PetscErrorCode IGAAxisGetSizes(IGAAxis axis,PetscInt *nel,PetscInt *nnp);
PETSC_EXTERN PetscErrorCode IGAAxisGetSpans(IGAAxis axis,PetscInt *nel,PetscInt *spans[]);
PETSC_EXTERN PetscErrorCode IGAAxisInit(IGAAxis axis,PetscInt p,PetscInt m,const PetscReal U[]);
PETSC_EXTERN PetscErrorCode IGAAxisInitBreaks(IGAAxis axis,PetscInt nu,const PetscReal u[],PetscInt C);
PETSC_EXTERN PetscErrorCode IGAAxisInitUniform(IGAAxis axis,PetscInt N,PetscReal Ui,PetscReal Uf,PetscInt C);
PETSC_EXTERN PetscErrorCode IGAAxisSetUp(IGAAxis axis);
struct _n_IGARule {
PetscInt refct;
/**/
PetscInt nqp; /* number of quadrature points */
PetscReal *point; /* [nqp] quadrature points */
PetscReal *weight; /* [nqp] quadrature weights */
};
PETSC_EXTERN PetscErrorCode IGARuleCreate(IGARule *rule);
PETSC_EXTERN PetscErrorCode IGARuleDestroy(IGARule *rule);
PETSC_EXTERN PetscErrorCode IGARuleReset(IGARule rule);
PETSC_EXTERN PetscErrorCode IGARuleReference(IGARule rule);
PETSC_EXTERN PetscErrorCode IGARuleCopy(IGARule base,IGARule rule);
PETSC_EXTERN PetscErrorCode IGARuleDuplicate(IGARule base,IGARule *rule);
PETSC_EXTERN PetscErrorCode IGARuleInit(IGARule rule,PetscInt q);
PETSC_EXTERN PetscErrorCode IGARuleSetRule(IGARule rule,PetscInt q,const PetscReal x[],const PetscReal w[]);
PETSC_EXTERN PetscErrorCode IGARuleGetRule(IGARule rule,PetscInt *q,PetscReal *x[],PetscReal *w[]);
typedef enum {
IGA_BASIS_BSPLINE=0,
IGA_BASIS_BERNSTEIN,
IGA_BASIS_LAGRANGE,
IGA_BASIS_HIERARCHICAL
} IGABasisType;
PETSC_EXTERN const char *const IGABasisTypes[];
struct _n_IGABasis {
PetscInt refct;
/**/
IGABasisType type; /* basis type */
/**/
PetscInt nel; /* number of elements */
PetscInt nqp; /* number of quadrature points */
PetscInt nen; /* number of local basis functions */
PetscInt p,d; /* polynomial order, last derivative index */
PetscInt *offset; /* [nel] basis offset */
PetscReal *detJ; /* [nel] */
PetscReal *weight; /* [nqp] */
PetscReal *point; /* [nel][nqp] */
PetscReal *value; /* [nel][nqp][nen][d+1] */
PetscInt bnd_offset[2];
PetscReal bnd_detJ[2];
PetscReal bnd_weight[2];
PetscReal bnd_point[2];
PetscReal *bnd_value[2]; /* [nen][d+1] */
};
PETSC_EXTERN PetscErrorCode IGABasisCreate(IGABasis *basis);
PETSC_EXTERN PetscErrorCode IGABasisDestroy(IGABasis *basis);
PETSC_EXTERN PetscErrorCode IGABasisReset(IGABasis basis);
PETSC_EXTERN PetscErrorCode IGABasisReference(IGABasis basis);
PETSC_EXTERN PetscErrorCode IGABasisSetType(IGABasis basis,IGABasisType type);
PETSC_EXTERN PetscErrorCode IGABasisInitQuadrature (IGABasis basis,IGAAxis axis,IGARule rule,PetscInt order);
PETSC_EXTERN PetscErrorCode IGABasisInitCollocation(IGABasis basis,IGAAxis axis,PetscInt order);
/* ---------------------------------------------------------------- */
typedef PetscErrorCode (*IGAFormScalar)(IGAPoint point,const PetscScalar *U,PetscInt n,PetscScalar *S,void *ctx);
typedef PetscErrorCode (*IGAFormVector)(IGAPoint point,PetscScalar *F,void *ctx);
typedef PetscErrorCode (*IGAFormMatrix)(IGAPoint point,PetscScalar *K,void *ctx);
typedef PetscErrorCode (*IGAFormSystem)(IGAPoint point,PetscScalar *K,PetscScalar *F,void *ctx);
typedef PetscErrorCode (*IGAFormFunction)(IGAPoint point,const PetscScalar *U,PetscScalar *F,void *ctx);
typedef PetscErrorCode (*IGAFormJacobian)(IGAPoint point,const PetscScalar *U,PetscScalar *J,void *ctx);
typedef PetscErrorCode (*IGAFormIFunction)(IGAPoint point,PetscReal dt,
PetscReal a,const PetscScalar *V,
PetscReal t,const PetscScalar *U,
PetscScalar *F,void *ctx);
typedef PetscErrorCode (*IGAFormIJacobian)(IGAPoint point,PetscReal dt,
PetscReal a,const PetscScalar *V,
PetscReal t,const PetscScalar *U,
PetscScalar *J,void *ctx);
typedef PetscErrorCode (*IGAFormIFunction2)(IGAPoint point,PetscReal dt,
PetscReal a,const PetscScalar *A,
PetscReal v,const PetscScalar *V,
PetscReal t,const PetscScalar *U,
PetscScalar *F,void *ctx);
typedef PetscErrorCode (*IGAFormIJacobian2)(IGAPoint point,PetscReal dt,
PetscReal a,const PetscScalar *A,
PetscReal v,const PetscScalar *V,
PetscReal t,const PetscScalar *U,
PetscScalar *J,void *ctx);
typedef PetscErrorCode (*IGAFormIEFunction)(IGAPoint point,PetscReal dt,
PetscReal a,const PetscScalar *V,
PetscReal t,const PetscScalar *U,
PetscReal t0,const PetscScalar *U0,
PetscScalar *F,void *ctx);
typedef PetscErrorCode (*IGAFormIEJacobian)(IGAPoint point,PetscReal dt,
PetscReal a,const PetscScalar *V,
PetscReal t,const PetscScalar *U,
PetscReal t0,const PetscScalar *U0,
PetscScalar *J,void *ctx);
typedef PetscErrorCode (*IGAFormRHSFunction)(IGAPoint point,PetscReal dt,
PetscReal t,const PetscScalar *U,
PetscScalar *F,void *ctx);
typedef PetscErrorCode (*IGAFormRHSJacobian)(IGAPoint point,PetscReal dt,
PetscReal t,const PetscScalar *U,
PetscScalar *J,void *ctx);
typedef struct _IGAFormBC *IGAFormBC;
struct _IGAFormBC {
PetscInt count;
PetscInt field[64];
PetscScalar value[64];
};
typedef struct _IGAFormOps *IGAFormOps;
struct _IGAFormOps {
/**/
IGAFormVector Vector;
void *VecCtx;
IGAFormMatrix Matrix;
void *MatCtx;
IGAFormSystem System;
void *SysCtx;
/**/
IGAFormFunction Function;
void *FunCtx;
IGAFormJacobian Jacobian;
void *JacCtx;
/**/
IGAFormIFunction IFunction;
IGAFormIFunction2 IFunction2;
void *IFunCtx;
IGAFormIJacobian IJacobian;
IGAFormIJacobian2 IJacobian2;
void *IJacCtx;
/**/
IGAFormIEFunction IEFunction;
void *IEFunCtx;
IGAFormIEJacobian IEJacobian;
void *IEJacCtx;
/**/
IGAFormRHSFunction RHSFunction;
void *RHSFunCtx;
IGAFormRHSJacobian RHSJacobian;
void *RHSJacCtx;
};
struct _n_IGAForm {
PetscInt refct;
/**/
IGAFormOps ops;
PetscInt dof;
IGAFormBC value[3][2];
IGAFormBC load [3][2];
PetscBool visit[3][2];
};
PETSC_EXTERN PetscErrorCode IGAGetForm(IGA iga,IGAForm *form);
PETSC_EXTERN PetscErrorCode IGASetForm(IGA iga,IGAForm form);
PETSC_EXTERN PetscErrorCode IGAFormCreate(IGAForm *form);
PETSC_EXTERN PetscErrorCode IGAFormDestroy(IGAForm *form);
PETSC_EXTERN PetscErrorCode IGAFormReset(IGAForm form);
PETSC_EXTERN PetscErrorCode IGAFormReference(IGAForm form);
PETSC_EXTERN PetscErrorCode IGAFormSetBoundaryValue(IGAForm form,PetscInt axis,PetscInt side,PetscInt field,PetscScalar value);
PETSC_EXTERN PetscErrorCode IGAFormSetBoundaryLoad (IGAForm form,PetscInt axis,PetscInt side,PetscInt field,PetscScalar value);
PETSC_EXTERN PetscErrorCode IGAFormSetBoundaryForm (IGAForm form,PetscInt axis,PetscInt side,PetscBool flag);
PETSC_EXTERN PetscErrorCode IGAFormClearBoundary (IGAForm form,PetscInt axis,PetscInt side);
PETSC_EXTERN PetscErrorCode IGAFormSetVector (IGAForm form,IGAFormVector Vector, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetMatrix (IGAForm form,IGAFormMatrix Matrix, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetSystem (IGAForm form,IGAFormSystem System, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetFunction (IGAForm form,IGAFormFunction Function, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetJacobian (IGAForm form,IGAFormJacobian Jacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetIFunction (IGAForm form,IGAFormIFunction IFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetIJacobian (IGAForm form,IGAFormIJacobian IJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetIFunction2 (IGAForm form,IGAFormIFunction2 IFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetIJacobian2 (IGAForm form,IGAFormIJacobian2 IJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetIEFunction (IGAForm form,IGAFormIEFunction IEFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetIEJacobian (IGAForm form,IGAFormIEJacobian IEJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetRHSFunction(IGAForm form,IGAFormRHSFunction RHSFunction,void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetRHSJacobian(IGAForm form,IGAFormRHSJacobian RHSJacobian,void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFixTable(IGA iga,Vec table);
PETSC_EXTERN PetscErrorCode IGASetBoundaryValue(IGA iga,PetscInt axis,PetscInt side,PetscInt field,PetscScalar value);
PETSC_EXTERN PetscErrorCode IGASetBoundaryLoad (IGA iga,PetscInt axis,PetscInt side,PetscInt field,PetscScalar value);
PETSC_EXTERN PetscErrorCode IGASetBoundaryForm (IGA iga,PetscInt axis,PetscInt side,PetscBool flag);
PETSC_EXTERN PetscErrorCode IGASetFormVector (IGA iga,IGAFormVector Vector, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormMatrix (IGA iga,IGAFormMatrix Matrix, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormSystem (IGA iga,IGAFormSystem System, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormFunction (IGA iga,IGAFormFunction Function, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormJacobian (IGA iga,IGAFormJacobian Jacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormIFunction (IGA iga,IGAFormIFunction IFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormIJacobian (IGA iga,IGAFormIJacobian IJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormIFunction2 (IGA iga,IGAFormIFunction2 IFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormIJacobian2 (IGA iga,IGAFormIJacobian2 IJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormIEFunction (IGA iga,IGAFormIEFunction IEFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormIEJacobian (IGA iga,IGAFormIEJacobian IEJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormRHSFunction(IGA iga,IGAFormRHSFunction RHSFunction,void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormRHSJacobian(IGA iga,IGAFormRHSJacobian RHSJacobian,void *ctx);
/* ---------------------------------------------------------------- */
typedef struct _IGAOps *IGAOps;
struct _IGAOps {
PetscErrorCode (*create)(IGA);
PetscErrorCode (*destroy)(IGA);
PetscErrorCode (*view)(IGA);
PetscErrorCode (*setup)(IGA);
PetscErrorCode (*setfromoptions)(IGA);
};
struct _p_IGA {
PETSCHEADER(struct _IGAOps);
PetscBool setup;
PetscInt setupstage;
PetscBool collocation;
VecType vectype;
MatType mattype;
char **fieldname;
PetscInt dim; /* parametric dimension of the function space*/
PetscInt dof; /* number of degrees of freedom per node */
PetscInt order; /* maximum derivative order */
IGAAxis axis[3];
IGARule rule[3];
IGABasis basis[3];
IGAForm form;
IGAElement iterator;
PetscBool rational;
PetscInt geometry;
PetscInt property;
PetscBool fixtable;
PetscReal *rationalW;
PetscReal *geometryX;
PetscScalar *propertyA;
PetscScalar *fixtableU;
PetscInt proc_sizes[3];
PetscInt proc_ranks[3];
PetscInt elem_sizes[3];
PetscInt elem_start[3];
PetscInt elem_width[3];
PetscInt geom_sizes[3];
PetscInt geom_lstart[3];
PetscInt geom_lwidth[3];
PetscInt geom_gstart[3];
PetscInt geom_gwidth[3];
PetscInt node_sizes[3];
PetscInt node_lstart[3];
PetscInt node_lwidth[3];
PetscInt node_gstart[3];
PetscInt node_gwidth[3];
AO ao;
LGMap lgmap;
PetscLayout map;
VecScatter g2l,l2g,l2l;
PetscInt nwork;
Vec vwork[16];
Vec natural;
VecScatter n2g,g2n;
DM elem_dm;
DM geom_dm;
DM node_dm;
DM draw_dm;
};
PETSC_EXTERN PetscClassId IGA_CLASSID;
#define IGA_FILE_CLASSID 1211299
PETSC_EXTERN PetscErrorCode IGAInitializePackage(void);
PETSC_EXTERN PetscErrorCode IGAFinalizePackage(void);
PETSC_EXTERN PetscErrorCode IGARegisterAll(void);
PETSC_EXTERN PetscErrorCode IGACreate(MPI_Comm comm,IGA *iga);
PETSC_EXTERN PetscErrorCode IGADestroy(IGA *iga);
PETSC_EXTERN PetscErrorCode IGAReset(IGA iga);
PETSC_EXTERN PetscErrorCode IGASetUp(IGA iga);
PETSC_EXTERN PetscErrorCode IGAView(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGAGetOptionsPrefix(IGA iga,const char *prefix[]);
PETSC_EXTERN PetscErrorCode IGASetOptionsPrefix(IGA iga,const char prefix[]);
PETSC_EXTERN PetscErrorCode IGAPrependOptionsPrefix(IGA iga,const char prefix[]);
PETSC_EXTERN PetscErrorCode IGAAppendOptionsPrefix(IGA iga,const char prefix[]);
PETSC_EXTERN PetscErrorCode IGASetFromOptions(IGA iga);
PETSC_EXTERN PetscErrorCode IGAViewFromOptions(IGA iga,const char prefix[],const char option[]);
PETSC_EXTERN PetscErrorCode IGAOptionsAlias(const char name[],const char defval[],const char alias[]);
PETSC_EXTERN PetscErrorCode IGALoad(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGASave(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGARead(IGA iga,const char filename[]);
PETSC_EXTERN PetscErrorCode IGAWrite(IGA iga,const char filename[]);
PETSC_EXTERN PetscErrorCode IGASetGeometryDim(IGA iga,PetscInt dim);
PETSC_EXTERN PetscErrorCode IGAGetGeometryDim(IGA iga,PetscInt *dim);
PETSC_EXTERN PetscErrorCode IGALoadGeometry(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGASaveGeometry(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGASetPropertyDim(IGA iga,PetscInt dim);
PETSC_EXTERN PetscErrorCode IGAGetPropertyDim(IGA iga,PetscInt *dim);
PETSC_EXTERN PetscErrorCode IGALoadProperty(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGASaveProperty(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGALoadVec(IGA iga,Vec vec,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGASaveVec(IGA iga,Vec vec,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGADrawVec(IGA iga,Vec vec,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGAReadVec(IGA iga,Vec vec,const char filename[]);
PETSC_EXTERN PetscErrorCode IGAWriteVec(IGA iga,Vec vec,const char filename[]);
PETSC_EXTERN PetscErrorCode IGASetDim(IGA iga,PetscInt dim);
PETSC_EXTERN PetscErrorCode IGAGetDim(IGA iga,PetscInt *dim);
PETSC_EXTERN PetscErrorCode IGASetDof(IGA iga,PetscInt dof);
PETSC_EXTERN PetscErrorCode IGAGetDof(IGA iga,PetscInt *dof);
PETSC_EXTERN PetscErrorCode IGASetFieldName(IGA iga,PetscInt field,const char name[]);
PETSC_EXTERN PetscErrorCode IGAGetFieldName(IGA iga,PetscInt field,const char *name[]);
PETSC_EXTERN PetscErrorCode IGASetOrder(IGA iga,PetscInt order);
PETSC_EXTERN PetscErrorCode IGAGetOrder(IGA iga,PetscInt *order);
PETSC_EXTERN PetscErrorCode IGASetProcessors(IGA iga,PetscInt i,PetscInt processors);
PETSC_EXTERN PetscErrorCode IGASetBasisType(IGA iga,PetscInt i,IGABasisType type);
PETSC_EXTERN PetscErrorCode IGASetQuadrature(IGA iga,PetscInt i,PetscInt q);
PETSC_EXTERN PetscErrorCode IGASetUseCollocation(IGA iga,PetscBool collocation);
PETSC_EXTERN PetscErrorCode IGAGetComm(IGA iga,MPI_Comm *comm);
PETSC_EXTERN PetscErrorCode IGAGetAxis(IGA iga,PetscInt i,IGAAxis *axis);
PETSC_EXTERN PetscErrorCode IGAGetRule(IGA iga,PetscInt i,IGARule *rule);
PETSC_EXTERN PetscErrorCode IGAGetBasis(IGA iga,PetscInt i,IGABasis *basis);
PETSC_EXTERN PetscErrorCode IGACreateDMDA(IGA iga,PetscInt bs,
const PetscInt gsizes[],
const PetscInt lsizes[],
const PetscBool periodic[],
PetscBool stencil_box,
PetscInt stencil_width,
DM *dm);
PETSC_EXTERN PetscErrorCode IGACreateElemDM(IGA iga,PetscInt bs,DM *dm);
PETSC_EXTERN PetscErrorCode IGACreateGeomDM(IGA iga,PetscInt bs,DM *dm);
PETSC_EXTERN PetscErrorCode IGACreateNodeDM(IGA iga,PetscInt bs,DM *dm);
PETSC_EXTERN PetscErrorCode IGAGetElemDM(IGA iga,DM *dm);
PETSC_EXTERN PetscErrorCode IGAGetGeomDM(IGA iga,DM *dm);
PETSC_EXTERN PetscErrorCode IGAGetNodeDM(IGA iga,DM *dm);
PETSC_EXTERN PetscErrorCode IGASetVecType(IGA iga,const VecType vectype);
PETSC_EXTERN PetscErrorCode IGASetMatType(IGA iga,const MatType mattype);
PETSC_EXTERN PetscErrorCode IGACreateVec(IGA iga,Vec *vec);
PETSC_EXTERN PetscErrorCode IGACreateMat(IGA iga,Mat *mat);
PETSC_EXTERN PetscErrorCode IGACreateCoordinates(IGA iga,Vec *coords);
PETSC_EXTERN PetscErrorCode IGACreateRigidBody(IGA iga,MatNullSpace *nsp);
PETSC_EXTERN PetscErrorCode IGACreateLocalVec(IGA iga, Vec *lvec);
PETSC_EXTERN PetscErrorCode IGAGetLocalVec(IGA iga,Vec *lvec);
PETSC_EXTERN PetscErrorCode IGARestoreLocalVec(IGA iga,Vec *lvec);
PETSC_EXTERN PetscErrorCode IGAGlobalToLocalBegin(IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGAGlobalToLocalEnd (IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGAGlobalToLocal (IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToGlobalBegin(IGA iga,Vec lvec,Vec gvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToGlobalEnd (IGA iga,Vec lvec,Vec gvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToGlobal (IGA iga,Vec lvec,Vec gvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToLocalBegin (IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToLocalEnd (IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToLocal (IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGAGetNaturalVec(IGA iga,Vec *nvec);
PETSC_EXTERN PetscErrorCode IGANaturalToGlobal(IGA iga,Vec nvec,Vec gvec);
PETSC_EXTERN PetscErrorCode IGAGlobalToNatural(IGA iga,Vec gvec,Vec nvec);
PETSC_EXTERN PetscErrorCode IGAGetLocalVecArray(IGA iga,Vec gvec,Vec *lvec,const PetscScalar *array[]);
PETSC_EXTERN PetscErrorCode IGARestoreLocalVecArray(IGA iga,Vec gvec,Vec *lvec,const PetscScalar *array[]);
PETSC_EXTERN PetscErrorCode IGAClone(IGA iga,PetscInt dof,IGA *newiga);
#undef DMIGA
#define DMIGA "iga"
PETSC_EXTERN PetscErrorCode IGACreateWrapperDM(IGA iga,DM *dm);
PETSC_EXTERN PetscErrorCode DMIGASetIGA(DM dm,IGA iga);
PETSC_EXTERN PetscErrorCode DMIGAGetIGA(DM dm,IGA *iga);
/* ---------------------------------------------------------------- */
struct _n_IGAElement {
PetscInt refct;
/**/
PetscInt start[3];
PetscInt width[3];
PetscInt sizes[3];
PetscInt ID[3];
/**/
PetscBool atboundary;
PetscInt boundary_id;
/**/
PetscInt count;
PetscInt index;
/**/
PetscInt neq;
PetscInt nen;
PetscInt dof;
PetscInt dim;
PetscInt nsd;
PetscInt npd;
PetscInt *mapping; /*[nen] */
PetscInt *rowmap; /*[neq] */
PetscInt *colmap; /*[nen] */
PetscBool rational;
PetscReal *rationalW; /*[nen] */
PetscBool geometry;
PetscReal *geometryX; /*[nen][nsd] */
PetscBool property;
PetscScalar *propertyA; /*[nen][npd] */
PetscInt nqp;
PetscReal *point; /* [nqp][dim] */
PetscReal *weight; /* [nqp] */
PetscReal *detJac; /* [nqp] */
PetscReal *basis[4]; /*0: [nqp][nen] */
/*1: [nqp][nen][dim] */
/*2: [nqp][nen][dim][dim] */
/*3: [nqp][nen][dim][dim][dim] */
PetscReal *detX; /* [nqp] */
PetscReal *gradX[2]; /*0: [nqp][nsd][dim] */
/*1: [nqp][dim][nsd] */
PetscReal *hessX[2]; /*0: [nqp][nsd][dim][dim] */
/*1: [nqp][dim][nsd][nsd] */
PetscReal *der3X[2]; /*0: [nqp][nsd][dim][dim][dim] */
/*1: [nqp][dim][nsd][nsd][nsd] */
PetscReal *detS; /* [nqp] */
PetscReal *normal; /* [nqp][dim] */
PetscReal *shape[4]; /*0: [nqp][nen] */
/*1: [nqp][nen][nsd] */
/*2: [nqp][nen][nsd][nsd] */
/*3: [nqp][nen][nsd][nsd][nsd] */
IGA parent;
IGAPoint iterator;
PetscBool collocation;
PetscInt nfix;
PetscInt *ifix;
PetscScalar *vfix;
PetscScalar *ufix;
PetscInt nflux;
PetscInt *iflux;
PetscScalar *vflux;
PetscInt nval;
PetscScalar *wval[8];
PetscInt nvec;
PetscScalar *wvec[8];
PetscInt nmat;
PetscScalar *wmat[4];
};
PETSC_EXTERN PetscErrorCode IGAElementCreate(IGAElement *element);
PETSC_EXTERN PetscErrorCode IGAElementDestroy(IGAElement *element);
PETSC_EXTERN PetscErrorCode IGAElementReference(IGAElement element);
PETSC_EXTERN PetscErrorCode IGAElementReset(IGAElement element);
PETSC_EXTERN PetscErrorCode IGAElementInit(IGAElement element,IGA iga);
PETSC_EXTERN PetscErrorCode IGAGetElement(IGA iga,IGAElement *element);
PETSC_EXTERN PetscErrorCode IGABeginElement(IGA iga,IGAElement *element);
PETSC_EXTERN PetscBool IGANextElement(IGA iga,IGAElement element);
PETSC_EXTERN PetscErrorCode IGAEndElement(IGA iga,IGAElement *element);
PETSC_EXTERN PetscBool IGAElementNextForm(IGAElement element,PetscBool visit[][2]);
PETSC_EXTERN PetscErrorCode IGAElementGetPoint(IGAElement element,IGAPoint *point);
PETSC_EXTERN PetscErrorCode IGAElementBeginPoint(IGAElement element,IGAPoint *point);
PETSC_EXTERN PetscBool IGAElementNextPoint(IGAElement element,IGAPoint point);
PETSC_EXTERN PetscErrorCode IGAElementEndPoint(IGAElement element,IGAPoint *point);
PETSC_EXTERN PetscErrorCode IGAElementBuildClosure(IGAElement element);
PETSC_EXTERN PetscErrorCode IGAElementBuildQuadrature(IGAElement element);
PETSC_EXTERN PetscErrorCode IGAElementBuildShapeFuns (IGAElement element);
PETSC_EXTERN PetscErrorCode IGAElementBuildQuadratureAtBoundary(IGAElement element,PetscInt dir,PetscInt side);
PETSC_EXTERN PetscErrorCode IGAElementBuildShapeFunsAtBoundary (IGAElement element,PetscInt dir,PetscInt side);
PETSC_EXTERN PetscErrorCode IGAElementGetParent(IGAElement element,IGA *parent);
PETSC_EXTERN PetscErrorCode IGAElementGetIndex(IGAElement element,PetscInt *index);
PETSC_EXTERN PetscErrorCode IGAElementGetCount(IGAElement element,PetscInt *count);
PETSC_EXTERN PetscErrorCode IGAElementGetSizes(IGAElement element,PetscInt *neq,PetscInt *nen,PetscInt *dof);
PETSC_EXTERN PetscErrorCode IGAElementGetClosure(IGAElement element,PetscInt *nen,const PetscInt *mapping[]);
PETSC_EXTERN PetscErrorCode IGAElementGetIndices(IGAElement element,
PetscInt *neq,const PetscInt *rowmap[],
PetscInt *nen,const PetscInt *colmap[]);
PETSC_EXTERN PetscErrorCode IGAElementGetWorkVec(IGAElement element,PetscScalar *V[]);
PETSC_EXTERN PetscErrorCode IGAElementGetWorkMat(IGAElement element,PetscScalar *M[]);
PETSC_EXTERN PetscErrorCode IGAElementGetValues(IGAElement element,const PetscScalar arrayU[],PetscScalar *U[]);
PETSC_EXTERN PetscErrorCode IGAElementBuildFix(IGAElement element);
PETSC_EXTERN PetscErrorCode IGAElementFixValues(IGAElement element,PetscScalar U[]);
PETSC_EXTERN PetscErrorCode IGAElementFixSystem(IGAElement element,PetscScalar K[],PetscScalar F[]);
PETSC_EXTERN PetscErrorCode IGAElementFixFunction(IGAElement element,PetscScalar F[]);
PETSC_EXTERN PetscErrorCode IGAElementFixJacobian(IGAElement element,PetscScalar J[]);
PETSC_EXTERN PetscErrorCode IGAElementAssembleVec(IGAElement element,const PetscScalar F[],Vec vec);
PETSC_EXTERN PetscErrorCode IGAElementAssembleMat(IGAElement element,const PetscScalar K[],Mat mat);
/* ---------------------------------------------------------------- */
struct _n_IGAPoint {
PetscInt refct;
/**/
PetscBool atboundary;
PetscInt boundary_id;
/**/
PetscInt count;
PetscInt index;
/**/
PetscInt neq;
PetscInt nen;
PetscInt dof;
PetscInt dim;
PetscInt nsd;
PetscInt npd;
PetscReal *rational;/* [nen] */
PetscReal *geometry;/* [nen][nsd] */
PetscScalar *property;/* [nen][npd] */
PetscReal *point; /* [dim] */
PetscReal *weight; /* [1] */
PetscReal *detJac; /* [1] */
PetscReal *basis[4]; /*0: [nen] */
/*1: [nen][dim] */
/*2: [nen][dim][dim] */
/*3: [nen][dim][dim][dim] */
PetscReal *detX; /* [1] */
PetscReal *gradX[2]; /*0: [nsd][dim] */
/*1: [dim][nsd] */
PetscReal *hessX[2]; /*0: [nsd][dim][dim] */
/*1: [dim][nsd][nsd] */
PetscReal *der3X[2]; /*0: [nsd][dim][dim][dim] */
/*1: [dim][nsd][nsd][nsd] */
PetscReal *detS; /* [1] */
PetscReal *normal; /* [dim] */
PetscReal *shape[4]; /*0: [nen] */
/*1: [nen][nsd] */
/*2: [nen][nsd][nsd] */
/*3: [nen][nsd][nsd][nsd] */
IGAElement parent;
PetscInt nvec;
PetscScalar *wvec[8];
PetscInt nmat;
PetscScalar *wmat[4];
};
PETSC_EXTERN PetscErrorCode IGAPointCreate(IGAPoint *point);
PETSC_EXTERN PetscErrorCode IGAPointDestroy(IGAPoint *point);
PETSC_EXTERN PetscErrorCode IGAPointReference(IGAPoint point);
PETSC_EXTERN PetscErrorCode IGAPointReset(IGAPoint point);
PETSC_EXTERN PetscErrorCode IGAPointInit(IGAPoint point,IGAElement element);
PETSC_EXTERN PetscErrorCode IGAPointGetParent(IGAPoint point,IGAElement *element);
PETSC_EXTERN PetscErrorCode IGAPointGetIndex(IGAPoint point,PetscInt *index);
PETSC_EXTERN PetscErrorCode IGAPointGetCount(IGAPoint point,PetscInt *count);
PETSC_EXTERN PetscErrorCode IGAPointAtBoundary(IGAPoint point,PetscInt *axis,PetscInt *side);
PETSC_EXTERN PetscErrorCode IGAPointGetSizes(IGAPoint point,PetscInt *neq,PetscInt *nen,PetscInt *dof);
PETSC_EXTERN PetscErrorCode IGAPointGetDims(IGAPoint point,PetscInt *dim,PetscInt *nsd,PetscInt *npd);
PETSC_EXTERN PetscErrorCode IGAPointGetQuadrature(IGAPoint point,PetscReal *weigth,PetscReal *detJac);
PETSC_EXTERN PetscErrorCode IGAPointGetBasisFuns(IGAPoint point,PetscInt der,const PetscReal *basisfuns[]);
PETSC_EXTERN PetscErrorCode IGAPointGetShapeFuns(IGAPoint point,PetscInt der,const PetscReal *shapefuns[]);
PETSC_EXTERN PetscErrorCode IGAPointInterpolate(IGAPoint point,PetscInt ider,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointFormPoint(IGAPoint p,PetscReal x[]);
PETSC_EXTERN PetscErrorCode IGAPointFormGeomMap(IGAPoint p,PetscReal x[]);
PETSC_EXTERN PetscErrorCode IGAPointFormGradGeomMap(IGAPoint p,PetscReal F[]);
PETSC_EXTERN PetscErrorCode IGAPointFormInvGradGeomMap(IGAPoint p,PetscReal G[]);
PETSC_EXTERN PetscErrorCode IGAPointFormValue(IGAPoint p,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointFormGrad (IGAPoint p,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointFormHess (IGAPoint p,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointFormDel2 (IGAPoint p,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointFormDer3 (IGAPoint p,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointGetWorkVec(IGAPoint point,PetscScalar *V[]);
PETSC_EXTERN PetscErrorCode IGAPointGetWorkMat(IGAPoint point,PetscScalar *M[]);
PETSC_EXTERN PetscErrorCode IGAPointAddArray(IGAPoint point,PetscInt n,const PetscScalar a[],PetscScalar A[]);
PETSC_EXTERN PetscErrorCode IGAPointAddVec(IGAPoint point,const PetscScalar f[],PetscScalar F[]);
PETSC_EXTERN PetscErrorCode IGAPointAddMat(IGAPoint point,const PetscScalar k[],PetscScalar K[]);
/* ---------------------------------------------------------------- */
PETSC_EXTERN PetscLogEvent IGA_FormScalar;
PETSC_EXTERN PetscLogEvent IGA_FormVector;
PETSC_EXTERN PetscLogEvent IGA_FormMatrix;
PETSC_EXTERN PetscLogEvent IGA_FormSystem;
PETSC_EXTERN PetscLogEvent IGA_FormFunction;
PETSC_EXTERN PetscLogEvent IGA_FormJacobian;
PETSC_EXTERN PetscLogEvent IGA_FormIFunction;
PETSC_EXTERN PetscLogEvent IGA_FormIJacobian;
PETSC_EXTERN PetscErrorCode IGAComputeScalar(IGA iga,Vec U,
PetscInt n,PetscScalar S[],
IGAFormScalar Scalar,void *ctx);
PETSC_EXTERN PetscErrorCode IGAComputeScalarCustom(IGA iga,Vec U,
PetscInt n,PetscScalar S[],
IGAFormScalar Scalar,void *ctx,
PetscBool fix);
#define PCIGAEBE "igaebe"
#define PCIGABBB "igabbb"
PETSC_EXTERN PetscErrorCode IGACreateKSP(IGA iga,KSP *ksp);
PETSC_EXTERN PetscErrorCode IGAComputeVector(IGA iga,Vec B);
PETSC_EXTERN PetscErrorCode IGAComputeMatrix(IGA iga,Mat A);
PETSC_EXTERN PetscErrorCode IGAComputeSystem(IGA iga,Mat A,Vec B);
PETSC_EXTERN PetscErrorCode IGACreateSNES(IGA iga,SNES *snes);
PETSC_EXTERN PetscErrorCode IGAComputeFunction(IGA iga,Vec U,Vec F);
PETSC_EXTERN PetscErrorCode IGAComputeJacobian(IGA iga,Vec U,Mat J);
PETSC_EXTERN PetscErrorCode IGACreateTS(IGA iga,TS *ts);
PETSC_EXTERN PetscErrorCode IGAComputeIFunction(IGA iga,PetscReal dt,
PetscReal a,Vec V,
PetscReal t,Vec U,
Vec F);
PETSC_EXTERN PetscErrorCode IGAComputeIJacobian(IGA iga,PetscReal dt,
PetscReal a,Vec V,
PetscReal t,Vec U,
Mat J);
PETSC_EXTERN PetscErrorCode IGAComputeIEFunction(IGA iga,PetscReal dt,
PetscReal a, Vec V,
PetscReal t, Vec U,
PetscReal t0,Vec U0,
Vec F);
PETSC_EXTERN PetscErrorCode IGAComputeIEJacobian(IGA iga,PetscReal dt,
PetscReal a, Vec V,
PetscReal t, Vec U,
PetscReal t0,Vec U0,
Mat J);
PETSC_EXTERN PetscErrorCode IGAComputeRHSFunction(IGA iga,PetscReal dt,
PetscReal t,Vec U,
Vec F);
PETSC_EXTERN PetscErrorCode IGAComputeRHSJacobian(IGA iga,PetscReal dt,
PetscReal t,Vec U,
Mat J);
PETSC_EXTERN PetscErrorCode IGACreateTS2(IGA iga, TS *ts);
PETSC_EXTERN PetscErrorCode IGAComputeIFunction2(IGA iga,PetscReal dt,
PetscReal a,Vec vecA,
PetscReal v,Vec vecV,
PetscReal t,Vec vecU,
Vec vecF);
PETSC_EXTERN PetscErrorCode IGAComputeIJacobian2(IGA iga,PetscReal dt,
PetscReal a,Vec vecA,
PetscReal v,Vec vecV,
PetscReal t,Vec vecU,
Mat matJ);
/* ---------------------------------------------------------------- */
PETSC_EXTERN PetscErrorCode IGAPreparePCBDDC(IGA iga,PC pc);
PETSC_EXTERN PetscErrorCode IGASetOptionsHandlerPC(PC pc);
PETSC_EXTERN PetscErrorCode IGASetOptionsHandlerKSP(KSP ksp);
PETSC_EXTERN PetscErrorCode IGASetOptionsHandlerSNES(SNES snes);
PETSC_EXTERN PetscErrorCode IGASetOptionsHandlerTS(TS ts);
/* ---------------------------------------------------------------- */
#if defined(PETSC_USE_DEBUG)
#define IGACheckSetUp(iga,arg) do { \
if (PetscUnlikely(!(iga)->setup)) \
SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, \
"Must call IGASetUp() on argument %D \"%s\" before %s()", \
(arg),#iga,PETSC_FUNCTION_NAME); \
} while (0)
#define IGACheckSetUpStage(iga,arg,stg) do { \
if (PetscUnlikely((iga)->setupstage<(stg))) IGACheckSetUp(iga,arg); \
} while (0)
#else
#define IGACheckSetUp(iga,arg) do {} while (0)
#define IGACheckSetUpStage(iga,arg,stg) do {} while (0)
#endif
#define IGACheckSetUpStage1(iga,arg) IGACheckSetUpStage(iga,arg,1)
#define IGACheckSetUpStage2(iga,arg) IGACheckSetUpStage(iga,arg,2)
#if defined(PETSC_USE_DEBUG)
#define IGACheckFormOp(iga,arg,FormOp) do { \
if (!iga->form->ops->FormOp) \
SETERRQ4(((PetscObject)iga)->comm,PETSC_ERR_USER, \
"Must call IGASetForm%s() " \
"on argument %D \"%s\" before %s()", \
#FormOp,(arg),#iga,PETSC_FUNCTION_NAME); \
} while (0)
#else
#define IGACheckFormOp(iga,arg,FormOp) do {} while (0)
#endif
/* ---------------------------------------------------------------- */
#ifndef PetscValidRealPointer
#define PetscValidRealPointer PetscValidDoublePointer
#endif
#ifndef PetscMalloc1
#define PetscMalloc1(m1,r1) \
PetscMalloc((m1)*sizeof(**(r1)),r1)
#endif
#ifndef PetscCalloc1
#define PetscCalloc1(m1,r1) \
(PetscMalloc1((m1),r1) || PetscMemzero(*(r1),(m1)*sizeof(**(r1))))
#endif
/* ---------------------------------------------------------------- */
#if PETSC_VERSION_(3,3,0)
#undef PETSC_VERSION_LT
#define PETSC_VERSION_LT(MAJOR,MINOR,SUBMINOR) \
(PETSC_VERSION_RELEASE == 1 && \
(PETSC_VERSION_MAJOR < (MAJOR) || \
(PETSC_VERSION_MAJOR == (MAJOR) && \
(PETSC_VERSION_MINOR < (MINOR) || \
(PETSC_VERSION_MINOR == (MINOR) && \
(PETSC_VERSION_SUBMINOR < (SUBMINOR)))))))
#undef PETSC_VERSION_LE
#define PETSC_VERSION_LE(MAJOR,MINOR,SUBMINOR) \
(PETSC_VERSION_LT(MAJOR,MINOR,SUBMINOR) || \
PETSC_VERSION_(MAJOR,MINOR,SUBMINOR))
#undef PETSC_VERSION_GE
#define PETSC_VERSION_GE(MAJOR,MINOR,SUBMINOR) \
(0 == PETSC_VERSION_LT(MAJOR,MINOR,SUBMINOR))
#undef PETSC_VERSION_GT
#define PETSC_VERSION_GT(MAJOR,MINOR,SUBMINOR) \
(0 == PETSC_VERSION_LE(MAJOR,MINOR,SUBMINOR))
#endif
/* ---------------------------------------------------------------- */
#endif/*PETIGA_H*/
| {
"alphanum_fraction": 0.6786550953,
"avg_line_length": 46.2610837438,
"ext": "h",
"hexsha": "23c32b7977eac0196409af618b23ca502ca4faa1",
"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": "include/petiga.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": "include/petiga.h",
"max_line_length": 127,
"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": "include/petiga.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": 10157,
"size": 37564
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include <gsl/gsl>
#include "core/framework/tensor.h"
#include "core/util/math_cpuonly.h"
namespace onnxruntime {
template <typename T>
auto EigenMap(Tensor& t) -> EigenVectorMap<T> {
return EigenVectorMap<T>(t.template MutableData<T>(), gsl::narrow<ptrdiff_t>(t.Shape().Size()));
}
template <typename T>
auto EigenMap(const Tensor& t) -> ConstEigenVectorMap<T> {
return ConstEigenVectorMap<T>(t.template Data<T>(), gsl::narrow<ptrdiff_t>(t.Shape().Size()));
}
} // namespace onnxruntime
| {
"alphanum_fraction": 0.724137931,
"avg_line_length": 25.375,
"ext": "h",
"hexsha": "609c2de118d637cdf9dbedf77d8b889d11b583aa",
"lang": "C",
"max_forks_count": 140,
"max_forks_repo_forks_event_max_datetime": "2019-05-06T18:02:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-12-03T21:15:28.000Z",
"max_forks_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SiriusKY/onnxruntime",
"max_forks_repo_path": "onnxruntime/core/framework/math.h",
"max_issues_count": 440,
"max_issues_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d",
"max_issues_repo_issues_event_max_datetime": "2019-05-06T20:47:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-03T21:09:56.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SiriusKY/onnxruntime",
"max_issues_repo_path": "onnxruntime/core/framework/math.h",
"max_line_length": 98,
"max_stars_count": 669,
"max_stars_repo_head_hexsha": "3c5853dcbc9d5dda2476afa8c6105802d2b8e53d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SiriusKY/onnxruntime",
"max_stars_repo_path": "onnxruntime/core/framework/math.h",
"max_stars_repo_stars_event_max_datetime": "2019-05-06T19:42:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-03T22:00:31.000Z",
"num_tokens": 154,
"size": 609
} |
/************************************************************************
* $Id$
*
* MYSTIC - Monte Carlo code for the physically correct tracing of
* photons in cloudy atmospheres.
*
* Copyright (c) 2000-2012 by Arve Kylling, Bernhard Mayer,
* Claudia Emde, Robert Buras
*
* Correspondence: bernhard.mayer@lmu.de
*
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
/*#include <values.h>*/
#include "uvspecrandom.h"
#include "wcloud3d.h"
#include "mystic.h"
#if HAVE_MYSTIC3D
#include "mystic_3d.h"
#endif
#if HAVE_ALIS
#include "alis.h"
#endif
#if HAVE_OPENGL
#include "GLmystic.h"
#endif
#include "yang56.h"
#include "sofi.h"
#include "errors.h"
#include "common_math.h"
#include "ascii.h"
#include "miecalc.h"
#include "phasetable.h"
#include "numeric.h"
#include "ambralsfor.h"
#include "ocean.h"
#include "f77-uscore.h"
#include "solver.h"
#include "rayleigh.h"
#include "locate.h"
#include "cdisort.h"
#include "allocnd.h"
#ifdef HAVE_TENSTREAM
#include "tenstream.h"
#endif
#if HAVE_LIBGSL
#include <gsl/gsl_sf.h>
#endif
#if HAVE_NETCDF4
#include <netcdf.h>
#endif
#if HAVE_VROOM
/* include vroom, and evtl. also lidar stuff */
#include "vroom.h"
#if HAVE_LIDAR
#include "lidar.h"
#endif
#endif
/* will be deleted soon */
#define CLDPRP
#ifndef PI
#define PI 3.14159265358979323846264338327
#endif
/* This is a fix needed at MIM, need to test whether this also works on DLR */
#if COMPILING_CONDOR_AT_MIM
#define fscanf __fscanf
#endif
/* for impatient users. If set, touching the file "fastexit" */
/* in the working directly will let the code end prematurely */
/* results are summarized as usual, only the number of simul */
/* ated photons is reduced */
#define ALLOW_FILE_CHECKS
/* this should probably be on for lidar, FODDIS is bad */
#undef NOFODDIS
/* experimental stuff for Lidar, not yet debugged */
#undef NEWRISQIDD
#undef NEWVISQIDD
#undef SPIKEOUT
#undef ESCAPES
#undef TIMINGS
/* absorption optical depth along path is calculated separately */
/* for different absorbers; if ONLY_TOT is true, only the total */
/* optical depth is calculated */
#define ONLY_TOT 1
/* if PRINT_PHOTON_PATH is defined, the location of the photon at */
/* the start and end of its journey as well as at each scattering */
/* event will be written to stdout. */
/*WARNING: Will produce stack overflows for very long photon paths!*/
// #define PRINT_PHOTON_PATH 1
/* similar to PRINT_PHOTON_PATH but here the local escape */
/* contributions are written to stdout. */
// #define PRINT_ESCAPE_CONTRIBUTIONS 1
/* experimental option to calculate full-sky radiances with "cone" */
/* sampling, BM 27.7.2016 */
#define NTHETA 180
#define NPHI 180
#include "raytracing.h"
/* ??? Attention, this is only to reduce noise ??? CHECK!!! */
/* ??? but it actually throws away part of the ??? */
/* ??? signal. To get correct results, set ??? */
/* ??? ACTINIC_CUTOFF to 0 ??? */
#define ACTINIC_CUTOFF 0.01
/* if MYSTIC_DEBUG is switched on, some extra tests are performed; */
/* might be useful for testing MYSTIC on new machines */
/* #define MYSTIC_DEBUG 1 */
/* angle from which on the phase function will be tabulated in high resolution */
#define MUHIGH 0.99
#include "nca.h" /* Carolin Klinger 2019 */
/* prototypes of internal functions */
static int mystic_check_consistency (sample_struct* sample,
elevation_struct* elev,
surftemp_struct* surftemp,
double delta_scaling_mucut,
double truncate,
int source,
char* umufilename,
int ipa);
static int mystic_set (/* input */
int nlyr,
int* nmomaer,
int** nthetaaer,
int source,
int absorption,
int visualize,
int* loaddata,
int nzoutorg,
float* zoutorg,
float rpv_rho0,
float rpv_k,
float rpv_theta,
float hapke_h,
float hapke_b0,
float hapke_w,
float rossli_iso,
float rossli_vol,
float rossli_geo,
float u10,
float pcl,
float xsal,
float bpdf_u10,
char* albedo_filename,
char* ambralsfilename,
char* rosslifilename,
char* alb_type_filename,
char* rpv_type_filename,
char* ambrals_type_filename,
int reflectalways,
/* throughput */
int* first,
sample_struct* sample,
albedo_struct** albedo,
float* delta_scaling_mucut,
float* truncate,
/* output */
int* aerosol_scatter_type,
long int* nphotons,
int* nzout,
float** zout,
float* rfldir,
float* rfldn,
float* flup,
float* uavgso,
float* uavgdn,
float* uavgup,
int quiet);
static int mystic_verbose (int quiet,
sample_struct* sample,
albedo_struct* albedo,
int aerosol_scatter_type,
long int nphotons,
int ipa,
double delta_scaling_mucut,
double truncate);
#ifdef ALLOW_FILE_CHECKS
static int check_premature_exit (const char* filename, sample_struct* sample);
static void check_progress (long int photoncounter, long int nphotons, sample_struct* sample, float wavelength);
#endif
#if HAVE_OPENGL
static void initialize_plot_photon_path (photon_struct* p,
sample_struct* sample,
result_struct* result,
int photoncounter,
int* plotpathcounter,
int* plotpath,
int* plotresultcounter,
int* plotresult);
#endif
static int cleanup_after_photon_journey (photon_struct* p, sample_struct* sample, result_struct* result, int n_caoth, int chouf);
static void free_mystic (result_struct* result,
atmosphere_struct* atmos,
sample_struct* sample,
float* zout,
int absorption,
int thermal_heating_method); /* **CK 2013.09.23 added thermal_heating_method */
/* static int istrue(double p); */
inline double random_tau();
static int reflection (double albedo);
static int emission (double albedo);
static void random_direction (direction* dir);
/* now elsewhere: static void new_direction (double mu, double phi, direction *dir); */
static double pv_model_weight (double* dx, double* norm, float refractive_index_pv);
static ddprofile3D* calloc_ddprofile3D (int Nz, int Nx, int Ny, int* threed);
static radiation_field* calloc_radiation_field (int Nx, int Ny, int Nd, int Nr, int Nt, int Np, int std, int cldprp);
static radiation_field_t* calloc_radiation_field_t (int Nc, int Nv, int Nx, int Ny, int Np);
static profile* calloc_profile (int ntypes, int n);
static profile3D* calloc_profile3D (int n_caoth, int* tocalloc, int Nz, int Nx, int Ny, int** threed);
static void free_profile (profile*);
static void free_profile3D (profile3D*);
static void free_ddprofile3D (ddprofile3D*);
static void free_radiation_field (radiation_field* res, int Nx, int Nr, int Nd, int Np, int std);
static int cp_1D_to_3D (profile3D* p3D, profile* p);
static void cp_optical_depth (optical_depth* dest, optical_depth* source);
static inline void mc_add_optical_depth (atmosphere_struct* atmos, photon_struct* p, double length, int calc_tauext);
static void mc_add_absorption_3D (profile3D* kabs3D,
profile* kabs,
int kc,
int ic,
int jc,
double length,
double totabs,
int std,
ddprofile3D* absorption3D,
ddprofile3D* absorption3D2,
struct tnode** wtree);
static double elevation (surface surf, double x, double y);
static int cross_bilinear (surface surf, double* a, double* b, double x0, double y0, double* solution);
static int setup_caoth3D (caoth3d_out_struct* caoth3d,
int nxcld,
int nycld,
int nzcld,
int* threed,
double dxcld,
double dycld,
float wavelength,
atmosphere_struct* atmos,
char* datapath,
int delta_scaling,
int spherical3D,
int spherical3D_scene,
double spherical3D_scene_lon_min,
double spherical3D_scene_lon_max,
double spherical3D_scene_lat_min,
double spherical3D_scene_lat_max,
float r_earth,
float sza,
int setup_tipa,
int visualize,
int sample_cldprp,
int quiet);
static int setup_thermal (float*** temper,
int temper3d,
int cldNx,
int cldNy,
int nlyr,
float wvnmlo,
float wvnmhi,
profile* kabs,
profile3D* kabs3D,
float* Z,
int source,
int absorption,
int thermal_heating_method,
profile3D** Bplanck,
double* maxemis,
double* Watm,
surftemp_struct* surftemp,
int backward,
float zstart,
int* backemis_kc,
int nlambda_abs,
float* lambda,
double*** Bplanck_spectral,
t_triangular_surface* triangular_surface,
int quiet,
long int nphotons,
sample_struct* sample); /* **CK 2013.08.27 Added nphotons and sample_struct, added cldNx and CldNy */
static int setup_albedo2D (char* albedo_filename,
char* rossli_filename,
char* spectral_albedo_filename,
char* spectral_rpv_filename,
char* spectral_ambrals_filename,
int isAmbralsFile,
atmosphere_struct* atmos,
albedo_struct* albedo,
double alb,
float* alb_type,
float* rpv_rho0,
float* rpv_k,
float* rpv_theta,
float* rpv_scale,
float* rpv_sigma,
float* rpv_t1,
float* rpv_t2,
char** surface_labels,
int surface_nlabels,
float* hapke_h,
float* hapke_b0,
float* hapke_w,
float* rossli_iso,
float* rossli_vol,
float* rossli_geo,
int rossli_hotspot,
float u10,
float pcl,
float xsal,
float uphi,
int solar_wind,
float bpdf_u10,
int polarisation,
int spherical3D,
int spherical3D_scene,
double spherical3D_scene_lon_min,
double spherical3D_scene_lon_max,
double spherical3D_scene_lat_min,
double spherical3D_scene_lat_max,
int nlambda_abs,
double* alis_albedo,
double** alis_alb_type,
int ixmin,
int ixmax,
int iymin,
int iymax,
int quiet);
static int setup_umu2D (char* umu_filename, sample_struct* sample, atmosphere_struct* atmos, int quiet);
static int setup_sample2D (atmosphere_struct* atmos,
float* zout,
int nzout,
float* sza,
float* phi0,
float* wavelength,
sample_struct* sample,
int quiet);
static int setup_mc_result (atmosphere_struct* atmos,
sample_struct* sample,
t_triangle_radiation_field* triangle_results,
result_struct* result,
int absorption,
int thermal_heating_method,
int quiet);
static int setup_Legendre_table_aerosol (double** moment, int nmom, int nphamat, double truncate, pft* phase, int quiet);
static inline double get_Lambertian_phase (double mu);
static double sc_interp_mu (double reff, phase_function_table* phase, int scaled);
static int incone (double* dx, radang rad);
static double HG (double g, double mu);
static double HG2 (double g1, double g2, double ff, double mu);
static double HGint (double g, double mu);
static double HG2int (double g1, double g2, double ff, double mu);
static void
count_photon (radiation_field* res, photon_struct* p, sample_struct* sample, double* totweight, int surfaceparallel, int incoming);
static int count_thermal_backward_photon (result_struct* result,
photon_struct* p,
atmosphere_struct* atmos,
surftemp_struct* surftemp,
sample_struct* sample,
t_triangular_surface* triangular_surface,
double btemp_plkavg,
int quiet,
int boundary);
static int count_photon_on_triangular_surface (const double weight,
const photon_struct* p,
const int incoming,
t_triangle_radiation_field* triangle_result);
static int forward2backward (atmosphere_struct* atmos,
float** zout,
int* nzout,
float* sza,
float* phi0,
sample_struct* sample,
result_struct* result,
int quiet);
static inline int perform_periodic_bc (photon_struct* p, atmosphere_struct* atmos);
static inline int perform_mirroring_bc (photon_struct* p, atmosphere_struct* atmos);
/* static photon_struct *calloc_photon (sample_struct *sample); */
/* CE: Generate photon also needs complex surface struct to calculate e.g. irradiance on triangular surface */
static int generate_photon (int source,
int photoncounter,
atmosphere_struct* atmos,
albedo_struct* albedo,
elevation_struct* elev,
sample_struct* sample,
float wvnmlo,
float wvnmhi,
float wavelength,
double sza,
double phi,
int ipa,
long int nphotons,
photon_struct** new_photon,
float refractive_index_pv);
void generate_photon_backward_photon_direction_panorama (sample_struct* sample,
photon_struct* p,
double phi,
double sza,
double cossza,
double sinsza,
double cosphi,
double sinphi);
int generate_photon_backward_vertical_position_heat (sample_struct* sample,
atmosphere_struct* atmos,
photon_struct* p,
int* hit,
long int nphotons,
int* counter1);
static photon_struct* generate_photon_backward_photon_direction (sample_struct* sample,
atmosphere_struct* atmos,
photon_struct* p,
elevation_struct* elev,
int* hit,
long int nphotons,
int* counter1,
double sza,
double phi,
double phase,
int source,
double* norm,
float refractive_index_pv);
static int generate_photon_backward_vertical_position (sample_struct* sample,
atmosphere_struct* atmos,
photon_struct* p,
int* hit,
long int nphotons,
int* counter1);
static photon_struct* generate_photon_backward (sample_struct* sample,
atmosphere_struct* atmos,
photon_struct* p,
elevation_struct* elev,
int* hit,
long int nphotons,
int* counter1,
double sza,
double phi,
double phase,
int source,
double* norm,
float refractive_index_pv);
static void hunt_modified (float* xx, int n, float x, int* jlo, int* hit);
static double slt2hrz (elevation_struct* elev, photon_struct* p, int surfaceparallel, int incoming);
static void area_average (radiation_field* res,
double*** back,
int Nx,
int Ny,
int islower,
int isupper,
int jslower,
int jsupper,
int isstep,
int jsstep,
int* ndir,
int* ndn,
int* nup,
float* edir,
float* edn,
float* eup,
float* fdir,
float* fdn,
float* fup,
int backward,
double** surface_area,
int** surface_area_counter,
int elev2D,
int surfaceparallel);
static int summarize_result (result_struct* result,
sample_struct* sample,
atmosphere_struct* atmos,
albedo_struct* albedo,
t_triangular_surface* triangular_surface,
int source,
long int mcphotons,
int mcsimulations,
double sza,
int absorption,
int write_files,
int write_output_as_netcdf,
int tenstream,
int nca, /* Carolin Klinger 2019 */
char* basename,
float* rfldir,
float* rfldn,
float* flup,
float* uavgso,
float* uavgdn,
float* uavgup,
float*** rfldir3d,
float*** rfldn3d,
float*** flup3d,
float***** fl3d_is,
float*** uavgso3d,
float*** uavgdn3d,
float*** uavgup3d,
float**** radiance3d,
float*** absback3d,
float*** abs3d,
float****** radiance3s_is,
float****** jacobian,
float*** rfldir3d_var,
float*** rfldn3d_var,
float*** flup3d_var,
float*** uavgso3d_var,
float*** uavgdn3d_var,
float*** uavgup3d_var,
float**** radiance3d_var,
float*** absback3d_var,
float*** abs3d_var,
int escape,
int elev2D,
double wavelength,
int quiet);
static int reflect (photon_struct* p,
albedo_struct* albedo,
elevation_struct* elev,
t_triangular_surface* triangular_surface,
atmosphere_struct* atmos,
sample_struct* sample,
result_struct* result,
float wvnmlo,
float wvnmhi,
float* refind,
int* mcstatus);
static double reflection_probability_tot (albedo_struct* albedo,
photon_struct* p,
double murad,
double mu1,
double phi2,
double phi1,
int ia,
int ja,
int il,
int DoLE,
float wvnmlo,
float wvnmhi,
double paw,
int spherical3D,
int spectral_is,
int nlambda,
int* status);
static int scattering (atmosphere_struct* atmos,
photon_struct* p,
sample_struct* sample,
result_struct* result,
elevation_struct* elev,
albedo_struct* albedo,
t_triangular_surface* triangular_surface,
float wvnmlo,
float wvnmhi,
float* refind,
char* datapath);
static inline int random_scatter_type (atmosphere_struct* atmos, photon_struct* p);
static int setup_mystic (caoth3d_out_struct* caoth3d,
atmosphere_struct* atmos,
result_struct* result,
albedo_struct* albedo,
surftemp_struct* surftemp,
sample_struct* sample,
float delta_scaling_mucut,
int absorption,
int thermal_heating_method,
int nlyr,
int* threed,
int n_caoth,
float** dt_s,
float** om_s,
float** g1_s,
float** g2_s,
float** f_s,
float** ds_s,
alis_struct* alis,
float rayleigh_depol,
float** re_s,
float*** temper,
int temper3d,
float* zprof,
float* sza,
float* phi0,
float sza_spher,
float phi0_spher,
int aerosol_scatter_type,
float*** momaer,
int* nmomaer,
int** nthetaaer,
float*** thetaaer,
double*** muaer,
float*** phaseaer,
int nphamataer,
float alb,
float* alb_type,
float* rpv_rho0,
float* rpv_k,
float* rpv_theta,
float* rpv_scale,
float* rpv_sigma,
float* rpv_t1,
float* rpv_t2,
float* hapke_h,
float* hapke_b0,
float* hapke_w,
float* rossli_iso,
float* rossli_vol,
float* rossli_geo,
int rossli_hotspot,
float* u10,
float* pcl,
float* xsal,
float* uphi,
int* solar_wind,
float* bpdf_u10,
int source,
float* wvnmlo,
float* wvnmhi,
float* wavelength,
float* zout,
int nzout,
int nxcld,
int nycld,
int nzcld,
double dxcld,
double dycld,
char* umufilename,
char* sunshape_filename,
char* albedo_filename,
char* ambralsfilename,
char* rosslifilename,
char* alb_type_filename,
char* rpv_type_filename,
char* ambrals_type_filename,
char** surface_labels,
int surface_nlabels,
double truncate,
int loaddata,
char* datapath,
double r_earth,
int visualize,
t_triangular_surface* triangular_surface,
t_triangle_radiation_field* triangle_results,
int quiet,
long int nphotons); /* **CK 2013.08.27 Added nphotons */
static int setup_sunshape (sample_struct* sample, char* filename, float wvnmlo, float wvnmhi);
static inline int
calc_surface_emission (albedo_struct* albedo, int source, float btemp, float* wvnmlo, float* wvnmhi, float* bplkavg, double* Wsurf);
static inline int setup_aerosol1D (pft** phase_aer,
int nlyr,
float* dtaer,
float* omaer,
float*** momaer,
int* nmomaer,
int** nthetaaer,
double*** muaer,
float*** phaseaer,
int nphamataer,
double truncate,
int quiet);
static void free_mystic_for_load (albedo_struct* albedo);
double sc_Isotropic_phi (void);
static void free_albedo (albedo_struct* albedo);
static void free_atmosphere (atmosphere_struct* atmos);
static void free_result (result_struct* result,
int thermal_heating_method, /* **CK 2013.09.23 added thermal_heating_method */
atmosphere_struct* atmos,
sample_struct* sample,
int absorption);
static int register_at_start (photon_struct* p,
sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
int source,
int absorption);
static photon_struct* create_escape_photon (photon_struct* photon, atmosphere_struct* atmos, sample_struct* sample, int id);
static int escape_probability (photon_struct* photon,
atmosphere_struct* atmos,
sample_struct* sample,
result_struct* result,
elevation_struct* elev,
t_triangular_surface* triangular_surface,
int id,
int il,
int it,
int surface,
float* refind);
static void count_escape (photon_struct* p,
sample_struct* sample,
atmosphere_struct* atmos,
radiation_field* result_alt,
int id,
int il,
int backward,
double*** result_back,
double*** result_back2,
double***** result_back_t,
double** circcontr,
jacobian_result_field* jacobian,
radiation_field_t* result_rad_t,
double tauabs,
double slant2horz,
double* totweight_spectral,
double* totweight_concentration,
double*** pathlength_per_layer_tot,
double***** pathlength_per_box_tot,
mishchenko_cb_struct* mish);
static int equal (double x, double y);
static inline void sample_coord (photon_struct* p, sample_struct* sample, int* is, int* js);
static int sample_radius (photon_struct* p, sample_struct* sample, int* ir);
static int sample_time (photon_struct* p, sample_struct* sample, int* it);
static inline void calc_normal_vector (photon_struct* p,
elevation_struct* elev,
sample_struct* sample,
atmosphere_struct* atmos,
int use_elev,
int use_sensordirection,
double* norm);
static inline void elev_coord_normal_vector (photon_struct* p, elevation_struct* elev, double* dx);
static inline void albedo_coord (photon_struct* p, albedo_struct* albedo, int* ia, int* ja);
static inline void surftemp_coord (photon_struct* p, surftemp_struct* surftemp, int* it, int* jt);
static int calculate_emission (atmosphere_struct* atmos, result_struct* result);
static int calculate_backward_emission (atmosphere_struct* atmos, sample_struct* sample, int kc, double* emis);
#if defined PRINT_PHOTON_PATH || defined PRINT_ESCAPE_CONTRIBUTIONS
static void add_to_photonpath (struct photon_path** p, double* x, double weight);
static void print_and_clear_photonpath (struct photon_path* p, char* prefix);
#endif
static int setup_profiles1D (int n_caoth,
float** dt_s,
float** om_s,
float** g1_s,
float** g2_s,
float** f_s,
float** ds_s,
float** re_s,
float* zprof,
int nlyr,
sample_struct* sample,
atmosphere_struct* atmos,
alis_struct* alis);
static int calloc_1D_atmos (atmosphere_struct* atmos, int nlyr, int n_caoth, int nlambda_abs, int nlambda_ref);
static inline double get_ksca_spectral (atmosphere_struct* atmos, photon_struct* p, int isp, int iv);
static inline double get_kabs_tot (atmosphere_struct* atmos, photon_struct* p);
static inline double get_g1 (atmosphere_struct* atmos, photon_struct* p, int isp);
static inline double get_g2 (atmosphere_struct* atmos, photon_struct* p, int isp);
static inline double get_ff (atmosphere_struct* atmos, photon_struct* p, int isp);
static inline double get_reff (atmosphere_struct* atmos, photon_struct* p, int isp);
static inline double get_dxlwc (atmosphere_struct* atmos, photon_struct* p, int isp);
static inline double get_dylwc (atmosphere_struct* atmos, photon_struct* p, int isp);
static inline double get_dzlwc (atmosphere_struct* atmos, photon_struct* p, int isp);
static inline double get_kext (atmosphere_struct* atmos, photon_struct* p);
static int stokes_vector_sca (double* stokes_vector, double* P, double* pdir_sca, double* pdir_inc, double phi_sun, double phi_det);
static int get_phase_matrix_caoth (atmosphere_struct* atmos,
photon_struct* p,
int isp,
double mu,
int np,
/* Output */
double* phase_matrix);
static inline int calc_stokes_vector_for_escape (sample_struct* sample,
atmosphere_struct* atmos,
double* phase_matrix,
double mu2,
direction dir_inc,
double phi_esc,
direction dir_esc,
int polmat,
/* In-/Output */
photon_struct* p);
int get_reflection_probability_matrix (albedo_struct* albedo,
photon_struct* p,
int nstokes,
int backward,
double mu_inc,
double phi_inc,
double mu_esc,
double phi_esc,
int ia,
int ja,
int il,
float wvnmlo,
float wvnmhi,
int iv,
/* Output */
double*** refl_mat);
static double reflection_polarized (albedo_struct* albedo,
photon_struct* p,
int nstokes,
int backward,
double* dir_inc,
double* dx_out,
double* n_hor,
double mu_inc,
double phi_inc,
double mu_esc,
double phi_esc,
double phi_target,
int ia,
int ja,
int il,
float wvnmlo,
float wvnmhi,
int escape,
int spherical3D,
int spectral_is,
int nlambda,
float* lambda,
int* status);
void phase_matr_rot (double** Z_in, double cos2alpha, double sin2alpha, double** Z_out);
void rot_phase_matr (double** Z_in, double cos2alpha, double sin2alpha, double** Z_out);
/*static inline void dtauabs_spectral_calc(atmosphere_struct *atmos, photon_struct *p*/
/* double step); */
static int correct_escape_dir_refract (double* dir_sensor,
photon_struct* photon,
atmosphere_struct* atmos,
sample_struct* sample,
float* refind);
static inline double std_noisy (double var, double avg, double dmcphotons);
int set_panorama_dir (sample_struct* sample, float* sza, float* phi0);
double Fresnel (double nr, double ni, double coschi);
void index_water (double wl, double xsal, double* nr, double* ni);
static double find_max (double x, double y, double z); /* **CK 2013.08.27 */
static double find_min (double x, double y, double z); /* **CK 2013.08.27 */
static double pst (double mu, int i, double dtau); /* **CK 2013.08.27 */
static int
emabsopt_location (photon_struct* p, atmosphere_struct* atmos, sample_struct* sample, long int photons); /* **CK 2013.08.27 */
static int denet_weight (photon_struct* p,
atmosphere_struct* atmos,
sample_struct* sample,
long int nphotons,
int* counter1); /* **CK 2013.08.27 */
static int denet_set_direction (photon_struct* p,
atmosphere_struct* atmos,
sample_struct* sample,
long int nphotons,
int* counter1,
double* norm); /* **CK 2013.08.27 */
static int dist_photon_direction_by_phasemax (photon_struct* p,
sample_struct* sample,
double* sza,
double* cossza,
double* sinsza); /* Bernhard Reinhardt 2013.12.23 */
#ifdef CLDPRP
static int summarize_result_cldprp (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
int elev2D,
int islower,
int isupper,
int jslower,
int jsupper,
int isstep,
int jsstep);
#endif
inline static void write_backward_irradiance (sample_struct* sample, double result, FILE* backfile, int is, int js, int nn);
static int summarize_result_forward_surface (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
double dmcphotons,
double factor,
double incident,
int write_files,
int elev2D,
char* flxext,
char* flxext2,
char* radext,
char* radext2,
char* rplext,
char* rplext2);
static int summarize_result_backward_irradiance (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
char* specradfilename,
char* bacext,
char* bacext2,
char* bacjacext,
char* bacjacext2,
double dmcphotons,
double factor,
double wavelength,
int mcsimulations,
int write_files,
int elev2D,
int islower,
int isupper,
int jslower,
int jsupper,
int isstep,
int jsstep);
static int summarize_result_backward_radiance (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
char* specradfilename,
char* bacext,
char* bacext2,
char* picext,
char* bacjacext,
char* bacjacext2,
double dmcphotons,
double factor,
double sza,
int source,
int mcsimulations,
int write_files,
int elev2D,
int islower,
int isupper,
int jslower,
int jsupper,
int isstep,
int jsstep);
static int summarize_result_forward_altitude_radiance (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
char* specradfilename,
char* radext,
char* radext2,
double dmcphotons,
double factor,
int write_files,
int kc);
static int summarize_result_passback3D (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
float*** rfldir3d,
float*** rfldn3d,
float*** flup3d,
float***** fl3d_is,
float*** uavgso3d,
float*** uavgdn3d,
float*** uavgup3d,
float**** radiance3d,
float*** absback3d,
float*** rfldir3d_var,
float*** rfldn3d_var,
float*** flup3d_var,
float*** uavgso3d_var,
float*** uavgdn3d_var,
float*** uavgup3d_var,
float**** radiance3d_var,
float*** absback3d_var,
float*** abs3d,
float****** radiance3d_is,
float****** jacobian,
int escape,
int islower,
int isupper,
int jslower,
int jsupper,
int isstep,
int jsstep,
int* lu3D);
static int summarize_result_altitude_rpl (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
char* rplext,
char* rplext2,
double dmcphotons,
double incident,
int write_files,
int kc);
static int summarize_result_absorption (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
float*** abs3d,
float*** abs3d_var,
char* basename,
char* absext,
char* absext2,
double dmcphotons,
double incident,
int write_files,
int absorption);
static int summarize_result_forward_altitude_irradiance (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
double dmcphotons,
double factor,
int write_files,
int kc,
char* flxext,
char* flxext2);
static int summarize_result_boxairmass (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
double dmcphotons,
char* basename);
int mystic (int* nlyr,
int* threed,
int n_caoth,
float** dt_s,
float** om_s,
float** g1_s,
float** g2_s,
float** f_s,
float** ds_s,
alis_struct* alis,
float* refind,
float r_earth,
float refractive_index_pv,
float* rayleigh_depol,
caoth3d_out_struct* caoth3d,
float** re_s,
float*** temper,
int temper3d,
float* zprof,
float*** momaer,
int* nmomaer,
int** nthetaaer,
float*** thetaaer,
double*** muaer,
float*** phaseaer,
int nphamataer,
float* alb,
float* alb_type,
float sza,
float phi0,
float sza_spher,
float phi0_spher,
long int nphotons,
int* source,
float* wvnmlo,
float* wvnmhi,
float* wavelength,
float* zoutorg,
int* nzoutorg,
float* rpv_rho0,
float* rpv_k,
float* rpv_theta,
float* rpv_scale,
float* rpv_sigma,
float* rpv_t1,
float* rpv_t2,
float* hapke_h,
float* hapke_b0,
float* hapke_w,
float* rossli_iso,
float* rossli_vol,
float* rossli_geo,
int rossli_hotspot,
float* u10,
float* pcl,
float* xsal,
float* uphi,
int* solar_wind,
float* bpdf_u10,
int* tenstream,
char* tenstream_options,
int* nca, /* Carolin Klinger 2019 */
char* nca_options,
int* ipa,
int* absorption,
int* thermal_heating_method,
int* loaddata,
sample_struct* sample,
elevation_struct* elev,
t_triangular_surface* triangular_surface,
surftemp_struct* surftemp,
char* basename,
char* umufilename,
char* sunshape_filename,
char* albedo_filename,
char* ambralsfilename,
char* rosslifilename,
char* alb_type_filename,
char* rpv_type_filename,
char* ambrals_type_filename,
char** surface_labels,
int* surface_nlabels,
float* delta_scaling_mucut,
float* truncate,
int* reflectalways,
int quiet,
float* rfldir,
float* rfldn,
float* flup,
float* uavgso,
float* uavgdn,
float* uavgup,
float*** rfldir3d,
float*** rfldn3d,
float*** flup3d,
float***** fl3d_is,
float*** uavgso3d,
float*** uavgdn3d,
float*** uavgup3d,
float**** radiance3d,
float*** absback3d,
float*** abs3d,
float****** radiance3d_is,
float****** jacobian,
float*** rfldir3d_var,
float*** rfldn3d_var,
float*** flup3d_var,
float*** uavgso3d_var,
float*** uavgdn3d_var,
float*** uavgup3d_var,
float**** radiance3d_var,
float*** absback3d_var,
float*** abs3d_var,
t_triangle_radiation_field* triangle_results,
int nxcld,
int nycld,
int nzcld,
double dxcld,
double dycld,
char* datapath,
char* randomstatusfilename,
int readrandomstatus,
int write_output_as_netcdf,
int write_files,
int visualize) {
/* local variables */
static int first = 1;
int status = 0;
long int photoncounter = 0;
long int totalphotoncounter = 0;
int totalsimulations = 0;
int outofdomaincounter = 0;
static albedo_struct* albedo = NULL;
result_struct* result = calloc (1, sizeof (result_struct));
atmosphere_struct* atmos = calloc (1, sizeof (atmosphere_struct));
photon_struct* p = NULL;
int starttime, endtime;
int aerosol_scatter_type = 0;
float* zout = NULL;
int dummy = 0;
int* nzout = &dummy;
int plotpath = 0;
#ifdef ALLOW_FILE_CHECKS
long int fileteststarttime = 0;
long int newfileteststarttime = 0;
#endif
#if HAVE_OPENGL
int plotpathcounter = 0, plotresult = 0, plotresultcounter = 0;
#endif
#ifdef TIMINGS
int clockstarttime = 0;
#endif
int chouf = 0; /* needed by MUCHOUT etc */
/****************************************************/
/* 1. return if mystic does not need to do anything */
/****************************************************/
/* do nothing if SZA >= 90 degrees, unless in spherical geometry */
if (!sample->spherical && !sample->spherical3D && sza >= 90.0)
return 0;
/* do nothing if number of photons smaller or equal zero */
if (*absorption != MCFORWARD_ABS_EMISSION && nphotons <= 0)
return 0;
/****************************************************/
/* 2. check on errors */
/****************************************************/
status = mystic_check_consistency (sample, elev, surftemp, *delta_scaling_mucut, *truncate, *source, umufilename, *ipa);
if (status)
return fct_err_out (status, "mystic_check_consistency", ERROR_POSITION);
/****************************************************/
/* 3. set things */
/****************************************************/
status = mystic_set (*nlyr,
nmomaer,
nthetaaer,
*source,
*absorption,
visualize,
loaddata,
*nzoutorg,
zoutorg,
*rpv_rho0,
*rpv_k,
*rpv_theta,
*hapke_h,
*hapke_b0,
*hapke_w,
*rossli_iso,
*rossli_vol,
*rossli_geo,
*u10,
*pcl,
*xsal,
*bpdf_u10,
albedo_filename,
ambralsfilename,
rosslifilename,
alb_type_filename,
rpv_type_filename,
ambrals_type_filename,
*reflectalways,
&first,
sample,
&albedo,
delta_scaling_mucut,
truncate,
&aerosol_scatter_type,
&nphotons,
nzout,
&zout,
rfldir,
rfldn,
flup,
uavgso,
uavgdn,
uavgup,
quiet);
if (status)
return err_out ("Error, mystic_set returned status %d\n", status);
/****************************************************/
/* 4. talk to user */
/****************************************************/
status = mystic_verbose (quiet, sample, albedo, aerosol_scatter_type, nphotons, *ipa, *delta_scaling_mucut, *truncate);
if (status)
return err_out ("Error, mystic_verbose returned status %d\n", status);
/* initial setup: read 3D caoths, 2D albedo, and elevation fields; */
/* allocate memory and initialize arrays. */
status = setup_mystic (caoth3d,
atmos,
result,
albedo,
surftemp,
sample,
*delta_scaling_mucut,
*absorption,
*thermal_heating_method,
*nlyr,
threed,
n_caoth,
dt_s,
om_s,
g1_s,
g2_s,
f_s,
ds_s,
alis,
*rayleigh_depol,
re_s,
temper,
temper3d,
zprof,
&sza,
&phi0,
sza_spher,
phi0_spher,
aerosol_scatter_type,
momaer,
nmomaer,
nthetaaer,
thetaaer,
muaer,
phaseaer,
nphamataer,
*alb,
alb_type,
rpv_rho0,
rpv_k,
rpv_theta,
rpv_scale,
rpv_sigma,
rpv_t1,
rpv_t2,
hapke_h,
hapke_b0,
hapke_w,
rossli_iso,
rossli_vol,
rossli_geo,
rossli_hotspot,
u10,
pcl,
xsal,
uphi,
solar_wind,
bpdf_u10,
*source,
wvnmlo,
wvnmhi,
wavelength,
zout,
*nzout,
nxcld,
nycld,
nzcld,
dxcld,
dycld,
umufilename,
sunshape_filename,
albedo_filename,
ambralsfilename,
rosslifilename,
alb_type_filename,
rpv_type_filename,
ambrals_type_filename,
surface_labels,
*surface_nlabels,
*truncate,
*loaddata,
datapath,
r_earth,
visualize,
triangular_surface,
triangle_results,
quiet,
nphotons); /* **CK 2013.08.27 Added nphotons */
if (status)
return err_out ("Error, setup_mystic returned status %d\n", status);
/* in case of atmospheric thermal radiation: */
/* if maximum emission equals zero, we are done (no thermal emission) */
if (*source == MCSRC_THERMAL_ATMOSPHERE)
if (atmos->maxemis <= 0)
return 0;
/* if MCFORWARD_ABS_EMISSION was specified, we only need to calculate */
/* the emission of each grid cell. */
if (*absorption == MCFORWARD_ABS_EMISSION) {
status = calculate_emission (atmos, result);
if (status)
return err_out ("Error %d returned by calculate_emission()\n", status);
}
#if HAVE_OPENGL
if (visualize) {
GLmystic_setdomain (GLMYSTIC_PHOTONS,
atmos->X[0],
atmos->Y[0],
atmos->Z[0],
atmos->X[atmos->Nx],
atmos->Y[atmos->Ny],
atmos->Z[atmos->Nz]);
}
#endif
/***********************/
/* end of preparations */
/***********************/
if (*tenstream && nphotons > 0) {
#ifdef HAVE_TENSTREAM
status = tenstream_like_mystic (tenstream_options,
*source,
dxcld,
dycld,
atmos->Z,
albedo->albedo,
phi0,
sza,
atmos,
sample,
temper3d,
surftemp,
temper,
*wvnmlo,
*wvnmhi,
rfldir,
rfldn,
flup,
rfldir3d,
rfldn3d,
flup3d,
*absorption,
abs3d);
CHKERR (status);
nphotons = 0;
#else
return err_out ("Error you tried running the TENSTREAM solver with input option mc_tenstream"
"-- your installation however is not configured to run it. Check your installation",
-1);
#endif
}
/* Carolin Klinger 2019 */
/* check if thermal and if nca */
if (*nca && nphotons > 0) {
status = nca_like_mystic (nca_options,
datapath,
dxcld,
dycld,
atmos->Z,
atmos,
surftemp,
temper,
*wvnmlo,
*wvnmhi,
*source,
temper3d,
abs3d);
CHKERR (status);
nphotons = 0;
}
if (!quiet)
fprintf (stderr, " ... starting first photon!\n");
starttime = (int)time (NULL);
/*****************************************/
/* loops over lasers and lidar detectors */
/*****************************************/
for (sample->ili = 0; sample->ili < sample->Nli; sample->ili++) {
if (!quiet && sample->LidarLocEst && (sample->Nli > 1))
fprintf (stderr, "starting laser-detector-system %d ...\n", sample->ili);
/*****************************************************************************/
/* loop over backward sample pixels; in forward mode, upper and lower pixels */
/* are identical and the photon loop is executed only once, as it should be */
/*****************************************************************************/
/* For now, set sample->backward_Nz to 1 since at present only one altitude is calculated */
/* this should change in future. */
/* int Nx=0, Ny_min=0, Ny=0; */
/* int **sample_pixel=NULL; */
/* status=ASCII_file2int("sample_pixels.txt", &Nx, &Ny_min, &Ny, &sample_pixel); */
/* fprintf(stderr, "status %d \n", status); */
/* fprintf(stderr, "sample pixles Nx %d Ny %d\n", Nx, Ny); */
/* fprintf(stderr, "sample pixles Nx %d Ny %d sample_pixel[3][4] %d\n", */
/* Nx, Ny, sample_pixel[3][4]); */
sample->backward_Nz = 1;
for (sample->backward_ks = 0; sample->backward_ks < sample->backward_Nz; sample->backward_ks++) {
for (sample->backward_is = sample->backward_islower; sample->backward_is <= sample->backward_isupper;
sample->backward_is += sample->backward_isstep) {
for (sample->backward_js = sample->backward_jslower; sample->backward_js <= sample->backward_jsupper;
sample->backward_js += sample->backward_jsstep) {
/* fprintf(stderr, "is %d js %d sample_pixel %d \n", sample->backward_is, */
/* sample->backward_js, sample_pixel[sample->backward_is][sample->backward_js]); */
/* if(sample_pixel[sample->backward_is][sample->backward_js] ==1 ){ */
if (!quiet && sample->backward)
fprintf (stderr,
" ... sample pixel %d %d %d, %ld photons\n",
sample->backward_is,
sample->backward_js,
sample->backward_ks,
nphotons);
if (!sample->backward && (sample->backward_is > 0 || sample->backward_js > 0 || sample->backward_ks > 0)) {
fprintf (stderr, "\n");
fprintf (stderr, "*** Error: loop over backward pixels initiated although forward\n");
fprintf (stderr, "*** calculation. This is not supposed to happen!\n");
fprintf (stderr, "\n");
return -1;
}
#ifdef ALLOW_FILE_CHECKS
newfileteststarttime = (long int)clock() / 10000;
/* wait at least one second before next file test */
if (newfileteststarttime - fileteststarttime > 1000)
if (check_premature_exit ("slowexit", sample))
break;
#endif
#ifdef TIMINGS
clockstarttime = clock();
#endif
if (sample->panorama) {
status = set_panorama_dir (sample, &sza, &phi0);
if (status < 0)
return err_out ("Error %d returned by set_panorama_dir()\n", status);
if (status == 1)
continue;
}
/* calculate emission for backward heating rate calculation */
if (sample->backward == MCBACKWARD_EMIS) {
status = calculate_backward_emission (atmos,
sample,
sample->backemis_kc,
&(result->backemis[sample->backward_is][sample->backward_js]));
if (status)
return err_out ("Error %d returned by calculate_backward_emission()\n", status);
}
/*********************/
/* loop over photons */
/*********************/
photoncounter = 0;
while (photoncounter++ < nphotons) {
#ifdef ALLOW_FILE_CHECKS
newfileteststarttime = (long int)clock() / 10000;
/* wait at least one second before next file test */
if (newfileteststarttime - fileteststarttime > 1000) {
check_progress (photoncounter, nphotons, sample, *wavelength);
if (check_premature_exit ("fastexit", sample))
break;
fileteststarttime = newfileteststarttime;
}
#endif
#if HAVE_LIBGSL
status = read_and_write_random_status (randomstatusfilename,
&(sample->ili),
&(sample->backward_is),
&(sample->backward_js),
photoncounter,
&readrandomstatus);
if (status)
return err_out ("Error %d returned by read_and_write_random_status()\n", status);
#endif
/* generate a new photon */
status = generate_photon (*source,
photoncounter,
atmos,
albedo,
elev,
sample,
*wvnmlo,
*wvnmhi,
*wavelength,
sza,
phi0,
*ipa,
nphotons,
&p,
refractive_index_pv);
CHKERROUT (status, "Error, failed to generate a photon");
/* don't trace photons with zero weight */
if (p->weight == 0.0) {
destroy_photon (p, atmos->n_caoth);
continue;
}
#if HAVE_OPENGL
if (visualize)
initialize_plot_photon_path (p,
sample,
result,
photoncounter,
&plotpathcounter,
&plotpath,
&plotresultcounter,
&plotresult);
#endif
/* ============================Start Ris Factor================================ */
/* RIS-Factor works only with lidar and radar. */
/* There are 3 variables: */
/* sample->ris_factor: Value from config, does not change, not used after this. */
/* sample->ris_optical_depth: Like sample->ris_factor */
/* atmos->ris_factor: Is set below and used everywhere else, must not be 0, */
/* defaults to 1! */
/* Cases: */
/* A. If sample->ris_optical_depth != 0 then find_ris_factor() is called and */
/* atmos->ris_factor is determined and set in that function */
/* B. If sample->ris_factor != 0 then atmos->ris_factor = sample->ris_factor. */
/* */
/* The following code is executed once per lidar/radar shot and ris factor is */
/* set anew for each shot. Otherwise it's just executed once before the first */
/* photon starts its journey. */
/* */
if (photoncounter == 1) {
if (!sample->LidarLocEst && (sample->ris_optical_depth != 0. || sample->ris_factor != 0.)) {
fprintf (stdout, "Error, use ris factor only with lidar or radar!\n");
return -1;
}
if (sample->ris_optical_depth != 0. && sample->ris_factor != 0.) {
fprintf (stdout, "Error, use only one ris factor method at a time!\n");
return -1;
}
/* Case A */
else if (sample->ris_optical_depth != 0.) {
find_ris_factor (p, atmos, sample, elev, refind);
if (!quiet)
fprintf (stderr, " ... RIS-FACTOR: %e\n", atmos->ris_factor);
}
/* Case B */
else if (sample->ris_factor != 0.) {
atmos->ris_factor = sample->ris_factor;
if (!quiet)
fprintf (stderr, " ... RIS-FACTOR: %e\n", atmos->ris_factor);
}
}
/* ===========================End Ris Factor=================================== */
// PANPAN if panorama_extinction
if (sample->pan_transmittance) {
photon_struct* p_escape =
calloc_photon (sample, atmos->Nx, atmos->Ny, atmos->Nz, MCSRC_NONE, atmos->nlambda_abs, atmos->Nc, atmos->n_caoth);
/* work on a copy of the photon, not the original one */
cp_photon_struct (p_escape, p, sample, atmos->n_caoth);
p_escape->pdir[0] = 1;
p_escape->weight = 4; // radiance will later be normalized by 4 if output_quantity reflectivity is chosen
p_escape->dir.cotheta = 1;
p_escape->stokes[0] = 1;
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, 0, -1, -1, 1, refind);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
/* calculate direct contribution to radiation */
status = direct_radiation (sample, atmos, p, result, elev, triangular_surface, source, refind);
if (status)
return err_out ("Error %d returned by direct_radiation()\n", status);
/* register photon at its start position */
status = register_at_start (p, sample, atmos, result, *source, *absorption);
if (status)
return err_out ("Error %d returned by register_at_start()\n", status);
#if HAVE_LIDAR
if (sample->LLE_taumax != 0.0 && p->photoncounter == 1) {
status = mc_lidar_fix_taumax (sample, atmos, result, elev, triangular_surface, p, refind, quiet);
if (status > 0)
break;
if (status < 0)
return err_out ("Error %d returned by mc_lidar_fix_taumax()\n", status);
}
#endif
#ifdef MUCHOUT
/* chouf=1;*/
if (chouf) {
fprintf (stderr, "choufing\n");
p->muchoutcounter = MUCHOUTPHOTON;
}
#endif
/*********************/
/* start the journey */
/*********************/
status = photon_journey (p,
atmos,
sample,
result,
elev,
albedo,
triangular_surface,
surftemp,
absorption,
source,
plotpath,
visualize,
wvnmlo,
wvnmhi,
refind,
quiet,
datapath);
if (status) {
fprintf (stderr, "Error in photon_journey() occured for photon %d\n", p->photoncounter);
CHKERR (status);
}
outofdomaincounter += (p->photon_status == MCSTATUS_OUTOFDOMAIN);
status = cleanup_after_photon_journey (p, sample, result, atmos->n_caoth, chouf);
if (status) {
CHKERROUT (status, "Error returned by cleanup_after_photon_journey()");
}
if (sample->pan_quicklook) {
photoncounter++;
break;
}
} /* end of photon loop */
totalphotoncounter += photoncounter - 1;
totalsimulations++;
#ifdef TIMINGS
fprintf (stderr, "cputime %d %d %d\n", sample->backward_is, sample->backward_js, ((int)clock() - clockstarttime) / 10000);
#endif
// } /* end of sample pixel mask */
} /* end of sample->backward_js loop */
} /* end of sample->backward_is loop */
} /* end of sample->backward_ks loop */
/* Chris - special output for CB stuff, must be within ili-loop */
if (sample->coherent_backscatter) {
#if HAVE_LIDAR
if (sample->LidarLocEst) {
summarize_result_lidar_cb (result->mish, result->lidcb, sample, atmos->ris_factor, nphotons, basename);
} else
summarize_result_mishchenko_cb (result->mish, basename);
#else
summarize_result_mishchenko_cb (result->mish, basename);
#endif
}
} /* end of sample->ili loop */
endtime = (int)time (NULL);
if (!quiet)
fprintf (stderr,
" ... intended to trace %ld photons, traced %ld in %d simulations\n",
nphotons,
totalphotoncounter,
totalsimulations);
if (!quiet)
fprintf (stderr, " ... summarizing\n");
#ifdef CLDPRP
/* summarized effective radius has to be stored for each wavelength seperatly */
result->wavelength = 0.5 * 1e4 * (1.0 / (*wvnmlo) + 1.0 / (*wvnmhi));
#endif
/**************************************************************/
/* calculate result arrays, write data to files and to stderr */
/**************************************************************/
status = summarize_result (result,
sample,
atmos,
albedo,
triangular_surface,
*source,
totalphotoncounter,
totalsimulations,
sza,
*absorption,
write_files,
write_output_as_netcdf,
*tenstream,
*nca,
basename,
rfldir,
rfldn,
flup,
uavgso,
uavgdn,
uavgup,
rfldir3d,
rfldn3d,
flup3d,
fl3d_is,
uavgso3d,
uavgdn3d,
uavgup3d,
radiance3d,
absback3d,
abs3d,
radiance3d_is,
jacobian,
rfldir3d_var,
rfldn3d_var,
flup3d_var,
uavgso3d_var,
uavgdn3d_var,
uavgup3d_var,
radiance3d_var,
absback3d_var,
abs3d_var,
sample->escape,
elev->elev2D,
2.0 / ((*wvnmlo + *wvnmhi)) * 1e7,
quiet);
if (status)
return err_out ("Error %d returned by summarize_result()\n", status);
if (!quiet)
fprintf (stderr, " ... back from summarize_result\n");
fflush (stderr);
free_mystic (result,
atmos,
sample,
zout,
*absorption,
*thermal_heating_method); /* **CK 2013.09.23 added thermal_heating_method */
/* other stuff, unsorted */
if (!quiet) {
if (endtime - starttime > 0)
fprintf (stderr,
" ... used %d seconds for tracing; %d photons per second\n",
endtime - starttime,
(int)((double)totalphotoncounter / (double)(endtime - starttime)));
else
fprintf (stderr, " ... used less than 1 second for tracing\n");
}
if (sample->bcond == MCBCOND_ABSORB && !sample->LidarLocEst && outofdomaincounter > 0) {
fprintf (stderr,
"ATTENTION! %d/%ld = %.1f%% photons tried to leave the domain sideways\n",
outofdomaincounter,
totalphotoncounter,
(double)outofdomaincounter / (double)totalphotoncounter * 100.0);
fprintf (stderr, " or were absorbed due to numerical problems \n");
fprintf (stderr, " and were eliminated - the result is affected by that!\n");
}
#if HAVE_OPENGL
if (visualize) {
fprintf (stderr, " ... waiting for 3D graphics to terminate\n");
wait (&status);
wait (&status);
/* free shared memory */
GLmystic_free_shared (GLMYSTIC_PHOTONS);
GLmystic_free_shared (GLMYSTIC_ELEVATION);
}
#endif
/***** I3RC CASE 7 VERSION ******/
/* fprintf (stderr, "ATTENTION! THIS IS A SPECIAL I3RC CASE 7 VERSION!\n"); */
/* fprintf (stderr, "DO NOT USE FOR ANY OTHER PURPOSE\n"); */
/***** I3RC CASE 7 VERSION ******/
/* restore original directions - they might be needed again */
/* if MYSTIC called more than once */
if (sample->Nd > 0) {
sample->rad[0].theta = sample->forward_vza;
sample->rad[0].phi = sample->forward_phi;
}
return 0;
}
/***********************************************************************************/
/* Function: mystic_check_consistency @62_30i@ */
/* Description: */
/* check consistency of settings for mystic, and exit if inconsistent */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
static int mystic_check_consistency (sample_struct* sample,
elevation_struct* elev,
surftemp_struct* surftemp,
double delta_scaling_mucut,
double truncate,
int source,
char* umufilename,
int ipa) {
if (delta_scaling_mucut > -1.0) {
if (truncate > -1.0) {
fprintf (stderr, "Error! Combination of delta-scaling AND additional truncation");
fprintf (stderr, " using 'mc_truncate' not allowed. \n");
return -1;
}
}
if (ipa != 0 && sample->reference_to_NN) {
fprintf (stderr, "Error! Combination of reference_to_nn AND mc_ipa not allowed. \n");
return -1;
}
/* adjust for periodic boundary conditions */
switch (sample->bcond) {
case MCBCOND_PERIODIC:
case MCBCOND_ABSORB:
break;
case MCBCOND_MIRROR:
// fprintf (stderr, "Error, mirroring boundary conditions not implemented! The reason is\n");
//fprintf (stderr, "that is does not bring any advantage to handle mirroring\n");
//fprintf (stderr, "boundary conditions internally. If you want those, please\n");
//fprintf (stderr, "mirror your input data manually!\n");
//return -1;
break;
default:
fprintf (stderr, "Error, unknown boundary conditions %d\n", sample->bcond);
return -1;
}
if (elev->elev2D && source == MCSRC_THERMAL_SURFACE) {
fprintf (stderr, "Error, emission from inclined surfaces not yet included!\n");
return -1;
}
if (sample->spherical3D && !(sample->backward && sample->panorama && source == MCSRC_SOLAR)) {
fprintf (stderr, "DANGER! DANGER! DANGER! DANGER! DANGER! DANGER! DANGER! DANGER!\n");
fprintf (stderr, " 3D spherical geometry only works in combination with backward,\n");
fprintf (stderr, " panorama, and solar! Your photons will be entering a dimension\n");
fprintf (stderr, " where no photon has gone before!\n");
}
if (sample->spherical3D && strlen (umufilename) != 0) {
fprintf (stderr, "Error, 3D spherical geometry and umu2d can not be used together!\n");
return -1;
}
if (elev->elev2D && sample->spherical3D) {
fprintf (stderr, "Error, elevation in spherical geometry not yet implemented!\n");
return -1;
}
if (elev->elev2D && sample->spherical) {
fprintf (stderr, "Error, elevation in spherical geometry not yet implemented!\n");
return -1;
}
/* ??? currently 2D surface temperature is only available in backward mode; CHECK!!! */
/* ??? it's easy to implement in forward mode as well. */
if (surftemp->surf2D && source != MCSRC_THERMAL_BACKWARD) {
fprintf (stderr, "Error, 2D surface temperature currently only implemented for\n");
fprintf (stderr, "backward thermal calcultions. Sorry!\n");
return -1;
}
// if (sample->vroom && (sample->spectral_is || sample->concentration_is) ) {
// fprintf (stderr, "Error, vroom probably does not work together with ALIS and AerIS (spectral_is, aerosol_is)!\n");
// return -1;
// }
return 0;
}
/***********************************************************************************/
/* Function: mystic_set @62_30i@ */
/* Description: */
/* basic settings for mystic */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
static int mystic_set (/* input */
int nlyr,
int* nmomaer,
int** nthetaaer,
int source,
int absorption,
int visualize,
int* loaddata,
int nzoutorg,
float* zoutorg,
float rpv_rho0,
float rpv_k,
float rpv_theta,
float hapke_h,
float hapke_b0,
float hapke_w,
float rossli_iso,
float rossli_vol,
float rossli_geo,
float u10,
float pcl,
float xsal,
float bpdf_u10,
char* albedo_filename,
char* ambralsfilename,
char* rosslifilename,
char* alb_type_filename,
char* rpv_type_filename,
char* ambrals_type_filename,
int reflectalways,
/* throughput */
int* first,
sample_struct* sample,
albedo_struct** albedo,
float* delta_scaling_mucut,
float* truncate,
/* output */
int* aerosol_scatter_type,
long int* nphotons,
int* nzout,
float** zout,
float* rfldir,
float* rfldn,
float* flup,
float* uavgso,
float* uavgdn,
float* uavgup,
int quiet) {
int kc = 0, lu = 0;
int sumaer = 0;
/* HG aerosol or user-defined aerosol? */
for (kc = 0; kc < nlyr; kc++)
sumaer += nmomaer[kc] + nthetaaer[kc][0];
if (sumaer > 0)
*aerosol_scatter_type = MCSCAT_AER;
else
*aerosol_scatter_type = MCSCAT_HG1;
if (absorption == MCFORWARD_ABS_EMISSION || sample->backward == MCBACKWARD_EMIS) {
if (!quiet)
fprintf (stderr, " ... calculating atmospheric emission; no need to trace any photons!\n");
*nphotons = 0;
}
/* **CK , 2013.08.27 - Adujsting number of photons to a multiple of 12 for backward thermal heating rates */
if (sample->backward == MCBACKWARD_HEAT) {
if (*nphotons % 4 != 0)
*nphotons = 4 * (*nphotons / 4 + 1);
if (!quiet)
fprintf (stderr, " ... calculating backward thermal heating rates; adjusting photon number to %ld \n", *nphotons);
} /* **CK 2013.08.27 End MCBACKWARD_HEAT */
/* move this to setup_sample_grid in caoth3d.c ? */
if (sample->escape && source == MCSRC_THERMAL_BACKWARD) {
if (!quiet) {
fprintf (stderr, "\n");
fprintf (stderr, "*** Warning, backward thermal and mc_escape doesn't work!\n");
fprintf (stderr, "*** Switching off mc_escape!\n");
fprintf (stderr, "\n");
}
sample->escape = 0;
sample->vroom = 0;
if (*delta_scaling_mucut > -1.0 || *truncate > -1.0) {
fprintf (stderr,
"%s %s\n %s %s\n",
"... ATTENTION, Combination of delta-scaling",
"or other truncation of phase function",
"... doesn't make much sense with backward thermal mode.",
"Switching off truncation!");
*truncate = -1.0;
*delta_scaling_mucut = -1.0;
sample->delta_scaling = -1;
}
}
/* memory allocation for static structures */
if (*first) {
#if HAVE_OPENGL
if (visualize) {
GLmystic_init();
GLmystic_calloc_shared (GLMYSTIC_PHOTONS, 10000);
GLmystic_calloc_shared (GLMYSTIC_RESULT, sample->Nx * sample->Ny);
}
#endif
/* first call to mystic(); need to load the data in any case */
*loaddata = 1;
*first = 0;
/* allocate memory for structs */
*albedo = calloc (1, sizeof (albedo_struct));
} else {
/* mystic() has been called before; need to free memory if new */
/* data are to be loaded */
/* BM, 8.9.2020: not needed anymore because albedo data allocated only once */
/*
if (*loaddata != 0) {
if (!quiet)
fprintf (stderr, " ... freeing albedo structure)\n");
free_mystic_for_load (*albedo);
*albedo = calloc (1, sizeof (albedo_struct));
} else if (!quiet)
fprintf (stderr, " ... no need to load data again\n");
*/
}
/* make a copy of zout because zout[] may be changed by mystic */
/* and we want the original values for the next call. */
if (*zout != NULL) {
free (*zout);
*zout = NULL;
}
*nzout = 0;
if (nzoutorg > 0) { /* XXX this is probably bug!!! * is missing? */
*nzout = nzoutorg;
*zout = calloc (*nzout, sizeof (float));
for (lu = 0; lu < *nzout; lu++)
(*zout)[lu] = zoutorg[lu];
}
/* reset output */
for (lu = 0; lu < *nzout; lu++) {
rfldir[lu] = 0.0;
rfldn[lu] = 0.0;
flup[lu] = 0.0;
uavgso[lu] = 0.0;
uavgdn[lu] = 0.0;
uavgup[lu] = 0.0;
}
/**********************************************/
/* default settings for elevation and albedo; */
/* can be changed by the user but may be */
/* overwritten by the mystic() function */
/* parameters */
/**********************************************/
/* albedo->method = MCALB_LAM2D; */ /* 2D Lambertian surface albedo */
(*albedo)->method = MCALB_LAM; /* homogeneous Lambertian albedo */
/* ????? need more checking to avoid contraditionary specifications ????? */
/* override albedo->method if RPV specified CHECK!!! */
/* BCA: this is nasty, rpv_k is normally a vector, improve if statement */
if (rpv_k != 0 || rpv_rho0 != 0 || rpv_theta != 0)
(*albedo)->method = MCALB_RPV;
/* override albedo->method if HAPKE specified */
if (hapke_h != 0 || hapke_b0 != 0 || hapke_w != 0)
(*albedo)->method = MCALB_HAPKE;
/* override albedo->method if ROSSLI specified */
if (rossli_iso != 0 || rossli_vol != 0 || rossli_geo != 0)
(*albedo)->method = MCALB_ROSSLI;
/* override albedo->method if Cox and Munk specified */
if (u10 >= 0 || pcl >= 0 || xsal >= 0)
(*albedo)->method = MCALB_COXANDMUNK;
/* override albedo->method if Tsang BPDF is specified */
if (bpdf_u10 > 0)
(*albedo)->method = MCALB_TSANG;
/* override albedo->method if 2D albedo file specified */
if (*albedo_filename)
(*albedo)->method = MCALB_LAM2D;
/* override albedo->method if 2D spectral albedo file specified */
if (*alb_type_filename)
(*albedo)->method = MCALB_LAM2D_SPECTRAL;
/* override albedo->method if 2D RPV file specified; */
/* it is important that this comes AFTER the Cox_and_Munk */
/* check because we allow MCALB_RPV2D_SPECTRAL with ocean pixels. */
if (*rpv_type_filename)
(*albedo)->method = MCALB_RPV2D_SPECTRAL;
if (*ambrals_type_filename)
(*albedo)->method = MCALB_AMBRALS2D_SPECTRAL;
/* override albedo->method if 2D ROSSLI file specified */
if (*ambralsfilename)
(*albedo)->method = MCALB_ROSSLI2D;
if (*rosslifilename)
(*albedo)->method = MCALB_ROSSLI2D;
/* reflect each photon and weight with albedo or reflect only a fraction of "albedo" */
(*albedo)->reflectalways = reflectalways;
/* CP - Hotfix to avoid rare error from mc_vroom_DDIS_weight_and_prep_stuff()
over reflect() despite vroom being off and albedo being zero */
#if HAVE_LIDAR
if (sample->LidarLocEst == MCRADAR && !(sample->vroom) && (*albedo)->albedo == 0.)
(*albedo)->reflectalways = 0;
#endif
switch ((*albedo)->method) {
case MCALB_LAM:
case MCALB_LAM2D:
case MCALB_LAM2D_SPECTRAL:
break;
case MCALB_RPV:
case MCALB_RPV2D_SPECTRAL:
case MCALB_AMBRALS2D_SPECTRAL:
case MCALB_COXANDMUNK:
case MCALB_HAPKE:
case MCALB_ROSSLI:
case MCALB_ROSSLI2D:
case MCALB_TSANG:
if (!(*albedo)->reflectalways) {
(*albedo)->reflectalways = 1;
if (!quiet)
fprintf (stderr, " ... switching on reflectalways\n");
}
break;
default:
fprintf (stderr, "Fatal error, unknown albedo type %d\n", (*albedo)->method);
return -1;
}
return 0;
}
/***********************************************************************************/
/* Function: mystic_verbose @62_30i@ */
/* Description: */
/* talk to user: tell user what is being done */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
static int mystic_verbose (int quiet,
sample_struct* sample,
albedo_struct* albedo,
int aerosol_scatter_type,
long int nphotons,
int ipa,
double delta_scaling_mucut,
double truncate) {
static int firstwarning = 1;
if (!quiet) {
if (ipa)
fprintf (stderr, "\n ... start independent pixel approximation!\n");
else
fprintf (stderr, "\n ... start three-dimensional calculation\n");
if (aerosol_scatter_type == MCSCAT_AER)
fprintf (stderr, " ... user-defined aerosol properties\n");
/***** I3RC CASE 7 VERSION *****/
/* fprintf (stderr, "ATTENTION! THIS IS A SPECIAL I3RC CASE 7 VERSION!\n"); */
/* fprintf (stderr, "DO NOT USE FOR ANY OTHER PURPOSE\n"); */
/***** I3RC CASE 7 VERSION ******/
if (delta_scaling_mucut > -1.0) {
fprintf (stderr, " ... delta-scaling ... truncating phase function at mu = %f.\n", delta_scaling_mucut);
fprintf (stderr, " USE ONLY IF YOU REALLY, REALLY KNOW WHAT YOU ARE DOING!\n");
}
switch (sample->bcond) {
case MCBCOND_PERIODIC:
fprintf (stderr, " ... periodic boundary conditions\n");
break;
case MCBCOND_MIRROR:
fprintf (stderr, " ... mirroring boundary conditions\n");
// return -1;
break;
case MCBCOND_ABSORB:
fprintf (stderr, " ... absorbing boundary conditions\n");
break;
default:
fprintf (stderr, "Error, unknown boundary conditions %d\n", sample->bcond);
return -1;
}
#if HAVE_VROOM
if (sample->escape && sample->escape_eps_ddis_upf)
fprintf (stderr, "DDISUPF for escape (%e)", sample->escape_eps_ddis_upf);
#endif
fprintf (stderr, " ... running %ld photons\n", nphotons);
} /* end if quiet */
/* if truncate is true, the phase function will be truncated */
/* but only for the calculation of the escape probability after */
/* the first scattering event; this helps reducing hot spots */
if (truncate > -1.0) {
fprintf (stderr, " ... truncating phase function at mu = %f.\n", truncate);
fprintf (stderr, " ... USE ONLY IF YOU KNOW WHAT YOU ARE DOING!\n");
}
if (firstwarning == 1) {
if ((sample->spherical3D || sample->spherical3D_scene) && !quiet) {
fprintf (stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
fprintf (stderr, "!!! Warning! Spherical3D options are still very !!!\n");
fprintf (stderr, "!!! experimental! It is not sure whether what you are !!!\n");
fprintf (stderr, "!!! trying to calculate will work! Please be extremely!!!\n");
fprintf (stderr, "!!! careful with interpreting your results, and talk !!!\n");
fprintf (stderr, "!!! to Claudia Emde about whether what you are !!!\n");
fprintf (stderr, "!!! calculating can work at all! !!!\n");
fprintf (stderr, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
}
if (sample->LidarLocEst && sample->polarisation) {
fprintf (stderr, "Warning, polarisation not yet validated for Lidar! Be careful with results!\n");
}
if (sample->LidarLocEst) {
switch (albedo->method) {
case MCALB_LAM:
case MCALB_LAM2D:
case MCALB_LAM2D_SPECTRAL:
break;
case MCALB_RPV:
case MCALB_RPV2D_SPECTRAL:
case MCALB_AMBRALS2D_SPECTRAL:
case MCALB_COXANDMUNK:
case MCALB_HAPKE:
case MCALB_ROSSLI:
case MCALB_ROSSLI2D:
case MCALB_TSANG:
fprintf (stderr, "Warning, BRDF not yet validated for Lidar! Be careful with results!\n");
break;
default:
fprintf (stderr, "Fatal error, unknown albedo type %d\n", albedo->method);
break;
}
}
if (sample->vroom && sample->spherical3D && !quiet) {
fprintf (stderr, "Warning, vroom not yet validated for spherical geometry! Be careful with results!\n");
}
if (sample->vroom && sample->spherical && !quiet) {
fprintf (stderr, "Warning, vroom not yet validated for spherical geometry! Be careful with results!\n");
}
if (sample->refraction) {
fprintf (stderr, "Warning, refraction not yet working for reflection! Be careful with results!\n");
}
if (!sample->pan_distr_photons_over_pixel && sample->pan_with_direct_rad && !quiet) {
fprintf (stderr, "\n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
fprintf (stderr, " !!!! ATTENTION, it may be a good idea to use !!!!!!\n");
fprintf (stderr, " !!!! mc_panorama_distr_photons_over_pixel when !!!!!!\n");
fprintf (stderr, " !!!! using mc_panorama_with_direct_rad. !!!!!!\n");
fprintf (stderr, " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n");
}
if (sample->planar_switch) {
fprintf (stderr, "Warning, you are using experimental options! They can be wrong! Be careful!\n");
}
if (sample->spherical && !quiet) {
fprintf (stderr, "ATTENTION: For spherical MonteCarlo, the photons are started\n");
fprintf (stderr, " at the central point of the domain (not in the central\n");
fprintf (stderr, " sample pixel, as usual).\n");
}
firstwarning = 0;
}
return 0;
}
/***********************************************************************************/
/* Function: check_premature_exit @62_30i@ */
/* Description: */
/* check whether user has decided to exit prematurely with output of stuff so far */
/* calculated. */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
#ifdef ALLOW_FILE_CHECKS
static int check_premature_exit (const char* filename, sample_struct* sample) {
FILE* file;
file = fopen (filename, "r");
if (file != NULL) {
fclose (file);
sample->ili = sample->Nli;
sample->backward_is = sample->backward_isupper;
sample->backward_js = sample->backward_jsupper;
fprintf (stderr, "Exiting prematurely...\n");
return 1;
}
return 0;
}
#endif
/***********************************************************************************/
/* Function: check_premature_exit @62_30i@ */
/* Description: */
/* check whether user has decided to exit prematurely with output of stuff so far */
/* calculated. */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
#ifdef ALLOW_FILE_CHECKS
static void check_progress (long int photoncounter, long int nphotons, sample_struct* sample, float wavelength) {
FILE* file;
file = fopen ("progress", "r");
if (file != NULL) {
fclose (file);
fprintf (stderr,
"%s %e, is: %d of [%d-%d], js: %d of [%d-%d], ili %d of %d, nphots %ld of %ld\n",
"Progress reached: wvl: ",
wavelength,
sample->backward_is,
sample->backward_islower,
sample->backward_isupper,
sample->backward_js,
sample->backward_jslower,
sample->backward_jsupper,
sample->ili,
sample->Nli,
photoncounter,
nphotons);
}
return;
}
#endif
/***********************************************************************************/
/* Function: initialize_plot_photon_path @62_30i@ */
/* Description: */
/* check whether to plot photon path of current photon. */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
#if HAVE_OPENGL
static void initialize_plot_photon_path (photon_struct* p,
sample_struct* sample,
result_struct* result,
int photoncounter,
int* plotpathcounter,
int* plotpath,
int* plotresultcounter,
int* plotresult) {
/* start new photon path if first photon or a multiple of 10000 */
*plotpath = 0;
(*plotpathcounter)++;
if (*plotpathcounter == 10000 || photoncounter == 1) {
*plotpathcounter = 0;
*plotpath = 1;
GLmystic_start_photon_path (p);
}
/* copy global surface irradiance to result field for plotting, */
/* either for the first photon or for every 100000 photons */
*plotresult = 0;
(*plotresultcounter)++;
if (*plotresultcounter == 100000 || photoncounter == 1) {
*plotresultcounter = 0;
*plotresult = 1;
GLmystic_write_global (p, sample, result);
}
}
#endif
/***********************************************************************************/
/* Function: cleanup_after_photon_journey @62_30i@ */
/* Description: */
/* save and free stuff after photon journey. */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
static int cleanup_after_photon_journey (photon_struct* p, sample_struct* sample, result_struct* result, int n_caoth, int chouf) {
#if defined MUCHOUT || defined SPIKEOUT || defined ESCAPES
#if 0
static double oldres=0.0;
/* if (chouf) return -1; */
double churn=result->back[sample->backward_is][sample->backward_js][0]-oldres;
/* if (sample->backward_is==76)*/
fprintf(stderr,"delta %30.20f %d %d\n",churn,sample->backward_is,p->photoncounter);
#if defined SPIKEOUT
if (result->back[sample->backward_is][sample->backward_js][0]-oldres
> 145220. && chouf ) {
fprintf(stderr,"found spike...\n");
return -1;
}
if (churn==7.11312911017375881784)
chouf=1;
#endif
oldres=result->back[sample->backward_is][sample->backward_js][0];
#endif
#endif
treeprint_stddev (p->wtree); /* calculate standard deviation */
free (p->wtree);
p->wtree = NULL;
#if HAVE_LIDAR
/* special treatment for standard deviation of jacobians */
if (sample->LLE_jacobian_std)
lidar_collect_jacobian_stddev (result->lidar, sample->LLE_Nt, sample->ili, n_caoth);
if (sample->jacobian_std)
abs_collect_jacobian_stddev (result->jacobian, sample->backward_is, sample->backward_js);
#endif
#ifdef PRINT_PHOTON_PATH
/* print photon path to stdout and free memory */
print_and_clear_photonpath (p->path, "");
/* photon path separator */
fprintf (stdout, "! x x x x\n");
fflush (stdout);
#endif
#ifdef PRINT_ESCAPE_CONTRIBUTIONS
/* print photon path to stdout and free memory */
print_and_clear_photonpath (p->escapepath, "ESCAPE ");
/* photon path separator */
fprintf (stdout, "ESCAPE ! x x x x\n");
fflush (stdout);
#endif
destroy_photon (p, n_caoth);
return 0;
}
/***********************************************************************************/
/* Function: free_mystic @62_30i@ */
/* Description: */
/* Deallocate memory after mystic has ended. */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
static void free_mystic (result_struct* result,
atmosphere_struct* atmos,
sample_struct* sample,
float* zout,
int absorption,
int thermal_heating_method) /* **CK 2013.09.23 added thermal_heating_method */
{
int kc = 0;
/* Free the result structure; this structure is allocated and */
/* zeroed during each call of mystic, other than the other */
/* structures which are allocated only if loaddata!=0. Reason: */
/* freeing and reallocating is a convenient way to reset the */
/* structures to 0 without forgetting anything. */
free_result (result, thermal_heating_method, atmos, sample, absorption); /* **CK 2013.09.23 added thermal_heating_method */
free (zout);
if (sample->escape_eps_ddis_upf || sample->LLE_D_DIS || sample->n_phase_max != 0) {
free_iphase (sample->phase_max[0]);
free (sample->phase_max[0]);
free (sample->phase_max);
free_hybrid3D_field (&(atmos->spiky_box), atmos);
}
if (atmos->phase_aer != NULL) {
for (kc = 0; kc < atmos->Nz; kc++)
free_pft (&((atmos->phase_aer)[kc]));
free (atmos->phase_aer);
}
/* free stuff in functions */
get_phase_matrix_total (atmos, NULL, 0.0, 0, 0, 0, 0, 0, 1, NULL, NULL, NULL, NULL);
mc_vroom_scattering_calc_phases_and_jacobians (NULL, NULL, atmos, 0.0, 1, NULL, NULL, NULL);
free_atmosphere (atmos);
free (atmos);
}
/***********************************************************************************/
/* Function: direct_radiation @62_30i@ */
/* Description: */
/* Calculate direct contribution to radiation. */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
int direct_radiation (sample_struct* sample,
atmosphere_struct* atmos,
photon_struct* p,
result_struct* result,
elevation_struct* elev,
t_triangular_surface* triangular_surface,
int* source,
float* refind) {
int id = 0, status = 0, j = 0;
double norm[3] = {0, 0, 0};
double cotheta = 0, slope = 0.0, alpha2 = 0.0;
photon_struct* p_escape = NULL;
/* radiance contribution of the new photon at its start position */
if (sample->escape && p->scattercounter >= sample->minscatters) {
switch (sample->backward) {
case MCBACKWARD_EGLOB:
case MCBACKWARD_EDIR:
case MCBACKWARD_FDIR:
/* in case of direct irradiance we only count the escape */
/* radiance of the starting photon; here we need to consider */
/* the projection of the surface area perpendicular to the */
/* photon direction */
/* determine upward normal to the surface */
calc_normal_vector (p,
elev,
sample,
atmos,
sample->surfaceparallel && sample->zstart == -999.0,
sample->sensordirection && sample->zstart == -999.0,
norm);
v_mult (norm, sample->rad[0].dir.dx, &cotheta);
/* no contribution to direct irradiance if sensor looking downward */
/* CE: not for spherical atmosphere! CHECK!!!*/
/* RPB: think! If norm is calculated correctly, ok for spherical atmosphere! */
/* CE 2019-07-24 : Now I think that it is indeed correct also for spherical geometry. */
if (cotheta > 0) {
p_escape = create_escape_photon (p, atmos, sample, 0);
p_escape->pdir[0] = 4.0 * fabs (cotheta);
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, 0, -1, -1, 1, refind);
if (status != 0)
return err_out ("Error, escape_probability() returned status %d\n", status);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
break;
default:
break;
}
switch (*source) {
case MCSRC_THERMAL_ATMOSPHERE:
for (id = 0; id < sample->Nd; id++) {
p_escape = create_escape_photon (p, atmos, sample, id);
p_escape->pdir[id] = 1.0;
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, id, -1, -1, 0, refind);
if (status != 0)
return err_out ("Error, escape_probability() returned status %d\n", status);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
break;
case MCSRC_THERMAL_SURFACE:
for (id = 0; id < sample->Nd; id++) {
p_escape = create_escape_photon (p, atmos, sample, id);
/* ??? the following statement is not correct ??? CHECK!!! */
/* ??? for thermal emission from inclined surface ??? */
if (sample->rad[id].dir.dx[2] > 0) /* upward */
p_escape->pdir[id] = 4.0 * sample->rad[id].dir.dx[2];
else /* downward */
p_escape->pdir[id] = 0;
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, id, -1, -1, 1, refind);
if (status != 0)
return err_out ("Error, escape_probability() returned status %d\n", status);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
break;
case MCSRC_NONE:
break;
case MCSRC_SOLAR:
/* Do a 0-order local estimate (no scattering is taking place) */
/* to account for DIRECT RADIATION IN PANORAMA */
if (sample->pan_with_direct_rad) {
/* At this point we should still be at the location where the */
/* photon is generated. */
if (sample->sample_backward_sunshape) {
if (sample->pan_alignment != MCPAN_ALIGNMENT_SUN) {
fprintf (stderr, "Error, pan_with_direct_rad with sunshape does not work without pan_alignment sun! Exiting...\n");
return -1;
}
status = v_mult_mu (p->dir.dx, sample->rad_dir0.dx, &cotheta);
CHKERR (status);
/* Check if photon direction is pointing somewhere inside sun */
/* disc and if above horizon */
if ((cotheta >= cosd (sample->sun_radius)) && p->dir.dx[2] >= 0) {
p_escape = create_escape_photon (p, atmos, sample, 0);
/* alpha2: relative position on sun disc. scalar product of */
/* direction to sun center and photon direction gives the */
/* cosine of the angle between them. division by sunradius */
/* gives the relative position on sun disc */
alpha2 = acosd (cotheta) / sample->sun_radius;
/* find nearest alpha */
j = locate (sample->sample_backward_sunshape_alpha, sample->sample_backward_sunshape_n_lines, alpha2);
/* slope is the slope of the linear interpolation */
slope = sample->sample_backward_sunshape_slope[j];
/* Calc. probability of photon originating from this spot on the sun */
/* Interpolate sunshape to actual alpha */
p_escape->pdir[0] =
sample->sample_backward_sunshape_p[j] + slope * (alpha2 - sample->sample_backward_sunshape_alpha[j]);
/* We want radiances, so account for the solid angle of the sun */
p_escape->pdir[0] *= 4.0 * PI / (2. * PI * (1.0 - cosd (sample->sun_radius)));
/* In count_escape the weight is divided by */
/* sample->rad[id].dir.cotheta but instead it should be */
/* divided by the cotheta of the direction to sun center */
/* (sample->rad_dir0.cotheta) we account for that by */
/* modifying p->pdir[0] accordingly */
id = 0;
p_escape->pdir[0] *= sample->rad[id].dir.cotheta / sample->rad_dir0.cotheta;
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, 0, -1, 0, 0, refind);
if (status != 0)
return err_out ("Error, escape_probability() returned status %d\n", status);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
} else {
p_escape = create_escape_photon (p, atmos, sample, 0);
p_escape->pdir[0] = 1.0;
if (sample->pan_weight_with_cos) {
status = v_mult_mu (p->dir00.dx, sample->rad_dir0.dx, &cotheta);
CHKERR (status)
p_escape->pdir[0] *= 4.0 * PI * cotheta;
}
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, 0, -1, 0, 0, refind);
if (status != 0)
return err_out ("Error, escape_probability() returned status %d\n", status);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
}
break;
case MCSRC_BLITZ:
if (sample->pan_with_direct_rad) {
p_escape = create_escape_photon (p, atmos, sample, 0);
p_escape->pdir[0] = 1.0;
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, 0, -1, 0, 0, refind);
if (status != 0)
return err_out ("Error, escape_probability() returned status %d\n", status);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
break;
default:
fprintf (stderr, "Error, unknown source type\n");
return -1;
}
}
if (sample->pan_weight_with_cos)
p->weight *= -2.0 * PI * p->weight1;
return 0;
}
/***********************************************************************************/
/* Function: photon_journey @62_30i@ */
/* Description: */
/* Handle the journey of one photon. */
/* The function loops infinitely over the switch, which does something according */
/* to the current status of the photon. Each switch must change the status of */
/* the photon to a different status, else the loop does not work. */
/* Two cases lead to an exit from the loop, OUTOFDOMAIN and PURGE. PURGE should */
/* be the standard way to exit the loop, OUTOFDOMAIN is counted outside photon_ */
/* journey and leads to a warning. */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
int photon_journey (photon_struct* p,
atmosphere_struct* atmos,
sample_struct* sample,
result_struct* result,
elevation_struct* elev,
albedo_struct* albedo,
t_triangular_surface* triangular_surface,
surftemp_struct* surftemp,
int* absorption,
int* source,
int plotpath,
int visualize,
float* wvnmlo,
float* wvnmhi,
float* refind,
int quiet,
char* datapath) {
int status = 0, ie = 0, je = 0, ip = 0, old_photon_status = MCSTATUS_DEFAULT;
double tau = 0.0, zsurf = 0.0, slant2horz = 0.0;
double totweight[4];
/* nothing to do if direct irradiance is to be calculated backwards */
/* in this case only the escape radiance from the start counts */
if (sample->maxscatters == 0 || sample->backward == MCBACKWARD_EDIR || sample->backward == MCBACKWARD_FDIR ||
sample->backward == MCBACKWARD_EMIS || sample->pan_transmittance)
return 0;
while (1 == 1) {
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON) {
fprintf (stderr,
"counters %d %d %d %d --- photonstatus %d isclone %d \n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
p->photon_status,
p->isclone);
}
#endif
old_photon_status = p->photon_status;
/**************************************************/
/* process photon according to its current status */
/**************************************************/
switch (p->photon_status) {
case MCSTATUS_TRAVEL:
/* random step, in optical depth units */
if (sample->pan_quicklook)
tau = 0.1;
else
tau = random_tau();
/********************************/
/* now travel optical depth tau */
/********************************/
status = travel_tau (p,
atmos,
sample,
result,
elev,
triangular_surface,
tau,
*absorption,
*source,
plotpath,
visualize,
refind,
quiet);
if (status < 0)
return err_out ("Error %d returned by travel_tau()\n", status);
/***** I3RC CASE 7 VERSION ******/
/* if (p->pathlength > 15360) */
/* break; */
/***** I3RC CASE 7 VERSION ******/
#ifdef PRINT_PHOTON_PATH
/* add photon to photon path */
add_to_photonpath (&(p->path), p->x, p->weight);
#endif
#if HAVE_OPENGL
if (visualize)
if (plotpath)
GLmystic_add_node_to_photon_path (p->x[0], p->x[1], p->x[2]);
#endif
p->photon_status = status;
break;
case MCSTATUS_SCATTER:
/**************************************/
/* ... normal scattering, no boundary */
/**************************************/
#if HAVE_LIDAR
/* save tauext for CB */
if (sample->coherent_backscatter && sample->LidarLocEst)
add_tauext_to_cohebasca (p, sample, result->lidcb);
#endif
status = scattering (atmos, p, sample, result, elev, albedo, triangular_surface, *wvnmlo, *wvnmhi, refind, datapath);
if (status < 0)
return err_out ("Error, scattering() returned status %d\n", status);
if (status == MCSTATUS_VIRTUALSCATTER)
p->photon_status = MCSTATUS_TRAVEL;
else
p->photon_status = status;
break;
case MCSTATUS_ABSORB:
/***********************************************/
/* ... real absorption event in the atmosphere */
/***********************************************/
/*TZ bt...*/
/* contribution is Bplanck(T) in this case */
status = count_thermal_backward_photon (result, p, atmos, surftemp, sample, triangular_surface, 0.0, quiet, p->photon_status);
CHKERR (status);
/* now kill photon */
p->photon_status = MCSTATUS_PURGE;
break;
case MCSTATUS_SURFACE:
/*********************************************************************/
/* ... 2D surface hit preparation: */
/* adjust x[2] if photon hit the 2D surface to avoid roundoff errors */
/*********************************************************************/
/* elevation coordinates */
elev_coord (p, elev, &ie, &je);
/* final consistency check, if the photon really hit the surface */
zsurf = elevation (elev->surf[ie][je], p->x[0] - (double)ie * elev->delX, p->x[1] - (double)je * elev->delY);
/* here we test if the altitude deviates more than */
/* MC_EPSILON * maximum altitude from the surface; */
/* previously, MC_EPSILON was used as threshold, but */
/* this occasionally produced FATAL errors; are we */
/* still conservative enough? */
if (fabs (p->x[2] - zsurf) > MC_EPSILON * elev->surfmax) {
fprintf (stderr, "FATAL error:\n");
fprintf (stderr, "cross_surface() found that photon hit the surface at\n");
fprintf (stderr, "x = %g, y = %g, z = %.10f\n", p->x[0], p->x[1], p->x[2]);
fprintf (stderr, "while the surface elevation at this xy-location\n");
fprintf (stderr, "is actually %.10f.\n", zsurf);
return -1;
}
/* and adjust x[2] to the "true" surface altitude */
p->x[2] = zsurf;
/* no break */
case MCSTATUS_TRIANGLE_SURFACE: {
const double weight = p->weight * p->stokes[0] * exp (-p->tauabs.tot);
const int ierr = count_photon_on_triangular_surface (weight, p, 1 /*incoming*/, result->triangle_results);
CHKERR (ierr);
}
case MCSTATUS_BOUNDARY_LOWER:
/************************************************************/
/* ... if photon arrived at the surface or lower boundary */
/************************************************************/
/* register photon at the lower boundary */
if (*source != MCSRC_THERMAL_BACKWARD) {
/* conversion factor to correct for slant surface */
slant2horz = slt2hrz (elev, p, sample->surfaceparallel, 1);
if (slant2horz < 0.0)
return fct_err_out (-1, "slt2hrz", ERROR_POSITION);
for (ip = 0; ip < sample->nstokes; ip++)
totweight[ip] = p->weight * p->stokes[ip] * exp (-p->tauabs.tot) * slant2horz;
/* register incoming photon */
count_photon (result->surf, p, sample, totweight, sample->surfaceparallel, 1);
}
/* reflect photon at the lower boundary */
/**********************/
/* surface reflection */
/**********************/
int reflect_status;
status = reflect (p, albedo, elev, triangular_surface, atmos, sample, result, *wvnmlo, *wvnmhi, refind, &reflect_status);
CHKERR (status);
p->reflectcounter = 1;
/* don't do anything more if photon was destroyed */
if (reflect_status == MCSTATUS_PURGE) {
p->photon_status = reflect_status;
break;
}
/* if photon was absorbed by surface: */
if (reflect_status == MCSTATUS_ABSORB) {
/* count contribution of surface emission, if no reflection */
if (*source == MCSRC_THERMAL_BACKWARD) { /*TZ bt ...*/
/* contribution is here Bplanck(T) */
status = count_thermal_backward_photon (result,
p,
atmos,
surftemp,
sample,
triangular_surface,
albedo->bplkavg,
quiet,
p->photon_status);
CHKERR (status);
}
/* forward+solar backward: kill photon if no reflection */
p->photon_status = MCSTATUS_PURGE;
break;
} /*... TZ bt*/
if (*source != MCSRC_THERMAL_BACKWARD) { /*TZ bt*/
/* conversion factor to correct for slant surface */
slant2horz = slt2hrz (elev, p, sample->surfaceparallel, 0);
if (slant2horz < 0.0)
return fct_err_out (-1, "slt2hrz", ERROR_POSITION);
/* register reflected photon */
for (ip = 0; ip < sample->nstokes; ip++)
totweight[ip] = p->weight * p->stokes[ip] * exp (-p->tauabs.tot) * slant2horz;
count_photon (result->surf, p, sample, totweight, sample->surfaceparallel, 0);
/* if the reflection was off the 1D lower boundary */
/* register also into altitude profile */
if (p->photon_status == MCSTATUS_BOUNDARY_LOWER && sample->sample[0] != 0) {
count_photon (result->alt[0], p, sample, totweight, 0, 0);
}
} /*TZ bt*/
{
const double weight = p->weight * p->stokes[0] * exp (-p->tauabs.tot);
const int ierr = count_photon_on_triangular_surface (weight, p, 0 /*incoming*/, result->triangle_results);
CHKERR (ierr);
}
p->photon_status = MCSTATUS_INCREMENT;
break;
case MCSTATUS_BOUNDARY_UPPER:
/**************************************************/
/* ... if photon arrived at the upper boundary */
/**************************************************/
/* leave TOA */
if (*source == MCSRC_THERMAL_BACKWARD) { /*TZ bt ...*/
/* contribution is here Bplanck*emissivity. T(TOA)=0 => Bplanck=0*/
status =
count_thermal_backward_photon (result, p, atmos, surftemp, sample, triangular_surface, 0.0, quiet, p->photon_status);
CHKERR (status);
} /*... TZ bt*/
/* now kill photon */
p->photon_status = MCSTATUS_PURGE;
break;
case MCSTATUS_INCREMENT:
/*********************************************************************************/
/* photon has finished scattering/reflecting, now increment scattercounters etc. */
/*********************************************************************************/
/* is not done if virtual scatter (see VIS-FOD) */
/* surface reflection is also counted */
/* if escapescattercounter was smaller or equal than scattercounter then escape was done */
if (p->escapescattercounter <= p->scattercounter)
p->escapescattercounter++;
if (p->escapescattercounter <= p->scattercounter) {
fprintf (stderr,
"Error! escape seems to have skipped a von-Neumann-order! %d %d\n",
p->escapescattercounter,
p->scattercounter);
return -1;
}
p->scattercounter++;
if (p->isclone)
p->clonescattercounter++;
p->direct = 0;
if (sample->tipadir == 3) /* should be TIPA_DIR3D */
p->ipa = 1;
if (sample->delta_scaling > 0 && (p->scattercounter >= sample->delta_scaling))
p->SC_mode = MCSC_MODE_DELTA_SCALE;
if (sample->delta_scaling > 0 && (p->scattercounter >= sample->delta_scaling))
p->DDIS_SC_mode = MCSC_MODE_DELTA_SCALE;
if (sample->maxscatters > 0)
if (p->scattercounter >= sample->maxscatters) {
p->photon_status = MCSTATUS_PURGE;
break;
}
if (sample->pan_quicklook && p->scattercounter > 0) {
p->photon_status = MCSTATUS_PURGE;
break;
}
p->photon_status = MCSTATUS_TRAVEL;
/* go to cloning if VROOM is on */
if (sample->ntupelLE)
p->photon_status = MCSTATUS_CLONE;
else
p->photon_status = MCSTATUS_TRAVEL;
break;
#if HAVE_VROOM
case MCSTATUS_CLONE:
status = mc_vroom_cloning (p,
atmos,
sample,
result,
elev,
albedo,
triangular_surface,
surftemp,
absorption,
source,
plotpath,
visualize,
wvnmlo,
wvnmhi,
refind,
quiet);
if (status < 0)
return err_out ("FATAL error! mc_vroom_cloning() returned status %d\n", status);
p->photon_status = MCSTATUS_SPLIT;
break;
case MCSTATUS_SPLIT:
status = mc_vroom_splitting_and_rr (p,
atmos,
sample,
result,
elev,
albedo,
triangular_surface,
surftemp,
absorption,
source,
plotpath,
visualize,
wvnmlo,
wvnmhi,
refind,
quiet);
if (status < 0)
return err_out ("FATAL error! mc_vroom_splitting_and_rr() returned status %d\n", status);
p->photon_status = status;
/* after split comes travel */
if (p->photon_status == MCSTATUS_DEFAULT)
p->photon_status = MCSTATUS_TRAVEL;
break;
#endif
case MCSTATUS_DEFAULT: /* should not happen here */
case MCSTATUS_OUTOFDOMAIN: /* should not happen here */
case MCSTATUS_PURGE: /* should not happen here */
case MCSTATUS_VIRTUALSCATTER: /* uld not happen here */
default:
fprintf (stderr, "Error in photon_journey() loop, no valid photon_status %d\n", p->photon_status);
return -1;
}
/* if the photon status did not change in the switch, something is wrong */
/* the photon will be in the same status in the next switch, and might */
/* stay so infinitely. Hence, exit is better. */
if (old_photon_status == p->photon_status) {
fprintf (stderr, "Error, photon_status %d did not change, this potentially means infinite loop!\n", p->photon_status);
return -1;
}
/* ============ Don't trace photons with zero weight! ============== */
/* Testing exp(-p->tauabs.tot) == 0 should not be done because the */
/* exp function is too expensive to calculate, therefore we check */
/* p->tauabs.tot >= 709. since exp(-709) = 1.217e-308, which is near */
/* the lowest possible double precision number, so it's save to kill */
/* photons if they ever reach that point */
if (p->weight == 0. || p->stokes[0] == 0. || p->tauabs.tot >= 709.)
p->photon_status = MCSTATUS_PURGE;
/**************************************************************/
/* stop if photon absorbed, in space, or due to other reasons */
/**************************************************************/
if (p->photon_status == MCSTATUS_PURGE)
break;
/* exit loop if photon out of domain */
if (p->photon_status == MCSTATUS_OUTOFDOMAIN)
break;
} /* end while */
return 0;
}
/***********************************************************************************/
/* Function: free_albedo @62_30i@ */
/* Description: */
/* Free memory of struct albedo_struct. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void free_albedo (albedo_struct* albedo) {
switch (albedo->method) {
case MCALB_LAM2D:
for (int ia = 0; ia < albedo->Nx; ia++)
free (albedo->albedo2D[ia]);
free (albedo->albedo2D);
break;
case MCALB_ROSSLI2D:
for (int ix = 0; ix < albedo->Nx; ix++)
free (albedo->rossli2D[ix]);
free (albedo->rossli2D);
break;
case MCALB_RPV2D_SPECTRAL:
case MCALB_AMBRALS2D_SPECTRAL:
case MCALB_LAM2D_SPECTRAL:
// BM, 31.8.2020: General problem: Most of the albedo variables are now defined as "flat" (one-dimensional) arrays
// which need to be freed differently; needs to be checked for all other variables as well; the only way to find out
// is check how each field is allocated in wcloud3D.c
free_uchar_2D (albedo->surface_index);
free_int_1D (albedo->surface_count);
if (albedo->method == MCALB_LAM2D_SPECTRAL)
free (albedo->alb_type);
if (albedo->method == MCALB_RPV2D_SPECTRAL)
free (albedo->rpv);
if (albedo->method == MCALB_AMBRALS2D_SPECTRAL)
free (albedo->ambrals);
break;
default:
fprintf (stderr, "Error, unknown albedo->method %d\n", albedo->method);
}
free (albedo);
}
/***********************************************************************************/
/* Function: free_atmosphere @62_30i@ */
/* Description: */
/* Free memory of struct atmosphere_struct. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void free_atmosphere (atmosphere_struct* atmos) {
int ids = 0, iris = 0, ivs = 0, iv = 0, ic = 0, isp = 0;
free (atmos->X);
free (atmos->Y);
free (atmos->Z);
for (isp = 0; isp <= atmos->n_caoth; isp++)
free (atmos->threed[isp]);
free (atmos->threed);
if (atmos->ddis_eps != NULL)
free (atmos->ddis_eps);
free_profile (atmos->kabs);
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
free_profile (atmos->ksca[ids][iris]);
for (ids = 0; ids < atmos->nscaDS; ids++)
free (atmos->ksca[ids]);
free (atmos->ksca);
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
for (ivs = 0; ivs < atmos->nscaVIS; ivs++)
free_profile (atmos->kext[ids][iris][ivs]);
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
free (atmos->kext[ids][iris]);
for (ids = 0; ids < atmos->nscaDS; ids++)
free (atmos->kext[ids]);
free (atmos->kext);
free_profile (atmos->g1);
free_profile (atmos->g2);
free_profile (atmos->ff);
free_profile (atmos->reff);
free_profile3D (atmos->Bplanck);
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
free_profile3D (atmos->ksca3D[ids][iris]);
for (ids = 0; ids < atmos->nscaDS; ids++)
free (atmos->ksca3D[ids]);
free (atmos->ksca3D);
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
for (ivs = 0; ivs < atmos->nscaVIS; ivs++)
free_profile3D (atmos->kext3D[ids][iris][ivs]);
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
free (atmos->kext3D[ids][iris]);
for (ids = 0; ids < atmos->nscaDS; ids++)
free (atmos->kext3D[ids]);
free (atmos->kext3D);
free_profile3D (atmos->kabs3D);
free_profile3D (atmos->g1_3D);
free_profile3D (atmos->g2_3D);
free_profile3D (atmos->ff_3D);
free_profile3D (atmos->reff_3D);
#ifdef CLDPRP
if (atmos->sample_cldprp) {
free_profile3D (atmos->dxlwc_3D);
free_profile3D (atmos->dylwc_3D);
free_profile3D (atmos->dzlwc_3D);
}
#endif
/* FIXCE better to use sample->spectral_is as criterion CHECK!!! */
if (atmos->nlambda_abs > 1) {
free (atmos->lambda);
for (isp = 0; isp <= atmos->n_caoth; isp++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
free (atmos->kabs_spectral[isp][iv]);
free (atmos->ksca_spectral[isp][iv]);
}
free (atmos->kabs_spectral[isp]);
free (atmos->ksca_spectral[isp]);
}
free (atmos->kabs_spectral);
free (atmos->ksca_spectral);
for (iv = 0; iv < atmos->nlambda_abs; iv++)
free ((atmos->Bplanck_spectral)[iv]);
free (atmos->Bplanck_spectral);
}
if (atmos->Nc > 1) {
for (ic = 0; ic < atmos->Nc; ic++) {
free (atmos->kabs_scaled[ic]);
free (atmos->ksca_scaled[ic]);
}
free (atmos->kabs_scaled);
free (atmos->ksca_scaled);
}
}
/***********************************************************************************/
/* Function: free_result @62_30i@ */
/* Description: */
/* Free memory of struct result_struct. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void free_result (result_struct* result,
int thermal_heating_method,
atmosphere_struct* atmos,
sample_struct* sample,
int absorption) /* **CK 2013.09.23 added thermal_heating_method */
{
int is = 0, js = 0, kc = 0, ic = 0, il = 0, ip = 0;
/* free memory of result arrays */
free_radiation_field (result->surf, sample->Nx, sample->Nr, sample->Nd, sample->Ny, sample->std);
#if HAVE_LIDAR
if (sample->LidarLocEst)
free_lidar_result_field (result->lidar, sample->Nli, sample->LLE_Nt, sample->std);
#endif
if (sample->jacobian || sample->jacobian3D)
free_jacobian_result_field (result->jacobian);
/* CE: This should be moved to subroutine CHECK!!! */
if (sample->spectral_is || sample->concentration_is) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (is = 0; is < sample->Nx; is++) {
for (js = 0; js < sample->Ny; js++) {
for (ip = 0; ip < sample->nstokes; ip++) {
free (result->surf_t->rad_t[ic][is][js][ip]);
}
free (result->surf_t->rad_t[ic][is][js]);
}
free (result->surf_t->rad_t[ic][is]);
}
free (result->surf_t->rad_t[ic]);
}
free (result->surf_t->rad_t);
for (kc = 0; kc <= atmos->Nz; kc++) {
if (sample->sample[kc] != 0) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (is = 0; is < sample->Nx; is++) {
for (js = 0; js < sample->Ny; js++) {
for (ip = 0; ip < sample->nstokes; ip++) {
free (result->rad_t[kc]->rad_t[ic][is][js][ip]);
}
free (result->rad_t[kc]->rad_t[ic][is][js]);
}
free (result->rad_t[kc]->rad_t[ic][is]);
}
free (result->rad_t[kc]->rad_t[ic]);
}
free (result->rad_t[kc]->rad_t);
}
}
}
for (kc = 0; kc <= atmos->Nz; kc++)
if (sample->sample[kc] != 0)
free_radiation_field (result->alt[kc], sample->Nx, sample->Nr, sample->Nd, sample->Ny, sample->std);
free (result->alt);
if (sample->backward) {
for (is = 0; is < sample->Nx; is++) {
for (js = 0; js < sample->Ny; js++) {
free (result->back[is][js]);
free (result->back2[is][js]);
if (sample->backward == MCBACKWARD_HEAT) /* **CK 2013.09.23 */
if (thermal_heating_method == MCBACKWARD_HEAT_DENET || thermal_heating_method == MCBACKWARD_HEAT_HYBRID) {
free (result->back_dEnet[is][js]);
free (result->back_dEnet2[is][js]);
}
}
free (result->back[is]);
free (result->back2[is]);
free (result->backemis[is]);
if (sample->backward == MCBACKWARD_HEAT) /* **CK 2013.09.23 */
if (thermal_heating_method == MCBACKWARD_HEAT_DENET || thermal_heating_method == MCBACKWARD_HEAT_HYBRID) {
free (result->back_dEnet[is]);
free (result->back_dEnet2[is]);
}
}
free (result->back);
free (result->back2);
free (result->backemis);
if (sample->backward == MCBACKWARD_HEAT) /* **CK 2013.09.23 */
if (thermal_heating_method == MCBACKWARD_HEAT_DENET || thermal_heating_method == MCBACKWARD_HEAT_HYBRID) {
free (result->back_dEnet);
free (result->back_dEnet2);
}
if (sample->spectral_is || sample->concentration_is) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (is = 0; is < sample->Nx; is++) {
for (js = 0; js < sample->Ny; js++) {
for (ip = 0; ip < sample->nstokes; ip++) {
free (result->back_t[ic][is][js][ip]);
}
free (result->back_t[ic][is][js]);
}
free (result->back_t[ic][is]);
}
free (result->back_t[ic]);
}
free (result->back_t);
}
}
if (absorption) {
free_ddprofile3D (result->absorption3D);
if (sample->std)
free_ddprofile3D (result->absorption3D2);
}
if (sample->boxairmass)
ASCII_free_double_3D (result->pathlength_per_layer_tot, sample->Nx, sample->Ny);
else if (sample->boxairmass3D)
ASCII_free_double_5D (result->pathlength_per_box_tot, sample->Nx, sample->Ny, atmos->Nx, atmos->Ny);
if (sample->ncirc) {
/* QUICK FIX*/
for (il = 0; il < 10; il++)
free (result->circcontr[il]);
free (result->circcontr);
}
free (result->mish);
#if HAVE_LIDAR
free (result->lidcb);
#endif
free (result);
}
/***********************************************************************************/
/* Function: setup_mystic @62_30i@ */
/* Description: */
/* Allocate memory, create and initialize 1D and 3D arrays, etc. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int setup_mystic (caoth3d_out_struct* caoth3d,
atmosphere_struct* atmos,
result_struct* result,
albedo_struct* albedo,
surftemp_struct* surftemp,
sample_struct* sample,
float delta_scaling_mucut,
int absorption,
int thermal_heating_method,
int nlyr,
int* threed,
int n_caoth,
float** dt_s,
float** om_s,
float** g1_s,
float** g2_s,
float** f_s,
float** ds_s,
alis_struct* alis,
float rayleigh_depol,
float** re_s,
float*** temper,
int temper3d,
float* zprof,
float* sza,
float* phi0,
float sza_spher,
float phi0_spher,
int aerosol_scatter_type,
float*** momaer,
int* nmomaer,
int** nthetaaer,
float*** thetaaer,
double*** muaer,
float*** phaseaer,
int nphamataer,
float alb,
float* alb_type,
float* rpv_rho0,
float* rpv_k,
float* rpv_theta,
float* rpv_scale,
float* rpv_sigma,
float* rpv_t1,
float* rpv_t2,
float* hapke_h,
float* hapke_b0,
float* hapke_w,
float* rossli_iso,
float* rossli_vol,
float* rossli_geo,
int rossli_hotspot,
float* u10,
float* pcl,
float* xsal,
float* uphi,
int* solar_wind,
float* bpdf_u10,
int source,
float* wvnmlo,
float* wvnmhi,
float* wavelength,
float* zout,
int nzout,
int nxcld,
int nycld,
int nzcld,
double dxcld,
double dycld,
char* umufilename,
char* sunshape_filename,
char* albedo_filename,
char* ambralsfilename,
char* rosslifilename,
char* alb_type_filename,
char* rpv_type_filename,
char* ambrals_type_filename,
char** surface_labels,
int surface_nlabels,
double truncate,
int loaddata,
char* datapath,
double r_earth,
int visualize,
t_triangular_surface* triangular_surface,
t_triangle_radiation_field* triangle_results,
int quiet,
long int nphotons) /* **CK 2013.08.27 Added nphotons */
{
int status = 0;
int doddis = 0;
int isp = 0;
int ispo = 0;
int isAmbralsFile = 0;
if (sample->spherical3D) {
*sza = 90.0 - sza_spher;
*phi0 = -90.0 - phi0_spher;
}
/* define dimensions of scatter profiles concerning different scatter modes */
atmos->nscaDS = MCSC_MODE_NORMAL + 1;
if (sample->delta_scaling != -1)
atmos->nscaDS = MCSC_MODE_DELTA_SCALE + 1;
/* define dimensions of scatter profiles concerning different RIS modes */
atmos->nscaRIS = MCRIS_MODE_NORMAL + 1;
#if HAVE_LIDAR
if (sample->LLE_RIS_MAS || sample->RIS_MS)
atmos->nscaRIS = MCRIS_MODE_MAS + 1;
#ifdef NEWRISQIDD
atmos->nscaRIS++;
#endif
#endif
/* define dimensions of scatter profiles concerning different VIS modes */
atmos->nscaVIS = MCVIS_MODE_NORMAL + 1;
#if HAVE_LIDAR
if (sample->LLE_VIS_QIDD)
atmos->nscaVIS = MCVIS_MODE_QIDD + 1;
#endif
/* Rayleigh depolarisation */
atmos->rayleigh_depol = rayleigh_depol;
status = setup_profiles1D (n_caoth, dt_s, om_s, g1_s, g2_s, f_s, ds_s, re_s, zprof, nlyr, sample, atmos, alis);
if (status != 0)
return err_out ("Error %d returned by setup_profiles1D()\n", status);
if (!quiet)
fprintf (stderr, " ... setting up 3D grid\n");
status = setup_caoth3D (caoth3d,
nxcld,
nycld,
nzcld,
threed,
dxcld,
dycld,
*wavelength,
atmos,
datapath,
sample->delta_scaling,
sample->spherical3D,
sample->spherical3D_scene,
sample->spherical3D_scene_lon_min,
sample->spherical3D_scene_lon_max,
sample->spherical3D_scene_lat_min,
sample->spherical3D_scene_lat_max,
r_earth,
*sza,
sample->tipadir,
visualize,
sample->cldprp,
quiet);
if (status != 0)
return err_out ("Error %d returned by setup_caoth3D()\n", status);
/* read sampling information */
status = setup_sample2D (atmos, zout, nzout, sza, phi0, wavelength, sample, quiet);
if (status != 0)
return err_out ("Error %d returned by setup_sample2D()\n", status);
if (loaddata) {
if (strlen (umufilename) != 0) {
/* setup umu data */
status = setup_umu2D (umufilename, sample, atmos, quiet);
if (status != 0)
return err_out ("Error %d returned by read_2D_umu()\n", status);
}
/* Check if either a sunshape file or a sun radius is given, Bernhard Reinhardt */
if ((strlen (sunshape_filename) != 0) || (sample->sun_radius > 0.0)) {
status = setup_sunshape (sample, sunshape_filename, *wvnmlo, *wvnmhi);
if (status != 0)
return err_out ("Error %d returned by setup_sunshape()\n", status);
}
/* setup albedo data */
if (*albedo_filename)
strcpy (albedo->filename, albedo_filename);
if (*alb_type_filename)
strcpy (albedo->spectral_albedo_filename, alb_type_filename);
if (*rpv_type_filename)
strcpy (albedo->spectral_rpv_filename, rpv_type_filename);
if (*ambrals_type_filename) {
isAmbralsFile = 1;
strcpy (albedo->spectral_ambrals_filename, ambrals_type_filename);
}
if (*rosslifilename)
strcpy (albedo->rossli_filename, rosslifilename);
if (*ambralsfilename) {
isAmbralsFile = 1;
strcpy (albedo->rossli_filename, ambralsfilename);
}
if (!quiet) {
switch (albedo->method) {
case MCALB_LAM:
fprintf (stderr, " ... homogeneous Lambertian surface albedo\n");
break;
case MCALB_LAM2D:
fprintf (stderr, " ... reading 2D albedo data from %s\n", albedo->filename);
break;
case MCALB_LAM2D_SPECTRAL:
fprintf (stderr, " ... reading 2D albedo data from %s\n", albedo->spectral_albedo_filename);
break;
case MCALB_RPV:
fprintf (stderr, " ... homogeneous RPV BRDF\n");
break;
case MCALB_RPV2D_SPECTRAL:
fprintf (stderr, " ... reading RPV BRDF from %s\n", albedo->spectral_rpv_filename);
break;
case MCALB_AMBRALS2D_SPECTRAL:
fprintf (stderr, " ... reading AMBRALS BRDF from %s\n", albedo->spectral_ambrals_filename);
break;
case MCALB_COXANDMUNK:
fprintf (stderr, " ... homogeneous Cox and Munk ocean BRDF\n");
break;
case MCALB_HAPKE:
fprintf (stderr, " ... homogeneous Hapke BRDF\n");
break;
case MCALB_ROSSLI:
fprintf (stderr, " ... homogeneous Ross-Li BRDF\n");
break;
case MCALB_ROSSLI2D:
fprintf (stderr, " ... reading Ross-Li BRDF from %s\n", albedo->rossli_filename);
if (isAmbralsFile)
fprintf (stderr, " ... using AMBRALS (Lucht2000) implementation of Ross-Li\n");
else
fprintf (stderr, " ... using Lin(2015) implementation of Ross-Li\n");
break;
case MCALB_TSANG:
fprintf (stderr, " ... homogeneous Tsang ocean BPDF\n");
break;
default:
fprintf (stderr, "Fatal error, unknown albedo type %d\n", albedo->method);
break;
}
}
status = setup_albedo2D (albedo->filename,
albedo->rossli_filename,
albedo->spectral_albedo_filename,
albedo->spectral_rpv_filename,
albedo->spectral_ambrals_filename,
isAmbralsFile,
atmos,
albedo,
alb,
alb_type,
rpv_rho0,
rpv_k,
rpv_theta,
rpv_scale,
rpv_sigma,
rpv_t1,
rpv_t2,
surface_labels,
surface_nlabels,
hapke_h,
hapke_b0,
hapke_w,
rossli_iso,
rossli_vol,
rossli_geo,
rossli_hotspot,
*u10,
*pcl,
*xsal,
*uphi,
*solar_wind,
*bpdf_u10,
sample->polarisation,
sample->spherical3D,
sample->spherical3D_scene,
sample->spherical3D_scene_lon_min,
sample->spherical3D_scene_lon_max,
sample->spherical3D_scene_lat_min,
sample->spherical3D_scene_lat_max,
alis->nlambda_abs,
alis->albedo,
alis->alb_type,
sample->ixmin,
sample->ixmax,
sample->iymin,
sample->iymax,
quiet);
if (status)
return err_out ("Error %d returned by setup_albedo2D()\n", status);
} /* endif loaddata */
/* formerly, the aerosol setup was performed only if loaddata */
/* now, phase_aer etc. is deallocated at the end of MYSTIC, so */
/* at the next call, the aerosol must always be setup! */
/* As soon as MCSCAT_AER has been merged with CAOTH, all this will be */
/* obsolete */
if (atmos->tscatot[MCCAOTH_AER] > 0.0)
atmos->scatter_type[MCCAOTH_AER] = aerosol_scatter_type;
else
atmos->scatter_type[MCCAOTH_AER] = MCSCAT_SKIP;
if (atmos->scatter_type[MCCAOTH_AER] == MCSCAT_AER) {
status = setup_aerosol1D (&(atmos->phase_aer),
nlyr,
dt_s[CAOTH_AER],
om_s[CAOTH_AER],
momaer,
nmomaer,
nthetaaer,
muaer,
phaseaer,
nphamataer,
truncate,
quiet);
if (status)
return err_out ("Error %d returned by setup_aerosol1D()\n", status);
}
#if HAVE_VROOM
/* following should be standing somewhere else !!! */
for (isp = MCCAOTH_AER; isp <= atmos->n_caoth; isp++) /* molecular should not be tested here */
/* doddis is only zero if pure rayleigh and no scattering in any other caoth */
if (atmos->tscatot[isp] > 0.0)
doddis++;
else {
ispo = isp - MCCAOTH_FIR;
if (ispo >= 0)
if (caoth3d[ispo].nthreed >= 1)
doddis++;
}
/* prepare vroom, in particular define representative phase function */
if (sample->vroom != 0 || sample->LidarLocEst) {
status = mc_vroom_prepare (sample, atmos, delta_scaling_mucut, nlyr, atmos->tscatot[MCCAOTH_AER] > 0.0, quiet);
if (status != 0)
return err_out ("Error %d returned by mc_vroom_prepare()\n", status);
}
if (!sample->LidarLocEst) {
status = set_vroom_settings (sample->vroom, sample, quiet);
if (status != 0)
return err_out ("Error %d returned by set_vroom_settings()\n", status);
}
/* if vroom then enforce reflectalways */
if (sample->vroomreflectalways)
albedo->reflectalways = 1;
status = mc_vroom_check_and_verbose (sample, quiet, doddis);
if (status != 0)
return err_out ("Error, mc_vroom_check_and_verbose returned status %d\n", status);
#endif
status = setup_mc_result (atmos, sample, triangle_results, result, absorption, thermal_heating_method, quiet);
if (status != 0)
return err_out ("Error %d returned by setup_mc_result()\n", status);
/* calculate energy emitted from the surface */
status = calc_surface_emission (albedo, source, surftemp->btemp, wvnmlo, wvnmhi, &(albedo->bplkavg), &(albedo->Wsurf));
if (status)
return err_out ("Error %d returned by calc_surface_emission()\n", status);
status = setup_thermal (temper,
temper3d,
atmos->Nx,
atmos->Ny,
atmos->Nz,
*wvnmlo,
*wvnmhi,
atmos->kabs,
atmos->kabs3D,
atmos->Z,
source,
absorption,
thermal_heating_method,
&(atmos->Bplanck),
&(atmos->maxemis),
&(atmos->Watm),
surftemp,
sample->backward,
sample->zstart,
&(sample->backemis_kc),
alis->nlambda_abs,
alis->lambda,
&(atmos->Bplanck_spectral),
triangular_surface,
quiet,
nphotons,
sample); /* **CK 2013.08.27 Added nphotons and sample; added atmos->Nx, atmos->Ny */
if (status != 0)
return err_out ("Error %d returned by setup_thermal()\n", status);
#if HAVE_LIDAR
check_lidar_in_atmos (sample, atmos);
if (status != 0)
return err_out ("Error %d returned by check_lidar_in_atmos()\n", status);
#endif
return 0;
}
/***********************************************************************************/
/* Function: setup_sunshape @62_30i@ */
/* Description: */
/* Setup sunshape. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int setup_sunshape (sample_struct* sample, char* filename, float wvnmlo, float wvnmhi) {
double sunshape_norm_factor = 0.0;
double** mu_new = NULL;
float* temp = NULL;
int i = 0, status = 0;
/* Use default spectral sunshape if sunshape filename is "default" or not specified */
if (strcmp ("default", filename) == 0 || strcmp ("", filename) == 0) {
sample->sample_backward_sunshape_n_lines = 200;
sample->sample_backward_sunshape_p = (float*)calloc (sample->sample_backward_sunshape_n_lines, sizeof (float));
sample->sample_backward_sunshape_alpha = (double*)calloc (sample->sample_backward_sunshape_n_lines, sizeof (double));
sample->sample_backward_sunshape_F = (double*)calloc (sample->sample_backward_sunshape_n_lines, sizeof (double));
/* generate spectral sunshape according to Koepke2001 */
gen_default_sunshape (wvnmlo,
wvnmhi,
sample->sample_backward_sunshape_n_lines,
sample->sample_backward_sunshape_p,
sample->sample_backward_sunshape_alpha);
} else {
/* Read sun shape file, Bernhard Reinhardt */
/* Do a first read of the sun shape file. This is to allocate sunshape_F */
/* and to read alpha as doubles. */
status = read_2c_file (filename,
&sample->sample_backward_sunshape_F,
&sample->sample_backward_sunshape_alpha,
&sample->sample_backward_sunshape_n_lines);
if (status != 0)
return err_out ("Error %d returned by read_2c_file() when reading sun shape input file\n", status);
/* Now do a second read to get p as float. we read the second */
/* column as float into temp to throw it away */
status = read_2c_file_float (filename, &sample->sample_backward_sunshape_p, &temp, &sample->sample_backward_sunshape_n_lines);
if (status != 0)
return err_out ("Error %d returned by read_2c_file_float() when reading sun shape input file\n", status);
free (temp);
}
/* Now we have either read in or generated a sun shape. Let??s do */
/* some postprocessing */
sample->sample_backward_sunshape = 1;
sample->sample_backward_sunshape_p2 = (float*)calloc (sample->sample_backward_sunshape_n_lines, sizeof (float));
status = ASCII_calloc_double (&mu_new, 1, sample->sample_backward_sunshape_n_lines);
/* We need the temp variable mu_new in matrix notation to call */
/* normalize_phase. Weight the PDF (sunshape_p2) with sine to */
/* make sure that we do not send to many photons to the center */
/* of the sun. sunshape_F is the cumulative distribution */
/* function of sunshape_p2. sunshape_F is used in the routines */
/* for the diffuse radiation, while direct radiation is computed */
/* using sunshape_p (not weighted with sine) */
for (i = 0; i < sample->sample_backward_sunshape_n_lines; i++) {
mu_new[0][i] = sample->sample_backward_sunshape_alpha[i];
sample->sample_backward_sunshape_p2[i] = sample->sample_backward_sunshape_p[i];
sample->sample_backward_sunshape_p2[i] *= sind (sample->sample_backward_sunshape_alpha[i] * sample->sun_radius);
}
normalize_phase (mu_new,
&sample->sample_backward_sunshape_p2,
sample->sample_backward_sunshape_F,
&sample->sample_backward_sunshape_n_lines,
1,
0);
/*normalize to 1 instead of 2 */
for (i = 0; i < sample->sample_backward_sunshape_n_lines; i++) {
sample->sample_backward_sunshape_F[i] /= 2.0;
}
/* sunshape_norm_factor is the normalizing factor for the */
/* sunshape pdf. It is calculated as */
/* integral(sin(theta))_0..sunrad / */
/* integral(p(theta)*sin(theta))_0..sunrad. This works probably */
/* only for geometric distribution of the photons */
/* First calc the denominator of the term: */
for (i = 1; i < sample->sample_backward_sunshape_n_lines; i++) {
sunshape_norm_factor += (cosd (sample->sample_backward_sunshape_alpha[i - 1] * sample->sun_radius) -
cosd (sample->sample_backward_sunshape_alpha[i] * sample->sun_radius)) *
(sample->sample_backward_sunshape_p[i] + sample->sample_backward_sunshape_p[i - 1]) / 2.;
}
/* Now the numerator. Here the integral is easy to solve: */
sunshape_norm_factor = (1. - cosd (sample->sun_radius)) / sunshape_norm_factor;
for (i = 0; i < sample->sample_backward_sunshape_n_lines; i++) {
sample->sample_backward_sunshape_p[i] *= sunshape_norm_factor;
}
ASCII_free_double (mu_new, 1);
/* calculate sunshape slope */
sample->sample_backward_sunshape_slope = (double*)calloc (sample->sample_backward_sunshape_n_lines - 1, sizeof (double));
for (i = 0; i < sample->sample_backward_sunshape_n_lines - 1; i++)
sample->sample_backward_sunshape_slope[i] =
(sample->sample_backward_sunshape_p[i + 1] - sample->sample_backward_sunshape_p[i]) /
(sample->sample_backward_sunshape_alpha[i + 1] - sample->sample_backward_sunshape_alpha[i]);
return 0;
}
/***********************************************************************************/
/* Function: calc_surface_emission @62_30i@ */
/* Description: */
/* Calculate albedo->bplkavg and albedo->Wsurf */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static inline int calc_surface_emission (albedo_struct* albedo,
int source,
float btemp,
float* wvnmlo,
float* wvnmhi,
float* bplkavg,
double* Wsurf) {
double avg_albedo = 0.0;
int ia = 0, ja = 0;
/* calculate Planck emission for surface temperature */
switch (source) {
case MCSRC_THERMAL_SURFACE:
switch (albedo->method) {
case MCALB_LAM2D:
case MCALB_LAM2D_SPECTRAL:
/* ??? need to check if this averaging procedure gives correct results ??? CHECK!!! */
if (albedo->method == MCALB_LAM2D) {
avg_albedo = 0;
for (ia = 0; ia < albedo->Nx; ia++)
for (ja = 0; ja < albedo->Ny; ja++) {
if (albedo->method == MCALB_LAM2D)
avg_albedo += albedo->albedo2D[ia][ja];
else
avg_albedo += albedo->alb_type[(int)albedo->surface_index[ia][ja]];
}
avg_albedo /= (double)(albedo->Nx * albedo->Ny);
}
break;
case MCALB_LAM:
avg_albedo = albedo->albedo;
break;
case MCALB_RPV:
case MCALB_RPV2D_SPECTRAL:
case MCALB_AMBRALS2D_SPECTRAL:
case MCALB_COXANDMUNK:
case MCALB_HAPKE:
case MCALB_ROSSLI:
case MCALB_ROSSLI2D:
fprintf (stderr, "**** hmm, bi-directional reflectance specified together\n");
fprintf (stderr, "**** with thermal source; ignoring BRDF and using albedo %g\n", albedo->albedo);
fprintf (stderr, "**** instead!\n");
return -1;
default:
fprintf (stderr, "Error, albedo->method %d not yet implemented!\n", albedo->method);
return -1;
}
/* no break */
case MCSRC_THERMAL_ATMOSPHERE:
case MCSRC_THERMAL_BACKWARD:
if (btemp > 0) /* F77_FUNC (cplkavg, CPLKAVG) (wvnmlo, wvnmhi, &btemp, bplkavg); */
*bplkavg = c_planck_func1 (*wvnmlo, *wvnmhi, btemp);
else
*bplkavg = 0;
if (source == MCSRC_THERMAL_SURFACE)
*Wsurf = PI * (1.0 - avg_albedo) * *bplkavg;
break;
case MCSRC_NONE:
case MCSRC_SOLAR:
case MCSRC_LIDAR:
case MCSRC_BLITZ:
break;
default:
fprintf (stderr, "Error, unknown source %d\n", source);
}
return 0;
}
/***********************************************************************************/
/* Function: setup_aerosol1D @62_30i@ */
/* Description: */
/* Setup the structures for 1D aerosols. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
static inline int setup_aerosol1D (pft** phase_aer,
int nlyr,
float* dtaer,
float* omaer,
float*** momaer,
int* nmomaer,
int** nthetaaer,
double*** muaer,
float*** phaseaer,
int nphamataer,
double truncate,
int quiet) {
int sumphases = 0, kc = 0, i = 0, ip = 0, status = 0;
double** moment;
/* aerosol phase function table CHECK!!! */
/* ??? this is not a good solution; the phase function table is */
/* ??? calculated separately for each layer, although it is */
/* ??? very likely that several layers use the same table; */
/* ??? how to improve: */
/* ??? read each phase function file only once in aerosol.c, */
/* ??? read_optprop_files(); create table that stores */
/* ??? the different moment arrays and an index table that */
/* ??? just stores which array is to be used for each layer */
/* ??? (similar to the handling of 2D BRDFs */
(*phase_aer) = calloc (nlyr, sizeof (pft));
for (kc = 0; kc < nlyr; kc++)
sumphases += nthetaaer[kc][0];
if (!sumphases) {
for (kc = 0; kc < nlyr; kc++) {
if (dtaer[kc] > 0.0) {
moment = calloc (nphamataer, sizeof (double*));
for (ip = 0; ip < nphamataer; ip++) {
moment[ip] = calloc ((size_t)nmomaer[kc], sizeof (double));
for (i = 0; i < nmomaer[kc]; i++)
moment[ip][i] = momaer[kc][ip][i];
}
if (!quiet)
fprintf (stderr,
" ... creating aerosol scattering table for layer %d, using %d moments, phase matrix elements %d\n",
kc,
nmomaer[kc],
nphamataer);
status = setup_Legendre_table_aerosol (moment, nmomaer[kc], nphamataer, truncate, &((*phase_aer)[kc]), quiet);
if (status != 0)
return err_out ("Error %d returned by setup_Legendre_table_aerosol()\n", status);
for (ip = 0; ip < nphamataer; ip++)
free (moment[ip]);
free (moment);
}
}
} else {
for (kc = 0; kc < nlyr; kc++)
if (dtaer[kc] > 0.0) {
/* calculate cumulative table */
status =
calc_cumulative_table (muaer[kc], phaseaer[kc], nthetaaer[kc], nphamataer, truncate, &((*phase_aer)[kc]), -999.99, quiet);
if (status != 0)
return err_out ("Error %d returned by calc_cumulative_table()\n", status);
}
}
return 0;
}
/***********************************************************************************/
/* Function: free_mystic_for_load @62_30i@ */
/* Description: */
/* Free the MYSTIC memory structures. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void free_mystic_for_load (albedo_struct* albedo) {
switch (albedo->method) {
case MCALB_LAM:
/*??????????????????????????
CE: Moved up MCALB_LAM2D, because free_albedo causes segmentation fault, when mc_albedo_file is used and more than 1 wavelength is calculated.
Not sure, whether this is correct or not, needs to be checked! */
case MCALB_LAM2D:
case MCALB_RPV:
case MCALB_HAPKE:
case MCALB_ROSSLI:
case MCALB_TSANG:
case MCALB_COXANDMUNK:
/* don't need to do anything because 1D albedo */
break;
case MCALB_RPV2D_SPECTRAL:
case MCALB_AMBRALS2D_SPECTRAL:
case MCALB_LAM2D_SPECTRAL:
case MCALB_ROSSLI2D:
free_albedo (albedo);
break;
default:
fprintf (stderr, "Fatal error, unknown albedo type %d\n", albedo->method);
break;
}
/* ?????????? CHECK!!!
if (nonHGaer)
for (kc=0; kc<nlyr; kc++)
free_pft (phase_aer[kc]);
?????????? */
}
/***********************************************************************************/
/* Function: sc_Isotropic_phi @62_30i@ */
/* Description: */
/* Calculate a random azimuth angle for an azimutally isotropic phase function. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
double sc_Isotropic_phi() {
return 360.0 * uvspec_random();
}
/***********************************************************************************/
/* Function: sc_Rayleigh_mu @62_30i@ */
/* Description: */
/* Calculate a random scattering angle for the Rayleigh phase function. */
/* Effect of depolarization is not included, see sc_Rayleigh_mu_depol() */
/* Returns mu=cos(theta), for more speed! */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
double sc_Rayleigh_mu() {
double P = uvspec_random();
double q = 8.0 * P - 4.0;
/* ??? cbrt() is a GNU extension ??? CHECK!!! */
double u = cbrt (-q / 2.0 + sqrt (1.0 + q * q / 4.0));
double v = -1.0 / u;
double mu = u + v;
/* ATTENTION: No error check, but very rude correction */
if (mu > 1.0) {
if (mu > 1.0 + MC_EPSILON) {
fprintf (stderr, "Error! mu = %e in sc_Rayleigh_mu() is unphysical!\n", mu);
return NOT_A_NUMBER;
}
mu = 1.0;
}
if (mu < -1.0) {
if (mu < -1.0 - MC_EPSILON) {
fprintf (stderr, "Error! mu = %e in sc_Rayleigh_mu() is unphysical!\n", mu);
return NOT_A_NUMBER;
}
mu = -1.0;
}
return mu;
}
/***********************************************************************************/
/* Function: sc_Rayleigh_mu_depol @62_30i@ */
/* Description: */
/* Calculate a random scattering angle for the Rayleigh phase function */
/* including depolarisation. */
/* Returns mu=cos(theta), for more speed! */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
double sc_Rayleigh_mu_depol (double depol) {
double gamma = depol / (2.0 - depol);
double P = uvspec_random();
double p = (3.0 * gamma + 1.0) / (1.0 - gamma);
double q = (1.0 + 2.0 * gamma) / (1.0 - gamma) * (2.0 - 4.0 * P);
double D = sqrt (q * q + p * p * p);
/* ??? cbrt() is a GNU extension ??? CHECK!!! */
double u = cbrt (-q + D);
double v = -p / u;
double mu = u + v;
/* ATTENTION: No error check, but very rude correction */
if (mu > 1.0) {
if (mu > 1.0 + MC_EPSILON) {
fprintf (stderr, "Error! mu = %e in sc_Rayleigh_mu_depol() is unphysical!\n", mu);
return NOT_A_NUMBER;
}
mu = 1.0;
}
if (mu < -1.0) {
if (mu < -1.0 - MC_EPSILON) {
fprintf (stderr, "Error! mu = %e in sc_Rayleigh_mu_depol() is unphysical!\n", mu);
return NOT_A_NUMBER;
}
mu = -1.0;
}
return mu;
}
/***********************************************************************************/
/* Function: sc_Isotropic_mu @62_30i@ */
/* Description: */
/* Calculate a random scattering angle for an isotropic phase function. */
/* Returns mu=cos(theta), for more speed! */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
inline double sc_Isotropic_mu() {
double P = uvspec_random();
return (1.0 - 2.0 * P);
}
/***********************************************************************************/
/* Function: sc_Isotropic_upward_mu @62_30i@ */
/* Description: */
/* Calculate an upward random scattering angle for an isotropic phase function. */
/* Returns mu=cos(theta), for more speed! */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static inline double sc_Isotropic_upward_mu() {
return uvspec_random();
}
/***********************************************************************************/
/* Function: sc_Isotropic_downward_mu @62_30i@ */
/* Description: */
/* Calculate a downward random scattering angle for an isotropic phase function. */
/* Returns mu=cos(theta), for more speed! */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static inline double sc_Isotropic_downward_mu() {
return -uvspec_random();
}
/***********************************************************************************/
/* Function: sc_Lambertian_mu @62_30i@ */
/* Description: */
/* Calculate a random polar angle for a Lambertian source. */
/* Returns mu=cos(theta), for more speed! */
/* Is not exactly equivalent to old version, should be sqrt(1-P) for exact equiv */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
inline double sc_Lambertian_mu() {
double P = uvspec_random();
return sqrt (P); /* would be equivalent to old version if sqrt(1-P) */
}
/***********************************************************************************/
/* Function: sc_HG_mu @62_30i@ */
/* Description: */
/* Calculate a random polar angle for the Henyey-Greenstein phase function. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
double sc_HG_mu (double g) {
double P = uvspec_random();
double mu = 0.0;
/* ATTENTION: No error check, but very rude correction */
if (g < -1.0) {
fprintf (stderr, " ... g = %g out of range, setting to -1\n", g);
g = -1;
}
if (g > 1.0) {
fprintf (stderr, " ... g = %g out of range, setting to 1\n", g);
g = 1;
}
if (g == 0)
mu = 1.0 - 2.0 * P;
else
mu = 1.0 / 2.0 / g * (1.0 + g * g - (g * g - 1.0) * (g * g - 1.0) / ((2.0 * g * P - g - 1.0) * (2.0 * g * P - g - 1.0)));
/* ATTENTION: No error check, but very rude correction */
if (mu > 1.0) {
if (mu > 1.0 + MC_EPSILON) {
fprintf (stderr, "Error! mu = %e in sc_HG_mu() is unphysical!\n", mu);
return NOT_A_NUMBER;
}
mu = 1.0;
}
if (mu < -1.0) {
if (mu < -1.0 - MC_EPSILON) {
fprintf (stderr, "Error! mu = %e in sc_HG_mu() is unphysical!\n", mu);
return NOT_A_NUMBER;
}
mu = -1.0;
}
return mu;
}
/***********************************************************************************/
/* Function: HG @62_30i@ */
/* Description: */
/* Evaluate the Henyey-Greenstein phase function at cosine of polar angle */
/* mu = cos(theta) for asymmetry parameter g. The phase function */
/* p(mu) = p(cos(theta)) is normalized to 2. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static double HG (double g, double mu) {
double temp = 1.0 + g * g - 2.0 * g * mu;
return (1.0 - g * g) / (temp * sqrt (temp));
}
/***********************************************************************************/
/* Function: HG2 @62_30i@ */
/* Description: */
/* Evaluate the double-Henyey-Greenstein phase function at cosine of polar angle */
/* mu = cos(theta) for asymmetry parameter g. The phase function */
/* p(mu) = p(cos(theta)) is normalized to 2. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static double HG2 (double g1, double g2, double ff, double mu) {
return ff * HG (g1, mu) + (1.0 - ff) * HG (g2, mu);
}
/***********************************************************************************/
/* Function: setup_Legendre_table_aerosol @62_30i@ */
/* Description: */
/* Calculate lookup-tables of the cumulative probability distribution and the */
/* phase function from the moments of the phase function */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int setup_Legendre_table_aerosol (double** moment, int nmom, int nphamat, double truncate, pft* phase, int quiet) {
int status = 0, ip = 0;
double** mu;
float** p;
int* n;
/* calculate phase function p(mu) */
status = calc_Legendre_phase (moment, nmom, nphamat, &mu, &p, &n);
if (status != 0)
return err_out ("Error %d returned by calc_Legendre_phase()\n", status);
/* calculate cumulative table */
status = calc_cumulative_table (mu, p, n, nphamat, truncate, phase, -999.99, quiet); /*TZ ds: no delta-scaling for aerosol*/
if (status != 0)
return err_out ("Error %d returned by calc_cumulative_table()\n", status);
for (ip = 0; ip < nphamat; ip++) {
free (mu[ip]);
free (p[ip]);
}
free (mu);
free (p);
free (n);
return 0;
}
/***********************************************************************************/
/* Function: get_F @62_30i@ */
/* Description: */
/* Extract the integrated phase function for a given polar angle mu from a */
/* phase function table. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
double get_F (pft* iphase, double mu, int scaled) {
int it = 0, ip = 0;
double F = 0;
/* if inside the truncation range */
if (iphase->truncate && mu > iphase->mutrnc) {
fprintf (stderr, "ERROR! truncate not implemented for get_F!\n");
return NOT_A_NUMBER;
}
/* make sure that mu is physical, this should be checked directly at mu calculation site! */
/* if (mu > 1.0) mu=1.0;
if (mu < -1.0) mu=-1.0;
*/
ip = 0;
if (iphase->is_linear) {
/* this is a new version of getting it, it is much quicker, but less precise, CHECK */
it = (int)((acos (mu) - iphase->theta_0) * iphase->dthetainv);
/* careful with rounding errors at the array boundaries */
if (it > iphase->n[ip] - 1 || it < 0) {
fprintf (stderr, "ERROR! mu is outside delta-scaled phasetable! Probably only infinitesimally, fix this in get_F\n");
fprintf (stderr,
"it %d nit %d mu %e rit %e \n",
it,
iphase->n[ip] - 1,
mu,
((acos (mu) - iphase->theta_0) * iphase->dthetainv));
return NOT_A_NUMBER;
}
} else
it = locate (iphase->mu[ip], iphase->n[ip], mu);
if (it == iphase->n[ip] - 1)
F = iphase->F[scaled][iphase->n[ip] - 1];
else
/* bug fix, old version was unstable for spiky phase functions */
F = iphase->F[scaled][it] + iphase->p[scaled][0][it] * (mu - iphase->mu[scaled][it]) +
iphase->A[scaled][it] * (mu - iphase->mu[scaled][it]) * (mu - iphase->mu[scaled][it]);
/* F = iphase->C[scaled][it] + mu * iphase->B[scaled][it] + mu * mu *
iphase->A[scaled][it]; */
if (F < 0.0)
F = 0.0;
return F;
}
/***********************************************************************************/
/* Function: get_Lambertian_phase @62_30i@ */
/* Description: */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static inline double get_Lambertian_phase (double mu) {
return 4. * mu;
}
/***********************************************************************************/
/* Function: sc_mu @62_30i@ */
/* Description: */
/* Calculate a random scattering angle mu = cos(theta) using a pre-calculated */
/* table, see description of calc_cumulative_table(). If newrand is TRUE, a new */
/* random number is selected, otherwise the old one is recycled. CAREFUL: THIS */
/* FUNCTION IS NOT THREAD-SAFE AS IT STORES THE RANDOM NUMBER LOCALLY! */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
double sc_mu (pft* iphase, int newrand, int scaled, double F_max, double F_min) {
int it = 0;
double mu = 0.0, mu1 = 0.0, mu2 = 0.0, d = 0.0, norm = 2.0;
static double U = 0;
/* limit F to within F_min and F_max */
if (F_max != 0.0)
norm = F_max - F_min;
if (newrand != 0)
U = norm * uvspec_random() + F_min;
it = locate (iphase->F[scaled], iphase->n[0], U);
/* special case: forward peak */
if (it == iphase->n[0] - 1)
return 1.0;
/* special case: phase function constant within interval */
if (iphase->A[scaled][it] == 0)
return (U - iphase->C[scaled][it]) / iphase->B[scaled][it];
/* CE 20100705: This calculation for d is unstable for plates CHECK!!! */
/* d = sqrt(iphase->B[scaled][it]*iphase->B[scaled][it] */
/* -4.0*iphase->A[scaled][it]*(iphase->C[scaled][it]-U)); */
/* CE: The following seems to be more stable */
d = sqrt (iphase->p[scaled][0][it] * iphase->p[scaled][0][it] - 4. * iphase->A[scaled][it] * (iphase->F[scaled][it] - U));
if (iphase->B[scaled][it] < 0.0) {
mu1 = (2.0 * (iphase->C[scaled][it] - U)) / (-iphase->B[scaled][it] + d);
mu2 = (-iphase->B[scaled][it] + d) / (2.0 * iphase->A[scaled][it]);
} else {
mu1 = (-iphase->B[scaled][it] - d) / (2.0 * iphase->A[scaled][it]);
mu2 = (2.0 * (iphase->C[scaled][it] - U)) / (-iphase->B[scaled][it] - d);
}
if (iphase->p[scaled][0][it] < iphase->p[scaled][0][it + 1])
mu = (mu1 > mu2 ? mu1 : mu2);
else
mu = (mu1 < mu2 ? mu1 : mu2);
if (mu > 1.0) {
if (mu > 1.0 + MC_EPSILON) {
fprintf (stderr, "Error! mu= %e in sc_mu() is unphysical!\n", mu);
return NOT_A_NUMBER;
}
/* fprintf (stderr, " ... sc_mu(): cutting mu=%f to 1\n", mu); */
mu = 1.0;
}
if (mu < -1.0) {
if (mu < -1.0 - MC_EPSILON) {
fprintf (stderr, "Error! mu= %e in sc_mu() is unphysical!\n", mu);
return NOT_A_NUMBER;
}
/* fprintf (stderr, " ... sc_mu(): cutting mu=%f to -1\n", mu); */
mu = -1.0;
}
return mu;
}
/***********************************************************************************/
/* Function: sc_interp_mu @62_30i@ */
/* Description: Calculate a random scattering angle mu = cos(theta) using a */
/* pre-calculated table, see description of calc_cumulative_table(). */
/* Interpolation between to tables is needed here since reff lies between the */
/* reff's of two table entries. */
/* */
/* CAUTION!!!! */
/* Note that the "interpolation" in reff has been done on purpose! */
/* The former version was inconsistent with the way the phase function is */
/* calculated for a given mu. However, methods like VROOM rely on the fact that */
/* randomly chosing alpha from the phase function (sc_interp_mu) and deriving the */
/* phase function from mu (get_phase_matrix_pft_interpol_reff) are done with */
/* exactly the same phase function. */
/* */
/* So: If you change anything in this subroutine, you must do so consistently also */
/* in get_phase_matrix_pft_interpol_reff!!! */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static double sc_interp_mu (double reff, phase_function_table* phase, int scaled) {
int i1 = 0, i2 = 0;
double temp = 0, r1 = 0, r2 = 0;
double mu = 0;
double weight = 0.0;
/* determine lower and upper reff's */
temp = (reff - phase->r0) / phase->dr;
/* this is a new version of getting i1 and i2, it is much quicker, but less precise */
i1 = (int)(temp);
i2 = i1;
if ((float)i1 != (float)temp)
i2++;
/* careful with rounding errors at the array boundaries */
i1 = (i1 > phase->n - 1 ? phase->n - 1 : i1);
i2 = (i2 > phase->n - 1 ? phase->n - 1 : i2);
i1 = (i1 < 0 ? 0 : i1);
i2 = (i2 < 0 ? 0 : i2);
/* adjacent radii */
r1 = phase->r0 + (double)i1 * phase->dr;
r2 = phase->r0 + (double)i2 * phase->dr;
if (i2 > i1)
weight = (r2 - reff) * phase->sca[i1] / ((r2 - reff) * phase->sca[i1] + (reff - r1) * phase->sca[i2]);
else
weight = 1.00;
if (uvspec_random() < weight)
mu = sc_mu (phase->iphase[i1], 1, scaled, 0., 0.);
else
mu = sc_mu (phase->iphase[i2], 1, scaled, 0., 0.);
return mu;
}
/***********************************************************************************/
/* Function: reflection @62_30i@ */
/* Description: */
/* Return 1 with a probability of albedo and 0 with a probability of (1-albedo). */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static inline int reflection (double albedo) {
if (uvspec_random() < albedo)
return 1;
return 0;
}
/***********************************************************************************/
/* Function: emission @62_30i@ */
/* Description: */
/* Return 1 with a probability of (1-albedo) and 0 with a probability of albedo. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static inline int emission (double albedo) {
if (uvspec_random() < albedo)
return 0;
return 1;
}
/***********************************************************************************/
/* Function: random_tau @62_30i@ */
/* Description: */
/* Calculate a random optical thickness with a pdf defined */
/* by Lambert-Beer's law. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
inline double random_tau() {
double temp = uvspec_random();
if (temp > 0) /* careful with 0 */
return (-log (temp));
else
return DBL_MAX;
}
/***********************************************************************************/
/* Function: random_direction @62_30i@ */
/* Description: */
/* Calculate a random direction. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void random_direction (direction* dir) {
double phi = sc_Isotropic_phi();
double cotheta = sc_Isotropic_mu();
double sitheta = sqrt (1.0 - cotheta * cotheta);
dir->dx[0] = cosd (phi) * sitheta;
dir->dx[1] = sind (phi) * sitheta;
dir->dx[2] = cotheta;
dir->cotheta = fabs (dir->dx[2]);
hitflag (dir);
}
/***********************************************************************************/
/* Function: random_Isotropic_normal @62_30i@ */
/* Description: */
/* Calculate a random upward direction relative to normal vector. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void random_Isotropic_normal (direction* dir, double* norm) {
int i = 0;
double phi = 0, mu = 0;
/* surface/elevation upward normal vector */
for (i = 0; i < 3; i++)
dir->dx[i] = norm[i];
/* Lambertian reflection */
phi = sc_Isotropic_phi();
mu = sc_Isotropic_upward_mu();
/* calculate new direction */
new_direction (mu, phi, dir, 0.);
}
/***********************************************************************************/
/* Function: random_variation_above @62_30i@ */
/* Description: */
/* Calculate a random value within a certain interval above the original value */
/* A more sophisticated version would include a distribution function */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Bernhard Reinhardt */
/* @i62_30@ */
/***********************************************************************************/
double random_variation_above (double orig_value, double interval_width) {
return orig_value + interval_width * uvspec_random();
}
/***********************************************************************************/
/* Function: random_theta_above @62_30i@ */
/* Description: */
/* Calculate a random theta within a certain interval above the original value */
/* Distribute according to p(theta)=sin(theta) */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Bernhard Reinhardt */
/* @i62_30@ */
/***********************************************************************************/
double random_theta_above (double orig_value, double interval_width) {
double norm_factor;
norm_factor = cosd (orig_value) - cosd (orig_value + interval_width);
return acosd (cosd (orig_value) - norm_factor * uvspec_random());
}
/***********************************************************************************/
/* Function: random_cone_mu @62_30i@ */
/* Description: */
/* Calculate a random mu within a certain cone around mu = 1 */
/* A more sophisticated version would include a detector sensitivity function */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
double random_cone_mu (double* cotheta) {
return 1. - (1. - *cotheta) * uvspec_random();
}
/***********************************************************************************/
/* Function: random_cone_mu_gauss @62_30i@ */
/* Description: */
/* Calculate a random mu within a certain cone around mu = 1 */
/* A more sophisticated version would include a detector sensitivity function */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
double random_cone_mu_gauss (double* cotheta) {
double alpha = uvspec_random();
if (alpha > 1.0 - 1e-7)
alpha = 1.0 - 1e-7;
double result = 1.0 / sqrt (1.0 - (1. / (*cotheta * *cotheta) - 1.0) * log (1.0 - alpha));
if (result > 1.0)
result = 1.0;
return result;
}
/***********************************************************************************/
/* Function: random_Lambertian_normal @62_30i@ */
/* Description: */
/* Random (Lambertian) reflection at the surface. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void random_Lambertian_normal (direction* dir, double* norm) {
int i = 0;
double phi = 0, mu = 0;
/* surface/elevation upward normal vector */
for (i = 0; i < 3; i++)
dir->dx[i] = norm[i];
/* Lambertian reflection */
phi = sc_Isotropic_phi();
mu = sc_Lambertian_mu();
/* calculate new direction */
new_direction (mu, phi, dir, 0.);
}
double pv_model_weight (double* dx, double* norm, float refractive_index_pv) {
double costheta = 0.0, theta = 0.0, theta_r = 0.0, t0 = 0.0, t = 0.0;
double kappa = 4; /* extinction coefficient of glass */
double L = 0.002; /* thickness of glass */
double n = refractive_index_pv; /* default=1.526 refractive index of glass*/
/* incident direction w.r.t. surface normal */
v_mult (dx, norm, &costheta);
theta = acos (costheta);
/* angle of refraction */
theta_r = asin (sin (theta) / n);
/* Transmission at normal incidence */
t0 = exp (-kappa * L) * (4. * n / pow ((1. + n), 2));
t = exp (-kappa * L / cos (theta_r)) * (1. - 0.5 * (pow (sin (theta_r - theta), 2) / pow (sin (theta_r + theta), 2) +
pow (tan (theta_r - theta), 2) / pow (tan (theta_r + theta), 2)));
/* fprintf(stderr, "t0 %.5f t %.5f theta %.3f theta_r %.3f \n", */
/* t0, t, theta*180./PI, theta_r*180./PI); */
if (theta == 0.0)
return 1.0;
else
return t / t0;
}
/***********************************************************************************/
/* Function: new_direction @62_30i@ */
/* Description: */
/* Calculate new direction at angles (mu, phi) to the original direction. */
/* This is an optimized version, thus being much faster than the old version */
/* It produces the same results within 1e-12 */
/* In the case of mu=-1, it even produces the correct result! (mu=-1) */
/* The old version of new_direction produced mu=+1 in that case */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
void new_direction (double mu, double phi, direction* dir, double phi_inc) {
int i = 0;
double u[3], v[3], e[3];
double siphi = 0, cophi = 0, sitheta = 0, cotheta = 0;
double u2inv = 0;
/********************************/
/* u,v are vectors of length 1; */
/* u,v,dx form a left-handed */
/* orthogonal system */
/********************************/
u[2] = +sqrt (dir->dx[0] * dir->dx[0] + dir->dx[1] * dir->dx[1]);
if (u[2] == 0.) {
v[0] = -cosd (phi_inc) * dir->dx[2];
v[1] = sind (phi_inc) * dir->dx[2];
v[2] = 0.;
} else {
u2inv = 1. / u[2];
v[0] = -dir->dx[1] * u2inv;
v[1] = +dir->dx[0] * u2inv;
v[2] = 0.;
}
u[0] = -dir->dx[2] * v[1];
u[1] = +dir->dx[2] * v[0];
/****************************/
/* create a new vector from */
/* u, v, and dx */
/****************************/
cotheta = mu;
sitheta = sqrt (1.0 - mu * mu);
cophi = cosd (phi);
siphi = sind (phi);
e[0] = sitheta * siphi;
e[1] = sitheta * cophi;
e[2] = cotheta;
for (i = 0; i < 3; i++)
dir->dx[i] = e[0] * u[i] + e[1] * v[i] + e[2] * dir->dx[i];
/* cosine of solar zenith angle for radiance calculation */
dir->cotheta = fabs (dir->dx[2]);
hitflag (dir);
}
/***********************************************************************************/
/* Function: ddprofile3D @62_30i@ */
/* Description: */
/* Allocate memory for struct ddprofile3D and initialize structure. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static ddprofile3D* calloc_ddprofile3D (int Nz, int Nx, int Ny, int* threed) {
int kc = 0, ic = 0;
ddprofile3D* p = calloc (1, sizeof (ddprofile3D));
if (p == NULL)
return NULL;
p->Nz = Nz;
p->Nx = Nx;
p->Ny = Ny;
p->threed = calloc ((size_t)Nz, sizeof (int));
if (p->threed == NULL)
return NULL;
for (kc = 0; kc < Nz; kc++) {
p->threed[kc] = threed[kc];
if (p->threed[kc] >= 1)
p->nthreed++;
}
/*
p->aer = calloc((size_t) Nz, sizeof(double **));
if (p->aer==NULL)
return NULL;
*/
/*
p->ozo = calloc((size_t) Nz, sizeof(double **));
if (p->ozo==NULL)
return NULL;
*/
/*
p->ice = calloc((size_t) Nz, sizeof(double **));
if (p->ice==NULL)
return NULL;
*/
p->cld = calloc ((size_t)Nz, sizeof (double**));
if (p->cld == NULL)
return NULL;
p->tot = calloc ((size_t)Nz, sizeof (double**));
if (p->tot == NULL)
return NULL;
for (kc = 0; kc < Nz; kc++)
if (p->threed[kc] >= 1) {
/*
p->aer[kc] = calloc(Nx, sizeof(double *));
for (ic=0; ic<Nx; ic++)
p->aer[kc][ic] = calloc((size_t) Ny, sizeof(double));
*/
/*
p->ozo[kc] = calloc((size_t) Nx, sizeof(double *));
for (ic=0; ic<Nx; ic++)
p->ozo[kc][ic] = calloc((size_t) Ny, sizeof(double));
*/
p->cld[kc] = calloc ((size_t)Nx, sizeof (double*));
for (ic = 0; ic < Nx; ic++)
p->cld[kc][ic] = calloc ((size_t)Ny, sizeof (double));
/*
p->ice[kc] = calloc((size_t) Nx, sizeof(double *));
for (ic=0; ic<Nx; ic++)
p->ice[kc][ic] = calloc((size_t) Ny, sizeof(double));
*/
p->tot[kc] = calloc ((size_t)Nx, sizeof (double*));
for (ic = 0; ic < Nx; ic++)
p->tot[kc][ic] = calloc ((size_t)Ny, sizeof (double));
}
return p;
}
/***********************************************************************************/
/* Function: cp_direction @62_30i@ */
/* Description: */
/* Copy struct direction. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void cp_direction (direction* dest, direction* source) {
int i = 0;
for (i = 0; i < 3; i++)
dest->dx[i] = source->dx[i];
for (i = 0; i < 3; i++)
dest->hit[i] = source->hit[i];
dest->cotheta = source->cotheta;
}
/***********************************************************************************/
/* Function: cp_optical_depth @62_30i@ */
/* Description: */
/* Copy struct optical_depth */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void cp_optical_depth (optical_depth* dest, optical_depth* source) {
dest->mol = source->mol;
dest->aer = source->aer;
dest->cld = source->cld;
dest->ice = source->ice;
dest->tot = source->tot;
}
/***********************************************************************************/
/* Function: cp_photon_struct @62_30i@ */
/* Description: */
/* Copy struct photon_struct */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void cp_photon_struct (photon_struct* dest, photon_struct* source, sample_struct* sample, int n_caoth) {
int i = 0, j = 0, k = 0, l = 0, id = 0, ip = 0, iv = 0, ic = 0, jc = 0, kc = 0, isp = 0;
for (i = 0; i < 3; i++)
dest->x[i] = source->x[i];
cp_direction (&(dest->dir), &(source->dir));
cp_direction (&(dest->dir00), &(source->dir00));
dest->ic = source->ic;
dest->jc = source->jc;
dest->kc = source->kc;
dest->jcg = source->jcg;
dest->iv_alis = source->iv_alis;
dest->photon_status = source->photon_status;
for (i = 0; i < 3; i++)
dest->reallyhit[i] = source->reallyhit[i];
dest->SC_mode = source->SC_mode;
dest->DDIS_SC_mode = source->DDIS_SC_mode;
dest->RIS_mode = source->RIS_mode;
dest->VIS_mode = source->VIS_mode;
dest->direct = source->direct;
dest->scattercounter = source->scattercounter;
dest->reflectcounter = source->reflectcounter;
dest->spikewarningcounter = source->spikewarningcounter;
dest->photoncounter = source->photoncounter;
dest->backward_is = source->backward_is;
dest->backward_js = source->backward_js;
dest->rayleighcounter = source->rayleighcounter;
dest->muchoutcounter = source->muchoutcounter;
dest->ncircos = source->ncircos;
for (ic = 0; ic < dest->ncircos; ic++)
dest->tocirco[ic] = source->tocirco[ic];
dest->update_atmos_coord = source->update_atmos_coord;
dest->pathlength = source->pathlength;
cp_optical_depth (&(dest->tauabs), &(source->tauabs));
dest->tauris = source->tauris;
dest->p_norm = source->p_norm;
if (sample->spectral_is || sample->concentration_is) {
dest->nlambda = source->nlambda;
dest->Nc = source->Nc;
for (iv = 0; iv < dest->nlambda; iv++) {
dest->q_spectral[iv] = source->q_spectral[iv];
dest->q2_spectral[iv] = source->q2_spectral[iv];
dest->q_albedo_spectral[iv] = source->q_albedo_spectral[iv];
/* dest->dtauabs_spectral[iv] = source->dtauabs_spectral[iv];*/
}
for (ic = 0; ic < dest->Nc; ic++) {
dest->q_concentration[ic] = source->q_concentration[ic];
dest->q2_concentration[ic] = source->q2_concentration[ic];
}
dest->Nz_alis = source->Nz_alis;
for (kc = 0; kc < dest->Nz_alis; kc++)
dest->pathlength_per_layer[kc] = source->pathlength_per_layer[kc];
}
if (sample->boxairmass || sample->jacobian) {
dest->Nz_alis = source->Nz_alis;
for (kc = 0; kc < dest->Nz_alis; kc++)
dest->pathlength_per_layer[kc] = source->pathlength_per_layer[kc];
}
else if (sample->boxairmass3D || sample->jacobian3D) {
dest->Nx_boxairmass = source->Nx_boxairmass;
dest->Ny_boxairmass = source->Ny_boxairmass;
dest->Nz_alis = source->Nz_alis;
for (ic = 0; ic < dest->Nx_boxairmass; ic++) {
for (jc = 0; jc < dest->Ny_boxairmass; jc++) {
for (kc = 0; kc < dest->Nz_alis; kc++) {
dest->pathlength_per_box[ic][jc][kc] = source->pathlength_per_box[ic][jc][kc];
}
}
}
}
if (sample->jacobian || sample->jacobian3D) {
for (isp = 0; isp < n_caoth; isp++) {
for (ic = 0; ic < dest->Nx_boxairmass; ic++) {
for (jc = 0; jc < dest->Ny_boxairmass; jc++) {
for (kc = 0; kc < dest->Nz_alis; kc++) {
dest->q_jacobian_sca[isp][ic][jc][kc] = source->q_jacobian_sca[isp][ic][jc][kc];
}
}
}
}
}
dest->weight = source->weight;
dest->phi0 = source->phi0;
dest->fw_phi0 = source->fw_phi0;
dest->fw_phi = source->fw_phi;
for (ip = 0; ip < sample->nstokes; ip++)
dest->stokes0[ip] = source->stokes0[ip];
for (ip = 0; ip < sample->nstokes; ip++)
dest->stokes[ip] = source->stokes[ip];
for (i = 0; i < sample->nstokes; i++)
for (j = 0; j < sample->nstokes; j++)
dest->phamat[i][j] = source->phamat[i][j];
#if HAVE_VROOM
dest->q_isoene = source->q_isoene;
dest->special_weight = source->special_weight;
if (dest->q_jacobian != NULL) { /* FIJ */
for (j = 0; j < 2; j++)
for (k = 0; k < n_caoth; k++)
for (l = 0; l < dest->Nz_jac; l++)
dest->q_jacobian[j][k][l] = source->q_jacobian[j][k][l];
for (l = 0; l < dest->Nz_jac; l++)
dest->r_jacobian[l] = source->r_jacobian[l];
dest->Nz_jac = source->Nz_jac;
}
for (id = 0; id < sample->Nd; id++)
dest->pdir[id] = source->pdir[id];
cp_locest (&(dest->lest), &(source->lest), sample, n_caoth);
#if HAVE_LIDAR
/* CB - copy cb and pss */
if (sample->coherent_backscatter && sample->LidarLocEst) {
copy_cohebasca (&(dest->cb), &(source->cb));
copy_pss (&(dest->pss), &(source->pss));
}
dest->tauext_tot = source->tauext_tot;
#endif
dest->isclone = source->isclone;
dest->clonescattercounter = source->clonescattercounter;
dest->escapescattercounter = source->escapescattercounter;
#endif
/* these two should not be in photon structure !!! CHECK!!! */
dest->ipa = source->ipa;
dest->maxpathlength = source->maxpathlength;
/* do not copy photon weight tree !!!??? CHECK!!! */
/* do not copy photon_path !!!??? */
dest->escapepath = source->escapepath;
dest->vis_beta = source->vis_beta;
dest->risqidd_beta = source->risqidd_beta;
/* it is quite useful to know the parent of the photon! Used e.g. in escape_probability */
dest->parent_photon = source;
#ifdef CLDPRP
if (sample->cldprp) {
dest->cldprp.reff_wc = source->cldprp.reff_wc;
dest->cldprp.reff_ic = source->cldprp.reff_ic;
dest->cldprp.rhit_wc = source->cldprp.rhit_wc;
dest->cldprp.rhit_ic = source->cldprp.rhit_ic;
dest->cldprp.tau_wc = source->cldprp.tau_wc;
dest->cldprp.tau_ic = source->cldprp.tau_ic;
dest->cldprp.dxlwc = source->cldprp.dxlwc;
dest->cldprp.dylwc = source->cldprp.dylwc;
dest->cldprp.dzlwc = source->cldprp.dzlwc;
dest->cldprp.dxiwc = source->cldprp.dxiwc;
dest->cldprp.dyiwc = source->cldprp.dyiwc;
dest->cldprp.dziwc = source->cldprp.dziwc;
}
#endif
dest->intersect_triangle_id = source->intersect_triangle_id;
}
/***********************************************************************************/
/* Function: calloc_radiation_field @62_30i@ */
/* Description: */
/* Allocate memory for struct radiation_field and initialize structure. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static radiation_field* calloc_radiation_field (int Nx, int Ny, int Nd, int Nr, int Nt, int Np, int std, int cldprp) {
int id = 0, ir = 0, is = 0, iy = 0;
radiation_field* temp = calloc (1, sizeof (radiation_field));
temp->ndir = calloc ((size_t)Nx, sizeof (int*));
temp->ndn = calloc ((size_t)Nx, sizeof (int*));
temp->nup = calloc ((size_t)Nx, sizeof (int*));
temp->edir = calloc ((size_t)Nx, sizeof (double*));
temp->edn = calloc ((size_t)Nx, sizeof (double*));
temp->eup = calloc ((size_t)Nx, sizeof (double*));
temp->fdir = calloc ((size_t)Nx, sizeof (double*));
temp->fdn = calloc ((size_t)Nx, sizeof (double*));
temp->fup = calloc ((size_t)Nx, sizeof (double*));
if (std) { /* standard deviations */
temp->edir2 = calloc ((size_t)Nx, sizeof (double*));
temp->edn2 = calloc ((size_t)Nx, sizeof (double*));
temp->eup2 = calloc ((size_t)Nx, sizeof (double*));
temp->fdir2 = calloc ((size_t)Nx, sizeof (double*));
temp->fdn2 = calloc ((size_t)Nx, sizeof (double*));
temp->fup2 = calloc ((size_t)Nx, sizeof (double*));
}
if (Nd > 0) {
temp->raddir = calloc ((size_t)Nd, sizeof (double***));
temp->raddif = calloc ((size_t)Nd, sizeof (double***));
temp->radesc = calloc ((size_t)Nd, sizeof (double***));
temp->radpat = calloc ((size_t)Nd, sizeof (double***));
temp->radpes = calloc ((size_t)Nd, sizeof (double***));
if (std) {
temp->raddir2 = calloc ((size_t)Nd, sizeof (double***));
temp->raddif2 = calloc ((size_t)Nd, sizeof (double***));
temp->radesc2 = calloc ((size_t)Nd, sizeof (double***));
temp->radpat2 = calloc ((size_t)Nd, sizeof (double***));
temp->radpes2 = calloc ((size_t)Nd, sizeof (double***));
temp->nraddir = calloc ((size_t)Nd, sizeof (int***));
temp->nraddif = calloc ((size_t)Nd, sizeof (int***));
temp->nradesc = calloc ((size_t)Nd, sizeof (int***));
temp->nradpat = calloc ((size_t)Nd, sizeof (int***));
temp->nradpes = calloc ((size_t)Nd, sizeof (int***));
}
}
for (is = 0; is < Nx; is++) {
temp->ndir[is] = calloc ((size_t)Ny, sizeof (int));
temp->ndn[is] = calloc ((size_t)Ny, sizeof (int));
temp->nup[is] = calloc ((size_t)Ny, sizeof (int));
temp->edir[is] = calloc ((size_t)Ny, sizeof (double));
temp->edn[is] = calloc ((size_t)Ny, sizeof (double));
temp->eup[is] = calloc ((size_t)Ny, sizeof (double));
temp->fdir[is] = calloc ((size_t)Ny, sizeof (double));
temp->fdn[is] = calloc ((size_t)Ny, sizeof (double));
temp->fup[is] = calloc ((size_t)Ny, sizeof (double));
if (std) {
temp->edir2[is] = calloc ((size_t)Ny, sizeof (double));
temp->edn2[is] = calloc ((size_t)Ny, sizeof (double));
temp->eup2[is] = calloc ((size_t)Ny, sizeof (double));
temp->fdir2[is] = calloc ((size_t)Ny, sizeof (double));
temp->fdn2[is] = calloc ((size_t)Ny, sizeof (double));
temp->fup2[is] = calloc ((size_t)Ny, sizeof (double));
}
}
for (id = 0; id < Nd; id++) {
temp->raddir[id] = calloc ((size_t)Nx, sizeof (double**));
temp->raddif[id] = calloc ((size_t)Nx, sizeof (double**));
temp->radesc[id] = calloc ((size_t)Nx, sizeof (double**));
temp->radpat[id] = calloc ((size_t)Nr, sizeof (double**));
temp->radpes[id] = calloc ((size_t)Nr, sizeof (double**));
if (std) {
temp->raddir2[id] = calloc ((size_t)Nx, sizeof (double**));
temp->raddif2[id] = calloc ((size_t)Nx, sizeof (double**));
temp->radesc2[id] = calloc ((size_t)Nx, sizeof (double**));
temp->radpat2[id] = calloc ((size_t)Nr, sizeof (double**));
temp->radpes2[id] = calloc ((size_t)Nr, sizeof (double**));
temp->nraddir[id] = calloc ((size_t)Nx, sizeof (int**));
temp->nraddif[id] = calloc ((size_t)Nx, sizeof (int**));
temp->nradesc[id] = calloc ((size_t)Nx, sizeof (int**));
temp->nradpat[id] = calloc ((size_t)Nr, sizeof (int**));
temp->nradpes[id] = calloc ((size_t)Nr, sizeof (int**));
}
for (is = 0; is < Nx; is++) {
temp->raddir[id][is] = calloc ((size_t)Ny, sizeof (double*));
temp->raddif[id][is] = calloc ((size_t)Ny, sizeof (double*));
temp->radesc[id][is] = calloc ((size_t)Ny, sizeof (double*));
if (std) {
temp->raddir2[id][is] = calloc ((size_t)Ny, sizeof (double*));
temp->raddif2[id][is] = calloc ((size_t)Ny, sizeof (double*));
temp->radesc2[id][is] = calloc ((size_t)Ny, sizeof (double*));
temp->nraddir[id][is] = calloc ((size_t)Ny, sizeof (int*));
temp->nraddif[id][is] = calloc ((size_t)Ny, sizeof (int*));
temp->nradesc[id][is] = calloc ((size_t)Ny, sizeof (int*));
}
for (iy = 0; iy < Ny; iy++) {
temp->raddir[id][is][iy] = calloc ((size_t)Np, sizeof (double));
temp->raddif[id][is][iy] = calloc ((size_t)Np, sizeof (double));
temp->radesc[id][is][iy] = calloc ((size_t)Np, sizeof (double));
if (std) {
temp->raddir2[id][is][iy] = calloc ((size_t)Np, sizeof (double));
temp->raddif2[id][is][iy] = calloc ((size_t)Np, sizeof (double));
temp->radesc2[id][is][iy] = calloc ((size_t)Np, sizeof (double));
temp->nraddir[id][is][iy] = calloc ((size_t)Np, sizeof (int));
temp->nraddif[id][is][iy] = calloc ((size_t)Np, sizeof (int));
temp->nradesc[id][is][iy] = calloc ((size_t)Np, sizeof (int));
}
}
}
for (ir = 0; ir < Nr; ir++) {
temp->radpat[id][ir] = calloc ((size_t)Nt, sizeof (double*));
temp->radpes[id][ir] = calloc ((size_t)Nt, sizeof (double*));
if (std) {
temp->radpat2[id][ir] = calloc ((size_t)Nt, sizeof (double*));
temp->radpes2[id][ir] = calloc ((size_t)Nt, sizeof (double*));
temp->nradpat[id][ir] = calloc ((size_t)Nt, sizeof (int*));
temp->nradpes[id][ir] = calloc ((size_t)Nt, sizeof (int*));
}
for (iy = 0; iy < Np; iy++) {
temp->radpat[id][ir][iy] = calloc ((size_t)Np, sizeof (double));
temp->radpes[id][ir][iy] = calloc ((size_t)Np, sizeof (double));
if (std) {
temp->radpat2[id][ir][iy] = calloc ((size_t)Np, sizeof (double));
temp->radpes2[id][ir][iy] = calloc ((size_t)Np, sizeof (double));
temp->nradpat[id][ir][iy] = calloc ((size_t)Np, sizeof (int));
temp->nradpes[id][ir][iy] = calloc ((size_t)Np, sizeof (int));
}
}
}
}
#ifdef CLDPRP
temp->cldprp.sample_cldprp = cldprp;
if (temp->cldprp.sample_cldprp) {
temp->cldprp.reff_wc = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.reff_ic = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.rhit_wc = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.rhit_ic = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.tau_wc = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.tau_ic = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.dxlwc = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.dylwc = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.dzlwc = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.dxiwc = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.dyiwc = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.dziwc = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.totweights = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.wc_weights = (double**)calloc ((size_t)Nx, sizeof (double*));
temp->cldprp.ic_weights = (double**)calloc ((size_t)Nx, sizeof (double*));
for (is = 0; is < (size_t)Nx; is++) {
temp->cldprp.reff_wc[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.reff_ic[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.rhit_wc[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.rhit_ic[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.tau_wc[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.tau_ic[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.dxlwc[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.dylwc[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.dzlwc[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.dxiwc[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.dyiwc[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.dziwc[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.totweights[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.wc_weights[is] = (double*)calloc ((size_t)Ny, sizeof (double));
temp->cldprp.ic_weights[is] = (double*)calloc ((size_t)Ny, sizeof (double));
}
}
#endif
return temp;
}
/***********************************************************************************/
/* Function: calloc_radiation_field_t */
/* Description: */
/* Allocate spectral radiation field (for calculation of high resolution */
/* spectra using importance sampling). */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Claudia Emde */
/* */
/***********************************************************************************/
static radiation_field_t* calloc_radiation_field_t (int Nc, int Nx, int Ny, int Np, int Nv) {
int ic = 0, ip = 0, is = 0, js = 0;
radiation_field_t* temp = calloc (1, sizeof (radiation_field_t));
temp->Nc = Nc;
temp->Nv = Nv;
temp->Np = Np;
temp->rad_t = calloc ((size_t)Nc, sizeof (double****));
for (ic = 0; ic < Nc; ic++) {
temp->rad_t[ic] = calloc ((size_t)Nx, sizeof (double***));
for (is = 0; is < Nx; is++) {
temp->rad_t[ic][is] = calloc ((size_t)Ny, sizeof (double**));
for (js = 0; js < Ny; js++) {
temp->rad_t[ic][is][js] = calloc ((size_t)Np, sizeof (double*));
for (ip = 0; ip < Np; ip++) {
temp->rad_t[ic][is][js][ip] = calloc ((size_t)Nv, sizeof (double));
}
}
}
}
return temp;
}
/***********************************************************************************/
/* Function: free_profile @62_30i@ */
/* Description: */
/* Free memory of struct profile. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void free_profile (profile* p) {
int isp = 0;
for (isp = 0; isp <= p->n_caoth; isp++)
free (p->prof[isp]);
free (p->prof);
free (p);
}
/***********************************************************************************/
/* Function: free_profile3D @62_30i@ */
/* Description: */
/* Free memory of struct profile3D. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void free_profile3D (profile3D* p) {
int isp = 0, kc = 0, ic = 0;
for (isp = 0; isp <= p->n_caoth; isp++) {
if (p->tocalloc[isp]) {
for (kc = 0; kc < p->Nz; kc++)
if (p->threed[isp][kc] >= 1) {
for (ic = 0; ic < p->Nx; ic++)
free (p->prof[isp][kc][ic]);
free (p->prof[isp][kc]);
}
free (p->prof[isp]);
}
free (p->threed[isp]);
}
free (p->tocalloc);
free (p->prof);
free (p->threed);
free (p->nthreed);
free (p);
}
/***********************************************************************************/
/* Function: free_ddprofile3D @62_30i@ */
/* Description: */
/* Free memory of struct ddprofile3D. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void free_ddprofile3D (ddprofile3D* p) {
int kc = 0, ic = 0;
for (kc = 0; kc < p->Nz; kc++)
if (p->threed[kc] >= 1) {
/*
for (ic=0; ic<p->Nx; ic++)
free(p->aer[kc][ic]);
free(p->aer[kc]);
*/
/*
for (ic=0; ic<p->Nx; ic++)
free(p->ozo[kc][ic]);
free(p->ozo[kc]);
*/
/*
for (ic=0; ic<p->Nx; ic++)
free(p->ice[kc][ic]);
free(p->ice[kc]);
*/
for (ic = 0; ic < p->Nx; ic++)
free (p->cld[kc][ic]);
free (p->cld[kc]);
for (ic = 0; ic < p->Nx; ic++)
free (p->tot[kc][ic]);
free (p->tot[kc]);
}
/* free (p->aer); */
/* free (p->ozo); */
/* free (p->ice); */
free (p->cld);
free (p->tot);
free (p->threed);
free (p);
}
/***********************************************************************************/
/* Function: free_radiation_field @62_30i@ */
/* Description: */
/* Free memory of struct radiation_field. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void free_radiation_field (radiation_field* res, int Nx, int Nr, int Nd, int Ny, int std) {
int id = 0, ir = 0, is = 0, iy = 0;
for (is = 0; is < Nx; is++) {
free (res->ndir[is]);
free (res->ndn[is]);
free (res->nup[is]);
free (res->edir[is]);
free (res->edn[is]);
free (res->eup[is]);
free (res->fdir[is]);
free (res->fdn[is]);
free (res->fup[is]);
if (std) {
free (res->edir2[is]);
free (res->edn2[is]);
free (res->eup2[is]);
free (res->fdir2[is]);
free (res->fdn2[is]);
free (res->fup2[is]);
}
}
for (id = 0; id < Nd; id++) {
for (is = 0; is < Nx; is++) {
for (iy = 0; iy < Ny; iy++) {
free (res->raddir[id][is][iy]);
free (res->raddif[id][is][iy]);
free (res->radesc[id][is][iy]);
if (std) {
free (res->raddir2[id][is][iy]);
free (res->raddif2[id][is][iy]);
free (res->radesc2[id][is][iy]);
free (res->nraddir[id][is][iy]);
free (res->nraddif[id][is][iy]);
free (res->nradesc[id][is][iy]);
}
}
free (res->raddir[id][is]);
free (res->raddif[id][is]);
free (res->radesc[id][is]);
if (std) {
free (res->raddir2[id][is]);
free (res->raddif2[id][is]);
free (res->radesc2[id][is]);
free (res->nraddir[id][is]);
free (res->nraddif[id][is]);
free (res->nradesc[id][is]);
}
}
for (ir = 0; ir < Nr; ir++) {
for (iy = 0; iy < Ny; iy++) {
free (res->radpat[id][ir][iy]);
free (res->radpes[id][ir][iy]);
if (std) {
free (res->radpat2[id][ir][iy]);
free (res->radpes2[id][ir][iy]);
free (res->nradpat[id][ir][iy]);
free (res->nradpes[id][ir][iy]);
}
}
free (res->radpat[id][ir]);
free (res->radpes[id][ir]);
if (std) {
free (res->radpat2[id][ir]);
free (res->radpes2[id][ir]);
free (res->nradpat[id][ir]);
free (res->nradpes[id][ir]);
}
}
free (res->raddir[id]);
free (res->raddif[id]);
free (res->radesc[id]);
free (res->radpat[id]);
free (res->radpes[id]);
if (std) {
free (res->raddir2[id]);
free (res->raddif2[id]);
free (res->radesc2[id]);
free (res->radpat2[id]);
free (res->radpes2[id]);
free (res->nraddir[id]);
free (res->nraddif[id]);
free (res->nradesc[id]);
free (res->nradpat[id]);
free (res->nradpes[id]);
}
}
free (res->ndir);
free (res->ndn);
free (res->nup);
free (res->edir);
free (res->edn);
free (res->eup);
free (res->fdir);
free (res->fdn);
free (res->fup);
free (res->raddir);
free (res->raddif);
free (res->radesc);
free (res->radpat);
free (res->radpes);
if (std) {
free (res->edir2);
free (res->edn2);
free (res->eup2);
free (res->fdir2);
free (res->fdn2);
free (res->fup2);
free (res->raddir2);
free (res->raddif2);
free (res->radesc2);
free (res->radpat2);
free (res->radpes2);
free (res->nraddir);
free (res->nraddif);
free (res->nradesc);
free (res->nradpat);
free (res->nradpes);
}
#ifdef CLDPRP
if (res->cldprp.sample_cldprp) {
for (is = 0; is < Nx; is++) {
free (res->cldprp.totweights[is]);
free (res->cldprp.wc_weights[is]);
free (res->cldprp.ic_weights[is]);
free (res->cldprp.reff_wc[is]);
free (res->cldprp.reff_ic[is]);
free (res->cldprp.rhit_wc[is]);
free (res->cldprp.rhit_ic[is]);
free (res->cldprp.tau_wc[is]);
free (res->cldprp.tau_ic[is]);
free (res->cldprp.dxlwc[is]);
free (res->cldprp.dylwc[is]);
free (res->cldprp.dzlwc[is]);
free (res->cldprp.dxiwc[is]);
free (res->cldprp.dyiwc[is]);
free (res->cldprp.dziwc[is]);
}
free (res->cldprp.totweights);
free (res->cldprp.wc_weights);
free (res->cldprp.ic_weights);
free (res->cldprp.reff_wc);
free (res->cldprp.reff_ic);
free (res->cldprp.rhit_wc);
free (res->cldprp.rhit_ic);
free (res->cldprp.tau_wc);
free (res->cldprp.tau_ic);
free (res->cldprp.dxlwc);
free (res->cldprp.dylwc);
free (res->cldprp.dzlwc);
free (res->cldprp.dxiwc);
free (res->cldprp.dyiwc);
free (res->cldprp.dziwc);
}
#endif
free (res);
}
/***********************************************************************************/
/* Function: compare_levels @62_30i@ */
/* Description: */
/* Compare two altitude grids. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int compare_levels (float* z1, int n1, float* z2, int n2) {
int kc = 0;
if (n1 != n2) {
fprintf (stderr, "Error, number of layers differing, %d vs %d\n", n1, n2);
return -1;
}
for (kc = 0; kc <= n1; kc++)
if (fabs (z1[kc] - z2[kc]) > MC_EPSILON * z1[kc]) {
fprintf (stderr, "Error, difference at level %d, altitude %g vs. %g\n", kc, z1[kc], z2[kc]);
return -1;
}
return 0; /* if o.k. */
}
/***********************************************************************************/
/* Function: mc_add_optical_depth @62_30i@ */
/* Description: */
/* Add an optical depth to tauabs, using the extinction coefficient kabs */
/* of layer kc and the pathlength. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static inline void mc_add_optical_depth (atmosphere_struct* atmos, photon_struct* p, double length, int calc_tauext) {
/* commented four fields out to save computational time */
/* 1D */
/* p->tauabs.aer += length * (atmos->kabs->aer)[p->kc]; */
/* p->tauabs.mol += length * (atmos->kabs->ozo)[p->kc]; */
/* p->tauabs.ice += length * (atmos->kabs->ice)[p->kc]; */
/* old version */
/* if (is_threed==1) {/\* 3D layer *\/ */
/* /\* p->tauabs.cld += length * (atmos->kabs3D->cld)[p->kc][p->ic][p->jc]; *\/ */
/* p->tauabs.tot += length * atmos->kabs3D->prof [MCCAOTH_TOT][p->kc][p->ic][p->jc]; */
/* } */
/* else { */
/* /\* p->tauabs.cld += length * (atmos->kabs->cld)[p->kc]; *\/ */
/* p->tauabs.tot += length * atmos->kabs->prof [MCCAOTH_TOT][p->kc]; */
/* } */
p->tauabs.tot += length * get_kabs (atmos, p, MCCAOTH_TOT);
p->cb.tausca += length * get_kscaIS (atmos, p, MCCAOTH_TOT);
if (calc_tauext)
p->tauext_tot += length * (get_ksca (atmos, p, MCCAOTH_TOT) + get_kabs (atmos, p, MCCAOTH_TOT));
}
/***********************************************************************************/
/* Function: mc_add_absorption_3D @62_30i@ */
/* Description: */
/* Calculate the fraction of radiation absorbed in pixel (kc, ic,jc) and add */
/* it to the total amount absorbed. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void mc_add_absorption_3D (profile3D* kabs3D,
profile* kabs,
int kc,
int ic,
int jc,
double length,
double totweight,
int std,
ddprofile3D* absorption3D,
ddprofile3D* absorption3D2,
struct tnode** wtree) {
double weight = 0;
/* commented four fields out to save computational time */
/* 1D */
/* absorption3D->aer[kc][ic][jc] += i0 * (1.0 - exp(- length * kabs->prof [MCPROF_AER][kc])); */
/* absorption3D->ozo[kc][ic][jc] += i0 * (1.0 - exp(- length * kabs->prof [MCPROF_MOL][kc])); */
/* 3D */
/* absorption3D->cld[kc][ic][jc] += i0 * (1.0 - exp(- length * kabs3D->prof [MCPROF_WC ][kc][ic][jc])); */
/* absorption3D->ice[kc][ic][jc] += i0 * (1.0 - exp(- length * kabs3D->prof [MCPROF_IC ][kc][ic][jc])); */
weight = totweight * (1.0 - exp (-length * kabs3D->prof[MCCAOTH_TOT][kc][ic][jc]));
absorption3D->tot[kc][ic][jc] += weight;
if (std)
*wtree = addtree_stddev (*wtree, &(absorption3D2->tot[kc][ic][jc]), weight);
}
/***********************************************************************************/
/* Function: elevation @62_30i@ */
/* Description: */
/* Calculate surface elevation using bi-linear interpolation. */
/* ATTENTION: x and y are trucated coordinates, that is, relative to the left */
/* and lower edges of the pixel. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static double elevation (surface surf, double x, double y) {
return surf.a * x + surf.b * y + surf.c * x * y + surf.d;
}
/***********************************************************************************/
/* Function: cross_bilinear @62_30i@ */
/* Description: */
/* Calculate crossing points between a straight line and the bi-linear surface */
/* for a given pixel. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int cross_bilinear (surface surf, double* a, double* b, double x0, double y0, double* solution) {
double alpha = 0, beta = 0, gamma = 0;
double disc = 0, sqdisc = 0;
double r1 = 0, r2 = 0;
/* reset solution */
solution[0] = -1;
solution[1] = -1;
gamma = surf.a * a[0] - surf.a * x0 + surf.b * a[1] - surf.b * y0 + surf.c * a[0] * a[1] + surf.c * x0 * y0 - surf.c * a[0] * y0 -
surf.c * a[1] * x0 + surf.d - a[2];
beta = surf.a * b[0] + surf.b * b[1] + surf.c * (a[0] * b[1] + a[1] * b[0] - b[0] * y0 - b[1] * x0) - b[2];
alpha = surf.c * b[0] * b[1];
if (alpha == 0) {
if (beta == 0)
return 0;
else {
solution[0] = -gamma / beta;
return 1;
}
} else {
/* solve quadratic equation */
disc = beta * beta - 4.0 * alpha * gamma;
if (disc < 0) /* no solution */
return 0;
else {
if (disc == 0) {
solution[0] = -beta / 2.0 / alpha;
return 1;
} else {
sqdisc = sqrt (disc);
if (beta < 0)
r1 = 2.0 * gamma / (-beta + sqdisc);
else
r1 = (-beta - sqdisc) / 2.0 / alpha;
if (beta < 0)
r2 = (-beta + sqdisc) / 2.0 / alpha;
else
r2 = 2.0 * gamma / (-beta - sqdisc);
/* sort in ascending order */
if (r1 < r2) {
solution[0] = r1;
solution[1] = r2;
} else {
solution[0] = r2;
solution[1] = r1;
}
return 2;
}
}
}
fprintf (stderr, "\nFATAL error, arrived at the end of cross_bilinear()\n");
return -1; /* this should not happen */
}
/***********************************************************************************/
/* Function: cross_surface @62_30i@ */
/* Description: */
/* Determine crossing point of a photon with the surface. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int cross_surface (photon_struct* p, double step, elevation_struct* elev, int bcond, double* gamma) {
int i = 0, status = 0;
int ie = 0, je = 0;
double X_elev = 0, Y_elev = 0;
double alpha[2] = {0, 0};
int reallyhit[2] = {0, 0};
double xp[2] = {0, 0};
double stepact = 0, hop = 0;
double xact[3] = {p->x[0], p->x[1], p->x[2]};
double n[3] = {0, 0, 0};
double X = 0, Y = 0;
int used2nd = 0, heureka = 0;
double solution[2] = {0, 0};
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr,
"counters %d %d %d %d --- cross_surface %e %e %e\n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
p->x[0],
p->x[1],
p->x[2]);
#endif
/* photon cannot cross the surface if the whole path is above */
/* the maximum surface elevation */
if (p->x[2] > elev->surfmax + MC_EPSILON && p->x[2] + step * p->dir.dx[2] > elev->surfmax + MC_EPSILON)
return 0;
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr,
"counters %d %d %d %d --- could cross_surface\n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode);
#endif
/* determine elevation pixel */
elev_coord (p, elev, &ie, &je);
/* hmm, in the version before March 2, 2008 the right and upper edges were treated differently: */
/* when the photon was at the right/upper boundary, X_elev/Y_elev was set to the right/upper */
/* boundary and afterwards ie/je was reduced by one. Now we reduce before (in elev_coord) and */
/* X_elev/Y_elev is therefore to the left/lower of the pixel which seems correct */
X_elev = (double)ie * elev->delX;
Y_elev = (double)je * elev->delY;
while (1) {
status = cross_bilinear (elev->surf[ie][je], xact, p->dir.dx, X_elev, Y_elev, solution);
if (status < 0) {
fprintf (stderr, "FATAL error:\n");
fprintf (stderr, "cross_bilinear returned -1!\n");
return -1;
}
used2nd = 0;
if (status > 0) { /* if there is a solution */
*gamma = solution[0];
/* use 2nd solution if 1st is smaller than 0 */
if (status == 2 && *gamma < 0) {
*gamma = solution[1];
used2nd = 1;
}
/* proceed only if a positive solution exists */
if (*gamma >= 0) {
if (-MC_EPSILON < *gamma && stepact + *gamma < step + MC_EPSILON) {
xp[0] = xact[0] + *gamma * p->dir.dx[0];
xp[1] = xact[1] + *gamma * p->dir.dx[1];
if (X_elev <= xp[0] && xp[0] <= X_elev + elev->delX && Y_elev <= xp[1] && xp[1] <= Y_elev + elev->delY) {
/* check if the photon is going towards the surface or */
/* away from the surface. */
/* upward normal */
n[0] = -elev->surf[ie][je].a - elev->surf[ie][je].c * (xp[1] - Y_elev);
n[1] = -elev->surf[ie][je].b - elev->surf[ie][je].c * (xp[0] - X_elev);
n[2] = 1.0;
/* only if the scalar product between surface normal and */
/* photon direction is larger than 0, the photon hits the */
/* surface from outside. */
if (n[0] * p->dir.dx[0] + n[1] * p->dir.dx[1] + n[2] * p->dir.dx[2] < 0) {
heureka = 1;
*gamma += stepact;
break; /* done */
} else {
if (used2nd == 0) {
*gamma = solution[1];
if (-MC_EPSILON < *gamma && stepact + *gamma < step + MC_EPSILON) {
xp[0] = xact[0] + *gamma * p->dir.dx[0];
xp[1] = xact[1] + *gamma * p->dir.dx[1];
if (X_elev <= xp[0] && xp[0] <= X_elev + elev->delX && Y_elev <= xp[1] && xp[1] <= Y_elev + elev->delY) {
/* check if the photon is going towards the surface or */
/* away from the surface. */
/* upward normal */
n[0] = -elev->surf[ie][je].a - elev->surf[ie][je].c * (xp[1] - Y_elev);
n[1] = -elev->surf[ie][je].b - elev->surf[ie][je].c * (xp[0] - X_elev);
n[2] = 1.0;
/* only if the scalar product between surface normal and */
/* photon direction is larger than 0, the photon hits the */
/* surface from outside. */
if (n[0] * p->dir.dx[0] + n[1] * p->dir.dx[1] + n[2] * p->dir.dx[2] < 0) {
heureka = 1;
*gamma += stepact;
break; /* done */
}
}
}
}
}
}
}
}
}
/* stop if solution found */
if (heureka == 1)
break;
/* no need to check any further if vertical movement */
if (p->dir.hit[0] == -1 && p->dir.hit[1] == -1)
break;
/* advance to next 2D elevation grid point */
/* reset reallyhit */
reallyhit[0] = 0;
reallyhit[1] = 0;
if (p->dir.hit[0] >= 0) { /* x-axis */
X = (double)(ie + p->dir.hit[0]) * elev->delX;
alpha[0] = (X - xact[0]) / p->dir.dx[0];
xp[1] = xact[1] + alpha[0] * p->dir.dx[1];
if (Y_elev <= xp[1] && xp[1] <= Y_elev + elev->delY)
reallyhit[0] = 1;
else
reallyhit[0] = 0;
}
if (p->dir.hit[1] >= 0) { /* y-axis */
Y = (double)(je + p->dir.hit[1]) * elev->delY;
alpha[1] = (Y - xact[1]) / p->dir.dx[1];
xp[0] = xact[0] + alpha[1] * p->dir.dx[0];
if (X_elev <= xp[0] && xp[0] <= X_elev + elev->delX)
reallyhit[1] = 1;
else
reallyhit[1] = 0;
}
/* adjust indices */
if (reallyhit[0]) {
hop = alpha[0];
if (p->dir.hit[0] == 0)
ie--;
else
ie++;
X_elev = (double)ie * elev->delX;
}
if (reallyhit[1]) {
hop = alpha[1];
if (p->dir.hit[1] == 0)
je--;
else
je++;
Y_elev = (double)je * elev->delY;
}
for (i = 0; i < 3; i++)
xact[i] += hop * p->dir.dx[i];
/* finally, adjust data to grid to avoid roundoff errors */
if (reallyhit[0]) {
if (fabs (xact[0] - X) > MC_EPSILON) {
fprintf (stderr, "PANIC, expected xact[0] = %g to be X = %g in cross_surface().\n", xact[0], X);
return -1;
} else
xact[0] = X;
}
if (reallyhit[1]) {
if (fabs (xact[1] - Y) > MC_EPSILON) {
fprintf (stderr, "PANIC, expected xact[1] = %g to equal Y = %g in cross_surface().\n", xact[1], Y);
return -1;
} else
xact[1] = Y;
}
/* stop if step is exceeded */
stepact += hop;
if (stepact > step)
break;
/* adjust for periodic boundary conditions */
switch (bcond) {
case MCBCOND_PERIODIC:
if (ie == -1) {
ie = elev->Nx - 1;
X_elev = (double)ie * elev->delX;
xact[0] += (double)elev->Nx * elev->delX;
} else {
if (ie == elev->Nx) {
ie = 0;
X_elev = (double)ie * elev->delX;
xact[0] -= (double)elev->Nx * elev->delX;
}
}
if (je == -1) {
je = elev->Ny - 1;
Y_elev = (double)je * elev->delY;
xact[1] += (double)elev->Ny * elev->delY;
} else {
if (je == elev->Ny) {
je = 0;
Y_elev = (double)je * elev->delY;
xact[1] -= (double)elev->Ny * elev->delY;
}
}
break;
case MCBCOND_MIRROR:
fprintf (stderr, "Error, mirroring boundary conditions not implemented with topography.\n");
fprintf (stderr, "No specific reason, except lazyness of the developer!\n");
return -1;
case MCBCOND_ABSORB:
if (ie == -1 || ie == elev->Nx || je == -1 || je == elev->Ny) {
/*fprintf(stderr,"absorbing surface photon \n");*/
p->photon_status = MCSTATUS_OUTOFDOMAIN;
p->weight = 0.0;
return 0;
}
break;
default:
fprintf (stderr, "Error, unknown boundary conditions %d\n", bcond);
return -1;
}
}
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr,
"counters %d %d %d %d --- result of cross_surface: heureka %d gamma %e\n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
heureka,
*gamma);
#endif
return heureka;
}
/***********************************************************************************/
/* Function: cp_1D_to_3D @62_30i@ */
/* Description: */
/* Copy 1D profile to 3D profile, assuming constant optical properties within */
/* each layer. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int cp_1D_to_3D (profile3D* p3D, profile* p) {
int isp = 0, kc = 0, ic = 0, jc = 0;
if (p3D->n_caoth > p->n_caoth) {
fprintf (stderr, "ERROR, cannot copy profile, dimensions different! %d %d\n", p3D->n_caoth, p->n_caoth);
return -1;
}
for (isp = 0; isp <= p3D->n_caoth; isp++)
if (p3D->tocalloc[isp])
for (kc = 0; kc < p3D->Nz; kc++)
if (p3D->threed[isp][kc] >= 1)
for (ic = 0; ic < p3D->Nx; ic++)
for (jc = 0; jc < p3D->Ny; jc++)
p3D->prof[isp][kc][ic][jc] = p->prof[isp][kc];
return 0;
}
/***********************************************************************************/
/* Function: setup_thermal @62_30i@ */
/* Description: */
/* Initialize thermal emission; calculate emission of each box */
/* (emissivity * planck function), determine maximum emission and the total */
/* energy emitted by the atmosphere. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int setup_thermal (float*** temper,
int temper3d,
int cldNx,
int cldNy,
int nlyr,
float wvnmlo,
float wvnmhi,
profile* kabs,
profile3D* kabs3D,
float* Z,
int source,
int absorption,
int thermal_heating_method,
profile3D** Bplanck,
double* maxemis,
double* Watm,
surftemp_struct* surftemp,
int backward,
float zstart,
int* backemis_kc,
int nlambda_abs,
float* lambda,
double*** Bplanck_spectral,
t_triangular_surface* triangular_surface,
int quiet,
long int nphotons,
sample_struct* sample) /* **CK 2013.08.27 Added nphotons and sample_struct, added cldNx and CldNy*/
{
int ic = 0, jc = 0, lc = 0;
int it = 0, jt = 0;
/* **CK 2013.08.27 Add new variables for thermal backward heating rate calculation */
int i = 0;
int phot_fourth = 0, n_miss = 0;
int use_dEnet = 0; /* checking weather dEnet is used */
static int isNx = 0; /*store number of x gridboxes of actual layer */
double a_xy = 0.0, a_xz = 0.0, a_yz = 0.0, a = 0.0; /* area fraction of grid box face and sum of the three fractions */
double v = 0.0; /* grid box volume */
double rho = 0.0; /* random number */
double taux = 0.0, tauy = 0.0, tauz = 0.0,
taumin = 0.0; /* optical thickness in x,y and z direction and minimum optical thickness of those three */
double tau_crossover = 0.0; /* crossover optical thickness to switch methods */
/* **CK END */
float temp = 0;
/* float plkavg=0; */
int iv = 0;
int* tocalloc = NULL;
int** threed = NULL;
int isp = 0;
/* reset output data */
*maxemis = 0;
*Watm = 0;
/* 3D temperature is defined for full atmosphere, therefore all levels will be allocated for profile3D BPlanck*/
tocalloc = calloc (2, sizeof (int));
ASCII_calloc_int (&threed, 2, nlyr + 1);
for (isp = 0; isp <= 1; isp++) {
tocalloc[isp] = 1;
for (lc = 0; lc < nlyr + 1; lc++) {
threed[isp][lc] = 1;
}
}
/* need nlyr+1 points because emission is defined */
/* at levels, not at layers */
*Bplanck = calloc_profile3D (1, tocalloc, nlyr + 1, kabs3D->Nx, kabs3D->Ny, threed);
if (*Bplanck == NULL) {
fprintf (stderr, "Error allocating memory for Bplanck\n");
return -1;
}
/* 3DAbs Planck needs to be extended to 3D */
if (nlambda_abs > 0) {
*Bplanck_spectral = calloc (nlambda_abs, sizeof (double*));
for (iv = 0; iv < nlambda_abs; iv++)
(*Bplanck_spectral)[iv] = calloc (nlyr + 1, sizeof (double));
}
if (source == MCSRC_THERMAL_ATMOSPHERE || source == MCSRC_THERMAL_BACKWARD) { /*TZ bt*/
/* thermal emission: */
/* calculate wavelength integrated Planck function at levels */
for (lc = 0; lc < nlyr + 1; lc++) {
for (ic = 0; ic < kabs3D->Nx; ic++) {
for (jc = 0; jc < kabs3D->Ny; jc++) {
/* F77_FUNC (cplkavg, CPLKAVG) (&wvnmlo, &wvnmhi, &temper[lc], &plkavg); */
/* (*Bplanck)->prof [MCCAOTH_TOT][lc] = plkavg; */
if (temper3d)
(*Bplanck)->prof[MCCAOTH_TOT][lc][ic][jc] = c_planck_func1 (wvnmlo, wvnmhi, temper[ic][jc][lc]);
else
(*Bplanck)->prof[MCCAOTH_TOT][lc][ic][jc] = c_planck_func1 (wvnmlo, wvnmhi, temper[0][0][lc]);
}
}
if (nlambda_abs > 1) {
for (iv = 0; iv < nlambda_abs; iv++) {
(*Bplanck_spectral)[iv][lc] = c_planck_func1 (1e7 / lambda[iv] - 0.5, 1e7 / lambda[iv] + 0.5, temper[ic][jc][lc]);
}
}
}
{ /* determine average total column emissivity: required for */
/* absolute calibration of irradiance and radiance */
double Wsum = 0;
/* column integrated emitted flux */
for (lc = 0; lc < nlyr; lc++) {
double dz = Z[lc + 1] - Z[lc];
if (kabs3D->threed[MCCAOTH_TOT][lc] >= 1) {
for (ic = 0; ic < kabs3D->Nx; ic++) {
for (jc = 0; jc < kabs3D->Ny; jc++) {
Wsum += ((*Bplanck)->prof[MCCAOTH_TOT][lc][ic][jc] + (*Bplanck)->prof[MCCAOTH_TOT][lc + 1][ic][jc]) * .5 *
kabs3D->prof[MCCAOTH_TOT][lc][ic][jc] * dz;
}
}
} else {
double col_emis = ((*Bplanck)->prof[MCCAOTH_TOT][lc][0][0] + (*Bplanck)->prof[MCCAOTH_TOT][lc + 1][0][0]) * .5 *
kabs->prof[MCCAOTH_TOT][lc] * dz;
Wsum += col_emis * kabs3D->Nx * kabs3D->Ny;
}
}
/* average Ws over all columns */
/* ??? need to check if this gives the correct number for 3D calcs ??? CHECK!!! */
*Watm = Wsum / (kabs3D->Nx * kabs3D->Ny);
*Watm *= (4.0 * PI); /* integrate radiance over 4 pi */
}
/* determine maximum emission (= emissivity * Bplanck) */
for (lc = 0; lc < nlyr; lc++) {
if (kabs3D->threed[MCCAOTH_TOT][lc] >= 1) {
for (ic = 0; ic < kabs3D->Nx; ic++) {
for (jc = 0; jc < kabs3D->Ny; jc++) {
const double emis = ((*Bplanck)->prof[MCCAOTH_TOT][lc + 1][ic][jc] > (*Bplanck)->prof[MCCAOTH_TOT][lc][ic][jc]
? (*Bplanck)->prof[MCCAOTH_TOT][lc + 1][ic][jc]
: (*Bplanck)->prof[MCCAOTH_TOT][lc][ic][jc]) *
kabs3D->prof[MCCAOTH_TOT][lc][ic][jc];
if (emis > *maxemis)
*maxemis = emis;
}
}
} else {
const double emis = ((*Bplanck)->prof[MCCAOTH_TOT][lc + 1][0][0] > (*Bplanck)->prof[MCCAOTH_TOT][lc][0][0]
? (*Bplanck)->prof[MCCAOTH_TOT][lc + 1][0][0]
: (*Bplanck)->prof[MCCAOTH_TOT][lc][0][0]) *
kabs->prof[MCCAOTH_TOT][lc];
if (emis > *maxemis)
*maxemis = emis;
}
}
if (source != MCSRC_THERMAL_BACKWARD) { /*TZ bt*/
/* normalize Bplanck to maximum probability; */
/* attention: after this normalization, Bplanck */
/* is of course no longer the Planck function */
if (*maxemis > 0)
for (lc = 0; lc <= nlyr; lc++) {
for (ic = 0; ic < kabs3D->Nx; ic++) {
for (jc = 0; jc < kabs3D->Ny; jc++) {
(*Bplanck)->prof[MCCAOTH_TOT][lc][ic][jc] /= *maxemis;
}
}
}
} /*TZ bt*/
}
if (absorption == MCFORWARD_ABS_EMISSION) {
/* thermal emission: */
/* calculate wavelength integrated Planck function at levels */
for (lc = 0; lc < nlyr + 1; lc++) {
for (ic = 0; ic < kabs3D->Nx; ic++) {
for (jc = 0; jc < kabs3D->Ny; jc++) {
/* F77_FUNC (cplkavg, CPLKAVG) (&wvnmlo, &wvnmhi, &temper[lc], &plkavg); */
/* (*Bplanck)->prof [MCCAOTH_TOT][lc] = plkavg; */
(*Bplanck)->prof[MCCAOTH_TOT][lc][ic][jc] = c_planck_func1 (wvnmlo, wvnmhi, temper[ic][jc][lc]);
}
}
}
}
/* 2D surface temperature distribution */
if (surftemp->surf2D)
for (it = 0; it < surftemp->Nx; it++)
for (jt = 0; jt < surftemp->Ny; jt++) {
temp = surftemp->temp2D[it][jt];
/* F77_FUNC (cplkavg, CPLKAVG) (&wvnmlo, &wvnmhi, &temp, &plkavg); */
/* surftemp->plkavg2D[it][jt] = plkavg; */
surftemp->plkavg2D[it][jt] = c_planck_func1 (wvnmlo, wvnmhi, temp);
}
if (backward == MCBACKWARD_EMIS || backward == MCBACKWARD_HEAT) {
/* determine vertical box index kc */
/* ??? this could be made faster! CHECK!!! */
if (zstart > 0)
temp = zstart; /* zstart contains zout[0] (swap in setup_sample2D)*/
else
temp = Z[0];
*backemis_kc = -1;
/* Determine the internal z-index of the zstart given in input file */
while (Z[++(*backemis_kc)] < temp)
;
if (!quiet)
fprintf (stderr, " ... calculating emission for backward heating rate calculations in layer %d\n", *backemis_kc);
}
if (backward == MCBACKWARD_HEAT) {
/* ********************************************************************************* */
/* **CK 2013.08.27 Setting flag for thermal backward heating rate calculation method */
/* ********************************************************************************* */
/* ** free heat_flag if already allocated and allocate new! */
if (sample->heat_flag != NULL) {
for (ic = 0; ic < isNx; ic++) {
free (sample->heat_flag[ic]);
}
free (sample->heat_flag);
}
sample->heat_flag = calloc (sample->Nx, sizeof (int*));
for (ic = 0; ic < sample->Nx; ic++)
sample->heat_flag[ic] = calloc (sample->Ny, sizeof (int));
/* ******************************************************************************************************** */
/* **CK 2013.08.28 Check if sample grid and cloud grid have the same size. Optimized methods only work then */
/* ******************************************************************************************************** */
if (thermal_heating_method != MCBACKWARD_HEAT_EMABS) {
if ((sample->Nx != kabs3D->Nx) || (sample->Ny != kabs3D->Ny)) {
fprintf (stderr, " ***********************************************************************\n");
fprintf (stderr, " Atmospheric grid and the sample grid do not have the same size! \n");
fprintf (stderr, " Therefore, standard EMABS method is used, instead of optimized. \n");
fprintf (stderr, " ***********************************************************************\n");
for (ic = 0; ic < sample->Nx; ic++)
for (jc = 0; jc < sample->Ny; jc++)
sample->heat_flag[ic][jc] = MCBACKWARD_HEAT_EMABS;
return 0;
}
}
/* ************************************************* */
/* **CK 2013.08.27 EMABS is used. Set flag to EMABS */
/* ************************************************* */
switch (thermal_heating_method) {
case MCBACKWARD_HEAT_EMABS:
if (!quiet)
fprintf (stderr, " EMABS-method (unoptimized) is choosen. \n");
for (ic = 0; ic < sample->Nx; ic++)
for (jc = 0; jc < sample->Ny; jc++)
sample->heat_flag[ic][jc] = MCBACKWARD_HEAT_EMABS;
break;
/* **************************************************************************** */
/* **CK 2013.08.27 Check which optimized method is choosen and setup variables. */
/* If EMABS_OPT is used. Set flag to EMABSOPT. */
/* DENET is used. Set flag to DENET. */
/* HYBRID is used. Set flag to HYBRID. Hybrid is also default. */
/* **************************************************************************** */
case MCBACKWARD_HEAT_EMABSOPT:
if (!quiet)
fprintf (stderr, " EMABS_OPT method is choosen. \n");
for (ic = 0; ic < kabs3D->Nx; ic++) {
for (jc = 0; jc < kabs3D->Ny; jc++) {
if (kabs3D->threed[MCCAOTH_TOT][*backemis_kc] >= 1) { /* if 3d */
taux = kabs3D->prof[MCCAOTH_TOT][*backemis_kc][ic][jc] * sample->delX;
tauy = kabs3D->prof[MCCAOTH_TOT][*backemis_kc][ic][jc] * sample->delY;
tauz = kabs3D->prof[MCCAOTH_TOT][*backemis_kc][ic][jc] * (Z[*backemis_kc + 1] - Z[*backemis_kc]);
taumin = find_min (taux, tauy, tauz);
if (taux * tauy * tauz > 100000000) {
fprintf (stderr, " ***********************************************************************\n");
fprintf (stderr, " The optical thickness is very large. Large optical thicknesses \n");
fprintf (stderr, " need huge amounts of memory if EMABS_OPT is chosen. Please \n");
fprintf (stderr, " use DENET or HYBRID method and restart! \n");
fprintf (stderr, " ***********************************************************************\n");
return -1;
}
}
if (taumin <= 2) /*make sure that grid box can be split in sub cubes, if not, use EMABS*/
sample->heat_flag[ic][jc] = MCBACKWARD_HEAT_EMABS;
else
sample->heat_flag[ic][jc] = MCBACKWARD_HEAT_EMABSOPT;
}
}
break;
case MCBACKWARD_HEAT_DENET:
if (!quiet)
fprintf (stderr, " DENET method is choosen. \n");
for (ic = 0; ic < sample->Nx; ic++)
for (jc = 0; jc < sample->Ny; jc++)
sample->heat_flag[ic][jc] = MCBACKWARD_HEAT_DENET;
use_dEnet = 1;
break;
case MCBACKWARD_HEAT_HYBRID:
if (!quiet)
fprintf (stderr, " HYBRID method is choosen. \n");
/* *** set flag with crossover optical thickness - using EMABS_OPT or DENET Method *** */
for (ic = 0; ic < kabs3D->Nx; ic++) {
for (jc = 0; jc < kabs3D->Ny; jc++) {
if (kabs3D->threed[MCCAOTH_TOT][*backemis_kc] >= 1) { /* if 3d */
taux = kabs3D->prof[MCCAOTH_TOT][*backemis_kc][ic][jc] * sample->delX;
tauy = kabs3D->prof[MCCAOTH_TOT][*backemis_kc][ic][jc] * sample->delY;
tauz = kabs3D->prof[MCCAOTH_TOT][*backemis_kc][ic][jc] * (Z[*backemis_kc + 1] - Z[*backemis_kc]);
taumin = find_min (taux, tauy, tauz);
} else
taumin = kabs->prof[MCCAOTH_TOT][*backemis_kc];
tau_crossover = 5.0;
if (taumin < tau_crossover) {
// change 14.9.2017, CK and BM: MCBACKWARD_HEAT_EMABSOPT causes problems with "flat" grid boxes (dx >> dz)
// where a lot of memory is allocated in generate_photon_backward_vertical_heat(); therefore
// using EMABS instead of EMABS_OPT in accordance with the conclusions in Klinger and Mayer (2014)
// sample->heat_flag[ic][jc] = MCBACKWARD_HEAT_EMABSOPT;
// if(taumin<=2) /*make sure that grid box can be split in sub cubes, if not, use EMABS*/
// sample->heat_flag[ic][jc] = MCBACKWARD_HEAT_EMABS;
sample->heat_flag[ic][jc] = MCBACKWARD_HEAT_EMABS;
} else {
sample->heat_flag[ic][jc] = MCBACKWARD_HEAT_DENET;
use_dEnet = 1;
}
}
}
break; /* end HYBRID */
default:
fprintf (stderr, " ***********************************************************************\n");
fprintf (stderr, " Error! No calculation method for thermal backward heating rates is set! \n");
fprintf (stderr, " ***********************************************************************\n");
return -1;
}
/* *********************************************************************************** */
/* if DENET method is used, or DENET is used within HYBRID, make following calculation */
/* Set area fraction for photon distribution. Photons are distirbuted according to the */
/* face area of a grid box which may vary if the grid box is non-cubic. */
/* *********************************************************************************** */
if (kabs3D->threed[MCCAOTH_TOT][*backemis_kc] >= 1) { /* if 3d */
if (use_dEnet) {
phot_fourth = nphotons / 4;
a_xy = sample->delX * sample->delY;
a_xz = sample->delX * (Z[*backemis_kc + 1] - Z[*backemis_kc]);
a_yz = sample->delY * (Z[*backemis_kc + 1] - Z[*backemis_kc]);
v = sample->delX * sample->delY * (Z[*backemis_kc + 1] - Z[*backemis_kc]);
a = a_xy + a_xz + a_yz;
sample->weight_heat = (Z[*backemis_kc + 1] - Z[*backemis_kc]) / v * a;
a_xy = a_xy / a;
a_xz = a_xz / a;
a_yz = a_yz / a;
sample->n_xy = (int)(a_xy * phot_fourth);
sample->n_xz = (int)(a_xz * phot_fourth);
sample->n_yz = (int)(a_yz * phot_fourth);
n_miss = phot_fourth - sample->n_xy - sample->n_xz - sample->n_yz;
for (i = 0; i < n_miss; i++) {
rho = uvspec_random();
if (rho < ((a_xy * phot_fourth - sample->n_xy) / (phot_fourth - sample->n_xy - sample->n_xz - sample->n_yz)))
sample->n_xy++;
else if (rho < 1 - ((a_yz * phot_fourth - sample->n_yz) / (phot_fourth - sample->n_xy - sample->n_xz - sample->n_yz)))
sample->n_xz++;
else
sample->n_yz++;
}
sample->n_xy = sample->n_xy * 4;
sample->n_xz = sample->n_xz * 4;
sample->n_yz = sample->n_yz * 4;
if (sample->n_xy + sample->n_xz + sample->n_yz != nphotons) {
fprintf (stderr,
"Error, number of photons not consistent!! %d %ld \n",
sample->n_xy + sample->n_xz + sample->n_yz,
nphotons);
return 0;
}
} /* close use_dEnet */
isNx =
kabs3D
->Nx; /* set isNx to number of x-gridboxes; this simulation is performed in 3d mode -- necessary to free sample->heat_flag for next layer */
} /* end 3d */
else { /* if 1d */
if (use_dEnet) {
phot_fourth = nphotons / 4;
sample->n_xy = (int)phot_fourth;
sample->n_xy = sample->n_xy * 4;
if (sample->n_xy != nphotons) {
fprintf (stderr, "Error, number of photons not consistent!! %d %ld \n", sample->n_xy, nphotons);
return 0;
}
} /* close use_dEnet */
isNx =
1; /* set isNx to number of x-gridboxes; this simulation is performed in 3d mode -- necessary to free sample->heat_flag for next layer */
} /* end 1d */
} /* close backward = MCBACKWARD_HEAT*/
if (triangular_surface->N_triangles && triangular_surface->temperature_of_triangle) {
if (!triangular_surface->Bplanck_of_triangle)
CHKERROUT (1, "Triangle surface is enabled but BPlanck array is not allocated");
for (size_t i = 0; i < triangular_surface->N_triangles; ++i)
triangular_surface->Bplanck_of_triangle[i] = c_planck_func1 (wvnmlo, wvnmhi, triangular_surface->temperature_of_triangle[i]);
}
return 0;
}
/***********************************************************************************/
/* Function: setup_caoth3D @62_30i@ */
/* Description: */
/* Initialize the 3D part of the atmosphere_struct with the caoth data read from */
/* filename. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int setup_caoth3D (caoth3d_out_struct* caoth3d,
int nxcld,
int nycld,
int nzcld,
int* threed,
double dxcld,
double dycld,
float wavelength,
atmosphere_struct* atmos,
char* datapath,
int delta_scaling,
int spherical3D,
int spherical3D_scene,
double spherical3D_scene_lon_min,
double spherical3D_scene_lon_max,
double spherical3D_scene_lat_min,
double spherical3D_scene_lat_max,
float r_earth,
float sza,
int setup_tipa,
int visualize,
int sample_cldprp,
int quiet) {
int status = 0, i = 0, ic = 0, jc = 0, kc = 0, ids = 0, iris = 0, ivs = 0, isp = 0, ispo = 0, n_caoth = 0;
int found_raytracing_prop = 0;
int* tocalloc;
/* copy 3D caoth data to final destination */
atmos->Nx = nxcld;
atmos->Ny = nycld;
atmos->delX = dxcld;
atmos->delY = dycld;
atmos->scatter_type = calloc ((size_t)atmos->n_caoth + 1, sizeof (int));
/* allocate indices array to locate water and ice profiles for subsequent lookups */
atmos->i_wc = calloc ((size_t)atmos->n_caoth + 1, sizeof (int));
atmos->i_ic = calloc ((size_t)atmos->n_caoth + 1, sizeof (int));
atmos->r_earth = (double)r_earth;
/* molecular scatter type */
atmos->scatter_type[MCCAOTH_MOL] = MCSCAT_MOL;
/* aerosol scatter type is set in setup_aerosol1D */
/* scatter types of other caoth */
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++) {
ispo = isp - MCCAOTH_FIR;
if (caoth3d[ispo].nonHG)
atmos->scatter_type[isp] = MCSCAT_PFT;
else
atmos->scatter_type[isp] = MCSCAT_HG2;
/* transfer indices of water and ice from coath3d to atmos structure
for subsequent lookups since caoth arrangement can be arbitrary */
if (strncasecmp (caoth3d[ispo].name, "wc", 2) == 0)
atmos->i_wc[isp] = 1;
if (strncasecmp (caoth3d[ispo].name, "ic", 2) == 0)
atmos->i_ic[isp] = 1;
}
atmos->phase = calloc ((size_t)atmos->n_caoth + 1, sizeof (phase_function_table*));
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++) {
ispo = isp - MCCAOTH_FIR;
atmos->phase[isp] = &(caoth3d[ispo].phase);
}
atmos->caoth_name = calloc ((size_t)atmos->n_caoth + 1, sizeof (char*));
atmos->caoth_name[MCCAOTH_TOT] = (char*)calloc (strlen ("total") + 1, sizeof (char));
strcpy (atmos->caoth_name[MCCAOTH_TOT], "total");
atmos->caoth_name[MCCAOTH_MOL] = (char*)calloc (strlen ("molecular") + 1, sizeof (char));
strcpy (atmos->caoth_name[MCCAOTH_MOL], "molecular");
atmos->caoth_name[MCCAOTH_AER] = (char*)calloc (strlen ("aerosol") + 1, sizeof (char));
strcpy (atmos->caoth_name[MCCAOTH_AER], "aerosol");
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++) {
ispo = isp - MCCAOTH_FIR;
atmos->caoth_name[isp] = (char*)calloc (strlen (caoth3d[ispo].fullname) + 1, sizeof (char));
strcpy (atmos->caoth_name[isp], caoth3d[ispo].fullname);
}
/* Set scatter type to Rayleigh for molecular_3d. */
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++)
if (strcmp (atmos->caoth_name[isp], "profile molecular_3d") == 0)
atmos->scatter_type[isp] = MCSCAT_MOL;
if (!quiet) {
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++) {
if (atmos->scatter_type[isp] == MCSCAT_MOL)
fprintf (stderr, " ... %s considered with Rayleigh phase function \n", atmos->caoth_name[isp]);
else if (atmos->scatter_type[isp] == MCSCAT_PFT)
fprintf (stderr, " ... %s considered with explicit phase function\n", atmos->caoth_name[isp]);
else
fprintf (stderr, " ... %s considered with Henyey-Greenstein phase function\n", atmos->caoth_name[isp]);
}
}
/* XXX part of the stuff above here should be somewhere else */
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++) {
ispo = isp - MCCAOTH_FIR;
/* check if water caoth file levels agree with the 1D atmospheric profile */
if (caoth3d[ispo].nthreed >= 1) {
if (!quiet)
fprintf (stderr, " ... checking 3D %s levels\n", caoth3d[ispo].fullname);
/* make sure that 1D and 3D properties are defined on the same altitude grid */
status = compare_levels (caoth3d[ispo].zd, caoth3d[ispo].nlyr, atmos->Z, atmos->Nz);
if (status != 0) {
fprintf (stderr, "\nFATAL error: z-grid of 1D atmosphere and 3D caoths are different\n");
return status;
}
}
}
/********************************************************/
/* determine threed profile: threed is true for a layer */
/* if it contains caoth */
/********************************************************/
atmos->nthreed = calloc ((size_t)atmos->n_caoth + 1, sizeof (int));
atmos->threed = calloc ((size_t)atmos->n_caoth + 1, sizeof (int*));
for (isp = 0; isp <= atmos->n_caoth; isp++)
atmos->threed[isp] = calloc ((size_t)atmos->Nz, sizeof (int));
for (kc = 0; kc < atmos->Nz; kc++) {
atmos->threed[MCCAOTH_TOT][kc] = threed[kc];
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++) {
ispo = isp - MCCAOTH_FIR;
if (caoth3d[ispo].nthreed >= 1) {
atmos->threed[isp][kc] = caoth3d[ispo].threed[kc];
atmos->threed[MCCAOTH_TOT][kc] += caoth3d[ispo].threed[kc];
}
}
for (isp = 0; isp <= atmos->n_caoth; isp++)
if (atmos->threed[isp][kc] >= 1)
atmos->nthreed[isp]++;
}
if (!quiet)
fprintf (stderr, " ... found %d 3D layers\n", atmos->nthreed[MCCAOTH_TOT]);
/************************************************************/
/* Now check if we have 1D and 3D caoths in the same layer. */
/* We don't want that because it may cause confusion! */
/* Exception is in case of spherical3D-scenes, then 1d is */
/* outside the scene */
/************************************************************/
status = 0;
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++) {
ispo = isp - MCCAOTH_FIR;
if (caoth3d[ispo].nthreed >= 1)
for (kc = 0; kc < atmos->Nz; kc++)
if (caoth3d[ispo].threed[kc] >= 1)
if (atmos->ksca[MCSC_MODE_NORMAL][MCRIS_MODE_NORMAL]->prof[isp][kc] + atmos->kabs->prof[isp][kc] > 0.0) {
fprintf (stderr, "Error, found 1D AND 3D %s in layer %d.\n", caoth3d[ispo].fullname, kc);
fprintf (stderr, "Don't know how to handle that - must be programming error!\n");
status++;
}
}
if (status != 0)
return status;
/* allocate memory for 3D profiles */
tocalloc = calloc (atmos->n_caoth + 1, sizeof (int));
/* absorption and extinction coefficients are needed for total only */
for (isp = 0; isp <= atmos->n_caoth; isp++)
tocalloc[isp] = 0;
if (atmos->nthreed[MCCAOTH_TOT] >= 1)
tocalloc[MCCAOTH_TOT] = 1;
n_caoth = 0;
#ifdef CLDPRP
if (sample_cldprp) {
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++) {
if (atmos->i_wc[isp] || atmos->i_ic[isp])
tocalloc[isp] = 1;
}
n_caoth = atmos->n_caoth;
}
#endif
atmos->kabs3D = calloc_profile3D (n_caoth, tocalloc, atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed);
if (atmos->kabs3D == NULL)
return mem_err_out ("atmos->kabs3D", ERROR_POSITION);
atmos->kext3D = calloc (atmos->nscaDS, sizeof (profile3D**));
if (atmos->kext3D == NULL)
return mem_err_out ("atmos->kext3D", ERROR_POSITION);
for (ids = 0; ids < atmos->nscaDS; ids++) {
atmos->kext3D[ids] = calloc (atmos->nscaRIS, sizeof (profile3D*));
if (atmos->kext3D[ids] == NULL)
return mem_err_out ("atmos->kext3D[]", ERROR_POSITION);
}
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++) {
atmos->kext3D[ids][iris] = calloc (atmos->nscaVIS, sizeof (profile3D));
if (atmos->kext3D[ids][iris] == NULL)
return mem_err_out ("atmos->kext3D[][]", ERROR_POSITION);
}
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
for (ivs = 0; ivs < atmos->nscaVIS; ivs++) {
atmos->kext3D[ids][iris][ivs] = calloc_profile3D (0, tocalloc, atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed);
if (atmos->kext3D[ids][iris][ivs] == NULL)
return mem_err_out ("atmos->kext3D[][][]", ERROR_POSITION);
}
/* scattering coefficients are needed for all cases in which threed layers exist */
for (isp = 0; isp <= atmos->n_caoth; isp++)
tocalloc[isp] = 0;
for (isp = 0; isp <= atmos->n_caoth; isp++)
if (atmos->nthreed[isp] >= 1)
tocalloc[isp] = 1;
atmos->ksca3D = calloc (atmos->nscaDS, sizeof (profile3D*));
if (atmos->ksca3D == NULL)
return mem_err_out ("atmos->ksca3D", ERROR_POSITION);
for (ids = 0; ids < atmos->nscaDS; ids++) {
atmos->ksca3D[ids] = calloc (atmos->nscaRIS, sizeof (profile3D));
if (atmos->ksca3D[ids] == NULL)
return mem_err_out ("atmos->ksca3D[]", ERROR_POSITION);
}
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++) {
atmos->ksca3D[ids][iris] = calloc_profile3D (atmos->n_caoth, tocalloc, atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed);
if (atmos->ksca3D[ids][iris] == NULL)
return mem_err_out ("atmos->ksca3D[][]", ERROR_POSITION);
}
/* HG parameters are needed for HG 3d caoth only */
for (isp = 0; isp <= atmos->n_caoth; isp++)
tocalloc[isp] = 0;
for (isp = 1; isp <= atmos->n_caoth; isp++)
if (atmos->nthreed[isp] >= 1 && !(atmos->scatter_type[isp] == MCSCAT_PFT))
tocalloc[isp] = 1;
atmos->g1_3D = calloc_profile3D (atmos->n_caoth, tocalloc, atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed);
if (atmos->g1_3D == NULL)
return mem_err_out ("atmos->g1_3D", ERROR_POSITION);
atmos->g2_3D = calloc_profile3D (atmos->n_caoth, tocalloc, atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed);
if (atmos->g2_3D == NULL)
return mem_err_out ("atmos->g2_3D", ERROR_POSITION);
atmos->ff_3D = calloc_profile3D (atmos->n_caoth, tocalloc, atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed);
if (atmos->ff_3D == NULL)
return mem_err_out ("atmos->ff_3D", ERROR_POSITION);
/* r_eff are needed for pft 3d caoth only */
for (isp = 0; isp <= atmos->n_caoth; isp++)
tocalloc[isp] = 0;
for (isp = 1; isp <= atmos->n_caoth; isp++)
if (atmos->nthreed[isp] >= 1 && atmos->scatter_type[isp] == MCSCAT_PFT)
tocalloc[isp] = 1;
atmos->reff_3D = calloc_profile3D (atmos->n_caoth, tocalloc, atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed);
if (atmos->reff_3D == NULL)
return mem_err_out ("atmos->reff_3D", ERROR_POSITION);
#ifdef CLDPRP
if (sample_cldprp) {
atmos->sample_cldprp = 1;
atmos->dxlwc_3D = calloc_profile3D (atmos->n_caoth, tocalloc, atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed);
atmos->dylwc_3D = calloc_profile3D (atmos->n_caoth, tocalloc, atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed);
atmos->dzlwc_3D = calloc_profile3D (atmos->n_caoth, tocalloc, atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed);
}
#endif
/* copy raytracing properties */
found_raytracing_prop = 0;
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++) {
ispo = isp - MCCAOTH_FIR;
if (strncasecmp (caoth3d[ispo].name, "ic", 2) == 0 && caoth3d[ispo].n_raytracing_prop > 0) {
found_raytracing_prop = 1;
break;
}
}
if (found_raytracing_prop > 0) {
atmos->raytracing_prop = calloc (caoth3d[ispo].n_raytracing_prop, sizeof (crystal_prop_struct));
atmos->n_raytracing_prop = caoth3d[ispo].n_raytracing_prop;
for (i = 0; i < atmos->n_raytracing_prop; i++) {
if (!quiet)
fprintf (stderr, "CAOTH = %s\n", caoth3d[ispo].raytracing_prop[i].name);
(atmos->raytracing_prop)[i].name = calloc (strlen (caoth3d[ispo].raytracing_prop[i].name) + 1, sizeof (char));
strcpy (atmos->raytracing_prop[i].name, caoth3d[ispo].raytracing_prop[i].name);
atmos->raytracing_prop[i].fraction = caoth3d[ispo].raytracing_prop[i].fraction;
atmos->raytracing_prop[i].oriented_fraction = caoth3d[ispo].raytracing_prop[i].oriented_fraction;
atmos->raytracing_prop[i].angdist_width = caoth3d[ispo].raytracing_prop[i].angdist_width;
atmos->raytracing_prop[i].orientation_dof = caoth3d[ispo].raytracing_prop[i].orientation_dof;
}
}
/**********************/
/* now fill 3D arrays */
/**********************/
/* copy 1D properties to 3D profiles */
/* liquid, ice, and total (=liquid + ice + molecules + aerosol + ...) */
/* The newest version only copies what really is needed. */
status = cp_1D_to_3D (atmos->kabs3D, atmos->kabs);
if (status != 0)
return err_out ("Error %d returned by cp_1D_to_3D(kabs)\n", status);
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++) {
status = cp_1D_to_3D (atmos->ksca3D[ids][iris], atmos->ksca[ids][iris]);
if (status != 0)
return err_out ("Error %d returned by cp_1D_to_3D(ksca)\n", status);
}
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
for (ivs = 0; ivs < atmos->nscaVIS; ivs++) {
status = cp_1D_to_3D (atmos->kext3D[ids][iris][ivs], atmos->kext[ids][iris][ivs]);
if (status != 0)
return err_out ("Error %d returned by cp_1D_to_3D(kext)\n", status);
}
status = cp_1D_to_3D (atmos->g1_3D, atmos->g1);
if (status != 0)
return err_out ("Error %d returned by cp_1D_to_3D(g1)\n", status);
status = cp_1D_to_3D (atmos->g2_3D, atmos->g2);
if (status != 0)
return err_out ("Error %d returned by cp_1D_to_3D(g2)\n", status);
status = cp_1D_to_3D (atmos->ff_3D, atmos->ff);
if (status != 0)
return err_out ("Error %d returned by cp_1D_to_3D(ff)\n", status);
status = cp_1D_to_3D (atmos->reff_3D, atmos->reff);
if (status != 0)
return err_out ("Error %d returned by cp_1D_to_3D(reff)\n", status);
/* fill 3D optical properties */
if (atmos->nthreed[MCCAOTH_TOT] > 0) {
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++) {
ispo = isp - MCCAOTH_FIR;
if (atmos->nthreed[isp] >= 1) {
for (kc = 0; kc < atmos->Nz; kc++) {
if (atmos->threed[isp][kc] >= 1) {
for (ic = 0; ic < atmos->Nx; ic++) {
for (jc = 0; jc < atmos->Ny; jc++) {
/* for now no IS */
iris = MCRIS_MODE_NORMAL;
atmos->ksca3D[MCSC_MODE_NORMAL][iris]->prof[isp][kc][ic][jc] =
caoth3d[ispo].ext[kc][ic][jc] * caoth3d[ispo].ssa[kc][ic][jc];
if (delta_scaling > -1)
atmos->ksca3D[MCSC_MODE_DELTA_SCALE][iris]->prof[isp][kc][ic][jc] =
caoth3d[ispo].ext[kc][ic][jc] * caoth3d[ispo].ssa[kc][ic][jc] * (1.0 - caoth3d[ispo].dscale[kc][ic][jc]);
if (atmos->scatter_type[isp] == MCSCAT_PFT)
atmos->reff_3D->prof[isp][kc][ic][jc] = caoth3d[ispo].reff[kc][ic][jc];
else {
atmos->g1_3D->prof[isp][kc][ic][jc] = caoth3d[ispo].g1[kc][ic][jc];
atmos->g2_3D->prof[isp][kc][ic][jc] = caoth3d[ispo].g2[kc][ic][jc];
atmos->ff_3D->prof[isp][kc][ic][jc] = caoth3d[ispo].ff[kc][ic][jc];
}
#ifdef CLDPRP
if (sample_cldprp) {
/* fill 3D absorption properties, when sampling cloud optical properties */
if (atmos->scatter_type[isp] == MCSCAT_PFT) {
atmos->kabs3D->prof[isp][kc][ic][jc] += caoth3d[ispo].ext[kc][ic][jc] * (1.0 - caoth3d[ispo].ssa[kc][ic][jc]);
}
/* calculate dx/dy/dz gradients of the lwc/iwc */
if (ic < atmos->Nx - 1) {
atmos->dxlwc_3D->prof[isp][kc][ic][jc] =
(caoth3d[ispo].lwc[kc][ic + 1][jc] - caoth3d[ispo].lwc[kc][ic][jc]) / caoth3d[ispo].delX;
}
if (jc < atmos->Ny - 1) {
atmos->dylwc_3D->prof[isp][kc][ic][jc] =
(caoth3d[ispo].lwc[kc][ic][jc + 1] - caoth3d[ispo].lwc[kc][ic][jc]) / caoth3d[ispo].delY;
}
if (kc < atmos->Nz - 1 && atmos->threed[isp][kc + 1] >= 1) {
atmos->dzlwc_3D->prof[isp][kc][ic][jc] = (caoth3d[ispo].lwc[kc + 1][ic][jc] - caoth3d[ispo].lwc[kc][ic][jc]) /
(caoth3d[ispo].zd[kc + 1] - caoth3d[ispo].zd[kc]);
}
}
#endif
/* add 3D caoths to total scattering and absorption coefficients */
for (ids = 0; ids < atmos->nscaDS; ids++)
atmos->ksca3D[ids][iris]->prof[MCCAOTH_TOT][kc][ic][jc] += atmos->ksca3D[ids][iris]->prof[isp][kc][ic][jc];
atmos->kabs3D->prof[MCCAOTH_TOT][kc][ic][jc] +=
caoth3d[ispo].ext[kc][ic][jc] * (1.0 - caoth3d[ispo].ssa[kc][ic][jc]);
/* if ( strncasecmp(caoth3d[ispo].name, "molecular_3d", 3) && ic == 1 && jc==1 ){ */
/* fprintf(stderr, "kc %d Z %.2f ext %.4e \n", kc, atmos->Z[kc], caoth3d[ispo].ext[kc][ic][jc]); */
/* } */
/* copy into IS modes */
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 1; iris < atmos->nscaRIS; iris++) {
atmos->ksca3D[ids][iris]->prof[isp][kc][ic][jc] = atmos->ksca3D[ids][MCRIS_MODE_NORMAL]->prof[isp][kc][ic][jc];
atmos->ksca3D[ids][iris]->prof[MCCAOTH_TOT][kc][ic][jc] +=
atmos->ksca3D[ids][MCRIS_MODE_NORMAL]->prof[isp][kc][ic][jc];
}
} /* end for jc */
} /* end for ic */
} /* end if atmos->threed[isp][kc] */
} /* end for kc */
} /* end if atmos->nthreed[isp] */
} /* end for isp */
} /* end if atmos->nthreed[0] */
/* setup extinction coefficient profile; Virtual IS may not be set up before here! */
/* the memory consumption here could be reduced if we point instead of callocating */
if (atmos->nthreed[MCCAOTH_TOT] >= 1)
for (kc = 0; kc < atmos->Nz; kc++)
if (atmos->threed[MCCAOTH_TOT][kc] >= 1)
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
for (ivs = 0; ivs < atmos->nscaVIS; ivs++)
for (ic = 0; ic < atmos->Nx; ic++)
for (jc = 0; jc < atmos->Ny; jc++)
atmos->kext3D[ids][iris][ivs]->prof[MCCAOTH_TOT][kc][ic][jc] =
atmos->ksca3D[ids][iris]->prof[MCCAOTH_TOT][kc][ic][jc];
/* finally, create X[], Y[] arrays of grid coordinates */
if (spherical3D) {
#if HAVE_MYSTIC3D
status = setup_spherical3D ("atmos",
atmos->Nx,
atmos->Ny,
spherical3D_scene,
spherical3D_scene_lon_min,
spherical3D_scene_lon_max,
spherical3D_scene_lat_min,
spherical3D_scene_lat_max,
&(atmos->delX),
&(atmos->delY),
&(atmos->xmax),
&(atmos->ymax),
&(atmos->X),
&(atmos->Y),
&(atmos->Nyg),
&(atmos->Yg),
&(atmos->realY),
&(atmos->sin2_lat),
&(atmos->tan2_lat),
&(atmos->jc_eq),
quiet);
if (status)
return fct_err_out (status, "setup_spherical3D", ERROR_POSITION);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else {
atmos->X = calloc ((size_t) (atmos->Nx + 1), sizeof (double));
if (atmos->X == NULL)
return mem_err_out ("atmos->X", ERROR_POSITION);
atmos->Y = calloc ((size_t) (atmos->Ny + 1), sizeof (double));
if (atmos->Y == NULL)
return mem_err_out ("atmos->Y", ERROR_POSITION);
for (ic = 0; ic <= atmos->Nx; ic++)
atmos->X[ic] = (double)ic * atmos->delX;
for (jc = 0; jc <= atmos->Ny; jc++)
atmos->Y[jc] = (double)jc * atmos->delY;
/* horizontal boundaries */
atmos->xmax = (double)atmos->Nx * atmos->delX;
atmos->ymax = (double)atmos->Ny * atmos->delY;
}
/* set Ris Factor to 1 */
atmos->ris_factor = 1.;
#if HAVE_OPENGL
if (visualize)
GLmystic_write_caoth (atmos);
#endif
free (tocalloc);
return 0;
}
/***********************************************************************************/
/* Function: setup_albedo2D @62_30i@ */
/* Description: */
/* Initialize the 2D albedo_struct with the albedo data read from */
/* filename. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int setup_albedo2D (char* albedo_filename,
char* rossli_filename,
char* spectral_albedo_filename,
char* spectral_rpv_filename,
char* spectral_ambrals_filename,
int isAmbralsFile,
atmosphere_struct* atmos,
albedo_struct* albedo,
double alb,
float* alb_type,
float* rpv_rho0,
float* rpv_k,
float* rpv_theta,
float* rpv_scale,
float* rpv_sigma,
float* rpv_t1,
float* rpv_t2,
char** surface_labels,
int surface_nlabels,
float* hapke_h,
float* hapke_b0,
float* hapke_w,
float* rossli_iso,
float* rossli_vol,
float* rossli_geo,
int rossli_hotspot,
float u10,
float pcl,
float xsal,
float uphi,
int solar_wind,
float bpdf_u10,
int polarisation,
int spherical3D,
int spherical3D_scene,
double spherical3D_scene_lon_min,
double spherical3D_scene_lon_max,
double spherical3D_scene_lat_min,
double spherical3D_scene_lat_max,
int nlambda_abs,
double* alis_albedo,
double** alis_alb_type,
int ixmin,
int ixmax,
int iymin,
int iymax,
int quiet) {
int il = 0, status = 0, nfi = 0, therewereCaMs = 0, iv = 0;
static int first = 1;
/* BM, 8.9.2020: split into part which needs only be called once (if (first) ...) and should be moved outside mystic() */
/* and part which needs to be done for each wavelength (after if(first)) and which needs to stay here */
switch (albedo->method) {
case MCALB_LAM:
if (first) {
if (!quiet)
fprintf (stderr, " ... 1D albedo\n");
}
albedo->albedo = alb;
albedo->lambertian_albedo = alb;
if (nlambda_abs > 1) {
albedo->spectral_albedo =
calloc (nlambda_abs,
sizeof (double)); // BM: calloc should only be done once, if nlambda_abs is the same for all mystic() calls
for (iv = 0; iv < nlambda_abs; iv++)
albedo->spectral_albedo[iv] = alis_albedo[iv];
}
break;
case MCALB_LAM2D:
if (first) {
if (!quiet)
fprintf (stderr, " ... reading monochromatic 2D albedo data\n");
/* read 2D albedo data */
status = read_2D_albedo (albedo_filename,
&(albedo->Nx),
&(albedo->Ny),
&(albedo->delX),
&(albedo->delY),
&(albedo->albedo2D),
ixmin,
ixmax,
iymin,
iymax,
quiet);
if (status != 0) {
fprintf (stderr, "Error %d reading %s\n", status, albedo_filename);
return status;
}
if (!spherical3D) {
if (!equal ((double)(albedo->Nx) * albedo->delX, (double)atmos->Nx * atmos->delX)) {
fprintf (stderr,
"Error, x-size of albedo area (%g) does not equal x-size of cloud area (%g)\n",
(double)(albedo->Nx) * albedo->delX,
(double)atmos->Nx * atmos->delX);
return -1;
}
if (!equal ((double)(albedo->Ny) * albedo->delY, (double)atmos->Ny * atmos->delY)) {
fprintf (stderr,
"Error, y-size of albedo area (%g) does not equal y-size of cloud area (%g)\n",
(double)(albedo->Ny) * albedo->delY,
(double)atmos->Ny * atmos->delY);
return -1;
}
}
} // end if (first)
break;
case MCALB_LAM2D_SPECTRAL:
if (first) {
if (!quiet)
fprintf (stderr, " ... reading 2D albedo data from %s\n", spectral_albedo_filename);
/* 2D surface albedo */
status = read_2D_surface_labels (spectral_albedo_filename,
surface_labels,
surface_nlabels,
&(albedo->Nx),
&(albedo->Ny),
&(albedo->delX),
&(albedo->delY),
&(albedo->surface_index),
&(albedo->surface_count),
&therewereCaMs,
quiet);
if (status != 0) {
fprintf (stderr, "Error %d reading %s\n", status, spectral_albedo_filename);
return status;
}
if (!spherical3D) {
if (!equal ((double)(albedo->Nx) * albedo->delX, (double)atmos->Nx * atmos->delX)) {
fprintf (stderr,
"Error, x-size of 2D albedo area (%g) does not equal x-size of cloud area (%g)\n",
(double)(albedo->Nx) * albedo->delX,
(double)atmos->Nx * atmos->delX);
return -1;
}
if (!equal ((double)(albedo->Ny) * albedo->delY, (double)atmos->Ny * atmos->delY)) {
fprintf (stderr,
"Error, y-size of 2D albedo area (%g) does not equal y-size of cloud area (%g)\n",
(double)(albedo->Ny) * albedo->delY,
(double)atmos->Ny * atmos->delY);
return -1;
}
}
if (!quiet)
for (il = 0; il < surface_nlabels; il++)
fprintf (stderr, " ... found %d pixels with %s\n", albedo->surface_count[il], surface_labels[il]);
albedo->alb_type = calloc ((size_t)surface_nlabels, sizeof (double));
} // end if (first)
for (il = 0; il < surface_nlabels; il++)
if (albedo->surface_count[il])
albedo->alb_type[il] = alb_type[il];
/* spectral albedo type for ALIS */
if (nlambda_abs > 1) {
albedo->spectral_alb_type = calloc (surface_nlabels, sizeof (double*));
for (il = 0; il < surface_nlabels; il++) {
albedo->spectral_alb_type[il] = calloc (nlambda_abs, sizeof (double));
for (iv = 0; iv < nlambda_abs; iv++)
albedo->spectral_alb_type[il][iv] = alis_alb_type[il][iv];
}
}
break;
case MCALB_RPV:
if (first) {
if (!albedo->reflectalways) {
fprintf (stderr, "Error, BRDF only implemented together with reflectalways!\n");
return -1;
}
albedo->rpv = calloc ((size_t)1, sizeof (rpv_struct));
}
/* this is no bug, for RPV 1D, il=0 is correct */
albedo->rpv[0].rho0 = rpv_rho0[0];
albedo->rpv[0].k = rpv_k[0];
albedo->rpv[0].theta = rpv_theta[0];
albedo->rpv[0].scale = rpv_scale[0];
albedo->rpv[0].sigma = rpv_sigma[0];
albedo->rpv[0].t1 = rpv_t1[0];
albedo->rpv[0].t2 = rpv_t2[0];
break;
case MCALB_RPV2D_SPECTRAL:
if (first) {
if (!albedo->reflectalways) {
fprintf (stderr, "Error, BRDF only implemented together with reflectalways!\n");
return -1;
}
if (!quiet)
fprintf (stderr, " ... reading 2D RPV data from %s\n", spectral_rpv_filename);
status = read_2D_surface_labels (spectral_rpv_filename,
surface_labels,
surface_nlabels,
&(albedo->Nx),
&(albedo->Ny),
&(albedo->delX),
&(albedo->delY),
&(albedo->surface_index),
&(albedo->surface_count),
&therewereCaMs,
quiet);
if (status != 0) {
fprintf (stderr, "Error %d reading %s\n", status, spectral_rpv_filename);
return status;
}
if (therewereCaMs) {
if (u10 <= 0 && !polarisation) {
fprintf (stderr, "Error, need to specify a wind speed for Cox and Munk!\n");
return -1;
}
if (bpdf_u10 <= 0 && polarisation) {
fprintf (stderr, "Error, need to specify a wind speed for Tsang!\n");
return -1;
}
if (!polarisation)
albedo->u10 = u10;
else
albedo->u10 = bpdf_u10;
albedo->pcl = pcl;
albedo->xsal = xsal;
albedo->uphi = uphi;
albedo->solar_wind = solar_wind;
}
if (!spherical3D) {
if (!equal ((double)(albedo->Nx) * albedo->delX, (double)atmos->Nx * atmos->delX)) {
fprintf (stderr,
"Error, x-size of rpv2D area (%g) does not equal x-size of cloud area (%g)\n",
(double)(albedo->Nx) * albedo->delX,
(double)atmos->Nx * atmos->delX);
return -1;
}
if (!equal ((double)(albedo->Ny) * albedo->delY, (double)atmos->Ny * atmos->delY)) {
fprintf (stderr,
"Error, y-size of rpv2D area (%g) does not equal y-size of cloud area (%g)\n",
(double)(albedo->Ny) * albedo->delY,
(double)atmos->Ny * atmos->delY);
return -1;
}
}
if (!quiet)
for (il = 0; il < surface_nlabels; il++)
fprintf (stderr, " ... found %d pixels with %s\n", albedo->surface_count[il], surface_labels[il]);
albedo->rpv = calloc ((size_t)surface_nlabels, sizeof (rpv_struct));
} // end if (first)
for (il = 1; il < surface_nlabels; il++) { /* first element is reserved for Cox and Munk */
if (albedo->surface_count[il]) {
albedo->rpv[il].rho0 = rpv_rho0[il];
albedo->rpv[il].k = rpv_k[il];
albedo->rpv[il].theta = rpv_theta[il];
albedo->rpv[il].scale = rpv_scale[il];
albedo->rpv[il].sigma = rpv_sigma[il];
albedo->rpv[il].t1 = rpv_t1[il];
albedo->rpv[il].t2 = rpv_t2[il];
}
}
break;
case MCALB_AMBRALS2D_SPECTRAL:
if (first) {
if (!albedo->reflectalways) {
fprintf (stderr, "Error, BRDF only implemented together with reflectalways!\n");
return -1;
}
if (!quiet)
fprintf (stderr, " ... reading 2D AMBRALS data from %s\n", spectral_ambrals_filename);
status = read_2D_surface_labels (spectral_ambrals_filename,
surface_labels,
surface_nlabels,
&(albedo->Nx),
&(albedo->Ny),
&(albedo->delX),
&(albedo->delY),
&(albedo->surface_index),
&(albedo->surface_count),
&therewereCaMs,
quiet);
if (status != 0) {
fprintf (stderr, "Error %d reading %s\n", status, spectral_ambrals_filename);
return status;
}
if (therewereCaMs) {
if (u10 <= 0 && !polarisation) {
fprintf (stderr, "Error, need to specify a wind speed for Cox and Munk!\n");
return -1;
}
if (bpdf_u10 <= 0 && polarisation) {
fprintf (stderr, "Error, need to specify a wind speed for Tsang!\n");
return -1;
}
if (!polarisation)
albedo->u10 = u10;
else
albedo->u10 = bpdf_u10;
albedo->pcl = pcl;
albedo->xsal = xsal;
albedo->uphi = uphi;
albedo->solar_wind = solar_wind;
}
if (!spherical3D) {
if (!equal ((double)(albedo->Nx) * albedo->delX, (double)atmos->Nx * atmos->delX)) {
fprintf (stderr,
"Error, x-size of rpv2D area (%g) does not equal x-size of cloud area (%g)\n",
(double)(albedo->Nx) * albedo->delX,
(double)atmos->Nx * atmos->delX);
return -1;
}
if (!equal ((double)(albedo->Ny) * albedo->delY, (double)atmos->Ny * atmos->delY)) {
fprintf (stderr,
"Error, y-size of rpv2D area (%g) does not equal y-size of cloud area (%g)\n",
(double)(albedo->Ny) * albedo->delY,
(double)atmos->Ny * atmos->delY);
return -1;
}
}
if (!quiet)
for (il = 0; il < surface_nlabels; il++)
fprintf (stderr, " ... found %d pixels with %s\n", albedo->surface_count[il], surface_labels[il]);
albedo->ambrals = calloc ((size_t)surface_nlabels, sizeof (rossli_brdf_spec));
} // end if (first)
for (il = 1; il < surface_nlabels; il++) { /* first element is reserved for Cox and Munk */
if (albedo->surface_count[il]) {
albedo->ambrals[il].iso = rossli_iso[il];
albedo->ambrals[il].vol = rossli_vol[il];
albedo->ambrals[il].geo = rossli_geo[il];
}
}
break;
case MCALB_COXANDMUNK:
if (first) {
if (!albedo->reflectalways) {
fprintf (stderr, "Error, BRDF only implemented together with reflectalways!\n");
return -1;
}
albedo->u10 = u10;
albedo->pcl = pcl;
albedo->xsal = xsal;
albedo->uphi = uphi;
albedo->solar_wind = solar_wind;
} // end if (first)
break;
case MCALB_TSANG:
if (first) {
if (!(albedo->reflectalways)) {
fprintf (stderr, "Error, BPDF only implemented together with reflectalways and polarisation!\n");
return -1;
}
albedo->u10 = bpdf_u10;
} // end if (first)
break;
case MCALB_HAPKE:
if (first) {
if (!albedo->reflectalways) {
fprintf (stderr, "Error, BRDF only implemented together with reflectalways!\n");
return -1;
}
albedo->hapke = calloc ((size_t)1, sizeof (hapke_brdf_spec));
} // end if (first)
albedo->hapke[0].h = hapke_h[0];
albedo->hapke[0].b0 = hapke_b0[0];
albedo->hapke[0].w = hapke_w[0];
break;
case MCALB_ROSSLI:
if (first) {
if (!albedo->reflectalways) {
fprintf (stderr, "Error, BRDF only implemented together with reflectalways!\n");
return -1;
}
albedo->rossli = calloc ((size_t)1, sizeof (rossli_brdf_spec));
} // end if (first)
albedo->rossli[0].iso = rossli_iso[0];
albedo->rossli[0].vol = rossli_vol[0];
albedo->rossli[0].geo = rossli_geo[0];
albedo->rossli[0].hotspot = rossli_hotspot;
break;
case MCALB_ROSSLI2D:
if (first) {
if (!albedo->reflectalways) {
fprintf (stderr, "Error, BRDF only implemented together with reflectalways!\n");
return -1;
}
if (!quiet)
fprintf (stderr, " ... reading 2D Ross-Li data from %s\n", rossli_filename);
status = read_2D_rossli (rossli_filename,
&(albedo->Nx),
&(albedo->Ny),
&(albedo->delX),
&(albedo->delY),
&(albedo->rossli2D),
&therewereCaMs,
rossli_hotspot,
isAmbralsFile,
ixmin,
ixmax,
iymin,
iymax,
quiet);
if (status != 0) {
fprintf (stderr, "Error %d reading %s\n", status, rossli_filename);
return status;
}
if (therewereCaMs) {
if (u10 <= 0) {
fprintf (stderr, "Error, need to specify a wind speed for Cox and Munk!\n");
return -1;
}
albedo->u10 = u10;
albedo->pcl = pcl;
albedo->xsal = xsal;
albedo->uphi = uphi;
albedo->solar_wind = solar_wind;
}
if (!spherical3D) {
if (!equal ((double)(albedo->Nx) * albedo->delX, (double)atmos->Nx * atmos->delX)) {
fprintf (stderr,
"Error, x-size of RossLi2D area (%g) does not equal x-size of cloud area (%g)\n",
(double)(albedo->Nx) * albedo->delX,
(double)atmos->Nx * atmos->delX);
return -1;
}
if (!equal ((double)(albedo->Ny) * albedo->delY, (double)atmos->Ny * atmos->delY)) {
fprintf (stderr,
"Error, y-size of RossLi2D area (%g) does not equal y-size of cloud area (%g)\n",
(double)(albedo->Ny) * albedo->delY,
(double)atmos->Ny * atmos->delY);
return -1;
}
}
} // end if (first)
break;
default:
fprintf (stderr, "??? Error, unknown albedo->method %d\n", albedo->method);
return -1;
}
if (first)
first = 0;
if (spherical3D)
switch (albedo->method) {
case MCALB_LAM2D:
case MCALB_ROSSLI2D:
case MCALB_LAM2D_SPECTRAL:
case MCALB_RPV2D_SPECTRAL:
case MCALB_AMBRALS2D_SPECTRAL:
#if HAVE_MYSTIC3D
status = setup_spherical3D ("albedo",
albedo->Nx,
albedo->Ny,
spherical3D_scene,
spherical3D_scene_lon_min,
spherical3D_scene_lon_max,
spherical3D_scene_lat_min,
spherical3D_scene_lat_max,
&(albedo->delX),
&(albedo->delY),
&(albedo->xmax),
&(albedo->ymax),
&(albedo->X),
&(albedo->Y),
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
quiet);
if (status != 0)
return err_out ("Error %d returned by setup_spherical3D()\n", status);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
case MCALB_LAM:
case MCALB_RPV:
case MCALB_COXANDMUNK:
case MCALB_HAPKE:
case MCALB_ROSSLI:
case MCALB_TSANG:
break;
default:
fprintf (stderr, "Fatal error, unknown albedo type %d\n", albedo->method);
return -1;
}
return 0;
}
/***********************************************************************************/
/* Function: setup_umu2D @62_30i@ */
/* Description: */
/* Initialize the 2D umu_struct with the umu data read from */
/* filename. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int setup_umu2D (char* umu_filename, sample_struct* sample, atmosphere_struct* atmos, int quiet) {
int status = 0;
int Nx = 0, Ny = 0;
double delX = 0.0, delY = 0.0;
if (!quiet)
fprintf (stderr, " ... reading 2D umu data\n");
/* read 2D umu data, identical to albedo! */
status = read_2D_umu (umu_filename,
&Nx,
&Ny,
&delX,
&delY,
&(sample->umu2D),
&(sample->phi2D),
sample->ixmin,
sample->ixmax,
sample->iymin,
sample->iymax,
quiet);
if (status != 0) {
fprintf (stderr, "Error %d reading %s\n", status, umu_filename);
return status;
}
/* tests */
if (!equal ((double)delX, (double)atmos->delX) || !equal ((double)delY, (double)atmos->delY) || !equal (Nx, atmos->Nx) ||
!equal (Ny, atmos->Ny)) {
fprintf (stderr,
"Error, size of umu file size of cloud (%d %d %g %g ne %d %d %g %g)\n",
Nx,
Ny,
delX,
delY,
atmos->Nx,
atmos->Ny,
atmos->delX,
atmos->delY);
return -1;
}
return 0;
}
/* switch from forward tracing to backward tracing; */
/* basically, exchange observation and sun direction */
/* as well as start and sampling altitudes */
static int forward2backward (atmosphere_struct* atmos,
float** zout,
int* nzout,
float* sza,
float* phi0,
sample_struct* sample,
result_struct* result,
int quiet) {
int kc = 0;
int id = 0;
if (!quiet) {
if ((*zout)[0] == -999.0)
fprintf (stderr, "BACKWARD! before: starting photons at %gm, sampling at the surface\n", sample->zstart);
else
fprintf (stderr, "BACKWARD! before: starting photons at %gm, sampling at %gm\n", sample->zstart, (*zout)[0] * 1000.0);
}
if (*nzout < 1) {
fprintf (stderr, "Error, no zout defined!\n");
return -1;
}
/* save altitude string for backward sampling file; */
/* to make sure that the output goes to the same */
/* location where the forward results would have */
/* gone, determine filename from "forward" zout[0] */
/* before switching zout and zstart */
strcpy (sample->backward_altstr, "");
/* need special treatment for surface */
if ((*zout)[0] != -999.0) {
for (kc = 0; kc <= atmos->Nz; kc++) {
if (fabs (atmos->Z[kc] - (*zout)[0] * 1000.0) < 1E-2) {
sprintf (sample->backward_altstr, "%d", kc);
break;
}
}
if (kc == atmos->Nz + 1) {
fprintf (stderr, "\nFATAL error: altitude grid does not contain level %11.7f\n", (*zout)[0]);
fprintf (stderr, "which has been specified as output altitude in the sample file.\n");
return -1;
}
}
switch (sample->backward) {
case MCBACKWARD_EDIR:
case MCBACKWARD_EGLOB:
case MCBACKWARD_EDN:
case MCBACKWARD_EDNPV:
case MCBACKWARD_EUP:
case MCBACKWARD_FDIR:
case MCBACKWARD_FDN:
case MCBACKWARD_FUP:
case MCBACKWARD_ABS:
case MCBACKWARD_EMIS:
case MCBACKWARD_HEAT:
case MCBACKWARD_ACT:
case MCBACKWARD_EXP:
case MCBACKWARD_EXN:
case MCBACKWARD_EYP:
case MCBACKWARD_EYN:
/* need to allocate memory for one sampling direction */
if (!quiet)
fprintf (stderr, " ... backward sampling irradiance / actinic flux!\n");
/* allocate memory for sample radiances */
sample->Nd = 1;
sample->rad = calloc (1 + sample->DoLE, sizeof (radang));
/* copy uvspec radiance to sample array */
sample->rad[0].theta = sample->backward_vza;
sample->rad[0].phi = sample->backward_phi;
/* sample->rad[0].alpha = 5.0; default, can be modified using input option mc_rad_alpha */
if (sample->DoLE) {
sample->rad[1].theta = 180.0 - sample->backward_vza;
sample->rad[1].phi = sample->backward_phi;
/* sample->rad[1].alpha = 5.0; default, can be modified using input option mc_rad_alpha */
}
break;
case MCBACKWARD_RADIANCE:
if (!quiet) {
fprintf (stderr, "BACKWARD! sza = %f, phi0 = %f\n", *sza, *phi0);
fprintf (stderr, "BACKWARD! vza = %f, phi = %f\n", sample->rad[0].theta, sample->rad[0].phi);
}
if (sample->Nd < 1) {
fprintf (stderr, "Error, need at least one radiance direction for MCBACKWARD_RADIANCE.\n");
fprintf (stderr, "This indicates a programming error!\n");
return -1;
}
sample->Nd = 1; /* we use only the first direction */
/* exchange zenith and azimuth angles */
*sza = sample->backward_sza;
*phi0 = sample->backward_phi0;
sample->rad[0].theta = sample->backward_vza;
sample->rad[0].phi = sample->backward_phi;
if (sample->DoLE) {
sample->rad[1].theta = 180.0 - sample->backward_vza;
sample->rad[1].phi = sample->backward_phi;
}
if (!quiet) {
fprintf (stderr, "BACKWARD! after: sza = %f, phi0 = %f\n", *sza, *phi0);
fprintf (stderr, "BACKWARD! vza = %f, phi = %f\n", sample->rad[0].theta, sample->rad[0].phi);
}
break;
case MCBACKWARD_NONE:
break;
default:
fprintf (stderr, "Error, unknown backward quantity %d\n", sample->backward);
return -1;
}
for (id = 0; id < 1 + sample->DoLE; id++) {
/* need to initialize new radiance direction */
sample->rad[id].cosalpha = cosd (sample->rad[id].alpha);
sample->rad[id].omega = 2.0 * PI * (1.0 - sample->rad[id].cosalpha);
init_direction (-sind (sample->rad[id].theta),
-cosd (sample->rad[id].theta),
sind (sample->rad[id].phi),
cosd (sample->rad[id].phi),
&(sample->rad[id].dir));
}
/* Backup rad.dir */
cp_direction (&(sample->rad_dir0), &(sample->rad[0].dir));
/* exchange zstart / zout */
sample->zstart = sample->backward_zstart;
if (!sample->pan_transmittance) {
/* if no zout's allocated, allocate one */
if (*nzout <= 0)
*zout = calloc (1, sizeof (float));
(*zout)[0] = sample->backward_zout;
*nzout = 1; /* reset to one because we obviously only look at one direction */
/* no surface sampling for backward */
sample->surface = 0;
/* reset sample flag and determine new sample flag */
for (kc = 0; kc <= atmos->Nz; kc++)
sample->sample[kc] = 0;
if (*nzout >= 1) {
if ((*zout)[0] != -999.0) {
for (kc = 0; kc <= atmos->Nz; kc++) {
if (fabs (atmos->Z[kc] - (*zout)[0] * 1000.0) < 1E-2) {
sample->sample[kc] = 1;
break;
}
}
if (kc == atmos->Nz + 1) {
fprintf (stderr, "\nFATAL error: altitude grid does not contain level %g\n", (*zout)[0]);
fprintf (stderr, "which has been specified as output altitude in the sample file.\n");
return -1;
}
}
}
if (!quiet) {
if (sample->zstart == -999.0)
fprintf (stderr, "BACKWARD! starting photons at the surface, sampling at %gm\n", (*zout)[0] * 1000.0);
else
fprintf (stderr, "BACKWARD! starting photons at %gm, sampling at %gm\n", sample->zstart, (*zout)[0] * 1000.0);
}
}
/* if no user-defined sample range, */
/* sample all pixels */
if (sample->backward_islower == -999 && sample->backward_jslower == -999 && sample->backward_isupper == -999 &&
sample->backward_jsupper == -999) {
sample->backward_islower = 0;
sample->backward_jslower = 0;
sample->backward_isupper = sample->Nx - 1;
sample->backward_jsupper = sample->Ny - 1;
sample->backward_isstep = 1;
sample->backward_jsstep = 1;
}
return 0;
}
/***********************************************************************************/
/* Function: setup_sample2D @62_30i@ */
/* Description: */
/* Initialize sample_struct with data read from samplefilename and passed as */
/* function arguments. */
/* */
/* Parameters: */
/* float *zout: array of altitudes to be sampled; overwrites data from */
/* samplefilename if nzout>0 */
/* int nzout: number of altitudes to be sampled; if nzout<=0, data from */
/* samplefilename are used. */
/* */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int setup_sample2D (atmosphere_struct* atmos,
float* zout,
int nzout,
float* sza,
float* phi0,
float* wavelength,
sample_struct* sample,
int quiet) {
int status = 0;
int id = 0;
/********************************************************/
/* set start and sampling altitude for forward/backward */
/********************************************************/
/* default: forward photons start at TOA */
sample->zstart = atmos->Z[atmos->Nz];
/* backward photons start at the first user-defined zout */
/* or, if no zout is defined, use -999 */
if (nzout > 0 && zout[0] >= 0)
sample->backward_zstart = zout[0] * 1000; /* convert from km to m */
else
sample->backward_zstart = -999;
sample->backward_zout = sample->zstart / 1000.0;
/* quick dirty fix for blitz... BCA: clean up generate_photon,
setup_sample_grid, forward2backward, and setup_sample2d*/
if (sample->blitz_position != NULL) {
*sza = sample->rad[0].theta;
*phi0 = 180 + sample->rad[0].phi;
}
/**********************************************************************/
/* save original directions - they might be reversed in backward mode */
/**********************************************************************/
sample->forward_sza = *sza;
sample->forward_phi0 = *phi0;
sample->backward_vza = sample->forward_sza;
sample->backward_phi = sample->forward_phi0;
if (sample->Nd > 0) {
sample->forward_vza = sample->rad[0].theta;
sample->forward_phi = sample->rad[0].phi;
sample->backward_sza = sample->forward_vza;
sample->backward_phi0 = sample->forward_phi;
}
/* CE probably not needed, CHECK!!! */
/* #ifdef NEW_REFLECT */
/* if (sample->backward) */
/* sample->phi_target=sample->forward_phi0; */
/* else */
/* sample->phi_target=sample->forward_phi; */
/* #endif */
/* now switch forward to backward */
if (sample->backward) {
status = forward2backward (atmos, &zout, &nzout, sza, phi0, sample, NULL, quiet);
if (status != 0)
return err_out ("Error %d returned by forward2backward()\n", status);
}
/* initialize radiance directions, after the first one has */
/* possibly been modified in the above backward section; */
for (id = 0; id < sample->Nd; id++) {
sample->rad[id].cosalpha = cosd (sample->rad[id].alpha);
sample->rad[id].omega = 2.0 * PI * (1.0 - sample->rad[id].cosalpha);
init_direction (-sind (sample->rad[id].theta),
-cosd (sample->rad[id].theta),
sind (sample->rad[id].phi),
cosd (sample->rad[id].phi),
&(sample->rad[id].dir));
if (sample->rad[id].dir.dx[2] == 0.0 && !sample->spherical) {
fprintf (stderr, "Error! Horizontal escape radiances will never end for non-spherical geometry!!! Exiting...\n");
return -1;
}
}
#if HAVE_LIDAR
/*WARNING: Accuracy of wavelength as double is only 6 digits*/
sample->wavelength = float_zeros (*wavelength, 6);
sample->wavenumber = (2.e9 * PI) / sample->wavelength;
#endif
return 0;
}
/***********************************************************************************/
/* Function: setup_mc_result @62_30i@ */
/* Description: */
/* Allocate memory for the result structures. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int setup_mc_result (atmosphere_struct* atmos,
sample_struct* sample,
t_triangle_radiation_field* triangle_results,
result_struct* result,
int absorption,
int thermal_heating_method,
int quiet) {
int is = 0, js = 0, kc = 0, ip = 0, ic = 0, il = 0;
/* surface quantities */
result->surf = calloc_radiation_field (sample->Nx,
sample->Ny,
sample->Nd,
sample->Nr,
sample->Nt,
sample->nstokes,
sample->std,
sample->cldprp);
result->triangle_results = triangle_results;
if (result->triangle_results) {
const int ierr = reset_triangular_surface_result_struct (result->triangle_results);
CHKERR (ierr);
}
/* altitude profiles */
result->alt = calloc ((size_t) (atmos->Nz + 1), sizeof (radiation_field*));
if (sample->spectral_is || sample->concentration_is) {
result->surf_t = calloc_radiation_field_t (atmos->Nc, sample->Nx, sample->Ny, sample->nstokes, atmos->nlambda_abs);
result->rad_t = calloc ((size_t) (atmos->Nz + 1), sizeof (radiation_field_t*));
}
#if HAVE_LIDAR
/* lidar quantities */
if (sample->LidarLocEst)
result->lidar = calloc_lidar_result_field (sample->Nli,
sample->LLE_Nt,
atmos->n_caoth,
1 + (sample->LLE_channels > 0),
sample->LLE_scatterout + 1,
sample->nstokes,
sample->LLE_No,
sample->LLE_Na,
sample->std,
sample->LLE_jacobian,
sample->Nz_jac);
#endif
if (sample->jacobian || sample->jacobian3D)
result->jacobian = calloc_jacobian_result_field (sample->std, atmos->Nx, atmos->Ny, atmos->Nz, atmos->n_caoth, sample->nstokes);
for (kc = 0; kc <= atmos->Nz; kc++) {
if (sample->sample[kc]) {
result->alt[kc] = calloc_radiation_field (sample->Nx,
sample->Ny,
sample->Nd,
sample->Nr,
sample->Nt,
sample->nstokes,
sample->std,
sample->cldprp);
if (sample->spectral_is || sample->concentration_is)
result->rad_t[kc] = calloc_radiation_field_t (atmos->Nc, sample->Nx, sample->Ny, sample->nstokes, atmos->nlambda_abs);
}
}
/* backward radiance / irradiance */
if (sample->backward) {
if (!quiet)
fprintf (stderr, " ... allocating %d x %d pixels for backward fields\n", sample->Nx, sample->Ny);
result->back = calloc (sample->Nx, sizeof (double**));
result->back2 = calloc (sample->Nx, sizeof (double**));
result->backemis = calloc (sample->Nx, sizeof (double*));
if (sample->backward == MCBACKWARD_HEAT) /* **CK 2013.09.23*/
if (thermal_heating_method == MCBACKWARD_HEAT_DENET ||
thermal_heating_method == MCBACKWARD_HEAT_HYBRID) { /* **CK 2013.08.27*/
result->back_dEnet = calloc (sample->Nx, sizeof (double**));
result->back_dEnet2 = calloc (sample->Nx, sizeof (double**));
}
for (is = 0; is < sample->Nx; is++) {
result->back[is] = calloc (sample->Ny, sizeof (double*));
result->back2[is] = calloc (sample->Ny, sizeof (double*));
result->backemis[is] = calloc (sample->Ny, sizeof (double));
if (sample->backward == MCBACKWARD_HEAT) /* **CK 2013.09.23*/
if (thermal_heating_method == MCBACKWARD_HEAT_DENET ||
thermal_heating_method == MCBACKWARD_HEAT_HYBRID) { /* **CK 2013.08.27*/
result->back_dEnet[is] = calloc (sample->Ny, sizeof (double*));
result->back_dEnet2[is] = calloc (sample->Ny, sizeof (double*));
}
for (js = 0; js < sample->Ny; js++) {
result->back[is][js] = calloc (sample->nstokes, sizeof (double));
result->back2[is][js] = calloc (sample->nstokes, sizeof (double));
if (sample->backward == MCBACKWARD_HEAT) /* **CK 2013.09.23*/
if (thermal_heating_method == MCBACKWARD_HEAT_DENET ||
thermal_heating_method == MCBACKWARD_HEAT_HYBRID) { /* **CK 2013.08.27*/
result->back_dEnet[is][js] = calloc (12, sizeof (double));
result->back_dEnet2[is][js] = calloc (12, sizeof (double));
}
}
}
if (sample->spectral_is || sample->concentration_is) {
result->back_t = calloc (atmos->Nc, sizeof (double****));
for (ic = 0; ic < atmos->Nc; ic++) {
result->back_t[ic] = calloc (sample->Nx, sizeof (double***));
for (is = 0; is < sample->Nx; is++) {
result->back_t[ic][is] = calloc (sample->Ny, sizeof (double**));
for (js = 0; js < sample->Ny; js++) {
result->back_t[ic][is][js] = calloc (sample->nstokes, sizeof (double*));
for (ip = 0; ip < sample->nstokes; ip++)
result->back_t[ic][is][js][ip] = calloc (atmos->nlambda_abs, sizeof (double));
}
}
}
}
}
if (absorption) {
result->absorption3D = calloc_ddprofile3D (atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed[MCCAOTH_TOT]);
if (result->absorption3D == NULL) {
fprintf (stderr, "Error allocating memory for absorption3D\n");
return -1;
}
if (sample->std) {
result->absorption3D2 = calloc_ddprofile3D (atmos->Nz, atmos->Nx, atmos->Ny, atmos->threed[MCCAOTH_TOT]);
if (result->absorption3D2 == NULL) {
fprintf (stderr, "Error allocating memory for absorption3D\n");
return -1;
}
}
}
/* CE: variables need to be extended with sample->Nx and sample->Ny so that
box_amfs can be calculated for each backward pixel !!!*/
if (sample->boxairmass)
ASCII_calloc_double_3D (&result->pathlength_per_layer_tot, (size_t)sample->Nx, (size_t)sample->Ny, (size_t)atmos->Nz);
else if (sample->boxairmass3D)
ASCII_calloc_double_5D (&result->pathlength_per_box_tot,
(size_t)sample->Nx,
(size_t)sample->Ny,
(size_t)atmos->Nx,
(size_t)atmos->Ny,
(size_t)atmos->Nz);
if (sample->ncirc) {
/* QUICK FIX*/
result->circcontr = calloc (10, sizeof (double*));
for (il = 0; il < 10; il++)
result->circcontr[il] = calloc (sample->ncirc, sizeof (double));
}
result->mish = calloc (1, sizeof (mishchenko_cb_struct));
#if HAVE_LIDAR
result->lidcb = calloc (1, sizeof (lidar_cb_struct));
#endif
return 0;
}
/***********************************************************************************/
/* Function: incone @62_30i@ */
/* Description: */
/* Check if a direction dx lies within the cone define in rad. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int incone (double* dx, radang rad) {
if (dx[0] * rad.dir.dx[0] + dx[1] * rad.dir.dx[1] + dx[2] * rad.dir.dx[2] >= rad.cosalpha)
return 1;
else
return 0;
}
/***********************************************************************************/
/* Function: count_photon @62_30i@ */
/* Description: */
/* Register a photon; that is, add its contribution to the irradiance, */
/* actinic flux, and radiance arrays in result_struct *res. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void
count_photon (radiation_field* res, photon_struct* p, sample_struct* sample, double* totweight, int surfaceparallel, int incoming) {
int id = 0;
int ir = 0, is = 0, it = 0, js = 0, ip = 0;
/* determine sample coordinates */
sample_coord (p, sample, &is, &js);
if (p->direct) { /* direct beam source */
/* direct irradiance and actinic flux */
res->ndir[is][js]++;
res->edir[is][js] += totweight[0];
res->fdir[is][js] += totweight[0] / p->dir.cotheta;
if (sample->std) {
p->wtree = addtree_stddev (p->wtree, &(res->edir2[is][js]), totweight[0]);
p->wtree = addtree_stddev (p->wtree, &(res->fdir2[is][js]), totweight[0] / p->dir.cotheta);
}
/* direct radiance */
if (!sample->panorama_forward) {
for (id = 0; id < sample->Nd; id++) {
/* Stokes components loop not necessary, for randomly oriented particles, direct */
/* radiation is not polarized. THIS IS NOT TRUE FOR LIDAR!!! BUG!!! CE, please fix... CHECK!!! */
if (incone (p->dir.dx, sample->rad[id])) {
res->raddir[id][is][js][0] += totweight[0] / p->dir.cotheta;
if (sample->std)
p->wtree = addtree_stddev (p->wtree, &(res->raddir2[id][is][js][0]), totweight[0] / p->dir.cotheta);
}
}
}
} else { /* diffuse */
if ((surfaceparallel && incoming) || (!surfaceparallel && p->dir.dx[2] < 0)) { /* down-welling */
res->ndn[is][js]++;
res->edn[is][js] += totweight[0];
if (sample->std)
p->wtree = addtree_stddev (p->wtree, &(res->edn2[is][js]), totweight[0]);
/* ??? Attention, this is only to reduce noise ??? CHECK!!! */
/* ??? but it actually introduces systematic ??? */
/* ??? error! Tests show that we loose up to ??? */
/* ??? 1 - 2% of the diffuse components when ??? */
/* ??? ACTINIC_CUTOFF is set to 0.01 ??? */
/* ??? ??? */
/* ??? We correct that partly by multiplying ??? */
/* ??? the result by 1/(1-ACTINIC_CUTOFF), ??? */
/* ??? assuming that the actinic flux in the ??? */
/* ??? cutoff range equals the average actinic ??? */
/* ??? flux in the hemisphere ??? */
if (fabs (p->dir.cotheta) >= ACTINIC_CUTOFF) {
res->fdn[is][js] += totweight[0] / p->dir.cotheta / (1.0 - ACTINIC_CUTOFF);
if (sample->std)
p->wtree = addtree_stddev (p->wtree, &(res->fdn2[is][js]), totweight[0] / p->dir.cotheta / (1.0 - ACTINIC_CUTOFF));
}
}
if ((surfaceparallel && !incoming) || (!surfaceparallel && p->dir.dx[2] > 0)) { /* up-welling */
res->nup[is][js]++;
res->eup[is][js] += totweight[0];
if (sample->std)
p->wtree = addtree_stddev (p->wtree, &(res->eup2[is][js]), totweight[0]);
/* ??? Attention, this is only to reduce noise ??? CHECK!!! */
/* ??? but it actually introduces systematic ??? */
/* ??? error! Tests show that we loose up to ??? */
/* ??? 1 - 2% of the diffuse components when ??? */
/* ??? ACTINIC_CUTOFF is set to 0.01 ??? */
/* ??? ??? */
/* ??? We correct that partly by multiplying ??? */
/* ??? the result by 1/(1-ACTINIC_CUTOFF), ??? */
/* ??? assuming that the actinic flux in the ??? */
/* ??? cutoff range equals the average actinic ??? */
/* ??? flux in the hemisphere ??? */
if (fabs (p->dir.cotheta) >= ACTINIC_CUTOFF) {
res->fup[is][js] += totweight[0] / p->dir.cotheta / (1.0 - ACTINIC_CUTOFF);
if (sample->std)
p->wtree = addtree_stddev (p->wtree, &(res->fup2[is][js]), totweight[0] / p->dir.cotheta / (1.0 - ACTINIC_CUTOFF));
}
}
/* diffuse radiance */
if (sample->panorama_forward) {
double theta = acosd (p->dir.dx[2]);
double phi = 0;
if (p->dir.dx[0] == 0 && p->dir.dx[1] == 0)
phi = 0;
else
phi = atan2 (p->dir.dx[0], p->dir.dx[1]) / M_PI * 180.0;
while (phi < 0)
phi = 360.0 + phi;
is = (int)((phi) / 360.0 * sample->Nx);
js = (int)((theta) / 180.0 * sample->Ny);
/* collect edges of forward panorama in last bin (LF 2016/08/19) */
if (is == sample->Nx)
is -= is;
if (js == sample->Ny)
js -= js;
for (ip = 0; ip < sample->nstokes; ip++) {
res->raddif[0][is][js][ip] += totweight[ip] / p->dir.cotheta;
if (sample->std)
p->wtree = addtree_stddev (p->wtree, &(res->raddif2[0][is][js][ip]), totweight[ip] / p->dir.cotheta);
}
} else {
for (id = 0; id < sample->Nd; id++) {
if (incone (p->dir.dx, sample->rad[id])) {
for (ip = 0; ip < sample->nstokes; ip++) {
res->raddif[id][is][js][ip] += totweight[ip] / p->dir.cotheta;
if (sample->std)
p->wtree = addtree_stddev (p->wtree, &(res->raddif2[id][is][js][ip]), totweight[ip] / p->dir.cotheta);
}
}
}
}
/* radial pathlength radiance */
if (sample->Nr > 0 && sample->Nt > 0)
if (sample_radius (p, sample, &ir))
if (sample_time (p, sample, &it))
for (id = 0; id < sample->Nd; id++)
if (incone (p->dir.dx, sample->rad[id])) {
for (ip = 0; ip < sample->nstokes; ip++) {
res->radpat[id][ir][it][ip] += totweight[ip] / p->dir.cotheta;
if (sample->std)
p->wtree = addtree_stddev (p->wtree, &(res->radpat2[id][ir][it][ip]), totweight[ip] / p->dir.cotheta);
}
}
}
}
static int count_photon_on_triangular_surface (const double weight,
const photon_struct* p,
const int incoming,
t_triangle_radiation_field* triangle_result) {
if (p->intersect_triangle_id != -1) { // collect contributions onto triangular surfaces
if (!(p->intersect_triangle_id < triangle_result->N_triangles)) {
CHKERROUT (p->intersect_triangle_id, "intersection_id index out of bounds");
}
const size_t triangle_id = p->intersect_triangle_id;
if (p->direct) {
triangle_result->ndir[triangle_id]++;
triangle_result->edir[triangle_id] += weight;
} else {
if (incoming) { // before reflection
triangle_result->ndn[triangle_id]++;
triangle_result->edn[triangle_id] += weight;
} else {
triangle_result->nup[triangle_id]++;
triangle_result->eup[triangle_id] += weight;
}
}
}
return 0;
}
/*TZ bt ****************************************************************************/
/* Function: count_thermal_backward_photon @62_30i@ */
/* Description: */
/* Register a thermal backward photon; that is, add its contribution to the */
/* irradiance, actinic flux, and radiance arrays in result_struct *res. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int count_thermal_backward_photon (result_struct* result,
photon_struct* p,
atmosphere_struct* atmos,
surftemp_struct* surftemp,
sample_struct* sample,
t_triangular_surface* triangular_surface,
double btemp_plkavg,
int quiet,
int toa_surf_flag) {
int it = 0, jt = 0, ip = 0;
#if HAVE_ALIS
int iv = 0, ic = 0;
double* totweight_spectral = NULL;
double* totweight_concentration = NULL;
double factor = 0.0;
double planck_ref = 0.0;
double planck_iv = 0.0;
double planck_ratio = 1.0;
#endif
#if HAVE_ALIS
if (sample->spectral_is || sample->concentration_is) {
totweight_spectral = calloc (atmos->nlambda_abs, sizeof (double));
totweight_concentration = calloc (atmos->Nc, sizeof (double));
totweight_spectral[0] = 1.0;
totweight_concentration[0] = 1.0;
if (sample->spectral_is)
spectral_is_weight (&totweight_spectral, p, p, atmos); /* RpA??? CHECK!!! */
if (sample->concentration_is)
concentration_is_weight (&totweight_concentration, p, p, atmos);
}
#endif
for (ip = 0; ip < sample->nstokes; ip++) {
double totweight = 0;
double totweight_emis = 0;
/* **CK 2013.08.27 */
if (sample->backward != MCBACKWARD_HEAT)
totweight = p->phamat[ip][0] * p->weight * exp (-p->tauabs.tot);
else {
switch (sample->heat_flag[sample->backward_is][sample->backward_js]) {
case MCBACKWARD_HEAT_EMABS:
case MCBACKWARD_HEAT_EMABSOPT:
totweight = p->phamat[ip][0] * p->weight * exp (-p->tauabs.tot);
totweight_emis =
p->phamat[ip][0] *
p->weight_emis; // **CK 2013.08.27 p->weight_emis only set for new photon distribution for thermal backward heating rates EMABS_Method
break;
case MCBACKWARD_HEAT_DENET:
totweight = p->phamat[ip][0] * p->weight * exp (-p->tauabs.tot);
break;
}
}
switch (toa_surf_flag) {
case MCSTATUS_ABSORB:
/*linear interpolation of Bplanck for comparison with DISORT*/
totweight *=
(atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] +
(((p->x[2] - atmos->Z[p->kc]) / (atmos->Z[p->kc + 1] - atmos->Z[p->kc])) *
(atmos->Bplanck->prof[MCCAOTH_TOT][p->kc + 1][p->ic][p->jc] - atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc])));
break;
case MCSTATUS_BOUNDARY_UPPER:
/* TOA exit => zero contribution and not Bplanck(top level) contribution */
totweight = 0.0;
break;
case MCSTATUS_BOUNDARY_LOWER:
/* ??? BM:don't think so. We don't need to weight with the emissivity CHECK!!! */
/* ??? because this is already done by reflecting the photon or not */
/* ??? reflecting it. When multiplied by (1.0-albedo) the upward */
/* ??? irradiance at the surface was divided by 4 if the albedo was */
/* ??? set to 0.5! */
/* surface absorption => Bplanck(surface temp)*/
/* totweight *= btemp_plkavg*(1.0-albedo); */
if (surftemp->surf2D) {
/* 2D surface temperature */
surftemp_coord (p, surftemp, &it, &jt);
totweight *= surftemp->plkavg2D[it][jt];
} else
totweight *= btemp_plkavg;
break;
case MCSTATUS_TRIANGLE_SURFACE:
if (triangular_surface->Bplanck_of_triangle) {
totweight *= triangular_surface->Bplanck_of_triangle[p->intersect_triangle_id];
} else {
totweight *=
atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] +
(((p->x[2] - atmos->Z[p->kc]) / (atmos->Z[p->kc + 1] - atmos->Z[p->kc])) *
(atmos->Bplanck->prof[MCCAOTH_TOT][p->kc + 1][p->ic][p->jc] - atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc]));
}
break;
case MCSTATUS_SURFACE:
if (surftemp->surf2D) {
/* 2D surface temperature */
surftemp_coord (p, surftemp, &it, &jt);
totweight *= surftemp->plkavg2D[it][jt];
} else {
/* if surface temperature not explicitely defined by user */
/* interpolate atmospheric planck function to actual location */
/* assuming that the surface temperature equals the air */
/* temperature at this height. */
if (surftemp->user_defined_btemp)
totweight *= btemp_plkavg;
else
totweight *=
atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] +
(((p->x[2] - atmos->Z[p->kc]) / (atmos->Z[p->kc + 1] - atmos->Z[p->kc])) *
(atmos->Bplanck->prof[MCCAOTH_TOT][p->kc + 1][p->ic][p->jc] - atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc]));
}
break;
default:
fprintf (stderr, "Error, unknown toa_surf_flag %d\n", toa_surf_flag);
CHKERR (1);
}
double add = NOT_A_NUMBER;
double add_emis = NOT_A_NUMBER;
switch (sample->backward) {
case MCBACKWARD_EGLOB:
case MCBACKWARD_EDN:
case MCBACKWARD_EDNPV:
case MCBACKWARD_EUP:
case MCBACKWARD_EXP:
case MCBACKWARD_EXN:
case MCBACKWARD_EYP:
case MCBACKWARD_EYN:
case MCBACKWARD_FDN:
case MCBACKWARD_FUP:
case MCBACKWARD_ABS:
case MCBACKWARD_ACT:
case MCBACKWARD_HEAT: /* emission is counted separately in sample->backemis, therefore no difference to absorption */
if (sample->backward != MCBACKWARD_HEAT)
add = totweight * 4.0 * PI;
else {
switch (sample->heat_flag[sample->backward_is][sample->backward_js]) { /* **CK 2013.08.27 */
case MCBACKWARD_HEAT_EMABS:
case MCBACKWARD_HEAT_EMABSOPT:
add = totweight * 4.0 * PI;
add_emis = totweight_emis * 4.0 * PI;
break;
case MCBACKWARD_HEAT_DENET:
add = totweight * 4.0 * PI;
break;
}
}
break;
case MCBACKWARD_RADIANCE:
add = totweight;
break;
case MCBACKWARD_EMIS:
fprintf (stderr, "\n");
fprintf (stderr, "*** Warning, with MCBACKWARD_EMIS we are not supposed to end\n");
fprintf (stderr, "*** in count_thermal_backward_photon()\n");
fprintf (stderr, "\n");
return 1;
break;
default:
fprintf (stderr, "Error, unknown sample->backward %d in count_thermal_backward_photon()\n", sample->backward);
return 1;
}
/* If backward, then relate the escape result to a certain xy index */
if (sample->backward != MCBACKWARD_HEAT) {
result->back[sample->backward_is][sample->backward_js][ip] += add;
} else {
/* **CK 2013.08.27 */
switch (sample->heat_flag[sample->backward_is][sample->backward_js]) {
case MCBACKWARD_HEAT_EMABS:
case MCBACKWARD_HEAT_EMABSOPT:
result->backemis[sample->backward_is][sample->backward_js] += add_emis;
result->back[sample->backward_is][sample->backward_js][ip] += add;
break;
case MCBACKWARD_HEAT_DENET:
//fprintf (stderr, "CARO : %i %f %f\n", p->dEnet_component, add, totweight);
result->back[sample->backward_is][sample->backward_js][ip] += add;
break;
}
}
#if HAVE_ALIS
if (sample->spectral_is || sample->concentration_is) {
factor = (p->x[2] - atmos->Z[p->kc]) / (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
planck_ref = atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] +
factor * (atmos->Bplanck->prof[MCCAOTH_TOT][p->kc + 1][p->ic][p->jc] -
atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc]);
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
planck_iv = atmos->Bplanck_spectral[iv][p->kc] +
factor * (atmos->Bplanck_spectral[iv][p->kc + 1] - atmos->Bplanck_spectral[iv][p->kc]);
if (sample->spectral_is)
planck_ratio = planck_iv / planck_ref;
for (ic = 0; ic < atmos->Nc; ic++) {
result->back_t[ic][sample->backward_is][sample->backward_js][ip][iv] +=
add * totweight_spectral[iv] * totweight_concentration[ic] * planck_ratio;
/* fprintf(stderr, "FIXCE ic %d specweight %g concweight %g back_t %g add %g planck %g\n",ic, totweight_spectral[iv], totweight_concentration[ic], result->back_t[ic][iv][sample->backward_is][sample->backward_js][ip], add, planck_ratio ); CHECK!!! */
}
}
}
#endif
if (sample->std) { /* **CK 2013.08.27*/
if (sample->backward != MCBACKWARD_HEAT)
p->wtree = addtree_stddev (p->wtree, &(result->back2[sample->backward_is][sample->backward_js][ip]), add);
else {
switch (sample->heat_flag[sample->backward_is][sample->backward_js]) {
case MCBACKWARD_HEAT_EMABS:
case MCBACKWARD_HEAT_EMABSOPT:
p->wtree = addtree_stddev (p->wtree, &(result->back2[sample->backward_is][sample->backward_js][ip]), add + add_emis);
break;
case MCBACKWARD_HEAT_DENET:
result->back_dEnet[sample->backward_is][sample->backward_js][p->dEnet_component] += add / sqrt (p->n_dEnet);
result->back_dEnet2[sample->backward_is][sample->backward_js][p->dEnet_component] += add * add;
break;
}
}
}
}
//}
#if HAVE_ALIS
free (totweight_spectral);
free (totweight_concentration);
#endif
return 0;
}
/***********************************************************************************/
/* Function: intersection1D @62_30i@ */
/* Description: */
/* Calculate intersection with a 1D layer boundary. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void intersection1D (photon_struct* p, atmosphere_struct* atmos, double tau, double tausca, double* step, int source) {
double alpha = 0;
if (p->dir.hit[2] >= 0) /* upward or downward */
alpha = (atmos->Z[p->kc + p->dir.hit[2]] - p->x[2]) / p->dir.dx[2];
else { /* horizontal */
/* RPB: the extra MC_EPSILON is to prevent the photon */
/* from being trapped. The photon overshoots and is */
/* corrected to the right position in travel_tau */
if (source != MCSRC_THERMAL_BACKWARD)
alpha = (tau - tausca + MC_EPSILON) / get_kscaIS (atmos, p, MCCAOTH_TOT);
else
alpha = (tau - tausca + MC_EPSILON) / (get_kscaIS (atmos, p, MCCAOTH_TOT) + get_kabs_tot (atmos, p));
}
*step = alpha;
}
/***********************************************************************************/
/* Function: intersection1D_spherical @62_30i@ */
/* Description: */
/* Calculate intersection with a 1D spherical layer boundary. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Claudia Emde */
/* @i62_30@ */
/***********************************************************************************/
int intersection1D_spherical (photon_struct* p, atmosphere_struct* atmos, int refraction, float* refind, double* step) {
int i = 0;
double alpha = -1.;
double x = 0., y = 0., z = 0., r = 0., r_sq = 0., r1 = 0., r2 = 0.;
double costheta = 0., sintheta = 0.;
double rdr = 0.;
double r2diff = 1.0;
double r1diff = 1.0;
double N = 1.0, b1 = 0.0, a2 = 0.0, b2 = 0.0, fac = 0.0;
double e_r[3], e_t[3];
x = p->x[0] - atmos->xmax / 2.;
y = p->x[1] - atmos->ymax / 2.;
z = p->x[2] + atmos->r_earth;
/* r of layers below and above */
r2 = atmos->Z[p->kc + 1] + atmos->r_earth;
r1 = atmos->Z[p->kc] + atmos->r_earth;
r_sq = x * x + y * y + z * z;
r = sqrt (r_sq);
if (z < atmos->r_earth * 1e-5) {
fprintf (stderr, "\n");
fprintf (stderr, "*** Warning: Photon travelled around the Earth and is absorbed.\n");
fprintf (stderr, "\n");
p->weight = 0.0;
alpha = 0.;
return -1;
}
/* Normalize direction vector */
e_r[0] = x / r;
e_r[1] = y / r;
e_r[2] = z / r;
rdr = 0.0;
for (i = 0; i < 3; i++)
rdr += e_r[i] * p->dir.dx[i];
/* Angle between dr and r */
costheta = rdr;
sintheta = sqrt (1. - costheta * costheta);
/* fprintf(stderr, "=====================================\n"); */
/* fprintf(stderr, "refind kc+1 %g kc %g \n", refind[p->kc+1], refind[p->kc]); */
/* fprintf(stderr, "before refrac rdr %g dx %g dy %g dz %g costheta %g sintheta %g \n", */
/* rdr, p->dir.dx[0], p->dir.dx[1], p->dir.dx[2], costheta, sintheta); */
/* fprintf(stderr, "p %g \n", (1+refind[p->kc])*r*sintheta); */
if (refraction) {
/* if direction not parallel to radial or tangential direction */
if (rdr != 1.0 && sintheta < 0.999) {
if (costheta >= 0.0) /*upward*/
fac = (1 + refind[p->kc]) / (1 + refind[p->kc + 1]);
else { /* downward and limb*/
fac = (1 + refind[p->kc + 1]) / (1 + refind[p->kc]);
for (i = 0; i < 3; i++)
e_r[i] *= -1;
rdr *= -1;
}
/* Calculate tangential vector */
N = 0;
for (i = 0; i < 3; i++) {
e_t[i] = rdr * e_r[i] - p->dir.dx[i];
N += e_t[i] * e_t[i];
}
for (i = 0; i < 3; i++)
e_t[i] /= sqrt (N);
/* fprintf(stderr, "et %g %g %g \n", e_t[0], e_t[1], e_t[2]); */
/* fprintf(stderr, "er %g %g %g \n", e_r[0], e_r[1], e_r[2]); */
b1 = 0;
for (i = 0; i < 3; i++)
b1 += p->dir.dx[i] * e_t[i];
b2 = fac * b1;
a2 = sqrt (1. - b2 * b2);
/* fprintf(stderr, "fac %g b1 %g a2 %g b2 %g \n",fac, b1, a2, b2); */
for (i = 0; i < 3; i++)
p->dir.dx[i] = a2 * e_r[i] + b2 * e_t[i];
/* Recalculate rdr */
rdr = 0.0;
for (i = 0; i < 3; i++)
rdr += e_r[i] * p->dir.dx[i];
if (!(costheta >= 0.0)) {
for (i = 0; i < 3; i++)
e_r[i] *= -1;
rdr *= -1;
}
/* Special case limb ??? CHECK!!! */
if (costheta / rdr < 0.0)
rdr *= -1;
/* Angle between dr and r */
costheta = rdr;
sintheta = sqrt (1. - costheta * costheta);
}
/* fprintf(stderr, "after refrac rdr %g dx %g dy %g dz %g costheta %g sintheta %g \n", */
/* rdr, p->dir.dx[0], p->dir.dx[1], p->dir.dx[2], costheta, sintheta); */
/* fprintf(stderr, "p %g \n", (1+refind[p->kc])*r*sintheta); */
/* Check for normalisation */
/* N=sqrt(p->dir.dx[0]*p->dir.dx[0] + p->dir.dx[1]*p->dir.dx[1] + p->dir.dx[2]*p->dir.dx[2]); */
/* fprintf(stderr, "normalisation %g \n \n", N); */
} /* end refraction */
rdr *= r;
/* upward and limb */
if (costheta >= 0. || sintheta >= r1 / r) {
/* Numerical problems likely to occur here, especially if atmosphere */
/* has very thin layers, r_sq and r1*r1 are very close, so this threshold has been included. */
/* 0.01 is a very small value compared to r_sq, which is something like 6370e3*6370e3.*/
r2diff = r_sq - r2 * r2;
if (fabs (r2diff) > 0.01)
alpha = r2diff / (-rdr - sqrt (rdr * rdr - r2diff));
/* special case, intersection with the same layer */
else
alpha = -2. * r * costheta;
/* Direction forced to upward for "limb" cases.*/
p->dir.hit[2] = 1;
}
/* downward
else if (costheta < 0. && sintheta <r1/r)*/
else {
/* Numerical problems likely to occur here, see above */
r1diff = r_sq - r1 * r1;
if (fabs (r2diff) > 0.01) {
alpha = r1diff / (-rdr + sqrt (rdr * rdr - r1diff));
p->dir.hit[2] = 0;
}
else {
/* Photon is absorberd. This can only happen due to numerical
problems. */
p->weight = 0.0;
alpha = 0.0;
/*Some debugging output:*/
fprintf (stderr, "Photon absorbed by surface!!\n");
fprintf (stderr, "direction: %g \n", acosd (p->dir.dx[2]));
fprintf (stderr,
"position: z_p %g z_i %g z_i+1 %g, r %g \n",
p->x[2],
atmos->Z[p->kc],
atmos->Z[p->kc + 1],
r - atmos->r_earth);
fprintf (stderr, "x %f, y %f, z %f, p->x[0] %f, p->x[1], %f \n", x, y, z, p->x[0], p->x[1]);
fprintf (stderr, " r1/r %g costheta %g sintheta %g \n \n", r1 / r, costheta, sintheta);
return -1;
}
}
*step = alpha;
if (alpha < 0.0 || alpha != alpha) {
/*Some debugging output:*/
fprintf (stderr, "direction: %f \n", acosd (p->dir.dx[2]));
fprintf (stderr,
"position: z_p %f z_i %f z_i+1 %f, r %f \n",
p->x[2],
atmos->Z[p->kc],
atmos->Z[p->kc + 1],
r - atmos->r_earth);
fprintf (stderr, "x %f, y %f, z %f, p->x[0] %f, p->x[1], %f \n", x, y, z, p->x[0], p->x[1]);
fprintf (stderr, " r1/r %g costheta %g sintheta %g \n", r1 / r, costheta, sintheta);
fprintf (stderr, " alpha %g rdr*rdr %g r1diff %g r2diff %g r_sq %g r2 %g \n", alpha, rdr * rdr, r1diff, r2diff, r_sq, r2);
fprintf (stderr, "UUPS!!!: Steplength less or equal to zero: %.6e. If this does not happen\n", alpha);
fprintf (stderr, " too often, you can probably still trust your result.\n");
p->weight = 0.0;
alpha = 0.0;
return -1;
}
return 0;
}
/***********************************************************************************/
/* Function: step1D @62_30i@ */
/* Description: */
/* Move photon to the next layer boundary or to the next scattering point and */
/* and update layer number kc. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int step1D (photon_struct* p, atmosphere_struct* atmos, double step, int bcond, int photonpath, int visualize) {
int periodic = 0;
#if HAVE_OPENGL
double x = 0, y = 0, z = 0;
/* save start position and direction */
if (visualize) {
x = p->x[0];
y = p->x[1];
z = p->x[2];
}
#endif
/* new position */
if (!p->ipa) {
p->x[0] += step * p->dir.dx[0];
p->x[1] += step * p->dir.dx[1];
}
p->x[2] += step * p->dir.dx[2];
switch (bcond) {
case MCBCOND_PERIODIC:
periodic = perform_periodic_bc (p, atmos);
#if HAVE_OPENGL
if (visualize)
if (periodic && photonpath)
GLmystic_add_periodic_nodes_to_photon_path (p, atmos, x, y, z, step);
#endif
break;
case MCBCOND_ABSORB:
if (p->x[0] < 0 || p->x[0] > atmos->xmax || p->x[1] < 0 || p->x[1] > atmos->ymax) {
p->weight = 0.0;
p->photon_status = MCSTATUS_OUTOFDOMAIN;
return 0;
}
break;
case MCBCOND_MIRROR:
periodic = perform_mirroring_bc (p, atmos);
hitflag (&(p->dir)); /* need to update direction which probably has changed */
break;
default:
fprintf (stderr, "Error, unknown boundary conditions %d\n", bcond);
return -1;
}
/* determine indices of current box */
atmos_coord (p, atmos, &(p->ic), &(p->jc));
if (p->photon_status == MCSTATUS_TRAVEL) {
if (p->dir.hit[2] == 0) /* downward */
(p->kc)--;
if (p->dir.hit[2] == 1) /* upward */
(p->kc)++;
}
return periodic;
}
/***********************************************************************************/
/* Function: perform_periodic_bc @62_30i@ */
/* Description: */
/* Check whether photon is outside of grid, and apply periodic bc if necessary. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static inline int perform_periodic_bc (photon_struct* p, atmosphere_struct* atmos) {
int periodic = 0;
if (p->dir.hit[0]) {
/* photon moving in +x direction */
while (p->x[0] < 0) {
p->x[0] += atmos->xmax;
periodic = 1;
}
while (p->x[0] >= atmos->xmax) {
p->x[0] -= atmos->xmax;
periodic = 1;
}
} else {
/* photon moving in -x direction */
while (p->x[0] <= 0) {
p->x[0] += atmos->xmax;
periodic = 1;
}
while (p->x[0] > atmos->xmax) {
p->x[0] -= atmos->xmax;
periodic = 1;
}
}
if (p->dir.hit[1]) {
/* photon moving in +y direction */
while (p->x[1] < 0) {
p->x[1] += atmos->ymax;
periodic = 1;
}
while (p->x[1] >= atmos->ymax) {
p->x[1] -= atmos->ymax;
periodic = 1;
}
} else {
/* photon moving in -y direction */
while (p->x[1] <= 0) {
p->x[1] += atmos->ymax;
periodic = 1;
}
while (p->x[1] > atmos->ymax) {
p->x[1] -= atmos->ymax;
periodic = 1;
}
}
return periodic;
}
/***********************************************************************************/
/* Function: perform_mirroring_bc @62_30i@ */
/* Description: */
/* Check whether photon is outside of grid, and apply mirroring bc if necessary. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static inline int perform_mirroring_bc (photon_struct* p, atmosphere_struct* atmos) {
int mirroring = 0;
if (p->dir.hit[0]) {
/* photon moving in +x direction */
while (p->x[0] < 0 || p->x[0] >= atmos->xmax) {
if (p->x[0] < 0) {
p->x[0] = -p->x[0];
p->dir.dx[0] = -p->dir.dx[0];
}
if (p->x[0] >= atmos->xmax) {
p->x[0] = 2 * atmos->xmax - p->x[0];
p->dir.dx[0] = -p->dir.dx[0];
}
mirroring = 1;
}
} else {
/* photon moving in -x direction */
while (p->x[0] <= 0 || p->x[0] > atmos->xmax) {
if (p->x[0] <= 0) {
p->x[0] = -p->x[0];
p->dir.dx[0] = -p->dir.dx[0];
}
if (p->x[0] > atmos->xmax) {
p->x[0] = 2 * atmos->xmax - p->x[0];
p->dir.dx[0] = -p->dir.dx[0];
}
mirroring = 1;
}
}
if (p->dir.hit[1]) {
/* photon moving in +y direction */
while (p->x[1] < 0 || p->x[1] >= atmos->ymax) {
if (p->x[1] < 0) {
p->x[1] = -p->x[1];
p->dir.dx[1] = -p->dir.dx[1];
}
if (p->x[1] >= atmos->ymax) {
p->x[1] = 2 * atmos->ymax - p->x[1];
p->dir.dx[1] = -p->dir.dx[1];
}
mirroring = 1;
}
} else {
/* photon moving in -y direction */
while (p->x[1] <= 0 || p->x[1] > atmos->ymax) {
if (p->x[1] <= 0) {
p->x[1] = -p->x[1];
p->dir.dx[1] = -p->dir.dx[1];
}
if (p->x[1] > atmos->ymax) {
p->x[1] = 2 * atmos->ymax - p->x[1];
p->dir.dx[1] = -p->dir.dx[1];
}
mirroring = 1;
}
}
return mirroring;
}
/***********************************************************************************/
/* Function: calloc_photon @62_30i@ */
/* Description: */
/* Allocate memory for struct photon_struct. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
/* static */
photon_struct* calloc_photon (sample_struct* sample, int Nx, int Ny, int Nz, int source, int nlambda_abs, int Nc, int n_caoth) {
int i = 0;
photon_struct* p = calloc (1, sizeof (photon_struct));
/* allocate memory for radiance probabilities */
if (sample->Nd > 0)
p->pdir = calloc ((size_t)sample->Nd, sizeof (double));
/* allocate memory for weight vector */
p->stokes0 = calloc (4, sizeof (double));
p->stokes = calloc (4, sizeof (double));
p->phamat = calloc (4, sizeof (double*));
for (i = 0; i < 4; i++)
p->phamat[i] = calloc (4, sizeof (double));
/* spectral absorption */
if (sample->spectral_is || sample->concentration_is) {
/* p->nlambda=nlambda_abs; */
/* p->dtauabs_spectral = calloc (nlambda_abs, sizeof(double)); */
p->Nz_alis = Nz;
p->pathlength_per_layer = calloc (Nz, sizeof (double));
p->q_spectral = calloc (nlambda_abs, sizeof (double));
p->q2_spectral = calloc (nlambda_abs, sizeof (double));
p->q_albedo_spectral = calloc (nlambda_abs, sizeof (double));
p->q_concentration = calloc (Nc, sizeof (double));
p->q2_concentration = calloc (Nc, sizeof (double));
}
if (sample->jacobian || sample->jacobian3D)
calloc_photon_jacobian_part (p, sample, Nx, Ny, Nz, source, n_caoth);
if ((sample->boxairmass || sample->jacobian) && !(sample->spectral_is || sample->concentration_is)) {
p->pathlength_per_layer = calloc (Nz, sizeof (double));
p->Nx_boxairmass = 1;
p->Ny_boxairmass = 1;
p->Nz_alis = Nz;
} else if (sample->boxairmass3D || sample->jacobian3D) {
ASCII_calloc_double_3D (&p->pathlength_per_box, Nx, Ny, Nz);
p->Nx_boxairmass = Nx;
p->Ny_boxairmass = Ny;
p->Nz_alis = Nz;
}
if (sample->ncirc)
p->tocirco = calloc (100, sizeof (double*));
return p;
}
/***********************************************************************************/
/* Function: gen_default_sunshape @62_30i@ */
/* Description: */
/* Generate a wavelength dependend sunshape according to Köpke 2001 */
/* */
/* Parameters: wvnmlo, wvnmhi: Min and max wavenumbers */
/* N: number of requested supporting points for sunshape */
/* pd: (output) sunhape */
/* alpha: (output) relative position on sundisc (0-1) */
/* Return value */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Bernhard Reinhardt */
/* @i62_30@ */
/***********************************************************************************/
void gen_default_sunshape (float wvnmlo, float wvnmhi, int N, float* pd, double* alpha) {
/* Definition of constants:*/
double planck = 6.63e-34;
double speed_of_light = 2.998e8;
double boltzmann = 1.38e-23;
double T_S = 5740.0;
/* Wavelength */
double lambda = 2.0 / ((wvnmlo + wvnmhi) * 100.0);
/* Limb darkening coefficient*/
double beta = 3.0 * planck * speed_of_light * sqrt (sqrt (2.0)) / (8.0 * boltzmann * lambda * T_S);
int i;
/*pd = (float*) calloc(N+1,sizeof(float)); */
/*alpha = (double*) calloc(N+1,sizeof(double)); */
alpha[0] = 0.;
pd[0] = 1.;
for (i = 1; i < N; i++) {
alpha[i] = alpha[i - 1] + 1.0 / (N - 1);
pd[i] = (1.0 + beta * sqrt (fabs (1.0 - alpha[i] * alpha[i]))) / (1 + beta);
}
}
/***********************************************************************************/
/* Function: limb_dark_lest_dir @62_30i@ */
/* Description: */
/* Generate a photon escape direction according to a limb darkening function */
/* of the sun. I.e. choose a direction pointing to a spot in the sun disk */
/* */
/* Parameters: "dir_sun_center" is modified according to sunshape-information */
/* "sample" contains information about sunshape */
/* "phi" and "alpha" are filled with direction information about */
/* local estimate direction in regard to sun center */
/* Return value: 0 if ok, <=-1 if error */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Bernhard Reinhardt */
/* @i62_30@ */
/***********************************************************************************/
int limb_dark_lest_dir (direction* dir_sun_center, sample_struct* sample, double* phi, double* alpha) {
int j = 0;
double m = 0.0; /* slope of linear interpolation */
double random;
/* Sloppy check of sun shape */
if (sample->sample_backward_sunshape_n_lines < 3) {
fprintf (stderr,
"%s %s %s",
"sun shape file must contain more than one line and must be in correct format:",
" 1. Col: probability, 2. Col.: Normalized angular distance to center of sun:",
" 0-> center of sun, 1->limb of sun\n");
return -1;
}
random = uvspec_random();
j = locate (sample->sample_backward_sunshape_F, sample->sample_backward_sunshape_n_lines, random);
m = (sample->sample_backward_sunshape_alpha[j + 1] - sample->sample_backward_sunshape_alpha[j]) /
(sample->sample_backward_sunshape_F[j + 1] - sample->sample_backward_sunshape_F[j]);
*alpha = sample->sun_radius * (sample->sample_backward_sunshape_alpha[j] + m * (random - sample->sample_backward_sunshape_F[j]));
*phi = sc_Isotropic_phi();
new_direction (cosd (*alpha), *phi, dir_sun_center, 0.);
return 0;
}
/***********************************************************************************/
/* Function: generate_photon @62_30i@ */
/* Description: */
/* Generate a photon and inititalize its location and direction according to */
/* the source. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int generate_photon (int source,
int photoncounter,
atmosphere_struct* atmos,
albedo_struct* albedo,
elevation_struct* elev,
sample_struct* sample,
float wvnmlo,
float wvnmhi,
float wavelength,
double sza,
double phi,
int ipa,
long int nphotons,
photon_struct** new_photon,
float refractive_index_pv) {
/* ============================================================================== */
/* ==================== Declarations and Preparations =========================== */
/* ============================================================================== */
*new_photon = NULL;
double B = 0, emis = 0, phase = 0.0, tmpalb = 0.0;
int ia = 0, ja = 0;
double* norm = NULL;
int i = 0, j = 0, k = 0, ip = 0, iv = 0, isp = 0, ic = 0, jc = 0, kc = 0;
int hit = 0;
int status = 0;
static int counter1 = 0; /* **CK 2013.08.27 */
norm = calloc (3, sizeof (double));
double ran, apar, aperp, dd;
photon_struct* p = calloc_photon (sample, atmos->Nx, atmos->Ny, atmos->Nz, source, atmos->nlambda_abs, atmos->Nc, atmos->n_caoth);
#ifdef MUCHOUT
p->muchoutcounter = photoncounter;
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr, "Muchouting this photon: %d\n", p->muchoutcounter);
#endif
/* ============================================================================== */
/* ==================== Set Basic Stuff ========================================= */
/* ============================================================================== */
p->photoncounter = photoncounter;
p->backward_is = sample->backward_is;
p->backward_js = sample->backward_js;
p->scattercounter = 0; /* number of scattering events */
p->spikewarningcounter = 0; /* number of scattering events */
p->rayleighcounter = 0; /* number of rayleigh scattering events */
p->q_isoene = 1.0; /* weight of rayleigh scattering events */
p->direct = 1; /* indicates direct of diffuse */
p->pathlength = 0; /* photon pathlength */
p->weight = 1.0; /* photon weight for e.g. importance sampling */
p->weight_emis = 1.0; /* **CK 2013.08.27 photon weight for thermal backward emission - set to 1 here, changed later! */
p->phi0 = phi;
if (sample->backward) {
p->fw_phi0 = sample->forward_phi0;
p->fw_phi = phi;
} else {
p->fw_phi0 = phi;
p->fw_phi = sample->forward_phi;
}
p->special_weight = 1.0; /* photon weight for sponti-clone; has nothing to do with spectral IS! */
p->vis_beta = 0.0;
p->reflectcounter = 0;
p->tauext_tot = 0.0;
p->photon_status = MCSTATUS_TRAVEL;
p->maxpathlength = 1e33; /* if photon travels further, kill it */
/* Initially the polarization of the photon is defined in (x,y,z) coordinates,
later with respect to the respective scattering frames */
p->dir_ort.dx[0] = 0.0;
p->dir_ort.dx[1] = 0.0;
p->dir_ort.dx[2] = 1.0;
/* Assign unity matrix to phase matrix */
p->phamat[0][0] = 1.0;
p->phamat[1][1] = 1.0;
p->phamat[2][2] = 1.0;
p->phamat[3][3] = 1.0;
/* reset pathlengths */
p->tauabs.mol = 0;
p->tauabs.aer = 0;
p->tauabs.cld = 0;
p->tauabs.ice = 0;
p->tauabs.tot = 0;
p->tauris = 0;
p->tauext_tot = 0;
/* reset reallyhit */
p->reallyhit[0] = 0;
p->reallyhit[1] = 0;
p->reallyhit[2] = 0;
p->ncircos = 0;
p->isclone = 0;
p->clonescattercounter = 0;
p->escapescattercounter = 0;
p->update_atmos_coord = 0;
p->doling = 0;
/* ============================================================================== */
/* ==================== Stokes Vector =========================================== */
/* ============================================================================== */
p->stokes0[0] = 1.0; /* starting photon stokes vector intensity */
for (i = 1; i < 4; i++) /* starting photon weight vector required for polarization */
p->stokes0[i] = 0.0;
switch (sample->polarisation_state) {
case 0: /* In case of natural solar/thermal radiation w=(1,0,0,0) */
break;
case 1:
p->stokes0[1] = 1.0; /* +Q polarisation */
break;
case 2:
p->stokes0[2] = 1.0; /* +U polarisation */
break;
case 3:
p->stokes0[3] = 1.0; /* +V polarisation */
break;
case -1:
p->stokes0[1] = -1.0; /* -Q polarisation */
break;
case -2:
p->stokes0[2] = -1.0; /* -U polarisation */
break;
case -3:
p->stokes0[3] = -1.0; /* -V polarisation */
break;
case 4: /* randomized Stokes Vector, fulfills I^2 = Q^2 + U^2 + V^2 */
ran = 2 * PI * uvspec_random();
apar = fabs (cos (ran));
aperp = fabs (sin (ran));
dd = 2 * PI * uvspec_random();
p->stokes0[1] = apar * apar - aperp * aperp;
p->stokes0[2] = 2 * apar * aperp * cos (dd);
p->stokes0[3] = -2 * apar * aperp * sin (dd);
break;
case 5: /* Manually set initial Stokes Vector here! */
p->stokes0[1] = sqrt (0.5); /* example values */
p->stokes0[2] = 0.5;
p->stokes0[3] = 0.5;
break;
default:
CHKERROUT (sample->polarisation_state, "no valid polarisation mode in generate_photon()!");
}
#ifdef CLDPRP
/* ============================================================================== */
/* ==================== Cloud Prop ============================================== */
/* ============================================================================== */
if (sample->cldprp) {
p->cldprp.reff_wc = 0.0;
p->cldprp.reff_ic = 0.0;
p->cldprp.rhit_wc = 0.0;
p->cldprp.rhit_ic = 0.0;
p->cldprp.tau_wc = 0.0;
p->cldprp.tau_ic = 0.0;
p->cldprp.dxlwc = 0.0;
p->cldprp.dylwc = 0.0;
p->cldprp.dzlwc = 0.0;
p->cldprp.dxiwc = 0.0;
p->cldprp.dyiwc = 0.0;
p->cldprp.dziwc = 0.0;
}
#endif
/* ============================================================================== */
/* ==================== Importance Sampling ===================================== */
/* ============================================================================== */
p->RIS_mode = MCRIS_MODE_NORMAL; /* standard mode for (Real) Importance Sampling */
p->VIS_mode = MCVIS_MODE_NORMAL; /* standard mode for Virtual Importance Sampling */
if (sample->delta_scaling == 0) {
p->SC_mode = MCSC_MODE_DELTA_SCALE; /* delta scaling mode for Scattering */
p->DDIS_SC_mode = MCSC_MODE_DELTA_SCALE; /* delta scaling mode for DDIS */
} else {
p->SC_mode = MCSC_MODE_NORMAL; /* standard mode for Scattering */
p->DDIS_SC_mode = MCSC_MODE_NORMAL; /* standard mode for DDIS */
}
p->iv_alis = -1;
if (sample->spectral_is) {
p->iv_alis = atmos->ilambda_ref[0];
p->nlambda = atmos->nlambda_abs;
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
p->q_spectral[iv] = 1.0; /* weight for single scattering albedo */
p->q2_spectral[iv] = 1.0; /* weight for phase function */
p->q_albedo_spectral[iv] = 1.0; /* weigth for spectral albedo */
/* p->dtauabs_spectral[iv]=0.0; old method */
}
for (k = 0; k < atmos->Nz; k++) {
p->pathlength_per_layer[k] = 0.0;
}
}
if (sample->concentration_is) {
p->Nc = atmos->Nc;
for (i = 0; i < atmos->Nc; i++) {
p->q_concentration[i] = 1.0; /* weight for single scattering albedo */
p->q2_concentration[i] = 1.0; /* weight for phase function */
}
for (kc = 0; kc < atmos->Nz; kc++)
p->pathlength_per_layer[kc] = 0.0;
}
/* ============================================================================== */
/* ==================== Miscellaneous =========================================== */
/* ============================================================================== */
if (sample->boxairmass || sample->jacobian) {
for (kc = 0; kc < atmos->Nz; kc++) {
p->pathlength_per_layer[kc] = 0.0;
}
} else if (sample->boxairmass3D || sample->jacobian3D) {
for (ic = 0; ic < atmos->Nx; ic++) {
for (jc = 0; jc < atmos->Ny; jc++) {
for (kc = 0; kc < atmos->Nz; kc++) {
p->pathlength_per_box[ic][jc][kc] = 0.0;
}
}
}
}
if (sample->jacobian || sample->jacobian3D) {
for (isp = 0; isp < atmos->n_caoth; isp++) {
for (ic = 0; ic < atmos->Nx; ic++) {
for (jc = 0; jc < atmos->Ny; jc++) {
for (kc = 0; kc < atmos->Nz; kc++) {
p->q_jacobian_sca[isp][ic][jc][kc] = 0.0;
}
}
}
}
}
/* independent pixel */
if (sample->tipadir == 3) /* should be TIPA_DIR3D */
p->ipa = 0;
else
p->ipa = ipa;
if (sample->LLE_moon) /* BCA clean up! */
source = MCSRC_SOLAR;
/* horizontal start position */
/* within the pixel: x = i*dx .. (i+1)*dx; y = j*dy .. (j+1)*dy*/
/* ============================================================================== */
/* ========== Set Starting Position and Direction Depending on Source =========== */
/* ============================================================================== */
switch (source) {
/* ============================================================================== */
/* ========== SOLAR, BLITZ, THERMAL_BACKWARD: Starting Position and Direction === */
/* ============================================================================== */
case MCSRC_SOLAR:
case MCSRC_BLITZ:
case MCSRC_THERMAL_BACKWARD:
if ((p = generate_photon_backward (sample,
atmos,
p,
elev,
&hit,
nphotons,
&counter1,
sza,
phi,
phase,
source,
norm,
refractive_index_pv)) == NULL)
CHKERROUT (-1, "Error in generate_photon_backward()!");
break;
/* ============================================================================== */
/* ========== THERMAL_SURFACE: Starting Position and Direction ================== */
/* ============================================================================== */
case MCSRC_THERMAL_SURFACE:
if (elev->elev2D && !sample->backward)
CHKERROUT (1, "topography and thermal emission only available with backward MYSTIC!");
/* ??? don't forget to consider sensorposition and sensordirection when implementing backward CHECK!!! */
if (sample->backward)
CHKERROUT (1, "Error, backward not implemented for MCSRC_THERMAL_SURFACE");
p->direct = 0; /* no direct beam source */
/* horizontal start position: */
/* a rectangle: x = 0 .. xmax; y = 0 .. ymax */
/* loop until photon is emitted */
while (1) {
p->x[0] = atmos->xmax * uvspec_random();
p->x[1] = atmos->ymax * uvspec_random();
/* albedo coordinates */
if (albedo->method == MCALB_LAM2D || albedo->method == MCALB_LAM2D_SPECTRAL) {
if (sample->spherical3D) {
#if HAVE_MYSTIC3D
coord_spherical3D (p, albedo->Nx, albedo->X, albedo->Ny, albedo->Y, 0, NULL, 0, NULL, 0, &ia, &ja, NULL, NULL, 0);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else
albedo_coord (p, albedo, &ia, &ja);
}
switch (albedo->method) {
case MCALB_LAM:
tmpalb = albedo->albedo;
break;
case MCALB_LAM2D:
tmpalb = albedo->albedo2D[ia][ja];
break;
case MCALB_LAM2D_SPECTRAL:
tmpalb = albedo->alb_type[(int)albedo->surface_index[ia][ja]];
break;
default:
fprintf (stderr, "Error, albedo->method %d not yet implemented!\n", albedo->method);
CHKERR (albedo->method);
}
if (emission (tmpalb))
break;
}
atmos_coord (p, atmos, &(p->ic), &(p->jc));
/* initialize direction: isotropic upward */
norm[0] = 0.0;
norm[1] = 0.0;
norm[2] = 1.0;
random_Lambertian_normal (&(p->dir), norm);
/* vertical start position: surface */
/* Make always sure to call set_photon_z() AFTER the new photon */
/* direction has been assigned because the start index and position */
/* might depend on direction */
set_photon_z (atmos->Z[0], atmos, p);
break;
/* ============================================================================== */
/* ========== THERMAL_ATMOSPHERE: Starting Position and Direction =============== */
/* ============================================================================== */
case MCSRC_THERMAL_ATMOSPHERE:
if (elev->elev2D && !sample->backward) {
CHKERROUT (1, "Error, topography and thermal emission only available with backward MYSTIC!");
}
if (sample->backward) {
/* ??? don't forget to consider sensorposition and sensordirection when implementing backward CHECK!!! */
CHKERROUT (1, "Error, backward not implemented for MCSRC_THERMAL_ATMOSPHERE");
}
p->direct = 0; /* no direct beam source */
/* horizontal start position: */
/* a rectangle: x = 0 .. xmax; y = 0 .. ymax */
/* initialize direction: isotropic */
random_direction (&(p->dir));
/* loop until photon is emitted */
while (1) {
p->x[0] = atmos->xmax * uvspec_random();
p->x[1] = atmos->ymax * uvspec_random();
/* Make always sure to call set_photon_z() AFTER the new photon */
/* direction has been assigned because the start index and position */
/* might depend on direction */
set_photon_z (atmos->Z[0] + uvspec_random() * (atmos->Z[atmos->Nz] - atmos->Z[0]), atmos, p);
atmos_coord (p, atmos, &(p->ic), &(p->jc));
/* interpolate Bplanck linearely between levels */
B = atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] +
(p->x[2] - atmos->Z[p->kc]) / (atmos->Z[p->kc + 1] - atmos->Z[p->kc]) *
(atmos->Bplanck->prof[MCCAOTH_TOT][p->kc + 1][p->ic][p->jc] - atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc]);
if (atmos->kabs3D->threed[MCCAOTH_TOT][p->kc] >= 1)
emis = B * atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc];
else
emis = B * atmos->kabs->prof[MCCAOTH_TOT][p->kc];
if (uvspec_random() <= emis)
break;
}
break;
/* ============================================================================== */
/* ========== LIDAR: Set everything Lidar-related (Function in lidar.c) ========= */
/* ============================================================================== */
case MCSRC_LIDAR:
#if HAVE_LIDAR
status = generate_photon_lidar (p, sample, atmos);
CHKERROUT (status, "Error returned by generate_photon_lidar_part()");
#endif
break;
default:
CHKERROUT (1, "Error, unknown or unimplemented MC source type");
}
/* ============================================================================== */
/* ========== More Miscellaneous Stuff ========================================== */
/* ============================================================================== */
#if HAVE_LIDAR
if (sample->LLE_moon)
status = generate_photon_lidar (p, sample, atmos);
#endif
/* this is a quick and dirty solution: photons starting horizontally in a non-absorbing, non-scattering */
/* layer might cause an infinite loop - therefore we set the photon weight of these photons to 0. */
/* Should find a better solution - at least check the extinction coefficient and stop only if the */
/* latter is 0. */
if (p->dir.dx[2] == 0 && sample->bcond != MCBCOND_ABSORB) {
fprintf (stderr, "Photon starting in horizontal direction - this might cause trouble\n");
fprintf (stderr, "and the photon weight is set to 0 for this reason. If you see this\n");
fprintf (stderr, "message just occasionally everything is ok. If it appears many many\n");
fprintf (stderr, "times, you should not trust the result! Photon coordinates:\n");
fprintf (stderr,
"(%d, %d, %d), (%g, %g, %g), (%g, %g, %g)\n",
p->ic,
p->jc,
p->kc,
p->x[0],
p->x[1],
p->x[2],
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2]);
p->weight = 0;
}
for (ip = 0; ip < 4; ip++) {
p->stokes[ip] = 0.0;
for (j = 0; j < 4; j++)
p->stokes[ip] += p->phamat[ip][j] * p->stokes0[j];
}
if (sample->use_p_norm) {
double mu_norm = 0.0;
if (sample->escape) {
status = v_mult_mu (p->dir.dx, sample->rad[0].dir.dx, &mu_norm);
CHKERR (status);
}
if (sample->LidarLocEst)
v_mult (sample->lidar[sample->ili].dir.dx, p->dir.dx, &mu_norm);
p->p_norm = get_phase_max (sample->phase_max, sample->n_phase_max, mu_norm, 0);
} else
p->p_norm = 0.0;
#ifdef PRINT_PHOTON_PATH
/* add photon to photon path */
add_to_photonpath (&(p->path), p->x, p->weight);
#endif
#if HAVE_LIDAR
/* CB - add coordinate to cohebasca */
if (sample->coherent_backscatter && sample->LidarLocEst) {
add_coord_to_cohebasca (p);
p->pss.ic_s = p->ic;
p->pss.jc_s = p->jc;
p->pss.kc_s = p->kc;
}
#endif
fflush (stderr);
free (norm);
/* intersect_triangle_id will only be different from -1 (i.e. overflow to HUGE(size_t)), if the photon recently hit a triangle surface */
p->intersect_triangle_id = -1;
*new_photon = p;
return 0;
}
/***********************************************************************************/
/* Function: generate_photon_backward @62_30i@ */
/* Description: */
/* */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
photon_struct* generate_photon_backward (sample_struct* sample,
atmosphere_struct* atmos,
photon_struct* p,
elevation_struct* elev,
int* hit,
long int nphotons,
int* counter1,
double sza,
double phi,
double phase,
int source,
double* norm,
float refractive_index_pv)
{
double local_elevation = 0.0;
int ie = 0, je = 0;
double alpha = 0;
int status = 0;
/* ------------------------------------------------------------------------------ */
/* ---------- 1. SOLAR BLITZ THERMAL_BW: Various Checks ------------------------- */
/* ------------------------------------------------------------------------------ */
/* check consistency of settings, exit if error */
if (source == MCSRC_THERMAL_BACKWARD) {
if (!sample->backward) {
fprintf (stderr, "Fatal error, we shouldn't end up in MCSRC_THERMAL_BACKWARD\n");
fprintf (stderr, "in a forward calculation - programming error!\n");
return NULL;
}
if (sample->backward == MCBACKWARD_EDIR || sample->backward == MCBACKWARD_FDIR) {
fprintf (stderr, "Fatal error, direct radiation and MCSRC_THERMAL_BACKWARD\n");
fprintf (stderr, "does not make sense - programming error!\n");
return NULL;
}
if (sample->spherical) {
fprintf (stderr, "Warning, spherical and MCSRC_THERMAL_BACKWARD\n");
fprintf (stderr, "has never been tested, might be bullshit!\n");
}
}
if (source == MCSRC_SOLAR || source == MCSRC_BLITZ) {
switch (sample->backward) {
case MCBACKWARD_ABS:
case MCBACKWARD_HEAT:
case MCBACKWARD_EMIS:
// case MCBACKWARD_ACT:
fprintf (stderr, "Fatal error, MCSRC_SOLAR does not make sense\n");
fprintf (stderr, "with backward mode %d - programming error!\n", sample->backward);
return NULL;
}
}
/* ------------------------------------------------------------------------------ */
/* ---------- 2. SOLAR BLITZ THERMAL_BW: Set Horizontal Starting Position ------- */
/* ------------------------------------------------------------------------------ */
if (source == MCSRC_THERMAL_BACKWARD)
p->direct = 0; /* no direct beam source */
else
p->direct = 1; /* direct beam source */
/* horizontal start position */
/* within the pixel: x = i*dx .. (i+1)*dx; y = j*dy .. (j+1)*dy*/
if (!sample->backward) { /* forward */
if (source == MCSRC_BLITZ) {
/* simulate blitz */
alpha = uvspec_random();
p->x[0] = (sample->blitz_position[3] - sample->blitz_position[0]) * alpha + sample->blitz_position[0];
p->x[1] = (sample->blitz_position[4] - sample->blitz_position[1]) * alpha + sample->blitz_position[1];
p->x[2] = (sample->blitz_position[5] - sample->blitz_position[2]) * alpha + sample->blitz_position[2];
} else {
p->x[0] = atmos->xmax * uvspec_random();
p->x[1] = atmos->ymax * uvspec_random();
/* radial/pathlength calculation */
if (sample->Nr > 0 && sample->dt > 0) {
p->x[0] = atmos->xmax / 2.0;
p->x[1] = atmos->ymax / 2.0;
}
}
} else { /* backward */
if (!sample->spherical) {
if (!sample->sensorposition) { /* random */
p->x[0] = ((double)sample->backward_is + uvspec_random()) * sample->delX;
p->x[1] = ((double)sample->backward_js + uvspec_random()) * sample->delY;
/* for horizontal irradiances we start on the side face */
switch (sample->backward) {
case MCBACKWARD_EXP:
case MCBACKWARD_EXN:
p->x[0] = ((double)sample->backward_is) * sample->delX;
break;
case MCBACKWARD_EYP:
case MCBACKWARD_EYN:
p->x[1] = ((double)sample->backward_js) * sample->delY;
break;
default:
break;
}
} else { /* user-defined */
p->x[0] = sample->sensorposition_x[0];
p->x[1] = sample->sensorposition_x[1];
}
} else { /* spherical, start position is center of domain */
p->x[0] = atmos->xmax / 2.0;
p->x[1] = atmos->ymax / 2.0;
}
}
if (!sample->spherical3D)
atmos_coord (p, atmos, &(p->ic), &(p->jc));
/* ------------------------------------------------------------------------------ */
/* ---------- 3. SOLAR BLITZ THERMAL_BW: Set Vertical Starting Position 1 ------- */
/* ------------------------------------------------------------------------------ */
/*********************************************/
/* first define third photon position (x[2]) */
/*********************************************/
if (sample->spherical3D)
/* set_photon_z is called later for spherical3D; the sensor
may still be outside the atmosphere at this point */
p->x[2] = sample->sensorposition_x[2];
else {
if (source != MCSRC_BLITZ) {
if (!sample->sensorposition) {
if (sample->zstart != -999.0) /* XXX??? or should it be (sample->zstart>0) for TH_BW? CHECK!!! */
p->x[2] = sample->zstart;
else
p->x[2] = atmos->Z[0];
} else
p->x[2] = sample->sensorposition_x[2];
}
/* else already set for blitz */
}
/* ------------------------------------------------------------------------------ */
/* ---------- 4. SOLAR BLITZ THERMAL_BW: Initialize Photon Direction ------------ */
/* ------------------------------------------------------------------------------ */
/******************************************************/
/* second calculate normal vector relative to surface */
/******************************************************/
calc_normal_vector (p,
elev,
sample,
atmos,
sample->surfaceparallel && sample->zstart == -999.0,
sample->sensordirection && sample->zstart == -999.0,
norm);
/*************************************/
/* third initialize photon direction */
/*************************************/
if (generate_photon_backward_photon_direction (sample,
atmos,
p,
elev,
hit,
nphotons,
counter1,
sza,
phi,
phase,
source,
norm,
refractive_index_pv) == NULL) {
fprintf (stderr, "Error in generate_photon_backward_photon_direction()!\n");
return NULL;
}
/* ------------------------------------------------------------------------------ */
/* ---------- 5. SOLAR BLITZ THERMAL_BW: Set Vertical Starting Position 2 ------- */
/* ------------------------------------------------------------------------------ */
/**********************************************************/
/* fourth determine vertical start position of the photon */
/**********************************************************/
/* flat surface */
/* Make always sure to call set_photon_z() AFTER the new photon */
/* direction has been assigned because the start index and position */
/* might depend on direction */
if (sample->spherical3D) {
/* if photon is outside of atmosphere, move it to border */
#if HAVE_MYSTIC3D
status = move_satellite_photon_to_toa (p, atmos);
if (status < 0) {
fprintf (stderr, "Error %d returned by move_satellite_photon_to_toa()\n", status);
return NULL;
}
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return NULL;
#endif
/* return photon with weight 0 if status>0 */
if (status > 0)
return p;
#if HAVE_MYSTIC3D
coord_spherical3D (p,
atmos->Nx,
atmos->X,
atmos->Ny,
atmos->Y,
atmos->Nz,
atmos->Z,
atmos->Nyg,
atmos->Yg,
atmos->r_earth,
&(p->ic),
&(p->jc),
&(p->kc),
&(p->jcg),
0);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return NULL;
#endif
} /* spherical3D end */
else
set_photon_z (p->x[2], atmos, p);
if (generate_photon_backward_vertical_position (sample, atmos, p, hit, nphotons, counter1)) {
fprintf (stderr, "Error in generate_photon_backward_vertical_position()!\n");
return NULL;
}
/* ------------------------------------------------------------------------------ */
/* ---------- 6. SOLAR BLITZ THERMAL_BW: Set Topography ------------------------- */
/* ------------------------------------------------------------------------------ */
/* topography */
if (elev->elev2D) {
switch (sample->backward) {
case MCBACKWARD_NONE:
/* nothing to do */
break;
default:
/* elevation coordinates */
elev_coord (p, elev, &ie, &je);
/* elevation at the given coordinates */
local_elevation = elevation (elev->surf[ie][je], p->x[0] - (double)ie * elev->delX, p->x[1] - (double)je * elev->delY);
/* if surface sampling then set start altitude to elevation at start location */
if (!sample->sensorposition) {
if (sample->zstart == -999.0) {
/* in any case, go away from the surface a little bit */
/* as the photon might get a direction directly into */
/* the surface and we want to avoid rounding problems */
/* Make always sure to call set_photon_z() AFTER the new photon */
/* direction has been assigned because the start index and position */
/* might depend on direction */
set_photon_z (local_elevation * (1.0 + MC_EPSILON), atmos, p);
}
} else /* user-defined sensor position */
set_photon_z (sample->sensorposition_x[2], atmos, p);
/* Sampling altitude below the ground; this happens when */
/* the sampling altitude zout[0] is lower than the highest */
/* point of the model area; this is reasonable, but we need */
/* to set the photon weight to 0 and start the photon above */
/* ground; it will not be traced anyway and will therefore */
/* not contribute to the result. */
if (p->x[2] < local_elevation) {
set_photon_z (local_elevation * (1.0 + MC_EPSILON), atmos, p);
/* weight is not consistently handled - need to set both weight and tauabs.tot to NAN */
p->tauabs.tot = NOT_A_NUMBER; /* NAN if photons starts below the ground */
p->weight = NOT_A_NUMBER; /* NAN if photons starts below the ground */
}
} /* endif sample->backward */
} /* endif elev2D */
/* ------------------------------------------------------------------------------ */
/* ---------- 7. SOLAR BLITZ THERMAL_BW: Reference to NN ------------------------ */
/* ------------------------------------------------------------------------------ */
/* sample pixel is referenced to NN according to photon direction */
if (sample->reference_to_NN) {
if (p->dir.dx[2] == 0) {
fprintf (stderr, "Fatal error, referencing to NN does not work with\n");
fprintf (stderr, "horizontally moving photons! Exiting...\n");
return NULL;
}
/* fprintf(stderr,"position before referencing %e %e %d %d\n",p->x[0],p->x[1],p->ic,p->jc); */
/* fprintf(stderr,"direction %e %e %e\n",p->dir.dx[0],p->dir.dx[1],p->dir.dx[2]); */
/* move photon along photon direction from NN to starting altitude */
p->x[0] += p->x[2] * p->dir.dx[0] / p->dir.dx[2];
p->x[1] += p->x[2] * p->dir.dx[1] / p->dir.dx[2];
/* photon might have left domain, use periodic boundary conditions to move it back into it */
/* maybe replace the following with
status = perform_periodic_bc (p, atmos); */
switch (sample->bcond) {
case MCBCOND_PERIODIC:
while (p->x[0] < 0)
p->x[0] += atmos->xmax;
while (p->x[0] >= atmos->xmax)
p->x[0] -= atmos->xmax;
while (p->x[1] < 0)
p->x[1] += atmos->ymax;
while (p->x[1] >= atmos->ymax)
p->x[1] -= atmos->ymax;
/* update indices of photon */
atmos_coord (p, atmos, &(p->ic), &(p->jc));
break;
case MCBCOND_MIRROR:
fprintf (stderr, "Error, mirroring boundary conditions not implemented with mc_reference_to_nn.\n");
return NULL;
case MCBCOND_ABSORB:
fprintf (stderr, "Error, absorbing boundary conditions not implemented with mc_reference_to_nn.\n");
return NULL;
default:
fprintf (stderr, "Error, unknown boundary conditions %d\n", sample->bcond);
return NULL;
}
/* fprintf(stderr,"position after referencing %e %e %d %d \n",p->x[0],p->x[1],p->ic,p->jc); */
} /* endif reference_to_NN */
/* need to weight with the area of the actual surface for backward surface-parallel */
if (elev->elev2D && sample->surfaceparallel && sample->backward != MCBACKWARD_NONE) {
if (sample->sensorposition || sample->zstart == -999.0) { /* only for photons starting at the surface */
/* BMSURFACEPARALLEL */
p->weight /= fabs (norm[2]);
}
}
return p;
}
/***********************************************************************************/
/* Function: generate_photon_backward_photon_direction @62_30i@ */
/* Description: */
/* */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
photon_struct* generate_photon_backward_photon_direction (sample_struct* sample,
atmosphere_struct* atmos,
photon_struct* p,
elevation_struct* elev,
int* hit,
long int nphotons,
int* counter1,
double sza,
double phi,
double phase,
int source,
double* norm,
float refractive_index_pv) {
double sinsza = 0, cossza = 0, sinphi = 0, cosphi = 0;
int status = 0;
int i = 0;
switch (sample->backward) {
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~ 5.1 SOLAR BLITZ THERMAL_BW / NONE RAD: Photon Direction ~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_NONE:
case MCBACKWARD_RADIANCE:
/* initialize direction using the specified solar zenith and azimuth angles which, */
/* backward mode is active, contain the actual viewing angles (see setup_sample2D) */
/* sine and cosine of solar zenith */
cossza = cosd (sza);
sinsza = sind (sza);
/* sine and cosine of solar azimuth */
cosphi = cosd (phi);
sinphi = sind (phi);
/* use different umu for each pixel */
if (sample->umu2D != NULL && sample->backward == MCBACKWARD_RADIANCE) {
/* sine and cosine of solar zenith */
cossza = sample->umu2D[p->ic][p->jc];
sinsza = sqrt (1.0 - cossza * cossza);
/* sine and cosine of solar azimuth */
cosphi = cosd (sample->phi2D[p->ic][p->jc]);
sinphi = sind (sample->phi2D[p->ic][p->jc]);
}
if (!sample->panorama) {
/* .............................................................................. */
/* ..................... 5.1.1 BLITZ / NONE RAD / Photon Direction .............. */
/* .............................................................................. */
if (source == MCSRC_BLITZ) {
if (!sample->escape_eps_ddis_upf)
random_direction (&(p->dir));
else {
/* First start the photon directly into the direction of
the detector; for blitz, cos(sza)==umu, phi==phi0 */
init_direction (sinsza, -cossza, sinphi, cosphi, &(p->dir));
/* Choose a random starting mu according to phase
function phase_max for the photon by abusing the
scattering routine sc_mu */
cossza = sc_mu (sample->phase_max[0], 1, p->SC_mode, 0.0, 0.0);
/* Now adjust photon weight for the "unphysical"
choice of direction: Divide photon-weight by
probability from phase_max for sending it into this
direction */
status = get_phase_matrix_pft (sample->phase_max[0], cossza, 0, 1, &phase);
if (status) {
fct_err_out (status, "get_phase_matrix_pft", ERROR_POSITION);
return NULL;
}
p->weight /= phase;
/* Then modify direction according to give mu and phi */
phi = sc_Isotropic_phi();
new_direction (cossza, phi - 90., &(p->dir), 0.);
}
}
/* .............................................................................. */
/* .............. 5.1.2 SOLAR THERMAL_BW / NONE RAD / Photon Direction .......... */
/* .............................................................................. */
else {
init_direction (sinsza, cossza, sinphi, cosphi, &(p->dir));
}
}
/* .............................................................................. */
/* ... 5.1.3 SOLAR BLITZ THERMAL_BW / NONE RAD / Panorama / Photon Direction .... */
/* .............................................................................. */
else { /* PANORAMA */
generate_photon_backward_photon_direction_panorama (sample, p, phi, sza, cossza, sinsza, cosphi, sinphi);
}
cp_direction (&(p->dir0), &(p->dir));
/* CE: Probably not needed, CHECK!!! */
/* #ifdef NEW_REFLECT */
/* p->phi0=calc_phi_horz ( p->dir.dx, NULL); */
/* #endif */
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~ 5.2 SOLAR BLITZ THERMAL_BW / EDIR EGLOB EDN / Photon Direction ~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_EDIR:
case MCBACKWARD_EGLOB:
case MCBACKWARD_EDN:
random_Lambertian_normal (&(p->dir), norm);
break;
/* Weight photon direction with directional transmission for glass of PV cell. */
case MCBACKWARD_EDNPV:
random_Lambertian_normal (&(p->dir), norm);
p->weight = pv_model_weight (p->dir.dx, norm, refractive_index_pv);
/* fprintf(stderr, "weight %.5f \n", p->weight); */
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 5.3 SOLAR BLITZ THERMAL_BW / EUP / Photon Direction ~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_EUP:
/* reverse direction because we need to go downward */
for (i = 0; i < 3; i++)
norm[i] = -norm[i];
random_Lambertian_normal (&(p->dir), norm);
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 5.4 SOLAR BLITZ THERMAL_BW / FDIR / Photon Direction ~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_FDIR:
if (sample->spherical3D) {
fprintf (stderr, "Error, backward fdir and spherical3d bugs!\n");
return NULL;
}
random_Isotropic_normal (&(p->dir), norm);
p->weight = 1.0 / fabs (cosd (sza));
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 5.5 SOLAR BLITZ THERMAL_BW / FDN / Photon Direction ~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_FDN:
random_Isotropic_normal (&(p->dir), norm);
p->weight = 2.0;
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 5.6 SOLAR BLITZ THERMAL_BW / FUP / Photon Direction ~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_FUP:
/* reverse direction because we need to go inward */
for (i = 0; i < 3; i++)
norm[i] = -norm[i];
random_Isotropic_normal (&(p->dir), norm);
p->weight = 2.0;
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 5.7 SOLAR BLITZ THERMAL_BW / ABS EMIS ACT / Photon Direction ~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_ABS:
case MCBACKWARD_EMIS:
case MCBACKWARD_ACT: /* **CK 2013.08.27 remove MCBACKWARD_HEAT from here and add in following lines the specific calculations */
random_direction (&(p->dir));
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 5.8 SOLAR BLITZ THERMAL_BW / HEAT / Photon Direction ~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_HEAT: /* **CK 2013.08.27 Apply different thermal backward heating rate calculations */
switch (sample->heat_flag[sample->backward_is][sample->backward_js]) {
case MCBACKWARD_HEAT_DENET:
hunt_modified (atmos->Z, atmos->Nz, p->x[2], &(p->kc), hit); /* **CK 2014.01.13 added hunt_modified here! */
status = denet_set_direction (p, atmos, sample, nphotons, counter1, norm); /* **CK 2013.08.27 */
if (status != 0) {
fprintf (stderr, "Error %d returned by denet_set_direction()\n", status);
return NULL;
}
break;
case MCBACKWARD_HEAT_EMABS:
case MCBACKWARD_HEAT_EMABSOPT:
random_direction (&(p->dir));
break;
default:
fprintf (stderr,
"Error, sample->heat_flag shouldn't be %d here!\n",
sample->heat_flag[sample->backward_is][sample->backward_js]);
return NULL;
}
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 5.9 SOLAR BLITZ THERMAL_BW / EXP / Photon Direction ~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_EXP:
norm[0] = -1;
norm[1] = 0;
norm[2] = 0;
random_Lambertian_normal (&(p->dir), norm);
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 5.10 SOLAR BLITZ THERMAL_BW / EXN / Photon Direction ~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_EXN:
norm[0] = 1;
norm[1] = 0;
norm[2] = 0;
random_Lambertian_normal (&(p->dir), norm);
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 5.11 SOLAR BLITZ THERMAL_BW / EYP / Photon Direction ~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_EYP:
norm[0] = 0;
norm[1] = -1;
norm[2] = 0;
random_Lambertian_normal (&(p->dir), norm);
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 5.12 SOLAR BLITZ THERMAL_BW / EYN / Photon Direction ~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_EYN:
norm[0] = 0;
norm[1] = +1;
norm[2] = 0;
random_Lambertian_normal (&(p->dir), norm);
break;
default:
fprintf (stderr, "Error, unknown backward quantity %d\n", sample->backward);
return NULL;
}
return p;
}
/***********************************************************************************/
/* Function: generate_photon_backward_photon_direction_panorama @62_30i@ */
/* Description: */
/* */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void generate_photon_backward_photon_direction_panorama (sample_struct* sample,
photon_struct* p,
double phi,
double sza,
double cossza,
double sinsza,
double cosphi,
double sinphi)
{
double cossza_forward = 0.0, sinsza_forward = 0.0, cosphi0_forward = 0.0, sinphi0_forward = 0.0;
/* initialize direction */
/* and copy direction to "initial direction" struct */
if (sample->pan_distr_photons_over_pixel) {
phi = random_variation_above (phi, sample->pan_dphi);
/* Bug fix, the following two lines were missing. RPB */
cosphi = cosd (phi);
sinphi = sind (phi);
if ((sample->pan_circumsolar_var_red && sample->escape_eps_ddis_upf != 0.0)) {
/* Distribute photon directions according to
phase_max.
BE AWARE THAT dist_photon_direction_by_phasemax alters
sza, cossza and sinsza*/
dist_photon_direction_by_phasemax (p, sample, &sza, &cossza, &sinsza);
} else {
/* Distribute photon directions geometrically */
sza = random_theta_above (sza, sample->pan_dtheta);
cossza = cosd (sza);
sinsza = sind (sza);
}
} /* end if pan_distr_photons_over_pixel */
if (sample->pan_weight_with_cos)
p->weight1 = cossza;
if (sample->pan_alignment != MCPAN_ALIGNMENT_NONE && sample->align_theta != 180.0) {
/* Get the direction that points from the instrument to
the sun/alignment */
sinsza_forward = sind (sample->align_theta);
cossza_forward = cosd (sample->align_theta);
sinphi0_forward = sind (sample->align_phi);
cosphi0_forward = cosd (sample->align_phi);
/* First start the photon directly into the direction of
alignment */
init_direction (sinsza_forward, cossza_forward, sinphi0_forward, cosphi0_forward, &(p->dir));
cp_direction (&(p->dir00), &(p->dir));
/* Then modify direction according to given mu and phi */
new_direction (-cossza, 90. - phi + sample->add_phi_when_aligning, &(p->dir), 0.);
} else {
/* this is the standard case!!! */
init_direction (sinsza, cossza, sinphi, cosphi, &(p->dir));
init_direction (0, -1, 0, 0, &(p->dir00));
}
if (sample->sample_backward_sunshape) {
/* p->dir is pointing to the center of the sun modify
direction slightly to point to somewhere on the sun
disc directions are chosen according sun shape which
acts a pdf for the directions (Bernhard Reinhardt) */
cp_direction (&(sample->rad[0].dir), &(sample->rad_dir0));
limb_dark_lest_dir (&(sample->rad[0].dir), sample, &(p->lest_phi), &(p->lest_alpha));
}
}
/***********************************************************************************/
/* Function: generate_photon_backward_vertical_position @62_30i@ */
/* Description: */
/* */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int generate_photon_backward_vertical_position (sample_struct* sample,
atmosphere_struct* atmos,
photon_struct* p,
int* hit,
long int nphotons,
int* counter1) {
int kc_save = 0;
int oopscounter = 0;
switch (sample->backward) {
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 6.1 SOLAR BLITZ THERMAL_BW / ABS / Vertical Position ~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_ABS:
if (sample->sensorposition) {
fprintf (stderr, "Error, don't know how to calculate box-averaged absorption/emission/heating\n");
fprintf (stderr, "for a user-defined sensor position!\n");
return -1;
}
/* for absorption/emission/heating/actinic calculations, the backward photon starts in the layer, not at the level */
/* Make always sure to call set_photon_z() AFTER the new photon */
/* direction has been assigned because the start index and position */
/* might depend on direction */
/* the call to hunt_modified() might seem a bit weird - we need it, however, */
/* as we need the index of the layer above p->x[2] irrespective of the */
/* photon direction! This basically undoes the "p->kc--;" in set_photon_z() */
hunt_modified (atmos->Z, atmos->Nz, p->x[2], &(p->kc), hit);
/* Use absorption coefficient as photon weight */
if (atmos->kabs3D->threed[MCCAOTH_TOT][p->kc] >= 1)
p->weight = atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
else
p->weight = atmos->kabs->prof[MCCAOTH_TOT][p->kc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
/* finally, set the real photon position to a random location in the layer */
/* set_photon_z (p->x[2] + uvspec_random()*(atmos->Z[p->kc+1]-atmos->Z[p->kc]), atmos, p); */
set_photon_z (p->x[2] + uvspec_random() * (atmos->Z[p->kc + 1] - p->x[2]), atmos, p);
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 6.2 SOLAR BLITZ THERMAL_BW / EMIS / Vertical Position ~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_EMIS:
if (sample->sensorposition) {
fprintf (stderr, "Error, don't know how to calculate box-averaged absorption/emission/heating\n");
fprintf (stderr, "for a user-defined sensor position!\n");
return -1;
}
/* for absorption/emission/heating/actinic calculations, the backward photon starts in the layer, not at the level */
/* Make always sure to call set_photon_z() AFTER the new photon */
/* direction has been assigned because the start index and position */
/* might depend on direction */
/* the call to hunt_modified() might seem a bit weird - we need it, however, */
/* as we need the index of the layer above p->x[2] irrespective of the */
/* photon direction! This basically undoes the "p->kc--;" in set_photon_z() */
hunt_modified (atmos->Z, atmos->Nz, p->x[2], &(p->kc), hit);
/* Use absorption coefficient as photon weight */
if (atmos->kabs3D->threed[MCCAOTH_TOT][p->kc] >= 1)
p->weight = atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
else
p->weight = atmos->kabs->prof[MCCAOTH_TOT][p->kc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
/* finally, set the real photon position to a random location in the layer */
/* set_photon_z (p->x[2] + uvspec_random()*(atmos->Z[p->kc+1]-atmos->Z[p->kc]), atmos, p); */
set_photon_z (p->x[2] + uvspec_random() * (atmos->Z[p->kc + 1] - p->x[2]), atmos, p);
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~ 6.3 SOLAR BLITZ THERMAL_BW / HEAT / Vertical Position ~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_HEAT: /* **CK 2013.08.27 */
if (generate_photon_backward_vertical_position_heat (sample, atmos, p, hit, nphotons, counter1)) {
fprintf (stderr, "Error in generate_photon_backward_vertical_position_heat()!\n");
return -1;
}
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~ 6.4 SOLAR BLITZ THERMAL_BW / ACT / Vertical Position ~~~~~~~~~~~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_ACT:
if (sample->sensorposition) {
fprintf (stderr, "Error, don't know how to calculate box-averaged actinic flux\n");
fprintf (stderr, "for a user-defined sensor position!\n");
return -1;
}
/* for absorption/emission/heating/actinic calculations, the backward photon starts in the layer, not at the level */
/* Make always sure to call set_photon_z() AFTER the new photon */
/* direction has been assigned because the start index and position */
/* might depend on direction */
/* the call to hunt_modified() might seem a bit weird - we need it, however, */
/* as we need the index of the layer above p->x[2] irrespective of the */
/* photon direction! This basically undoes the "p->kc--;" in set_photon_z() */
hunt_modified (atmos->Z, atmos->Nz, p->x[2], &(p->kc), hit);
kc_save = p->kc;
/* for safety reasons we stay away from the upper and lower boundaries */
set_photon_z (p->x[2] + (MC_EPSILON + (1.0 - 2.0 * MC_EPSILON) * uvspec_random()) * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]),
atmos,
p);
oopscounter = 0;
do {
if (oopscounter > 0)
fprintf (stderr,
"Oops %d, need to throw the dice more than once because %.10f was too close to boundary\n",
oopscounter,
p->x[2]);
/* for safety reasons we stay away from the upper and lower boundaries */
set_photon_z (atmos->Z[kc_save] * (1 + MC_EPSILON) +
(atmos->Z[kc_save + 1] * (1 - MC_EPSILON) - atmos->Z[kc_save] * (1 + MC_EPSILON)) * uvspec_random(),
atmos,
p);
oopscounter++;
/* and we roll the dice until we are really away from the boundaries: careful: z coordinate = float! */
} while (kc_save != p->kc);
break;
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* -~~~~ 6.5 SOLAR BLITZ THERMAL_BW / horizontal fluxes / Vertical Position ~~~~~ */
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
case MCBACKWARD_EXP:
case MCBACKWARD_EXN:
case MCBACKWARD_EYP:
case MCBACKWARD_EYN:
if (p->kc == atmos->Nz - 1) {
fprintf (stderr, "Error, it doesn't make sense to calculate horizontal fluxes above TOA!\n");
return -1;
}
/* the call to hunt_modified() might seem a bit weird - we need it, however, */
/* as we need the index of the layer above p->x[2] irrespective of the */
/* photon direction! This basically undoes the "p->kc--;" in set_photon_z() */
hunt_modified (atmos->Z, atmos->Nz, p->x[2], &(p->kc), hit);
/* random location on vertical grid box face for horizontal irradiances */
if (!sample->sensorposition) {
kc_save = p->kc;
oopscounter = 0;
do {
if (oopscounter > 0)
fprintf (stderr,
"Oops %d, need to throw the dice more than once because %.10f was too close to boundary\n",
oopscounter,
p->x[2]);
/* for safety reasons we stay away from the upper and lower boundaries */
set_photon_z (atmos->Z[kc_save] * (1 + MC_EPSILON) +
(atmos->Z[kc_save + 1] * (1 - MC_EPSILON) - atmos->Z[kc_save] * (1 + MC_EPSILON)) * uvspec_random(),
atmos,
p);
oopscounter++;
/* and we roll the dice until we are really away from the boundaries: careful: z coordinate = float! */
} while (kc_save != p->kc);
}
break;
default:
break;
} /* end switch sample->backward */
return 0;
}
/***********************************************************************************/
/* Function: generate_photon_backward_vertical_position_heat @62_30i@ */
/* Description: */
/* */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int generate_photon_backward_vertical_position_heat (sample_struct* sample,
atmosphere_struct* atmos,
photon_struct* p,
int* hit,
long int nphotons,
int* counter1) {
int status = 0;
int kc_save = 0;
int oopscounter = 0;
switch (sample->heat_flag[sample->backward_is][sample->backward_js]) {
/* .............................................................................. */
/* ........ 6.3.1 SOLAR BLITZ THERMAL_BW / HEAT / DENET / Vertical Position ..... */
/* .............................................................................. */
case MCBACKWARD_HEAT_DENET:
if (sample->sensorposition) {
fprintf (stderr, "Error, don't know how to calculate box-averaged absorption/emission/heating\n");
fprintf (stderr, "for a user-defined sensor position!\n");
return -1;
}
hunt_modified (atmos->Z, atmos->Nz, p->x[2], &(p->kc), hit);
p->x[0] = ((double)sample->backward_is + uvspec_random()) * sample->delX;
p->x[1] = ((double)sample->backward_js + uvspec_random()) * sample->delY;
kc_save = p->kc;
do {
if (oopscounter > 0)
fprintf (stderr,
"Oops %d, need to throw the dice more than once because %.10f was too close to boundary\n",
oopscounter,
p->x[2]);
/* for safety reasons we stay away from the upper and lower boundaries */
set_photon_z (atmos->Z[kc_save] * (1 + MC_EPSILON) +
(atmos->Z[kc_save + 1] * (1 - MC_EPSILON) - atmos->Z[kc_save] * (1 + MC_EPSILON)) * uvspec_random(),
atmos,
p);
oopscounter++;
/* and we roll the dice until we are really away from the boundaries: careful: z coordinate = float! */
} while (kc_save != p->kc);
status = denet_weight (p, atmos, sample, nphotons, counter1);
if (status != 0) {
fprintf (stderr, "Error %d returned by denet_weight()\n", status);
return -1;
}
break;
/* .............................................................................. */
/* ......... 6.3.2 SOLAR BLITZ THERMAL_BW / HEAT / EMABS / Vertical Position .... */
/* .............................................................................. */
case MCBACKWARD_HEAT_EMABS:
if (sample->sensorposition) {
fprintf (stderr, "Error, don't know how to calculate box-averaged absorption/emission/heating\n");
fprintf (stderr, "for a user-defined sensor position!\n");
return -1;
}
/* for absorption/emission/heating/actinic calculations, the backward photon starts in the layer, not at the level */
/* Make always sure to call set_photon_z() AFTER the new photon */
/* direction has been assigned because the start index and position */
/* might depend on direction */
/* the call to hunt_modified() might seem a bit weird - we need it, however, */
/* as we need the index of the layer above p->x[2] irrespective of the */
/* photon direction! This basically undoes the "p->kc--;" in set_photon_z() */
hunt_modified (atmos->Z, atmos->Nz, p->x[2], &(p->kc), hit);
if (atmos->kabs3D->threed[MCCAOTH_TOT][p->kc] >= 1) { /* if 3D */
/* calculate weights */
p->weight = atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
p->weight_emis = -atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
} /* end 3D */
else { /* if 1D */
p->weight = atmos->kabs->prof[MCCAOTH_TOT][p->kc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
p->weight_emis = -atmos->kabs->prof[MCCAOTH_TOT][p->kc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
} /* end 1D */
/* finally, set the real photon position to a random location in the layer */
/* set_photon_z (p->x[2] + uvspec_random()*(atmos->Z[p->kc+1]-atmos->Z[p->kc]), atmos, p); */
set_photon_z (p->x[2] + uvspec_random() * (atmos->Z[p->kc + 1] - p->x[2]), atmos, p);
/* Calculate Emission at the emission-location of the photon - not analytically! */
p->weight_emis *=
(atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] +
(((p->x[2] - atmos->Z[p->kc]) / (atmos->Z[p->kc + 1] - atmos->Z[p->kc])) *
(atmos->Bplanck->prof[MCCAOTH_TOT][p->kc + 1][p->ic][p->jc] - atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc])));
break;
/* .............................................................................. */
/* ....... 6.3.3 SOLAR BLITZ THERMAL_BW / HEAT / EMABSOPT / Vertical Position ... */
/* .............................................................................. */
case MCBACKWARD_HEAT_EMABSOPT:
if (sample->sensorposition) {
fprintf (stderr, "Error, don't know how to calculate box-averaged absorption/emission/heating\n");
fprintf (stderr, "for a user-defined sensor position!\n");
return -1;
}
/* for absorption/emission/heating/actinic calculations, the backward photon starts in the layer, not at the level */
/* Make always sure to call set_photon_z() AFTER the new photon */
/* direction has been assigned because the start index and position */
/* might depend on direction */
/* the call to hunt_modified() might seem a bit weird - we need it, however, */
/* as we need the index of the layer above p->x[2] irrespective of the */
/* photon direction! This basically undoes the "p->kc--;" in set_photon_z() */
hunt_modified (atmos->Z, atmos->Nz, p->x[2], &(p->kc), hit);
if (atmos->kabs3D->threed[MCCAOTH_TOT][p->kc] >= 1) { /* if 3D */
/* calculate weights */
p->weight = atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
p->weight_emis = -atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
} /* end 3D */
else { /* if 1D */
p->weight = atmos->kabs->prof[MCCAOTH_TOT][p->kc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
p->weight_emis = -atmos->kabs->prof[MCCAOTH_TOT][p->kc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
} /* end 1D */
status = emabsopt_location (p, atmos, sample, nphotons);
if (status != 0) {
fprintf (stderr, "Error %d returned by emabsopt_location()\n", status);
return -1;
}
p->weight_emis *=
(atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] +
(((p->x[2] - atmos->Z[p->kc]) / (atmos->Z[p->kc + 1] - atmos->Z[p->kc])) *
(atmos->Bplanck->prof[MCCAOTH_TOT][p->kc + 1][p->ic][p->jc] - atmos->Bplanck->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc])));
break;
default:
fprintf (stderr, "No Method used for setup of thermal backward heating rates!!!\n");
return -1;
}
return 0;
}
/***********************************************************************************/
/* Function: destroy_photon @62_30i@ */
/* Description: */
/* Free memory of a photon_struct. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void destroy_photon (photon_struct* p, int n_caoth) {
int i = 0;
if (p->pdir != NULL)
free (p->pdir);
if (p->stokes != NULL) {
free (p->stokes0);
free (p->stokes);
}
#if HAVE_LIDAR
destroy_photon_lidar_part (p, n_caoth);
#endif
if (p->phamat != NULL) {
for (i = 0; i < 4; i++)
free (p->phamat[i]);
free (p->phamat);
}
/* ALIS or concentration importance sampling */
if (p->pathlength_per_layer != NULL) {
free (p->pathlength_per_layer);
free (p->q_spectral);
free (p->q2_spectral);
free (p->q_albedo_spectral);
free (p->q_concentration);
free (p->q2_concentration);
/* free(p->dtauabs_spectral); */
}
if (p->pathlength_per_box != NULL) {
ASCII_free_double_3D (p->pathlength_per_box, p->Nx_boxairmass, p->Ny_boxairmass);
}
if (p->q_jacobian_sca != NULL)
ASCII_free_double_4D (p->q_jacobian_sca, n_caoth, p->Nx_boxairmass, p->Ny_boxairmass);
free (p->tocirco);
free (p);
}
/***********************************************************************************/
/* Function: slt2hrz @62_30i@ */
/* Description: */
/* Calculate the conversion factor for irradiance on a slant surface to */
/* irradiance on a horizonal surface. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static double slt2hrz (elevation_struct* elev, photon_struct* p, int surfaceparallel, int incoming) {
double slant2horz = 1;
int ie = 0, je = 0;
double cophi = 0, coalp = 0;
double norm[3] = {0, 0, 0};
if (elev->elev2D) {
/* phi: incidence angle on slant surface */
/* theta: incidence angle on horizontal surface */
/* alpha: angle between slant and horizontal surface */
/* elevation upward normal vector */
elev_coord_normal_vector (p, elev, norm);
cophi = (norm[0] * p->dir.dx[0] + norm[1] * p->dir.dx[1] + norm[2] * p->dir.dx[2]);
if (incoming)
cophi = -cophi;
/* and finally, the angle between the slant surface and the horizontal */
coalp = norm[2];
if (cophi <= 0) {
elev_coord (p, elev, &ie, &je);
fprintf (stderr, "OUCH!\n");
fprintf (stderr, "%d %d %g %g %g %g\n", ie, je, cophi, p->x[0], p->x[1], p->x[2]);
slant2horz = 0; /* don't count photon */
return -1;
} else
slant2horz = coalp * p->dir.cotheta / cophi;
/* much simpler if surface-parallel instead of horizontal */
if (surfaceparallel) /* BMSURFACEPARALLEL */
slant2horz = 1.0;
/* slant2horz = coalp; */
}
return slant2horz;
}
/***********************************************************************************/
/* Function: area_average @62_30i@ */
/* Description: */
/* Calculate area averages of irradiance and actinic flux. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static void area_average (radiation_field* res,
double*** back,
int Nx,
int Ny,
int islower,
int isupper,
int jslower,
int jsupper,
int isstep,
int jsstep,
int* ndir,
int* ndn,
int* nup,
float* edir,
float* edn,
float* eup,
float* fdir,
float* fdn,
float* fup,
int backward,
double** surface_area,
int** surface_area_counter,
int elev2D,
int surfaceparallel) {
int is = 0, js = 0, counter = 0;
double edir_d = 0, edn_d = 0, eup_d = 0;
double fdir_d = 0, fdn_d = 0, fup_d = 0;
double normalization = 0;
double factor = 0;
if (islower < 0)
islower = 0;
if (isupper < 0)
isupper = Nx - 1;
if (jslower < 0)
jslower = 0;
if (jsupper < 0)
jsupper = Ny - 1;
if (isstep <= 0)
isstep = 1;
if (jsstep <= 0)
jsstep = 1;
if (elev2D && surfaceparallel) {
for (is = islower; is <= isupper; is += isstep)
for (js = jslower; js <= jsupper; js += jsstep) {
factor += surface_area[is][js];
counter++;
}
factor /= counter;
} else
factor = 1.0;
if (backward)
normalization = (double)(((isupper - islower) / isstep + 1) * ((jsupper - jslower) / jsstep + 1)) * factor;
else
normalization = (double)(Nx * Ny) * factor;
/* reset result */
*ndir = 0;
*ndn = 0;
*nup = 0;
*edir = 0;
*edn = 0;
*eup = 0;
*fdir = 0;
*fdn = 0;
*fup = 0;
/* initialize counter to NAN if backward; */
/* in the forward case we are sure that we will get contributions */
/* to all quantities while backward we only get one quantitiy */
/* while the others should be NAN */
if (backward != MCBACKWARD_NONE) {
edir_d = 0.0 / 0.0;
edn_d = 0.0 / 0.0;
eup_d = 0.0 / 0.0;
fdir_d = 0.0 / 0.0;
fdn_d = 0.0 / 0.0;
fup_d = 0.0 / 0.0;
}
switch (backward) {
case MCBACKWARD_NONE:
break;
case MCBACKWARD_EDIR:
edir_d = 0.0;
break;
case MCBACKWARD_EDN:
case MCBACKWARD_EDNPV:
case MCBACKWARD_EXN:
case MCBACKWARD_EYN:
edn_d = 0.0;
break;
case MCBACKWARD_EUP:
case MCBACKWARD_EXP:
case MCBACKWARD_EYP:
eup_d = 0.0;
break;
case MCBACKWARD_FDIR:
fdir_d = 0.0;
break;
case MCBACKWARD_FDN:
fdn_d = 0.0;
break;
case MCBACKWARD_FUP:
fup_d = 0.0;
break;
case MCBACKWARD_EGLOB:
case MCBACKWARD_ABS:
case MCBACKWARD_ACT:
case MCBACKWARD_EMIS:
case MCBACKWARD_HEAT:
/* nothing to do */
break;
case MCBACKWARD_RADIANCE:
break;
default:
fprintf (stderr, "Error, unknown backward quantity %d in area_average()\n", backward);
return;
}
/* need to calculate the sum in double precision because */
/* the results may cover a high dynamic range */
for (is = 0; is < Nx; is++) {
for (js = 0; js < Ny; js++) {
*ndir += res->ndir[is][js];
*ndn += res->ndn[is][js];
*nup += res->nup[is][js];
/* weight with surface area of each pixel */
if (elev2D && surfaceparallel) {
if (is >= islower && is <= isupper && js >= jslower && js <= jsupper)
factor = surface_area[is][js];
else
factor = 1.0;
} else
factor = 1.0;
if (!backward) {
edir_d += res->edir[is][js] * factor;
edn_d += res->edn[is][js] * factor;
eup_d += res->eup[is][js] * factor;
fdir_d += res->fdir[is][js] * factor;
fdn_d += res->fdn[is][js] * factor;
fup_d += res->fup[is][js] * factor;
} else {
if (is >= islower && is <= isupper && js >= jslower && js <= jsupper) {
switch (backward) {
case MCBACKWARD_NONE:
case MCBACKWARD_RADIANCE:
break;
case MCBACKWARD_EDIR:
edir_d += back[is][js][0] * factor;
break;
case MCBACKWARD_EDN:
case MCBACKWARD_EDNPV:
case MCBACKWARD_EXN:
case MCBACKWARD_EYN:
edn_d += back[is][js][0] * factor;
break;
case MCBACKWARD_EUP:
case MCBACKWARD_EXP:
case MCBACKWARD_EYP:
eup_d += back[is][js][0] * factor;
break;
case MCBACKWARD_FDIR:
fdir_d += back[is][js][0] * factor;
break;
case MCBACKWARD_FDN:
fdn_d += back[is][js][0] * factor;
break;
case MCBACKWARD_FUP:
fup_d += back[is][js][0] * factor;
break;
case MCBACKWARD_EGLOB:
case MCBACKWARD_ABS:
case MCBACKWARD_ACT:
case MCBACKWARD_HEAT:
case MCBACKWARD_EMIS:
/* nothing to do */
break;
default:
fprintf (stderr, "Error, unknown backward quantity %d in area_average()\n", backward);
return;
}
}
}
}
}
/* UVSPEC wants averaged intensity, not actinic flux */
fdir_d /= (4.0 * PI);
fdn_d /= (4.0 * PI);
fup_d /= (4.0 * PI);
*edir = (float)(edir_d / normalization);
*edn = (float)(edn_d / normalization);
*eup = (float)(eup_d / normalization);
*fdir = (float)(fdir_d / normalization);
*fdn = (float)(fdn_d / normalization);
*fup = (float)(fup_d / normalization);
}
static int summarize_result_triangular_srfc (const int Nx,
const int Ny,
const double delX,
const double delY,
const double factor,
const double dmcphotons,
const t_triangular_surface* srfc,
t_triangle_radiation_field* result) {
const int ldebug = 0;
double global_area = 0;
for (size_t i = 0; i < srfc->N_triangles; ++i) {
// indices of vertices of triangle face
const size_t vA = srfc->triangles[i][0];
const size_t vB = srfc->triangles[i][1];
const size_t vC = srfc->triangles[i][2];
// coordinates of vertices
const double A[3] = {srfc->vertices[vA][0], srfc->vertices[vA][1], srfc->vertices[vA][2]};
const double B[3] = {srfc->vertices[vB][0], srfc->vertices[vB][1], srfc->vertices[vB][2]};
const double C[3] = {srfc->vertices[vC][0], srfc->vertices[vC][1], srfc->vertices[vC][2]};
const double area = triangle_area_by_vertices (A, B, C);
global_area += area;
result->edir[i] /= area;
result->edn[i] /= area;
result->eup[i] /= area;
}
const double sampling_area_factor = factor * delX * delY;
const double normalization = sampling_area_factor / dmcphotons;
for (size_t i = 0; i < srfc->N_triangles; ++i) {
result->edir[i] *= normalization;
result->edn[i] *= normalization;
result->eup[i] *= normalization;
}
if (ldebug) {
for (size_t i = 0; i < srfc->N_triangles; ++i) {
fprintf (stderr,
"Count on %lu direct %lu diffuse %lu %lu => %f %f %f "
" (factor %f, sample_area %f, photons %f normalization %f)\n",
i,
result->ndir[i],
result->ndn[i],
result->nup[i],
result->edir[i],
result->edn[i],
result->eup[i],
factor,
sampling_area_factor,
dmcphotons,
normalization);
}
}
return 0;
}
/***********************************************************************************/
/* Function: summarize_result @62_30i@ */
/* Description: */
/* Summarize result, create result arrays, write ASCII output files. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int summarize_result (result_struct* result,
sample_struct* sample,
atmosphere_struct* atmos,
albedo_struct* albedo,
t_triangular_surface* triangular_surface,
int source,
long int mcphotons,
int mcsimulations,
double sza,
int absorption,
int write_files,
int write_output_as_netcdf,
int tenstream,
int nca, /* Carolin Klinger 2019 */
char* basename,
float* rfldir,
float* rfldn,
float* flup,
float* uavgso,
float* uavgdn,
float* uavgup,
float*** rfldir3d,
float*** rfldn3d,
float*** flup3d,
float***** fl3d_is,
float*** uavgso3d,
float*** uavgdn3d,
float*** uavgup3d,
float**** radiance3d,
float*** absback3d,
float*** abs3d,
float****** radiance3d_is,
float****** jacobian,
float*** rfldir3d_var,
float*** rfldn3d_var,
float*** flup3d_var,
float*** uavgso3d_var,
float*** uavgdn3d_var,
float*** uavgup3d_var,
float**** radiance3d_var,
float*** absback3d_var,
float*** abs3d_var,
int escape,
int elev2D,
double wavelength,
int quiet) {
int lu = 0, nu = 0;
double incident = 0;
int * ndir = NULL, *ndn = NULL, *nup = NULL;
int isp = 0; /* caoth index */
int kc = 0; /* z coordinate */
/* XXXumu_2d??? CHECK!!! */
int islower = 0, jslower = 0, isupper = 0, jsupper = 0, isstep = 0, jsstep = 0;
int lu3D = 0;
char specradfilename[FILENAME_MAX] = "";
double factor = 0.;
double dmcphotons = (double)mcphotons;
char flxext[FILENAME_MAX] = "", flxext2[FILENAME_MAX] = "";
char radext[FILENAME_MAX] = "", radext2[FILENAME_MAX] = "";
char rplext[FILENAME_MAX] = "", rplext2[FILENAME_MAX] = "";
char absext[FILENAME_MAX] = "", absext2[FILENAME_MAX] = "";
char bacext[FILENAME_MAX] = "", bacext2[FILENAME_MAX] = "";
char bacjacext[FILENAME_MAX] = "", bacjacext2[FILENAME_MAX] = "";
char picext[FILENAME_MAX] = "";
char extension[FILENAME_MAX] = "", extension2[FILENAME_MAX] = "";
if (tenstream)
return 0;
if (nca)
return 0;
/* ======================= IMPORTANT ======================== */
/* If you want to implement a new output method please put it */
/* into a new function and use this function to call it! */
/* Do not directly add your method into this function! */
/* ========================================================== */
/* ====== 1. Lidar Output, special, needs nothing of the rest! */
if (sample->LidarLocEst) {
#if HAVE_LIDAR
int status = 0;
factor = (double)mcsimulations / dmcphotons;
if ((status = summarize_result_lidar (sample, atmos, result, basename, write_files, write_output_as_netcdf, factor))) {
fprintf (stderr, "Error, summarize_result_lidar_part returned status %d\n", status);
return -1;
}
#endif
}
/* not lidar, else brace goes until end of function! */
else {
/* ====== 2. Preparing everything */
/* allocate memory for photon counters */
ndir = calloc (atmos->Nz + 1, sizeof (int));
ndn = calloc (atmos->Nz + 1, sizeof (int));
nup = calloc (atmos->Nz + 1, sizeof (int));
/* extension for absorption/heating/actinic etc. file */
switch (absorption) {
case MCFORWARD_ABS_ACTINIC:
strcpy (extension, ".act");
strcpy (extension2, ".act.std");
break;
case MCFORWARD_ABS_ABSORPTION:
case MCFORWARD_ABS_EMISSION:
case MCFORWARD_ABS_HEATING:
case MCFORWARD_ABS_NONE:
strcpy (extension, ".abs");
strcpy (extension2, ".abs.std");
break;
default:
fprintf (stderr, "Error, unknown absorption type %d\n", absorption);
return -1;
}
switch (source) {
case MCSRC_THERMAL_ATMOSPHERE:
strcpy (radext, ".atm.rad");
strcpy (rplext, ".atm.rpl");
strcpy (flxext, ".atm.flx");
strcpy (absext, ".atm");
strcat (absext, extension);
strcpy (radext2, ".atm.rad.std");
strcpy (rplext2, ".atm.rpl.std");
strcpy (flxext2, ".atm.flx.std");
strcpy (absext2, ".atm");
strcat (absext2, extension2);
break;
case MCSRC_THERMAL_SURFACE:
strcpy (radext, ".sur.rad");
strcpy (rplext, ".sur.rpl");
strcpy (flxext, ".sur.flx");
strcpy (absext, ".sur");
strcat (absext, extension);
strcpy (radext2, ".sur.rad.std");
strcpy (rplext2, ".sur.rpl.std");
strcpy (flxext2, ".sur.flx.std");
strcpy (absext2, ".sur");
strcat (absext2, extension2);
break;
case MCSRC_SOLAR:
case MCSRC_BLITZ:
case MCSRC_THERMAL_BACKWARD: /*TZ bt ...*/
strcpy (radext, ".rad");
strcpy (rplext, ".rpl");
strcpy (flxext, ".flx");
strcpy (absext, extension);
strcpy (radext2, ".rad.std");
strcpy (rplext2, ".rpl.std");
strcpy (flxext2, ".flx.std");
strcpy (absext2, extension2);
/* special treatment for backward: here we want the TOA radiance */
/* in a special file *.bac which contains the contribution of each */
/* TOA pixel to the irradiance at zout */
switch (sample->backward) {
case MCBACKWARD_NONE:
break;
case MCBACKWARD_EDIR:
case MCBACKWARD_EGLOB:
case MCBACKWARD_EDN:
case MCBACKWARD_EDNPV:
case MCBACKWARD_EUP:
case MCBACKWARD_EXP:
case MCBACKWARD_EXN:
case MCBACKWARD_EYP:
case MCBACKWARD_EYN:
case MCBACKWARD_FDIR:
case MCBACKWARD_FDN:
case MCBACKWARD_FUP:
case MCBACKWARD_ABS:
case MCBACKWARD_EMIS:
case MCBACKWARD_HEAT:
case MCBACKWARD_ACT:
strcpy (bacext, ".flx");
strcpy (bacext2, ".flx.std");
sprintf (radext, ".wvl_%.3f.bac", wavelength);
sprintf (radext2, ".wvl_%.3f.bac.std", wavelength);
if (sample->jacobian || sample->jacobian3D) {
strcpy (bacjacext, ".jac");
strcpy (bacjacext2, ".jac.std");
}
/* strcpy (radext, ".bac"); */
/* strcpy (radext2, ".bac.std"); */
break;
case MCBACKWARD_RADIANCE:
strcpy (bacext, ".rad");
strcpy (bacext2, ".rad.std");
strcpy (picext, ".ppm");
sprintf (radext, ".wvl_%.3f.bac", wavelength);
sprintf (radext2, ".wvl_%.3f.bac.std", wavelength);
/* strcpy (radext, ".bac"); */
/* strcpy (radext2, ".bac.std"); */
if (sample->jacobian || sample->jacobian3D) {
strcpy (bacjacext, ".jac");
strcpy (bacjacext2, ".jac.std");
}
break;
default:
fprintf (stderr, "Error, unknown backward quantity %d\n", sample->backward);
return -1;
}
break;
case MCSRC_LIDAR:
break;
default:
fprintf (stderr, "Error, unknown or unimplemented MC source type\n");
return -1;
}
if (sample->spectral_is || sample->concentration_is) {
strcpy (specradfilename, basename);
strcat (specradfilename, ".is.spc");
}
/* "absolute calibration" */
switch (source) {
case MCSRC_THERMAL_ATMOSPHERE:
/* normalize to average column emission */
if (absorption == MCFORWARD_ABS_EMISSION)
incident = 1.0 / (4.0 * PI); /* integrate radiance over 4 pi */
else
incident = 1.0 / atmos->Watm;
break;
case MCSRC_THERMAL_BACKWARD: /*TZ bt ...*/
if (absorption == MCFORWARD_ABS_EMISSION)
incident = 1.0 / (4.0 * PI); /* integrate radiance over 4 pi */
else
incident = 1.0;
break; /*...TZ bt*/
case MCSRC_THERMAL_SURFACE:
/* normalize to average surface emission */
incident = 1.0 / albedo->Wsurf;
break;
case MCSRC_SOLAR:
case MCSRC_BLITZ:
/* correct for slant incidence at TOA or BOA; */
/* use fabs() because cosine might be negative for backward; */
/* the factor is the same for forward and backward because */
/* this is the cosine of the solar zenith angle in the */
/* definition of the transmittance outside mystic() */
incident = fabs (1.0 / cosd (sample->forward_sza));
break;
case MCSRC_LIDAR:
break;
default:
fprintf (stderr, "Error, unknown or unimplemented MC source type\n");
return -1;
}
if (sample->backward || source == MCSRC_BLITZ)
factor = 1.0 / incident;
else
factor = (double)sample->Nx * (double)sample->Ny / incident;
/* Air Mass Factors! */
if (sample->boxairmass || sample->boxairmass3D) {
if (summarize_result_boxairmass (sample, atmos, result, dmcphotons, basename)) {
fprintf (stderr, "Error in summarize_result_boxairmass().\n");
return -1;
}
}
/* ======================================== Forward ===================================================== */
/* ====== 4. Forward Surface Irradiance, Radiance, RPL! */
/* (RPL = Radial Path Length) */
if (!sample->backward) {
if (summarize_result_forward_surface (sample,
atmos,
result,
basename,
dmcphotons,
factor,
incident,
write_files,
elev2D,
flxext,
flxext2,
radext,
radext2,
rplext,
rplext2)) {
fprintf (stderr, "Error in summarize_result_forward.\n");
return -1;
}
}
/* ======================================== Backward ==================================================== */
else {
if (sample->Nd < 1) {
fprintf (stderr, "Fatal error, need at least one radiance direction in backward mode!\n");
fprintf (stderr, "Please inform the programmer!\n");
return -1;
}
if (sample->backward_writeallpixels) {
islower = 0;
isupper = sample->Nx - 1;
jslower = 0;
jsupper = sample->Ny - 1;
isstep = 1;
jsstep = 1;
} else {
islower = sample->backward_islower;
isupper = sample->backward_isupper;
jslower = sample->backward_jslower;
jsupper = sample->backward_jsupper;
isstep = sample->backward_isstep;
jsstep = sample->backward_jsstep;
}
if (sample->backward != MCBACKWARD_RADIANCE) {
/* ====== 5. Backward Irradiance! */
if (summarize_result_backward_irradiance (sample,
atmos,
result,
basename,
specradfilename,
bacext,
bacext2,
bacjacext,
bacjacext2,
dmcphotons,
factor,
wavelength,
mcsimulations,
write_files,
elev2D,
islower,
isupper,
jslower,
jsupper,
isstep,
jsstep)) {
fprintf (stderr, "Error in summarize_result_backward_irradiance.\n");
return -1;
}
} else {
/* ====== 6. Cloudprop (backward)! */
#ifdef CLDPRP
if (sample->cldprp) {
summarize_result_cldprp (sample, atmos, result, basename, elev2D, islower, isupper, jslower, jsupper, isstep, jsstep);
}
#endif
/* ====== 7. Backward Radiance! */
if (summarize_result_backward_radiance (sample,
atmos,
result,
basename,
specradfilename,
bacext,
bacext2,
picext,
bacjacext,
bacjacext2,
dmcphotons,
factor,
sza,
source,
mcsimulations,
write_files,
elev2D,
islower,
isupper,
jslower,
jsupper,
isstep,
jsstep)) {
fprintf (stderr, "Error in summarize_result_backward_radiance.\n");
return -1;
}
}
}
/* photons at altitude levels */
for (kc = 0; kc <= atmos->Nz; kc++) {
if (sample->sample[kc]) {
/* this loop is needed in forward mode; in backward mode it is only */
/* needed if the user wants the .bac files (mc_writeback) */
/* ======================================== Forward ===================================================== */
/* ====== 8. Forward Altitude Irradiance! */
if (!sample->backward) {
if (summarize_result_forward_altitude_irradiance (sample,
atmos,
result,
basename,
dmcphotons,
factor,
write_files,
kc,
flxext,
flxext2)) {
fprintf (stderr, "Error in summarize_result_forward_altitude_irradiance.\n");
return -1;
}
}
/* ======================================== Forward (& Backward) ======================================== */
/* ====== 9. Forward Altitude Radiance (Backward: bac files)! */
if (!sample->backward || (sample->backward && sample->backward_writeback)) {
if (summarize_result_forward_altitude_radiance (sample,
atmos,
result,
basename,
specradfilename,
radext,
radext2,
dmcphotons,
factor,
write_files,
kc)) {
fprintf (stderr, "Error in summarize_result_fw_alt_rad().\n");
return -1;
}
}
/* ======================================== Forward & Backward ========================================== */
/* ====== 10. Altitude RPL! */
if (summarize_result_altitude_rpl (sample,
atmos,
result,
basename,
rplext,
rplext2,
dmcphotons,
incident,
write_files,
kc)) {
fprintf (stderr, "Error in summarize_result_alt_rpl().\n");
return -1;
}
}
}
/* ======================================== Forward & Backward ========================================== */
/* ====== 11. Passback3D! */
lu3D = 0; /* counter for user levels */
if (summarize_result_passback3D (sample,
atmos,
result,
rfldir3d,
rfldn3d,
flup3d,
fl3d_is,
uavgso3d,
uavgdn3d,
uavgup3d,
radiance3d,
absback3d,
rfldir3d_var,
rfldn3d_var,
flup3d_var,
uavgso3d_var,
uavgdn3d_var,
uavgup3d_var,
radiance3d_var,
absback3d_var,
abs3d_var,
radiance3d_is,
jacobian,
escape,
islower,
isupper,
jslower,
jsupper,
isstep,
jsstep,
&lu3D)) {
fprintf (stderr, "Error in summarize_result_passback3D.\n");
return -1;
}
/* ====== 12. Absorbed Energy! */
if (absorption != 0) {
if (summarize_result_absorption (sample,
atmos,
result,
abs3d,
abs3d_var,
basename,
absext,
absext2,
dmcphotons,
incident,
write_files,
absorption)) {
fprintf (stderr, "Error in summarize_result_absorption().\n");
return -1;
}
}
// Handle results on triangle surfaces
const int ierr = summarize_result_triangular_srfc (sample->Nx,
sample->Ny,
sample->delX,
sample->delX,
factor,
dmcphotons,
triangular_surface,
result->triangle_results);
CHKERR (ierr);
/* ====== 13. Information for the user! */
if (!quiet) {
fprintf (stderr, "\n\n");
fprintf (stderr, "lower boundary = %g m\n", atmos->Z[0]);
fprintf (stderr, "upper boundary = %g m\n", atmos->Z[atmos->Nz]);
fprintf (stderr, "number of photons = %ld\n", mcphotons);
fprintf (stderr, "solar zenith angle = %g\n", sample->forward_sza);
fprintf (stderr, " \n");
for (isp = 1; isp <= atmos->n_caoth; isp++)
fprintf (stderr, "total 1D %10s scattering OD = %g\n", atmos->caoth_name[isp], atmos->tscatot[isp]);
fprintf (stderr, "total scattering OD = %g\n", atmos->tscatot[MCCAOTH_TOT]);
fprintf (stderr, " \n");
for (isp = 1; isp <= atmos->n_caoth; isp++)
fprintf (stderr, "total 1D %10s absorption OD = %g\n", atmos->caoth_name[isp], atmos->tabstot[isp]);
fprintf (stderr, "total absorption OD = %g\n", atmos->tabstot[MCCAOTH_TOT]);
}
lu = 0;
if (sample->surface) {
area_average (result->surf,
result->back,
sample->Nx,
sample->Ny,
sample->backward_islower,
sample->backward_isupper,
sample->backward_jslower,
sample->backward_jsupper,
sample->backward_isstep,
sample->backward_jsstep,
&(ndir[0]),
&(ndn[0]),
&(nup[0]),
&(rfldir[0]),
&(rfldn[0]),
&(flup[0]),
&(uavgso[0]),
&(uavgdn[0]),
&(uavgup[0]),
sample->backward,
sample->surface_area,
sample->surface_area_counter,
elev2D,
sample->surfaceparallel);
lu++;
}
for (kc = 0; kc <= atmos->Nz; kc++) {
if (sample->sample[kc]) {
area_average (result->alt[kc],
result->back,
sample->Nx,
sample->Ny,
sample->backward_islower,
sample->backward_isupper,
sample->backward_jslower,
sample->backward_jsupper,
sample->backward_isstep,
sample->backward_jsstep,
&(ndir[lu]),
&(ndn[lu]),
&(nup[lu]),
&(rfldir[lu]),
&(rfldn[lu]),
&(flup[lu]),
&(uavgso[lu]),
&(uavgdn[lu]),
&(uavgup[lu]),
sample->backward,
sample->surface_area,
sample->surface_area_counter,
elev2D,
sample->surfaceparallel);
lu++;
}
}
nu = lu;
if (!quiet) {
fprintf (stderr, "\ntotal number of (unweighted) photons:\n");
fprintf (stderr, " user level, direct, diffuse down, diffuse up\n");
for (lu = 0; lu < nu; lu++)
fprintf (stderr, " %3d %12d %12d %12d\n", lu, ndir[lu], ndn[lu], nup[lu]);
fprintf (stderr, "\n");
}
free (ndir);
free (ndn);
free (nup);
if (!quiet)
fprintf (stderr, " ... passing 3D fields for %d user levels back to uvspec()\n", lu3D);
} /* End brace else-Lidar-loop */
return 0;
}
/***********************************************************************************/
/* Function: print_sr_error_message @62_30i@ */
/* Description: Prints out certain error messages for summarize_result */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void print_sr_error_message (char* filename) {
perror (NULL);
fprintf (stderr, "errno = %d\n", errno);
fprintf (stderr, "Error opening %s for writing\n", filename);
}
/***********************************************************************************/
/* Function: summarize_result_forward_surface @62_30i@ */
/* Description: Outputs forward surface quantities */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int summarize_result_forward_surface (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
double dmcphotons,
double factor,
double incident,
int write_files,
int elev2D,
char* flxext,
char* flxext2,
char* radext,
char* radext2,
char* rplext,
char* rplext2) {
int is = 0, js = 0; /* sampling grid coordinates */
int id = 0; /* radiance index */
int ip = 0; /* stokes component index */
int iv = 0; /* wavelength index for spectral calculations with importance sampling */
int ir = 0, it = 0;
int ic = 0; /* atmospheric grid coordinates - why no jc in most functions? */
double var, rplfactor, areafactor, avg;
double normomega = 0;
FILE * histfile = NULL, *histfile2 = NULL;
FILE * histradfile = NULL, *histradfile2 = NULL;
FILE * histrplfile = NULL, *histrplfile2 = NULL;
char histfilename[FILENAME_MAX] = "", histfilename2[FILENAME_MAX] = "";
char histradfilename[FILENAME_MAX] = "", histradfilename2[FILENAME_MAX] = "";
char histrplfilename[FILENAME_MAX] = "", histrplfilename2[FILENAME_MAX] = "";
strcpy (histfilename, basename);
strcpy (histfilename2, basename);
strcpy (histradfilename, basename);
strcpy (histradfilename2, basename);
strcpy (histrplfilename, basename);
strcpy (histrplfilename2, basename);
strcat (histfilename, flxext);
strcat (histfilename2, flxext2);
strcat (histradfilename, radext);
strcat (histradfilename2, radext2);
strcat (histrplfilename, rplext);
strcat (histrplfilename2, rplext2);
if (write_files) {
/* open histogram file */
if ((histfile = fopen (histfilename, "w")) == NULL) {
print_sr_error_message (histfilename);
return -1;
}
/* open radiance histogram file */
if (sample->Nd > 0) {
if ((histradfile = fopen (histradfilename, "w")) == NULL) {
print_sr_error_message (histradfilename);
return -1;
}
}
/* open radiance/pathlength histogram file */
if (sample->Nr > 0 && sample->Nt > 0 && sample->Nd > 0) {
if ((histrplfile = fopen (histrplfilename, "w")) == NULL) {
print_sr_error_message (histrplfilename);
return -1;
}
}
if (sample->std) { /* standard deviations */
/* open histogram file */
if ((histfile2 = fopen (histfilename2, "w")) == NULL) {
print_sr_error_message (histfilename2);
return -1;
}
/* open radiance histogram file */
if (sample->Nd > 0) {
if ((histradfile2 = fopen (histradfilename2, "w")) == NULL) {
print_sr_error_message (histradfilename2);
return -1;
}
}
/* open radiance/pathlength histogram file */
if (sample->Nr > 0 && sample->Nt > 0 && sample->Nd > 0) {
if ((histrplfile2 = fopen (histrplfilename2, "w")) == NULL) {
print_sr_error_message (histrplfilename2);
return -1;
}
}
}
}
// =========================== Surface Irradiance
for (is = 0; is < sample->Nx; is++) {
for (js = 0; js < sample->Ny; js++) {
if (elev2D && sample->surfaceparallel)
areafactor = 1.0 / sample->surface_area[is][js];
else
areafactor = 1.0;
/* calculate average */
result->surf->edir[is][js] /= dmcphotons;
result->surf->edn[is][js] /= dmcphotons;
result->surf->eup[is][js] /= dmcphotons;
result->surf->fdir[is][js] /= dmcphotons;
result->surf->fdn[is][js] /= dmcphotons;
result->surf->fup[is][js] /= dmcphotons;
/* calculate standard deviation from second moment */
if (sample->std) {
avg = result->surf->edir[is][js];
var = result->surf->edir2[is][js] / dmcphotons;
result->surf->edir2[is][js] = std_noisy (var, avg, dmcphotons);
avg = result->surf->edn[is][js];
var = result->surf->edn2[is][js] / dmcphotons;
result->surf->edn2[is][js] = std_noisy (var, avg, dmcphotons);
avg = result->surf->eup[is][js];
var = result->surf->eup2[is][js] / dmcphotons;
result->surf->eup2[is][js] = std_noisy (var, avg, dmcphotons);
avg = result->surf->fdir[is][js];
var = result->surf->fdir2[is][js] / dmcphotons;
result->surf->fdir2[is][js] = std_noisy (var, avg, dmcphotons);
avg = result->surf->fdn[is][js];
var = result->surf->fdn2[is][js] / dmcphotons;
result->surf->fdn2[is][js] = std_noisy (var, avg, dmcphotons);
avg = result->surf->fup[is][js];
var = result->surf->fup2[is][js] / dmcphotons;
result->surf->fup2[is][js] = std_noisy (var, avg, dmcphotons);
result->surf->edir2[is][js] *= factor * areafactor;
result->surf->edn2[is][js] *= factor * areafactor;
result->surf->eup2[is][js] *= factor * areafactor;
result->surf->fdir2[is][js] *= factor * areafactor;
result->surf->fdn2[is][js] *= factor * areafactor;
result->surf->fup2[is][js] *= factor * areafactor;
}
result->surf->edir[is][js] *= factor * areafactor;
result->surf->edn[is][js] *= factor * areafactor;
result->surf->eup[is][js] *= factor * areafactor;
result->surf->fdir[is][js] *= factor * areafactor;
result->surf->fdn[is][js] *= factor * areafactor;
result->surf->fup[is][js] *= factor * areafactor;
if (write_files) {
fprintf (histfile,
"%g %g %.6e %.6e %.6e %.6e %.6e %.6e\n",
((double)is + 0.5) * sample->delX,
((double)js + 0.5) * sample->delY,
result->surf->edir[is][js],
result->surf->edn[is][js],
result->surf->eup[is][js],
result->surf->fdir[is][js],
result->surf->fdn[is][js],
result->surf->fup[is][js]);
if (sample->std)
fprintf (histfile2,
"%g %g %.6e %.6e %.6e %.6e %.6e %.6e\n",
((double)is + 0.5) * sample->delX,
((double)js + 0.5) * sample->delY,
result->surf->edir2[is][js],
result->surf->edn2[is][js],
result->surf->eup2[is][js],
result->surf->fdir2[is][js],
result->surf->fdn2[is][js],
result->surf->fup2[is][js]);
}
// =========================== Surface Radiance
for (id = 0; id < sample->Nd; id++) {
for (ip = 0; ip < sample->nstokes; ip++) {
/* calculate average */
result->surf->raddir[id][is][js][ip] /= dmcphotons;
result->surf->raddif[id][is][js][ip] /= dmcphotons;
result->surf->radesc[id][is][js][ip] /= dmcphotons;
/* calculate standard deviation from second moment */
if (sample->std) {
avg = result->surf->raddir[id][is][js][ip];
var = result->surf->raddir2[id][is][js][ip] / dmcphotons;
result->surf->raddir2[id][is][js][ip] = std_noisy (var, avg, dmcphotons);
avg = result->surf->raddif[id][is][js][ip];
var = result->surf->raddif2[id][is][js][ip] / dmcphotons;
result->surf->raddif2[id][is][js][ip] = std_noisy (var, avg, dmcphotons);
avg = result->surf->radesc[id][is][js][ip];
var = result->surf->radesc2[id][is][js][ip] / dmcphotons;
result->surf->radesc2[id][is][js][ip] = std_noisy (var, avg, dmcphotons);
/* divide by solid angle to get radiance */
if (!sample->panorama_forward) {
result->surf->raddir2[id][is][js][ip] /= sample->rad[id].omega;
result->surf->raddif2[id][is][js][ip] /= sample->rad[id].omega;
} else {
/* do forward panorama normalization here; divide by individual pixel solid angle */
/* and multiply with number of sample pixels sample->Nx * sample->Ny */
normomega = (cos ((double)(js) / (double)sample->Ny * M_PI) - cos ((double)(js + 1) / (double)sample->Ny * M_PI)) /
sample->Nx * 2 * M_PI;
normomega *= sample->Nx * sample->Ny;
result->surf->raddir2[id][is][js][ip] /= normomega;
result->surf->raddif2[id][is][js][ip] /= normomega;
}
result->surf->radesc2[id][is][js][ip] /= (4.0 * PI);
result->surf->raddir2[id][is][js][ip] *= factor * areafactor;
result->surf->raddif2[id][is][js][ip] *= factor * areafactor;
result->surf->radesc2[id][is][js][ip] *= factor * areafactor;
}
/* divide by solid angle to get radiance */
if (!sample->panorama_forward) {
result->surf->raddir[id][is][js][ip] /= sample->rad[id].omega;
result->surf->raddif[id][is][js][ip] /= sample->rad[id].omega;
} else {
/* do forward panorama normalization here; divide by individual pixel solid angle */
normomega = (cos ((double)(js) / (double)sample->Ny * M_PI) - cos ((double)(js + 1) / (double)sample->Ny * M_PI)) /
sample->Nx * 2 * M_PI;
normomega *= sample->Nx * sample->Ny;
result->surf->raddir[id][is][js][ip] /= normomega;
result->surf->raddif[id][is][js][ip] /= normomega;
}
result->surf->radesc[id][is][js][ip] /= (4.0 * PI);
result->surf->raddir[id][is][js][ip] *= factor * areafactor;
result->surf->raddif[id][is][js][ip] *= factor * areafactor;
result->surf->radesc[id][is][js][ip] *= factor * areafactor;
if (sample->spectral_is || sample->concentration_is) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
result->surf_t->rad_t[ic][is][js][ip][iv] /= dmcphotons;
result->surf_t->rad_t[ic][is][js][ip][iv] /= (4.0 * PI);
result->surf_t->rad_t[ic][is][js][ip][iv] *= factor * areafactor;
}
}
}
if (write_files) {
fprintf (histradfile,
"%g %g %.6e %.6e %.6e %.6e %.6e %.6e\n",
((double)is + 0.5) * sample->delX,
((double)js + 0.5) * sample->delY,
sample->rad[id].theta,
sample->rad[id].externalphi,
sample->rad[id].omega,
result->surf->raddir[id][is][js][ip],
result->surf->raddif[id][is][js][ip],
result->surf->radesc[id][is][js][ip]);
if (sample->std)
fprintf (histradfile2,
"%g %g %.6e %.6e %.6e %.6e %.6e %.6e\n",
((double)is + 0.5) * sample->delX,
((double)js + 0.5) * sample->delY,
sample->rad[id].theta,
sample->rad[id].externalphi,
sample->rad[id].omega,
result->surf->raddir2[id][is][js][ip],
result->surf->raddif2[id][is][js][ip],
result->surf->radesc2[id][is][js][ip]);
/* CE - spectral radiance at surface, write to file ??? CHECK!!!
for (iv=0; iv<atmos->nlambda_abs; iv++){
fprintf(specradfile, "%d, %.6e", iv, result->surf_t->rad_t[iv][ip]);
}
*/
}
}
}
}
}
// =========================== Surface RPL
for (ir = 0; ir < sample->Nr; ir++) {
/* normalize to area of circular ring and pathlength interval */
rplfactor = 1.0 / (PI * sample->dr * sample->dr * (double)(2 * ir + 1)) / incident / (3.0E8 * sample->dt);
for (it = 0; it < sample->Nt; it++) {
for (id = 0; id < sample->Nd; id++) {
for (ip = 0; ip < sample->nstokes; ip++) {
/* calculate average */
result->surf->radpat[id][ir][it][ip] /= dmcphotons;
result->surf->radpes[id][ir][it][ip] /= dmcphotons;
/* calculate standard deviation from second moment */
if (sample->std) {
avg = result->surf->radpat[id][ir][it][ip];
var = result->surf->radpat2[id][ir][it][ip] / dmcphotons;
result->surf->radpat2[id][ir][it][ip] = std_noisy (var, avg, dmcphotons);
avg = result->surf->radpes[id][ir][it][ip];
var = result->surf->radpes2[id][ir][it][ip] / dmcphotons;
result->surf->radpes2[id][ir][it][ip] = std_noisy (var, avg, dmcphotons);
/* divide by solid angle to get radiance */
result->surf->radpat2[id][ir][it][ip] /= sample->rad[id].omega;
result->surf->radpat2[id][ir][it][ip] *= rplfactor;
result->surf->radpes2[id][ir][it][ip] /= (4.0 * PI);
result->surf->radpes2[id][ir][it][ip] *= rplfactor;
}
/* divide by solid angle to get radiance */
result->surf->radpat[id][ir][it][ip] /= sample->rad[id].omega;
result->surf->radpat[id][ir][it][ip] *= rplfactor;
result->surf->radpes[id][ir][it][ip] /= (4.0 * PI);
result->surf->radpes[id][ir][it][ip] *= rplfactor;
if (write_files) {
fprintf (histrplfile,
"%4d %4d %.6e %.6e %.6e %.6e %.6e %.6e\n",
ir,
it,
sample->rad[id].theta,
sample->rad[id].externalphi,
sample->rad[id].omega,
0.0,
result->surf->radpat[id][ir][it][ip],
result->surf->radpes[id][ir][it][ip]);
if (sample->std) {
fprintf (histrplfile2,
"%4d %4d %.6e %.6e %.6e %.6e %.6e %.6e\n",
ir,
it,
sample->rad[id].theta,
sample->rad[id].externalphi,
sample->rad[id].omega,
0.0,
result->surf->radpat2[id][ir][it][ip],
result->surf->radpes2[id][ir][it][ip]);
}
}
}
}
}
}
/* close files */
if (write_files) {
(void)fclose (histfile);
if (sample->Nd > 0)
(void)fclose (histradfile);
if (sample->Nr > 0 && sample->Nt > 0 && sample->Nd > 0)
(void)fclose (histrplfile);
if (sample->std) {
(void)fclose (histfile2);
if (sample->Nd > 0)
(void)fclose (histradfile2);
if (sample->Nr > 0 && sample->Nt > 0 && sample->Nd > 0)
(void)fclose (histrplfile2);
}
}
return 0;
}
/***********************************************************************************/
/* Function: summarize_result_forward_altitude_irradiance @62_30i@ */
/* Description: Outputs forward quantities */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int summarize_result_forward_altitude_irradiance (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
double dmcphotons,
double factor,
int write_files,
int kc,
char* flxext,
char* flxext2) {
int is = 0, js = 0; /* sampling grid coordinates */
double var, avg;
FILE * altfile = NULL, *altfile2 = NULL;
char altfilename[FILENAME_MAX] = "", altfilename2[FILENAME_MAX] = "";
// =========================== Altitude Irradiance
if (write_files) {
sprintf (altfilename, "%s%d%s", basename, kc, flxext);
sprintf (altfilename2, "%s%d%s", basename, kc, flxext2);
if ((altfile = fopen (altfilename, "w")) == NULL) {
print_sr_error_message (altfilename);
return -1;
}
if (sample->std) {
if ((altfile2 = fopen (altfilename2, "w")) == NULL) {
print_sr_error_message (altfilename2);
return -1;
}
}
}
for (is = 0; is < sample->Nx; is++) {
for (js = 0; js < sample->Ny; js++) {
/* calculate average */
result->alt[kc]->edir[is][js] /= dmcphotons;
result->alt[kc]->edn[is][js] /= dmcphotons;
result->alt[kc]->eup[is][js] /= dmcphotons;
result->alt[kc]->fdir[is][js] /= dmcphotons;
result->alt[kc]->fdn[is][js] /= dmcphotons;
result->alt[kc]->fup[is][js] /= dmcphotons;
/* calculate standard deviation from second moment */
if (sample->std) {
avg = result->alt[kc]->edir[is][js];
var = result->alt[kc]->edir2[is][js] / dmcphotons;
result->alt[kc]->edir2[is][js] = std_noisy (var, avg, dmcphotons);
avg = result->alt[kc]->edn[is][js];
var = result->alt[kc]->edn2[is][js] / dmcphotons;
result->alt[kc]->edn2[is][js] = std_noisy (var, avg, dmcphotons);
avg = result->alt[kc]->eup[is][js];
var = result->alt[kc]->eup2[is][js] / dmcphotons;
result->alt[kc]->eup2[is][js] = std_noisy (var, avg, dmcphotons);
avg = result->alt[kc]->fdir[is][js];
var = result->alt[kc]->fdir2[is][js] / dmcphotons;
result->alt[kc]->fdir2[is][js] = std_noisy (var, avg, dmcphotons);
avg = result->alt[kc]->fdn[is][js];
var = result->alt[kc]->fdn2[is][js] / dmcphotons;
result->alt[kc]->fdn2[is][js] = std_noisy (var, avg, dmcphotons);
avg = result->alt[kc]->fup[is][js];
var = result->alt[kc]->fup2[is][js] / dmcphotons;
result->alt[kc]->fup2[is][js] = std_noisy (var, avg, dmcphotons);
result->alt[kc]->edir2[is][js] *= factor;
result->alt[kc]->edn2[is][js] *= factor;
result->alt[kc]->eup2[is][js] *= factor;
result->alt[kc]->fdir2[is][js] *= factor;
result->alt[kc]->fdn2[is][js] *= factor;
result->alt[kc]->fup2[is][js] *= factor;
}
result->alt[kc]->edir[is][js] *= factor;
result->alt[kc]->edn[is][js] *= factor;
result->alt[kc]->eup[is][js] *= factor;
result->alt[kc]->fdir[is][js] *= factor;
result->alt[kc]->fdn[is][js] *= factor;
result->alt[kc]->fup[is][js] *= factor;
if (write_files) {
fprintf (altfile,
"%g %g %.6e %.6e %.6e %.6e %.6e %.6e\n",
((double)is + 0.5) * sample->delX,
((double)js + 0.5) * sample->delY,
result->alt[kc]->edir[is][js],
result->alt[kc]->edn[is][js],
result->alt[kc]->eup[is][js],
result->alt[kc]->fdir[is][js],
result->alt[kc]->fdn[is][js],
result->alt[kc]->fup[is][js]);
if (sample->std)
fprintf (altfile2,
"%g %g %.6e %.6e %.6e %.6e %.6e %.6e\n",
((double)is + 0.5) * sample->delX,
((double)js + 0.5) * sample->delY,
result->alt[kc]->edir2[is][js],
result->alt[kc]->edn2[is][js],
result->alt[kc]->eup2[is][js],
result->alt[kc]->fdir2[is][js],
result->alt[kc]->fdn2[is][js],
result->alt[kc]->fup2[is][js]);
}
}
}
if (write_files) {
(void)fclose (altfile);
if (sample->std)
(void)fclose (altfile2);
}
return 0;
}
/***********************************************************************************/
/* Function: write_backward_irradiance @62_30i@ */
/* Description: Writes output for backward irradiance in summarize_result */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void write_backward_irradiance (sample_struct* sample, double result, FILE* backfile, int is, int js, int nn) {
int i;
fprintf (backfile, "%g %g ", ((double)is + 0.5) * sample->delX, ((double)js + 0.5) * sample->delY);
for (i = 0; i < 6; i++) {
if (i == nn)
fprintf (backfile, " %.6e", result);
else
fprintf (backfile, " %.6e", NOT_A_NUMBER);
}
fprintf (backfile, "\n");
}
/***********************************************************************************/
/* Function: summarize_result_backward_irradiance @62_30i@ */
/* Description: Outputs backward irradiance, spectral IS, Circ Rad, HEAT */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int summarize_result_backward_irradiance (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
char* specradfilename,
char* bacext,
char* bacext2,
char* bacjacext,
char* bacjacext2,
double dmcphotons,
double factor,
double wavelength,
int mcsimulations,
int write_files,
int elev2D,
int islower,
int isupper,
int jslower,
int jsupper,
int isstep,
int jsstep) {
int is = 0, js = 0; /* sampling grid coordinates */
int ip = 0; /* stokes component index */
int iv = 0; /* wavelength index for spectral calculations with importance sampling */
int isp = 0, ijac = 0; /* jacobians */
int ic = 0, jc = 0, kc = 0, il = 0, i = 0;
double avg, var, areafactor;
double norm = 1.;
FILE * backfile = NULL, *backfile2 = NULL;
FILE * backjacfile = NULL, *backjacfile2 = NULL;
FILE* specradfile = NULL;
FILE* circradfile = NULL;
char backfilename[FILENAME_MAX] = "", backfilename2[FILENAME_MAX] = "";
char backjacfilename[FILENAME_MAX] = "", backjacfilename2[FILENAME_MAX] = "";
char circradfilename[FILENAME_MAX] = "";
char circstr[FILENAME_MAX] = "";
if (sample->backward == MCBACKWARD_EDIR || sample->backward == MCBACKWARD_EGLOB || sample->backward == MCBACKWARD_EDN ||
sample->backward == MCBACKWARD_EDNPV || sample->backward == MCBACKWARD_EUP || sample->backward == MCBACKWARD_EXP ||
sample->backward == MCBACKWARD_EXN || sample->backward == MCBACKWARD_EYP || sample->backward == MCBACKWARD_EYN ||
sample->backward == MCBACKWARD_FDIR || sample->backward == MCBACKWARD_FDN || sample->backward == MCBACKWARD_FUP ||
sample->jacobian || sample->jacobian3D)
norm = 4.0;
sprintf (backfilename, "%s%s%s", basename, sample->backward_altstr, bacext);
sprintf (backfilename2, "%s%s%s", basename, sample->backward_altstr, bacext2);
if (write_files) {
if ((backfile = fopen (backfilename, "w")) == NULL) {
print_sr_error_message (backfilename);
return -1;
}
if (sample->std) {
if ((backfile2 = fopen (backfilename2, "w")) == NULL) {
print_sr_error_message (backfilename2);
return -1;
}
}
if (sample->jacobian || sample->jacobian3D) {
sprintf (backjacfilename, "%s%s%s", basename, sample->backward_altstr, bacjacext);
sprintf (backjacfilename2, "%s%s%s", basename, sample->backward_altstr, bacjacext2);
if ((backjacfile = fopen (backjacfilename, "w")) == NULL) {
print_sr_error_message (backjacfilename);
return -1;
}
if (sample->std) {
if ((backjacfile2 = fopen (backjacfilename2, "w")) == NULL) {
print_sr_error_message (backjacfilename2);
return -1;
}
}
}
}
/* =========== Irradiance Factors */
for (is = islower; is <= isupper; is += isstep) {
for (js = jslower; js <= jsupper; js += jsstep) {
if (elev2D && sample->surfaceparallel)
areafactor = 1.0 / sample->surface_area[is][js];
else
areafactor = 1.0;
for (ip = 0; ip < sample->nstokes; ip++) {
result->back[is][js][ip] /= (dmcphotons / (double)mcsimulations); /* **CK 2013.08.27 Add dmcphotons/mcsimulations*/
if (sample->concentration_is)
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
result->back_t[ic][is][js][ip][iv] /=
(dmcphotons / (double)mcsimulations); /* BM 2013.10.27 - mcsimulations was missing */
result->back_t[ic][is][js][ip][iv] *= factor / norm * areafactor;
}
}
if (sample->jacobian || sample->jacobian3D) {
for (isp = 1; isp <= atmos->n_caoth; isp++) {
for (ijac = 0; ijac < 2; ijac++) { /* scattering and absorption */
for (ic = 0; ic < atmos->Nx; ic++) {
for (jc = 0; jc < atmos->Ny; jc++) {
for (kc = 0; kc < atmos->Nz; kc++) {
result->jacobian->jacobian_t[ip][isp][ijac][ic][jc][kc] /= (dmcphotons / (double)mcsimulations);
result->jacobian->jacobian_t[ip][isp][ijac][ic][jc][kc] /= (atmos->Z[kc + 1] - atmos->Z[kc]);
result->jacobian->jacobian_t[ip][isp][ijac][ic][jc][kc] *= factor / norm * areafactor;
}
}
}
/* CE: include also standard deviation */
}
}
}
if (sample->backward == MCBACKWARD_HEAT)
if (sample->heat_flag[is][js] == MCBACKWARD_HEAT_EMABS || sample->heat_flag[is][js] == MCBACKWARD_HEAT_EMABSOPT)
result->backemis[is][js] /= (dmcphotons / (double)mcsimulations); /* **CK 2013.08.27 Add dmcphotons/mcsimulations*/
if (sample->std) {
if (sample->backward != MCBACKWARD_HEAT) { /* **CK 2013.09.27 */
avg = result->back[is][js][ip];
var = result->back2[is][js][ip] / (dmcphotons / (double)mcsimulations);
} else {
switch (sample->heat_flag[is][js]) {
case MCBACKWARD_HEAT_EMABS:
case MCBACKWARD_HEAT_EMABSOPT:
avg = result->back[is][js][ip] + result->backemis[is][js];
var = result->back2[is][js][ip] / (dmcphotons / (double)mcsimulations);
break;
case MCBACKWARD_HEAT_DENET:
avg = 0;
var = 0;
if (atmos->threed[MCCAOTH_TOT][sample->backemis_kc] >= 1) { /* **CK 1014.01.17*/
for (i = 0; i < 12; i++) {
avg += result->back_dEnet[is][js][i] * result->back_dEnet[is][js][i];
var += result->back_dEnet2[is][js][i];
}
} else {
for (i = 0; i < 4; i++) {
avg += result->back_dEnet[is][js][i] * result->back_dEnet[is][js][i];
var += result->back_dEnet2[is][js][i];
}
}
avg = sqrt (avg);
break;
default:
fprintf (stderr, "Error, unknown sample->heat_flag %d\n", sample->heat_flag[is][js]);
return -1;
}
}
if (sample->backward == MCBACKWARD_HEAT && sample->heat_flag[is][js] == MCBACKWARD_HEAT_DENET) /* **CK 2014.01.17 */
result->back2[is][js][ip] =
std_noisy (var, avg, (dmcphotons / (double)mcsimulations) * (dmcphotons / (double)mcsimulations));
else
result->back2[is][js][ip] =
std_noisy (var, avg, dmcphotons / (double)mcsimulations); /* **CK 2013.09.27 Add dmcphotons/mcsimulations*/
result->back2[is][js][ip] *= factor / norm * areafactor;
}
if (sample->backward != MCBACKWARD_HEAT) { /* **CK 2013.09.27 */
result->backemis[is][js] *= (4.0 * PI);
result->back[is][js][ip] *= factor / norm * areafactor;
} else {
switch (sample->heat_flag[is][js]) {
case MCBACKWARD_HEAT_EMABS:
case MCBACKWARD_HEAT_EMABSOPT:
result->backemis[is][js] *= factor / norm * areafactor;
result->back[is][js][ip] *= factor / norm * areafactor;
break;
case MCBACKWARD_HEAT_DENET:
result->back[is][js][ip] *= factor / norm * areafactor;
break;
default:
fprintf (stderr, "Error, unknown sample->heat_flag %d\n", sample->heat_flag[is][js]);
return -1;
}
}
} /* ip */
} /* js */
} /* is */
if (write_files) {
/* =========== Write Irradiance Files */
for (is = islower; is <= isupper; is += isstep) {
for (js = jslower; js <= jsupper; js += jsstep) {
switch (sample->backward) {
case MCBACKWARD_EDIR:
write_backward_irradiance (sample, result->back[is][js][0], backfile, is, js, 0);
break;
case MCBACKWARD_EGLOB:
case MCBACKWARD_EDN:
case MCBACKWARD_EDNPV:
case MCBACKWARD_EXN:
case MCBACKWARD_EYN:
write_backward_irradiance (sample, result->back[is][js][0], backfile, is, js, 1);
if (sample->jacobian || sample->jacobian3D) {
write_jacobian_result (sample, atmos, result->jacobian, backjacfile);
}
break;
case MCBACKWARD_EUP:
case MCBACKWARD_EXP:
case MCBACKWARD_EYP:
write_backward_irradiance (sample, result->back[is][js][0], backfile, is, js, 2);
if (sample->jacobian || sample->jacobian3D) {
write_jacobian_result (sample, atmos, result->jacobian, backjacfile);
}
break;
case MCBACKWARD_FDIR:
write_backward_irradiance (sample, result->back[is][js][0], backfile, is, js, 3);
break;
case MCBACKWARD_FDN:
write_backward_irradiance (sample, result->back[is][js][0], backfile, is, js, 4);
break;
case MCBACKWARD_FUP:
write_backward_irradiance (sample, result->back[is][js][0], backfile, is, js, 5);
break;
case MCBACKWARD_ABS:
case MCBACKWARD_ACT:
case MCBACKWARD_EMIS:
case MCBACKWARD_HEAT:
fprintf (stderr, "MCBACKWARD_ABS, MCBACKWARD_ACT etc not written to mc.flx\n");
break;
case MCBACKWARD_NONE:
fprintf (stderr, "Error, we are not supposed to be here in a forward simulation.\n");
return -1;
break;
default:
fprintf (stderr, "Error, unknown backward quantity %d\n", sample->backward);
return -1;
}
if (sample->std) {
switch (sample->backward) {
case MCBACKWARD_EDIR:
write_backward_irradiance (sample, result->back2[is][js][0], backfile2, is, js, 0);
break;
case MCBACKWARD_EGLOB:
case MCBACKWARD_EDN:
case MCBACKWARD_EDNPV:
case MCBACKWARD_EXN:
case MCBACKWARD_EYN:
write_backward_irradiance (sample, result->back2[is][js][0], backfile2, is, js, 1);
break;
case MCBACKWARD_EUP:
case MCBACKWARD_EXP:
case MCBACKWARD_EYP:
write_backward_irradiance (sample, result->back2[is][js][0], backfile2, is, js, 2);
break;
case MCBACKWARD_FDIR:
write_backward_irradiance (sample, result->back2[is][js][0], backfile2, is, js, 3);
break;
case MCBACKWARD_FDN:
write_backward_irradiance (sample, result->back2[is][js][0], backfile2, is, js, 4);
break;
case MCBACKWARD_FUP:
write_backward_irradiance (sample, result->back2[is][js][0], backfile2, is, js, 5);
break;
case MCBACKWARD_ABS:
case MCBACKWARD_ACT:
case MCBACKWARD_EMIS:
case MCBACKWARD_HEAT:
fprintf (stderr, "MCBACKWARD_ABS, MCBACKWARD_ACT etc not written to mc.flx\n");
break;
case MCBACKWARD_NONE:
fprintf (stderr, "Error, we are not supposed to be here in a forward simulation.\n");
return -1;
break;
default:
fprintf (stderr, "Error, unknown backward quantity %d\n", sample->backward);
return -1;
}
}
}
}
fclose (backfile);
if (sample->std)
fclose (backfile2);
/* =========== Spectral Importance Sampling */
if (sample->spectral_is || sample->concentration_is) {
if ((specradfile = fopen (specradfilename, "w")) == NULL) {
print_sr_error_message (specradfilename);
return -1;
}
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
for (is = islower; is <= isupper; is += isstep) {
for (js = jslower; js <= jsupper; js += jsstep) {
if (elev2D && sample->surfaceparallel)
areafactor = 1.0 / sample->surface_area[is][js];
else
areafactor = 1.0;
for (ip = 0; ip < sample->nstokes; ip++) {
result->back_t[ic][is][js][ip][iv] /=
(dmcphotons / (double)mcsimulations); /* BM 2013.10.27 - mcsimulations was missing */
result->back_t[ic][is][js][ip][iv] *= factor / norm * areafactor;
}
fprintf (specradfile, "%.8f %d %d %.6e \n", atmos->lambda[iv], is, js, result->back_t[ic][is][js][0][iv]);
}
}
}
}
fclose (specradfile);
}
}
/* =========== Circ Rad */
if (sample->ncirc) {
if (elev2D && sample->surfaceparallel)
areafactor = 1.0 / sample->surface_area[0][0];
else
areafactor = 1.0;
for (il = 0; il < 10; il++) {
for (ic = 0; ic < sample->ncirc; ic++) {
result->circcontr[il][ic] *= factor / norm * areafactor / dmcphotons;
}
}
strcpy (circradfilename, basename);
sprintf (circstr, ".%5.1f.circ", wavelength);
strcat (circradfilename, circstr);
if ((circradfile = fopen (circradfilename, "w")) == NULL) {
print_sr_error_message (circradfilename);
return -1;
}
for (ic = 0; ic < sample->ncirc; ic++) {
fprintf (circradfile, "%9.3f %12.3f", wavelength, sample->dcirc * ((double)(ic + 1)));
for (il = 0; il < 10; il++) {
fprintf (circradfile, " %12.4e", result->circcontr[il][ic]);
fprintf (circradfile, "\n");
}
}
fclose (circradfile);
}
return 0;
}
/***********************************************************************************/
/* Function: summarize_result_cldprp @62_30i@ */
/* Description: summarize_result output for cloud properties */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
#ifdef CLDPRP
int summarize_result_cldprp (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
int elev2D,
int islower,
int isupper,
int jslower,
int jsupper,
int isstep,
int jsstep)
{
int kc = 0, is = 0, js = 0;
FILE* cldprp_file = NULL;
char cldprp_filename[FILENAME_MAX] = "";
/* double areafactor; */
sprintf (cldprp_filename, "%s_%f", basename, result->wavelength);
strcat (cldprp_filename, ".cldprp");
for (kc = 0; kc <= atmos->Nz; kc++) {
if (sample->sample[kc]) {
if ((cldprp_file = fopen (cldprp_filename, "w")) == NULL) {
print_sr_error_message (cldprp_filename);
return -1;
}
for (is = islower; is <= isupper; is += isstep) {
for (js = jslower; js <= jsupper; js += jsstep) {
/* normalize estimated effective radius with summed-up tau */
if (result->alt[kc]->cldprp.tau_wc[is][js] > 0.0)
result->alt[kc]->cldprp.reff_wc[is][js] /= (result->alt[kc]->cldprp.tau_wc[is][js]);
if (result->alt[kc]->cldprp.tau_ic[is][js] > 0.0)
result->alt[kc]->cldprp.reff_ic[is][js] /= (result->alt[kc]->cldprp.tau_ic[is][js]);
/* normalize with number of traced photons */
if (result->alt[kc]->cldprp.totweights[is][js] > 0.0) {
result->alt[kc]->cldprp.tau_wc[is][js] /= (result->alt[kc]->cldprp.totweights[is][js]);
result->alt[kc]->cldprp.tau_ic[is][js] /= (result->alt[kc]->cldprp.totweights[is][js]);
}
/* normalize with number of traced photons which flew through clouds */
if (result->alt[kc]->cldprp.wc_weights[is][js] > 0.0) {
result->alt[kc]->cldprp.rhit_wc[is][js] /= (result->alt[kc]->cldprp.wc_weights[is][js]);
result->alt[kc]->cldprp.dylwc[is][js] /= (result->alt[kc]->cldprp.wc_weights[is][js]);
result->alt[kc]->cldprp.dylwc[is][js] /= (result->alt[kc]->cldprp.wc_weights[is][js]);
result->alt[kc]->cldprp.dzlwc[is][js] /= (result->alt[kc]->cldprp.wc_weights[is][js]);
}
if (result->alt[kc]->cldprp.ic_weights[is][js] > 0.0) {
result->alt[kc]->cldprp.rhit_ic[is][js] /= (result->alt[kc]->cldprp.ic_weights[is][js]);
result->alt[kc]->cldprp.dxiwc[is][js] /= (result->alt[kc]->cldprp.ic_weights[is][js]);
result->alt[kc]->cldprp.dyiwc[is][js] /= (result->alt[kc]->cldprp.ic_weights[is][js]);
result->alt[kc]->cldprp.dziwc[is][js] /= (result->alt[kc]->cldprp.ic_weights[is][js]);
}
/* why is this even here? */
/* if (elev2D && sample->surfaceparallel) */
/* areafactor = 1.0 / sample->surface_area[is][js]; */
/* else */
/* areafactor = 1.0; */
fprintf (cldprp_file,
"%4d %4d %7.3f %7.3f %7.3f %7.3f %8.3f %8.3f %+7.5f %+7.5f %+7.5f %+7.5f %+7.5f %+7.5f\n",
is,
js,
result->alt[kc]->cldprp.reff_wc[is][js],
result->alt[kc]->cldprp.reff_ic[is][js],
result->alt[kc]->cldprp.rhit_wc[is][js],
result->alt[kc]->cldprp.rhit_ic[is][js],
result->alt[kc]->cldprp.tau_wc[is][js],
result->alt[kc]->cldprp.tau_ic[is][js],
result->alt[kc]->cldprp.dylwc[is][js],
result->alt[kc]->cldprp.dylwc[is][js],
result->alt[kc]->cldprp.dzlwc[is][js],
result->alt[kc]->cldprp.dxiwc[is][js],
result->alt[kc]->cldprp.dyiwc[is][js],
result->alt[kc]->cldprp.dziwc[is][js]);
}
}
fclose (cldprp_file);
}
}
return 0;
}
#endif
/***********************************************************************************/
/* Function: summarize_result_backward_radiance @62_30i@ */
/* Description: Outputs backward radiance */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int summarize_result_backward_radiance (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
char* specradfilename,
char* bacext,
char* bacext2,
char* picext,
char* bacjacext,
char* bacjacext2,
double dmcphotons,
double factor,
double sza,
int source,
int mcsimulations,
int write_files,
int elev2D,
int islower,
int isupper,
int jslower,
int jsupper,
int isstep,
int jsstep) {
int is = 0, js = 0, ip = 0, iv = 0, isp = 0, ijac = 0, ic = 0, jc = 0, kc = 0;
double avg, var, areafactor;
FILE * backfile = NULL, *backfile2 = NULL;
FILE * backjacfile = NULL, *backjacfile2 = NULL;
FILE * picturefile = NULL, *specradfile = NULL;
;
char backfilename[FILENAME_MAX] = "", backfilename2[FILENAME_MAX] = "";
char backjacfilename[FILENAME_MAX] = "", backjacfilename2[FILENAME_MAX] = "";
char picturefilename[FILENAME_MAX] = "";
double picfac = 0.;
float xval = 0.0, yval = 0.0;
if (write_files) {
sprintf (backfilename, "%s%s%s", basename, sample->backward_altstr, bacext);
sprintf (backfilename2, "%s%s%s", basename, sample->backward_altstr, bacext2);
if ((backfile = fopen (backfilename, "w")) == NULL) {
print_sr_error_message (backfilename);
return -1;
}
if (sample->std) {
if ((backfile2 = fopen (backfilename2, "w")) == NULL) {
print_sr_error_message (backfilename2);
return -1;
}
}
if (sample->jacobian || sample->jacobian3D) {
sprintf (backjacfilename, "%s%s%s", basename, sample->backward_altstr, bacjacext);
sprintf (backjacfilename2, "%s%s%s", basename, sample->backward_altstr, bacjacext2);
if ((backjacfile = fopen (backjacfilename, "w")) == NULL) {
print_sr_error_message (backjacfilename);
return -1;
}
if (sample->std) {
if ((backjacfile2 = fopen (backjacfilename2, "w")) == NULL) {
print_sr_error_message (backjacfilename2);
return -1;
}
}
}
if (sample->spectral_is || sample->concentration_is) {
if ((specradfile = fopen (specradfilename, "w")) == NULL) {
print_sr_error_message (specradfilename);
return -1;
}
}
}
/* ============ Backward Radiance */
for (is = islower; is <= isupper; is += isstep) {
for (js = jslower; js <= jsupper; js += jsstep) {
if (elev2D && sample->surfaceparallel)
areafactor = 1.0 / sample->surface_area[is][js];
else
areafactor = 1.0;
for (ip = 0; ip < sample->nstokes; ip++) {
result->back[is][js][ip] /= (dmcphotons / (double)mcsimulations); /* BM 2013.10.27 - mcsimulations was missing */
if (sample->std) {
avg = result->back[is][js][ip];
var = result->back2[is][js][ip] / (dmcphotons / (double)mcsimulations); /* BM 2013.10.27 - mcsimulations was missing */
result->back2[is][js][ip] =
std_noisy (var, avg, dmcphotons / (double)mcsimulations); /* BM 2013.10.27 - mcsimulations was missing */
if (source == MCSRC_THERMAL_BACKWARD) /*TZ bt*/
result->back2[is][js][ip] *= factor * areafactor; /*TZ bt */
else /*TZ bt*/
result->back2[is][js][ip] *= factor / 4.0 / PI * areafactor;
}
if (source == MCSRC_THERMAL_BACKWARD) { /*TZ bt*/
result->back[is][js][ip] *= factor * areafactor; /*TZ bt*/
} else { /*TZ bt*/
result->back[is][js][ip] *= factor / 4.0 / PI * areafactor;
}
if (sample->jacobian || sample->jacobian3D) {
for (isp = 1; isp <= atmos->n_caoth; isp++) {
for (ijac = 0; ijac < 2; ijac++) { /* scattering and absorption */
for (ic = 0; ic < atmos->Nx; ic++) {
for (jc = 0; jc < atmos->Ny; jc++) {
for (kc = 0; kc < atmos->Nz; kc++) {
result->jacobian->jacobian_t[ip][isp][ijac][ic][jc][kc] /= (dmcphotons / (double)mcsimulations);
result->jacobian->jacobian_t[ip][isp][ijac][ic][jc][kc] /=
(atmos->Z[kc + 1] - atmos->Z[kc]); // CE-> move to count_escape?
if (sample->std) {
avg = result->jacobian->jacobian_t[ip][isp][ijac][ic][jc][kc];
var = result->jacobian->jacobian_t2[ip][isp][ijac][ic][jc][kc] / (dmcphotons / (double)mcsimulations);
result->jacobian->jacobian_t2[ip][isp][ijac][ic][jc][kc] =
std_noisy (var, avg, dmcphotons / (double)mcsimulations);
if (source == MCSRC_THERMAL_BACKWARD)
result->jacobian->jacobian_t2[ip][isp][ijac][ic][jc][kc] *= factor * areafactor;
else
result->jacobian->jacobian_t2[ip][isp][ijac][ic][jc][kc] *= factor / 4.0 / PI * areafactor;
}
if (source == MCSRC_THERMAL_BACKWARD)
result->jacobian->jacobian_t[ip][isp][ijac][ic][jc][kc] *= factor * areafactor;
else
result->jacobian->jacobian_t[ip][isp][ijac][ic][jc][kc] *= factor / 4.0 / PI * areafactor;
}
}
}
}
}
}
}
}
}
/* ============ Write Files */
if (write_files) {
for (is = islower; is <= isupper; is += isstep) {
for (js = jslower; js <= jsupper; js += jsstep) {
if (sample->panorama) {
sample->backward_is = is;
sample->backward_js = js;
set_panorama_dir (sample, &yval, &xval);
xval -= 180.0;
if (sample->pan_distr_photons_over_pixel) {
xval += 0.5 * sample->pan_dphi;
yval += 0.5 * sample->pan_dtheta;
}
} else {
xval = ((double)is + 0.5) * sample->delX;
yval = ((double)js + 0.5) * sample->delY;
}
for (ip = 0; ip < sample->nstokes; ip++)
fprintf (backfile,
"%.8e %.8e %.6e %.6e %.6e %.6e %.6e %.6e\n",
xval,
yval,
sza,
sample->rad[0].externalphi,
0.0,
0.0,
0.0,
result->back[is][js][ip]);
if (sample->std)
for (ip = 0; ip < sample->nstokes; ip++)
fprintf (backfile2,
"%.8e %.8e %.6e %.6e %.6e %.6e %.6e %.6e\n",
xval,
yval,
sample->forward_vza,
sample->forward_phi,
0.0,
0.0,
0.0,
result->back2[is][js][ip]);
if (sample->jacobian || sample->jacobian3D) {
write_jacobian_result (sample, atmos, result->jacobian, backjacfile);
}
}
}
fclose (backfile);
if (sample->std)
fclose (backfile2);
if (sample->jacobian || sample->jacobian3D) {
fclose (backjacfile);
if (sample->std)
fclose (backjacfile2);
}
/* ============= PanPicture */
if (sample->pan_picture) {
sprintf (picturefilename, "%s%s%s", basename, sample->backward_altstr, picext);
if ((picturefile = fopen (picturefilename, "w")) == NULL) {
print_sr_error_message (picturefilename);
return -1;
}
fprintf (picturefile, "P3\n# mystic\n%d %d\n255\n", (jsupper - jslower) / jsstep + 1, (isupper - islower) / isstep + 1);
for (is = islower; is <= isupper; is += isstep)
for (js = jslower; js <= jsupper; js += jsstep)
picfac = (picfac > result->back[is][js][0] ? picfac : result->back[is][js][0]);
picfac = 255.0 / picfac;
for (is = islower; is <= isupper; is += isstep)
for (js = jslower; js <= jsupper; js += jsstep)
fprintf (picturefile,
"%d %d %d\n",
(int)(result->back[is][js][0] * picfac),
(int)(result->back[is][js][0] * picfac),
(int)(result->back[is][js][0] * picfac));
fclose (picturefile);
}
}
/* ============ Spectral IS */
if (sample->spectral_is || sample->concentration_is) {
for (is = islower; is <= isupper; is += isstep) {
for (js = jslower; js <= jsupper; js += jsstep) {
if (elev2D && sample->surfaceparallel)
areafactor = 1.0 / sample->surface_area[is][js];
else
areafactor = 1.0;
for (ip = 0; ip < sample->nstokes; ip++) {
if (sample->spectral_is || sample->concentration_is) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
result->back_t[ic][is][js][ip][iv] /=
(dmcphotons / (double)mcsimulations); /* BM 2013.10.27 - mcsimulations was missing */
}
}
}
if (source == MCSRC_THERMAL_BACKWARD) { /*TZ bt*/
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
result->back_t[ic][iv][is][js][ip] *= factor * areafactor;
}
}
} else { /*TZ bt*/
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
result->back_t[ic][is][js][ip][iv] *= factor / 4.0 / PI * areafactor;
}
}
}
}
}
}
if (write_files) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
for (is = islower; is <= isupper; is += isstep) {
for (js = jslower; js <= jsupper; js += jsstep) {
if (sample->nstokes == 1) {
fprintf (specradfile, "%.8f %d %d %.6e \n", atmos->lambda[iv], is, js, result->back_t[ic][is][js][0][iv]);
} else {
fprintf (specradfile,
"%.8f %d %d %.6e %.6e %.6e %.6e\n",
atmos->lambda[iv],
is,
js,
result->back_t[ic][is][js][0][iv],
result->back_t[ic][is][js][1][iv],
result->back_t[ic][is][js][2][iv],
result->back_t[ic][is][js][3][iv]);
}
}
}
}
}
fclose (specradfile);
}
}
return 0;
}
/***********************************************************************************/
/* Function: summarize_result_forward_altitude_radiance @62_30i@ */
/* Description: Forward radiances at altitudes, backward bac files */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int summarize_result_forward_altitude_radiance (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
char* specradfilename,
char* radext,
char* radext2,
double dmcphotons,
double factor,
int write_files,
int kc) {
int is = 0, js = 0, id = 0, ip = 0, ic = 0, iv = 0;
double avg, var;
FILE * altradfile = NULL, *altradfile2 = NULL, *specradfile = NULL;
char altradfilename[FILENAME_MAX] = "";
char altradfilename2[FILENAME_MAX] = "";
double normomega = 0;
// =========================== Forward Altitude Radiance -> radext = rad
// =========================== Backward Altitude Radiance -> radext = bac
if (sample->Nd > 0) {
sprintf (altradfilename, "%s%d%s", basename, kc, radext);
sprintf (altradfilename2, "%s%d%s", basename, kc, radext2);
if (write_files) {
if ((altradfile = fopen (altradfilename, "w")) == NULL) {
print_sr_error_message (altradfilename);
return -1;
}
if (sample->std) {
if ((altradfile2 = fopen (altradfilename2, "w")) == NULL) {
print_sr_error_message (altradfilename2);
return -1;
}
}
}
}
for (is = 0; is < sample->Nx; is++) {
for (js = 0; js < sample->Ny; js++) {
for (id = 0; id < sample->Nd; id++) {
for (ip = 0; ip < sample->nstokes; ip++) {
/* calculate average */
result->alt[kc]->raddir[id][is][js][ip] /= dmcphotons;
result->alt[kc]->raddif[id][is][js][ip] /= dmcphotons;
result->alt[kc]->radesc[id][is][js][ip] /= dmcphotons;
/* calculate standard deviation from second moment */
if (sample->std) {
avg = result->alt[kc]->raddir[id][is][js][ip];
var = result->alt[kc]->raddir2[id][is][js][ip] / dmcphotons;
result->alt[kc]->raddir2[id][is][js][ip] = std_noisy (var, avg, dmcphotons);
avg = result->alt[kc]->raddif[id][is][js][ip];
var = result->alt[kc]->raddif2[id][is][js][ip] / dmcphotons;
result->alt[kc]->raddif2[id][is][js][ip] = std_noisy (var, avg, dmcphotons);
avg = result->alt[kc]->radesc[id][is][js][ip];
var = result->alt[kc]->radesc2[id][is][js][ip] / dmcphotons;
result->alt[kc]->radesc2[id][is][js][ip] = std_noisy (var, avg, dmcphotons);
/* divide by solid angle to get radiance */
if (sample->panorama_forward) {
result->alt[kc]->raddir2[id][is][js][ip] /= sample->rad[id].omega;
result->alt[kc]->raddif2[id][is][js][ip] /= sample->rad[id].omega;
} else {
/* do forward panorama normalization here; divide by individual pixel solid angle */
normomega = (cos ((double)(js) / (double)sample->Ny * M_PI) - cos ((double)(js + 1) / (double)sample->Ny * M_PI)) /
sample->Nx * 2 * M_PI;
normomega *= sample->Nx * sample->Ny;
result->alt[kc]->raddir2[id][is][js][ip] /= normomega;
result->alt[kc]->raddif2[id][is][js][ip] /= normomega;
}
result->alt[kc]->radesc2[id][is][js][ip] /= (4.0 * PI);
result->alt[kc]->raddir2[id][is][js][ip] *= factor;
result->alt[kc]->raddif2[id][is][js][ip] *= factor;
result->alt[kc]->radesc2[id][is][js][ip] *= factor;
switch (sample->backward) {
case MCBACKWARD_EGLOB:
case MCBACKWARD_EDIR:
case MCBACKWARD_EDN:
case MCBACKWARD_EDNPV:
case MCBACKWARD_EXP:
case MCBACKWARD_EXN:
case MCBACKWARD_EYP:
case MCBACKWARD_EYN:
case MCBACKWARD_EUP:
case MCBACKWARD_FDIR:
case MCBACKWARD_FDN:
case MCBACKWARD_FUP:
case MCBACKWARD_ABS:
case MCBACKWARD_ACT:
result->alt[kc]->raddir2[id][is][js][ip] *= PI;
result->alt[kc]->raddif2[id][is][js][ip] *= PI;
result->alt[kc]->radesc2[id][is][js][ip] *= PI;
break;
case MCBACKWARD_NONE:
case MCBACKWARD_RADIANCE:
break;
default:
fprintf (stderr, "Error, unknown backward quantity %d\n", sample->backward);
return -1;
}
}
if (!sample->panorama_forward) {
result->alt[kc]->raddir[id][is][js][ip] /= sample->rad[id].omega;
result->alt[kc]->raddif[id][is][js][ip] /= sample->rad[id].omega;
} else {
/* do forward panorama normalization here; divide by individual pixel solid angle */
normomega = (cos ((double)(js) / (double)sample->Ny * M_PI) - cos ((double)(js + 1) / (double)sample->Ny * M_PI)) /
sample->Nx * 2 * M_PI;
normomega *= sample->Nx * sample->Ny;
result->alt[kc]->raddir[id][is][js][ip] /= normomega;
result->alt[kc]->raddif[id][is][js][ip] /= normomega;
}
result->alt[kc]->radesc[id][is][js][ip] /= (4.0 * PI);
result->alt[kc]->raddir[id][is][js][ip] *= factor;
result->alt[kc]->raddif[id][is][js][ip] *= factor;
result->alt[kc]->radesc[id][is][js][ip] *= factor;
switch (sample->backward) {
case MCBACKWARD_EGLOB:
case MCBACKWARD_EDIR:
case MCBACKWARD_EDN:
case MCBACKWARD_EDNPV:
case MCBACKWARD_EXP:
case MCBACKWARD_EXN:
case MCBACKWARD_EYP:
case MCBACKWARD_EYN:
case MCBACKWARD_EUP:
case MCBACKWARD_FDIR:
case MCBACKWARD_FDN:
case MCBACKWARD_FUP:
case MCBACKWARD_ABS:
case MCBACKWARD_ACT:
result->alt[kc]->raddir[id][is][js][ip] *= PI;
result->alt[kc]->raddif[id][is][js][ip] *= PI;
result->alt[kc]->radesc[id][is][js][ip] *= PI;
break;
case MCBACKWARD_NONE:
case MCBACKWARD_RADIANCE:
break;
default:
fprintf (stderr, "Error, unknown backward quantity %d\n", sample->backward);
return -1;
}
if (write_files) {
fprintf (altradfile,
"%g %g %.6e %.6e %.6e %.6e %.6e %.6e\n",
((double)is + 0.5) * sample->delX,
((double)js + 0.5) * sample->delY,
sample->rad[id].theta,
sample->rad[id].externalphi,
sample->rad[id].omega,
result->alt[kc]->raddir[id][is][js][ip],
result->alt[kc]->raddif[id][is][js][ip],
result->alt[kc]->radesc[id][is][js][ip]);
if (sample->std)
fprintf (altradfile2,
"%g %g %.6e %.6e %.6e %.6e %.6e %.6e\n",
((double)is + 0.5) * sample->delX,
((double)js + 0.5) * sample->delY,
sample->rad[id].theta,
sample->rad[id].externalphi,
sample->rad[id].omega,
result->alt[kc]->raddir2[id][is][js][ip],
result->alt[kc]->raddif2[id][is][js][ip],
result->alt[kc]->radesc2[id][is][js][ip]);
}
} // end ip
} // end id
} // end js
} // end is
if (write_files) {
if (sample->Nd > 0)
(void)fclose (altradfile);
if (sample->std) {
if (sample->Nd > 0)
(void)fclose (altradfile2);
}
}
/* ============ Spectral IS */
if (sample->spectral_is || sample->concentration_is) {
for (is = 0; is < sample->Nx; is++) {
for (js = 0; js < sample->Ny; js++) {
for (ip = 0; ip < sample->nstokes; ip++) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
result->rad_t[kc]->rad_t[ic][is][js][ip][iv] /= (4.0 * PI);
result->rad_t[kc]->rad_t[ic][is][js][ip][iv] *= factor;
result->rad_t[kc]->rad_t[ic][is][js][ip][iv] /= dmcphotons;
}
}
}
}
}
if (write_files) {
if ((specradfile = fopen (specradfilename, "w")) == NULL) {
print_sr_error_message (specradfilename);
return -1;
}
for (is = 0; is < sample->Nx; is++) {
for (js = 0; js < sample->Ny; js++) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
if (sample->nstokes == 1) {
fprintf (specradfile, "%.8f %d %d %.6e \n", atmos->lambda[iv], is, js, result->rad_t[kc]->rad_t[ic][is][js][0][iv]);
} else {
fprintf (specradfile,
"%.8f %d %d %.6e %.6e %.6e %.6e\n",
atmos->lambda[iv],
is,
js,
result->rad_t[kc]->rad_t[ic][is][js][0][iv],
result->rad_t[kc]->rad_t[ic][is][js][1][iv],
result->rad_t[kc]->rad_t[ic][is][js][2][iv],
result->rad_t[kc]->rad_t[ic][is][js][3][iv]);
}
}
}
}
}
if (sample->Nd > 0)
(void)fclose (specradfile);
}
}
return 0;
}
/***********************************************************************************/
/* Function: summarize_result_passback3D @62_30i@ */
/* Description: Outputs 3D fields */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int summarize_result_passback3D (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
float*** rfldir3d,
float*** rfldn3d,
float*** flup3d,
float***** fl3d_is,
float*** uavgso3d,
float*** uavgdn3d,
float*** uavgup3d,
float**** radiance3d,
float*** absback3d,
float*** rfldir3d_var,
float*** rfldn3d_var,
float*** flup3d_var,
float*** uavgso3d_var,
float*** uavgdn3d_var,
float*** uavgup3d_var,
float**** radiance3d_var,
float*** absback3d_var,
float*** abs3d,
float****** radiance3d_is,
float****** jacobian,
int escape,
int islower,
int isupper,
int jslower,
int jsupper,
int isstep,
int jsstep,
int* lu3D) {
int is = 0, js = 0, ip = 0, kc = 0, ic = 0, iv = 0, isp = 0, ijac = 0;
/* ============ Forward */
if (!sample->backward) {
if (sample->passback3D && sample->surface) {
for (is = 0; is < sample->Nx; is++) {
for (js = 0; js < sample->Ny; js++) {
rfldir3d[(*lu3D)][is][js] = (float)result->surf->edir[is][js];
rfldn3d[(*lu3D)][is][js] = (float)result->surf->edn[is][js];
flup3d[(*lu3D)][is][js] = (float)result->surf->eup[is][js];
uavgso3d[(*lu3D)][is][js] = (float)result->surf->fdir[is][js];
uavgdn3d[(*lu3D)][is][js] = (float)result->surf->fdn[is][js];
uavgup3d[(*lu3D)][is][js] = (float)result->surf->fup[is][js];
if (sample->Nd > 0) {
for (ip = 0; ip < sample->nstokes; ip++) {
if (escape) {
radiance3d[(*lu3D)][is][js][ip] = (float)result->surf->radesc[0][is][js][ip];
if (sample->std)
radiance3d_var[(*lu3D)][is][js][ip] = (float)result->surf->radesc2[0][is][js][ip];
} else {
radiance3d[(*lu3D)][is][js][ip] =
(float)result->surf->raddir[0][is][js][ip] + (float)result->surf->raddif[0][is][js][ip];
if (sample->std)
radiance3d_var[(*lu3D)][is][js][ip] =
(float)result->surf->raddir2[0][is][js][ip] + (float)result->surf->raddif2[0][is][js][ip];
}
}
}
/* variance */
if (sample->std) {
rfldir3d_var[(*lu3D)][is][js] = (float)(result->surf->edir2[is][js] * result->surf->edir2[is][js]);
rfldn3d_var[(*lu3D)][is][js] = (float)(result->surf->edn2[is][js] * result->surf->edn2[is][js]);
flup3d_var[(*lu3D)][is][js] = (float)(result->surf->eup2[is][js] * result->surf->eup2[is][js]);
uavgso3d_var[(*lu3D)][is][js] = (float)(result->surf->fdir2[is][js] * result->surf->fdir2[is][js]);
uavgdn3d_var[(*lu3D)][is][js] = (float)(result->surf->fdn2[is][js] * result->surf->fdn2[is][js]);
uavgup3d_var[(*lu3D)][is][js] = (float)(result->surf->fup2[is][js] * result->surf->fup2[is][js]);
if (sample->Nd > 0) {
for (ip = 0; ip < sample->nstokes; ip++) {
if (escape)
radiance3d_var[(*lu3D)][is][js][ip] =
(float)(result->surf->radesc2[0][is][js][ip] * result->surf->radesc2[0][is][js][ip]);
else
radiance3d_var[(*lu3D)][is][js][ip] =
(float)((result->surf->raddir2[0][is][js][ip] + result->surf->raddif2[0][is][js][ip]) *
(result->surf->raddir2[0][is][js][ip] + result->surf->raddif2[0][is][js][ip]));
}
}
}
} /* for (js=0; is<sample->Ny; ... */
} /* for (is=0; is<sample->Nx; ... */
(*lu3D)++;
}
}
/* ============ Backward */
else {
if (sample->passback3D) {
if (sample->Nd < 1) {
fprintf (stderr, "Fatal error, need at least one radiance direction in backward mode!\n");
fprintf (stderr, "Please inform the programmer!\n");
return -1;
}
for (is = islower; is <= isupper; is += isstep) {
for (js = jslower; js <= jsupper; js += jsstep) {
/* initialize with NAN */
rfldir3d[(*lu3D)][is][js] = 0.0 / 0.0;
rfldn3d[(*lu3D)][is][js] = 0.0 / 0.0;
flup3d[(*lu3D)][is][js] = 0.0 / 0.0;
uavgso3d[(*lu3D)][is][js] = 0.0 / 0.0;
uavgdn3d[(*lu3D)][is][js] = 0.0 / 0.0;
uavgup3d[(*lu3D)][is][js] = 0.0 / 0.0;
if (sample->backward == MCBACKWARD_ABS || sample->backward == MCBACKWARD_ACT)
absback3d[(*lu3D)][is][js] = 0.0 / 0.0;
/* variances */
if (sample->std) {
rfldir3d_var[(*lu3D)][is][js] = 0.0 / 0.0;
rfldn3d_var[(*lu3D)][is][js] = 0.0 / 0.0;
flup3d_var[(*lu3D)][is][js] = 0.0 / 0.0;
uavgso3d_var[(*lu3D)][is][js] = 0.0 / 0.0;
uavgdn3d_var[(*lu3D)][is][js] = 0.0 / 0.0;
uavgup3d_var[(*lu3D)][is][js] = 0.0 / 0.0;
}
/* we want only numbers if something was calculated; otherwise NAN */
if (is >= sample->backward_islower && is <= sample->backward_isupper && js >= sample->backward_jslower &&
js <= sample->backward_jsupper) {
switch (sample->backward) {
case MCBACKWARD_EGLOB:
case MCBACKWARD_EDIR:
rfldir3d[(*lu3D)][is][js] = (float)result->back[is][js][0];
if (sample->std)
rfldir3d_var[(*lu3D)][is][js] = (float)(result->back2[is][js][0] * result->back2[is][js][0]);
if (sample->spectral_is || sample->concentration_is) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
fl3d_is[(*lu3D)][ic][is][js][iv] = (float)result->back_t[ic][is][js][0][iv];
}
}
}
if (sample->jacobian)
for (isp = 1; isp <= atmos->n_caoth; isp++) {
for (ijac = 0; ijac < 2; ijac++) {
for (kc = 0; kc < atmos->Nz; kc++) {
jacobian[(*lu3D)][is][js][isp - 1][ijac][kc] = (float)result->jacobian->jacobian_t[0][isp][ijac][0][0][kc];
}
}
}
if (sample->backward == MCBACKWARD_EDIR)
break;
case MCBACKWARD_EDN:
case MCBACKWARD_EDNPV:
case MCBACKWARD_EXN:
case MCBACKWARD_EYN:
rfldn3d[(*lu3D)][is][js] = (float)result->back[is][js][0];
if (sample->std)
rfldn3d_var[(*lu3D)][is][js] = (float)(result->back2[is][js][0] * result->back2[is][js][0]);
if (sample->spectral_is || sample->concentration_is) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
fl3d_is[(*lu3D)][ic][is][js][iv] = (float)result->back_t[ic][is][js][0][iv];
}
}
}
if (sample->jacobian)
for (isp = 1; isp <= atmos->n_caoth; isp++) {
for (ijac = 0; ijac < 2; ijac++) {
for (kc = 0; kc < atmos->Nz; kc++) {
jacobian[(*lu3D)][is][js][isp - 1][ijac][kc] = (float)result->jacobian->jacobian_t[0][isp][ijac][0][0][kc];
}
}
}
break;
case MCBACKWARD_EUP:
case MCBACKWARD_EXP:
case MCBACKWARD_EYP:
flup3d[(*lu3D)][is][js] = (float)result->back[is][js][0];
if (sample->jacobian)
for (isp = 1; isp <= atmos->n_caoth; isp++) {
for (ijac = 0; ijac < 2; ijac++) {
for (kc = 0; kc < atmos->Nz; kc++) {
jacobian[(*lu3D)][is][js][isp - 1][ijac][kc] = (float)result->jacobian->jacobian_t[0][isp][ijac][0][0][kc];
}
}
}
if (sample->std)
flup3d_var[(*lu3D)][is][js] = (float)(result->back2[is][js][0] * result->back2[is][js][0]);
break;
case MCBACKWARD_FDIR:
uavgso3d[(*lu3D)][is][js] = (float)result->back[is][js][0];
if (sample->std)
uavgso3d_var[(*lu3D)][is][js] = (float)(result->back2[is][js][0] * result->back2[is][js][0]);
break;
case MCBACKWARD_FDN:
uavgdn3d[(*lu3D)][is][js] = (float)result->back[is][js][0];
if (sample->std)
uavgdn3d_var[(*lu3D)][is][js] = (float)(result->back2[is][js][0] * result->back2[is][js][0]);
break;
case MCBACKWARD_FUP:
uavgup3d[(*lu3D)][is][js] = (float)result->back[is][js][0];
if (sample->std)
uavgup3d_var[(*lu3D)][is][js] = (float)(result->back2[is][js][0] * result->back2[is][js][0]);
break;
case MCBACKWARD_ABS:
case MCBACKWARD_ACT:
absback3d[(*lu3D)][is][js] = (float)result->back[is][js][0];
if (sample->std)
absback3d_var[(*lu3D)][is][js] = (float)(result->back2[is][js][0] * result->back2[is][js][0]);
break;
case MCBACKWARD_EMIS:
absback3d[(*lu3D)][is][js] = (float)result->backemis[is][js];
if (sample->std)
absback3d_var[(*lu3D)][is][js] = (float)0.0; /* standard deviation = 0 because analytical */
break;
case MCBACKWARD_HEAT: /* **CK 2013.09.27 */
switch (sample->heat_flag[is][js]) {
case MCBACKWARD_HEAT_EMABS:
case MCBACKWARD_HEAT_EMABSOPT:
absback3d[(*lu3D)][is][js] = (float)result->backemis[is][js] + (float)result->back[is][js][0];
break;
case MCBACKWARD_HEAT_DENET:
absback3d[(*lu3D)][is][js] = (float)result->back[is][js][0];
break;
}
if (sample->std)
absback3d_var[(*lu3D)][is][js] =
(float)(result->back2[is][js][0] *
result->back2[is][js][0]); /* 27.02.2013 **CK **BM: Calculation for thermal heating rates std */
break;
case MCBACKWARD_RADIANCE:
for (ip = 0; ip < sample->nstokes; ip++) {
radiance3d[(*lu3D)][is][js][ip] = (float)result->back[is][js][ip];
if (sample->spectral_is || sample->concentration_is) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
radiance3d_is[(*lu3D)][ic][is][js][ip][iv] = (float)result->back_t[ic][is][js][ip][iv];
}
}
}
if (sample->jacobian) {
for (isp = 1; isp <= atmos->n_caoth; isp++) {
for (ijac = 0; ijac < 2; ijac++) {
for (kc = 0; kc < atmos->Nz; kc++) {
jacobian[(*lu3D)][is][js][isp - 1][ijac][kc] = (float)result->jacobian->jacobian_t[0][isp][ijac][0][0][kc];
}
}
}
}
if (sample->std)
radiance3d_var[(*lu3D)][is][js][ip] = (float)(result->back2[is][js][ip] * result->back2[is][js][ip]);
}
break;
default:
fprintf (stderr, "Error, unknown backward quantity %d\n", sample->backward);
return -1;
}
}
} /* for (js=0; js<sample->Ny; ... */
} /* for (is=0; is<sample->Nx; ... */
(*lu3D)++;
}
}
/* ============ Write Results */
for (kc = 0; kc <= atmos->Nz; kc++) {
if (sample->sample[kc]) {
if (!sample->backward) {
/* no need to consider backward here - there is only one backward */
/* level which has been considered above. */
if (sample->passback3D) {
for (is = 0; is < sample->Nx; is++) {
for (js = 0; js < sample->Ny; js++) {
rfldir3d[(*lu3D)][is][js] = (float)result->alt[kc]->edir[is][js];
rfldn3d[(*lu3D)][is][js] = (float)result->alt[kc]->edn[is][js];
flup3d[(*lu3D)][is][js] = (float)result->alt[kc]->eup[is][js];
uavgso3d[(*lu3D)][is][js] = (float)result->alt[kc]->fdir[is][js];
uavgdn3d[(*lu3D)][is][js] = (float)result->alt[kc]->fdn[is][js];
uavgup3d[(*lu3D)][is][js] = (float)result->alt[kc]->fup[is][js];
for (ip = 0; ip < sample->nstokes; ip++) {
if (sample->Nd > 0) {
if (escape)
radiance3d[(*lu3D)][is][js][ip] = (float)result->alt[kc]->radesc[0][is][js][ip];
else
radiance3d[(*lu3D)][is][js][ip] =
(float)result->alt[kc]->raddir[0][is][js][ip] + (float)result->alt[kc]->raddif[0][is][js][ip];
if (sample->spectral_is || sample->concentration_is) {
for (ic = 0; ic < atmos->Nc; ic++) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
radiance3d_is[(*lu3D)][ic][is][js][ip][iv] = result->rad_t[kc]->rad_t[ic][is][js][ip][iv];
}
}
}
}
}
/* variances */
if (sample->std) {
rfldir3d_var[(*lu3D)][is][js] = (float)(result->alt[kc]->edir2[is][js] * result->alt[kc]->edir2[is][js]);
rfldn3d_var[(*lu3D)][is][js] = (float)(result->alt[kc]->edn2[is][js] * result->alt[kc]->edn2[is][js]);
flup3d_var[(*lu3D)][is][js] = (float)(result->alt[kc]->eup2[is][js] * result->alt[kc]->eup2[is][js]);
uavgso3d_var[(*lu3D)][is][js] = (float)(result->alt[kc]->fdir2[is][js] * result->alt[kc]->fdir2[is][js]);
uavgdn3d_var[(*lu3D)][is][js] = (float)(result->alt[kc]->fdn2[is][js] * result->alt[kc]->fdn2[is][js]);
uavgup3d_var[(*lu3D)][is][js] = (float)(result->alt[kc]->fup2[is][js] * result->alt[kc]->fup2[is][js]);
for (ip = 0; ip < sample->nstokes; ip++) {
if (sample->Nd > 0) {
if (escape)
radiance3d_var[(*lu3D)][is][js][ip] =
(float)(result->alt[kc]->radesc2[0][is][js][ip] * result->alt[kc]->radesc2[0][is][js][ip]);
else
radiance3d_var[(*lu3D)][is][js][ip] =
(float)((result->alt[kc]->raddir2[0][is][js][ip] + result->alt[kc]->raddif2[0][is][js][ip]) *
(result->alt[kc]->raddir2[0][is][js][ip] + result->alt[kc]->raddif2[0][is][js][ip]));
}
}
}
} /* for (js=0; js<sample->Ny; ... */
} /* for (is=0; is<sample->Nx; ... */
(*lu3D)++;
}
}
}
} // end Photons at height levels!
return 0;
}
/***********************************************************************************/
/* Function: summarize_result_alt_rpl @62_30i@ */
/* Description: Altitude RPL */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int summarize_result_altitude_rpl (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
char* basename,
char* rplext,
char* rplext2,
double dmcphotons,
double incident,
int write_files,
int kc) {
int ir = 0, it = 0, id = 0, ip = 0;
double rplfactor = 0.;
char altrplfilename[FILENAME_MAX] = "", altrplfilename2[FILENAME_MAX] = "";
FILE * altrplfile = NULL, *altrplfile2 = NULL;
double avg = 0., var = 0.;
if (sample->Nr > 0 && sample->Nt > 0) {
if (kc != 2)
fprintf (stderr, "KC = %d\n", sample->sample[kc]);
if (write_files) {
sprintf (altrplfilename, "%s%d%s", basename, kc, rplext);
sprintf (altrplfilename2, "%s%d%s", basename, kc, rplext2);
if (sample->Nd > 0)
if ((altrplfile = fopen (altrplfilename, "w")) == NULL) {
print_sr_error_message (altrplfilename);
return -1;
}
if (sample->std)
if (sample->Nd > 0)
if ((altrplfile2 = fopen (altrplfilename2, "w")) == NULL) {
print_sr_error_message (altrplfilename2);
return -1;
}
}
for (ir = 0; ir < sample->Nr; ir++) {
/* area of circular ring */
rplfactor = 1.0 / (PI * sample->dr * sample->dr * (double)(2 * ir + 1)) / incident / (3.0E8 * sample->dt);
for (it = 0; it < sample->Nt; it++) {
for (id = 0; id < sample->Nd; id++) {
for (ip = 0; ip < sample->nstokes; ip++) {
/* calculate average */
result->alt[kc]->radpat[id][ir][it][ip] /= dmcphotons;
result->alt[kc]->radpes[id][ir][it][ip] /= dmcphotons;
/* calculate standard deviation from second moment */
if (sample->std) {
avg = result->alt[kc]->radpat[id][ir][it][ip];
var = result->alt[kc]->radpat2[id][ir][it][ip] / dmcphotons;
result->alt[kc]->radpat2[id][ir][it][ip] = std_noisy (var, avg, dmcphotons);
avg = result->alt[kc]->radpes[id][ir][it][ip];
var = result->alt[kc]->radpes2[id][ir][it][ip] / dmcphotons;
result->alt[kc]->radpes2[id][ir][it][ip] = std_noisy (var, avg, dmcphotons);
/* divide by solid angle to get radiance */
result->alt[kc]->radpat2[id][ir][it][ip] /= sample->rad[id].omega;
result->alt[kc]->radpat2[id][ir][it][ip] *= rplfactor;
result->alt[kc]->radpes2[id][ir][it][ip] /= (4.0 * PI);
result->alt[kc]->radpes2[id][ir][it][ip] *= rplfactor;
}
/* divide by solid angle to get radiance */
result->alt[kc]->radpat[id][ir][it][ip] /= sample->rad[id].omega;
result->alt[kc]->radpat[id][ir][it][ip] *= rplfactor;
result->alt[kc]->radpes[id][ir][it][ip] /= (4.0 * PI);
result->alt[kc]->radpes[id][ir][it][ip] *= rplfactor;
if (write_files) {
fprintf (altrplfile,
"%4d %4d %.6e %.6e %.6e %.6e %.6e %.6e\n",
ir,
it,
sample->rad[id].theta,
sample->rad[id].externalphi,
sample->rad[id].omega,
0.0,
result->alt[kc]->radpat[id][ir][it][ip],
result->alt[kc]->radpes[id][ir][it][ip]);
if (sample->std)
fprintf (altrplfile2,
"%4d %4d %.6e %.6e %.6e %.6e %.6e %.6e\n",
ir,
it,
sample->rad[id].theta,
sample->rad[id].externalphi,
sample->rad[id].omega,
0.0,
result->alt[kc]->radpat2[id][ir][it][ip],
result->alt[kc]->radpes2[id][ir][it][ip]);
}
}
}
}
}
if (write_files) {
if (sample->Nd > 0)
(void)fclose (altrplfile);
if (sample->Nd > 0) {
if (sample->std)
(void)fclose (altrplfile2);
}
}
}
return 0;
}
/***********************************************************************************/
/* Function: summarize_result_absorption @62_30i@ */
/* Description: Absorption */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int summarize_result_absorption (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
float*** abs3d,
float*** abs3d_var,
char* basename,
char* absext,
char* absext2,
double dmcphotons,
double incident,
int write_files,
int absorption) {
int kc = 0, ic = 0, jc = 0;
double tempabs = 0.;
double var = 0., avg = 0.;
FILE * altfile = NULL, *altfile2 = NULL;
char altfilename[FILENAME_MAX] = "", altfilename2[FILENAME_MAX] = "";
/* multiplication factor to consider the area of a single pixel */
/* attention: absorption is defined on the 3D caoth grid, not */
/* the sample grid! */
if (absorption == MCFORWARD_ABS_EMISSION)
tempabs = 1;
else
tempabs = (double)(atmos->Nx * atmos->Ny);
/* photons at altitude levels */
for (kc = 0; kc < atmos->Nz; kc++) {
if (atmos->threed[MCCAOTH_TOT][kc] >= 1) {
if (write_files) {
sprintf (altfilename, "%.*s%d%.6s", FILENAME_MAX - 18, basename, kc, absext);
sprintf (altfilename2, "%.*s%d%.6s", FILENAME_MAX - 18, basename, kc, absext2);
if ((altfile = fopen (altfilename, "w")) == NULL) {
print_sr_error_message (altfilename);
return -1;
}
if (sample->std) {
if ((altfile2 = fopen (altfilename2, "w")) == NULL) {
print_sr_error_message (altfilename2);
return -1;
}
}
}
for (ic = 0; ic < atmos->Nx; ic++) {
for (jc = 0; jc < atmos->Ny; jc++) {
if (absorption != MCFORWARD_ABS_EMISSION) {
/* calculate average */
result->absorption3D->tot[kc][ic][jc] /= dmcphotons;
/* calculate standard deviation from second moment */
if (sample->std) {
avg = result->absorption3D->tot[kc][ic][jc];
var = result->absorption3D2->tot[kc][ic][jc] / dmcphotons;
result->absorption3D2->tot[kc][ic][jc] = std_noisy (var, avg, dmcphotons);
result->absorption3D2->tot[kc][ic][jc] /= incident;
}
}
result->absorption3D->tot[kc][ic][jc] /= incident;
if (absorption == MCFORWARD_ABS_ACTINIC) { /* dann sagt Rolle: */
result->absorption3D->tot[kc][ic][jc] /=
(atmos->kabs3D->prof[MCCAOTH_TOT][kc][ic][jc] * (atmos->Z[kc + 1] - atmos->Z[kc]));
if (sample->std)
result->absorption3D2->tot[kc][ic][jc] /=
(atmos->kabs3D->prof[MCCAOTH_TOT][kc][ic][jc] * (atmos->Z[kc + 1] - atmos->Z[kc]));
}
if (write_files) {
fprintf (altfile,
"%g %g %g\n",
((double)ic + 0.5) * atmos->delX,
((double)jc + 0.5) * atmos->delY,
result->absorption3D->tot[kc][ic][jc] * tempabs);
if (sample->std)
fprintf (altfile2,
"%g %g %g\n",
((double)ic + 0.5) * atmos->delX,
((double)jc + 0.5) * atmos->delY,
result->absorption3D2->tot[kc][ic][jc] * tempabs);
}
}
}
if (write_files) {
(void)fclose (altfile);
if (sample->std)
(void)fclose (altfile2);
}
}
}
/* copy to result array */
if (sample->passback3D) {
for (kc = 0; kc < atmos->Nz; kc++) {
for (ic = 0; ic < atmos->Nx; ic++) {
for (jc = 0; jc < atmos->Ny; jc++) {
if (atmos->threed[MCCAOTH_TOT][kc] >= 1) { /* **CK added bracket */
abs3d[kc][ic][jc] = result->absorption3D->tot[kc][ic][jc] * tempabs;
if (sample->std) { /* **CK added for forward mc_std */
abs3d_var[kc][ic][jc] =
result->absorption3D2->tot[kc][ic][jc] * tempabs * result->absorption3D2->tot[kc][ic][jc] * tempabs;
}
}
}
}
}
}
return 0;
}
/***********************************************************************************/
/* Function: summarize_result_boxairmass @62_30i@ */
/* Description: Outputs box airmass factors */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
int summarize_result_boxairmass (sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
double dmcphotons,
char* basename) {
int is = 0, js = 0, ip = 0, ic = 0, jc = 0, kc = 0;
FILE* airmassfile = NULL;
char airmassfilename[FILENAME_MAX] = "";
strcpy (airmassfilename, basename);
strcat (airmassfilename, ".amf");
int islower = sample->backward_islower;
int isupper = sample->backward_isupper;
int jslower = sample->backward_jslower;
int jsupper = sample->backward_jsupper;
int isstep = sample->backward_isstep;
int jsstep = sample->backward_jsstep;
if ((airmassfile = fopen (airmassfilename, "w")) == NULL) {
perror (NULL);
fprintf (stderr, "errno = %d\n", errno);
fprintf (stderr, "Error opening %s for writing\n", airmassfilename);
return -1;
}
if (sample->backward) {
for (is = islower; is <= isupper; is += isstep) {
for (js = jslower; js <= jsupper; js += jsstep) {
for (ip = 0; ip < sample->nstokes; ip++) {
for (kc = 0; kc < atmos->Nz; kc++) {
if (sample->boxairmass) {
fprintf (airmassfile,
"%d %d %10.3f %10.3e\n",
is,
js,
atmos->Z[kc] / 1000.,
result->pathlength_per_layer_tot[is][js][kc] /
(result->back[is][js][ip] * (atmos->Z[kc + 1] - atmos->Z[kc])));
} else {
for (ic = 0; ic < atmos->Nx; ic++)
for (jc = 0; jc < atmos->Ny; jc++) {
fprintf (airmassfile,
"%d %d %10.3f %10.3f %10.3f %10.3e\n",
is,
js,
atmos->X[ic] / 1000,
atmos->Y[jc] / 1000,
atmos->Z[kc] / 1000.,
result->pathlength_per_box_tot[is][js][ic][jc][kc] /
(result->back[is][js][ip] * (atmos->Z[kc + 1] - atmos->Z[kc])));
}
}
}
}
}
}
}
fclose (airmassfile);
return 0;
}
/***********************************************************************************/
/* Function: reflect @62_30i@ */
/* Description: */
/* Surface reflection. If albedo->reflectalways is set, each photons is reflected */
/* isotropically and the weight is reduced according to the BRDF. Otherwise, */
/* the photon is randomly reflected of not (works only with Lambertian albedo) */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int reflect (photon_struct* p,
albedo_struct* albedo,
elevation_struct* elev,
t_triangular_surface* triangular_surface,
atmosphere_struct* atmos,
sample_struct* sample,
result_struct* result,
float wvnmlo,
float wvnmhi,
float* refind,
int* mcstatus) {
int il = 0, id = 0, isp = 0, status = 0, ic = 0, dolamb = 0;
double mu1 = 0, mu2 = 0, phi1 = 0, phi2 = 0, paw = 0;
double srfc_normal[3] = {0, 0, 1};
double cotheta = 0;
int ia = 0, ja = 0;
photon_struct* p_escape = NULL;
int ie = 0, je = 0;
double nr = 0.0, ni = 0.0, zsurf = 0.0;
*mcstatus = -1; // initialize by default to signal error if we havent found a meaningful to handle it
/* Rotation matrix for transformation of surface in spherical geometry */
#if HAVE_VROOM
double mu = 0.0, mu_ddis = 0.0, phi = 0.0, mu_horz = 0.0, P_norm = 0.0, stheta_ddis = 0.0, cphi_ddis = 0.0;
int DDISsing = MCDDIS_NONE, FODDISsing = 0, out_of_cone = 0;
locest_struct lest;
scadis_struct scadis;
#endif
int i = 0;
double pdir_inc[3];
#ifdef MUCHOUT
double mua = 0.0;
#endif
#if HAVE_LIDAR
int it = 0;
#endif
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON) {
if (p->scattercounter == 0)
fprintf (stderr,
"counters %d %d %d %d --- reflect; satdir: %e %e %e\n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
sample->rad[0].dir.dx[0],
sample->rad[0].dir.dx[1],
sample->rad[0].dir.dx[2]);
fprintf (stderr,
"reflect x %e %e %e i %d %d %d dir %e %e %e spec %e\n",
p->x[0],
p->x[1],
p->x[2],
p->ic,
p->jc,
p->kc,
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2],
p->x[2] - 400.0);
}
#endif
if (sample->polarisation) {
/*Copy incoming direction*/
for (i = 0; i < 3; i++)
pdir_inc[i] = p->dir.dx[i];
}
/* determine coordinates in albedo/BRDF grid */
switch (albedo->method) {
case MCALB_LAM2D:
case MCALB_ROSSLI2D:
case MCALB_LAM2D_SPECTRAL:
case MCALB_RPV2D_SPECTRAL:
case MCALB_AMBRALS2D_SPECTRAL:
if (sample->spherical3D) {
#if HAVE_MYSTIC3D
coord_spherical3D (p, albedo->Nx, albedo->X, albedo->Ny, albedo->Y, 0, NULL, 0, NULL, 0, &ia, &ja, NULL, NULL, 0);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else
albedo_coord (p, albedo, &ia, &ja);
case MCALB_LAM:
case MCALB_RPV:
case MCALB_COXANDMUNK:
case MCALB_HAPKE:
case MCALB_ROSSLI:
case MCALB_TSANG:
break;
default:
fprintf (stderr, "Fatal error, unknown albedo type %d\n", albedo->method);
CHKERR (-1);
}
/* get surface type and use corresponding table */
if (albedo->method == MCALB_RPV2D_SPECTRAL || albedo->method == MCALB_AMBRALS2D_SPECTRAL ||
albedo->method == MCALB_LAM2D_SPECTRAL)
il = albedo->surface_index[ia][ja];
if (sample->ncirc) {
ic = (int)(sqrt ((sample->sensorposition_x[0] - p->x[0]) * (sample->sensorposition_x[0] - p->x[0]) +
(sample->sensorposition_x[1] - p->x[1]) * (sample->sensorposition_x[1] - p->x[1])) /
sample->dcirc);
if (il > 9)
fprintf (stderr, "Increase number of indices lcirc\n");
if (ic < sample->ncirc && il != -1) {
if (p->ncircos > 99) {
fprintf (stderr, "Increase number of ncircos\n");
exit (1);
}
p->tocirco[p->ncircos] = &(result->circcontr[il][ic]);
p->ncircos++;
}
}
/* get albedo from triangular surfaces */
if (p->intersect_triangle_id != -1) {
int ierr = get_triangle_albedo (triangular_surface, p->intersect_triangle_id, &albedo->albedo);
CHKERR (ierr)
} else {
albedo->albedo = albedo->lambertian_albedo; // reset the albedo
}
/* explicit treatment of reflection: photons are */
/* randomly reflected according to the albedo; */
/* if a photon is not reflected, return 0 and */
/* kill the photon immediately afterwards. */
if (!albedo->reflectalways) {
switch (albedo->method) {
case MCALB_LAM2D:
if (!reflection (albedo->albedo2D[ia][ja])) {
*mcstatus = MCSTATUS_ABSORB;
return 0;
}
break;
case MCALB_LAM2D_SPECTRAL:
if (!reflection (albedo->alb_type[(int)albedo->surface_index[ia][ja]])) {
*mcstatus = MCSTATUS_ABSORB;
return 0;
}
break;
case MCALB_LAM:
if (!reflection (albedo->albedo)) {
*mcstatus = MCSTATUS_ABSORB;
return 0;
}
break;
case MCALB_RPV:
case MCALB_RPV2D_SPECTRAL:
case MCALB_AMBRALS2D_SPECTRAL:
case MCALB_COXANDMUNK:
case MCALB_TSANG:
case MCALB_HAPKE:
case MCALB_ROSSLI:
case MCALB_ROSSLI2D:
CHKERROUT (-1, "Error, BRDF only implemented together with reflectalways!");
break;
default:
fprintf (stderr, "Error, albedo->method %d not yet implemented!\n", albedo->method);
CHKERR (-1);
}
}
/* Normal vector from triangular surface */
/* Normal surface vector */
if (p->intersect_triangle_id != -1) {
int ierr = get_triangle_normal (triangular_surface, p->intersect_triangle_id, srfc_normal);
CHKERR (ierr);
// in case that the surface normal indicates the photon comes out of the surface, we switch it,
// assuming that we only handle watertight buildings.
// I.e. surface normal always should point outward from the surface
double mu = vec3_dot_product (srfc_normal, p->dir.dx);
if (mu > 0) {
if (0) { // for debugging purposes, exit if we know that all triangles should only hit with correct orientation
fprintf (stderr,
"id %lu, hit a surface from behind, "
"if you have a watertight surface, this may come from a wrong winding order. "
"normal (%7.4f %7.4f %7.4f) / dir (%7.4f %7.4f %7.4f) -> mu %7.4f\n",
p->intersect_triangle_id,
srfc_normal[0],
srfc_normal[1],
srfc_normal[2],
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2],
mu);
CHKERR (-1);
}
v_neg (srfc_normal);
}
} else {
calc_normal_vector (p,
elev,
sample,
atmos,
1,
0, /* in any case, use elev if present, never use sensordir */
srfc_normal);
}
/* initial photon direction (only used for implicit albedo method) */
status = v_mult_mu (srfc_normal, p->dir.dx, &mu1);
CHKERR (status);
mu1 = -mu1;
phi1 = calc_phi_horz (p->dir.dx, srfc_normal);
/* relative azimuth between incoming photon and wind */
paw = phi1 - albedo->uphi;
/* if solar wind, set paw to zero, is old version */
if (albedo->solar_wind)
paw = 0.0;
if (sample->escape && sample->DoLE && p->scattercounter + 1 >= sample->minscatters &&
p->escapescattercounter <= p->scattercounter + 1) {
if (!p->doling) {
if (il != 0) { /* double reflection from ocean impossible! */
/* copied from escape stuff */
id = sample->Nd;
status = v_mult_mu (srfc_normal, sample->rad[id].dir.dx, &cotheta);
CHKERR (status);
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON) {
fprintf (stderr, "doling part one (reflect): cotheta %e \n", cotheta);
fprintf (stderr, " srfc_normal %e %e %e\n", srfc_normal[0], srfc_normal[1], srfc_normal[2]);
fprintf (stderr,
" raddir %e %e %e\n",
sample->rad[id].dir.dx[0],
sample->rad[id].dir.dx[1],
sample->rad[id].dir.dx[2]);
}
#endif
if (cotheta > 1e-5) { /* quick fix, too small values lead to problems! */
if (sample->refraction) {
CHKERROUT (-1, "Refraction and reflect do not work together!");
}
p_escape = create_escape_photon (p, atmos, sample, id);
/* fprintf(stderr,"direction dole 1: %e %e %e\n",p_escape->dir.dx[0],p_escape->dir.dx[1],p_escape->dir.dx[2]); */
/* very dirty trick: */
p_escape->wtree = p->wtree;
phi2 = calc_phi_horz (sample->rad[id].dir.dx, srfc_normal);
/* no polarization*/
if (!sample->polarisation) {
p_escape->pdir[0] = 4.0 * cotheta *
reflection_probability_tot (albedo,
p_escape,
cotheta,
mu1,
phi2,
phi1,
ia,
ja,
il,
sample->DoLE,
wvnmlo,
wvnmhi,
paw,
sample->spherical3D,
sample->spectral_is,
atmos->nlambda_abs,
&status);
CHKERR (status);
} else {
/* Calculate reflection matrix */
p_escape->pdir[0] = 4.0 * cotheta *
reflection_polarized (albedo,
p_escape,
sample->nstokes,
sample->backward,
p->dir.dx,
sample->rad[id].dir.dx,
srfc_normal,
mu1,
phi1 * PI / 180,
cotheta,
phi2 * PI / 180,
sample->phi_target,
ia,
ja,
il,
wvnmlo,
wvnmhi,
1,
sample->spherical3D,
sample->spectral_is,
atmos->nlambda_abs,
atmos->lambda,
&status);
CHKERR (status);
}
/* jacobian for surface does not make sense */
if (sample->jacobian || sample->LLE_jacobian || sample->jacobian3D)
for (isp = 0; isp < atmos->n_caoth; isp++)
p_escape->lest.pdir_sct[isp][0] = 0.0;
/* do not calculate escape probability */
p_escape->doling = 0; /* skip count escape */
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, 0, il, -1, 1, refind);
CHKERR (status);
/* Call reflect for Fresnel */
/* from photon_journey */
switch (p_escape->photon_status) {
case MCSTATUS_SURFACE:
elev_coord (p_escape, elev, &ie, &je);
zsurf =
elevation (elev->surf[ie][je], p_escape->x[0] - (double)ie * elev->delX, p_escape->x[1] - (double)je * elev->delY);
if (fabs (p_escape->x[2] - zsurf) > MC_EPSILON * elev->surfmax) {
fprintf (stderr, "FATAL error:\n");
fprintf (stderr, "cross_surface() found that photon hit the surface at\n");
fprintf (stderr, "x = %g, y = %g, z = %.10f\n", p->x[0], p->x[1], p->x[2]);
fprintf (stderr, "while the surface elevation at this xy-location\n");
fprintf (stderr, "is actually %.10f.\n", zsurf);
CHKERR (-1);
}
p_escape->x[2] = zsurf;
case MCSTATUS_TRIANGLE_SURFACE:
case MCSTATUS_BOUNDARY_LOWER:
status = reflect (p_escape, albedo, elev, triangular_surface, atmos, sample, result, wvnmlo, wvnmhi, refind, mcstatus);
CHKERR (status);
break;
}
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr, "end doling part one (reflect)\n");
#endif
}
}
} else { /* second part of dole */
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr, "doling?\n");
#endif
if (il == 0) { /* only apply if ocean=CaM */
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr, "doling part two\n");
#endif
/* copied for escape stuff */
id = 0;
status = v_mult_mu (srfc_normal, sample->rad[id].dir.dx, &cotheta);
CHKERR (status);
if (cotheta > 0) {
if (sample->refraction) {
CHKERROUT (-1, "Error! Refraction and reflect do not work together!");
}
p_escape = create_escape_photon (p, atmos, sample, id);
/* very dirty trick: */
p_escape->wtree = p->wtree;
/* change photon direction */
cp_direction (&(p_escape->dir), &(sample->rad[0].dir));
/* fprintf(stderr,"direction dole 2: %e %e %e\n",p->dir.dx[0],p->dir.dx[1],p->dir.dx[2]); */
phi2 = calc_phi_horz (sample->rad[id].dir.dx, srfc_normal);
/* Multiply locest with Fresnel */
index_water (0.5 * 1e4 * (1.0 / wvnmlo + 1.0 / wvnmhi), albedo->xsal, &nr, &ni);
p_escape->pdir[0] *= Fresnel (nr, ni, cotheta);
/* fprintf(stderr,"fresnel %e %e \n",cotheta,Fresnel(nr,ni,cotheta)); */
/* calculate escape probability */
p_escape->doling = 0; /* now do count escape */
if (p_escape->kc < 0)
p_escape->kc = 0;
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, id, il, -1, 1, refind);
CHKERR (status);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
}
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr, "end doling part two\n");
#endif
*mcstatus = 0;
return 0;
}
}
/* calculate probabilities for escape radiance */
if (sample->escape && !(sample->DoLE && il == 0) && p->scattercounter >= sample->minscatters &&
p->escapescattercounter <= p->scattercounter) {
/* calculate probabilities for the radiance angles; */
/* for the case of a Lambertian surface this is very */
/* simple because all directions are equally likely; */
/* in case of a bi-directional reflection function, */
/* the thus introduced angular dependence needs to be */
/* taken into account (as it is done in scattering()) */
for (id = 0; id < sample->Nd; id++) {
status = v_mult_mu (srfc_normal, sample->rad[id].dir.dx, &cotheta);
CHKERR (status);
if (cotheta > 0) {
if (sample->refraction) {
CHKERROUT (-1, "Refraction and reflect do not work together!");
}
p_escape = create_escape_photon (p, atmos, sample, id);
phi2 = calc_phi_horz (sample->rad[id].dir.dx, srfc_normal);
/* no polarization*/
if (!sample->polarisation) {
p_escape->pdir[id] = 4.0 * cotheta *
reflection_probability_tot (albedo,
p_escape,
cotheta,
mu1,
phi2,
phi1,
ia,
ja,
il,
sample->DoLE,
wvnmlo,
wvnmhi,
paw,
sample->spherical3D,
sample->spectral_is,
atmos->nlambda_abs,
&status);
CHKERR (status);
} else {
/* Calculate reflection matrix */
p_escape->pdir[id] = 4.0 * cotheta *
reflection_polarized (albedo,
p_escape,
sample->nstokes,
sample->backward,
p->dir.dx,
sample->rad[id].dir.dx,
srfc_normal,
mu1,
phi1 * PI / 180,
cotheta,
phi2 * PI / 180,
sample->phi_target,
ia,
ja,
il,
wvnmlo,
wvnmhi,
1,
sample->spherical3D,
sample->spectral_is,
atmos->nlambda_abs,
atmos->lambda,
&status);
CHKERR (status);
}
/* jacobian for surface does not make sense */
if (sample->jacobian || sample->LLE_jacobian || sample->jacobian3D)
for (isp = 0; isp < atmos->n_caoth; isp++)
p_escape->lest.pdir_sct[isp][0] = 0.0;
/* calculate escape probability */
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, id, il, -1, 1, refind);
CHKERR (status);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
}
}
#if HAVE_LIDAR
/* Single Local Estimator */
if (sample->LidarLocEst && !sample->DoLE && p->scattercounter >= sample->minscatters &&
p->escapescattercounter <= p->scattercounter) {
status = lidar_detector_kernel (sample->lidar[sample->ili], p->x, &(p->lest));
CHKERR (status);
/* stop immediately if photon passed last range bin */
if (p->pathlength > p->maxpathlength - p->lest.dist) {
p->photon_status = MCSTATUS_PURGE;
*mcstatus = MCSTATUS_PURGE;
return 0;
}
/* test whether local estimate of this scatter can contribute to result */
/* find range bin */
if (sample->LLE_Nt > 0) {
it = locate (sample->lidar_t, sample->LLE_Nt, p->pathlength + p->lest.dist);
if (it >= sample->LLE_Nt || it < 0) {
it = -1;
p->lest.cosalpha = -1.0;
}
} else
it = -1;
/* only if event within opening angle of lidar */
if (sample->lidar[sample->ili].cosalpha[0] <= p->lest.cosalpha) {
/* calculate angle between initial photon direction and lidar direction */
status = v_mult_mu (srfc_normal, p->lest.dir.dx, &cotheta);
CHKERR (status);
if (cotheta > 0) {
p_escape = create_escape_photon (p, atmos, sample, 0);
if (sample->refraction) {
CHKERROUT (-1, "Refraction and reflect do not work together!");
}
phi2 = calc_phi_horz (p_escape->lest.dir.dx, srfc_normal);
/* probability that the photon scatters into the direction of the lidar detector */
if (!sample->polarisation) {
p_escape->lest.pdir = 4.0 * cotheta *
reflection_probability_tot (albedo,
p,
cotheta,
mu1,
phi2,
phi1,
ia,
ja,
il,
sample->DoLE,
wvnmlo,
wvnmhi,
paw,
sample->spherical3D,
sample->spectral_is,
atmos->nlambda_abs,
&status);
CHKERR (status);
} else {
/* Calculate reflection matrix for water surface (Mishchenko code) */
p_escape->lest.pdir = 4.0 * cotheta *
reflection_polarized (albedo,
p,
sample->nstokes,
sample->backward,
p->dir.dx,
p_escape->lest.dir.dx,
srfc_normal,
mu1,
phi1 * PI / 180,
cotheta,
phi2 * PI / 180,
sample->phi_target,
ia,
ja,
il,
wvnmlo,
wvnmhi,
1,
sample->spherical3D,
sample->spectral_is,
atmos->nlambda_abs,
atmos->lambda,
&status);
CHKERR (status);
}
/* assuming that reflection is isoenergetic */
p_escape->lest.pdir_iso = p_escape->lest.pdir;
/* jacobian for surface does not make sense */
if (sample->jacobian || sample->LLE_jacobian || sample->jacobian3D)
for (isp = 0; isp < atmos->n_caoth; isp++)
p_escape->lest.pdir_sct[isp][0] = 0.0;
/* propagate virtual photon to the lidar detector and add contribution to local estimate */
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, 0, il, it, 0, refind);
CHKERR (status);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
}
}
#endif
/********************************************/
/* 3. return in case CP is no longer needed */
/********************************************/
if (p->isclone && p->clonescattercounter + 2 == sample->ntupelLE) { /* n-tupel local estimate */
p->photon_status = MCSTATUS_PURGE;
*mcstatus = MCSTATUS_PURGE;
return 0;
}
#if HAVE_VROOM
/*******************/
/* 4. DDIS stuff 1 */
/*******************/
/* NOTE: Lidar and DDIS and reflection has not been joined completely */
/* what is not yet working: UDA */
/* jacobians */
/* what is working but will evtl. create spikes: */
/* DDIS when Detector slightly above horizon */
/* Latter could be improved by iterative stuff if necessary (RPB,15.1.37) */
if (sample->escape_eps_ddis_upf != 0.0 || sample->LLE_D_DIS) {
status = mc_vroom_prep_DDIS (sample, p, atmos, &DDISsing, &FODDISsing, &out_of_cone, &lest, &scadis);
CHKERR (status);
/* UDA not implemented for reflection */
if (DDISsing == MCDDIS_UDA)
DDISsing = MCDDIS_UPF;
}
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON) {
fprintf (stderr,
"counters %d %d %d %d --- reflect DDIS: muhorz %e mumax %e epsfac %e DDISING %d mumin %e Fmin %e \n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
mu_horz,
scadis.mu_max,
scadis.epsfac,
DDISsing,
scadis.mu_min,
scadis.F_min[0]);
}
#endif
#endif
/******************************/
/* 7. calculate new direction */
/******************************/
#if HAVE_VROOM
if (il == 0 && sample->DoLE) { /* specular reflection */
p->dir.dx[2] = -p->dir.dx[2];
hitflag (&(p->dir));
status = v_mult_mu (p->dir.dx, srfc_normal, &mu_horz);
CHKERR (status);
if (mu_horz < 1e-5) { /* ocean is not horizontal, kill photon */
p->photon_status = MCSTATUS_PURGE;
*mcstatus = MCSTATUS_PURGE;
return 0;
}
/* Multiply photon weight with Fresnel */
index_water (0.5 * 1e4 * (1.0 / wvnmlo + 1.0 / wvnmhi), albedo->xsal, &nr, &ni);
p->weight *= Fresnel (nr, ni, p->dir.dx[2]);
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr,
"specular reflect %e %e %e %e %e\n",
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2],
Fresnel (nr, ni, p->dir.dx[2]),
mu_horz);
#endif
*mcstatus = MCSTATUS_INCREMENT;
return 0;
} else {
/* Lambertian reflection for all except CaM */
dolamb = 1;
switch (albedo->method) {
case MCALB_LAM:
case MCALB_LAM2D:
case MCALB_LAM2D_SPECTRAL:
case MCALB_RPV: /* in this case, il=0, and rpv is saved in il=0! */
case MCALB_HAPKE:
case MCALB_ROSSLI:
break;
case MCALB_TSANG:
case MCALB_COXANDMUNK:
dolamb = 0;
break;
case MCALB_RPV2D_SPECTRAL: /* in these cases, Cox&Munk is in il=0 */
case MCALB_AMBRALS2D_SPECTRAL:
if (il == 0) {
if (sample->DoLE)
CHKERROUT (sample->DoLE, "oceabrdfc 1 should not be called when DoLE");
dolamb = 0;
}
break;
case MCALB_ROSSLI2D:
if (albedo->rossli2D[ia][ja].isCaM) {
if (sample->DoLE)
CHKERROUT (sample->DoLE, "oceabrdfc 2 should not be called when DoLE");
dolamb = 0;
}
break;
default:
fprintf (stderr, "Error, albedo->method %d not yet implemented!\n", albedo->method);
CHKERR (-1);
}
random_reflection_special (sample,
atmos,
elev,
p,
sample->phase_max,
sample->n_phase_max,
&mu,
&phi,
srfc_normal,
&scadis,
lest,
dolamb,
DDISsing,
FODDISsing,
out_of_cone);
}
#else
/* photon is always reflected Lambertian, that is, */
/* with constant intensity in all directions */
random_Lambertian_normal (&(p->dir), srfc_normal);
#endif
/* zero weight -> don't need to trace photon any further */
if (p->weight == 0.) {
p->photon_status = MCSTATUS_PURGE;
*mcstatus = MCSTATUS_PURGE;
return 0;
}
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON) {
status = v_mult_mu (p->dir.dx, sample->rad[0].dir.dx, &mua);
CHKERR (status);
fprintf (stderr,
"counters %d %d %d %d --- intdir: %e %e %e mu %e box %d %d %d\n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2],
mua,
p->ic,
p->jc,
p->kc);
}
#endif
#if HAVE_VROOM
/*******************/
/* 8. DDIS stuff 2 */
/*******************/
if (p->RIS_mode != MCRIS_MODE_NORMAL || /* RIS */
sample->LLE_D_DIS || /* DDIS for LIDAR */
sample->escape_eps_ddis_upf != 0.0 || /* DDIS for escape */
sample->LLE_channels || /* Raman/HSRL */
sample->LLE_jacobian || /* jacobian LIDAR */
atmos->ris_factor != 1.) { /* is RIS-factor used? */
status = v_mult_mu (srfc_normal, p->dir.dx, &mu_horz);
CHKERR (status);
if (sample->LLE_D_DIS || (sample->escape_eps_ddis_upf != 0.0)) {
status = mc_vroom_set_mus_and_phis (sample, p, DDISsing, lest, scadis, &mu, &mu_ddis, &stheta_ddis, phi, &cphi_ddis);
CHKERR (status);
}
/* we do not do jacobians here! this is still missing */
/* For calculating the weight concerning DDIS, we here assume */
/* that the reflection was done lambertian. Further below the */
/* weight is corrected with respect to other albedo types, */
/* which is done with and without DDIS */
if (dolamb)
P_norm = get_Lambertian_phase (mu_horz);
else
/* factor 2.0 because of only upper half of sphere */
P_norm = 2.0;
status = mc_vroom_DDIS_weight_and_prep_stuff (sample,
atmos,
mu_ddis,
stheta_ddis,
cphi_ddis,
DDISsing,
out_of_cone,
P_norm,
P_norm,
P_norm,
lest,
scadis,
p);
CHKERR (status);
}
#endif
/* store new photon direction (only for implicit albedo method) */
/* implicit treatment of reflection: photons are */
/* always reflected Lambertian; afterwards, the */
/* photon weight is reduced according to the */
/* albedo/BRDF */
if (albedo->reflectalways) {
status = v_mult_mu (srfc_normal, p->dir.dx, &mu2);
CHKERR (status);
phi2 = calc_phi_horz (p->dir.dx, srfc_normal);
/* calculate photon weight according to albedo/BRDF (only for implicit albedo method) */
if (!sample->polarisation) {
p->weight *= reflection_probability_tot (albedo,
p,
mu2,
mu1,
phi2,
phi1,
ia,
ja,
il,
sample->DoLE,
wvnmlo,
wvnmhi,
paw,
sample->spherical3D,
sample->spectral_is,
atmos->nlambda_abs,
&status);
CHKERR (status);
} else {
/* Calculate reflection matrix */
p->weight *= reflection_polarized (albedo,
p,
sample->nstokes,
sample->backward,
pdir_inc,
p->dir.dx,
srfc_normal,
mu1,
phi1 * PI / 180,
mu2,
phi2 * PI / 180,
sample->phi_target,
ia,
ja,
il,
wvnmlo,
wvnmhi,
0,
sample->spherical3D,
sample->spectral_is,
atmos->nlambda_abs,
atmos->lambda,
&status);
CHKERR (status);
}
/* in case of isotropic distribution of reflected photons, need factor */
if (!dolamb) /* factor 2.0 because of only upper half of sphere */
p->weight *= get_Lambertian_phase (mu2) / 2.0;
/* zero weight -> don't need to trace photon any further */
if (p->weight == 0) {
p->photon_status = MCSTATUS_PURGE;
*mcstatus = MCSTATUS_PURGE;
return 0;
}
}
/* after surface reflection, photon is no longer direct radiation */
p->direct = 0;
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON) {
status = v_mult_mu (p->dir.dx, sample->rad[0].dir.dx, &mua);
CHKERR (status);
fprintf (stderr,
"counters %d %d %d %d --- newdir: %e %e %e mu %e box %d %d %d weight %e\n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2],
mua,
p->ic,
p->jc,
p->kc,
p->weight);
}
#endif
*mcstatus = MCSTATUS_INCREMENT;
return 0;
}
/***********************************************************************************/
/* Function: calc_phi_horz @62_30i@ */
/* Description: */
/* Calculate phirad from dir */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
double calc_phi_horz (const double* dx, double* n) {
double x = 0.0, y = 0.0, phi = 0.0;
int i = 0, horizontal = 0;
double u[3], v[3];
double u2inv = 0;
if (n == NULL)
horizontal = 1;
else if (n[2] == 1.0)
horizontal = 1;
if (horizontal) {
/* special case, horizontal surface */
x = dx[0];
y = dx[1];
} else {
/********************************/
/* u,v are vectors of length 1; */
/* u,v,dx form a left-handed */
/* orthogonal system */
/* */
/* Part is from new_direction */
/********************************/
u[2] = +sqrt (n[0] * n[0] + n[1] * n[1]);
u2inv = 1. / u[2];
v[0] = -n[1] * u2inv;
v[1] = +n[0] * u2inv;
v[2] = 0.;
u[0] = -n[2] * v[1];
u[1] = +n[2] * v[0];
for (i = 0; i < 3; i++)
x += dx[i] * v[i];
for (i = 0; i < 3; i++)
y += dx[i] * u[i];
}
/* radiance direction */
if (x == 0 && y == 0) /* special case: vertical incidence */
phi = 0.0;
else if (y == 0) { /* special case, 1/dx[1] is infinity */
if (x < 0)
phi = -90.;
else
phi = 90.;
} else
phi = atand (x / y);
if (y < 0)
phi += 180.;
else if (x < 0)
phi += 360.;
return phi;
}
/***********************************************************************************/
/* Function: reflection_probability_tot @62_30i@ */
/* Description: */
/* Calculate the total probability for reflection angle mu = cos(theta). */
/* CE: included spectal albedo weight for ALIS */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static double reflection_probability_tot (albedo_struct* albedo,
photon_struct* p,
double murad,
double mu1,
double phi2,
double phi1,
int ia,
int ja,
int il,
int DoLE,
float wvnmlo,
float wvnmhi,
double paw,
int spherical3D,
int spectral_is,
int nlambda,
int* status) {
*status = 0;
int iv = 0;
double deltaphirad = phi2 - phi1;
double** refl_mat = NULL;
double refl = 0.0, wavelength = 0.0;
if (murad <= 0.0)
return 0.0;
/* calculate probabilities for the radiance angles; */
/* for the case of a Lambertian surface this is very */
/* simple because all directions are equally likely; */
/* in case of a bi-directional reflection function, */
/* the thus introduced angular dependence needs to be */
/* taken into account (as it is done in scattering()) */
if (!(albedo->reflectalways))
return 1.0;
switch (albedo->method) {
case MCALB_LAM:
if (spectral_is && albedo->spectral_albedo != NULL) {
if (albedo->albedo != 0.0) {
for (iv = 0; iv < nlambda; iv++) {
p->q_albedo_spectral[iv] *= albedo->spectral_albedo[iv] / albedo->albedo;
}
}
}
return albedo->albedo;
case MCALB_LAM2D:
return albedo->albedo2D[ia][ja];
case MCALB_LAM2D_SPECTRAL:
if (spectral_is) {
if (albedo->alb_type[(int)albedo->surface_index[ia][ja]] != 0.0) {
for (iv = 0; iv < nlambda; iv++) {
if (spherical3D) {
#if HAVE_MYSTIC3D
coord_spherical3D (p, albedo->Nx, albedo->X, albedo->Ny, albedo->Y, 0, NULL, 0, NULL, 0, &ia, &ja, NULL, NULL, 0);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else
albedo_coord (p, albedo, &ia, &ja);
p->q_albedo_spectral[iv] *= albedo->spectral_alb_type[(int)albedo->surface_index[ia][ja]][iv] /
albedo->alb_type[(int)albedo->surface_index[ia][ja]];
}
}
}
return albedo->alb_type[(int)albedo->surface_index[ia][ja]];
case MCALB_RPV: /* in this case, il=0, and rpv is saved in il=0! */
case MCALB_RPV2D_SPECTRAL: /* in this case, Cox&Munk is in il=0 */
case MCALB_AMBRALS2D_SPECTRAL:
if (il == 0 && (albedo->method == MCALB_RPV2D_SPECTRAL || albedo->method == MCALB_AMBRALS2D_SPECTRAL)) {
/* attention: mu1, murad, deltaphirad are specified differently in oceabrdfc, see also src_f/BDREF.f */
if (DoLE) {
*status = -1;
return err_out ("Error, oceabrdfc 1 should not be called when DoLE is %d\n", DoLE);
}
return oceabrdfc (wvnmlo, wvnmhi, murad, mu1, deltaphirad / 180.0 * PI, albedo->u10, albedo->pcl, albedo->xsal, paw);
} else {
switch (albedo->method) {
case MCALB_RPV:
case MCALB_RPV2D_SPECTRAL:
return rpv_brdf (albedo->rpv[il].rho0,
albedo->rpv[il].k,
albedo->rpv[il].theta,
albedo->rpv[il].scale,
albedo->rpv[il].sigma,
albedo->rpv[il].t1,
albedo->rpv[il].t2,
mu1,
murad,
fabs (deltaphirad));
break;
case MCALB_AMBRALS2D_SPECTRAL:
#if 1
return c_bidir_reflectivity_rossli (&(albedo->ambrals[il]), mu1, murad, fabs (deltaphirad / 180.0 * PI));
#else
// former version
return ambrals_brdf (albedo->ambrals[il].iso,
albedo->ambrals[il].vol,
albedo->ambrals[il].geo,
mu1,
murad,
fabs (deltaphirad));
#endif
break;
default:
fprintf (stderr, "Error, albedo->method %d not yet implemented!\n", albedo->method);
*status = -1;
return NOT_A_NUMBER;
}
}
case MCALB_HAPKE:
return c_bidir_reflectivity_hapke (wvnmlo,
wvnmhi,
mu1,
murad,
fabs (deltaphirad),
albedo->hapke[0].b0,
albedo->hapke[0].h,
albedo->hapke[0].w);
case MCALB_ROSSLI:
#if 1
return c_bidir_reflectivity_rossli (&(albedo->rossli[il]),
mu1,
murad,
fabs (deltaphirad / 180.0 * PI)); // ?????? really il? or rather 0 ??????
#else
// former version
return ambrals_brdf (albedo->rossli[il].iso, albedo->rossli[il].vol, albedo->rossli[il].geo, mu1, murad, fabs (deltaphirad));
#endif
case MCALB_ROSSLI2D:
if (albedo->rossli2D[ia][ja].isCaM) {
/* attention: mu1, murad, deltaphirad are specified differently in oceabrdfc, see also src_f/BDREF.f */
if (DoLE) {
*status = -1;
return err_out ("Error, oceabrdfc 2 should not be called when DoLE is %d\n", DoLE);
}
return oceabrdfc (wvnmlo, wvnmhi, murad, mu1, deltaphirad / 180.0 * PI, albedo->u10, albedo->pcl, albedo->xsal, paw);
} else {
#if 1
return c_bidir_reflectivity_rossli (&(albedo->rossli2D[ia][ja]), mu1, murad, fabs (deltaphirad / 180.0 * PI));
#else
// former version
return ambrals_brdf (albedo->rossli2D[ia][ja].iso,
albedo->rossli2D[ia][ja].vol,
albedo->rossli2D[ia][ja].geo,
mu1,
murad,
fabs (deltaphirad));
#endif
}
case MCALB_COXANDMUNK:
/* attention: mu1, murad, deltaphirad are specified differently in oceabrdfc, see also src_f/BDREF.f */
if (DoLE) {
*status = -1;
return err_out ("Error, oceabrdfc 3 should not be called when DoLE is %d\n", DoLE);
}
return oceabrdfc (wvnmlo, wvnmhi, murad, mu1, deltaphirad / 180.0 * PI, albedo->u10, albedo->pcl, albedo->xsal, paw);
case MCALB_TSANG:
ASCII_calloc_double (&refl_mat, 4, 4);
/* Wavelength in micrometer */
wavelength = 0.5 * 1e4 * (1.0 / wvnmlo + 1.0 / wvnmhi);
/* backward and forward gives the same relf_mat[0][0], */
/* therefore we do not need to distinguish as in get_reflection_probability_matrix */
*status = bpdf_tsang (albedo->u10, wavelength, murad, phi2 * PI / 180., mu1, phi1 * PI / 180., &refl_mat);
refl = refl_mat[0][0];
ASCII_free_double (refl_mat, 4);
return refl;
default:
fprintf (stderr, "Error, albedo->method %d not yet implemented!\n", albedo->method);
*status = -1;
return NOT_A_NUMBER;
}
fprintf (stderr, "Error, something wrong in reflection_probability_tot!\n");
*status = -1;
return NOT_A_NUMBER;
}
/***********************************************************************************/
/* Function: scattering @62_30i@ */
/* Description: */
/* Scattering event (Rayleigh, aerosol, water, ice); pdf defined by the */
/* properties of the current box or layer. */
/* */
/* NOTE: Most steps in this routine are only used in case of LIDAR simulations! */
/* All other calculations only need the steps 1a, 2, (3)*, 5, 6, 7, 9. */
/* Escape can also use DIS: then it further needs steps 4a, 8a, 8c */
/* In case some of the tricks used for Lidar are extended to other methods, */
/* following steps will be needed: */
/* - Real Importance Sampling : step 8c */
/* - Virtual Importance Sampling: step 3 */
/* */
/* * Comment: 3 is also needed for normal mode since random_scatter_type can even */
/* return VIRTUAL in normal mode! This is due to the fact than */
/* 1D profiles are double while 3D profiles are float. */
/* Small discrepancies in the sum of the scatter coefficient can thus */
/* lead to an undefined scatter type in atmospheric layers with both */
/* 1D and 3D media. The probability of such is ca. 0.5e-7. */
/* Within floating point precision, it is safest to ignore the */
/* scattering and let the photon move on. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static int scattering (atmosphere_struct* atmos,
photon_struct* p,
sample_struct* sample,
result_struct* result,
elevation_struct* elev,
albedo_struct* albedo,
t_triangular_surface* triangular_surface,
float wvnmlo,
float wvnmhi,
float* refind,
char* datapath) {
double mu = 0.0, mu2 = 0.0, stheta2 = 0.0, phi = 0.0, cphi2 = 0.0;
int i = 0, j = 0, id = 0, ip = 0, iv = 0;
int ie = 0, je = 0;
double zsurf = 0.0;
int status = 0;
int isp = 0;
photon_struct* p_escape = NULL;
#if HAVE_VROOM
double P_norm = 0.0, P_spec = 0.0, P_isoene = 0.0;
int DDISsing = MCDDIS_NONE, FODDISsing = 0, out_of_cone = 0;
locest_struct lest;
scadis_struct scadis;
#endif
#if HAVE_LIDAR
int it = 0;
int cb_hit = 0;
int within_angle = 0;
double MKn = 0.;
double** Ztemp = NULL;
double mu_save;
#endif
#ifdef MUCHOUT
double mua = 0.0;
#endif
double pdir_inc[3];
double phi_inc = 0.0;
/* six independent elements for randomly oriented particles */
double phase_matrix[6] = {0, 0, 0, 0, 0, 0};
/* Set to 1 if method to calculate total phase matrix for whole atmosphere
should be used (works forward and backward).
Else the Stokes vector is calculated along the photon
path (works only in forward mode).*/
int polmat = 1;
double dir_sensor[3];
if (sample->polarisation) {
/*Copy incoming direction*/
for (i = 0; i < 3; i++)
pdir_inc[i] = p->dir.dx[i];
}
/*************************************************************************/
/* 1. Estimators: Estimate probability that photon contributes to signal */
/*************************************************************************/
/* weight for spectral importance sampling */
/* BCA, ksca_tot in denominator should probably be get_kscaIS!!! XXX */
/* CE: this is not correct when 3D clouds are included, quick fix with passback3D */
if (sample->spectral_is) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
if (atmos->threed[MCCAOTH_TOT][p->kc] >= 1)
p->q_spectral[iv] *=
(get_ksca (atmos, p, MCCAOTH_TOT) - (atmos->ksca[MCSC_MODE_NORMAL][MCRIS_MODE_NORMAL]->prof[MCCAOTH_TOT])[p->kc] +
atmos->ksca_spectral[MCCAOTH_TOT][iv][p->kc]) /
get_ksca (atmos, p, MCCAOTH_TOT);
else
p->q_spectral[iv] *= atmos->ksca_spectral[MCCAOTH_TOT][iv][p->kc] /
(atmos->ksca[MCSC_MODE_NORMAL][MCRIS_MODE_NORMAL]->prof[MCCAOTH_TOT])[p->kc];
/* debugging output */
/* if (1==1) //iv==0) */
/* fprintf(stderr, "kc %d p->q_spectral[iv] %g pathlengths %g %g \n q % g calc: aer %g mol %g,\n ivs tot %g mol %g aer %g \n", p->kc, p->q_spectral[iv], */
/* p->pathlength, p->pathlength_per_layer[p->kc], */
/* atmos->ksca_spectral[MCCAOTH_TOT][iv][p->kc]/ */
/* (atmos->ksca[MCSC_MODE_NORMAL][MCRIS_MODE_NORMAL]->prof [MCCAOTH_TOT])[p->kc], */
/* (atmos->ksca[MCSC_MODE_NORMAL][MCRIS_MODE_NORMAL]->prof [MCCAOTH_AER])[p->kc], */
/* (atmos->ksca[MCSC_MODE_NORMAL][MCRIS_MODE_NORMAL]->prof [MCCAOTH_MOL])[p->kc], */
/* atmos->ksca_spectral[MCCAOTH_TOT][iv][p->kc], atmos->ksca_spectral[MCCAOTH_MOL][iv][p->kc], */
/* atmos->ksca_spectral[MCCAOTH_AER][iv][p->kc]); */
}
}
if (sample->concentration_is) {
for (i = 0; i < atmos->Nc; i++) {
p->q_concentration[i] *=
((atmos->ksca[MCSC_MODE_NORMAL][MCRIS_MODE_NORMAL]->prof[MCCAOTH_TOT])[p->kc] -
(atmos->ksca[MCSC_MODE_NORMAL][MCRIS_MODE_NORMAL]->prof[MCCAOTH_AER])[p->kc] + atmos->ksca_scaled[i][p->kc]) /
(atmos->ksca[MCSC_MODE_NORMAL][MCRIS_MODE_NORMAL]->prof[MCCAOTH_TOT])[p->kc];
/* debugging output */
/* if (i==0) */
/* fprintf(stderr, " p->q_concentration[i] %g kscatot %g ksca_aer %g ksca_scaled %g \n", p->q_concentration[i], */
/* (atmos->ksca[MCSC_MODE_NORMAL][MCRIS_MODE_NORMAL]->prof [MCCAOTH_TOT])[p->kc], */
/* (atmos->ksca[MCSC_MODE_NORMAL][MCRIS_MODE_NORMAL]->prof[MCCAOTH_AER])[p->kc], */
/* atmos->ksca_scaled[i][p->kc]); */
}
}
/***************************************************/
/* 1a. Escape Radiances, aka Directional Estimator */
/***************************************************/
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON) {
if (p->scattercounter == 0 && sample->escape)
fprintf (stderr,
"counters %d %d %d %d --- scatter; satdir: %e %e %e\n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
sample->rad[0].dir.dx[0],
sample->rad[0].dir.dx[1],
sample->rad[0].dir.dx[2]);
if (p->scattercounter == 0 && sample->LidarLocEst)
fprintf (stderr,
"counters %d %d %d %d --- scatter; satdir: %e %e %e\n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
sample->lidar[sample->ili].dir.dx[0],
sample->lidar[sample->ili].dir.dx[1],
sample->lidar[sample->ili].dir.dx[2]);
}
#endif
if (sample->escape && sample->DoLE && p->scattercounter + 1 >= sample->minscatters &&
p->escapescattercounter <= p->scattercounter + 1) {
if (!p->doling) {
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr, "doling part one (scatter)\n");
#endif
/* copied from escape stuff */
id = sample->Nd;
p_escape = create_escape_photon (p, atmos, sample, id);
/* very dirty trick: */
p_escape->wtree = p->wtree;
/* fprintf(stderr,"direction dols 1: %e %e %e\n",p_escape->dir.dx[0],p_escape->dir.dx[1],p_escape->dir.dx[2]); */
if (sample->refraction) {
/* RPB change! I replaced p with p_escape. This should be more correct */
correct_escape_dir_refract (dir_sensor, p_escape, atmos, sample, refind);
status = v_mult_mu (p->dir.dx, dir_sensor, &mu2);
CHKERR (status);
} else {
status = v_mult_mu (p->dir.dx, sample->rad[id].dir.dx, &mu2);
CHKERR (status);
}
status = get_phase_matrix_total (atmos,
p_escape,
mu2,
sample->nphamat,
1,
sample->spectral_is,
sample->concentration_is,
atmos->ris_factor,
0,
phase_matrix,
p_escape->lest.pdir_sct,
NULL,
&(p_escape->weight));
if (status)
return fct_err_out (status, "get_phase_matrix_total", ERROR_POSITION);
id = 0;
p_escape->pdir[id] = phase_matrix[0];
/* Calculate weight vector for the sensor direction */
if (sample->polarisation) {
/* Compute weights of scattered stokes vector */
status = calc_stokes_vector_for_escape (sample,
atmos,
phase_matrix,
mu2,
p->dir,
sample->rad[1].phi + 180.,
sample->rad[1].dir,
polmat,
p_escape);
if (status)
return fct_err_out (status, "calc_stokes_vector_for_escape", ERROR_POSITION);
}
/* do not calculate escape probability */
p_escape->doling = 0; /* skip count escape */
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, 0, -1, -1, 0, refind);
if (status)
return fct_err_out (status, "escape_probability", ERROR_POSITION);
/* Call reflect for Fresnel */
/* from photon_journey */
int reflect_status;
switch (p_escape->photon_status) {
case MCSTATUS_SURFACE:
elev_coord (p_escape, elev, &ie, &je);
zsurf = elevation (elev->surf[ie][je], p_escape->x[0] - (double)ie * elev->delX, p_escape->x[1] - (double)je * elev->delY);
if (fabs (p_escape->x[2] - zsurf) > MC_EPSILON * elev->surfmax) {
fprintf (stderr, "FATAL error:\n");
fprintf (stderr, "cross_surface() found that photon hit the surface at\n");
fprintf (stderr, "x = %g, y = %g, z = %.10f\n", p_escape->x[0], p_escape->x[1], p_escape->x[2]);
fprintf (stderr, "while the surface elevation at this xy-location\n");
fprintf (stderr, "is actually %.10f.\n", zsurf);
return -1;
}
p_escape->x[2] = zsurf;
case MCSTATUS_TRIANGLE_SURFACE:
case MCSTATUS_BOUNDARY_LOWER:
status =
reflect (p_escape, albedo, elev, triangular_surface, atmos, sample, result, wvnmlo, wvnmhi, refind, &reflect_status);
CHKERR (status);
break;
}
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr, "end doling part one (scatter)\n");
#endif
}
}
if (sample->escape && p->scattercounter >= sample->minscatters && p->escapescattercounter <= p->scattercounter) {
/* calculate probabilities for all other radiance angles */
for (id = 0; id < sample->Nd; id++) {
p_escape = create_escape_photon (p, atmos, sample, id);
/* Calculated correct direction in case of refraction */
if (sample->refraction) {
correct_escape_dir_refract (dir_sensor, p, atmos, sample, refind);
/*fprintf(stderr, "dir_sensor %g %g %g \n", dir_sensor[0],
dir_sensor[1], dir_sensor[2]);
fprintf(stderr, "raddir %g %g %g \n", sample->rad[id].dir.dx[0],
sample->rad[id].dir.dx[1], sample->rad[id].dir.dx[2]);
*/
/* calculate angle between photon direction before scattering and radiance direction */
status = v_mult_mu (p->dir.dx, dir_sensor, &mu2);
CHKERR (status);
}
/* calculate angle between photon direction before scattering and radiance direction */
else {
status = v_mult_mu (p->dir.dx, sample->rad[id].dir.dx, &mu2);
CHKERR (status);
}
status = get_phase_matrix_total (atmos,
p_escape,
mu2,
sample->nphamat,
1,
sample->spectral_is,
sample->concentration_is,
atmos->ris_factor,
0,
phase_matrix,
p_escape->lest.pdir_sct,
NULL,
&(p_escape->weight));
if (status)
return fct_err_out (status, "get_phase_matrix_total", ERROR_POSITION);
p_escape->pdir[id] = phase_matrix[0];
/* Jacobian contribution to escape radiance */
if (sample->jacobian || sample->jacobian3D) {
for (isp = 1; isp <= atmos->n_caoth; isp++) {
p_escape->q_jacobian_sca[isp - 1][p->ic][p->jc][p->kc] =
p->q_jacobian_sca[isp - 1][p->ic][p->jc][p->kc] +
p_escape->lest.pdir_sct[isp][0] / get_ksca (atmos, p, isp) / p_escape->pdir[id];
}
}
/* Calculate weight vector for the sensor direction */
if (sample->polarisation) {
/* Compute weights of scattered stokes vector */
status = calc_stokes_vector_for_escape (sample,
atmos,
phase_matrix,
mu2,
p->dir,
sample->rad[id].phi + 180.,
sample->rad[id].dir,
polmat,
p_escape);
if (status)
return fct_err_out (status, "calc_stokes_vector_for_escape", ERROR_POSITION);
}
if (sample->coherent_backscatter)
save_phase_matrix_elements_temp (result->mish, p_escape->phamat, p_escape->scattercounter, phase_matrix);
/* propagate virtual photon in the radiance direction and add contributions to escape */
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, id, -1, -1, 0, refind);
if (status)
return fct_err_out (status, "escape_probability", ERROR_POSITION);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
}
#if HAVE_LIDAR
/***********************/
/* 1b. Local Estimator */
/***********************/
if (sample->LidarLocEst && p->scattercounter >= sample->minscatters && p->escapescattercounter <= p->scattercounter) {
/* EXPERIMENTAL option, leave planar_switch = 0 in cloud3d.c for normal behaviour */
/* use this to simulate planar waves with opening angle = 0 */
/* weight is not correct yet !!! */
/* 0 "spherical waves" (normal case) */
/* 1 transmitter planar waves */
/* 2 detector planar waves */
/* 3 both planar waves */
/* for CB either use 0 or 3 */
if (sample->planar_switch > 1) {
MKn = plane_wave_locest (p, sample);
}
/* choose hit point on detector and derive distance weight */
else {
status = lidar_detector_kernel (sample->lidar[sample->ili], p->x, &(p->lest));
if (status != 0)
return err_out ("Error %d returned by lidar_detector_kernel()\n", status);
}
/* stop immediately if photon passed last range bin */
if (p->pathlength > p->maxpathlength - p->lest.dist) {
p->photon_status = MCSTATUS_PURGE;
return MCSTATUS_PURGE;
}
/* test whether local estimate of this scatter can contribute to result */
/* find range bin */
if (sample->LLE_Nt > 0) {
it = locate (sample->lidar_t, sample->LLE_Nt, p->pathlength + p->lest.dist);
if (it >= sample->LLE_Nt || it < 0) {
it = -1;
p->lest.cosalpha = -1.0;
}
} else
it = -1;
/* only if event within opening angle of lidar */
if (sample->planar_switch < 2 && sample->lidar[sample->ili].cosalpha[0] <= p->lest.cosalpha)
within_angle = 1;
else if (sample->planar_switch > 1 && sample->lidar[sample->ili].radius >= MKn)
within_angle = 1;
if (within_angle == 1) {
p_escape = create_escape_photon (p, atmos, sample, 0);
if (sample->refraction) {
fprintf (stderr, "Error! Refraction and lidar do not work together!\n");
return -1;
}
/* when using CB, first scatter must be in FOV of the detector */
/* and last scatter must be in FOV of the transmitter! */
if (sample->coherent_backscatter && p->scattercounter != 0) {
cb_hit = check_opan_cb (p, p_escape, sample, atmos);
}
/* calculate angle between initial photon direction and lidar direction */
status = v_mult_mu (p->dir.dx, p_escape->lest.dir.dx, &mu2);
CHKERR (status);
/* CB - save second-to-last p->weight */
if (sample->coherent_backscatter)
p_escape->pss.weight_sl = p_escape->weight;
/* probability that the photon scatters into the direction of the lidar detector */
status = get_phase_matrix_total (atmos,
p_escape,
mu2,
sample->nphamat,
1,
sample->spectral_is,
sample->concentration_is,
atmos->ris_factor,
0,
phase_matrix,
p_escape->lest.pdir_sct,
NULL,
&(p_escape->weight));
if (status)
return fct_err_out (status, "get_phase_matrix_total", ERROR_POSITION);
p_escape->lest.pdir = phase_matrix[0];
if (sample->LLE_jacobian) /* for HSRL lidar, evtl. move somewhere else */
p_escape->lest.pdir_iso = p_escape->lest.pdir - p_escape->lest.pdir_sct[MCCAOTH_MOL][0];
/* Calculate weight vector for the sensor direction */
if (sample->polarisation) {
/* Compute weights of scattered stokes vector */
status = calc_stokes_vector_for_escape (sample,
atmos,
phase_matrix,
mu2,
p->dir,
calc_phi_horz (p_escape->lest.dir.dx, NULL),
p_escape->lest.dir, /* evtl +180. */
polmat,
p_escape);
if (status)
return fct_err_out (status, "calc_stokes_vector_for_escape", ERROR_POSITION);
}
/* !!! CB Lidar Main stuff happens here !!! */
if (sample->coherent_backscatter) {
add_coord_to_cohebasca (p_escape);
/* only continue if at least second order of scattering */
if (p_escape->scattercounter > 0 && cb_hit == 1) {
for (i = 0; i < 3; i++)
p_escape->cb.end[i] = p_escape->lest.hitpoint[i];
status = calc_stokes_alt (sample, atmos, p_escape, elev, refind);
if (status)
return fct_err_out (status, "calc_stokes_alt", ERROR_POSITION);
/* only continue if both stokes vectors are > 0 */
if (p_escape->stokes[0] > 0. && p_escape->cb.stokes_alt[0] > 0. &&
p_escape->cb.tausca < 709.) { /* quick fix to prevent inf in lidar.c in certain situations */
if (!sample->nocb_switch) {
calc_stokes_cb (&(p_escape->cb), p_escape->stokes);
result->lidcb->cPLD += 1u;
result->lidcb->meanPLD += p_escape->cb.pld;
}
p_escape->cb.cb = 1;
}
}
}
/* End CB */
/* propagate virtual photon to the lidar detector and add contribution to local estimate */
status = escape_probability (p_escape, atmos, sample, result, elev, triangular_surface, 0, -1, it, 0, refind);
if (status)
return fct_err_out (status, "escape_probability", ERROR_POSITION);
/* free memory */
p->escapepath = p_escape->escapepath;
destroy_photon (p_escape, atmos->n_caoth);
}
}
#endif
/***********************************/
/* 2. determine what is scattering */
/***********************************/
isp = random_scatter_type (atmos, p);
/*******************************/
/* 3. if VIRTUALSCATTER return */
/*******************************/
if (isp == atmos->n_caoth + 1) {
p->photon_status = MCSTATUS_VIRTUALSCATTER;
return MCSTATUS_VIRTUALSCATTER;
}
/* n-tupel local estimate; clone photon no longer needed */
if (p->isclone && p->clonescattercounter + 2 == sample->ntupelLE) {
p->photon_status = MCSTATUS_PURGE;
return MCSTATUS_PURGE;
}
#if HAVE_VROOM
/*******************/
/* 4. DDIS stuff 1 */
/*******************/
if (sample->escape_eps_ddis_upf != 0.0 || sample->LLE_D_DIS) {
status = mc_vroom_prep_DDIS (sample, p, atmos, &DDISsing, &FODDISsing, &out_of_cone, &lest, &scadis);
if (status != 0)
return err_out ("Error %d returned by mc_vroom_prep_DDIS ()\n", status);
}
#endif
/**************************************/
/* 5. Calculate scattering angle: phi */
/**************************************/
#if HAVE_LIDAR
if (FODDISsing)
phi = scadis.d_phi * (2.0 * uvspec_random() - 1.0);
else
/* standard case */
phi = sc_Isotropic_phi();
#else
phi = sc_Isotropic_phi();
#endif
/*************************************/
/* 6. Calculate scattering angle: mu */
/*************************************/
#if HAVE_VROOM
status = mu_scatter_special (atmos, p, sample->phase_max, sample->n_phase_max, isp, &mu, scadis, DDISsing, out_of_cone);
if (status != 0)
return err_out ("Error, mu_scatter_special() returned status %d\n", status);
#else
/* standard case */
status = mu_scatter (atmos, p, isp, &mu);
if (status != 0)
return err_out ("Error, mu_scatter() returned status %d\n", status);
#endif
#if HAVE_LIDAR
mu_save = mu;
if (sample->coherent_backscatter && sample->LidarLocEst) {
result->lidcb->mu_ave += mu;
result->lidcb->mu_counter += 1;
}
#endif
/********************************************/
/* 7. calculate new direction */
/* NOTE: definition of phi is different! */
/********************************************/
/* If polarization is calculated the new direction depends on the incoming phi, */
/* even if the direction of the photon is exactly parallel to the z-axis. */
/* This happens usually at the first scattering, if umu = +-1 (backward) or */
/* phi0=0 (forward)*. If the photon is scattered randomly exactly in z direction, */
/* the plane of polarization will be lost (this is highly unlikely). */
/* first scattering */
if (p->scattercounter == 0)
phi_inc = p->phi0;
else
phi_inc = 0.0;
#if HAVE_VROOM
/****************/
/* 4c. for both */
/****************/
/* save photon direction for later use and turn it into the direction of the cone center if DDIS active */
for (i = 0; i < 3; i++)
scadis.dirold_dx[i] = p->dir.dx[i];
if (DDISsing)
for (i = 0; i < 3; i++)
p->dir.dx[i] = lest.dir.dx[i];
#endif
if (atmos->i_ic[isp] > 0 && atmos->n_raytracing_prop > 0)
new_direction_raytracing (atmos, datapath, mu, phi - 90., &(p->dir), phi_inc, wvnmlo, wvnmhi);
else
new_direction (mu, phi - 90., &(p->dir), phi_inc);
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON) {
if (sample->escape) {
status = v_mult_mu (p->dir.dx, sample->rad[0].dir.dx, &mua);
CHKERR (status);
}
if (sample->LidarLocEst) {
status = v_mult_mu (p->dir.dx, sample->lidar[sample->ili].dir.dx, &mua);
CHKERR (status);
}
fprintf (stderr,
"counters %d %d %d %d --- newdir: %e %e %e mu %e box %d %d %d mu %e phi %e\n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2],
mua,
p->ic,
p->jc,
p->kc,
mu,
phi);
}
#endif
#if HAVE_VROOM
/*******************/
/* 8. DDIS stuff 2 */
/*******************/
if (sample->LLE_D_DIS || (sample->escape_eps_ddis_upf != 0.0)) {
status = mc_vroom_set_mus_and_phis (sample, p, DDISsing, lest, scadis, &mu, &mu2, &stheta2, phi, &cphi2);
if (status != 0)
return err_out ("Error %d returned by mc_vroom_set_mus ()\n", status);
}
if ((p->RIS_mode != MCRIS_MODE_NORMAL) || /* RIS */
sample->LLE_D_DIS || /* DDIS for LIDAR */
sample->escape_eps_ddis_upf != 0.0 || /* DDIS for escape */
sample->LLE_channels || /* Raman/HSRL */
sample->LLE_jacobian || /* jacobian LIDAR */
sample->jacobian || /* jacobian */
sample->jacobian3D || atmos->ris_factor != 1.) { /* is ris-factor used? */
status = mc_vroom_scattering_calc_phases_and_jacobians (sample, p, atmos, mu, 0, &P_norm, &P_spec, &P_isoene);
if (status != 0)
return err_out ("Error %d returned by mc_vroom_scattering_calc_phases_and_jacobians ()\n", status);
status = mc_vroom_DDIS_weight_and_prep_stuff (sample,
atmos,
mu2,
stheta2,
cphi2,
DDISsing,
out_of_cone,
P_norm,
P_spec,
P_isoene,
lest,
scadis,
p);
if (status != 0)
return err_out ("Error %d returned by mc_vroom_weight_and_prep_stuff ()\n", status);
}
#endif
/******************************************************/
/* 9. calculate polarization, Stokes vector weight */
/******************************************************/
if (sample->polarisation) {
if (sample->use_phase_matrix_total) {
/* another version, evtl. better statistics, but a bit slower */
/* the scatter type averaged phase_matrix is used */
status = get_phase_matrix_total (atmos,
p,
mu, /* correct?? */
NPHAMAT,
0,
sample->spectral_is,
sample->concentration_is,
atmos->ris_factor,
0,
phase_matrix,
NULL,
NULL,
&(p->weight));
if (status)
return fct_err_out (status, "get_phase_matrix_total", ERROR_POSITION);
} else {
status = get_phase_matrix_caoth (atmos, p, isp, mu, NPHAMAT, phase_matrix);
if (status != 0)
return fct_err_out (status, "get_phase_matrix_caoth", ERROR_POSITION);
}
/* CB - Chris */
#if HAVE_LIDAR
if (sample->coherent_backscatter && sample->LidarLocEst) {
add_coord_to_cohebasca (p);
result->lidcb->mu_ave += mu_save;
result->lidcb->mu_counter += 1;
if (p->scattercounter == 0)
p->cb.phamfirst = phase_matrix[0];
}
#endif
if (polmat) {
status = phase_matrix_mult (p->phamat,
phase_matrix,
p->dir.dx,
pdir_inc,
p->fw_phi0,
p->fw_phi,
0,
p->scattercounter,
sample->backward);
CHKERR (status);
/* Z*I_0 this weight is only used if photon is counted after this
scattering event, when p->phamat is total phase matrix */
for (ip = 0; ip < 4; ip++) {
p->stokes[ip] = 0.0;
for (j = 0; j < 4; j++)
p->stokes[ip] += p->phamat[ip][j] * p->stokes0[j];
}
#if HAVE_LIDAR
/* CB - get the correct phase matrices for the reverse path */
if (sample->coherent_backscatter && sample->LidarLocEst && p->scattercounter > 0) {
if (p->cb.Zmiddlealt[0][0] == 0.)
for (i = 0; i < 4; i++)
p->cb.Zmiddlealt[i][i] = 1.;
Ztemp = calloc (4, sizeof (double*));
for (i = 0; i < 4; i++)
Ztemp[i] = calloc (4, sizeof (double));
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
Ztemp[i][j] = p->cb.Zmiddlealt[i][j];
status = phase_matrix_mult (Ztemp,
phase_matrix,
p->dir.dx,
pdir_inc,
p->fw_phi0,
p->fw_phi,
0,
p->scattercounter,
1 - sample->backward);
CHKERR (status);
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
p->cb.Zmiddlealt[i][j] = Ztemp[i][j];
for (i = 0; i < 4; i++)
free (Ztemp[i]);
}
#endif
} else {
status = stokes_vector_sca (p->stokes, phase_matrix, p->dir.dx, pdir_inc, p->fw_phi0, p->fw_phi);
CHKERR (status);
}
}
/* This is used when vroom is disabled (scattering type is randomly chosen). With vroom the averaged phase function is used and the jacobian weight is then calculated in function mc_vroom_scattering_calc_phases_and_jacobians in vroom.c.*/
if ((sample->jacobian || sample->jacobian3D) && !(sample->vroom)) {
p->q_jacobian_sca[isp - 1][p->ic][p->jc][p->kc] += 1. / get_ksca (atmos, p, isp);
}
#if HAVE_LIDAR
free (Ztemp);
#endif
p->photon_status = MCSTATUS_INCREMENT;
return MCSTATUS_INCREMENT;
}
/***********************************************************************************/
/* Function: random_scatter_type @62_30i@ */
/* Description: */
/* determine what is scattering */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static inline int random_scatter_type (atmosphere_struct* atmos, photon_struct* p) {
double alpha = 0.0;
double kscaact = 0.0;
int isp = MCCAOTH_NONE;
alpha = uvspec_random() * get_kext (atmos, p);
for (isp = 1; isp <= atmos->n_caoth; isp++) {
kscaact = get_kscaIS (atmos, p, isp);
if (kscaact > alpha)
break;
alpha -= kscaact;
}
return isp;
}
/***********************************************************************************/
/* Function: mu_scatter @62_30i@ */
/* Description: */
/* Return mu for the scattering depending on the scatter type isp */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
int mu_scatter (atmosphere_struct* atmos, photon_struct* p, int isp, double* mu) {
switch (atmos->scatter_type[isp]) {
case MCSCAT_MOL: /* Rayleigh scattering */
p->rayleighcounter++;
*mu = sc_Rayleigh_mu_depol (atmos->rayleigh_depol);
break;
case MCSCAT_AER: /* Aerosol scattering */
/* ??? need to include phase matrix CHECK!!! */
*mu = sc_mu (&(atmos->phase_aer[p->kc]), 1, 0, 0., 0.);
break;
case MCSCAT_HG1:
*mu = sc_HG_mu (get_g1 (atmos, p, isp));
break;
case MCSCAT_HG2:
*mu = sc_HG2_mu (get_g1 (atmos, p, isp), get_g2 (atmos, p, isp), get_ff (atmos, p, isp));
break;
case MCSCAT_PFT:
if (atmos->phase[isp]->n == 1)
*mu = sc_mu (atmos->phase[isp]->iphase[0], 1, p->SC_mode, 0., 0.);
else
*mu = sc_interp_mu (get_reff (atmos, p, isp), atmos->phase[isp], p->SC_mode);
break;
default:
fprintf (stderr, "Error, no such type %d of scattering!!!\n", atmos->scatter_type[isp]);
return -1;
}
return 0;
}
/***********************************************************************************/
/* Function: get_phase_matrix_total @62_30i@ */
/* Description: */
/* Calculate the total probability for scattering angle mu = cos(theta). */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
int get_phase_matrix_total (atmosphere_struct* atmos,
photon_struct* p,
double mu,
int np,
int vismode,
int spectral_is,
int concentration_is,
double ris_factor,
int release,
/* Output */
double* phase_matrix,
double** P_caoth,
double* P_spec,
double* weight) {
int isp = 0, ip = 0, ic = 0;
static double* ksca = NULL;
static double** P_save = NULL;
double norm = 0.0, ksca_special = 0.0;
int rismode = 0;
int status = 0;
/* int iv=0; */
/* set rismode */
if (ris_factor != 1.)
rismode = 1;
if (p != NULL)
if (p->RIS_mode == MCRIS_MODE_MAS)
rismode = 1;
/* this function is called once at end of mystic in order to free memory */
if (release == 1) {
if (ksca != NULL) {
free (ksca);
ksca = NULL;
}
if (P_save != NULL) {
for (isp = 0; isp <= atmos->n_caoth; isp++)
free (P_save[isp]);
free (P_save);
P_save = NULL;
}
return 0.0;
}
/* allocate if first call */
if (ksca == NULL)
ksca = calloc ((size_t)atmos->n_caoth + 1, sizeof (double));
if (P_save == NULL) {
P_save = calloc ((size_t)atmos->n_caoth + 1, sizeof (double*));
for (isp = 0; isp <= atmos->n_caoth; isp++)
P_save[isp] = calloc (NPHAMAT, sizeof (double));
}
/* point P_caoth to local variable if not given by function call */
if (P_caoth == NULL)
P_caoth = P_save;
/* get scattering coefficients for each caoth */
for (isp = 1; isp <= atmos->n_caoth; isp++)
ksca[isp] = get_ksca (atmos, p, isp);
/* normalization */
norm = 1. / get_ksca (atmos, p, MCCAOTH_TOT);
if (vismode == 0)
ksca_special = get_kscaIS (atmos, p, MCCAOTH_TOT);
else
ksca_special = get_kext (atmos, p);
/* need to add to weight!!! */
if (weight != NULL)
*weight /= norm * ksca_special;
/* calculate phase matrix/function for all caoths */
for (isp = 1; isp <= atmos->n_caoth; isp++) {
if (ksca[isp] > 0.0) {
status = get_phase_matrix_caoth (atmos, p, isp, mu, np, P_caoth[isp]);
if (status)
return fct_err_out (status, "get_phase_matrix_caoth", ERROR_POSITION);
}
}
/* P_spec is needed for VROOM */
if (P_spec != NULL)
if (rismode) {
*P_spec = 0.0;
for (isp = 1; isp <= atmos->n_caoth; isp++)
*P_spec += get_kscaIS (atmos, p, isp) * P_caoth[isp][0];
*P_spec /= ksca_special;
}
/* add weight to P_caoth */
for (isp = 1; isp <= atmos->n_caoth; isp++)
for (ip = 0; ip < np; ip++)
P_caoth[isp][ip] *= ksca[isp] * norm;
/* initialize scattering phase matrix */
for (ip = 0; ip < np; ip++)
phase_matrix[ip] = 0.0;
/* add all caoths to scattering phase matrix */
for (isp = 1; isp <= atmos->n_caoth; isp++)
for (ip = 0; ip < np; ip++)
phase_matrix[ip] += P_caoth[isp][ip];
/* save total scattering phase matrix in P_caoth */
for (ip = 0; ip < np; ip++)
P_caoth[MCCAOTH_TOT][ip] = phase_matrix[ip];
/* Weight to correct phase function for ALIS */
/* Uncomment the following if you do not want to neglect it. Caution: CPU time increases by a factor of app. 1.5 !!!! */
/* Also it is not yet clear whether it works with vroom */
/* if (spectral_is){ */
/* for (iv=0; iv<atmos->nlambda_abs; iv++){ */
/* p->q2_spectral[iv]*= */
/* (paer + pcld + pice + */
/* atmos->ksca_spectral[iv][p->kc]*Rayleigh_depol (mu, atmos->rayleigh_depol))/ */
/* (get_ksca (atmos, p, MCCAOTH_TOT) - get_ksca (atmos, p, MCCAOTH_MOL) + atmos->ksca_spectral[iv][p->kc])/ */
/* (( pcld + pice + pmol + paer ) * norm); */
/* } */
/* } */
/* Phase function correction is very important for aerosol concentration importance sampling !!! */
if (concentration_is) {
for (ic = 0; ic < atmos->Nc; ic++) {
/* if ((P_caoth [MCCAOTH_TOT][0] != 0.0) && */
/* (get_ksca (atmos, p, MCCAOTH_TOT)-ksca [MCCAOTH_AER] + atmos->ksca_scaled[ic][p->kc]) !=0.0) { */
if (ksca[MCCAOTH_AER] != 0.0) {
p->q2_concentration[ic] *=
(P_caoth[MCCAOTH_TOT][0] + (-1.0 + atmos->ksca_scaled[ic][p->kc] / ksca[MCCAOTH_AER]) * P_caoth[MCCAOTH_AER][0]) /
P_caoth[MCCAOTH_TOT][0] * get_ksca (atmos, p, MCCAOTH_TOT) /
(get_ksca (atmos, p, MCCAOTH_TOT) - ksca[MCCAOTH_AER] + atmos->ksca_scaled[ic][p->kc]);
}
}
}
if (P_spec != NULL) /* set P_spec for non-special cases */
if (!rismode)
*P_spec = phase_matrix[0];
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON) {
for (isp = 1; isp <= atmos->n_caoth; isp++)
fprintf (stderr,
"counters %d %d %d %d --- caoth %d kscapprof %e norm %e mu %e\n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
isp,
P_caoth[isp][0],
norm,
mu);
}
#endif
return 0;
}
/***********************************************************************************/
/* Function: register_at_start @62_30i@ */
/* Description: */
/* Register a photon at the start of its journey. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int register_at_start (photon_struct* p,
sample_struct* sample,
atmosphere_struct* atmos,
result_struct* result,
int source,
int absorption) {
double* weight; /* Claudia, please tell me this isn't a bug!!! CHECK!!! */
weight = calloc (4, sizeof (double));
weight[0] = 1.0;
switch (source) {
case MCSRC_SOLAR:
if (sample->sample[atmos->Nz])
count_photon (result->alt[atmos->Nz], p, sample, weight, 0, 0);
break;
case MCSRC_THERMAL_SURFACE:
/* count outgoing photon */
/* CE: is outgoing photon polarized?? if yes we may need to change the weight vector. */
/* probably it is not polarized CHECK!!! */
count_photon (result->surf, p, sample, weight, 0, 0);
/* additionally add to altitude profile if sample[0] */
/* is switched on */
/* ??? careful: does not work with 2D elevation!!! ??? CHECK!!! */
if (sample->sample[0])
count_photon (result->alt[0], p, sample, weight, 0, 0);
break;
case MCSRC_THERMAL_BACKWARD: /*TZ bt*/
case MCSRC_THERMAL_ATMOSPHERE:
/* photon is not added to any flux or radiance */
/* counter because it is highly unlikely that */
/* the photon started exactly at a layer */
/* boundary */
/* However, if absorption is MCFORWARD_ABS_HEATING, */
/* we need to subtract the photon from the absorbed */
/* energy (= heating rate) because an emitted */
/* photon acts as cooling */
if (absorption == MCFORWARD_ABS_HEATING)
if (atmos->threed[MCCAOTH_TOT][p->kc] >= 1) {
result->absorption3D->tot[p->kc][p->ic][p->jc] -= 1.0;
if (sample->std)
p->wtree = addtree_stddev (p->wtree, &(result->absorption3D2->tot[p->kc][p->ic][p->jc]), -1.0);
}
break;
case MCSRC_LIDAR:
case MCSRC_BLITZ:
break;
default:
fprintf (stderr, "Error, unknown or unimplemented MC source type\n");
return -1;
}
free (weight);
return 0;
}
#ifdef CLDPRP
/***********************************************************************************/
/* Function: sample_cldprp @62_30i@ */
/* Description: */
/* Sample cloud properties (reff, tau, lwc gradient) along the photon path */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Florian Ewald */
/* @i62_30@ */
/***********************************************************************************/
int sample_cldprp (photon_struct* p, atmosphere_struct* atmos, double step) {
int isp = 0.0;
double tau = 0.0;
double reff = 0.0;
double taubox_wc = 0.0;
double taubox_ic = 0.0;
double reffbox_wc = 0.0;
double reffbox_ic = 0.0;
double rhitbox_wc = 0.0;
double rhitbox_ic = 0.0;
double dxbox_wc = 0.0;
double dxbox_ic = 0.0;
double dybox_wc = 0.0;
double dybox_ic = 0.0;
double dzbox_wc = 0.0;
double dzbox_ic = 0.0;
/* start sampling cloud properties at first cloud contact or continue
sampling when photon had already cloud contact - no sampling if photon
was cloned/scattered before cloud contact, to avoid values for clearsky pixels */
if ((p->isclone == 0 && p->scattercounter == 0) || (p->cldprp.rhit_wc + p->cldprp.rhit_ic) > 0.0) {
/* loop over n profiles to sum up cloud properties in this cloud box */
for (isp = MCCAOTH_FIR; isp <= atmos->n_caoth; isp++) {
if (atmos->i_wc[isp] || atmos->i_ic[isp]) {
/* reset values for every new profile */
reff = 0.0;
tau = 0.0;
/* lookup tau to test if in cloud */
tau = step * (get_ksca (atmos, p, isp) + get_ksca (atmos, p, isp));
/* lookup effective radius in cloud */
reff = get_reff (atmos, p, isp);
if (atmos->i_wc[isp]) {
/* integrate effective radius and tau along tau */
reffbox_wc += tau * reff;
taubox_wc += tau;
/* lookup effective radius for first cloud contact */
if (p->cldprp.rhit_wc == 0.0 || rhitbox_wc)
rhitbox_wc += tau * reff;
/* lookup lwc gradient if photon has been scattered in the cloud for the first time */
if (p->photon_status == MCSTATUS_SCATTER) {
if ((p->cldprp.dxlwc + p->cldprp.dylwc + p->cldprp.dzlwc) == 0 || (dxbox_wc + dybox_wc + dzbox_wc)) {
dxbox_wc = get_dxlwc (atmos, p, isp);
dybox_wc = get_dylwc (atmos, p, isp);
dzbox_wc = get_dzlwc (atmos, p, isp);
}
}
}
if (atmos->i_ic[isp]) {
/* integrate effective radius and tau along tau */
reffbox_ic += tau * reff;
taubox_ic += tau;
/* lookup effective radius for first cloud contact */
if (p->cldprp.rhit_ic == 0.0 || rhitbox_ic)
rhitbox_ic += tau * reff;
/* lookup lwc gradient if photon has been scattered in the cloud for the first time */
if (p->photon_status == MCSTATUS_SCATTER) {
if ((p->cldprp.dxiwc + p->cldprp.dyiwc + p->cldprp.dziwc) == 0 || (dxbox_ic + dybox_ic + dzbox_ic)) {
dxbox_ic += tau * get_dxlwc (atmos, p, isp);
dybox_ic += tau * get_dylwc (atmos, p, isp);
dzbox_ic += tau * get_dzlwc (atmos, p, isp);
}
}
}
}
}
/* sum up the integrated tau for all profiles in this cloud box */
p->cldprp.tau_wc += taubox_wc;
p->cldprp.tau_ic += taubox_ic;
/* sum up the weighted reff for all profiles in this cloud box */
p->cldprp.reff_wc += reffbox_wc;
p->cldprp.reff_ic += reffbox_ic;
/* register effective radius for first cloud contact */
if (taubox_wc)
p->cldprp.rhit_wc = rhitbox_wc / taubox_wc;
if (taubox_ic)
p->cldprp.rhit_ic = rhitbox_ic / taubox_ic;
/* register lwc gradient if photon has been scattered in the cloud for the first time*/
if (dxbox_wc + dybox_wc + dzbox_wc) {
p->cldprp.dxlwc = dxbox_wc / taubox_wc;
p->cldprp.dylwc = dybox_wc / taubox_wc;
p->cldprp.dzlwc = dzbox_wc / taubox_wc;
}
if (dxbox_ic + dybox_ic + dzbox_ic) {
p->cldprp.dxiwc = dxbox_ic / taubox_ic;
p->cldprp.dyiwc = dybox_ic / taubox_ic;
p->cldprp.dziwc = dzbox_ic / taubox_ic;
}
}
return 0;
}
#endif
/***********************************************************************************/
/* Function: travel_tau @62_30i@ */
/* Description: */
/* Travel optical depth tau, or to the next surface or boundary. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
int travel_tau (photon_struct* p,
atmosphere_struct* atmos,
sample_struct* sample,
result_struct* result,
elevation_struct* elev,
t_triangular_surface* triangular_surface,
double tau,
int absorption,
int source,
int photonpath,
int visualize,
float* refind,
int quiet) {
double tausca = 0.0, step = 0.0, gamma = 0.0;
double ksca = 0.0;
int status = 0;
double omegal = 0.0;
double totweight[4];
int is_threed = 0;
int ip = 0, iv = 0, ic = 0;
int intersection_counter = 0;
int need_VIS = 0;
double kscamin = 0.0;
int first = 1;
#if HAVE_LIDAR
int periodic = 0;
int moving_towards_detector = 0, need_preparation = 0, need_action = 0;
struct qidd_struct* qidd;
qidd = calloc ((size_t)1, sizeof (qidd_struct));
qidd->recalc = 1;
need_preparation = (sample->LLE_RIS_MAS || sample->LLE_VIS_QIDD);
#endif
/* initialize status; if unchanged at end of travel step, the photon crosses a grid boundary */
p->photon_status = MCSTATUS_TRAVEL;
#if HAVE_LIDAR
if (need_preparation)
mc_lidar_prepare_travel_tau (sample, p, &moving_towards_detector);
#endif
while (1 == 1) { /* until photon reaches optical depth tau */
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr,
"traveltau x %e %e %e i %d %d %d dir %e %e %e tau %e %e scaco %d weight %e\n",
p->x[0],
p->x[1],
p->x[2],
p->ic,
p->jc,
p->kc,
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2],
tau,
tausca,
p->scattercounter,
p->weight);
#endif
is_threed = (atmos->threed[MCCAOTH_TOT][p->kc] >= 1);
p->RIS_mode = MCRIS_MODE_NORMAL;
p->VIS_mode = MCVIS_MODE_NORMAL;
#if HAVE_LIDAR
periodic = 0;
need_action = (p->lest.will_hit_det_plane || p->lest.will_hit_cone || sample->LLE_VIS_QIDD);
if (source != 99 && need_preparation) {
status = mc_lidar_prepare_travel_tau_step (sample, p, qidd, atmos, tau - tausca, moving_towards_detector);
CHKERR (status);
}
if (sample->RIS_MS && !p->scattercounter)
p->RIS_mode = MCRIS_MODE_MAS;
#endif
/**************************************************************/
/* 1. find out what happens next with photon, and step length */
/**************************************************************/
/* calculate next intersection point with the box boundaries */
if (sample->spherical3D) {
#if HAVE_MYSTIC3D
status = intersection3D_spherical (p, atmos, sample->spherical3D_scene, &first, &step);
CHKERROUT (status, "Error returned by intersection3D_spherical");
#else
CHKERROUT (-1, "Error! you are not allowed to use mystic 3D!");
#endif
} else {
if (is_threed == 1) { /* 3D layer */
#if HAVE_MYSTIC3D
status = intersection3D (p, atmos, tau, tausca, &step);
CHKERROUT (status, "Error returned by intersection3D");
#else
CHKERROUT (-1, "Error! you are not allowed to use mystic 3D!");
#endif
} else {
if (sample->spherical) {
status = intersection1D_spherical (p, atmos, sample->refraction, refind, &step);
if (status < 0) {
fprintf (stderr, "\n");
fprintf (stderr, "*** Warning: Photon absorbed in intersection1D_spherical. \n");
fprintf (stderr, "\n");
p->photon_status = MCSTATUS_OUTOFDOMAIN;
break;
}
} else
intersection1D (p, atmos, tau, tausca, &step, source);
}
}
intersection_counter++;
if (intersection_counter == 100000 && !quiet)
fprintf (stderr, "Warning! Photon passed 100000 intersections, probably it has entered an infinite loop!\n");
#if HAVE_LIDAR
if (need_action) {
status = mc_lidar_travel_tau_action (p, &step, qidd);
if (status == 1)
continue;
}
#endif
if (sample->VIS_CS)
p->vis_beta = 0.0; /* dangerous, might destroy lidar ! */
/* set extinction coefficient */
ksca = get_kext (atmos, p);
/* for thermal backward absorption is included in extinction */
if (source == MCSRC_THERMAL_BACKWARD)
ksca += get_kabs_tot (atmos, p);
/* do some VIS if using VROOM */
if (sample->VIS_CS) {
/* check whether dtau VIS needed */
if (step * ksca < 1.0 && p->p_norm > 10.0) {
/* Check whether box is a spiky one */
if (atmos->threed[MCCAOTH_TOT][p->kc] >= 1)
need_VIS = atmos->spiky_box[p->kc][p->ic][p->jc];
else
need_VIS = atmos->spiky_box[p->kc][0][0];
if (need_VIS) {
kscamin = 0.001 * p->p_norm;
if (kscamin > 1.0)
kscamin = 1.0;
kscamin /= step;
if (ksca < kscamin) {
ksca = kscamin;
p->vis_beta = kscamin;
}
}
}
}
/* passed next scattering point on the way to the box boundary */
if (tausca + step * ksca > tau) {
step = (tau - tausca) / ksca;
p->photon_status = MCSTATUS_SCATTER;
if (source == MCSRC_THERMAL_BACKWARD) {
/* decide whether scattering or absorption happened */
omegal = get_kext (atmos, p) / ksca; /* RPB does not know what RIS or VIS do here! CHECK!!! */
if (sample->spectral_is) {
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
p->q_spectral[iv] = atmos->kabs_spectral[MCCAOTH_TOT][iv][p->kc] / get_kabs_tot (atmos, p);
}
}
if (sample->concentration_is) {
for (ic = 0; ic < atmos->Nc; ic++) {
p->q_concentration[ic] =
(get_kabs_tot (atmos, p) - (atmos->kabs->prof[MCCAOTH_AER])[p->kc] + atmos->kabs_scaled[ic][p->kc]) /
get_kabs_tot (atmos, p);
/* fprintf(stderr, "FIXCE, ic %d, tot %g, aer %g, scaled %g q %g \n", CHECK!!! */
/* ic, get_kabs_tot (atmos, p), (atmos->kabs->prof [MCCAOTH_AER])[p->kc], */
/* atmos->kabs_scaled[ic][p->kc], p->q_concentration[ic]); */
}
}
if (uvspec_random() > omegal) {
p->photon_status = MCSTATUS_ABSORB; /* real absorption reached flag*/
}
}
}
if (step < -MC_EPSILON) {
fprintf (stderr,
"\n!!FATAL error in travel_tau(), step %g < 0 in %dD box (%d, %d, %d).\n",
step,
(is_threed == 1 ? 3 : 1),
p->ic,
p->jc,
p->kc);
fprintf (stderr,
"Start at (%g, %g, %g), direction (%g, %g, %g)\n",
p->x[0],
p->x[1],
p->x[2],
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2]);
fprintf (stderr,
"hit (%d, %d, %d), cotheta %f, status %d\n",
p->dir.hit[0],
p->dir.hit[1],
p->dir.hit[2],
p->dir.cotheta,
p->photon_status);
fprintf (stderr, "tau %e, tausca %e, beta_local %e # of intersections %d\n", tau, tausca, ksca, intersection_counter);
CHKERR (-1);
}
if (step < 0)
step = 0;
/* check if photon crossed the 2D surface */
if (elev->elev2D) {
status = cross_surface (p, step, elev, sample->bcond, &gamma);
/* if cross_surface ran into some inconsistency */
if (status < 0) {
fprintf (stderr, "Something terrible has happened in cross_surface()\n");
CHKERR (status);
}
if (status > 0) {
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr, "crossing surface at \n");
#endif
step = gamma;
p->photon_status = MCSTATUS_SURFACE;
}
}
if (triangular_surface->N_triangles) {
const int ldebug = 0;
// do a look ahead; this is to make sure that triangle intersections
// have precedence over normal mystic steps.
// i.e. shorten the destination by a smidge to prevent numerical issues
// where we could tunnel through the srfc
const double lookahead = 10 * MC_EPSILON;
const double range[2] = {MC_EPSILON, step + lookahead};
const size_t kij[3] = {p->kc, p->ic, p->jc};
double distance_to_srfc;
const int ierr =
cross_triangular_surface (triangular_surface, p->x, p->dir.dx, range, kij, &distance_to_srfc, &(p->intersect_triangle_id));
CHKERR (ierr);
if (p->intersect_triangle_id != -1) // found a intersection with the triangle surface
{
step = MAX (range[0], distance_to_srfc - lookahead);
p->photon_status = MCSTATUS_TRIANGLE_SURFACE;
for (unsigned k = 0; k < 3; ++k)
p->reallyhit[k] = 0;
if (ldebug) {
fprintf (stderr,
"Intersection %i origin (%9.6g %9.6g %9.6g)"
"dir (%6.2f %6.2f %6.2f)"
"range (%6.4f %6.4f) id %lu dist %10.7e\n",
p->photoncounter,
p->x[0],
p->x[1],
p->x[2],
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2],
range[0],
range[1],
p->intersect_triangle_id,
step);
}
}
}
#ifdef CLDPRP
/*******************************************************************/
/* 1b. integration for visible cloud property estimation (F.Ewald) */
/*******************************************************************/
if (sample->cldprp) {
status = sample_cldprp (p, atmos, step);
if (status)
return err_out ("ERROR! sample_cldprp returned status %d\n", status);
}
#endif
/*******************************************************************/
/* 2. apply step length, move photon, and exit if photon path ends */
/*******************************************************************/
/* add absorption to absorption counter */
if (absorption && is_threed == 1) /* 3D layer */
mc_add_absorption_3D (atmos->kabs3D,
atmos->kabs, /* RPB does not know what RIS or VIS do here! CHECK!!! */
p->kc,
p->ic,
p->jc,
step,
exp (-p->tauabs.tot) * p->weight * p->stokes[0],
sample->std,
result->absorption3D,
result->absorption3D2,
&(p->wtree));
/* sum up absorption optical depth */
/* Please, Tobias and Bernhard, look at the following line:*/
if (source !=
MCSRC_THERMAL_BACKWARD) /*TZ bt*/ /* CAUTION! THIS LINE WAS ADDED BY RPB! CHECK WHETHER IT WAS CORRECT TO DO SO! CHECK!!! */
mc_add_optical_depth (atmos, p, step, sample->coherent_backscatter);
/* add step to pathlength */
p->pathlength += step;
#if HAVE_LIDAR
tausca += step * ksca_for_tausca (p, &step, &ksca, qidd);
if (need_action || sample->LLE_jacobian || sample->jacobian || sample->jacobian3D || p->RIS_mode != MCRIS_MODE_NORMAL ||
atmos->ris_factor != 1.)
mc_lidar_travel_tau_addition (atmos, sample, p, &step, qidd, &ksca);
#else
/* update passed add optical depth */
tausca += step * ksca;
#endif
if (sample->spectral_is || sample->jacobian || sample->concentration_is || sample->boxairmass) {
/* original method: */
/* dtauabs_spectral_calc(atmos, p, step); */
p->pathlength_per_layer[p->kc] += step;
} else if (sample->boxairmass3D || sample->jacobian3D) {
//fprintf(stderr, "travel_tau step pathlength_per_box[%d][%d][%d] %f \n", p->ic, p->jc, p->kc, step);
p->pathlength_per_box[p->ic][p->jc][p->kc] += step;
}
/* move photon to box boundary, to next scattering point, */
/* or to the 2D surface */
/* TZ bt: or to absorption point (backward thermal) */
if (is_threed == 1 || sample->spherical3D) { /* 3D layer */
#if HAVE_MYSTIC3D
status = step3D (p, atmos, step, sample->bcond, photonpath, sample->spherical3D, visualize);
#else
CHKERROUT (-1, "Error! you are not allowed to use mystic 3D!");
#endif
} else
status = step1D (p, atmos, step, sample->bcond, photonpath, visualize);
if (status < 0) {
fprintf (stderr, "Error %d returned by step%dD()\n", status, (is_threed == 1 ? 3 : 1));
return status;
}
#if HAVE_LIDAR
if (status == 1)
periodic = 1;
if (need_action)
mc_lidar_travel_special_cases (sample, p, qidd, &ksca, tau - tausca);
/* travelled through periodic boundary condition */
if (periodic == 1 && (sample->LLE_VIS_FOD || sample->LLE_eps_ddis_uda)) {
status = initialize_vis_fod (sample, p);
if (status)
return err_out ("ERROR! initialize_vis_fod returned status %d\n", status);
}
#endif
/* end photon travel unless it simply crosses the boundary or hits the FOV cone */
if (p->photon_status != MCSTATUS_TRAVEL)
break;
/********************************/
/* 3. count photon if necessary */
/********************************/
/* count photon at horizontal boundary */
/* TZ bt: If not backward thermal mode! Then the photons are only */
/* counted once - when absorbed - and not when passing by. */
if (sample->sample[p->kc + (1 - p->dir.hit[2])] && source != MCSRC_THERMAL_BACKWARD) { /*TZ bt*/
if (p->reallyhit[2] || (is_threed == 0)) {
/* count passing photon */
for (ip = 0; ip < sample->nstokes; ip++)
totweight[ip] = p->weight * p->stokes[ip] * exp (-p->tauabs.tot);
count_photon (result->alt[p->kc + (1 - p->dir.hit[2])], p, sample, totweight, 0, 0);
}
}
/**********************************/
/* 4. check if photon leaves grid */
/**********************************/
/* finally check if photon arrived at the lower surface */
/* or at the top of the atmosphere */
if (p->kc < 0) {
p->kc = 0;
/* to avoid roundoff errors */
if (!sample->spherical && !sample->spherical3D) /* This does not work in spherical geometry */
p->x[2] = atmos->Z[p->kc];
p->photon_status = MCSTATUS_BOUNDARY_LOWER;
if (elev->elev2D) {
fprintf (stderr, "FATAL error! Photon reached the 1D boundary in a\n");
fprintf (stderr, " 2D elevation case (%dD layer)!\n", (is_threed == 1 ? 3 : 1));
return -1;
}
break;
}
if (p->kc > atmos->Nz - 1) {
p->kc = atmos->Nz - 1;
/* to avoid roundoff errors */
if (!sample->spherical && !sample->spherical3D) /* This does not work in spherical geometry */
p->x[2] = atmos->Z[p->kc + 1];
p->photon_status = MCSTATUS_BOUNDARY_UPPER;
break;
}
} /* end while loop */
#if HAVE_LIDAR
free (qidd);
#endif
return p->photon_status;
}
/***********************************************************************************/
/* Function: create_escape_photon @62_30i@ */
/* Description: */
/* Create photon needed for the escape probability from actual photon. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static photon_struct* create_escape_photon (photon_struct* photon, atmosphere_struct* atmos, sample_struct* sample, int id) {
photon_struct* p =
calloc_photon (sample, atmos->Nx, atmos->Ny, atmos->Nz, MCSRC_NONE, atmos->nlambda_abs, atmos->Nc, atmos->n_caoth);
/* work on a copy of the photon, not the original one */
cp_photon_struct (p, photon, sample, atmos->n_caoth);
/* the direction to be traced is the radiance direction */
if (sample->escape)
cp_direction (&(p->dir), &(sample->rad[id].dir));
#if HAVE_LIDAR
/* the direction to be traced is the detector/end of backward beam direction */
if (sample->LidarLocEst)
cp_direction (&(p->dir), &(photon->lest.dir));
#endif
return p;
}
/***********************************************************************************/
/* Function: escape_probability @62_30i@ */
/* Description: */
/* Calculate the escape probability to all layers to be sampled. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static int escape_probability (photon_struct* p,
atmosphere_struct* atmos,
sample_struct* sample,
result_struct* result,
elevation_struct* elev,
t_triangular_surface* triangular_surface,
int id,
int il,
int itl,
int surface,
float* refind) {
double step = 0.0, gamma = 0.0, slant2horz = 0.0;
int status = 0;
int is_threed = 0;
int first = 1;
#if HAVE_ALIS
double* totweight_spectral;
double* totweight_concentration;
#endif
double e_r[3], r = 0.0, rlev = 0.0;
double sintheta = 0.0, costheta = 0.0;
#if HAVE_VROOM
int LoWeRR_crit = 0; /* Iwabuchi trick */
double tau = 0.0, tauabs = 0.0;
tau = sample->LE_taucrit;
#endif
if (sample->pan_quicklook && !surface)
p->pdir[id] = 1.0;
/* for spherical 3D, we should check here whether the earth is in the way */
if (sample->spherical3D && !sample->refraction && sample->backward == MCBACKWARD_RADIANCE) {
#if HAVE_MYSTIC3D
cart_to_spher (p->x, p->dir.dx, &r, &costheta, &sintheta, e_r);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
if (costheta < 0) {
/* escape photon is moving downward, check whether it hits earth */
rlev = atmos->Z[0] + atmos->r_earth;
if (sintheta < rlev / r) /* photon will hit earth, do not escape it */
return 0;
}
}
/* initialize status; if unchanged at end of travel step, the photon crosses a grid boundary */
p->photon_status = MCSTATUS_TRAVEL;
p->RIS_mode = MCRIS_MODE_NORMAL;
p->VIS_mode = MCVIS_MODE_NORMAL;
/* ??? need to check this ??? CHECK!!! */
/* special treatment for photons starting at the surface: */
if (surface && sample->escape && !sample->pan_transmittance) {
/* count escaping photon at the surface */
if (!sample->spectral_is && !sample->concentration_is && !sample->boxairmass && !sample->boxairmass3D)
count_escape (p,
sample,
atmos,
result->surf,
id,
il,
0,
NULL,
NULL,
NULL,
NULL,
NULL,
result->surf_t,
p->tauabs.tot,
1.0,
NULL,
NULL,
NULL,
NULL,
result->mish);
/* ????? special treatment for the layer which coincides with the surface; CHECK!!! */
/* e.g. z=0 if no elevation but for safety reasons also z=elevation ... */
/* it may also happen at arbitrary locations in the atmosphere but so */
/* rare that it may be neglected */
} /* endif surface && escape */
/* if vertical component is zero, there will be */
/* no contribution to any level */
if (p->dir.dx[2] == 0 && !sample->spherical && !sample->LidarLocEst)
return 0;
while (1 == 1) { /* until photon reaches the surface or TOA */
is_threed = (atmos->threed[MCCAOTH_TOT][p->kc] >= 1); /* 3D layer */
/**************************************************************/
/* 1. find out what happens next with photon, and step length */
/**************************************************************/
/* calculate next intersection point with the box boundaries */
if (sample->spherical3D) {
#if HAVE_MYSTIC3D
status = intersection3D_spherical (p, atmos, sample->spherical3D_scene, &first, &step);
CHKERROUT (status, "Error returned by intersection3D_spherical");
#else
CHKERROUT (-1, "Error! you are not allowed to use mystic 3D!");
#endif
} else {
if (is_threed == 1) { /* 3D layer */
#if HAVE_MYSTIC3D
status = intersection3D (p, atmos, 10000, 0, &step);
CHKERROUT (status, "Error returned by intersection3D");
#else
CHKERROUT (-1, "Error! you are not allowed to use mystic 3D!");
#endif
} else {
if (sample->spherical) {
status = intersection1D_spherical (p, atmos, sample->refraction, refind, &step);
/* Photon is absorbed by the surface.*/
if (status < 0)
break;
} else {
intersection1D (p, atmos, 10000, 0, &step, 0);
}
}
}
#ifdef MYSTIC_DEBUG
if (step < -MC_EPSILON) {
fprintf (stderr,
"\nFATAL error in escape_probability(), step %g < 0 in %dD box (%d, %d, %d).\n",
step,
(is_threed == 1 ? 3 : 1),
p->ic,
p->jc,
p->kc);
fprintf (stderr,
"Start at (%g, %g, %g), direction (%g, %g, %g)\n",
p->x[0],
p->x[1],
p->x[2],
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2]);
fprintf (stderr, "hit (%d, %d, %d), cotheta %f\n", p->dir.hit[0], p->dir.hit[1], p->dir.hit[2], p->dir.cotheta);
return -1;
}
#endif
if (step < 0)
step = 0;
/* check if photon crossed the 2D surface */
if (elev->elev2D) {
status = cross_surface (p, step, elev, sample->bcond, &gamma);
/* if cross_surface ran into some inconsistency */
if (status < 0) {
fprintf (stderr, "Something terrible has happened! cross_surface() returned\n");
fprintf (stderr, "status %d\n", status);
return -1;
}
if (status > 0) {
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON) {
fprintf (stderr, "escape photon crossing surface at %e %e %e\n", p->x[0], p->x[1], p->x[2]);
// return -1;
}
#endif
step = gamma;
p->photon_status = MCSTATUS_SURFACE;
}
}
if (triangular_surface->N_triangles) // if we have a triangular surface mesh
{
const int ldebug = 0;
// do a look ahead; this is to make sure that triangle intersections
// have precedence over normal steps.
const double lookahead = 10 * MC_EPSILON;
const double range[2] = {MC_EPSILON, step + lookahead};
const size_t kij[3] = {p->kc, p->ic, p->jc};
double distance_to_srfc;
int ierr =
cross_triangular_surface (triangular_surface, p->x, p->dir.dx, range, kij, &distance_to_srfc, &(p->intersect_triangle_id));
CHKERR (ierr);
if (p->intersect_triangle_id != -1) { // found a intersection with the triangle surface
step = MAX (range[0], distance_to_srfc - lookahead);
p->photon_status = MCSTATUS_TRIANGLE_SURFACE;
for (unsigned k = 0; k < 3; ++k)
p->reallyhit[k] = 0;
if (ldebug) {
fprintf (stderr,
"Escape %i Intersection origin (%8.4g %8.4g %8.4g) "
"dir (%6.2f %6.2f %6.2f) "
"range (%6.2f %6.2f) id %lu dist %e\n",
p->photoncounter,
p->x[0],
p->x[1],
p->x[2],
p->dir.dx[0],
p->dir.dx[1],
p->dir.dx[2],
range[0],
range[1],
p->intersect_triangle_id,
distance_to_srfc);
}
}
}
#if HAVE_LIDAR
/* stop if detector / end of backward beam has been reached */
if (sample->LidarLocEst)
if (p->pathlength + step >= p->parent_photon->pathlength + p->parent_photon->lest.dist) {
step = p->parent_photon->pathlength + p->parent_photon->lest.dist - p->pathlength;
p->photon_status = MCSTATUS_HIT_LIDAR;
}
#endif
#ifdef CLDPRP
/*******************************************************************/
/* 1b. integration for visible cloud property estimation (F.Ewald) */
/*******************************************************************/
if (sample->cldprp) {
status = sample_cldprp (p, atmos, step);
if (status)
return err_out ("ERROR! sample_cldprp returned status %d\n", status);
}
#endif
/*******************************************************************/
/* 2. apply step length, move photon, and exit if photon path ends */
/*******************************************************************/
/* sum up absorption and scattering optical depths */
/* step is the escape distance within each box between two box boundaries (or between initital photon position and box boundary) depending on the escape direction */
p->tauabs.tot += step * (get_ksca (atmos, p, MCCAOTH_TOT) + get_kabs_tot (atmos, p));
p->pathlength += step;
if (sample->coherent_backscatter && sample->LidarLocEst)
p->tauext_tot += step * (get_ksca (atmos, p, MCCAOTH_TOT) + get_kabs (atmos, p, MCCAOTH_TOT));
if (sample->spectral_is || sample->concentration_is || sample->boxairmass || sample->jacobian) {
/* dtauabs_spectral_calc(atmos, p, step); */
p->pathlength_per_layer[p->kc] += step;
} else if (sample->boxairmass3D || sample->jacobian3D) {
/* dtauabs_spectral_calc(atmos, p, step); */
//fprintf(stderr, "escape_probability step pathlength_per_box[%d][%d][%d] %f \n", p->ic, p->jc, p->kc, step);
p->pathlength_per_box[p->ic][p->jc][p->kc] += step;
}
#if HAVE_LIDAR
/* calculate Jacobian weight matrix FIJ */
if (sample->LLE_jacobian || sample->jacobian)
p->r_jacobian[p->kc] += step;
#endif
#if HAVE_VROOM
if (sample->LE_taucrit >= 0.0) {
/* Iwabuchi trick */
if (p->tauabs.tot - p->parent_photon->tauabs.tot > tau) {
tau += random_tau();
if (LoWeRR_crit || p->tauabs.tot - p->parent_photon->tauabs.tot > tau) {
p->photon_status = MCSTATUS_PURGE;
return 0;
}
LoWeRR_crit = 1;
}
}
#endif
/* move photon to box boundary, to next scattering point, */
/* or to the 2D surface */
if (is_threed == 1 || sample->spherical3D) { /* 3D layer */
#if HAVE_MYSTIC3D
status = step3D (p, atmos, step, sample->bcond, 0, sample->spherical3D, 0);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else
status = step1D (p, atmos, step, sample->bcond, 0, 0);
if (status < 0) {
fprintf (stderr, "Error %d returned by step%dD()\n", status, (is_threed == 1 ? 3 : 1));
return status;
}
/* end photon travel unless it simply crosses the boundary */
if (p->photon_status != MCSTATUS_TRAVEL)
break;
/********************************/
/* 3. count photon if necessary */
/********************************/
/* register photon at horizontal boundary */
if (sample->sample[p->kc + (1 - p->dir.hit[2])] && sample->escape) {
if (p->reallyhit[2] || (is_threed == 0)) {
if (LoWeRR_crit)
tauabs = p->parent_photon->tauabs.tot + sample->LE_taucrit;
else
tauabs = p->tauabs.tot;
if (sample->spectral_is || sample->concentration_is) {
#if HAVE_ALIS
totweight_spectral = calloc (atmos->nlambda_abs, sizeof (double));
totweight_concentration = calloc (atmos->Nc, sizeof (double));
totweight_spectral[0] = 1.0;
totweight_concentration[0] = 1.0;
if (sample->spectral_is)
spectral_is_weight (&totweight_spectral, p, p->parent_photon, atmos);
if (sample->concentration_is)
concentration_is_weight (&totweight_concentration, p, p->parent_photon, atmos);
count_escape (p,
sample,
atmos,
result->alt[p->kc + (1 - p->dir.hit[2])],
id,
il,
sample->backward,
result->back,
result->back2,
result->back_t,
result->circcontr,
result->jacobian,
result->rad_t[p->kc + (1 - p->dir.hit[2])],
tauabs,
1.0,
totweight_spectral,
totweight_concentration,
result->pathlength_per_layer_tot,
result->pathlength_per_box_tot,
result->mish);
free (totweight_spectral);
free (totweight_concentration);
#endif
} else {
if (!p->doling)
count_escape (p,
sample,
atmos,
result->alt[p->kc + (1 - p->dir.hit[2])],
id,
il,
sample->backward,
result->back,
result->back2,
result->back_t,
result->circcontr,
result->jacobian,
NULL,
tauabs,
1.0,
NULL,
NULL,
result->pathlength_per_layer_tot,
result->pathlength_per_box_tot,
result->mish);
}
}
}
/**********************************/
/* 4. check if photon leaves grid */
/**********************************/
/* finally check if photon arrived at the lower surface */
/* or at the top of the atmosphere */
if (p->kc < 0) {
p->photon_status = MCSTATUS_BOUNDARY_LOWER;
if (elev->elev2D) {
fprintf (stderr, "FATAL error! Escape photon reached the 1D boundary in a\n");
fprintf (stderr, " 2D elevation case (%dD layer)!\n\n", (is_threed == 1 ? 3 : 1));
return -1;
}
break;
}
if (p->kc > atmos->Nz - 1) {
p->photon_status = MCSTATUS_BOUNDARY_UPPER;
break;
}
}
/* end step loop */
#if HAVE_LIDAR
/**********************************************************************/
/* 5. if lidar photon has not yet reached satellite detector, move it */
/**********************************************************************/
if (sample->LidarLocEst && p->photon_status == MCSTATUS_BOUNDARY_UPPER) {
p->pathlength = p->parent_photon->pathlength + p->parent_photon->lest.dist;
p->photon_status = MCSTATUS_HIT_LIDAR;
/* we do not need to change the photon position, it is no longer needed */
}
#endif
/******************************************/
/* 6. count photon at ground and in lidar */
/******************************************/
/* register photon at the lower boundary */
if (sample->escape) {
if (p->photon_status == MCSTATUS_BOUNDARY_LOWER || p->photon_status == MCSTATUS_SURFACE) {
/* conversion factor to correct for slant surface */
slant2horz = slt2hrz (elev, p, sample->surfaceparallel, 1);
if (slant2horz < 0.0)
return fct_err_out (-1, "slt2hrz", ERROR_POSITION);
if (LoWeRR_crit)
tauabs = p->parent_photon->tauabs.tot + sample->LE_taucrit;
else
tauabs = p->tauabs.tot;
if (!sample->spectral_is && !sample->concentration_is && !sample->boxairmass && !sample->boxairmass3D) {
if (!sample->pan_transmittance)
count_escape (p,
sample,
atmos,
result->surf,
id,
il,
0,
NULL,
NULL,
NULL,
NULL,
NULL,
result->surf_t,
tauabs,
slant2horz,
NULL,
NULL,
result->pathlength_per_layer_tot,
result->pathlength_per_box_tot,
result->mish);
else
count_escape (p,
sample,
atmos,
result->surf,
id,
il,
sample->backward,
result->back,
result->back2,
result->back_t,
result->circcontr,
result->jacobian,
result->surf_t,
tauabs,
1.0,
NULL,
NULL,
result->pathlength_per_layer_tot,
result->pathlength_per_box_tot,
result->mish);
}
}
}
#if HAVE_LIDAR
/* register local estimate */
if (itl != -1) {
status = mc_lidar_locest (result, sample, atmos, p, itl, LoWeRR_crit);
if (status != 0)
return err_out ("Error %d returned by mc_lidar_locest()\n", status);
}
#endif
return 0;
}
/***********************************************************************************/
/* Function: count_escape @62_30i@ */
/* Description: */
/* Count the escape probability at the actual layer. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: put into function by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static void count_escape (photon_struct* p,
sample_struct* sample,
atmosphere_struct* atmos,
radiation_field* result_alt,
int id,
int il,
int backward,
double*** result_back,
double*** result_back2,
double***** result_back_t,
double** circcontr,
jacobian_result_field* jacobian,
radiation_field_t* result_rad_t,
double tauabs,
double slant2horz,
double* totweight_spectral,
double* totweight_concentration,
double*** pathlength_per_layer_tot,
double***** pathlength_per_box_tot,
mishchenko_cb_struct* mish) {
int is = 0, js = 0, ip = 0, ir = 0, it = 0, iv = 0, ic = 0;
int isp = 0, kc = 0, jc = 0;
double totweight = 0.0, add = 0.0, add_abs = 0.0, add_sca = 0.0;
/* count passing photon */
sample_coord (p, sample, &is, &js);
totweight = exp (-tauabs) * p->pdir[id] * p->weight / p->dir.cotheta;
if (sample->coherent_backscatter && !sample->LidarLocEst)
save_phase_matrix_elements (mish, totweight, p->scattercounter, p->stokes0);
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON)
fprintf (stderr,
"counters %d %d %d %d --- escape: add %e pdir %e pweight %e abs %e stokes %e cos %e\n",
p->scattercounter,
p->escapescattercounter,
p->clonescattercounter,
p->SC_mode,
totweight * p->stokes[0],
p->pdir[id],
p->weight,
exp (-tauabs),
p->stokes[0],
p->dir.cotheta);
#endif
#ifdef CLDPRP
if (sample->cldprp) {
if (p->rayleighcounter == 0 || (p->cldprp.rhit_wc + p->cldprp.rhit_ic) > 0.0) {
result_alt->cldprp.reff_wc[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.reff_wc;
result_alt->cldprp.reff_ic[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.reff_ic;
result_alt->cldprp.rhit_wc[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.rhit_wc;
result_alt->cldprp.rhit_ic[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.rhit_ic;
result_alt->cldprp.tau_wc[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.tau_wc;
result_alt->cldprp.tau_ic[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.tau_ic;
result_alt->cldprp.dxlwc[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.dxlwc;
result_alt->cldprp.dylwc[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.dylwc;
result_alt->cldprp.dzlwc[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.dzlwc;
result_alt->cldprp.dxiwc[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.dxiwc;
result_alt->cldprp.dyiwc[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.dyiwc;
result_alt->cldprp.dziwc[sample->backward_is][sample->backward_js] += totweight * p->stokes[0] * p->cldprp.dziwc;
result_alt->cldprp.totweights[sample->backward_is][sample->backward_js] += totweight * p->stokes[0];
if (p->cldprp.rhit_wc > 0.0)
result_alt->cldprp.wc_weights[sample->backward_is][sample->backward_js] += totweight * p->stokes[0];
if (p->cldprp.rhit_ic > 0.0)
result_alt->cldprp.ic_weights[sample->backward_is][sample->backward_js] += totweight * p->stokes[0];
}
}
#endif
for (ip = 0; ip < sample->nstokes; ip++) {
/* fprintf(stderr, "nstokes %d, p->stokes[%d] %g \n", sample->nstokes, ip, p->stokes[ip]); */
add = totweight * p->stokes[ip];
result_alt->radesc[id][is][js][ip] += add; /* RADESC */
#ifdef PRINT_ESCAPE_CONTRIBUTIONS
/* add photon to photon path */
// fprintf(stdout, "counter: %d %d %d %d", p->scattercounter,p->escapescattercounter,p->clonescattercounter,p->SC_mode);
//Paul Ockenfuss: Print parent photon position, i.e. where the escape was started
add_to_photonpath (&(p->escapepath), p->parent_photon->x, add);
//Print where the escape ended (top of atmosphere)
// add_to_photonpath (&(p->escapepath), p->x, add);
#endif
if (sample->boxairmass) {
for (kc = 0; kc < atmos->Nz; kc++)
pathlength_per_layer_tot[sample->backward_is][sample->backward_js][kc] += add * p->pathlength_per_layer[kc];
} else if (sample->boxairmass3D) {
for (ic = 0; ic < atmos->Nx; ic++)
for (jc = 0; jc < atmos->Ny; jc++)
for (kc = 0; kc < atmos->Nz; kc++)
pathlength_per_box_tot[sample->backward_is][sample->backward_js][ic][jc][kc] += add * p->pathlength_per_box[ic][jc][kc];
}
if (sample->spectral_is || sample->concentration_is) {
for (ic = 0; ic < atmos->Nc; ic++)
for (iv = 0; iv < atmos->nlambda_abs; iv++)
result_rad_t->rad_t[ic][is][js][ip][iv] += add * totweight_spectral[iv] * totweight_concentration[ic];
}
if (sample->std)
p->parent_photon->wtree = addtree_stddev (p->parent_photon->wtree, &(result_alt->radesc2[id][is][js][ip]), add);
if (backward) {
result_back[sample->backward_is][sample->backward_js][ip] += add;
if (sample->spectral_is || sample->concentration_is)
for (ic = 0; ic < atmos->Nc; ic++)
for (iv = 0; iv < atmos->nlambda_abs; iv++) {
/* fprintf(stderr, "count_escape %f is %f %f %f \n", result_back[sample->backward_is][sample->backward_js][ip], result_back_t[ic][sample->backward_is][sample->backward_js][ip][iv], totweight_spectral[iv], totweight_concentration[ic]); */
result_back_t[ic][sample->backward_is][sample->backward_js][ip][iv] +=
add * totweight_spectral[iv] * totweight_concentration[ic];
}
if (sample->ncirc) {
for (ic = 0; ic < p->parent_photon->ncircos; ic++)
*(p->parent_photon->tocirco[ic]) += add;
}
if (sample->std)
p->parent_photon->wtree =
addtree_stddev (p->parent_photon->wtree, &(result_back2[sample->backward_is][sample->backward_js][ip]), add);
}
if (sample->Nr > 0 && sample->Nt > 0)
if (sample_radius (p, sample, &ir))
if (sample_time (p, sample, &it)) {
result_alt->radpes[id][ir][it][ip] += add; /* radial/pathlength */
if (sample->std)
p->parent_photon->wtree = addtree_stddev (p->parent_photon->wtree, &(result_alt->radpes2[id][ir][it][ip]), add);
}
/* Jacobians, new implementation by Claudia (April 2019) */
if (backward && (sample->jacobian || sample->jacobian3D)) {
for (ic = 0; ic < atmos->Nx; ic++) {
for (jc = 0; jc < atmos->Ny; jc++) {
for (kc = 0; kc < atmos->Nz; kc++) {
/* for (ip = 0; ip < sample->nstokes; ip++){ */
/* absorption, not dependent on species */
if (sample->jacobian)
add_abs = totweight * p->stokes[ip] * -p->pathlength_per_layer[kc];
else if (sample->jacobian3D)
add_abs = totweight * p->stokes[ip] * -p->pathlength_per_box[ic][jc][kc];
/* fprintf(stderr, "count escape ip %d isp %d var %d ic %d jc %d kc %d \n", */
/* ip, isp, 0, ic, jc, kc); */
jacobian->jacobian_t[ip][1][MC_JAC_VAR_ABS][ic][jc][kc] += add_abs;
for (isp = 1; isp <= atmos->n_caoth; isp++) {
/* scattering */
if (sample->jacobian)
add_sca = totweight * p->stokes[ip] * (-p->pathlength_per_layer[kc] + p->q_jacobian_sca[isp - 1][0][0][kc]);
else if (sample->jacobian3D)
add_sca = totweight * p->stokes[ip] * (-p->pathlength_per_box[ic][jc][kc] + p->q_jacobian_sca[isp - 1][ic][jc][kc]);
jacobian->jacobian_t[ip][isp][MC_JAC_VAR_BETA][ic][jc][kc] += add_sca;
/* if (sample->std) { */
/* p->parent_photon->wtree = */
/* addtree_stddev (p->parent_photon->wtree, &(jacobian->jacobian_t2[ip][isp][MC_JAC_VAR_ABS][ic][jc][kc]), add_abs); */
/* p->parent_photon->wtree = */
/* addtree_stddev (p->parent_photon->wtree, &(jacobian->jacobian_t2[ip][isp][MC_JAC_VAR_BETA][ic][jc][kc]), add_sca); */
/* } */
}
}
}
}
}
}
}
/***********************************************************************************/
/* Function: rpv_brdf @62_30i@ */
/* Description: BRDF calculatation according to Rahman, Verstraete, */
/* and Pinty [1993]; attention: a factor 1/PI is added which */
/* translates from "biconical reflectance factor" to BRDF; this */
/* is different from Frank Evans' rpv_reflection.f which was used as */
/* a basis for rpv_brdf(); also different from Frank Evans' code */
/* is the hot spot occurring at phi=180 degree: Reflection into the */
/* hot spot direction implies a 180 degree azimuth change! */
/* Tested behaviour (March 1, 2004): radiances correct for both */
/* cone sampling and escape radiance. */
/* Lately implemented snow stuff from Meerkötter et al. (RPB) */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: last change by RPB */
/* @i62_30@ */
/***********************************************************************************/
double rpv_brdf (double rho0,
double k,
double theta,
double scale,
double sigma,
double t1,
double t2,
double mu1,
double mu2,
double phi) {
/* Local variables */
double capg = 0, cosg = 0, f = 0, h = 0, m = 0, t = 0;
double alpha = 0;
double result = 0;
phi = 180.0 - phi;
/* hot spot */
if (phi == 0 && mu1 == mu2) /* special case (might cause numerical troubles) */
return rho0 *
(pow (2.0 * mu1 * mu1 * mu1, k - 1.0) * (1.0 - theta) / (1.0 + theta) / (1.0 + theta) * (2.0 - rho0) + sigma / mu1) *
(t1 * exp (PI * t2) + 1.0) * scale;
m = pow (mu1 * mu2 * (mu1 + mu2), k - 1.0);
if (mu1 < 1.0 && mu2 < 1.0)
alpha = sqrt ((1.0 - mu1 * mu1) * (1.0 - mu2 * mu2)) * cosd (phi);
else
alpha = 0;
cosg = mu1 * mu2 + alpha;
f = (1.0 - theta * theta) / pow (1.0 + 2.0 * theta * cosg + theta * theta, 1.5);
capg = sqrt (1.0 / mu1 / mu1 + 1.0 / mu2 / mu2 - 2.0 - 2.0 * alpha / mu1 / mu2);
h = 1.0 + (1.0 - rho0) / (1.0 + capg);
t = 1.0 + t1 * exp (t2 * (PI - acos (cosg)));
result = rho0 * (m * f * h + sigma / mu1) * t * scale;
if (result < 0)
result = 0;
return result;
}
/***********************************************************************************/
/* Function: equal @62_30i@ */
/* Description: */
/* Two numbers equal? */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int equal (double x, double y) {
if ((float)x != (float)y)
return 0;
return 1;
}
/***********************************************************************************/
/* Function: sample_coord @62_30i@ */
/* Description: */
/* Determine sample coordinates of a photon. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static inline void sample_coord (photon_struct* p, sample_struct* sample, int* is, int* js) {
/* dummy for spherical3D and panorama; actually, this function should never be called! Clean up! */
if (sample->spherical3D || sample->panorama) {
*is = 0;
*js = 0;
return;
}
/* determine sample coordinates */
*is = (int)(p->x[0] / sample->delX);
*js = (int)(p->x[1] / sample->delY);
/* check boundaries */
if (*is < 0) {
fprintf (stderr, "OOPS, set sample coordinate is from %d to %d (you may still trust your result?)\n", *is, 0);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*is = 0;
}
if (*is >= sample->Nx) {
fprintf (stderr, "OOPS, set sample coordinate is from %d to %d (you may still trust your result?)\n", *is, sample->Nx - 1);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*is = sample->Nx - 1;
}
if (*js < 0) {
fprintf (stderr, "OOPS, set sample coordinate js from %d to %d (you may still trust your result?)\n", *js, 0);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*js = 0;
}
if (*js >= sample->Ny) {
fprintf (stderr, "OOPS, set sample coordinate js from %d to %d (you may still trust your result?)\n", *js, sample->Ny - 1);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*js = sample->Ny - 1;
}
}
/***********************************************************************************/
/* Function: sample_radius @62_30i@ */
/* Description: */
/* Determine radial coordinate of a photon. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int sample_radius (photon_struct* p, sample_struct* sample, int* ir) {
/* determine sample radial coordinate */
double dx = p->x[0] - 0.5 * (double)(sample->Nx) * sample->delX;
double dy = p->x[1] - 0.5 * (double)(sample->Ny) * sample->delY;
*ir = (int)(sqrt (dx * dx + dy * dy) / sample->dr);
if (*ir < 0 || *ir >= sample->Nr)
return 0;
else
return 1;
}
/***********************************************************************************/
/* Function: sample_time @62_30i@ */
/* Description: */
/* Determine time/pathlength coordinate of a photon. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int sample_time (photon_struct* p, sample_struct* sample, int* it) {
/* determine sample time coordinates */
double t = p->pathlength / 3.0E8; /* speed of light is assumed to be 3E8 m/s */
*it = (int)(t / sample->dt);
if (*it < 0 || *it >= sample->Nt)
return 0;
else
return 1;
}
/***********************************************************************************/
/* Function: atmos_coord @62_30i@ */
/* Description: */
/* Determine atmospheric coordinates of a photon. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void atmos_coord (photon_struct* p, atmosphere_struct* atmos, int* ic, int* jc) {
/* determine atmospheric coordinates */
*ic = (int)(p->x[0] / atmos->delX);
*jc = (int)(p->x[1] / atmos->delY);
/* check boundaries */
if (*ic < 0) {
fprintf (stderr, "OOPS, set atmospheric coordinate ic from %d to %d (you may still trust your result?)\n", *ic, 0);
fprintf (stderr, " x = %f, y = %f photon %d \n", p->x[0], p->x[1], p->photoncounter);
*ic = 0;
}
if (*ic >= atmos->Nx) {
if ((double)*ic == p->x[0] / atmos->delX) /* photon is at periodic boundary ! */
(*ic)--;
else {
fprintf (stderr,
"OOPS, set atmospheric coordinate ic from %d to %d (you may still trust your result?)\n",
*ic,
atmos->Nx - 1);
fprintf (stderr, " x = %f, y = %f photon %d \n", p->x[0], p->x[1], p->photoncounter);
*ic = atmos->Nx - 1;
}
}
if (*jc < 0) {
fprintf (stderr, "OOPS, set atmospheric coordinate jc from %d to %d (you may still trust your result?)\n", *jc, 0);
fprintf (stderr, " x = %f, y = %f photon %d \n", p->x[0], p->x[1], p->photoncounter);
*jc = 0;
}
if (*jc >= atmos->Ny) {
if ((double)*jc == p->x[1] / atmos->delY) /* photon is at periodic boundary ! */
(*jc)--;
else {
fprintf (stderr,
"OOPS, set atmospheric coordinate jc from %d to %d (you may still trust your result?)\n",
*jc,
atmos->Ny - 1);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*jc = atmos->Ny - 1;
}
}
}
/***********************************************************************************/
/* Function: elev_coord @62_30i@ */
/* Description: */
/* Determine elevation coordinates of a photon. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
void elev_coord (photon_struct* p, elevation_struct* elev, int* ie, int* je) {
/* determine elevation coordinates */
*ie = (int)(p->x[0] / elev->delX);
*je = (int)(p->x[1] / elev->delY);
/* if we are at the right / upper boundary, we want to get the */
/* index of the last pixel, rather than one more; this is required */
/* because elev_coord() is called while the photon steps from */
/* box boundary where it eventually hits the right or upper */
/* boundaries as well */
if (*ie == elev->Nx)
if (p->x[0] == elev->delX * (double)elev->Nx)
(*ie)--;
if (*je == elev->Ny)
if (p->x[1] == elev->delY * (double)elev->Ny)
(*je)--;
/* check boundaries */
if (*ie < 0) {
fprintf (stderr, "OOPS, set elevation coordinate ie from %d to %d (you may still trust your result?)\n", *ie, 0);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*ie = 0;
}
if (*ie >= elev->Nx) {
if ((double)*ie == p->x[0] / elev->delX) /* photon is at periodic boundary ! */
(*ie)--;
else {
fprintf (stderr, "OOPS, set elevation coordinate ie from %d to %d (you may still trust your result?)\n", *ie, elev->Nx - 1);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*ie = elev->Nx - 1;
}
}
if (*je < 0) {
fprintf (stderr, "OOPS, set elevation coordinate je from %d to %d (you may still trust your result?)\n", *je, 0);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*je = 0;
}
if (*je >= elev->Ny) {
if ((double)*je < p->x[1] / elev->delY * (1 + MC_EPSILON)) /* photon is at periodic boundary ! */
(*je)--;
else {
fprintf (stderr, "OOPS, set elevation coordinate je from %d to %d (you may still trust your result?)\n", *je, elev->Ny - 1);
fprintf (stderr, " x = %f, y = %f, doubleje %e\n", p->x[0], p->x[1], p->x[1] / elev->delY - (double)*je);
*je = elev->Ny - 1;
}
}
}
/***********************************************************************************/
/* Function: calc_normal_vector @62_30i@ */
/* Description: */
/* Determine normal vector on surface. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
static inline void calc_normal_vector (photon_struct* p,
elevation_struct* elev,
sample_struct* sample,
atmosphere_struct* atmos,
int use_elev,
int use_sensordirection,
double* norm) {
double temp = 0.0;
/* default is horizontal surface */
norm[0] = 0;
norm[1] = 0;
norm[2] = 1;
if (elev->elev2D && use_elev)
elev_coord_normal_vector (p, elev, norm);
else if (use_sensordirection) { /* user-defined surface normal */
norm[0] = sample->sensordirection_dx[0];
norm[1] = sample->sensordirection_dx[1];
norm[2] = sample->sensordirection_dx[2];
} else if (sample->spherical && !(p->x[0] - atmos->xmax / 2. == 0. && p->x[1] - atmos->ymax / 2. == 0.)) {
norm[0] = p->x[0] - atmos->xmax / 2.;
norm[1] = p->x[1] - atmos->ymax / 2.;
norm[2] = p->x[2] + atmos->r_earth;
/* normalize normal vector */
temp = sqrt (norm[0] * norm[0] + norm[1] * norm[1] + norm[2] * norm[2]);
norm[0] /= temp;
norm[1] /= temp;
norm[2] /= temp;
} else if (sample->spherical3D && !(p->x[0] == 0.0 && p->x[1] == 0.0))
#if HAVE_MYSTIC3D
cart_to_spher (p->x, NULL, &temp, NULL, NULL, norm);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return;
#endif
return;
}
/***********************************************************************************/
/* Function: elev_coord_normal_vector @62_30i@ */
/* Description: */
/* Determine normal vector on elevation coordinates of a photon. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: RPB */
/* @i62_30@ */
/***********************************************************************************/
static inline void elev_coord_normal_vector (photon_struct* p, elevation_struct* elev, double* dx) {
int ie = 0, je = 0, i = 0;
double temp = 0.0;
elev_coord (p, elev, &ie, &je);
/* upward normal to the slant surface */
dx[0] = -elev->surf[ie][je].a - elev->surf[ie][je].c * (p->x[1] - (double)je * elev->delY);
dx[1] = -elev->surf[ie][je].b - elev->surf[ie][je].c * (p->x[0] - (double)ie * elev->delX);
dx[2] = 1;
/* normalize dx */
temp = sqrt (dx[0] * dx[0] + dx[1] * dx[1] + dx[2] * dx[2]);
for (i = 0; i < 3; i++)
dx[i] /= temp;
}
/***********************************************************************************/
/* Function: albedo_coord @62_30i@ */
/* Description: */
/* Determine albedo coordinates of a photon. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static inline void albedo_coord (photon_struct* p, albedo_struct* albedo, int* ia, int* ja) {
/* albedo coordinates */
*ia = (int)(p->x[0] / albedo->delX);
*ja = (int)(p->x[1] / albedo->delY);
/* check boundaries */
if (*ia < 0) {
fprintf (stderr, "OOPS, set albedo coordinate ia from %d to %d (you may still trust your result?)\n", *ia, 0);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*ia = 0;
}
if (*ia >= albedo->Nx) {
fprintf (stderr, "OOPS, set albedo coordinate ia from %d to %d (you may still trust your result?)\n", *ia, albedo->Nx - 1);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*ia = albedo->Nx - 1;
}
if (*ja < 0) {
fprintf (stderr, "OOPS, set albedo coordinate ja from %d to %d (you may still trust your result?)\n", *ja, 0);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*ja = 0;
}
if (*ja >= albedo->Ny) {
fprintf (stderr, "OOPS, set albedo coordinate ja from %d to %d (you may still trust your result?)\n", *ja, albedo->Ny - 1);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*ja = albedo->Ny - 1;
}
}
/***********************************************************************************/
/* Function: surftemp_coord @62_30i@ */
/* Description: */
/* Determine surface temperature coordinates of a photon. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static inline void surftemp_coord (photon_struct* p, surftemp_struct* surftemp, int* it, int* jt) {
/* surface temperature coordinates */
*it = (int)(p->x[0] / surftemp->delX);
*jt = (int)(p->x[1] / surftemp->delY);
/* check boundaries */
if (*it < 0) {
fprintf (stderr, "OOPS, set surface temperature coordinate ia from %d to %d (you may still trust your result?)\n", *it, 0);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*it = 0;
}
if (*it >= surftemp->Nx) {
fprintf (stderr,
"OOPS, set surface temperature coordinate ia from %d to %d (you may still trust your result?)\n",
*it,
surftemp->Nx - 1);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*it = surftemp->Nx - 1;
}
if (*jt < 0) {
fprintf (stderr, "OOPS, set surface temperature coordinate ja from %d to %d (you may still trust your result?)\n", *jt, 0);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*jt = 0;
}
if (*jt >= surftemp->Ny) {
fprintf (stderr,
"OOPS, set surface temperature coordinate ja from %d to %d (you may still trust your result?)\n",
*jt,
surftemp->Ny - 1);
fprintf (stderr, " x = %f, y = %f\n", p->x[0], p->x[1]);
*jt = surftemp->Ny - 1;
}
}
/***********************************************************************************/
/* Function: calculate_emission @62_30i@ */
/* Description: */
/* */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int calculate_emission (atmosphere_struct* atmos, result_struct* result) {
int ic = 0, jc = 0, kc = 0;
for (kc = 0; kc < atmos->Nz; kc++)
for (ic = 0; ic < atmos->Nx; ic++)
for (jc = 0; jc < atmos->Ny; jc++)
if (atmos->threed[MCCAOTH_TOT][kc] >= 1) {
/* Average value of Planck function */
/* emission is negative! */
result->absorption3D->tot[kc][ic][jc] =
-0.5 * (atmos->Bplanck->prof[MCCAOTH_TOT][kc][ic][jc] + atmos->Bplanck->prof[MCCAOTH_TOT][kc + 1][ic][jc]) *
atmos->kabs3D->prof[MCCAOTH_TOT][kc][ic][jc] * (atmos->Z[kc + 1] - atmos->Z[kc]);
/* Linear interpolation of temperature */
/* ?????? CE ??????? CHECK!!!
For heating rate calculations the emission term calculated here
seems not to be consistent with the emission calculated in
thermal backward.
*/
/* Interpolation of temperature is also not really correct ...*/
/*Tavg = 0.5* (atmos->T[kc] + atmos->T[kc+1]);
F77_FUNC (cplkavg, CPLKAVG) (wvnmlo, wvnmhi, &Tavg, &plkavg);
result->absorption3D->tot[kc][ic][jc] = plkavg*
atmos->kabs3D->prof [MCCAOTH_TOT][kc][ic][jc] * (atmos->Z[kc+1] - atmos->Z[kc]);
*/
}
return 0; /* if o.k. */
}
/***********************************************************************************/
/* Function: calculate_backward_emission @62_30i@ */
/* Description: */
/* */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int calculate_backward_emission (atmosphere_struct* atmos, sample_struct* sample, int kc, double* emis) {
int ic = 0, jc = 0, ic1 = 0, ic2 = 0, jc1 = 0, jc2 = 0;
double xs1 = 0, xs2 = 0, ys1 = 0, ys2 = 0; /* sample pixel coordinates */
double xc1 = 0, xc2 = 0, yc1 = 0, yc2 = 0; /* atmospheric (=caothy) pixel coordinates */
double xl = 0, xr = 0, yl = 0, yu = 0;
double sum = 0, fraction = 0;
*emis = 0;
if (atmos->threed[MCCAOTH_TOT][kc] >= 1) {
/* first determine index of edges of the sample pixel in caoth coordinates; */
/* this should in principle be done with atmos_coord, but the latter */
/* requires a photon struct as input while we provide simply x/y values */
/* sample pixel edges */
xs1 = (double)(sample->backward_is) * sample->delX;
xs2 = (double)(sample->backward_is + 1) * sample->delX;
ys1 = (double)(sample->backward_js) * sample->delY;
ys2 = (double)(sample->backward_js + 1) * sample->delY;
/* caoth pixels containing the sample pixel edges */
ic1 = (int)(xs1 / atmos->delX);
ic2 = (int)(xs2 / atmos->delX);
jc1 = (int)(ys1 / atmos->delY);
jc2 = (int)(ys2 / atmos->delY);
/* check boundaries */
if (ic1 < 0)
ic1 = 0;
if (ic2 < 0)
ic2 = 0;
if (jc1 < 0)
jc1 = 0;
if (jc2 < 0)
jc2 = 0;
if (ic1 >= atmos->Nx)
ic1 = atmos->Nx - 1;
if (ic2 >= atmos->Nx)
ic2 = atmos->Nx - 1;
if (jc1 >= atmos->Ny)
jc1 = atmos->Ny - 1;
if (jc2 >= atmos->Ny)
jc2 = atmos->Ny - 1;
sum = 0;
for (ic = ic1; ic <= ic2; ic++)
for (jc = jc1; jc <= jc2; jc++) {
xc1 = (double)(ic * atmos->delX);
xc2 = xc1 + atmos->delX;
yc1 = (double)(jc * atmos->delY);
yc2 = yc1 + atmos->delY;
xl = (xc1 > xs1 ? xc1 : xs1);
xr = (xc2 < xs2 ? xc2 : xs2);
yl = (yc1 > ys1 ? yc1 : ys1);
yu = (yc2 < ys2 ? yc2 : ys2);
fraction = (xr - xl) * (yu - yl) / (sample->delX * sample->delY);
sum += fraction;
*emis = *emis - fraction * 0.5 *
(atmos->Bplanck->prof[MCCAOTH_TOT][kc][ic][jc] + atmos->Bplanck->prof[MCCAOTH_TOT][kc + 1][ic][jc]) *
atmos->kabs3D->prof[MCCAOTH_TOT][kc][ic][jc] * (atmos->Z[kc + 1] - atmos->Z[kc]);
}
/* fprintf (stderr, "ic = %d - %d, jc = %d - %d, sum=%.10f\n", ic1, ic2, jc1, jc2, sum); */
/* check if the sum of all fractions is 1 */
if (fabs (sum - 1.0) > MC_EPSILON) {
fprintf (stderr, "Error in calculate_backward_emission, sum = %.14f\n", sum);
return -1;
}
} else {
/* Average value of Planck function */
/* emission is negative! */
*emis = -0.5 * (atmos->Bplanck->prof[MCCAOTH_TOT][kc][0][0] + atmos->Bplanck->prof[MCCAOTH_TOT][kc + 1][0][0]) *
atmos->kabs->prof[MCCAOTH_TOT][kc] * (atmos->Z[kc + 1] - atmos->Z[kc]);
}
return 0;
}
/***********************************************************************************/
/* Function: HGint @62_30i@ */
/* Description: */
/* Calculate the integrated HG phase function. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static double HGint (double g, double mu) {
return (1.0 - g * g) / 2.0 / g / sqrt (1.0 + g * g - 2.0 * g * mu) - (1.0 - g) / 2.0 / g;
}
/***********************************************************************************/
/* Function: HGint @62_30i@ */
/* Description: */
/* Calculate the integrated double HG phase function. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static double HG2int (double g1, double g2, double ff, double mu) {
return ff * HGint (g1, mu) + (1.0 - ff) * HGint (g2, mu);
}
/***********************************************************************************/
/* Function: sc_HG2_theta_old @62_30i@ */
/* Description: */
/* Calculate a random polar angle for the double Henyey-Greenstein */
/* phase function. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
double sc_HG2_theta_old (double g1, double g2, double ff) {
double theta = 0.0;
double P = uvspec_random();
double F = 0, FF = 0, mu = 0;
double accur = 0.001;
if (ff == 1.0) {
theta = acos (sc_HG_mu (g1));
} else {
/* ATTENTION: No error check, but very rude correction */
if (g1 < -1.0) {
fprintf (stderr, " ... g1 = %g out of range, setting to -1\n", g1);
g1 = -1;
}
if (g1 > 1.0) {
fprintf (stderr, " ... g1 = %g out of range, setting to 1\n", g1);
g1 = 1;
}
if (g2 < -1.0) {
fprintf (stderr, " ... g2 = %g out of range, setting to -1\n", g2);
g2 = -1;
}
if (g2 > 1.0) {
fprintf (stderr, " ... g2 = %g out of range, setting to 1\n", g2);
g2 = 1;
}
if (ff < -1.0) {
fprintf (stderr, " ... ff = %g out of range, setting to -1\n", ff);
ff = -1;
}
if (ff > 1.0) {
fprintf (stderr, " ... ff = %g out of range, setting to 1\n", ff);
ff = 1;
}
/* start value slightly different from 0, otherwise */
/* we get a local maximum at 0. */
mu = -accur + 2.0 * accur * uvspec_random();
F = HG2int (g1, g2, ff, mu);
FF = HG2 (g1, g2, ff, mu);
/* Newton iteration */
while (fabs (P - F) > accur) {
F = HG2int (g1, g2, ff, mu);
FF = HG2 (g1, g2, ff, mu);
mu += (P - F) / FF;
if (mu < -1)
mu = -1;
if (mu > 1)
mu = 1;
}
theta = acos (mu);
}
return theta;
}
/***********************************************************************************/
/* Function: sc_HG2_mu @62_30i@ */
/* Description: */
/* Calculate a random polar angle for the double Henyey-Greenstein */
/* phase function. */
/* Returns mu=cos(theta), for more speed! */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: ...., last big modification by Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
double sc_HG2_mu (double g1, double g2, double ff) {
double mu = 0.0;
double P = uvspec_random();
/* ATTENTION: No error check, but very rude correction */
if (ff < -1.0) {
fprintf (stderr, " ... ff = %g out of range, setting to -1\n", ff);
ff = -1;
}
if (ff > 1.0) {
fprintf (stderr, " ... ff = %g out of range, setting to 1\n", ff);
ff = 1;
}
if (P <= ff) /* forward, with a probability of ff */
mu = sc_HG_mu (g1);
else /* backward, with a probability of 1-ff */
mu = sc_HG_mu (g2);
return mu;
}
/***********************************************************************************/
/* Function: init_direction */
/* Description: */
/* Initialize direction with solar zenith sza and azimuth phi. */
/* Convention: phi=0, South */
/* phi=90, West */
/* phi=180, North */
/* phi=270, East */
/* These definition refers to the position of the sun; e.g. phi=0 means that */
/* the sun is in the South and the photons are headed North. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* */
/***********************************************************************************/
void init_direction (double sinsza, double cossza, double sinphi, double cosphi, direction* dir) {
dir->dx[0] = sinsza * sinphi;
dir->dx[1] = sinsza * cosphi;
;
dir->dx[2] = -cossza;
/* cosine of solar zenith angle for radiance calculation */
dir->cotheta = fabs (cossza);
hitflag (dir);
}
/***********************************************************************************/
/* Function: hitflag */
/* Description: */
/* Calculate 'hitflag' which is used to determine the general direction of */
/* a photon: */
/* hit[i] = 1 positive */
/* hit[i] = 0 negative */
/* hit[i] = -1 no component */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* */
/***********************************************************************************/
void hitflag (direction* dir) {
int i = 0;
for (i = 0; i < 3; i++) {
dir->hit[i] = -1;
if (dir->dx[i] > 0)
dir->hit[i] = 1;
else {
if (dir->dx[i] < 0)
dir->hit[i] = 0;
}
}
}
/***********************************************************************************/
/* Function: addtree_stddev */
/* Description: */
/* Add a new photon weight to the weights tree. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* */
/***********************************************************************************/
struct tnode* addtree_stddev (struct tnode* p, double* loc, double weight) {
if (p == NULL) { /* a new word has arrived */
p = (struct tnode*)calloc (1, sizeof (struct tnode)); /* create a new node */
p->loc = loc;
p->weight = weight;
p->left = p->right = NULL;
} else {
if (loc == p->loc)
p->weight += weight; /* add photon weight */
else {
if (loc < p->loc) /* smaller goes into left subtree */
p->left = addtree_stddev (p->left, loc, weight);
else /* larger goes into right subtree */
p->right = addtree_stddev (p->right, loc, weight);
}
}
return (p);
}
/***********************************************************************************/
/* Function: treeprint_stddev */
/* Description: */
/* Store the squared photon weights at their destinations. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* */
/***********************************************************************************/
void treeprint_stddev (struct tnode* p) {
/* ??? check if freeing is ok ??? CHECK!!! */
if (p != NULL) {
treeprint_stddev (p->left);
free (p->left);
*(p->loc) += p->weight * p->weight; /* write weight to final destination */
treeprint_stddev (p->right);
free (p->right);
}
}
/***********************************************************************************/
/* Function: add_to_photonpath */
/* Description: */
/* Add a photon location to the photon path */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* */
/***********************************************************************************/
#if defined PRINT_PHOTON_PATH || PRINT_ESCAPE_CONTRIBUTIONS
static void add_to_photonpath (struct photon_path** p, double* x, double weight) {
int i = 0;
struct photon_path* new = calloc (1, sizeof (struct photon_path));
for (i = 0; i < 3; i++) {
new->x[i] = x[i];
new->weight = weight;
}
new->next = *p;
*p = new;
}
#endif
/***********************************************************************************/
/* Function: print_and_clear_photonpath */
/* Description: */
/* Print all photon locations to stdout and free memory */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* */
/***********************************************************************************/
#if defined PRINT_PHOTON_PATH || defined PRINT_ESCAPE_CONTRIBUTIONS
static void print_and_clear_photonpath (struct photon_path* p, char* prefix) {
if (p != NULL) {
print_and_clear_photonpath (p->next, prefix);
fprintf (stdout, "%s%.6e %.6e %.6e %.6e\n", prefix, p->x[0], p->x[1], p->x[2], p->weight);
free (p);
}
}
#endif
/***********************************************************************************/
/* Function: setup_profiles1D @62_30i@ */
/* Description: */
/* Initialize the 1D part of the atmosphere_struct with the 1D profiles passed */
/* as function arguments. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int setup_profiles1D (int n_caoth,
float** dt_s,
float** om_s,
float** g1_s,
float** g2_s,
float** f_s,
float** ds_s,
float** re_s,
float* zprof,
int nlyr,
sample_struct* sample,
atmosphere_struct* atmos,
alis_struct* alis) {
int lc = 0, status = 0;
double dz_inv = 0.0;
int ids = 0, iris = 0, ivs = 0, isp = 0, iv = 0;
int ic = 0;
/* allocate memory for 1D profiles in atmosphere_struct *atmos */
status = calloc_1D_atmos (atmos, nlyr, n_caoth, alis->nlambda_abs, alis->nlambda_ref);
if (status != 0)
return err_out ("Error %d returned by calloc_1D_atmos()\n", status);
/* !!! attention !!! z[0 ... atmos->Nz], (dsca->air)[0 ... atmos->Nz-1], ... */
/* distinguish between layer (0..atmos->Nz-1) and level (0..atmos->Nz) properties */
atmos->Nc = alis->Nc;
/* convert altitude km -> m */
for (lc = 0; lc < atmos->Nz + 1; lc++)
atmos->Z[lc] = zprof[lc] * 1000.0;
/* for now only treat standard scattering and non-importance-sampled scattering */
ids = MCSC_MODE_NORMAL;
iris = MCRIS_MODE_NORMAL;
if (sample->spectral_is) {
for (iv = 0; iv < alis->nlambda_abs; iv++)
atmos->lambda[iv] = alis->lambda[iv];
for (iv = 0; iv < alis->nlambda_ref; iv++)
atmos->ilambda_ref[iv] = alis->ilambda_ref[iv];
}
if (alis->Nc > 1) {
sample->concentration_is = 1;
ASCII_calloc_double (&(atmos->kabs_scaled), atmos->Nc, atmos->Nz);
ASCII_calloc_double (&(atmos->ksca_scaled), atmos->Nc, atmos->Nz);
}
for (lc = 0; lc < atmos->Nz; lc++) {
for (isp = 1; isp <= n_caoth; isp++) { /* this necessitates that MCCAOTH_MOL=CAOTH_MOL+1;
MCCAOTH_AER=CAOTH_AER+1*/
atmos->ksca[ids][iris]->prof[isp][lc] = dt_s[isp - 1][lc] * om_s[isp - 1][lc];
atmos->kabs->prof[isp][lc] = dt_s[isp - 1][lc] * (1.0 - om_s[isp - 1][lc]);
}
/* spectral molecular absorption */
if (sample->spectral_is) {
/* Absorption is considered by importance sampling, for the
calculation itself it can be set to 0 */
/* atmos->kabs->prof [MCCAOTH_MOL][lc]=0.0; */
/* moderate scaling scattering coefficient can improve
efficiency, especially if only Rayleigh scattering*/
/* is considered without surface reflections */
/* atmos->ksca [ids][iris]->prof [MCCAOTH_MOL][lc]*=2; */
/* FIXCE CHECK!!! */
/* fprintf(stderr, "caoth %d\n", n_caoth); */
for (iv = 0; iv < alis->nlambda_abs; iv++) {
for (isp = 1; isp <= n_caoth; isp++) {
/* layers are counted different in uvspec and mystic*/
atmos->ksca_spectral[isp][iv][lc] = alis->dt[iv][isp - 1][lc] * alis->om[iv][isp - 1][lc];
atmos->kabs_spectral[isp][iv][lc] = alis->dt[iv][isp - 1][lc] * (1.0 - alis->om[iv][isp - 1][lc]);
atmos->ksca_spectral[isp][iv][lc] /= (atmos->Z[lc + 1] - atmos->Z[lc]);
atmos->kabs_spectral[isp][iv][lc] /= (atmos->Z[lc + 1] - atmos->Z[lc]);
atmos->ksca_spectral[MCCAOTH_TOT][iv][lc] += atmos->ksca_spectral[isp][iv][lc];
atmos->kabs_spectral[MCCAOTH_TOT][iv][lc] += atmos->kabs_spectral[isp][iv][lc];
/* FIXCE debugging output CHECK!!! */
/* if (lc==2) */
/* if (iv==0) */
/* fprintf(stderr, "lc %d lambda %g molabs %g aerabs %g aersca %g \n", lc, atmos->lambda[iv], */
/* alis->tau_molabs[iv][atmos->Nz-1-lc], */
/* alis->tau_aerabs[iv][atmos->Nz-1-lc], */
/* alis->tau_aersca[iv][atmos->Nz-1-lc]); */
/* FIXCE debugging output */
/* if (lc==2) */
/* if (iv==0) */
/* fprintf(stderr, "lc %d lambda %g wcabs %g wcsca %g icsca %g \n", lc, atmos->lambda[iv], */
/* alis->tau_wcabs[iv][atmos->Nz-1-lc], */
/* alis->tau_wcsca[iv][atmos->Nz-1-lc], */
/* alis->tau_icsca[iv][atmos->Nz-1-lc]); */
/* } */
}
}
}
/* concentration importance sampling (aerosol), to be generalized for caoth*/
if (sample->concentration_is) {
isp = MCCAOTH_AER;
for (ic = 0; ic < atmos->Nc; ic++) {
atmos->kabs_scaled[ic][lc] = alis->aer_scaling_factors[ic] * atmos->kabs->prof[isp][lc] / (atmos->Z[lc + 1] - atmos->Z[lc]);
atmos->ksca_scaled[ic][lc] =
alis->aer_scaling_factors[ic] * atmos->ksca[ids][MCRIS_MODE_NORMAL]->prof[isp][lc] / (atmos->Z[lc + 1] - atmos->Z[lc]);
}
}
}
/* now do delta_scaling */
if (sample->delta_scaling > -1.0)
for (lc = 0; lc < atmos->Nz; lc++) {
ids = MCSC_MODE_DELTA_SCALE;
for (isp = 1; isp <= n_caoth; isp++) /* this necessitates that MCCAOTH_MOL=CAOTH_MOL+1;
MCCAOTH_AER+1 */
atmos->ksca[ids][iris]->prof[isp][lc] = dt_s[isp - 1][lc] * om_s[isp - 1][lc] * (1.0 - ds_s[isp - 1][lc]);
}
/* now copy into modified (IS) scattering */
for (lc = 0; lc < atmos->Nz; lc++)
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 1; iris < atmos->nscaRIS; iris++)
for (isp = 1; isp <= atmos->ksca[ids][iris]->n_caoth; isp++) /* tot not needed, therefore
we start at isp=1 */
atmos->ksca[ids][iris]->prof[isp][lc] = atmos->ksca[ids][MCRIS_MODE_NORMAL]->prof[isp][lc];
#if HAVE_LIDAR
if (sample->LLE_RIS_MAS || sample->RIS_MS) {
mc_lidar_setup_ris_mas (atmos, sample);
}
#endif
if (sample->LLE_jacobian || sample->jacobian)
sample->Nz_jac = atmos->Nz;
/* calculate total scattering optical depth */
for (lc = 0; lc < atmos->Nz; lc++) {
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++) {
atmos->ksca[ids][iris]->prof[MCCAOTH_TOT][lc] = 0.0;
for (isp = 1; isp <= atmos->ksca[ids][iris]->n_caoth; isp++)
atmos->ksca[ids][iris]->prof[MCCAOTH_TOT][lc] += atmos->ksca[ids][iris]->prof[isp][lc];
}
atmos->kabs->prof[MCCAOTH_TOT][lc] = 0.0;
for (isp = 1; isp <= atmos->kabs->n_caoth; isp++)
atmos->kabs->prof[MCCAOTH_TOT][lc] += atmos->kabs->prof[isp][lc];
}
/* calculate total optical depths */
ids = MCSC_MODE_NORMAL;
iris = MCRIS_MODE_NORMAL;
if (sample->LLE_D_DIS)
atmos->ddis_eps = calloc ((size_t)atmos->Nz, sizeof (double));
else
atmos->ddis_eps = NULL;
for (lc = atmos->Nz - 1; lc >= 0; lc--) {
for (isp = 0; isp <= atmos->ksca[ids][iris]->n_caoth; isp++) {
atmos->tabstot[isp] += atmos->kabs->prof[isp][lc];
atmos->tscatot[isp] += atmos->ksca[ids][iris]->prof[isp][lc];
}
if (sample->LLE_D_DIS)
atmos->ddis_eps[lc] = 1.0 - atmos->tscatot[MCCAOTH_TOT] / 10.;
}
/* normalize with 1/dz */
for (lc = 0; lc < atmos->Nz; lc++) {
dz_inv = 1.0 / (atmos->Z[lc + 1] - atmos->Z[lc]);
/* scattering */
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
for (isp = 0; isp <= atmos->ksca[ids][iris]->n_caoth; isp++)
atmos->ksca[ids][iris]->prof[isp][lc] *= dz_inv;
/* absorption */
for (isp = 0; isp <= atmos->kabs->n_caoth; isp++)
atmos->kabs->prof[isp][lc] *= dz_inv;
}
/* setup extinction coefficient profile; Virtual IS may not be set up before here! */
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
for (ivs = 0; ivs < atmos->nscaVIS; ivs++)
for (lc = 0; lc < atmos->Nz; lc++)
atmos->kext[ids][iris][ivs]->prof[MCCAOTH_TOT][lc] = atmos->ksca[ids][iris]->prof[MCCAOTH_TOT][lc];
/* convert asymmetry factor to double */
for (lc = 0; lc < atmos->Nz; lc++) {
for (isp = MCCAOTH_AER; isp <= atmos->g1->n_caoth; isp++) {
atmos->g1->prof[isp][lc] = g1_s[isp - 1][lc];
atmos->g2->prof[isp][lc] = g2_s[isp - 1][lc];
atmos->ff->prof[isp][lc] = f_s[isp - 1][lc];
atmos->reff->prof[isp][lc] = re_s[isp - 1][lc];
}
}
return 0;
}
/***********************************************************************************/
/* Function: calloc_1D_atmos @62_30i@ */
/* Description: */
/* Allocate memory for the 1D part of atmosphere_struct *atmos. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static int calloc_1D_atmos (atmosphere_struct* atmos, int nlyr, int n_caoth, int nlambda_abs, int nlambda_ref) {
int ids = 0, iris = 0, ivs = 0;
int iv = 0;
atmos->Nz = nlyr;
atmos->n_caoth = n_caoth;
/* allocate memory for profiles */
atmos->Z = calloc ((size_t) (atmos->Nz + 1), sizeof (double));
if (atmos->Z == NULL)
return mem_err_out ("atmos->Z", ERROR_POSITION);
atmos->kabs = calloc_profile (n_caoth, atmos->Nz);
if (atmos->kabs == NULL)
return mem_err_out ("atmos->kabs", ERROR_POSITION);
if (nlambda_abs > 0) {
atmos->nlambda_abs = nlambda_abs;
/* FIXCE CHECK!!! */
/* may be profile structure should be extended for spectral absorption ???*/
atmos->lambda = calloc (nlambda_abs, sizeof (float));
atmos->kabs_spectral = calloc (n_caoth + 1, sizeof (double**));
atmos->ksca_spectral = calloc (n_caoth + 1, sizeof (double**));
for (ids = 0; ids <= n_caoth; ids++) {
atmos->kabs_spectral[ids] = calloc (nlambda_abs, sizeof (double*));
atmos->ksca_spectral[ids] = calloc (nlambda_abs, sizeof (double*));
for (iv = 0; iv < nlambda_abs; iv++) {
atmos->kabs_spectral[ids][iv] = calloc (nlyr, sizeof (double));
atmos->ksca_spectral[ids][iv] = calloc (nlyr, sizeof (double));
}
}
}
/* FIXCE: Quick fix CHECK!!! */
else {
atmos->nlambda_abs = 1;
atmos->lambda = calloc (atmos->nlambda_abs, sizeof (float));
atmos->lambda[0] = 0;
}
if (nlambda_ref > 0) {
atmos->nlambda_ref = nlambda_ref;
atmos->ilambda_ref = calloc (nlambda_ref, sizeof (int));
}
atmos->ksca = calloc (atmos->nscaDS, sizeof (profile*));
for (ids = 0; ids < atmos->nscaDS; ids++)
atmos->ksca[ids] = calloc (atmos->nscaRIS, sizeof (profile));
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++) {
atmos->ksca[ids][iris] = calloc_profile (n_caoth, atmos->Nz);
if (atmos->ksca[ids][iris] == NULL)
return mem_err_out ("atmos->ksca[][]", ERROR_POSITION);
}
atmos->kext = calloc (atmos->nscaDS, sizeof (profile**));
for (ids = 0; ids < atmos->nscaDS; ids++)
atmos->kext[ids] = calloc (atmos->nscaRIS, sizeof (profile*));
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
atmos->kext[ids][iris] = calloc (atmos->nscaVIS, sizeof (profile));
for (ids = 0; ids < atmos->nscaDS; ids++)
for (iris = 0; iris < atmos->nscaRIS; iris++)
for (ivs = 0; ivs < atmos->nscaVIS; ivs++) {
atmos->kext[ids][iris][ivs] = calloc_profile (0, atmos->Nz);
if (atmos->kext[ids][iris][ivs] == NULL)
return mem_err_out ("atmos->kext[][][]", ERROR_POSITION);
}
atmos->g1 = calloc_profile (n_caoth, atmos->Nz);
if (atmos->g1 == NULL)
return mem_err_out ("atmos->g1", ERROR_POSITION);
atmos->g2 = calloc_profile (n_caoth, atmos->Nz);
if (atmos->g2 == NULL)
return mem_err_out ("atmos->g2", ERROR_POSITION);
atmos->ff = calloc_profile (n_caoth, atmos->Nz);
if (atmos->ff == NULL)
return mem_err_out ("atmos->ff", ERROR_POSITION);
/* ??? set ff to 1 ??? CHECK!!! */
atmos->reff = calloc_profile (n_caoth, atmos->Nz);
if (atmos->reff == NULL)
return mem_err_out ("atmos->reff", ERROR_POSITION);
atmos->tabstot = calloc ((size_t)n_caoth + 1, sizeof (double));
if (atmos->tabstot == NULL)
return mem_err_out ("atmos->tabstot", ERROR_POSITION);
atmos->tscatot = calloc ((size_t)n_caoth + 1, sizeof (double));
if (atmos->tscatot == NULL)
return mem_err_out ("atmos->tscatot", ERROR_POSITION);
return 0;
}
/***********************************************************************************/
/* Function: calloc_profile @62_30i@ */
/* Description: */
/* Allocate memory for struct profile and initialize structure. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static profile* calloc_profile (int n_caoth, int n) {
int isp = 0;
profile* p = calloc (1, sizeof (profile));
if (p == NULL)
return NULL;
p->n_caoth = n_caoth;
p->n = n;
p->prof = calloc ((size_t)n_caoth + 1, sizeof (double*));
if (p->prof == NULL)
return NULL;
for (isp = 0; isp < n_caoth + 1; isp++) {
p->prof[isp] = calloc ((size_t)n, sizeof (double));
if (p->prof[isp] == NULL)
return NULL;
}
return p;
}
/***********************************************************************************/
/* Function: calloc_profile3D @62_30i@ */
/* Description: */
/* Allocate memory for struct profile3D and initialize structure. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: */
/* @i62_30@ */
/***********************************************************************************/
static profile3D* calloc_profile3D (int n_caoth, int* tocalloc, int Nz, int Nx, int Ny, int** threed) {
int kc = 0, ic = 0, isp = 0;
profile3D* p = calloc (1, sizeof (profile3D));
if (p == NULL)
return NULL;
p->n_caoth = n_caoth;
/* this vector tells us which caoth need 3d allocation (incl. tot) */
p->tocalloc = calloc ((size_t)n_caoth + 1, sizeof (int));
if (p->tocalloc == NULL)
return NULL;
for (isp = 0; isp <= n_caoth; isp++)
p->tocalloc[isp] = tocalloc[isp];
p->Nz = Nz;
p->Nx = Nx;
p->Ny = Ny;
p->nthreed = calloc ((size_t)n_caoth + 1, sizeof (int));
if (p->nthreed == NULL)
return NULL;
p->threed = calloc ((size_t)n_caoth + 1, sizeof (int*));
if (p->threed == NULL)
return NULL;
for (isp = 0; isp <= n_caoth; isp++) {
p->threed[isp] = calloc ((size_t)Nz, sizeof (int));
if (p->threed[isp] == NULL)
return NULL;
}
for (isp = 0; isp <= n_caoth; isp++)
for (kc = 0; kc < Nz; kc++) {
p->threed[isp][kc] = threed[isp][kc];
if (p->threed[isp][kc] >= 1)
p->nthreed[isp]++;
}
p->prof = calloc ((size_t)n_caoth + 1, sizeof (float***));
if (p->prof == NULL)
return NULL;
for (isp = 0; isp <= n_caoth; isp++) {
if (p->tocalloc[isp]) {
p->prof[isp] = calloc ((size_t)Nz, sizeof (float**));
if (p->prof[isp] == NULL)
return NULL;
} else
p->prof[isp] = NULL;
}
for (isp = 0; isp <= n_caoth; isp++)
if (p->tocalloc[isp]) {
for (kc = 0; kc < Nz; kc++)
if (p->threed[isp][kc] >= 1) {
p->prof[isp][kc] = calloc ((size_t)Nx, sizeof (float*));
for (ic = 0; ic < Nx; ic++)
p->prof[isp][kc][ic] = calloc ((size_t)Ny, sizeof (float));
}
}
return p;
}
/***********************************************************************************/
/* Functions: get_ksca_tot, get_kabs_tot, get_ksca, etc @62_30i@ */
/* Description: */
/* return the value of an atmospheric quantity at the location of the photon */
/* depends of whether atmos->threed, and whether to deltascale */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
/* total absorption optical depth */
static inline double get_kabs_tot (atmosphere_struct* atmos, photon_struct* p) {
if (atmos->threed[MCCAOTH_TOT][p->kc] >= 1)
return (atmos->kabs3D->prof[MCCAOTH_TOT])[p->kc][p->ic][p->jc];
else if (p->iv_alis != -1)
return atmos->kabs_spectral[MCCAOTH_TOT][p->iv_alis][p->kc];
else
return (atmos->kabs->prof[MCCAOTH_TOT])[p->kc];
}
static inline double get_g1 (atmosphere_struct* atmos, photon_struct* p, int isp) {
if (atmos->threed[isp][p->kc] >= 1)
return (atmos->g1_3D->prof[isp])[p->kc][p->ic][p->jc];
else
return (atmos->g1->prof[isp])[p->kc];
}
static inline double get_g2 (atmosphere_struct* atmos, photon_struct* p, int isp) {
if (atmos->threed[isp][p->kc] >= 1)
return (atmos->g2_3D->prof[isp])[p->kc][p->ic][p->jc];
else
return (atmos->g2->prof[isp])[p->kc];
}
static inline double get_ff (atmosphere_struct* atmos, photon_struct* p, int isp) {
if (atmos->threed[isp][p->kc] >= 1)
return (atmos->ff_3D->prof[isp])[p->kc][p->ic][p->jc];
else
return (atmos->ff->prof[isp])[p->kc];
}
static inline double get_reff (atmosphere_struct* atmos, photon_struct* p, int isp) {
if (atmos->threed[isp][p->kc] >= 1)
return (atmos->reff_3D->prof[isp])[p->kc][p->ic][p->jc];
else
return (atmos->reff->prof[isp])[p->kc];
}
#ifdef CLDPRP
static double inline get_dxlwc (atmosphere_struct* atmos, photon_struct* p, int isp) {
if (atmos->threed[isp][p->kc] >= 1)
return (atmos->dxlwc_3D->prof[isp])[p->kc][p->ic][p->jc];
else
return 0.0;
}
static double inline get_dylwc (atmosphere_struct* atmos, photon_struct* p, int isp) {
if (atmos->threed[isp][p->kc] >= 1)
return (atmos->dylwc_3D->prof[isp])[p->kc][p->ic][p->jc];
else
return 0.0;
}
static double inline get_dzlwc (atmosphere_struct* atmos, photon_struct* p, int isp) {
if (atmos->threed[isp][p->kc] >= 1)
return (atmos->dzlwc_3D->prof[isp])[p->kc][p->ic][p->jc];
else
return 0.0;
}
#endif
/* scattering optical depth of choice */
double get_ksca (atmosphere_struct* atmos, photon_struct* p, int isp) {
if (isp < 0 || isp > atmos->n_caoth) {
fprintf (stderr, "Error in get_ksca, no such type %d of scattering!!!\n", isp);
return NOT_A_NUMBER;
}
if (atmos->threed[isp][p->kc] >= 1)
return atmos->ksca3D[p->SC_mode][MCRIS_MODE_NORMAL]->prof[isp][p->kc][p->ic][p->jc];
else if (p->iv_alis != -1)
return atmos->ksca_spectral[isp][p->iv_alis][p->kc];
else
return atmos->ksca[p->SC_mode][MCRIS_MODE_NORMAL]->prof[isp][p->kc];
}
/* scattering optical depth of choice */
static inline double get_ksca_spectral (atmosphere_struct* atmos, photon_struct* p, int isp, int iv) {
if (isp < 0 || isp > atmos->n_caoth) {
fprintf (stderr, "Error in get_ksca, no such type %d of scattering!!!\n", isp);
return NOT_A_NUMBER;
}
if (atmos->threed[isp][p->kc] >= 1)
return atmos->ksca3D[p->SC_mode][MCRIS_MODE_NORMAL]->prof[isp][p->kc][p->ic][p->jc];
else
return atmos->ksca_spectral[isp][iv][p->kc];
}
#ifdef CLDPRP
/* absorption optical depth of choice */
double get_kabs (atmosphere_struct* atmos, photon_struct* p, int isp) {
if (isp < 0 || isp > atmos->n_caoth) {
fprintf (stderr, "Error in get_kabs, no such type %d of absorption!!!\n", isp);
return 0.0 / 0.0;
}
if (atmos->threed[isp][p->kc] >= 1)
return atmos->kabs3D->prof[isp][p->kc][p->ic][p->jc];
else if (p->iv_alis != -1)
return atmos->kabs_spectral[isp][p->iv_alis][p->kc];
else
return atmos->kabs->prof[isp][p->kc];
}
#endif
#ifdef NEWRISQIDD
/* modified scattering optical depth of choice */
double get_kscaIS (atmosphere_struct* atmos, photon_struct* p, int isp) {
double ksca = 0.0, ksca2 = 0.0;
if (isp < 0 || isp > atmos->n_caoth) {
fprintf (stderr, "Error in get_kscaIS, no such type %d of scattering!!!\n", isp);
return NOT_A_NUMBER;
}
if (atmos->threed[isp][p->kc] >= 1)
ksca = atmos->ksca3D[p->SC_mode][p->RIS_mode]->prof[isp][p->kc][p->ic][p->jc];
else if (p->iv_alis != -1)
ksca = atmos->ksca_spectral[isp][p->iv_alis][p->kc];
else
ksca = atmos->ksca[p->SC_mode][p->RIS_mode]->prof[isp][p->kc];
if (p->risqidd_beta != 0.0) { /* here probably error */
if (atmos->threed[isp][p->kc] >= 1)
ksca2 = atmos->ksca3D[p->SC_mode][p->RIS_mode]->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc];
else
ksca2 = atmos->ksca[p->SC_mode][p->RIS_mode]->prof[MCCAOTH_TOT][p->kc];
if (p->risqidd_beta > ksca2) /* this should always be fulfilled */
ksca *= p->risqidd_beta / ksca2;
}
return ksca * atmos->ris_factor;
}
#else
/* modified scattering optical depth of choice */
double get_kscaIS (atmosphere_struct* atmos, photon_struct* p, int isp) {
if (isp < 0 || isp > atmos->n_caoth) {
fprintf (stderr, "Error in get_kscaIS, no such type %d of scattering!!!\n", isp);
return NOT_A_NUMBER;
}
if (atmos->threed[isp][p->kc] >= 1)
return atmos->ris_factor * atmos->ksca3D[p->SC_mode][p->RIS_mode]->prof[isp][p->kc][p->ic][p->jc];
else if (p->iv_alis != -1)
return atmos->ris_factor * atmos->ksca_spectral[isp][p->iv_alis][p->kc];
else
return atmos->ris_factor * atmos->ksca[p->SC_mode][p->RIS_mode]->prof[isp][p->kc];
}
#endif
/* modified extinction scattering optical depth */
/* this includes virtual scattering rates */
static inline double get_kext (atmosphere_struct* atmos, photon_struct* p) {
double ksca = 0.0;
if (atmos->threed[MCCAOTH_TOT][p->kc] >= 1)
ksca = atmos->kext3D[p->SC_mode][p->RIS_mode][p->VIS_mode]->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc];
else if (p->iv_alis != -1)
ksca = atmos->ksca_spectral[MCCAOTH_TOT][p->iv_alis][p->kc];
else
ksca = atmos->kext[p->SC_mode][p->RIS_mode][p->VIS_mode]->prof[MCCAOTH_TOT][p->kc];
if (p->vis_beta != 0.0 && ksca > 0. && ksca < p->vis_beta)
ksca = p->vis_beta;
/* special case for VIS-FOD */
if (!p->lest.behind_detector && ksca > 0. && ksca < p->lest.vis_fod_kext)
ksca = p->lest.vis_fod_kext;
return ksca * atmos->ris_factor;
}
/* Assign an altitude to a photon and determine the respective layer number; */
/* required by generate_photon. This function is used by generate_photon */
/* and MUST BE CALLED AFTER THE PHOTON DIRECTION HAS BEEN ASSIGNED BECAUSE */
/* THE LAYER NUMBER MIGHT DEPEND ON THE PHOTON DIRECTION! */
int set_photon_z (float z, atmosphere_struct* atmos, photon_struct* p) {
int hit = 0;
static int jlo = 0;
float zact = 0;
float* zz = atmos->Z;
int n = atmos->Nz + 1;
zact = z;
if (zz[0] != 0) {
fprintf (stderr, "Error, assuming that the profile starts at z=0\n");
return -1;
}
if (n < 2) {
fprintf (stderr, "Error, assuming at least two vertical levels\n");
return -1;
}
/* restrict start position to available range */
if (zact < 0.0)
zact = 0.0;
else {
if (zact > zz[n - 1])
zact = zz[n - 1];
}
/* an upward photon at top of atmosphere is moved downward a bit */
/* in order to avoid numerical problems; this is required e.g. */
/* to calculate downward irradiance at TOA in backward mode */
if (zact == zz[n - 1] && p->dir.dx[2] > 0)
zact *= (1.0 - MC_EPSILON);
/* a downward photon at the lowest level is moved upward a bit */
/* in order to avoid numerical problems; this is required e.g. */
/* to calculate surface upward irradiance in backward mode */
if (zact == 0.0 && p->dir.dx[2] < 0)
zact += MC_EPSILON;
hunt_modified (zz, n, zact, &jlo, &hit);
p->kc = jlo;
p->x[2] = zact; /* p->x[2] is a double while all other z's are float - does that make sense? */
/* downward moving photons starting at a level are assigned the index of the lower box */
if (hit && p->dir.dx[2] < 0)
p->kc--;
return 0;
}
/*****************************************************************/
/* slightly modified version of hunt() from numerical recipes; */
/* the layer index kc is assigned so that zz[kc] <= z < zz[kc+1] */
/*****************************************************************/
static void hunt_modified (float* xx, int n, float x, int* jlo, int* hit)
/* Given an array xx[1..n], and given a value x, returns a value jlo such that
x is between xx[jlo] and xx[jlo+1]. xx[1..n] must be monotonic, either
increasing or decreasing. jlo=0 or jlo=n is returned to indicate that x is out
of range. jlo on input is taken as the initial guess for jlo on output. */
{
int jm = 0, jhi = 0, inc = 0;
int ascnd = 0;
*hit = 0;
xx -= 1;
ascnd = (xx[n] >= xx[1]);
if (*jlo <= 0 || *jlo > n) {
*jlo = 0;
jhi = n + 1;
} else {
inc = 1;
/* hint: setting brackets around first logical, i.e. ((x >= xx[*jlo] ) == ascnd), will fix the compiler warnings */
if ((x >= xx[*jlo]) == ascnd) {
if (*jlo == n)
return;
jhi = (*jlo) + 1;
while ((x >= xx[jhi]) == ascnd) {
*jlo = jhi;
inc += inc;
jhi = (*jlo) + inc;
if (jhi > n) {
jhi = n + 1;
break;
}
}
} else {
if (*jlo == 1) {
*jlo = 0;
return;
}
jhi = (*jlo)--;
while ((x < xx[*jlo]) == ascnd) {
jhi = (*jlo);
inc <<= 1;
if (inc >= jhi) {
*jlo = 0;
break;
} else
*jlo = jhi - inc;
}
}
}
while (jhi - (*jlo) != 1) {
jm = (jhi + (*jlo)) >> 1;
if ((x >= xx[jm]) == ascnd)
*jlo = jm;
else
jhi = jm;
}
if (x == xx[n]) /* changed that, BM */
/* *jlo=n-1; */
*jlo = n;
if (x == xx[1])
*jlo = 1;
*jlo -= 1;
xx += 1;
if (xx[*jlo] == x)
*hit = 1;
return;
}
/***********************************************************************************/
/* Function: stokes_vector_sca @62_30i@ */
/* Description: */
/* Calculates the scattered Stokes (weight) vector. */
/* The Stokes (weight) vector is used to compute polarized radiative transfer. */
/* (this function works only for forward tracing and might be removed later.) */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Claudia Emde */
/* @i62_30@ */
/***********************************************************************************/
static int stokes_vector_sca (double* stokes_vector, double* P, double* dx_sca, double* dx_inc, double phi_sun, double phi_det) {
int i = 0, j = 0, status = 0;
double stokes_vector_inc[4];
double N = 0.0;
double n_z[3] = {0, 0, 1};
double n_ort_sca[3], n_ort_ref[3] = {0, 0, 0}, n_ort_sin[3];
double Z[4][4];
double cos2alpha1 = 1.0, sin2alpha1 = 0.0, cosalpha = 0.0;
double cos2alpha2 = 1.0, sin2alpha2 = 0.0, sinalpha = 0.0;
double n_ort_sca_z = 0.0;
/* Copy Stokes vector */
for (i = 0; i < 4; i++)
stokes_vector_inc[i] = stokes_vector[i];
/* Calculate vector orthogonal to scattering plane */
status = v_cross_product_norm (dx_inc, dx_sca, n_ort_sca);
n_ort_sca_z = n_ort_sca[2];
/*incoming and scattered direction are not parallel */
if (!status) {
/* orthogonal vector to p_inc-z-plane*/
status = v_cross_product_norm (dx_inc, n_z, n_ort_ref);
if (status) {
/* orthogonal vector to (z, phi_esc)-plane*/
n_ort_ref[0] = -cosd (phi_sun);
n_ort_ref[1] = sind (phi_sun);
n_ort_ref[2] = 0.0;
n_ort_sca_z = -sind (phi_sun) * dx_sca[1] + cosd (phi_sun) * dx_sca[0];
}
/* Calculate rotation angle 1 */
status = v_mult_mu (n_ort_sca, n_ort_ref, &cosalpha);
CHKERR (status);
/* Calculate sinalpha using vector product */
v_cross_product (n_ort_sca, n_ort_ref, n_ort_sin);
v_mult (n_ort_sin, n_ort_sin, &N);
sinalpha = -sqrt (N);
cos2alpha1 = cosalpha * cosalpha - sinalpha * sinalpha;
sin2alpha1 = 2.0 * sinalpha * cosalpha;
/* orthogonal to p_sca-z-plane*/
status = v_cross_product_norm (dx_sca, n_z, n_ort_ref);
if (status) {
/* orthogonal vector to (z, phi_esc)-plane*/
n_ort_ref[0] = -cosd (phi_det);
n_ort_ref[1] = sind (phi_det);
n_ort_ref[2] = 0.0;
n_ort_sca_z = -dx_inc[0] * cosd (phi_det) + dx_inc[1] * sind (phi_det);
}
/* Calculate rotation angle 2 */
status = v_mult_mu (n_ort_sca, n_ort_ref, &cosalpha);
CHKERR (status);
/* Calculate sinalpha using vector product */
v_cross_product (n_ort_sca, n_ort_ref, n_ort_sin);
v_mult (n_ort_sin, n_ort_sin, &N);
sinalpha = +sqrt (N);
cos2alpha2 = cosalpha * cosalpha - sinalpha * sinalpha;
sin2alpha2 = 2.0 * sinalpha * cosalpha;
}
/* Exact forward or backward scattering, no rotation required, as initialized */
/* cos2alpha1=1.0; */
/* cos2alpha2=1.0; */
/* sin2alpha1=0.0; */
/* sin2alpha2=0.0; */
/* The sign of the following elements depends on orientation */
/* The z-component of the cross product of dx_inc and dx_sca is the same as the z-component */
/* of the cross product of dx_inc_horz and dx_sca_horz (vectors projected in x-y-plane.) */
/* The orientation of the normal vector to dx_inc_horz and dx_sca_horz is equivalent to */
/* whether the azimutal difference between the two vectors in the x-y plane is smaller */
/* or larger 180 degrees. */
if (n_ort_sca_z < 0.) {
sin2alpha1 = -sin2alpha1;
sin2alpha2 = -sin2alpha2;
}
Z[0][0] = P[0];
Z[0][1] = P[1] * cos2alpha1;
Z[0][2] = -P[1] * sin2alpha1;
Z[0][3] = 0.0;
Z[1][0] = P[1] * cos2alpha2;
Z[1][1] = P[4] * cos2alpha1 * cos2alpha2 - P[2] * sin2alpha1 * sin2alpha2;
Z[1][2] = -P[4] * sin2alpha1 * cos2alpha2 - P[2] * cos2alpha1 * sin2alpha2;
Z[1][3] = -P[3] * sin2alpha2;
Z[2][0] = P[1] * sin2alpha2;
Z[2][1] = P[4] * cos2alpha1 * sin2alpha2 + P[2] * sin2alpha1 * cos2alpha2;
Z[2][2] = -P[4] * sin2alpha1 * sin2alpha2 + P[2] * cos2alpha1 * cos2alpha2;
Z[2][3] = P[3] * cos2alpha2;
Z[3][0] = 0.0;
Z[3][1] = -P[3] * sin2alpha1;
Z[3][2] = -P[3] * cos2alpha1;
Z[3][3] = P[5];
/* scattering matrix multiplication */
for (i = 0; i < 4; i++) {
stokes_vector[i] = 0.0;
for (j = 0; j < 4; j++) {
stokes_vector[i] += Z[i][j] * stokes_vector_inc[j];
}
stokes_vector[i] /= P[0];
}
return 0;
}
/****************************************************************************/
/* Function: phase_matrix_mult @62_30i@ */
/* Description: */
/* Multiplies the phase matrix of a scattering event with the photon */
/* phase matrix (product of all phase matrices along the photon path). */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Claudia Emde */
/* @i62_30@ */
/****************************************************************************/
int phase_matrix_mult (double** phase_matrix,
double* P,
double* dx_sca,
double* dx_inc,
double phi_sun,
double phi_det,
int escape,
int scattercounter,
int backward) {
int i = 0, j = 0, k = 0, status = 0;
double phase_matrix_inc[4][4];
double N = 0.0;
double n_ort_sca[3], n_ort_ref[3], n_ort_sin[3];
double n_z[3] = {0, 0, 1};
double Z[4][4];
double cos2alpha1 = 1.0, sin2alpha1 = 0.0, cosalpha = 0.0;
double cos2alpha2 = 1.0, sin2alpha2 = 0.0, sinalpha = 0.0;
double *dx1 = NULL, *dx2 = NULL;
double n_ort_sca_z = 0.0;
/* Copy photon phase matrix */
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
phase_matrix_inc[i][j] = phase_matrix[i][j];
if (backward) {
/*exchange incoming and scattered direction for backward */
dx2 = dx_inc;
dx1 = dx_sca;
n_z[2] = -1;
} else {
dx1 = dx_inc;
dx2 = dx_sca;
}
/* Calculate vector orthogonal to scattering plane */
status = v_cross_product_norm (dx1, dx2, n_ort_sca);
n_ort_sca_z = n_ort_sca[2];
/* incoming and scattered direction are not parallel */
if (!status) {
/* orthogonal vector to dx1-z-plane*/
status = v_cross_product_norm (dx1, n_z, n_ort_ref);
if (status) {
/* Incoming direction || z-axis happens if SZA=0 */
/* Polarization plane (z, phi0) */
if (!(backward && escape) && !(!backward && scattercounter == 0)) {
fprintf (stderr, "scattercounter %d \n", scattercounter);
fprintf (stderr, "\n");
fprintf (stderr, "*** Warning, polarization plane of photon lost, because \n");
fprintf (stderr, "*** photon is scattered exactly in z-direction.\n");
fprintf (stderr, "*** If this happens too often please contact Claudia.\n");
fprintf (stderr, "\n");
}
/* orthogonal vector to (z, phi_esc)-plane*/
n_ort_ref[0] = -cosd (phi_sun);
n_ort_ref[1] = sind (phi_sun);
n_ort_ref[2] = 0.0;
n_ort_sca_z = -sind (phi_sun) * dx2[1] + cosd (phi_sun) * dx2[0];
if (backward)
n_ort_sca_z *= -1;
}
/* Calculate rotation angle 1 */
status = v_mult_mu (n_ort_sca, n_ort_ref, &cosalpha);
CHKERR (status);
/* Calculate sinalpha using vector product */
v_cross_product (n_ort_sca, n_ort_ref, n_ort_sin);
v_mult (n_ort_sin, n_ort_sin, &N);
sinalpha = -sqrt (N);
cos2alpha1 = cosalpha * cosalpha - sinalpha * sinalpha;
sin2alpha1 = 2.0 * sinalpha * cosalpha;
/* orthogonal to dx2z-plane*/
status = v_cross_product_norm (dx2, n_z, n_ort_ref);
if (status) {
/* In case of umu=+/- 1 we need to consider this special case: */
/* In forward mode and umu +/-1 the last rotation needs to be in the plane */
/* defined by (z, phi_sensor). */
/* In backward mode the first rotation.*/
if (!(!backward && escape) && !(backward && scattercounter == 0)) {
fprintf (stderr, "scattercounter %d \n", scattercounter);
fprintf (stderr, "\n");
fprintf (stderr, "*** Warning, polarization plane of photon lost, because \n");
fprintf (stderr, "*** photon is scattered exactly in z-direction.\n");
fprintf (stderr, "*** If this happens too often please contact Claudia.\n");
fprintf (stderr, "\n");
}
/* orthogonal vector to (z, phi_esc)-plane*/
n_ort_ref[0] = -cosd (phi_det);
n_ort_ref[1] = sind (phi_det);
n_ort_ref[2] = 0.0;
n_ort_sca_z = -dx1[0] * cosd (phi_det) + dx1[1] * sind (phi_det);
if (backward)
n_ort_sca_z *= -1;
}
/* Calculate rotation angle 2 */
status = v_mult_mu (n_ort_sca, n_ort_ref, &cosalpha);
CHKERR (status);
/* Calculate sinalpha using vector product */
v_cross_product (n_ort_sca, n_ort_ref, n_ort_sin);
v_mult (n_ort_sin, n_ort_sin, &N);
sinalpha = +sqrt (N);
cos2alpha2 = cosalpha * cosalpha - sinalpha * sinalpha;
sin2alpha2 = 2.0 * sinalpha * cosalpha;
}
/* Exact forward or backward scattering, no rotation required, as initialized */
/* cos2alpha1=1.0; */
/* cos2alpha2=1.0; */
/* sin2alpha1=0.0; */
/* sin2alpha2=0.0; */
/* The sign of the following elements depends on orientation */
/* The z-component of the cross product of dx_inc and dx_sca is the same as the z-component */
/* of the cross product of dx_inc_horz and dx_sca_horz (vectors projected in x-y-plane.) */
/* The orientation of the normal vector to dx_inc_horz and dx_sca_horz is equivalent to */
/* whether the azimutal difference between the two vectors in the x-y plane is smaller */
/* or larger 180 degrees. */
if (n_ort_sca_z < 0.) {
sin2alpha1 = -sin2alpha1;
sin2alpha2 = -sin2alpha2;
}
Z[0][0] = P[0];
Z[0][1] = P[1] * cos2alpha1;
Z[0][2] = -P[1] * sin2alpha1;
Z[0][3] = 0.0;
Z[1][0] = P[1] * cos2alpha2;
Z[1][1] = P[4] * cos2alpha1 * cos2alpha2 - P[2] * sin2alpha1 * sin2alpha2;
Z[1][2] = -P[4] * sin2alpha1 * cos2alpha2 - P[2] * cos2alpha1 * sin2alpha2;
Z[1][3] = -P[3] * sin2alpha2;
Z[2][0] = P[1] * sin2alpha2;
Z[2][1] = P[4] * cos2alpha1 * sin2alpha2 + P[2] * sin2alpha1 * cos2alpha2;
Z[2][2] = -P[4] * sin2alpha1 * sin2alpha2 + P[2] * cos2alpha1 * cos2alpha2;
Z[2][3] = P[3] * cos2alpha2;
Z[3][0] = 0.0;
Z[3][1] = -P[3] * sin2alpha1;
Z[3][2] = -P[3] * cos2alpha1;
Z[3][3] = P[5];
/* scattering matrix multiplication */
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
phase_matrix[i][j] = 0.0;
for (k = 0; k < 4; k++) {
if (backward)
phase_matrix[i][j] += phase_matrix_inc[i][k] * Z[k][j];
else
phase_matrix[i][j] += Z[i][k] * phase_matrix_inc[k][j];
}
phase_matrix[i][j] /= P[0];
}
}
return 0;
}
/****************************************************************************/
/* Function: reflect_matrix_rotate @62_30i@ */
/* Description: */
/* Rotates the phase matrix of a reflection event and multiplies it with */
/* the photon phase matrix (product of all p. m.s along the photon path). */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/****************************************************************************/
int reflect_matrix_rotate (double** phase_matrix,
double** R,
double* dx_sca,
double* dx_inc,
double* n_hor,
double phi_source,
double phi_target,
int escape,
int scattercounter,
int backward,
double* rotmat1, //XXX
double* rotmat2) //XXX
{
int i = 0, j = 0, k = 0, status = 0;
double phase_matrix_inc[4][4];
double N = 0.0;
double n_ort_in[3], n_ort_out[3], n_ort_ref[3], n_ort_sin[3];
double n_z[3] = {0, 0, 1};
/* trick for making it possible to send matrices Z1,2 to subroutine via pointer */
double Z1m[4][4], Z2m[4][4];
double * Z1v[4] = {Z1m[0], Z1m[1], Z1m[2], Z1m[3]}, *Z2v[4] = {Z2m[0], Z2m[1], Z2m[2], Z2m[3]};
double **Z1 = Z1v, **Z2 = Z2v;
double cos2alpha1 = 1.0, sin2alpha1 = 0.0, cosalpha = 0.0;
double cos2alpha2 = 1.0, sin2alpha2 = 0.0, sinalpha = 0.0;
double scr = 0.0;
double * dx1 = NULL, *dx2 = NULL;
/* Copy photon phase matrix */
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
phase_matrix_inc[i][j] = phase_matrix[i][j];
if (backward) {
/*exchange incoming and scattered direction for backward */
dx2 = dx_inc;
dx1 = dx_sca;
scr = phi_target;
phi_target = phi_source;
phi_source = scr;
n_z[2] = -1;
} else {
dx1 = dx_inc;
dx2 = dx_sca;
}
if (n_hor[2] != 1.0) { /* do not rotate if n is already 0,0,1 */
/* Calculate vector orthogonal to incoming reflection plane */
status = v_cross_product_norm (dx1, n_hor, n_ort_in);
/* incoming and reflect direction are not parallel */
if (!status) {
/* incoming */
status = v_cross_product_norm (dx1, n_z, n_ort_ref);
if (status) {
/* Incoming direction || z-axis happens if SZA=0 */
/* Polarization plane (z, phi0) */
if (!(backward && escape) && !(!backward && scattercounter == 0)) {
fprintf (stderr, "scattercounter %d \n", scattercounter);
fprintf (stderr, "\n");
fprintf (stderr, "*** Warning, polarization plane of photon lost, because \n");
fprintf (stderr, "*** photon is scattered exactly in z-direction.\n");
fprintf (stderr, "*** If this happens too often please contact Robert.\n");
fprintf (stderr, "\n");
}
/* orthogonal vector to (z, phi_esc)-plane*/
n_ort_ref[0] = -cosd (phi_source);
n_ort_ref[1] = sind (phi_source);
n_ort_ref[2] = 0.0;
}
/* Calculate rotation angle 1 */
status = v_mult_mu (n_ort_in, n_ort_ref, &cosalpha);
CHKERR (status);
/* Calculate sinalpha using vector product */
v_cross_product (n_ort_in, n_ort_ref, n_ort_sin);
v_mult (n_ort_sin, n_ort_sin, &N);
sinalpha = -sqrt (N);
cos2alpha1 = cosalpha * cosalpha - sinalpha * sinalpha;
sin2alpha1 = 2.0 * sinalpha * cosalpha;
/* The sign of the following elements depends on phi:*/
if (n_ort_in[2] < 0.)
sin2alpha1 = -sin2alpha1;
phase_matr_rot (R, cos2alpha1, sin2alpha1, Z1);
} else
/* no rotation required, cos2alpha=1 by default */
Z1 = R;
/* Calculate vector orthogonal to outgoing reflection plane */
status = v_cross_product_norm (dx2, n_hor, n_ort_out);
/* incoming and reflect direction are not parallel */
if (!status) {
/* outgoing */
status = v_cross_product_norm (dx2, n_z, n_ort_ref);
if (status) {
/* In case of umu=+/- 1 we need to consider this special case: */
/* In forward mode and umu +/-1 the last rotation needs to be in the plane */
/* defined by (z, phi_sensor). */
/* In backward mode the first rotation.*/
if (!(!backward && escape) && !(backward && scattercounter == 0)) {
fprintf (stderr, "scattercounter %d \n", scattercounter);
fprintf (stderr, "\n");
fprintf (stderr, "*** Warning, polarization plane of photon lost, because \n");
fprintf (stderr, "*** photon is scattered exactly in z-direction.\n");
fprintf (stderr, "*** If this happens too often please contact Claudia.\n");
fprintf (stderr, "\n");
}
/* orthogonal vector to (z, phi_esc)-plane*/
n_ort_ref[0] = -cosd (phi_target);
n_ort_ref[1] = sind (phi_target);
n_ort_ref[2] = 0.0;
}
/* Calculate rotation angle 2 */
status = v_mult_mu (n_ort_out, n_ort_ref, &cosalpha);
CHKERR (status);
/* Calculate sinalpha using vector product */
v_cross_product (n_ort_out, n_ort_ref, n_ort_sin);
v_mult (n_ort_sin, n_ort_sin, &N);
sinalpha = +sqrt (N);
cos2alpha2 = cosalpha * cosalpha - sinalpha * sinalpha;
sin2alpha2 = 2.0 * sinalpha * cosalpha;
/* The sign of the following elements depends on phi:*/
if (n_ort_out[2] < 0.)
sin2alpha2 = -sin2alpha2;
/* fprintf(stderr, "no %d escape %d angle %g\n", scattercounter, escape, acos(cosalpha)*180/PI); */
rot_phase_matr (Z1, cos2alpha2, sin2alpha2, Z2);
} else
/* no rotation required, cos2alpha=1 by default */
Z2 = Z1;
} else
/* no rotation required, cos2alpha=1 by default */
Z2 = R;
/* scattering matrix multiplication */
/* fprintf(stderr,"matrix sigmas %e %e %e %e \n",cos2alpha1,sin2alpha1,cos2alpha2,sin2alpha2); */
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
/* fprintf(stderr," %e(%e)",R[i][j],Z2[i][j]); */
phase_matrix[i][j] = 0.0;
for (k = 0; k < 4; k++) {
if (backward)
phase_matrix[i][j] += phase_matrix_inc[i][k] * Z2[k][j];
else
phase_matrix[i][j] += Z2[i][k] * phase_matrix_inc[k][j];
}
/* XXX RPB: The following line is commented out. I think it is correct
this way. However, you could choose to do this in analogy to
scattering, then you would have to multiply R[0][0] to the photon
weight. Reason for doing so is that after many reflections, the
phase_matrix could become extremely small or large, leading to
numerical problems. It could maybe also affect VROOM, such that it
becomes extremely slow or very imprecise (the Stokes vector is only
partly taken into account for splitting). */
/* phase_matrix[i][j]/=R[0][0]; CHECK!!! */
}
/* fprintf(stderr,"\n"); */
}
return 0;
}
void phase_matr_rot (double** Z_in, double cos2alpha, double sin2alpha, double** Z_out) {
int i = 0;
for (i = 0; i < 4; i++) {
Z_out[i][0] = Z_in[i][0];
Z_out[i][1] = Z_in[i][1] * cos2alpha + Z_in[i][2] * sin2alpha;
Z_out[i][2] = -Z_in[i][1] * sin2alpha + Z_in[i][2] * cos2alpha;
Z_out[i][3] = Z_in[i][3];
}
}
void rot_phase_matr (double** Z_in, double cos2alpha, double sin2alpha, double** Z_out) {
int j = 0;
for (j = 0; j < 4; j++) {
Z_out[0][j] = Z_in[0][j];
Z_out[1][j] = Z_in[1][j] * cos2alpha - Z_in[2][j] * sin2alpha;
Z_out[2][j] = +Z_in[1][j] * sin2alpha + Z_in[2][j] * cos2alpha;
Z_out[3][j] = Z_in[3][j];
}
}
/***********************************************************************************/
/* Function: get_phase_matrix_caoth @62_30i@ */
/* Description: */
/* Obtain the phase matrix for caoth isp. */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Claudia Emde & Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static int get_phase_matrix_caoth (atmosphere_struct* atmos,
photon_struct* p,
int isp,
double mu,
int np,
/* Output */
double* phase_matrix) {
int status = 0;
switch (atmos->scatter_type[isp]) {
case MCSCAT_MOL: /* Rayleigh scattering */
get_phase_matrix_rayleigh (mu, atmos->rayleigh_depol, np, phase_matrix);
break;
case MCSCAT_AER: /* Aerosol scattering */
status = get_phase_matrix_pft (&(atmos->phase_aer[p->kc]), mu, 0, np, phase_matrix);
if (status)
return fct_err_out (status, "get_phase_matrix_pft", ERROR_POSITION);
break;
case MCSCAT_HG1:
if (np > 1) /* Henyey-Greenstein phase function can not be applied for polarization*/
return err_out ("Error %d returned\n The Henyey Greenstein phase function can not be used to calculate polarized radiances "
"with clouds.\n Please provide scattering phase matrices.",
-1);
phase_matrix[0] = HG (get_g1 (atmos, p, isp), mu);
break;
case MCSCAT_HG2:
if (np > 1) /* Henyey-Greenstein phase function can not be applied for polarization*/
return err_out ("Error %d returned\n The Henyey Greenstein phase function can not be used to calculate polarized radiances "
"with clouds.\n Please provide scattering phase matrices.",
-1);
phase_matrix[0] = HG2 (get_g1 (atmos, p, isp), get_g2 (atmos, p, isp), get_ff (atmos, p, isp), mu);
break;
case MCSCAT_PFT:
status = get_phase_matrix_pft_interpol_reff (mu, get_reff (atmos, p, isp), atmos->phase[isp], p->SC_mode, np, phase_matrix);
if (status)
return fct_err_out (status, "get_phase_matrix_pft_interpol_reff", ERROR_POSITION);
break;
default:
fprintf (stderr, "Error, no such type %d of scattering!!!\n", atmos->scatter_type[isp]);
return -1;
}
return 0;
}
/***********************************************************************************/
/* Function: calc_stokes_vector @62_30i@ */
/* Description: */
/* Pre-Calculate weight vector for the sensor direction */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Claudia Emde (put into subroutine by Robert Buras) */
/* @i62_30@ */
/***********************************************************************************/
static inline int calc_stokes_vector_for_escape (sample_struct* sample,
atmosphere_struct* atmos,
double* phase_matrix,
double mu2,
direction dir_inc,
double phi_esc,
direction dir_esc,
int polmat,
/* In-/Output */
photon_struct* p) {
int ip = 0, j = 0;
double phase_matrix_trivial[6] = {1, 0, 1, 0, 1, 1};
double tmp_dir[3];
/* calculate phase matrix for whole atmosphere and multiply it
with I_0. This works in forward and backward mode but might
take more CPU time */
if (polmat) {
const int status = phase_matrix_mult (p->phamat,
phase_matrix,
dir_esc.dx,
dir_inc.dx,
p->fw_phi0,
p->fw_phi,
1,
p->scattercounter,
sample->backward);
CHKERR (status);
/* turn polarisation in front of MFOV lidar detector */
if (sample->LidarLocEst) {
tmp_dir[0] = -sample->lidar[sample->ili].dir.dx[0];
tmp_dir[1] = -sample->lidar[sample->ili].dir.dx[1];
tmp_dir[2] = -sample->lidar[sample->ili].dir.dx[2];
const int status = phase_matrix_mult (p->phamat,
phase_matrix_trivial,
tmp_dir,
dir_esc.dx,
p->fw_phi0,
p->fw_phi,
1,
p->scattercounter,
sample->backward);
CHKERR (status);
}
/*Z_tot*I_0 (resulting phase matrix times I0, corresponds
to first column of Z for unpolarized incoming radiation
(1,0,0,0))*/
for (ip = 0; ip < 4; ip++) {
p->stokes[ip] = 0.0;
for (j = 0; j < 4; j++)
p->stokes[ip] += p->phamat[ip][j] * p->stokes0[j];
}
} else {
const int status = stokes_vector_sca (p->stokes, phase_matrix, dir_esc.dx, dir_inc.dx, p->fw_phi0, p->fw_phi);
CHKERR (status);
}
return 0;
}
/***********************************************************************************/
/* Function: derive_deltaphi_horz @62_30i@ */
/* Description: */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Claudia Emde (put into subroutine by Robert Buras) */
/* @i62_30@ */
/***********************************************************************************/
double derive_deltaphi_horz (double* dx, double phi_esc, int scattercounter, int LidarLocEst, double phi_init) {
double p_phi = 0.0, phi = 0.0;
/* Calculate azimuth of photon incoming direction */
if (scattercounter != 0 || LidarLocEst)
p_phi = calc_phi_horz (dx, NULL);
else
p_phi = phi_init;
/* Azimuth difference - very important to compute phase matrix */
phi = p_phi - phi_esc;
while (phi < 0.)
phi += 360.;
return phi;
}
/***********************************************************************************/
/* Function: get_reflection_probability_matrix */
/* Description: */
/* Calculate Stokes weight vector after a surface reflection taking */
/* into account the reflection matrix. This weight vector is then used in */
/* in the "local estimate" (escape_probability() ). */
/* So far only the BPDF by Tsang/Mishchenko is available, but other reflection */
/* matrices may be included in this function. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Claudia Emde */
/* */
/***********************************************************************************/
int get_reflection_probability_matrix (albedo_struct* albedo,
photon_struct* p,
int nstokes,
int backward,
double mu_inc,
double phi_inc,
double mu_esc,
double phi_esc,
int ia,
int ja,
int il,
float wvnmlo,
float wvnmhi,
int iv,
/* Output */
double*** refl_mat) {
int status = 0;
float wavelength = 0.0;
switch (albedo->method) {
case MCALB_HAPKE:
case MCALB_ROSSLI:
case MCALB_ROSSLI2D:
case MCALB_COXANDMUNK:
fprintf (stderr, "Error, albedo->method %d not yet implemented with polarisation!\n", albedo->method);
return -1;
case MCALB_RPV:
case MCALB_RPV2D_SPECTRAL:
case MCALB_AMBRALS2D_SPECTRAL:
/* CE: Why is Tsang here included for RPV2D?? */
ASCII_calloc_double (refl_mat, 4, 4);
if (il == 0 && (albedo->method == MCALB_RPV2D_SPECTRAL || albedo->method == MCALB_AMBRALS2D_SPECTRAL)) {
/* Wavelength in micron */
wavelength = 0.5 * 1e4 * (1.0 / wvnmlo + 1.0 / wvnmhi);
if (backward)
status = bpdf_tsang (albedo->u10, wavelength, mu_esc, phi_esc, mu_inc, phi_inc, refl_mat);
else
status = bpdf_tsang (albedo->u10, wavelength, mu_inc, phi_inc, mu_esc, phi_esc, refl_mat);
if (status)
return fct_err_out (status, "bpdf_tsang", ERROR_POSITION);
} else {
switch (albedo->method) {
case MCALB_RPV:
case MCALB_RPV2D_SPECTRAL:
(*refl_mat)[0][0] = rpv_brdf (albedo->rpv[il].rho0,
albedo->rpv[il].k,
albedo->rpv[il].theta,
albedo->rpv[il].scale,
albedo->rpv[il].sigma,
albedo->rpv[il].t1,
albedo->rpv[il].t2,
mu_inc,
mu_esc,
fabs ((phi_esc - phi_inc) * 180.0 / PI));
break;
case MCALB_AMBRALS2D_SPECTRAL:
#if 1
(*refl_mat)[0][0] =
c_bidir_reflectivity_rossli (&(albedo->rossli[il]), mu_inc, mu_esc, fabs ((phi_esc - phi_inc) * 180.0 / PI));
#else
// former version
(*refl_mat)[0][0] = ambrals_brdf (albedo->rossli[il].iso,
albedo->rossli[il].vol,
albedo->rossli[il].geo,
mu_inc,
mu_esc,
fabs ((phi_esc - phi_inc) * 180.0 / PI));
#endif
break;
default:
fprintf (stderr, "Error, albedo->method %d not yet implemented!\n", albedo->method);
status = -1;
return status;
}
}
break;
case MCALB_LAM:
ASCII_calloc_double (refl_mat, 4, 4);
if (iv == -1)
(*refl_mat)[0][0] = albedo->albedo;
else
(*refl_mat)[0][0] = albedo->spectral_albedo[iv];
break;
case MCALB_LAM2D:
ASCII_calloc_double (refl_mat, 4, 4);
(*refl_mat)[0][0] = albedo->albedo2D[ia][ja];
/* CE: dirty hack to include ocean in earthshine simulations */
//fprintf(stderr, "ia %d ja %d albedo %f \n", ia, ja, albedo->albedo2D[ia][ja]);
if (albedo->albedo2D[ia][ja] == -1) { /*in albedo file all water is set to -1 */
/* Wavelength in micrometer */
//fprintf(stderr, "use BPDF for water reflection u10 %f \n", albedo->u10);
albedo->u10 = 10.0;
wavelength = 0.5 * 1e4 * (1.0 / wvnmlo + 1.0 / wvnmhi);
if (backward)
status = bpdf_tsang (albedo->u10, wavelength, mu_esc, phi_esc, mu_inc, phi_inc, refl_mat);
else
status = bpdf_tsang (albedo->u10, wavelength, mu_inc, phi_inc, mu_esc, phi_esc, refl_mat);
if (status)
return fct_err_out (status, "bpdf_tsang", ERROR_POSITION);
}
break;
case MCALB_LAM2D_SPECTRAL:
ASCII_calloc_double (refl_mat, 4, 4);
(*refl_mat)[0][0] = albedo->alb_type[(int)albedo->surface_index[ia][ja]];
break;
case MCALB_TSANG:
ASCII_calloc_double (refl_mat, 4, 4);
/* Wavelength in micrometer */
wavelength = 0.5 * 1e4 * (1.0 / wvnmlo + 1.0 / wvnmhi);
if (backward)
status = bpdf_tsang (albedo->u10, wavelength, mu_esc, phi_esc, mu_inc, phi_inc, refl_mat);
else
status = bpdf_tsang (albedo->u10, wavelength, mu_inc, phi_inc, mu_esc, phi_esc, refl_mat);
if (status)
return fct_err_out (status, "bpdf_tsang", ERROR_POSITION);
break;
default:
fprintf (stderr, "Error, albedo->method %d not yet implemented!\n", albedo->method);
status = -1;
return status;
}
return 0;
}
/***********************************************************************************/
/* Function: reflection_polarized */
/* Description: */
/* Calculate Stokes weight vector after a surface reflection taking */
/* into account the reflection matrix. This weight vector is then used in */
/* in the "local estimate" (escape_probability() ). */
/* So far only the BPDF by Tsang/Mishchenko is available, but other reflection */
/* matrices may be included in this function. */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Claudia Emde */
/* */
/***********************************************************************************/
static double reflection_polarized (albedo_struct* albedo,
photon_struct* p,
int nstokes,
int backward,
double* dx_inc,
double* dx_out,
double* n_hor,
double mu_inc,
double phi_inc,
double mu_esc,
double phi_esc,
double phi_target,
int ia,
int ja,
int il,
float wvnmlo,
float wvnmhi,
int escape,
int spherical3D,
int spectral_is,
int nlambda,
float* lambda,
int* status) {
int iv = 0;
double** refl_mat = NULL;
#ifdef MUCHOUT
int ip;
#endif
*status = 0;
if (mu_esc <= 0.0)
return 0.0;
if (!(albedo->reflectalways)) {
fprintf (stderr, "Error, polarisation requires option mc_surface_reflectalways!\n");
*status = -1;
return NOT_A_NUMBER;
}
*status = get_reflection_probability_matrix (albedo,
p,
nstokes,
backward,
mu_inc,
phi_inc,
mu_esc,
phi_esc,
ia,
ja,
il,
wvnmlo,
wvnmhi,
-1,
&refl_mat);
if (*status)
return fct_err_out (*status, "get_reflection_probability_matrix", ERROR_POSITION);
/* Only Lambertian spectral albedo is considered for ALIS so far, for */
/* bpdf_tsang wavelength dependance is only due to changes in the */
/* refractive index of water which is very small. For the whole */
/* spectral range the refractive index of the calculation wavelength */
/* is assumed. Calling get_reflection_probability_matrix in the loop over*/
/* wavelengths is very expensive.*/
if (spectral_is) {
switch (albedo->method) {
/* For the first cases we do not expect that ALIS uses spectral albedo, */
/* so we do not throw a warning. */
case MCALB_HAPKE:
case MCALB_ROSSLI:
case MCALB_ROSSLI2D:
case MCALB_COXANDMUNK:
case MCALB_RPV:
case MCALB_LAM2D:
case MCALB_RPV2D_SPECTRAL:
case MCALB_TSANG:
break;
case MCALB_LAM:
if (albedo->spectral_albedo != NULL && refl_mat[0][0] != 0.0) {
for (iv = 0; iv < nlambda; iv++) {
p->q_albedo_spectral[iv] *= albedo->spectral_albedo[iv] / refl_mat[0][0];
}
}
break;
case MCALB_LAM2D_SPECTRAL:
if (refl_mat[0][0] != 0.0) {
for (iv = 0; iv < nlambda; iv++) {
if (spherical3D) {
#if HAVE_MYSTIC3D
coord_spherical3D (p, albedo->Nx, albedo->X, albedo->Ny, albedo->Y, 0, NULL, 0, NULL, 0, &ia, &ja, NULL, NULL, 0);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else
albedo_coord (p, albedo, &ia, &ja);
p->q_albedo_spectral[iv] *= albedo->spectral_alb_type[(int)albedo->surface_index[ia][ja]][iv] / refl_mat[0][0];
}
}
break;
default:
fprintf (stderr, "Error, albedo->method %d not yet implemented!\n", albedo->method);
*status = -1;
return NOT_A_NUMBER;
}
}
reflect_matrix_rotate (p->phamat,
refl_mat,
dx_out,
dx_inc,
n_hor,
p->phi0,
phi_target,
escape,
p->scattercounter,
backward,
NULL,
NULL);
/* scattering matrix multiplication */
mat_v_mult (4, p->phamat, p->stokes0, p->stokes);
#ifdef MUCHOUT
if (p->muchoutcounter == MUCHOUTPHOTON) {
for (ip = 0; ip < nstokes; ip++)
fprintf (stderr, "refl_mat %e %e %e %e\n", refl_mat[ip][0], refl_mat[ip][1], refl_mat[ip][2], refl_mat[ip][3]);
for (ip = 0; ip < nstokes; ip++)
fprintf (stderr, "phamat %e %e %e %e\n", p->phamat[ip][0], p->phamat[ip][1], p->phamat[ip][2], p->phamat[ip][3]);
fprintf (stderr, "stokes %e %e %e %e\n", p->stokes[0], p->stokes[1], p->stokes[2], p->stokes[3]);
}
#endif
ASCII_free_double (refl_mat, 4);
/* Isotropic scattering, BPDF or Lambertian albedo included in Stokes weight vector */
return 1.0;
}
/***********************************************************************************/
/* Function: correct_escape_dir_refract @62_30i@ */
/* Description: */
/* Correct the photon direction for the calculation of the escape probability */
/* the point of scattering towards the sun. */
/* Note: This is the first not yet fully verified version, which might be changed */
/* later on. */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Claudia Emde */
/* @i62_30@ */
/***********************************************************************************/
static int correct_escape_dir_refract (double* dir_sensor,
photon_struct* photon,
atmosphere_struct* atmos,
sample_struct* sample,
float* refind) {
double step = 0.0;
int id = 0, i = 0, status = 0;
int counter = 0;
photon_struct* p = calloc_photon (sample, 0, 0, 0, MCSRC_NONE, atmos->nlambda_abs, atmos->Nc, atmos->n_caoth);
double diff[3], N = 0.0;
double diff_abs = 999., diff_abs_old = 999., a_old = 0.0, a_new = 0.0, a = 0.0;
/* double dir_scatpoint[3]; */
/* double dir_sza; */
double e_r[3];
double epsilon = 1e-6;
/* work on a copy of the photon, not the original one */
cp_photon_struct (p, photon, sample, atmos->n_caoth);
/* the direction to be traced is the radiance direction */
cp_direction (&(p->dir), &(sample->rad[id].dir));
/* initialize status; if unchanged at end of travel step, the photon crosses a grid boundary */
p->photon_status = MCSTATUS_TRAVEL;
/* fprintf(stderr, "Correct direction for local estimate ... \n"); */
/* dir_start=p->dir.dx[2]; */
/* dir_sza=p->dir.dx[2]; */
e_r[0] = p->x[0] - atmos->xmax / 2.;
e_r[1] = p->x[1] - atmos->ymax / 2.;
e_r[2] = p->x[2] + atmos->r_earth;
N = 0;
for (i = 0; i < 3; i++) {
N += e_r[i] * e_r[i];
}
for (i = 0; i < 3; i++)
e_r[i] /= sqrt (N);
/* fprintf(stderr, "e_r %g %g %g \n", e_r[0],e_r[1],e_r[2]); */
/* how accurate do we need the escape radiance angle? Is 1e-5 required?*/
while (diff_abs > 1e-4) {
for (i = 0; i < 3; i++)
p->dir.dx[i] += a * e_r[i];
/* Normalize direction vector */
N = sqrt (p->dir.dx[0] * p->dir.dx[0] + p->dir.dx[1] * p->dir.dx[1] + p->dir.dx[2] * p->dir.dx[2]);
for (i = 0; i < 3; i++)
p->dir.dx[i] /= N;
/* fprintf(stderr, "at scattering point p->dir.dx %g %g %g \n", p->dir.dx[0], p->dir.dx[1], p->dir.dx[2]); */
/* for (i=0; i<3; i++) */
/* dir_scatpoint[i]= p->dir.dx[i]; */
while (1 == 1) {
/*******************************************************************/
/* 1. Calculate step length to next boundary */
/*******************************************************************/
status = intersection1D_spherical (p, atmos, sample->refraction, refind, &step);
/* Photon is absorbed by the surface.*/
if (status < 0)
break;
if (step < 0)
step = 0;
/*******************************************************************/
/* 2. apply step length, move photon, and exit if photon path ends */
/*******************************************************************/
/* sum up absorption and scattering optical depths */
/* step is the escape distance within each box between two box boundaries (or between initital photon position and box boundary) depending on the escape direction */
p->tauabs.tot += step * (get_ksca (atmos, p, MCCAOTH_TOT) + get_kabs_tot (atmos, p));
p->pathlength += step;
status = step1D (p, atmos, step, sample->bcond, 0, 0);
/* end photon travel unless it simply crosses the boundary */
if (p->photon_status != MCSTATUS_TRAVEL)
break;
/**********************************/
/* 3. check if photon leaves grid */
/**********************************/
/* finally check if photon arrived at the lower surface */
/* or at the top of the atmosphere */
if (p->kc < 0) {
/* fprintf(stderr, "at BOA p->dir.dx[2] %g \n", p->dir.dx[2]); */
p->photon_status = MCSTATUS_BOUNDARY_LOWER;
break;
}
if (p->kc > atmos->Nz - 1) {
/* fprintf(stderr, "at TOA p->dir.dx[2] %g \n", p->dir.dx[2]); */
p->photon_status = MCSTATUS_BOUNDARY_UPPER;
break;
}
}
diff_abs_old = diff_abs;
N = 0;
for (i = 0; i < 3; i++) {
diff[i] = p->dir.dx[i] - sample->rad[id].dir.dx[i];
N += diff[i] * diff[i];
}
diff_abs = sqrt (N);
/* Initialize new photon */
cp_photon_struct (p, photon, sample, atmos->n_caoth);
cp_direction (&(p->dir), &(sample->rad[id].dir));
p->photon_status = MCSTATUS_TRAVEL;
counter += 1;
/* fprintf(stderr, "iteration %d diff %g %g %g diffabs %g \n", counter, diff[0], diff[1], diff[2], diff_abs); */
/* fprintf(stderr, "diff_abs_old %g a_old %g diff_abs %g, a_new %g \n", */
/* diff_abs_old, a_old, diff_abs, a); */
/* Factor a to be found in iteration */
/* First guess */
if (counter == 1) {
a = 0.01;
a_new = 0.01;
a_old = 0.0;
} else {
a_new = (diff_abs * a_old + diff_abs_old * a) / (diff_abs_old + diff_abs);
a_old = a;
a = a_new;
/* a+=0.0001; */
}
if (fabs (diff_abs - diff_abs_old) < epsilon) {
/* fprintf(stderr, "Warning, refraction accurracy %g %g \n", diff_abs_old, diff_abs); */
break;
}
/* fprintf(stderr, "a_new %g \n", a); */
}
for (i = 0; i < 3; i++)
dir_sensor[i] = p->dir.dx[i];
/* free memory */
destroy_photon (p, atmos->n_caoth);
return 0;
}
/***********************************************************************************/
/* Function: set_panorama_dir @62_30i@ */
/* Description: */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Bernhard Reinhard, Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
int set_panorama_dir (sample_struct* sample, float* sza, float* phi0) {
double dtheta = 0, theta_min = 0, theta_max = 0;
double phi_min = 0, phi_max = 0, dphi = 0;
double upper_theta = 0, lower_theta = 0;
double addhalf = 0;
double sinalpha = 0, mu2 = 0;
double xc[3] = {0, 0, 0};
if (sample->pan_n_from_file == 0) {
if (sample->pan_distr_photons_over_pixel && sample->pan_no_pixel) {
fprintf (stderr, "ERROR: pan_no_pixel and pan_distr_photons_over_pixel may not be used together!\n");
exit (1);
}
/* assuming you want to simulate a CCD-camera */
/* Either by the simple method of sending all photons from the center of */
/* the individual CCD pixels, or by the more realistic option of */
/* distributing the photons over the finite solid angle covered by the */
/* individual pixels */
/* if pan_no pixel set, distribute angles in such manner that */
/* theta_min/theta_max; phi_min/phi_max as provided by user input file */
/* are directly faced */
theta_min = sample->pan_theta_min;
theta_max = sample->pan_theta_max;
phi_min = sample->pan_phi_min;
phi_max = sample->pan_phi_max;
if (sample->pan_umu_min < -2.0) {
/* "cartesian" coordinates (fish-eye) */
/* names need cleaning up !!! BCA */
sinalpha = sind (phi_max);
xc[0] = sinalpha * (2.0 * ((double)sample->backward_is + 0.5) / (double)sample->Nx - 1.0);
xc[1] = sinalpha * (2.0 * ((double)sample->backward_js + 0.5) / (double)sample->Ny - 1.0);
xc[2] = 0.0;
mu2 = xc[0] * xc[0] + xc[1] * xc[1];
if (mu2 > sinalpha * sinalpha) /* this angle does not exist, or should not be calculated */
return 1;
*sza = asind (sqrt (mu2));
*phi0 = calc_phi_horz (xc, NULL); /* check if +-90/180; or toggle 0][1 */
/* error messages for modes not working BCA */
return 0;
}
/* define dtheta */
if (sample->Ny - sample->pan_no_pixel > 0) {
dtheta = (theta_max - theta_min) / (double)(sample->Ny - sample->pan_no_pixel);
} else {
dtheta = 0.0;
if (theta_max != theta_min) {
fprintf (stderr,
"%s %s %s %s",
"Panorama_no_pixel: Theta_max != Theta_min but setup only",
"calculation at one specific theta. Will do the calculation",
"at theta_min. Maybe you want to increase the numbers at",
"mc_sample_grid?!\n");
return -1;
}
}
/* define dphi */
if (sample->Nx - sample->pan_no_pixel > 0)
dphi = (sample->pan_phi_max - sample->pan_phi_min) / (double)(sample->Nx - sample->pan_no_pixel);
else {
dphi = 0.;
if (phi_max != phi_min) {
fprintf (stderr,
"%s %s %s %s",
"Panorama_no_pixel: Phi_max != Phi_min but setup only",
"calculation at one specific phi. Will do the calculation",
"at phi_min. Maybe you want to increase the numbers at",
"mc_sample_grid?!\n");
return -1;
}
}
if (sample->pan_distr_photons_over_pixel) {
lower_theta = (sample->pan_theta_min + dtheta * (double)sample->backward_js);
upper_theta = lower_theta + dtheta;
sample->pan_FOV = -dphi / 180.0 * PI * (cosd (upper_theta) - cosd (lower_theta));
addhalf = 0.0;
} else
addhalf = 0.5;
/* calculate sza = minimum + delta times number of pixel*/
*sza = theta_min + dtheta * ((double)sample->backward_js + addhalf);
/* calculate phi0 */
*phi0 = phi_min + dphi * ((double)sample->backward_is + addhalf);
sample->pan_dphi = dphi;
sample->pan_dtheta = dtheta;
} else { // table of angles, e.g. read from mc_panorama_file
*sza = sample->pan_theta_from_file[sample->backward_js];
*phi0 = sample->pan_phi_from_file[sample->backward_js];
}
return 0;
}
/***********************************************************************************/
/* Function: std_noisy @62_30i@ */
/* Description: */
/* Calculate standard deviation, taking into account that the input might suffer */
/* from computational noise and set to 0 instead of sqrt(-tiny number) = NaN */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
static inline double std_noisy (double var, double avg, double dmcphotons) {
if (fabs (var / avg / avg - 1.0) >= MC_EPSILON * MC_EPSILON)
return sqrt ((var - avg * avg) / dmcphotons);
else
return 0.0;
}
/***********************************************************************************/
/* Function: Fresnel @62_30i@ */
/* Description: */
/* Stolen from Cox & Munk */
/* */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Robert Buras */
/* @i62_30@ */
/***********************************************************************************/
double Fresnel (double nr, double ni, double coschi) {
/*
C to compute the Fresnel's coefficient of reflection (see for
C example M. Born and E. Wolf, Principles of Optics, Pergamon Press,
C fifth edition, 1975, pp 628; seventh edition, 1999, pp 753
C input parameters: nr=index of refraction of the sea water
C ni=extinction coefficient of the sea water
C coschi & sinchi=cosine and sine of the incident radiation
C with respect of the wave facet normal.
C output parameter: R1=Fresnel's coefficient for reflection
*/
double nr2 = 0.0, ni2 = 0.0, a1 = 0.0, a2 = 0.0, u = 0.0, v = 0.0;
double Rr2 = 0.0, b1 = 0.0, b2 = 0.0, Rl2 = 0.0;
double sinchi = sqrt (1.0 - coschi * coschi);
/* absolute value for a1 to get v=0 when ni=0 */
nr2 = nr * nr;
ni2 = ni * ni;
a1 = nr2 - ni2 - sinchi * sinchi;
a1 = a1 > 0.0 ? a1 : -a1;
a2 = sqrt (a1 * a1 + 4.0 * nr2 * ni2);
/* bm:
added the abs because a1 quite often equals a2,
except for very small rounding errors that cause
nonsense because the sqrt of a negative number is NAN */
u = a1 + a2;
u = u > 0.0 ? u : -u;
u = sqrt (0.5 * u);
v = -a1 + a2;
v = v > 0.0 ? v : -v;
v = sqrt (0.5 * v);
Rr2 = ((coschi - u) * (coschi - u) + v * v) / ((coschi + u) * (coschi + u) + v * v);
b1 = (nr2 - ni2) * coschi;
b2 = 2 * nr * ni * coschi;
/* bm:
changed the following line which was buggy in the original
6S code */
Rl2 = ((b1 - u) * (b1 - u) + (b2 - v) * (b2 - v)) / ((b1 + u) * (b1 + u) + (b2 + v) * (b2 + v));
return (Rr2 + Rl2) / 2.;
}
void index_water (double wl, double xsal, double* nr, double* ni) {
/*
C input parameters: wl=wavelength (in micrometers)
C xsal=salinity (in ppt), if xsal<0 then 34.3ppt by default
C output parameters: nr=index of refraction of sea water
C ni=extinction coefficient of sea water
*/
int i = 0;
double xwl = 0.0, yr = 0.0, yi = 0.0;
double nrc = 0.0, nic = 0.0;
/*
C Indices of refraction for pure water from Hale and Querry,
C Applied Optique, March 1973, Vol. 12, No. 3, pp. 555-563
*/
double twl[] = {0.250, 0.275, 0.300, 0.325, 0.345, 0.375, 0.400, 0.425, 0.445, 0.475, 0.500, 0.525, 0.550, 0.575, 0.600, 0.625,
0.650, 0.675, 0.700, 0.725, 0.750, 0.775, 0.800, 0.825, 0.850, 0.875, 0.900, 0.925, 0.950, 0.975, 1.000, 1.200,
1.400, 1.600, 1.800, 2.000, 2.200, 2.400, 2.600, 2.650, 2.700, 2.750, 2.800, 2.850, 2.900, 2.950, 3.000, 3.050,
3.100, 3.150, 3.200, 3.250, 3.300, 3.350, 3.400, 3.450, 3.500, 3.600, 3.700, 3.800, 3.900, 4.000};
/* double tnr[] = { */
/* 1.362,1.354,1.349,1.346,1.343,1.341,1.339,1.338,1.337,1.336, */
/* 1.000,1.100,1.200,1.300,1.400,1.500,1.600,1.700,1.800,1.900, */
/* 1.330,1.330,1.329,1.329,1.329,1.328,1.328,1.328,1.327,1.327, */
/* 1.327,1.324,1.321,1.317,1.312,1.306,1.296,1.279,1.242,1.219, */
/* 1.188,1.157,1.142,1.149,1.201,1.292,1.371,1.426,1.467,1.483, */
/* 1.478,1.467,1.450,1.432,1.420,1.410,1.400,1.385,1.374,1.364, */
/* 1.357,1.351 }; */
/* double tni[] = { */
/* 3.35E-08,2.35E-08,1.60E-08,1.08E-08,6.50E-09, */
/* 3.50E-09,1.86E-09,1.30E-09,1.02E-09,9.35E-10, */
/* 1.00E-09,1.32E-09,1.96E-09,3.60E-09,1.09E-08, */
/* 1.39E-08,1.64E-08,2.23E-08,3.35E-08,9.15E-08, */
/* 1.56E-05,1.48E-03,1.25E-01,1.82E-07,2.93E-07, */
/* 3.91E-07,4.86E-07,1.06E-06,2.93E-06,3.48E-06, */
/* 2.89E-06,9.89E-06,1.38E-04,8.55E-05,1.15E-04, */
/* 1.10E-03,2.89E-04,9.56E-04,3.17E-03,6.70E-03, */
/* 1.90E-02,5.90E-02,1.15E-01,1.85E-01,2.68E-01, */
/* 2.98E-01,2.72E-01,2.40E-01,1.92E-01,1.35E-01, */
/* 9.24E-02,6.10E-02,3.68E-02,2.61E-02,1.95E-02, */
/* 1.32E-02,9.40E-03,5.15E-03,3.60E-03,3.40E-03, */
/* 3.80E-03,4.60E-03 }; */
/* double tnr[] = { */
/* 1.362,1.354,1.349,1.346,1.343,1.341,1.339,1.338,1.337,1.336, */
/* 1.335,1.334,1.333,1.333,1.332,1.332,1.331,1.331,1.331,1.330, */
/* 1.330,1.330,1.329,1.329,1.329,1.328,1.328,1.328,1.327,1.327, */
/* 1.327,1.324,1.321,1.317,1.312,1.306,1.296,1.279,1.242,1.219, */
/* 1.188,1.157,1.142,1.149,1.201,1.292,1.371,1.426,1.467,1.483, */
/* 1.478,1.467,1.450,1.432,1.420,1.410,1.400,1.385,1.374,1.364, */
/* 1.357,1.351 }; */
/* double tni[] = { */
/* 3.35E-08,2.35E-08,1.60E-08,1.08E-08,6.50E-09, */
/* 3.50E-09,1.86E-09,1.30E-09,1.02E-09,9.35E-10, */
/* 1.00E-15,1.00E-14,1.00E-13,1.00E-12,1.00E-11, */
/* 1.00E-10,1.00E-09,1.00E-08,1.00E-07,1.00E-06, */
/* 1.56E-07,1.48E-07,1.25E-07,1.82E-07,2.93E-07, */
/* 3.91E-07,4.86E-07,1.06E-06,2.93E-06,3.48E-06, */
/* 2.89E-06,9.89E-06,1.38E-04,8.55E-05,1.15E-04, */
/* 1.10E-03,2.89E-04,9.56E-04,3.17E-03,6.70E-03, */
/* 1.90E-02,5.90E-02,1.15E-01,1.85E-01,2.68E-01, */
/* 2.98E-01,2.72E-01,2.40E-01,1.92E-01,1.35E-01, */
/* 9.24E-02,6.10E-02,3.68E-02,2.61E-02,1.95E-02, */
/* 1.32E-02,9.40E-03,5.15E-03,3.60E-03,3.40E-03, */
/* 3.80E-03,4.60E-03 }; */
double tnr[] = {1.362, 1.354, 1.349, 1.346, 1.343, 1.341, 1.339, 1.338, 1.337, 1.336, 1.335, 1.334, 1.333, 1.333, 1.332, 1.332,
1.331, 1.331, 1.331, 1.330, 1.330, 1.330, 1.329, 1.329, 1.329, 1.328, 1.328, 1.328, 1.327, 1.327, 1.327, 1.324,
1.321, 1.317, 1.312, 1.306, 1.296, 1.279, 1.242, 1.219, 1.188, 1.157, 1.142, 1.149, 1.201, 1.292, 1.371, 1.426,
1.467, 1.483, 1.478, 1.467, 1.450, 1.432, 1.420, 1.410, 1.400, 1.385, 1.374, 1.364, 1.357, 1.351};
double tni[] = {3.35E-08, 2.35E-08, 1.60E-08, 1.08E-08, 6.50E-09, 3.50E-09, 1.86E-09, 1.30E-09, 1.02E-09, 9.35E-10, 1.00E-09,
1.32E-09, 1.96E-09, 3.60E-09, 1.09E-08, 1.39E-08, 1.64E-08, 2.23E-08, 3.35E-08, 9.15E-08, 1.56E-07, 1.48E-07,
1.25E-07, 1.82E-07, 2.93E-07, 3.91E-07, 4.86E-07, 1.06E-06, 2.93E-06, 3.48E-06, 2.89E-06, 9.89E-06, 1.38E-04,
8.55E-05, 1.15E-04, 1.10E-03, 2.89E-04, 9.56E-04, 3.17E-03, 6.70E-03, 1.90E-02, 5.90E-02, 1.15E-01, 1.85E-01,
2.68E-01, 2.98E-01, 2.72E-01, 2.40E-01, 1.92E-01, 1.35E-01, 9.24E-02, 6.10E-02, 3.68E-02, 2.61E-02, 1.95E-02,
1.32E-02, 9.40E-03, 5.15E-03, 3.60E-03, 3.40E-03, 3.80E-03, 4.60E-03};
/* locate */
i = 1;
while (wl >= twl[i] && i < 61)
i++;
xwl = twl[i] - twl[i - 1];
yr = tnr[i] - tnr[i - 1];
yi = tni[i] - tni[i - 1];
*nr = tnr[i - 1] + (wl - twl[i - 1]) * yr / xwl;
*ni = tni[i - 1] + (wl - twl[i - 1]) * yi / xwl;
/*
c Correction to be applied to the index of refraction and to the extinction
c coefficients of the pure water to obtain the ocean water one (see for
c example Friedman). By default, a typical sea water is assumed
c (Salinity=34.3ppt, Chlorinity=19ppt) as reported by Sverdrup.
c In that case there is no correction for the extinction coefficient between
c 0.25 and 4 microns. For the index of refraction, a correction of +0.006
c has to be applied (McLellan). For a chlorinity of 19.0ppt the correction
c is a linear function of the salt concentration. Then, in 6S users are able
c to enter the salt concentration (in ppt).
c REFERENCES:
c Friedman D., Applied Optics, 1969, Vol.8, No.10, pp.2073-2078.
c McLellan H.J., Elements of physical Oceanography, Pergamon Press, Inc.,
c New-York, 1965, p 129.
c Sverdrup H.V. et al., The Oceans (Prentice-Hall, Inc., Englewood Cliffs,
c N.J., 1942, p 173.
*/
nrc = 0.006;
nic = 0.000;
*nr = *nr + nrc * (xsal / 34.3);
*ni = *ni + nic * (xsal / 34.3);
}
/***********************************************************************************/
/* Function: find_tau_ext @62_30i@ */
/* Description: */
/* Find extinction between two given points */
/* Code mostly taken from escape_probability() */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Christian Pause */
/* @i62_30@ */
/***********************************************************************************/
int find_tau_ext (photon_struct* photon,
atmosphere_struct* atmos,
sample_struct* sample,
elevation_struct* elev,
int ic,
int jc,
int kc,
float* refind,
double* dx,
double* start,
double path,
double* tau_save) {
double step = 0.0, gamma = 0.0;
int status = 0;
int is_threed = 0;
int j = 0;
/* double pt[3]; */
int first = 1;
/* prepare things */
photon_struct* p =
calloc_photon (sample, atmos->Nx, atmos->Ny, atmos->Nz, MCSRC_NONE, atmos->nlambda_abs, atmos->Nc, atmos->n_caoth);
/* work on a copy of the photon, not the original one */
cp_photon_struct (p, photon, sample, atmos->n_caoth);
/* set direction and starting point */
for (j = 0; j < 3; j++) {
p->dir.dx[j] = dx[j];
p->x[j] = start[j];
}
p->ic = ic;
p->jc = jc;
p->kc = kc;
p->pathlength = 0.;
p->tauext_tot = 0.;
p->tauabs.tot = 0.;
/* adjust p->dir.hit if neccessary */
for (j = 0; j < 3; j++) {
if (p->dir.dx[j] > 0.0)
p->dir.hit[j] = 1;
else if (p->dir.dx[j] < 0.0)
p->dir.hit[j] = 0;
else
p->dir.hit[j] = -1;
}
/* initialize status; if unchanged at end of travel step, the photon crosses a grid boundary */
p->photon_status = MCSTATUS_TRAVEL;
p->RIS_mode = MCRIS_MODE_NORMAL;
p->VIS_mode = MCVIS_MODE_NORMAL;
while (1 == 1) { /* until photon reaches the surface or TOA */
is_threed = (atmos->threed[MCCAOTH_TOT][p->kc] >= 1); /* 3D layer */
/**************************************************************/
/* 1. find out what happens next with photon, and step length */
/**************************************************************/
/* calculate next intersection point with the box boundaries */
if (sample->spherical3D) {
#if HAVE_MYSTIC3D
status = intersection3D_spherical (p, atmos, sample->spherical3D_scene, &first, &step);
if (status)
return err_out ("Error %d returned by intersection3D_spherical\n", status);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else {
if (is_threed == 1) { /* 3D layer */
#if HAVE_MYSTIC3D
status = intersection3D (p, atmos, 10000, 0, &step);
if (status)
return err_out ("Error %d returned by intersection3D\n", status);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else {
if (sample->spherical) {
status = intersection1D_spherical (p, atmos, sample->refraction, refind, &step);
/* Photon is absorbed by the surface.*/
if (status < 0)
break;
} else {
intersection1D (p, atmos, 10000, 0, &step, 0);
}
}
}
if (step < 0)
step = 0;
/* check if photon crossed the 2D surface */
if (elev->elev2D) {
status = cross_surface (p, step, elev, sample->bcond, &gamma);
/* if cross_surface ran into some inconsistency */
if (status < 0) {
fprintf (stderr, "Something terrible has happened! cross_surface() returned\n");
fprintf (stderr, "status %d\n", status);
return -1;
}
if (status > 0) {
step = gamma;
p->photon_status = MCSTATUS_SURFACE;
}
}
if (p->pathlength + step >= path) {
step = path - p->pathlength;
p->photon_status = MCSTATUS_DEFAULT;
}
/*******************************************************************/
/* 2. apply step length, move photon, and exit if photon path ends */
/*******************************************************************/
/* sum up absorption optical depth */
/*tau_ext += step * (get_kabs_tot (atmos, p) + get_ksca (atmos, p, MCCAOTH_TOT));*/
p->pathlength += step;
mc_add_optical_depth (atmos, p, step, sample->coherent_backscatter);
/* for (j=0; j<3; j++) */
/* pt[j] = p->x[j] + step * p->dir.dx[0]; */
/* move photon to box boundary, to next scattering point, */
/* or to the 2D surface */
if (is_threed == 1 || sample->spherical3D) { /* 3D layer */
#if HAVE_MYSTIC3D
status = step3D (p, atmos, step, sample->bcond, 0, sample->spherical3D, 0);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else
status = step1D (p, atmos, step, sample->bcond, 0, 0);
if (status < 0) {
fprintf (stderr, "Error %d returned by step%dD()\n", status, (is_threed == 1 ? 3 : 1));
return status;
}
/* end photon travel unless it simply crosses the boundary */
if (p->photon_status != MCSTATUS_TRAVEL)
break;
/**********************************/
/* 3. check if photon leaves grid */
/**********************************/
/* finally check if photon arrived at the lower surface */
/* or at the top of the atmosphere */
if (p->kc < 0) {
p->photon_status = MCSTATUS_BOUNDARY_LOWER;
if (elev->elev2D) {
fprintf (stderr, "FATAL error! Escape photon reached the 1D boundary in a\n");
fprintf (stderr, " 2D elevation case (%dD layer)!\n\n", (is_threed == 1 ? 3 : 1));
return -1;
}
break;
}
if (p->kc > atmos->Nz - 1) {
p->photon_status = MCSTATUS_BOUNDARY_UPPER;
break;
}
} /* end step loop */
tau_save[0] = p->tauext_tot;
tau_save[1] = p->tauabs.tot;
/* free memory */
destroy_photon (p, atmos->n_caoth);
return 1;
}
/***********************************************************************************/
/* Function: find_ris_factor @62_30i@ */
/* Description: */
/* Find out the ris-factor needed for a scattering-optical depth of 1 (or choice) */
/* Code partly taken from escape_probability() */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Christian Pause */
/* @i62_30@ */
/***********************************************************************************/
int find_ris_factor (photon_struct* photon,
atmosphere_struct* atmos,
sample_struct* sample,
elevation_struct* elev,
float* refind) {
double step = 0.0, gamma = 0.0;
int status = 0;
int is_threed = 0;
double tau_sca = 0.0;
double opan = 0.0;
double radi = 0.0;
double tsca[6];
double tautemp[5];
double taumin = 0.0;
double taumax = 0.0;
double theta = 0.0;
double phi = 0.0;
int i = 0;
int j = 0;
int cloudy = 0;
double psqrt = 0;
int numberOfShots = 0;
double aadd[6][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
double arad[6][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
int first = 1;
/* prepare things */
photon_struct* p =
calloc_photon (sample, atmos->Nx, atmos->Ny, atmos->Nz, MCSRC_NONE, atmos->nlambda_abs, atmos->Nc, atmos->n_caoth);
if (sample->LidarLocEst) {
/* send out six photons */
/* first one straight with only molecular scattering to determine magnitude of mol sca */
/* second one straight with full scattering */
/* third to sixth from four extremal points on the detector along the maximum opening angles */
/* if any of these five photons sees a cloud, a ris-factor is calculated */
numberOfShots = 6;
theta = sample->laser[sample->ili].theta;
phi = sample->laser[sample->ili].phi;
opan = sin (sample->laser[sample->ili].alpha);
radi = sample->laser[sample->ili].radius;
/* copy an array blockwise */
/* The following constructs do not seem to be compatible with every compiler:
memcpy(aadd,(double[6][3]){{0,0,0},
{0,0,0},
{opan*cosd(phi),opan*sind(phi),0},
{-opan*cosd(phi),-opan*sind(phi),0},
{opan*sind(phi)*cosd(theta),opan*cosd(phi)*cosd(theta),opan*sind(theta)},
{-opan*sind(phi)*cosd(theta),-opan*cosd(phi)*cosd(theta),-opan*sind(theta)}}, sizeof aadd);
memcpy(arad,(double[6][3]){{0,0,0},
{0,0,0},
{radi*cosd(phi),radi*sind(phi),0},
{-radi*cosd(phi),-radi*sind(phi),0},
{radi*sind(phi)*cosd(theta),radi*cosd(phi)*cosd(theta),radi*sind(theta)},
{-radi*sind(phi)*cosd(theta),-radi*cosd(phi)*cosd(theta),-radi*sind(theta)}}, sizeof arad);
Doing it by hand instead: */
aadd[2][0] = opan * cosd (phi);
aadd[2][1] = opan * sind (phi);
aadd[3][0] = -opan * cosd (phi);
aadd[3][1] = -opan * sind (phi);
aadd[4][0] = opan * sind (phi) * cosd (theta);
aadd[4][1] = opan * cosd (phi) * cosd (theta);
aadd[4][2] = opan * sind (theta);
aadd[5][0] = -opan * sind (phi) * cosd (theta);
aadd[5][1] = -opan * cosd (phi) * cosd (theta);
aadd[5][2] = -opan * sind (theta);
arad[2][0] = radi * cosd (phi);
arad[2][1] = radi * sind (phi);
arad[3][0] = -radi * cosd (phi);
arad[3][1] = -radi * sind (phi);
arad[4][0] = radi * sind (phi) * cosd (theta);
arad[4][1] = radi * cosd (phi) * cosd (theta);
arad[4][2] = radi * sind (theta);
arad[5][0] = -radi * sind (phi) * cosd (theta);
arad[5][1] = -radi * cosd (phi) * cosd (theta);
arad[5][2] = -radi * sind (theta);
} else {
/* Standard MYSTIC, only one path is needed */
/* we have to loop two times because the first loop only considers */
/* molecular scattering, its result is disregarded */
numberOfShots = 2;
}
for (i = 0; i < numberOfShots; i++) {
/* reset tau_sca for each run */
tau_sca = 0.0;
/* work on a copy of the photon, not the original one */
cp_photon_struct (p, photon, sample, atmos->n_caoth);
/* set direction and starting point on the detector */
if (sample->LidarLocEst) {
cp_direction (&(p->dir), &(sample->laser[sample->ili].dir));
for (j = 0; j < 3; j++) {
p->dir.dx[j] = p->dir.dx[j] + aadd[i][j];
p->x[j] = sample->laser[sample->ili].x[j] + arad[i][j];
}
/* normalize new direction and adjust p->dir.hit if neccessary */
psqrt = sqrt (p->dir.dx[0] * p->dir.dx[0] + p->dir.dx[1] * p->dir.dx[1] + p->dir.dx[2] * p->dir.dx[2]);
for (j = 0; j < 3; j++) {
p->dir.dx[j] = p->dir.dx[j] / psqrt;
if (p->dir.dx[j] > 0.0)
p->dir.hit[j] = 1;
else if (p->dir.dx[j] < 0.0)
p->dir.hit[j] = 0;
else
p->dir.hit[j] = -1;
}
/* check if photon has entered another box after offset on the detector area and adjust if neccessary */
for (j = 0; j < atmos->Nx; j++) {
if (atmos->X[j] >= p->x[0]) {
p->ic = j - 1;
break;
}
}
for (j = 0; j < atmos->Ny; j++) {
if (atmos->Y[j] >= p->x[1]) {
p->jc = j - 1;
break;
}
}
for (j = 0; j < atmos->Nz; j++) {
if (atmos->Z[j] >= p->x[2]) {
p->kc = j - 1;
break;
}
}
}
/* initialize status; if unchanged at end of travel step, the photon crosses a grid boundary */
p->photon_status = MCSTATUS_TRAVEL;
p->RIS_mode = MCRIS_MODE_NORMAL;
p->VIS_mode = MCVIS_MODE_NORMAL;
while (1 == 1) { /* until photon reaches the surface or TOA */
is_threed = (atmos->threed[MCCAOTH_TOT][p->kc] >= 1); /* 3D layer */
/**************************************************************/
/* 1. find out what happens next with photon, and step length */
/**************************************************************/
/* calculate next intersection point with the box boundaries */
if (sample->spherical3D) {
#if HAVE_MYSTIC3D
status = intersection3D_spherical (p, atmos, sample->spherical3D_scene, &first, &step);
if (status)
return err_out ("Error %d returned by intersection3D_spherical\n", status);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else {
if (is_threed == 1) { /* 3D layer */
#if HAVE_MYSTIC3D
status = intersection3D (p, atmos, 10000, 0, &step);
if (status)
return err_out ("Error %d returned by intersection3D\n", status);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else {
if (sample->spherical) {
status = intersection1D_spherical (p, atmos, sample->refraction, refind, &step);
/* Photon is absorbed by the surface.*/
if (status < 0)
break;
} else {
intersection1D (p, atmos, 10000, 0, &step, 0);
}
}
}
if (step < 0)
step = 0;
/* check if photon crossed the 2D surface */
if (elev->elev2D) {
status = cross_surface (p, step, elev, sample->bcond, &gamma);
/* if cross_surface ran into some inconsistency */
if (status < 0) {
fprintf (stderr, "Something terrible has happened! cross_surface() returned\n");
fprintf (stderr, "status %d\n", status);
return -1;
}
if (status > 0) {
step = gamma;
p->photon_status = MCSTATUS_SURFACE;
}
}
/*******************************************************************/
/* 2. apply step length, move photon, and exit if photon path ends */
/*******************************************************************/
/* sum up scattering optical depth */
if (i == 0)
tau_sca += step * get_ksca (atmos, p, MCCAOTH_MOL);
else
tau_sca += step * get_ksca (atmos, p, MCCAOTH_TOT);
p->pathlength += step;
/* move photon to box boundary, to next scattering point, */
/* or to the 2D surface */
if (is_threed == 1 || sample->spherical3D) { /* 3D layer */
#if HAVE_MYSTIC3D
status = step3D (p, atmos, step, sample->bcond, 0, sample->spherical3D, 0);
#else
fprintf (stderr, "Error! you are not allowed to use mystic 3D!\n");
return -1;
#endif
} else
status = step1D (p, atmos, step, sample->bcond, 0, 0);
if (status < 0) {
fprintf (stderr, "Error %d returned by step%dD()\n", status, (is_threed == 1 ? 3 : 1));
return status;
}
/* end photon travel unless it simply crosses the boundary */
if (p->photon_status != MCSTATUS_TRAVEL)
break;
/**********************************/
/* 3. check if photon leaves grid */
/**********************************/
/* finally check if photon arrived at the lower surface */
/* or at the top of the atmosphere */
if (p->kc < 0) {
p->photon_status = MCSTATUS_BOUNDARY_LOWER;
if (elev->elev2D) {
fprintf (stderr, "FATAL error! Escape photon reached the 1D boundary in a\n");
fprintf (stderr, " 2D elevation case (%dD layer)!\n\n", (is_threed == 1 ? 3 : 1));
return -1;
}
break;
}
if (p->kc > atmos->Nz - 1) {
p->photon_status = MCSTATUS_BOUNDARY_UPPER;
break;
}
} /* end step loop */
tsca[i] = tau_sca;
} /* end loop over all directions */
/*********************/
/* 4. set ris-factor */
/*********************/
/* check if there is one or more cloudy paths */
/* XXX factor 100 is arbitrary, maybe increase it */
if (sample->LidarLocEst) {
for (j = 1; j < numberOfShots; j++) {
if (tsca[j] >= 100 * tsca[0]) {
tautemp[j - 1] = tsca[j];
cloudy = 1;
} else
tautemp[j - 1] = -1;
}
/* if there is one or more cloudy paths, find smallest and largest tau_sca among them */
if (cloudy) {
for (j = 0; j < 5; j++) {
if (tautemp[j] > 0) {
taumin = tautemp[j];
taumax = tautemp[j];
i = j;
break;
}
}
for (j = i; j < 5; j++) {
if (tautemp[j] > 0) {
if (tautemp[j] < taumin)
taumin = tautemp[j];
else if (tautemp[j] > taumax)
taumax = tautemp[j];
}
}
tau_sca = 0.5 * (taumin + taumax);
} else
atmos->ris_factor = 1.0;
}
/* set tau_sca as average between highest and lowest optical depth */
/* XXX not sure if this is the best possible way */
if (tau_sca > sample->ris_optical_depth) {
atmos->ris_factor = 1.0;
} else {
atmos->ris_factor = sample->ris_optical_depth / tau_sca;
}
sample->pathlength = p->pathlength;
if (atmos->ris_factor > 1.e10)
atmos->ris_factor = 1.e10;
/* free memory */
destroy_photon (p, atmos->n_caoth);
return 0;
}
/***********************************************************************************/
/* Function: summarize_result_mishchenko_cb @62_30i@ */
/* Description: outputs stuff related to CB into stdout */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Christian Pause */
/* @i62_30@ */
/***********************************************************************************/
int summarize_result_mishchenko_cb (mishchenko_cb_struct* mish, char* basename) {
double I = 0., Id = 0., Q = 0., Qd = 0., U = 0., Ud = 0., V = 0., Vd = 0.;
int i, j;
I = fiveKahanSum (mish->M_Elements_S0[0][0],
mish->M_Elements_S0[0][1],
mish->M_Elements_S0[0][2],
mish->M_Elements_S0[1][3],
2 * mish->M_Elements_S0[1][4]);
Id = fourKahanSum (mish->M_Elements_S0[0][0], mish->M_Elements_S0[0][1], mish->M_Elements_S0[1][3], mish->M_Elements_S0[1][4]);
Q = fiveKahanSum (mish->M_Elements_S0[1][0],
mish->M_Elements_S0[1][1],
mish->M_Elements_S0[1][2],
mish->M_Elements_S0[0][3],
2 * mish->M_Elements_S0[0][4]);
Qd = fourKahanSum (mish->M_Elements_S0[1][0], mish->M_Elements_S0[1][1], mish->M_Elements_S0[0][3], mish->M_Elements_S0[0][4]);
U = fiveKahanSum (mish->M_Elements_S0[2][0],
mish->M_Elements_S0[2][1],
mish->M_Elements_S0[2][2],
mish->M_Elements_S0[3][3],
2 * mish->M_Elements_S0[3][4]);
Ud = fourKahanSum (mish->M_Elements_S0[2][0], mish->M_Elements_S0[2][1], mish->M_Elements_S0[3][3], mish->M_Elements_S0[3][4]);
V = fiveKahanSum (mish->M_Elements_S0[3][0],
mish->M_Elements_S0[3][1],
mish->M_Elements_S0[3][2],
-mish->M_Elements_S0[2][3],
-2 * mish->M_Elements_S0[2][4]);
Vd = fourKahanSum (mish->M_Elements_S0[3][0], mish->M_Elements_S0[3][1], -mish->M_Elements_S0[2][3], -mish->M_Elements_S0[2][4]);
char mishchenkoCBFilename[FILENAME_MAX] = "";
FILE* mishchenkoCBFile = NULL;
strcpy (mishchenkoCBFilename, basename);
strcat (mishchenkoCBFilename, ".mish.cb");
if ((mishchenkoCBFile = fopen (mishchenkoCBFilename, "w")) == NULL) {
fprintf (stderr, "Error opening %s for writing\n", mishchenkoCBFilename);
return -1;
}
fprintf (mishchenkoCBFile, "Backscatter Enhancements computed by Mishchenko's formulas:\n");
fprintf (mishchenkoCBFile, "backscatter enhancement I: %e\n", I / Id);
fprintf (mishchenkoCBFile, "backscatter enhancement Q: %e\n", Q / Qd);
fprintf (mishchenkoCBFile, "backscatter enhancement U: %e\n", U / Ud);
fprintf (mishchenkoCBFile, "backscatter enhancement V: %e\n", V / Vd);
fprintf (mishchenkoCBFile, "backscatter enhancement QP: %e\n", (I + Q) / (Id + Qd));
fprintf (mishchenkoCBFile, "backscatter enhancement QX: %e\n", (I - Q) / (Id - Qd));
fprintf (mishchenkoCBFile, "backscatter enhancement UP: %e\n", (I + U) / (Id + Ud));
fprintf (mishchenkoCBFile, "backscatter enhancement UX: %e\n", (I - U) / (Id - Ud));
fprintf (mishchenkoCBFile, "backscatter enhancement VP: %e\n", (I + V) / (Id + Vd));
fprintf (mishchenkoCBFile, "backscatter enhancement VX: %e\n", (I - V) / (Id - Vd));
for (i = 0; i < 4; i++) {
for (j = 0; j < 5; j++) {
mish->M_Elements_S0[i][j] = 0.;
}
}
(void)fclose (mishchenkoCBFile);
return 0;
}
/***********************************************************************************/
/* Function: save_phase_matrix_elements_temp @62_30i@ */
/* Description: save phase temporary matrix elements for Mishchenko matrices */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Christian Pause */
/* @i62_30@ */
/***********************************************************************************/
void save_phase_matrix_elements_temp (mishchenko_cb_struct* mish, double** phamat, int scattercounter, double* phaseMatrix) {
if (scattercounter == 0) {
mish->R1t[0] = phamat[0][0];
mish->R1t[1] = phamat[0][1];
mish->R1t[2] = phamat[2][2];
mish->R1t[3] = phamat[2][3];
mish->R1t[4] = phamat[1][1];
mish->R1t[5] = phamat[3][3];
} else {
mish->RMt[0] = phamat[0][0];
mish->RMt[1] = phamat[0][1];
mish->RMt[2] = phamat[2][2];
mish->RMt[3] = phamat[2][3];
mish->RMt[4] = phamat[1][1];
mish->RMt[5] = phamat[3][3];
}
}
/***********************************************************************************/
/* Function: save_phase_matrix_elements @62_30i@ */
/* Description: save phase matrix elements for Mishchenko matrices */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Christian Pause */
/* @i62_30@ */
/***********************************************************************************/
void save_phase_matrix_elements (mishchenko_cb_struct* mish, double totweight, int scattercounter, double* stokes0) {
double R1[6], RM[6], RC[4] = {0., 0., 0., 0.};
int i;
if (scattercounter == 0) {
for (i = 0; i < 6; i++) {
R1[i] = mish->R1t[i] * totweight;
mish->R1t[i] = 0.;
}
mish->R1C += 1;
mish->M_Elements_S0[0][0] += R1[0] * stokes0[0];
mish->M_Elements_S0[0][3] += R1[1] * stokes0[0];
mish->M_Elements_S0[1][0] += R1[4] * stokes0[1];
mish->M_Elements_S0[1][3] += R1[1] * stokes0[1];
mish->M_Elements_S0[2][0] += R1[2] * stokes0[2];
mish->M_Elements_S0[2][3] += R1[3] * stokes0[2];
mish->M_Elements_S0[3][0] += R1[5] * stokes0[3];
mish->M_Elements_S0[3][3] += R1[3] * stokes0[3];
} else {
for (i = 0; i < 6; i++) {
RM[i] = mish->RMt[i] * totweight;
mish->RMt[i] = 0.;
}
mish->RMC += 1;
RC[0] += 0.5 * fourKahanSum (RM[0], RM[4], -RM[2], RM[5]);
RC[1] += 0.5 * fourKahanSum (RM[0], RM[4], RM[2], -RM[5]);
RC[2] += 0.5 * fourKahanSum (-RM[0], RM[4], RM[2], RM[5]);
RC[3] += 0.5 * fourKahanSum (RM[0], -RM[4], RM[2], RM[5]);
mish->M_Elements_S0[0][1] += RM[0] * stokes0[0];
mish->M_Elements_S0[0][2] += RC[0] * stokes0[0];
mish->M_Elements_S0[0][4] += RM[1] * stokes0[0];
mish->M_Elements_S0[1][1] += RM[4] * stokes0[1];
mish->M_Elements_S0[1][2] += RC[1] * stokes0[1];
mish->M_Elements_S0[1][4] += RM[1] * stokes0[1];
mish->M_Elements_S0[2][1] += RM[2] * stokes0[2];
mish->M_Elements_S0[2][2] += RC[2] * stokes0[2];
mish->M_Elements_S0[2][4] += RM[3] * stokes0[2];
mish->M_Elements_S0[3][1] += RM[5] * stokes0[3];
mish->M_Elements_S0[3][2] += RC[3] * stokes0[3];
mish->M_Elements_S0[3][4] += RM[3] * stokes0[3];
}
}
/***********************************************************************************/
/* Function: kahan summation @62_30i@ */
/* Description: Implementation of the Kahan summation algorithm, taken from */
/* http://en.wikipedia.org/wiki/Kahan_summation_algorithm */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Christian Pause */
/* @i62_30@ */
/***********************************************************************************/
inline double kahanSum (double* f, int N) {
double sum = f[0];
double c = 0.0, y, t;
int i;
for (i = 1; i < N; i++) {
y = f[i] - c;
t = sum + y;
c = (t - sum) - y;
sum = t;
}
return sum;
}
double fiveKahanSum (double a, double b, double c, double d, double e) {
double* f = NULL;
double s;
f = calloc (5, sizeof (double));
f[0] = a;
f[1] = b;
f[2] = c;
f[3] = d;
f[4] = e;
s = kahanSum (f, 5);
free (f);
return s;
}
double fourKahanSum (double a, double b, double c, double d) {
double* f = NULL;
double s;
f = calloc (4, sizeof (double));
f[0] = a;
f[1] = b;
f[2] = c;
f[3] = d;
s = kahanSum (f, 4);
free (f);
return s;
}
double threeKahanSum (double a, double b, double c) {
double* f = NULL;
double s;
f = calloc (3, sizeof (double));
f[0] = a;
f[1] = b;
f[2] = c;
s = kahanSum (f, 3);
free (f);
return s;
}
/***********************************************************************************/
/* Function: find_max @62_30i@ */
/* Description: */
/* Find maximum value of 3 given variables */
/* Parameters: */
/* Return value: max */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Carolin Klinger, 2013.09.27 */
/* @i62_30@ */
/***********************************************************************************/
static double find_max (double x, double y, double z) {
double max = x;
if (max <= z)
max = z;
if (max <= y)
max = y;
return max;
}
/***********************************************************************************/
/* Function: find_min @62_30i@ */
/* Description: */
/* Find minimum value of 3 given variables */
/* Parameters: */
/* Return value: min */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Carolin Klinger, 2013.09.27 */
/* @i62_30@ */
/***********************************************************************************/
static double find_min (double x, double y, double z) {
double min = x;
if (min >= z)
min = z;
if (min >= y)
min = y;
return min;
}
/*****************************************************************************************/
/* Function: pst @62_30i@ */
/* Description: */
/* Estimate escape probability (backward heating rates, thermal; Klinger and Mayer,2013) */
/* Parameters: */
/* Return value: escape probability */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Carolin Klinger, 2013.09.27 */
/* @i62_30@ */
/*****************************************************************************************/
static double pst (double mu, int i, double dtau) {
if (dtau == 0 || i == 0)
return 0.5 * mu * mu;
if (mu == 0)
return 0;
/* if the optical thickness is too large we approximate the result with 0 to avoid numerical under/overflow */
if ((double)i * dtau > 200)
return 0;
#if HAVE_LIBGSL
// we need the exponential integral Ei() from the gsl
return 0.5 * (mu * exp (-(double)i * dtau / mu) * (mu - (double)i * dtau) -
((double)i * dtau) * ((double)i * dtau) * gsl_sf_expint_Ei (-(double)i * dtau / mu));
#else
fprintf (stderr, "Error, for heating rate calculations with EMABS_OPT we need the gsl.\n");
fprintf (stderr, "Please install and recompile!\n");
return 0.0 / 0.0;
#endif
}
/***********************************************************************************/
/* Function: emabsopt_location @62_30i@ */
/* Description: */
/* Calculates additional weightings and starting locations for an optimized photon */
/* distribution for the thermal backward heating rate EMABSOPT method. */
/* Function is called in generate_photon. */
/* An exact description of the method can be found in Klinger and Mayer (2013). */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Carolin Klinger, 2013.09.27 */
/* @i62_30@ */
/***********************************************************************************/
static int emabsopt_location (photon_struct* p, atmosphere_struct* atmos, sample_struct* sample, long int nphotons) {
/* Definition of variables */
/* General variables */
static double kabs_save = -1.0;
static double ***w_xy = NULL, ***w_xz = NULL, ***w_yz = NULL;
static double* w_z = NULL;
static double* p_sum2 = NULL;
static double delta_tau_x = 0.0, delta_tau_y = 0.0, delta_tau_z = 0.0;
static double tau_x = 0.0, tau_y = 0.0, tau_z = 0.0;
static double phot_frac = 0.0;
static double w_in = 0.0;
static int N_sub = 0;
static int N_sub_cutoff = 0;
static int nx = 0, ny = 0, nz = 0;
static int n_xy = 0, n_yz = 0, n_xz = 0;
static int n_max = 0;
int ix = 0, iy = 0, iz = 0;
double delta_z = 0.0;
double position = 0.0;
double r_location = 0.0, r_frac = 0.0;
double delta_tau_orig = 0.0;
double tau_cutoff = 0.0, tau_min = 0.0;
double N0 = 0.0;
double mug = 0.0;
double p_sum_tot = 0.0;
double p_avg = 0.0, p_avg_out = 0.0;
double p_in = 0.0, p_in_avg = 0.0;
double *p_z = NULL, *p_an_z = NULL;
double phot_dist_in = 0.0;
/* ** 3d variables** */
double N0_xy = 0.0, N0_xz = 0.0, N0_yz = 0.0;
double p_sum_xy = 0.0, p_sum_xz = 0.0, p_sum_yz = 0.0;
double * p_x = NULL, *p_y = NULL;
double * p_an_x = NULL, *p_an_y = NULL;
double ***prob_xy = NULL, ***prob_xz = NULL, ***prob_yz = NULL;
double * p_sum1_xy = NULL, *p_sum1_xz = NULL, *p_sum1_yz = NULL;
double ***phot_dist_xy = NULL, ***phot_dist_xz = NULL, ***phot_dist_yz = NULL;
/* ** 1d variables ** */
double N0_z = 0.0;
double p_sum_z = 0.0;
double* prob_z = NULL;
double* p_sum1_z = NULL;
double* phot_dist_z = NULL;
/* ************************************************************************* */
/* In the following section, all variables are only calculated for the first */
/* photon of aspecific optical thickness. The calculation is perfomed again, */
/* if the optical thickness of the grid box changes, e.g. for a new */
/* correlated-k subband or different atmospheric/cloud properties. */
/* The cutoff optical thickness of a grid box is set to 10, the optical */
/* thickness of a sub grid box is set to 1, mug is set to 0. */
/* If the cutoff optical thickness is smaller then the half of the total */
/* optical thickness, a inner cuboid is left - variance reduction, avoiding */
/* spikes! */
/* ************************************************************************* */
/* The optical thickness in all 3 spatial direction is calculated and the */
/* minimum optical thickness of the three is found. */
/* Depending on this minimum optical thickness, the number of sub grid boxes */
/* is calculated and the escape probabilty is estimated, as well as */
/* additional weights. */
/* ************************************************************************* */
if (atmos->kabs3D->threed[MCCAOTH_TOT][p->kc] >= 1) { /* if 3D */
if (atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] != kabs_save) {
mug = 0;
delta_tau_orig = 1; /* ** Optical thicknes of a subbox */
tau_cutoff = 10; /* Cutoff optical thickness - from the edge to the middle of the gridbox ** */
/* if (n_max>0){ */
/* free memory of static variable if already allocated w_xy w_yz w_xz */
if (w_xy != NULL) {
for (ix = 0; ix < nx; ix++) {
for (iy = 0; iy < ny; iy++)
free (w_xy[ix][iy]);
free (w_xy[ix]);
}
free (w_xy);
}
if (w_xz != NULL) {
for (ix = 0; ix < nx; ix++) {
for (iy = 0; iy < n_max; iy++)
free (w_xz[ix][iy]);
free (w_xz[ix]);
}
free (w_xz);
}
if (w_yz != NULL) {
for (ix = 0; ix < n_max; ix++) {
for (iy = 0; iy < ny; iy++)
free (w_yz[ix][iy]);
free (w_yz[ix]);
}
free (w_yz);
}
/* } */
/* calculate tau of x,y and z-direction and find mimimum */
tau_x = atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] * (atmos->X[p->ic + 1] - atmos->X[p->ic]);
tau_y = atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] * (atmos->Y[p->jc + 1] - atmos->Y[p->jc]);
tau_z = atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
tau_min = find_min (tau_x, tau_y, tau_z);
/* maximum number of sub grid boxes within tau_cutoff */
n_max = (int)(tau_cutoff / delta_tau_orig);
/* If the minimum optical thickness is smaller then the standard "tau_cutoff=10", find a new tau_cutoff */
if (2 * tau_cutoff >= tau_min)
n_max = (int)(tau_min / (2 * delta_tau_orig));
if (n_max <= 0) {
fprintf (stderr, "Ooops! n_max ( %d ) should never be zero or smaller than zero! Some error occured! \n", n_max);
return -1;
}
/* calculate number of sub cubes / number of sub-distances in one direction */
nx = (int)(tau_x / delta_tau_orig) + 1;
ny = (int)(tau_y / delta_tau_orig) + 1;
nz = (int)(tau_z / delta_tau_orig) + 1;
N_sub = nx * ny * nz; /* total number of sub grid boxes */
N_sub_cutoff =
2 * (nx * ny * n_max + nx * nz * n_max + ny * nz * n_max); /* total number of sub grid boxes within tau_cutoff*/
delta_tau_x = tau_x / nx; /* optical thickness in x,y,z for a sub grid box*/
delta_tau_y = tau_y / ny;
delta_tau_z = tau_z / nz;
/* number of sub grid boxes on one grid box face within tau_cutoff*/
n_xy = nx * ny * n_max;
n_xz = nx * (nz - 2 * n_max) * n_max;
n_yz = (ny - 2 * n_max) * (nz - 2 * n_max) * n_max;
/* calculate original photon distribution per sub-cube */
N0 = (double)nphotons / (double)N_sub; /* !! Attention! nphotons must be double here!! */
N0_xy = 2 * N0 * n_xy; /* photons started in xy plane. Factor 2, because each face exists twice! */
N0_xz = 2 * N0 * n_xz; /* photons started in xz plane */
N0_yz = 2 * N0 * n_yz; /* photons started in yz plane */
/* If there is a inner cuboid/cube, perform following calculation*/
/* if (n_max>0) { */
/* allocate memory */
p_x = calloc (nx, sizeof (double));
p_y = calloc (ny, sizeof (double));
p_z = calloc (nz, sizeof (double));
p_an_x = calloc (nx / 2, sizeof (double));
p_an_y = calloc (ny / 2, sizeof (double));
p_an_z = calloc (nz / 2, sizeof (double));
p_sum1_xy = calloc (nx * ny * n_max, sizeof (double));
p_sum1_xz = calloc (nx * nz * n_max, sizeof (double));
p_sum1_yz = calloc (ny * nz * n_max, sizeof (double));
/* free memory of static variable p_sum2 if already allocated*/
if (p_sum2 != NULL)
free (p_sum2);
p_sum2 = calloc (N_sub_cutoff / 2 + 1, sizeof (double));
prob_xy = calloc (nx, sizeof (double**));
for (ix = 0; ix < nx; ix++) {
prob_xy[ix] = calloc (ny, sizeof (double*));
for (iy = 0; iy < ny; iy++)
prob_xy[ix][iy] = calloc (n_max, sizeof (double));
}
prob_xz = calloc (nx, sizeof (double**));
for (ix = 0; ix < nx; ix++) {
prob_xz[ix] = calloc (n_max, sizeof (double*));
for (iy = 0; iy < n_max; iy++)
prob_xz[ix][iy] = calloc (nz, sizeof (double));
}
prob_yz = calloc (n_max, sizeof (double**));
for (ix = 0; ix < n_max; ix++) {
prob_yz[ix] = calloc (ny, sizeof (double*));
for (iy = 0; iy < ny; iy++)
prob_yz[ix][iy] = calloc (nz, sizeof (double));
}
w_xy = calloc (nx, sizeof (double**));
for (ix = 0; ix < nx; ix++) {
w_xy[ix] = calloc (ny, sizeof (double*));
for (iy = 0; iy < ny; iy++)
w_xy[ix][iy] = calloc (n_max, sizeof (double));
}
w_xz = calloc (nx, sizeof (double**));
for (ix = 0; ix < nx; ix++) {
w_xz[ix] = calloc (n_max, sizeof (double*));
for (iy = 0; iy < n_max; iy++)
w_xz[ix][iy] = calloc (nz, sizeof (double));
}
if (w_xz == NULL)
fprintf (stderr, "Fatal Error! Out of memory \n");
w_yz = calloc (n_max, sizeof (double**));
for (ix = 0; ix < n_max; ix++) {
w_yz[ix] = calloc (ny, sizeof (double*));
for (iy = 0; iy < ny; iy++)
w_yz[ix][iy] = calloc (nz, sizeof (double));
}
phot_dist_xy = calloc (nx, sizeof (double**));
for (ix = 0; ix < nx; ix++) {
phot_dist_xy[ix] = calloc (ny, sizeof (double*));
for (iy = 0; iy < ny; iy++)
phot_dist_xy[ix][iy] = calloc (n_max, sizeof (double));
}
phot_dist_xz = calloc (nx, sizeof (double**));
for (ix = 0; ix < nx; ix++) {
phot_dist_xz[ix] = calloc (n_max, sizeof (double*));
for (iy = 0; iy < n_max; iy++)
phot_dist_xz[ix][iy] = calloc (nz, sizeof (double));
}
phot_dist_yz = calloc (n_max, sizeof (double**));
for (ix = 0; ix < n_max; ix++) {
phot_dist_yz[ix] = calloc (ny, sizeof (double*));
for (iy = 0; iy < ny; iy++)
phot_dist_yz[ix][iy] = calloc (nz, sizeof (double));
}
/* save optical thickness of current grid box. Necessary to check if optical */
/* thickness has changed for next photon and if this calculation has to be */
/* performed again */
kabs_save = atmos->kabs3D->prof[MCCAOTH_TOT][p->kc][p->ic][p->jc];
#if !HAVE_LIBGSL
fprintf (stderr, "Error, for heating rate calculations with EMABS_OPT we need the gsl.\n");
fprintf (stderr, "Please install and recompile!\n");
return -1;
#endif
/* Calculate escape probabilty for 3 spatial direction within tau_cutoff */
for (ix = 0; ix < (nx / 2); ix++)
p_an_x[ix] = ((pst (1, ix, delta_tau_x) - pst (1, (ix + 1), delta_tau_x)) -
(pst (mug, ix, delta_tau_x) - pst (mug, (ix + 1), delta_tau_x))) /
delta_tau_x / (1 - mug);
for (iy = 0; iy < (ny / 2); iy++)
p_an_y[iy] = ((pst (1, iy, delta_tau_y) - pst (1, (iy + 1), delta_tau_y)) -
(pst (mug, iy, delta_tau_y) - pst (mug, (iy + 1), delta_tau_y))) /
delta_tau_y / (1 - mug);
for (iz = 0; iz < (nz / 2); iz++)
p_an_z[iz] = ((pst (1, iz, delta_tau_z) - pst (1, (iz + 1), delta_tau_z)) -
(pst (mug, iz, delta_tau_z) - pst (mug, (iz + 1), delta_tau_z))) /
delta_tau_z / (1 - mug);
/* Escape probabilty is the same for the opposit spatial direction, therefore use above calculated escepa probability */
for (ix = 0; ix < (nx / 2); ix++) {
p_x[ix] = p_an_x[ix];
p_x[nx - ix - 1] = p_an_x[ix];
}
for (iy = 0; iy < (ny / 2); iy++) {
p_y[iy] = p_an_y[iy];
p_y[ny - iy - 1] = p_an_y[iy];
}
for (iz = 0; iz < (nz / 2); iz++) {
p_z[iz] = p_an_z[iz];
p_z[nz - iz - 1] = p_an_z[iz];
}
/* averaged probability */
for (ix = 0; ix < nx; ix++)
for (iy = 0; iy < ny; iy++)
for (iz = 0; iz < n_max; iz++) {
prob_xy[ix][iy][iz] = find_max (p_x[ix], p_y[iy], p_z[iz]);
p_avg_out += (2 * N0 * sqrt (prob_xy[ix][iy][iz] * (1 - prob_xy[ix][iy][iz])));
}
for (ix = 0; ix < nx; ix++)
for (iy = 0; iy < n_max; iy++)
for (iz = n_max; iz < (nz - n_max); iz++) {
prob_xz[ix][iy][iz] = find_max (p_x[ix], p_y[iy], p_z[iz]);
p_avg_out += (2 * N0 * sqrt (prob_xz[ix][iy][iz] * (1 - prob_xz[ix][iy][iz])));
}
for (ix = 0; ix < n_max; ix++)
for (iy = n_max; iy < (ny - n_max); iy++)
for (iz = n_max; iz < (nz - n_max); iz++) {
prob_yz[ix][iy][iz] = find_max (p_x[ix], p_y[iy], p_z[iz]);
p_avg_out += (2 * N0 * sqrt (prob_yz[ix][iy][iz] * (1 - prob_yz[ix][iy][iz])));
}
p_in = p_x[n_max + 1];
p_in_avg = (nphotons - (N0_yz + N0_xz + N0_xy)) * sqrt (p_in * (1 - p_in));
p_avg = (p_avg_out + p_in_avg) / nphotons;
for (ix = 0; ix < nx; ix++)
for (iy = 0; iy < ny; iy++)
for (iz = 0; iz < n_max; iz++) {
w_xy[ix][iy][iz] = (p_avg / sqrt (prob_xy[ix][iy][iz] * (1 - prob_xy[ix][iy][iz])));
phot_dist_xy[ix][iy][iz] = 2 * N0 / w_xy[ix][iy][iz];
phot_frac += phot_dist_xy[ix][iy][iz];
p_sum1_xy[ix * ny * n_max + iy * n_max + iz] = phot_dist_xy[ix][iy][iz] / (N0_xy + N0_xz + N0_yz);
p_sum_xy += phot_dist_xy[ix][iy][iz] / (N0_xy + N0_xz + N0_yz);
}
for (ix = 0; ix < nx; ix++)
for (iy = 0; iy < n_max; iy++)
for (iz = n_max; iz < (nz - n_max); iz++) {
w_xz[ix][iy][iz] = (p_avg / sqrt (prob_xz[ix][iy][iz] * (1 - prob_xz[ix][iy][iz])));
phot_dist_xz[ix][iy][iz] = 2 * N0 / w_xz[ix][iy][iz];
phot_frac += phot_dist_xz[ix][iy][iz];
p_sum1_xz[ix * nz * n_max + iy * nz + iz] = phot_dist_xz[ix][iy][iz] / (N0_xy + N0_xz + N0_yz);
p_sum_xz += phot_dist_xz[ix][iy][iz] / (N0_xy + N0_xz + N0_yz);
}
for (ix = 0; ix < n_max; ix++)
for (iy = n_max; iy < (ny - n_max); iy++)
for (iz = n_max; iz < (nz - n_max); iz++) {
w_yz[ix][iy][iz] = (p_avg / sqrt (prob_yz[ix][iy][iz] * (1 - prob_yz[ix][iy][iz])));
phot_dist_yz[ix][iy][iz] = 2 * N0 / w_yz[ix][iy][iz];
phot_frac += phot_dist_yz[ix][iy][iz];
p_sum1_yz[ix * ny * nz + iy * nz + iz] = phot_dist_yz[ix][iy][iz] / (N0_xy + N0_xz + N0_yz);
p_sum_yz += phot_dist_yz[ix][iy][iz] / (N0_xy + N0_xz + N0_yz);
}
w_in = (p_avg / sqrt (p_in * (1 - p_in)));
phot_dist_in = (nphotons - (N0_yz + N0_xz + N0_xy)) / w_in;
p_sum_tot = p_sum_xy + p_sum_xz + p_sum_yz;
p_sum2[0] = 0.0;
phot_frac = phot_frac / (phot_frac + phot_dist_in);
for (ix = 1; ix <= (nx * ny * n_max); ix++)
p_sum2[ix] = p_sum2[ix - 1] + p_sum1_xy[ix - 1] / p_sum_tot;
for (ix = (nx * ny * n_max + 1); ix <= (nx * ny * n_max + nx * nz * n_max); ix++)
p_sum2[ix] = p_sum2[ix - 1] + p_sum1_xz[ix - 1 - nx * ny * n_max] / p_sum_tot;
for (ix = (nx * ny * n_max + nx * nz * n_max + 1); ix <= (nx * ny * n_max + nx * nz * n_max + n_max * ny * nz); ix++)
p_sum2[ix] = p_sum2[ix - 1] + p_sum1_yz[ix - 1 - (nx * ny * n_max + nx * nz * n_max)] / p_sum_tot;
/* **** free memory **** */
free (p_x);
free (p_y);
free (p_z);
free (p_an_x);
free (p_an_y);
free (p_an_z);
free (p_sum1_xy);
free (p_sum1_xz);
free (p_sum1_yz);
/* free memory of static variable prob */
for (ix = 0; ix < (nx); ix++) {
for (iy = 0; iy < (ny); iy++)
free (prob_xy[ix][iy]);
free (prob_xy[ix]);
}
free (prob_xy);
for (ix = 0; ix < (nx); ix++) {
for (iy = 0; iy < (n_max); iy++)
free (prob_xz[ix][iy]);
free (prob_xz[ix]);
}
free (prob_xz);
for (ix = 0; ix < (n_max); ix++) {
for (iy = 0; iy < ny; iy++)
free (prob_yz[ix][iy]);
free (prob_yz[ix]);
}
free (prob_yz);
/* free memory of static variable phot_dist */
for (ix = 0; ix < (nx); ix++) {
for (iy = 0; iy < (ny); iy++)
free (phot_dist_xy[ix][iy]);
free (phot_dist_xy[ix]);
}
free (phot_dist_xy);
for (ix = 0; ix < (nx); ix++) {
for (iy = 0; iy < (n_max); iy++)
free (phot_dist_xz[ix][iy]);
free (phot_dist_xz[ix]);
}
free (phot_dist_xz);
for (ix = 0; ix < (n_max); ix++) {
for (iy = 0; iy < ny; iy++)
free (phot_dist_yz[ix][iy]);
free (phot_dist_yz[ix]);
}
free (phot_dist_yz);
} /* close kabs_save */
} /* end 3D */
/* If there is a inner cuboid/cube, perform following calculation*/
else { /* if 1D */
/* The whole calculation from the 3D case is performed only in z-direction */
if (atmos->kabs->prof[MCCAOTH_TOT][p->kc] != kabs_save) {
mug = 0;
delta_tau_orig = 1;
tau_cutoff = 10;
/* calculate tau of x,y and z-direction */
tau_z = atmos->kabs->prof[MCCAOTH_TOT][p->kc] * (atmos->Z[p->kc + 1] - atmos->Z[p->kc]);
/* maximum number of sub grid boxes within tau_cutoff */
n_max = (int)(tau_cutoff / delta_tau_orig);
/* If the minimum optical thickness is smaller then the standard "tau_cutoff=10", find a new tau_cutoff */
if (2 * tau_cutoff >= tau_z)
n_max = (int)(tau_z / (2 * delta_tau_orig));
if (n_max <= 0) {
fprintf (stderr, "Ooops! n_max ( %d ) should never be zero or smaller than zero! Some error occured! \n", n_max);
return -1;
}
/* calculate number of sub cubes / number of sub-distances in one direction */
nz = (int)(tau_z / delta_tau_orig) + 1;
N_sub = nz;
N_sub_cutoff = 2 * n_max;
delta_tau_z = tau_z / nz;
/* calculate original photon distribution per sub-cube */
N0 = nphotons / N_sub;
N0_z = N0 * N_sub_cutoff;
/* If there is a inner cuboid/cube, perform following calculation*/
/* if (n_max>0) { */
/* allocate memory */
p_z = calloc (nz, sizeof (double));
p_an_z = calloc (nz / 2, sizeof (double));
p_sum1_z = calloc (n_max, sizeof (double));
prob_z = calloc (nz, sizeof (double));
w_z = calloc (nz, sizeof (double));
phot_dist_z = calloc (nz, sizeof (double));
/* free memory of static variable p_sum2 */
if (p_sum2 != NULL)
free (p_sum2);
p_sum2 = calloc (N_sub_cutoff / 2 + 1, sizeof (double));
/* save optical thickness of current grid box. Necessary to check if optical */
/* thickness has changed for next photon and if this calculation has to be */
/* performed again */
kabs_save = atmos->kabs->prof[MCCAOTH_TOT][p->kc];
/* estimate escape probability */
for (iz = 0; iz < (nz / 2); iz++)
p_an_z[iz] = ((pst (1, iz, delta_tau_z) - pst (1, (iz + 1), delta_tau_z)) -
(pst (mug, iz, delta_tau_z) - pst (mug, (iz + 1), delta_tau_z))) /
delta_tau_z / (1 - mug);
/* calculate total p for each sub-part in z */
for (iz = 0; iz < (nz / 2); iz++) {
p_z[iz] = p_an_z[iz];
p_z[nz - iz - 1] = p_an_z[iz];
}
/* averaged probability */
for (iz = 0; iz < n_max; iz++) {
prob_z[iz] = p_z[iz];
p_avg_out += (2 * N0 * sqrt (prob_z[iz] * (1 - prob_z[iz])));
}
p_in = p_z[n_max + 1];
p_in_avg = (nphotons - (N0_z)) * sqrt (p_in * (1 - p_in));
p_avg = (p_avg_out + p_in_avg) / nphotons;
/* calculate weight */
for (iz = 0; iz < n_max; iz++) {
w_z[iz] = (p_avg / sqrt (prob_z[iz] * (1 - prob_z[iz])));
phot_dist_z[iz] = 2 * N0 / w_z[iz];
phot_frac += phot_dist_z[iz];
p_sum1_z[iz] = phot_dist_z[iz] / N0_z;
p_sum_z += phot_dist_z[iz] / N0_z;
}
w_in = (p_avg / sqrt (p_in * (1 - p_in)));
phot_dist_in = (nphotons - (N0_z)) / w_in;
p_sum_tot = p_sum_z;
p_sum2[0] = 0.0;
phot_frac = phot_frac / (phot_frac + phot_dist_in);
for (iz = 1; iz <= (n_max); iz++)
p_sum2[iz] = p_sum2[iz - 1] + p_sum1_z[iz - 1] / p_sum_tot;
/* **** free memory **** */
free (p_z);
free (p_an_z);
free (p_sum1_z);
free (prob_z);
free (phot_dist_z);
} /* end kabs_save */
} /* end 1D */
/* ************************************************************************* */
/* End of calcualtion for a changing optical thickness */
/* ************************************************************************* */
/* ************************************************************************* */
/* In the following - starting locations of the photons within the sub grid */
/* boxes are choosen randomly and the corrsponding weight is applied */
/* ************************************************************************* */
if (atmos->kabs3D->threed[MCCAOTH_TOT][p->kc] >= 1) { /* if 3D */
/* if(n_max>0){ */
r_frac = uvspec_random();
if (r_frac < phot_frac) { /* if photon is within cutoff optical thickness, if not, see calulation for inner cubiod/cube */
/* getting position/intervall of cumulative probability */
r_location = uvspec_random();
position = locate (p_sum2, N_sub_cutoff / 2, r_location);
/* deriving x,y and z coordinate from culumaltive probability */
/* Find exact starting position and apply weight */
if (position < nx * ny * n_max) {
ix = position / (ny * n_max);
iy = (position - ix * ny * n_max) / n_max;
iz = position - ix * ny * n_max - iy * n_max;
p->weight *= w_xy[ix][iy][iz];
p->weight_emis *= w_xy[ix][iy][iz];
r_location = uvspec_random();
if (r_location < 0.5) {
p->x[0] = ((double)sample->backward_is + ((double)ix + uvspec_random()) / (double)nx) * sample->delX;
p->x[1] = ((double)sample->backward_js + ((double)iy + uvspec_random()) / (double)ny) * sample->delY;
delta_z = (atmos->Z[p->kc + 1] - atmos->Z[p->kc]) / nz * (iz + uvspec_random());
} else {
p->x[0] = ((double)sample->backward_is + ((double)ix + uvspec_random()) / (double)nx) * sample->delX;
p->x[1] = ((double)sample->backward_js + ((double)iy + uvspec_random()) / (double)ny) * sample->delY;
delta_z = (atmos->Z[p->kc + 1] - atmos->Z[p->kc]) / nz * ((nz - iz - 1) + uvspec_random());
}
}
else if ((position < (nx * ny * n_max + nx * nz * n_max)) && (position >= (nx * ny * n_max))) {
position = position - nx * ny * n_max;
ix = position / (nz * n_max);
iy = (position - ix * nz * n_max) / nz;
iz = position - ix * nz * n_max - iy * nz;
p->weight *= w_xz[ix][iy][iz];
p->weight_emis *= w_xz[ix][iy][iz];
r_location = uvspec_random();
if (r_location < 0.5) {
p->x[0] = ((double)sample->backward_is + ((double)ix + uvspec_random()) / (double)nx) * sample->delX;
p->x[1] = ((double)sample->backward_js + ((double)iy + uvspec_random()) / (double)ny) * sample->delY;
delta_z = (atmos->Z[p->kc + 1] - atmos->Z[p->kc]) / nz * (iz + uvspec_random());
} else {
p->x[0] = ((double)sample->backward_is + ((double)ix + uvspec_random()) / (double)nx) * sample->delX;
p->x[1] = ((double)sample->backward_js + ((double)(ny - iy - 1) + uvspec_random()) / (double)ny) * sample->delY;
delta_z = (atmos->Z[p->kc + 1] - atmos->Z[p->kc]) / nz * (iz + uvspec_random());
}
}
else {
position = position - nx * ny * n_max - nx * nz * n_max;
ix = position / (ny * nz);
iy = (position - ix * ny * nz) / nz;
iz = position - ix * ny * nz - iy * nz;
p->weight *= w_yz[ix][iy][iz];
p->weight_emis *= w_yz[ix][iy][iz];
r_location = uvspec_random();
if (r_location < 0.5) {
p->x[0] = ((double)sample->backward_is + ((double)ix + uvspec_random()) / (double)nx) * sample->delX;
p->x[1] = ((double)sample->backward_js + ((double)iy + uvspec_random()) / (double)ny) * sample->delY;
delta_z = (atmos->Z[p->kc + 1] - atmos->Z[p->kc]) / nz * (iz + uvspec_random());
} else {
p->x[0] = ((double)sample->backward_is + ((double)(nx - ix - 1) + uvspec_random()) / (double)nx) * sample->delX;
p->x[1] = ((double)sample->backward_js + ((double)iy + uvspec_random()) / (double)ny) * sample->delY;
delta_z = (atmos->Z[p->kc + 1] - atmos->Z[p->kc]) / nz * (iz + uvspec_random());
}
}
if (!sample->spherical3D)
atmos_coord (p, atmos, &(p->ic), &(p->jc));
set_photon_z (p->x[2] + delta_z, atmos, p);
} /* end phot_frac */
else { /* if photon is started in inner cuboid/cube */
p->x[0] =
((double)sample->backward_is + (((double)n_max + (double)(nx - 2 * n_max) * uvspec_random())) / (double)nx) * sample->delX;
p->x[1] =
((double)sample->backward_js + (((double)n_max + (double)(ny - 2 * n_max) * uvspec_random())) / (double)ny) * sample->delY;
delta_z = (atmos->Z[p->kc + 1] - atmos->Z[p->kc]) / nz * (n_max + ((nz - 2 * n_max) * uvspec_random()));
p->weight *= w_in;
p->weight_emis *= w_in;
if (!sample->spherical3D)
atmos_coord (p, atmos, &(p->ic), &(p->jc));
set_photon_z (p->x[2] + delta_z, atmos, p);
}
} /* end 3D */
else { /* if 1d */
/* if(n_max>0){ */
r_frac = uvspec_random();
if (r_frac < phot_frac) { /* if photon is within cutoff optical thickness, if not, see calulation for inner cubiod/cube */
/* getting position/intervall of cumulative probability */
r_location = uvspec_random();
position = locate (p_sum2, N_sub_cutoff / 2, r_location);
/* deriving x,y and z coordinate from culumaltive probability */
/* Find exact starting position and apply weight */
iz = position;
p->weight *= w_z[iz];
p->weight_emis *= w_z[iz];
r_location = uvspec_random();
if (r_location < 0.5)
delta_z = (atmos->Z[p->kc + 1] - atmos->Z[p->kc]) / nz * (iz + uvspec_random());
else
delta_z = (atmos->Z[p->kc + 1] - atmos->Z[p->kc]) / nz * ((nz - iz - 1) + uvspec_random());
if (!sample->spherical3D)
atmos_coord (p, atmos, &(p->ic), &(p->jc));
set_photon_z (p->x[2] + delta_z, atmos, p);
}
else { /* if photon is started in inner cuboid/cube */
delta_z = (atmos->Z[p->kc + 1] - atmos->Z[p->kc]) / nz * (n_max + ((nz - 2 * n_max) * uvspec_random()));
p->weight *= w_in;
p->weight_emis *= w_in;
if (!sample->spherical3D)
atmos_coord (p, atmos, &(p->ic), &(p->jc));
set_photon_z (p->x[2] + delta_z, atmos, p);
}
} /* end if 1d */
return 0;
} /* End function emabsopt_location */
/***********************************************************************************/
/* Function: denet_weight @62_30i@ */
/* Description: */
/* Calculates additional weightings according to starting direction */
/* for dEnet method. Counts photons (counter1) */
/* An exact description of the method can be found in Klinger and Mayer (2013). */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Carolin Klinger, 2013.09.27 */
/* @i62_30@ */
/***********************************************************************************/
static int denet_weight (photon_struct* p, atmosphere_struct* atmos, sample_struct* sample, long int nphotons, int* counter1) {
if (atmos->kabs3D->threed[MCCAOTH_TOT][p->kc] >= 1) { /* 3D case */
p->weight = sample->weight_heat;
/* upper and lower area - set z new, x and y are constant*/
if ((*counter1 < (sample->n_xy / 4)) || (*counter1 < (3 * sample->n_xy / 4) && *counter1 >= (sample->n_xy / 2))) {
/* set location to the edge of the layer (lower edge)*/
set_photon_z (atmos->Z[p->kc], atmos, p);
p->n_dEnet = sample->n_xy / 4;
if (p->dir.dx[2] < 0)
p->dEnet_component = 0;
if (p->dir.dx[2] > 0) {
p->weight *= -1.0;
p->dEnet_component = 1;
}
}
else if ((*counter1 < (sample->n_xy / 2) && *counter1 >= (sample->n_xy / 4)) ||
(*counter1 < (sample->n_xy) && *counter1 >= (3 * sample->n_xy / 4))) {
/* set location to the edge of the layer (upper edge)*/
set_photon_z ((atmos->Z[p->kc + 1]), atmos, p);
p->n_dEnet = sample->n_xy / 4;
if (p->dir.dx[2] > 0)
p->dEnet_component = 2;
if (p->dir.dx[2] < 0) {
p->weight *= -1.0;
p->dEnet_component = 3;
}
}
/* left and right area - set x new, y and z are constant*/
else if ((*counter1 < (sample->n_xy + (sample->n_yz / 4)) && *counter1 >= (sample->n_xy)) ||
(*counter1 < (sample->n_xy + (3 * sample->n_yz / 4)) && *counter1 >= (sample->n_xy + (sample->n_yz / 2)))) {
/* set location to the edge of the layer (left)*/
p->x[0] = (double)sample->backward_is * sample->delX;
p->n_dEnet = sample->n_yz / 4;
if (p->dir.dx[0] < 0)
p->dEnet_component = 4;
if (p->dir.dx[0] > 0) {
p->weight *= -1.0;
p->dEnet_component = 5;
}
}
else if ((*counter1 < (sample->n_xy + (sample->n_yz / 2)) && *counter1 >= (sample->n_xy + (sample->n_yz / 4))) ||
(*counter1 < (sample->n_xy + (sample->n_yz)) && *counter1 >= (sample->n_xy + (3 * sample->n_yz / 4)))) {
/* set location to the edge of the layer (right)*/;
p->x[0] = (double)(sample->backward_is + 1) * sample->delX;
p->n_dEnet = sample->n_yz / 4;
if (p->dir.dx[0] > 0)
p->dEnet_component = 6;
if (p->dir.dx[0] < 0) {
p->weight *= -1.0;
p->dEnet_component = 7;
}
}
/* front and back area - set y new, x and z are constant*/
else if ((*counter1 < (sample->n_xy + sample->n_yz + (sample->n_xz / 4)) && *counter1 >= (sample->n_xy + (sample->n_yz))) ||
(*counter1 < (sample->n_xy + sample->n_yz + (3 * sample->n_xz / 4)) &&
*counter1 >= (sample->n_xy + sample->n_yz + (sample->n_xz / 2)))) {
/* set location to the edge of the layer (forward)*/
p->x[1] = (double)sample->backward_js * sample->delY;
p->n_dEnet = sample->n_xz / 4;
if (p->dir.dx[1] < 0)
p->dEnet_component = 8;
if (p->dir.dx[1] > 0) {
p->weight *= -1.0;
p->dEnet_component = 9;
}
}
else {
/* set location to the edge of the layer (backward)*/
p->x[1] = (double)(sample->backward_js + 1) * sample->delY;
p->n_dEnet = sample->n_xz / 4;
if (p->dir.dx[1] > 0)
p->dEnet_component = 10;
if (p->dir.dx[1] < 0) {
p->weight *= -1.0;
p->dEnet_component = 11;
}
}
}
else { /* 1d case */
/* upper and lower area - set z new, x and y are constant*/
// if ((*counter1 < (nphotons/4)) || (*counter1 < (3*nphotons/4) && *counter1 >= (2*nphotons/4))) {
if ((*counter1 < (sample->n_xy / 4)) || (*counter1 < (3 * sample->n_xy / 4) && *counter1 >= (sample->n_xy / 2))) {
/* set location to the edge of the layer (lower edge)*/
set_photon_z (atmos->Z[p->kc], atmos, p);
p->n_dEnet = sample->n_xy / 4;
if (p->dir.dx[2] < 0)
p->dEnet_component = 0;
if (p->dir.dx[2] > 0) {
p->weight *= -1.0;
p->dEnet_component = 1;
}
}
// else if ((*counter1 < (2*nphotons/4) && *counter1 >= (nphotons/4)) || (*counter1 < (4*nphotons/4) && *counter1 >= (3*nphotons/4))) {
else { //((*counter1 < (2*sample->n_xy/4) && *counter1 >= (1*sample->n_xy/4)) || (*counter1 < (4*sample->n_xy/4) && *counter1 >= (3*sample->n_xy/4))) {
/* set location to the edge of the layer (upper edge)*/
set_photon_z ((atmos->Z[p->kc + 1]), atmos, p);
p->n_dEnet = sample->n_xy / 4;
if (p->dir.dx[2] > 0)
p->dEnet_component = 2;
if (p->dir.dx[2] < 0) {
p->weight *= -1.0;
p->dEnet_component = 3;
}
}
}
atmos_coord (p, atmos, &(p->ic), &(p->jc));
(*counter1)++;
if (*counter1 == nphotons)
(*counter1) = 0;
return 0;
}
/***********************************************************************************/
/* Function: denet_set_direction @62_30i@ */
/* Description: */
/* Sets diretion for dEnet method (photon direction at each face of grid box. */
/* An exact description of the method can be found in Klinger and Mayer (2013). */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: */
/* Author: Carolin Klinger, 2013.09.27 */
/* @i62_30@ */
/***********************************************************************************/
static int denet_set_direction (photon_struct* p,
atmosphere_struct* atmos,
sample_struct* sample,
long int nphotons,
int* counter1,
double* norm) {
int i = 0;
if (atmos->kabs3D->threed[MCCAOTH_TOT][p->kc] >= 1) { /* 3D */
if (*counter1 < (sample->n_xy / 2)) /* downward */
random_Lambertian_normal (&(p->dir), norm);
else if (*counter1 < (2 * sample->n_xy / 2)) {
/* upward */
for (i = 0; i < 3; i++)
norm[i] = -norm[i];
random_Lambertian_normal (&(p->dir), norm);
}
else if (*counter1 >= (2 * sample->n_xy / 2) && *counter1 < (sample->n_xy + (sample->n_yz / 2))) {
/* right */
norm[0] = 1.0;
norm[1] = 0.0;
norm[2] = 0.0;
random_Lambertian_normal (&(p->dir), norm);
}
else if (*counter1 >= (sample->n_xy + (sample->n_yz / 2)) && *counter1 < (sample->n_xy + (2 * sample->n_yz / 2))) {
/* left */
norm[0] = -1.0;
norm[1] = 0.0;
norm[2] = 0.0;
random_Lambertian_normal (&(p->dir), norm);
}
else if (*counter1 >= (sample->n_xy + (2 * sample->n_yz / 2)) &&
*counter1 < (sample->n_xy + sample->n_yz + (sample->n_xz / 2))) {
/* forward */
norm[0] = 0.0;
norm[1] = -1.0;
norm[2] = 0.0;
random_Lambertian_normal (&(p->dir), norm);
}
else {
/* backward */
norm[0] = 0.0;
norm[1] = 1.0;
norm[2] = 0.0;
random_Lambertian_normal (&(p->dir), norm);
}
}
else { /* 1D */
// if (*counter1 < (nphotons/2)) {
if (*counter1 < (sample->n_xy / 2)) {
/* downward */
random_Lambertian_normal (&(p->dir), norm);
} else {
/* upward */
for (i = 0; i < 3; i++)
norm[i] = -norm[i];
random_Lambertian_normal (&(p->dir), norm);
}
}
return 0;
}
/***********************************************************************************/
/* Function: dist_photon_direction_by_phasemax */
/* Description: */
/* Distribute initial backward photon directions according to phase_max. */
/* This used for the option mc_panorama circumsolar_var_red */
/* Parameters: */
/* Return value: */
/* Example: */
/* Files: */
/* Known bugs: Extent of sundisk or extraterrestrial sunshape is not considered. */
/* Implementation should be easy. Just fold phase_max with sunshape. */
/* Author: Bernhard Reinhardt, 2014.03.27 */
/* @i62_30@ */
/***********************************************************************************/
static int
dist_photon_direction_by_phasemax (photon_struct* p, sample_struct* sample, double* sza, double* cossza, double* sinsza) {
double F_max = 0.0, F_min = 0.0;
double mu_min = 0.0, mu_max = 0.0;
double phase_max_value = 0.0;
/* Distribute photon directions according to
phase_max. Store upper and lower boundaries of
pixel*/
mu_min = *cossza;
mu_max = cosd (*sza + sample->pan_dtheta);
/* Get cummulative values F of phase_max for upper and
lower boundary of pixel */
F_min = get_F (sample->phase_max[0], -mu_min, 0);
F_max = get_F (sample->phase_max[0], -mu_max, 0);
/* Choose a random starting mu according to phase
function phase_max for the photon by abusing the
scattering routine sc_mu */
*cossza = -sc_mu (sample->phase_max[0], 1, 0, F_max, F_min);
*sza = acosd (*cossza);
*sinsza = sqrt (1.0 - (*cossza) * (*cossza));
/* Now adjust photon weight for the "unphysical"
choice of direction: Divide photon-weight by
probability from phase_max for sending it into this
direction */
phase_max_value = get_phase_max (sample->phase_max, sample->n_phase_max, -1.0 * *cossza, p->DDIS_SC_mode);
p->weight /= 2.0 / fabs (F_max - F_min) * phase_max_value;
/* Now multiply photon weight by the photons
probability it would have been sent to this
direction by geometrical considerations */
p->weight *= 2.0 / fabs (-mu_max + mu_min);
/* Handling of input file errors */
if (sample->pan_alignment != MCPAN_ALIGNMENT_SUN) {
fprintf (stderr,
"%s %s",
"\n\n mc_panorama circumsolar_var_red can only be used together with",
"mc_panorama_alignment sun!\n\n");
return -1;
}
return 0;
}
| {
"alphanum_fraction": 0.4179417009,
"avg_line_length": 42.5254628658,
"ext": "c",
"hexsha": "0402c38fec80d345e388f9be54cb36c6c0075f99",
"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": "0182f991db6a13e0cacb3bf9f43809e6850593e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "AmberCrafter/docker-compose_libRadtran",
"max_forks_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/mystic.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4",
"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": "AmberCrafter/docker-compose_libRadtran",
"max_issues_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/mystic.c",
"max_line_length": 264,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "AmberCrafter/docker-compose_libRadtran",
"max_stars_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/mystic.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 237758,
"size": 1012914
} |
#ifndef __GSL_SORT_H__
#define __GSL_SORT_H__
#include <gsl/gsl_sort_long_double.h>
#include <gsl/gsl_sort_double.h>
#include <gsl/gsl_sort_float.h>
#include <gsl/gsl_sort_ulong.h>
#include <gsl/gsl_sort_long.h>
#include <gsl/gsl_sort_uint.h>
#include <gsl/gsl_sort_int.h>
#include <gsl/gsl_sort_ushort.h>
#include <gsl/gsl_sort_short.h>
#include <gsl/gsl_sort_uchar.h>
#include <gsl/gsl_sort_char.h>
#endif /* __GSL_SORT_H__ */
| {
"alphanum_fraction": 0.7747126437,
"avg_line_length": 20.7142857143,
"ext": "h",
"hexsha": "b1496c2efbfe8973743213f869d15bf416bc40d0",
"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/sort/gsl_sort.h",
"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/sort/gsl_sort.h",
"max_line_length": 37,
"max_stars_count": 77,
"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/sort/gsl_sort.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-24T22:20:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-18T00:45:00.000Z",
"num_tokens": 136,
"size": 435
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
#include <gbpInterpolate.h>
double interpolate_derivative(interp_info *interp, double x) {
double r_val;
r_val = gsl_interp_eval_deriv(
((interp_info *)interp)->interp, ((interp_info *)interp)->x, ((interp_info *)interp)->y, x, ((interp_info *)interp)->accel);
return (r_val);
}
| {
"alphanum_fraction": 0.6928251121,
"avg_line_length": 27.875,
"ext": "c",
"hexsha": "1c8f39bf88c5b54f552cd537b8d83ff7b749a628",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpMath/gbpInterpolate/interpolate_derivative.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpMath/gbpInterpolate/interpolate_derivative.c",
"max_line_length": 132,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpMath/gbpInterpolate/interpolate_derivative.c",
"max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z",
"num_tokens": 123,
"size": 446
} |
#ifndef QDM_MSPLINE_H
#define QDM_MSPLINE_H 1
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
void
qdm_mspline_vector(gsl_vector *result, const double tau, const size_t spline_df, const gsl_vector *knots);
void
qdm_mspline_matrix(gsl_matrix *result, const size_t spline_df, const gsl_vector *x, const gsl_vector *knots);
#endif /* QDM_MSPLINE_H */
| {
"alphanum_fraction": 0.7916666667,
"avg_line_length": 25.7142857143,
"ext": "h",
"hexsha": "2cae4aba1f1f1d145a19ed7ee249ef0f9124f4b1",
"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": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "calebcase/qdm",
"max_forks_repo_path": "include/qdm/mspline.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_issues_repo_issues_event_max_datetime": "2020-03-22T20:22:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-03-06T18:09:06.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "calebcase/qdm",
"max_issues_repo_path": "include/qdm/mspline.h",
"max_line_length": 109,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ee95bec6c8be64f69e231c78f2be5fce3509c67",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "calebcase/qdm",
"max_stars_repo_path": "include/qdm/mspline.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 109,
"size": 360
} |
#include <gsl/gsl_errno.h>
#include <gsl/matrix/gsl_matrix.h>
#include <gsl/vector/gsl_vector.h>
#define BASE_DOUBLE
#include <gsl/templates_on.h>
#include <gsl/matrix/getset_source.c>
#include <gsl/templates_off.h>
#undef BASE_DOUBLE
| {
"alphanum_fraction": 0.776371308,
"avg_line_length": 21.5454545455,
"ext": "c",
"hexsha": "1e343723350360a1609635308e8b40f2f7feca7d",
"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": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_forks_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/getset.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"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": "MontyThibault/centre-of-mass-awareness",
"max_issues_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/getset.c",
"max_line_length": 37,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58778f148e65749e1dfc443043e9fc054ca3ff4d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MontyThibault/centre-of-mass-awareness",
"max_stars_repo_path": "Cartwheel/cartwheel-3d/gsl/matrix/getset.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 65,
"size": 237
} |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright 2018 - Matteo Ragni, Matteo Cocetti - University of Trento
*
* 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 LIBNEWTON_H_
#define LIBNEWTON_H_
#include <lapacke.h>
#include <cblas.h>
/**
* @brief Jacobian Callback for the Newton algorithm
*
* The callback receivs the current input, the current control, and the list of
* parameter vectors. It should store the first argument the Jacobian matrix (stored as an array).
* To select the ordering in the matrix, you must select the correct ordering in newton_options
* structure, at the ordering input.
* @param df output vector (vectorized Jacobian matrix)
* @param t current time for evaluation
* @param x current point for evaluation
* @param u current control for evaluation
* @param p array of parameter vectors
* @param data user space input (simply use it as a pointer casted to void)
*/
typedef void (*newton_jacobian)(
double *df,
const double t,
const double *x,
const double *u,
const double **p,
void *data);
/**
* @brief Vector Field Callback for the Newton algorithm
*
* The callback receivs the current input, the current control, and the list of
* parameter vectors. It should store the first argument the function output vector.
* @param df output vector (vectorized Jacobian matrix)
* @param t current time for evaluation
* @param x current point for evaluation
* @param u current control for evaluation
* @param p array of parameter vectors
* @param data user space input (simply use it as a pointer casted to void)
*/
typedef void (*newton_function)(
double *f,
const double t,
const double *x,
const double *u,
const double **p,
void *data);
/**
* @brief Options for the Newton Algorithm
*
* This structure contains all the options for the Newton algorithm, alongside the callbacks.
* The structure will be modified by the algorithm with some debug information, such as number
* of iterations, tolerances and ordering for the jacobian matrix.
*/
typedef struct newton_options {
lapack_int ordering; /**< Should be LAPACK_ROW_MAJOR or LAPACK_COL_MAJOR */
lapack_int f_size; /**< Vector field size */
lapack_int x_size; /**< Variable vector size */
double f_tol; /**< Stopping tolerance for the zero.
At the end will contain the 2 norm of the
vector field in the solution */
double x_tol; /**< Stopping tolerance for the x vector step.
At the end will contain the 2 norm of the last update step */
lapack_int max_iter; /**< Maximum number of iteration,
At the end will contain the number of step executed */
newton_function f; /**< Pointer to vector field callback */
newton_jacobian df; /**< Pointer to Jacobian callback */
} newton_options;
/**
* @brief Error code returned by the algorithm
*/
typedef enum newton_ret {
NEWTON_F_TOL = 0, /**< (0) The solver reached the required tolerance limit for the vector field */
NEWTON_X_TOL, /**< (1) The last step for solution update was less than the minimum */
NEWTON_MAX_ITER, /**< (2) Maximum number of iterations reached */
NEWTON_SINGULAR_JACOBIAN, /**< (3 LAPACKE) The jacobian is singular */
NEWTON_ILLEGAL_JACOBIAN, /**< (4 LAPACKE) Illegal jacobian */
NEWTON_MALLOC_ERROR, /**< (5) Cannot allocate memory */
NEWTON_GENERIC_ERROR /**< (6) Generic error in the execution of the algorithm */
} newton_ret;
/**
* @brief Boolean implementation
*/
typedef enum newton_bool {
NEWTON_FALSE = 0, /**< False */
NEWTON_TRUE /**< True */
} newton_bool;
/**
* @brief Executes the Newton algorithm for root finding
*
* Executes the Newton algorithm for root finding. The step Performed is:
* \f{
* x_{k+1} - x_{k} = -\nabla F^{-1}(x_k, u, p) F(x_k, u, p)
* \f}
* and the solution is found by using DGELS defined in LAPACK library.
* The stopping conditions are:
* * Number of iterations bigger than maximum allowed (specified in newton_options)
* * \f$ |x_{k+1} - x_k| \leq x_{tol}\f$
* * \f$ |f(x_k, u, p)| \leq y_{tol}\f$
* and the function and jacobian are evaluated through callbacks. On exit, the values
* inside the option structure are update for debuggin purposes (this is why Newton
* options is not a const pointer). It returns a status enum.
* @param opt option structure
* @param x root position and initial condition. Will be modified
* @param u control action input. It can be NULL.
* @param p parameter array of vectors. It can be NULL.
* @param data space for user data. Will be passed to callbacks. It can be NULL
* @return a status exit code as described in newton_ret enum.
*/
newton_ret newton_solve(
newton_options *opt,
const double t,
double *x,
const double *u,
const double **p,
void *data);
#endif
| {
"alphanum_fraction": 0.6667733163,
"avg_line_length": 43.1103448276,
"ext": "h",
"hexsha": "a098d32ea181b719f94091ce4350af5e06308d8e",
"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": "7dd73c1b383b6c32086da4880a82326ebf47b71b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MatteoRagni/libeuler",
"max_forks_repo_path": "libnewton.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7dd73c1b383b6c32086da4880a82326ebf47b71b",
"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": "MatteoRagni/libeuler",
"max_issues_repo_path": "libnewton.h",
"max_line_length": 109,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "7dd73c1b383b6c32086da4880a82326ebf47b71b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MatteoRagni/libeuler",
"max_stars_repo_path": "libnewton.h",
"max_stars_repo_stars_event_max_datetime": "2020-01-22T02:16:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-05T07:42:42.000Z",
"num_tokens": 1488,
"size": 6251
} |
/**
*
* @file core_zhetrf2_nopiv.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.4.5
* @author Dulceneia Becker
* @date 2011-1-18
**/
/*
* @precisions normal z -> c d s
*/
#include <lapacke.h>
#include "dplasma_cores.h"
#include "dplasma_zcores.h"
#if defined(PARSEC_HAVE_STRING_H)
#include <string.h>
#endif /* defined(PARSEC_HAVE_STRING_H) */
#if defined(PARSEC_HAVE_STDARG_H)
#include <stdarg.h>
#endif /* defined(PARSEC_HAVE_STDARG_H) */
#include <stdio.h>
#ifdef PARSEC_HAVE_LIMITS_H
#include <limits.h>
#endif
#include <cblas.h>
#include <core_blas.h>
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
extern void CORE_zhetrf_nopiv(int uplo, int N, int ib,
PLASMA_Complex64_t *A, int LDA,
PLASMA_Complex64_t *WORK, int LDWORK,
int *INFO);
void CORE_zhetrf2_nopiv(PLASMA_enum uplo, int N, int ib,
PLASMA_Complex64_t *A, int LDA,
PLASMA_Complex64_t *WORK, int LWORK, int *INFO);
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex64_t
*
* CORE_zhetrf2_nopiv: ZHETRF_NOPIV followed by L*D
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
#if defined(PLASMA_PARSEC_HAVE_WEAK)
#pragma weak CORE_zhetrf2_nopiv = PCORE_zhetrf2_nopiv
#define CORE_zhetrf2_nopiv PCORE_zhetrf2_nopiv
#endif
void CORE_zhetrf2_nopiv(PLASMA_enum uplo, int N, int ib,
PLASMA_Complex64_t *A, int LDA,
PLASMA_Complex64_t *WORK, int LWORK, int *INFO)
{
int j;
PLASMA_Complex64_t alpha;
/* Factorize A as L*D*L' using the lower/upper triangle of A */
CORE_zhetrf_nopiv(uplo, N, ib, A, LDA, WORK, LWORK, INFO);
if (uplo==PlasmaLower) {
// Multiply L by D
for (j=0; j<(N-1); j++) {
alpha = A[LDA*j+j];
cblas_zscal(N-j-1, CBLAS_SADDR(alpha), &A[LDA*j+j+1], 1);
}
} else if (uplo==PlasmaUpper) {
// Multiply U by D
for (j=1; j<N; j++) {
alpha = A[LDA*j+j];
cblas_zscal(j, CBLAS_SADDR(alpha), &A[LDA*j], 1);
}
}
}
| {
"alphanum_fraction": 0.5620031797,
"avg_line_length": 27.0537634409,
"ext": "c",
"hexsha": "7df8b6f5643382a8fe8d5e3bfa3c03edf578e2f6",
"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": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "NLAFET/ABFT",
"max_forks_repo_path": "dplasma/cores/core_zhetrf2_nopiv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "NLAFET/ABFT",
"max_issues_repo_path": "dplasma/cores/core_zhetrf2_nopiv.c",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "NLAFET/ABFT",
"max_stars_repo_path": "dplasma/cores/core_zhetrf2_nopiv.c",
"max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z",
"num_tokens": 759,
"size": 2516
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.