Search is not available for this dataset
text string | meta dict |
|---|---|
#ifndef UBLAS_LIB_PLASMA_H
#define UBLAS_LIB_PLASMA_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
#include <plasma.h>
#include <cblas.h>
#include <lapacke.h>
#include <core_blas.h>
#include <ublas_types.h>
int ubf_init(void **ctx);
int ubf_gemm(void *ctx, ublas_matrix *a, ublas_matrix *b, ublas_matrix *c, double alpha, double beta);
int ubf_free(void *ctx);
#endif | {
"alphanum_fraction": 0.7382075472,
"avg_line_length": 21.2,
"ext": "h",
"hexsha": "b3a7bac7008e904dc93e61ed0be464f0b450c451",
"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": "770ae52382e2d7705ed3d990d8e33e6b6cc66e2e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "brgmnn/uob-ublas",
"max_forks_repo_path": "src/drivers/plasma/plasma.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "770ae52382e2d7705ed3d990d8e33e6b6cc66e2e",
"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": "brgmnn/uob-ublas",
"max_issues_repo_path": "src/drivers/plasma/plasma.h",
"max_line_length": 102,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "770ae52382e2d7705ed3d990d8e33e6b6cc66e2e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "brgmnn/uob-ublas",
"max_stars_repo_path": "src/drivers/plasma/plasma.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T03:13:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-13T03:13:08.000Z",
"num_tokens": 128,
"size": 424
} |
/* code by: iperetta@ieee.org */
#ifndef MYMATRIX_H_
#define MYMATRIX_H_
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>
#include <stdexcept>
#include <limits>
#include <lapacke.h>
#include "myfun.h"
using namespace std;
#ifndef MyEPS_
#define MyEPS_
static double EPS = numeric_limits<double>::epsilon();
#endif
// =====================================================================
template<typename T>
struct brace {
T first, second;
};
template<typename T> brace<T> make_brace(const T &m1, const T &m2) {
brace<T> ans;
ans.first = m1;
ans.second = m2;
return ans;
}
template<typename T>
struct triplet {
T first, second, third;
};
template<typename T> triplet<T> make_triplet(const T &m1, const T &m2,
const T &m3) {
triplet<T> ans;
ans.first = m1;
ans.second = m2;
ans.third = m3;
return ans;
}
// =====================================================================
class Matrix;
Matrix column_vector(const vector<double> &vec);
Matrix row_vector(const vector<double> &vec);
Matrix identityMatrix(const size_t &N);
Matrix diagonalMatrix(const vector<double> &vec);
class Matrix { // Matrix A_mXn
friend Matrix operator+(const double &lhs, const Matrix &rhs);
friend Matrix operator-(const double &lhs, const Matrix &rhs);
friend Matrix operator*(const double &lhs, const Matrix &rhs);
friend Matrix operator/(const double &lhs, const Matrix &rhs);
friend ostream& operator<<(ostream &os, const Matrix& M);
protected:
vector<double> elements;
void badConvergence(const string &str) const;
void invalidArgument(const int &errid, const string &str) const;
void checkDim(const size_t &i_, const string &str = "") const;
void checkDim(const size_t &i_, const size_t &j_,
const string &str = "") const;
void checkSize(const size_t &i_, const size_t &j_,
const string &str = "") const;
void ensureSquare(const string &str = "") const;
void ensureSameSize(const Matrix &B, const string &str = "") const;
void ensureNonSingularity(const string &str = "") const;
void ensureVector(const string &str) const;
public:
size_t m; // number of rows of the matrix
size_t n; // number of columns of the matrix
Matrix(); //constructor
Matrix(const size_t &m_, const size_t &n_, const double &cns = 0.);
Matrix(const size_t &m_, const size_t &n_, const double *elem,
const size_t &sz_elem);
Matrix(const size_t &m_, const size_t &n_,
const vector<double> &elem);
void swap(Matrix &);
~Matrix() {};//destructor
void print() const;
string str() const;
double& at(const size_t &i_);
const double& at(const size_t &i_) const;
double& at(const size_t &i_, const size_t &j_);
const double& at(const size_t &i_, const size_t &j_) const;
vector<double> as_vector() const;
vector<double> row(const size_t &r_) const;
void assign2row(const size_t &r_, const double &value);
void assign2row(const size_t &r_, const vector<double> &values);
void assign2row(const size_t &r_, const double *values,
const size_t &sz);
vector<double> column(const size_t &c_) const;
void assign2column(const size_t &c_, const double &value);
void assign2column(const size_t &c_, const vector<double> &values);
void assign2column(const size_t &c_, const double *values,
const size_t &sz);
vector<double> diagonal() const;
void assign2diagonal(const double &value);
void assign2diagonal(const vector<double> &values);
void assign2diagonal(const double *values, const size_t &sz);
void swap_rows(const size_t &r1, const size_t &r2);
void swap_columns(const size_t &c1, const size_t &c2);
void self_concat_row(const double &cte);
void self_concat_row(const vector<double> &values);
void self_concat_row(const Matrix &B);
void self_concat_column(const double &cte);
void self_concat_column(const vector<double> &values);
void self_concat_column(const Matrix &B);
void self_delete_row(const size_t &r_);
void self_delete_column(const size_t &c_);
Matrix concat_row(const double &cte) const;
Matrix concat_row(const vector<double> &values) const;
Matrix concat_row(const Matrix &B) const;
Matrix concat_column(const double &cte) const;
Matrix concat_column(const vector<double> &values) const;
Matrix concat_column(const Matrix &B) const;
Matrix delete_row(const size_t &r_) const;
Matrix delete_column(const size_t &c_) const;
size_t rank() const;
double determinant() const;
double trace() const;
double norm() const;
double infinity_norm() const;
double frobenius_norm() const;
double condition_number() const;
double cofactor(const size_t &r_, const size_t &c_) const;
double highest_eigenvalue() const;
Matrix transpose() const;
Matrix adjoint() const;
Matrix inverse() const;
brace<Matrix> eigen() const;
triplet<Matrix> lu_p_factorization() const;
brace<Matrix> qr_factorization() const;
brace<Matrix> lq_factorization() const;
triplet<Matrix> svd() const;
Matrix pseudoinverse() const;
Matrix operator+(const double &value) const;
void operator+=(const double &value);
Matrix operator-(const double &value) const;
void operator-=(const double &value);
Matrix operator*(const double &value) const;
void operator*=(const double &value);
Matrix operator/(const double &value) const;
void operator/=(const double &value);
Matrix operator+(const Matrix &value) const;
void operator+=(const Matrix &value);
Matrix operator-(const Matrix &value) const;
void operator-=(const Matrix &value);
Matrix operator*(const Matrix &value) const;
void operator*=(const Matrix &value);
bool operator==(const Matrix &B) const;
bool operator!=(const Matrix &B) const;
double min_all(const bool &absolute) const;
double max_all(const bool &absolute) const;
bool isFullRank() const;
bool isOrthogonal() const;
bool isDiagonal() const;
bool isPositiveDefinite() const;
bool isSingular() const;
bool isSymmetric() const;
bool isSkewSymmetric() const;
bool isValid() const;
void adjust_elements(const double &tol);
void saveAs(const string &namefile) const;
};
Matrix::Matrix() : m(0), n(0) {
}
Matrix::Matrix(const size_t &m_, const size_t &n_, const double &cns) :
m(m_), n(n_) {
this->elements.assign(m*n,cns);
}
Matrix::Matrix(const size_t &m_, const size_t &n_, const double *elem,
const size_t &sz_elem) : m(m_), n(n_) {
this->checkSize(this->m*this->n, sz_elem,"(CONSTRUCTOR)");
this->elements.assign(elem, elem+sz_elem);
}
Matrix::Matrix(const size_t &m_, const size_t &n_, const vector<double>
&elem) : m(m_), n(n_) {
this->checkSize(this->m*this->n, elem.size(),"(CONSTRUCTOR)");
this->elements = elem;
}
void Matrix::swap(Matrix &other) {
// need to swap all data members
std::swap(this->elements, other.elements);
std::swap(this->m, other.m);
std::swap(this->n, other.n);
}
// =====================================================================
void Matrix::badConvergence(const string &str) const {
string MSG = (str.empty() ? "" : "in ") + str +
(str.empty() ? "" : ", ") +
"the algorithm failed to converge.";
throw std::runtime_error(MSG.c_str());
}
void Matrix::invalidArgument(const int &errid, const string &str)
const {
string MSG = (str.empty() ? "" : "in ") + str +
(str.empty() ? "" : ", ") +
"invalid argument";
cerr << "[ " << errid << " ] ";
throw std::invalid_argument(MSG.c_str());
}
void Matrix::checkDim(const size_t &i_, const string &str) const {
string MSG = (str.empty() ? "" : "in ") + str +
(str.empty() ? "" : ", ") +
"index exceeds matrix dimension";
if(i_ >= this->elements.size())
throw std::out_of_range(MSG.c_str());
}
void Matrix::checkDim(const size_t &i_, const size_t &j_,
const string &str) const {
string MSG = (str.empty() ? "" : "in ") + str +
(str.empty() ? "" : ", ") +
"index exceeds matrix dimension";
if(i_ >= this->m || j_ >= this->n)
throw std::out_of_range(MSG.c_str());
}
void Matrix::checkSize(const size_t &i_, const size_t &j_,
const string &str) const {
string MSG = (str.empty() ? "" : "in ") + str +
(str.empty() ? "" : ", ") +
"sizes of matrices don't match";
if(i_ != j_)
throw std::invalid_argument(MSG.c_str());
}
void Matrix::ensureSquare(const string &str) const {
string MSG = (str.empty() ? "" : "in ") + str +
(str.empty() ? "" : ", ") +
"exclusive to square matrices";
if(this->m != this->n)
throw std::invalid_argument(MSG.c_str());
}
void Matrix::ensureSameSize(const Matrix &B, const string &str) const {
string MSG = (str.empty() ? "" : "in ") + str +
(str.empty() ? "" : ", ") +
"matrices must be of same size";
if(this->m != B.m || this->n != B.n)
throw std::invalid_argument(MSG.c_str());
}
void Matrix::ensureNonSingularity(const string &str) const {
string MSG = (str.empty() ? "" : "in ") + str +
(str.empty() ? "" : ", ") +
"matrix is singular";
if(this->isSingular())
throw std::invalid_argument(MSG.c_str());
}
void Matrix::ensureVector(const string &str) const {
string MSG = (str.empty() ? "" : "in ") + str +
(str.empty() ? "" : ", ") +
"matrices must be row or column vectors";
if(this->m != 1 && this->n != 1)
throw std::invalid_argument(MSG.c_str());
}
// =====================================================================
void Matrix::print() const {
cout << endl << ">> Matrix_" << this->m << "X" << this->n
<< " =" << endl;
for(size_t i = 0; i < this->m; i++) {
for(size_t j = 0; j < this->n; j++)
cout << this->elements.at(i*this->n + j) << '\t';
cout << endl;
}
cout << endl;
}
string Matrix::str() const {
string ST = "";
for(size_t i = 0; i < this->m; i++) {
for(size_t j = 0; j < this->n; j++)
ST += my::num2str<double>(this->elements.at(i*this->n + j))
+ ((j == this->n-1) ? '\0' : '\t');
ST += '\n';
}
return ST;
}
ostream& operator<<(ostream &os, const Matrix& M) {
return os << M.str();
}
double& Matrix::at(const size_t &i_) {
this->checkDim(i_,"AT");
return this->elements.at(i_);
}
const double& Matrix::at(const size_t &i_) const {
this->checkDim(i_,"AT");
return this->elements.at(i_);
}
double& Matrix::at(const size_t &i_, const size_t &j_) {
this->checkDim(i_,j_,"AT");
return this->elements.at(i_*(this->n)+j_);
}
const double& Matrix::at(const size_t &i_, const size_t &j_) const {
this->checkDim(i_,j_,"AT");
return this->elements.at(i_*(this->n)+j_);
}
vector<double> Matrix::as_vector() const {
return this->elements;
}
vector<double> Matrix::row(const size_t &r_) const {
this->checkDim(r_,0,"ROW");
vector<double> row_(this->elements.begin()+(r_*this->n),
this->elements.begin()+(r_*this->n+this->n));
return row_;
}
void Matrix::assign2row(const size_t &r_, const double &value) {
this->checkDim(r_,0,"ASSIGN2ROW");
for(size_t i = 0; i < this->n; i++)
this->elements.at(r_*this->n+i) = value;
}
void Matrix::assign2row(const size_t &r_,
const vector<double> &values) {
this->checkDim(r_,0,"ASSIGN2ROW");
this->checkSize(this->n,values.size(),"ASSIGN2ROW");
for(size_t i = 0; i < this->n; i++)
this->elements.at(r_*this->n+i) = values.at(i);
}
void Matrix::assign2row(const size_t &r_, const double *values,
const size_t &sz) {
vector<double> vec(values,values+sz);
this->assign2row(r_,vec);
}
vector<double> Matrix::column(const size_t &c_) const {
this->checkDim(0,c_,"COLUMN");
vector<double> column_(this->m,0.);
for(size_t i = 0; i < this->m; i++)
column_.at(i) = this->elements.at(i*this->n+c_);
return column_;
}
void Matrix::assign2column(const size_t &c_, const double &value) {
this->checkDim(0,c_,"ASSIGN2COLUMN");
for(size_t i = 0; i < this->m; i++)
this->elements.at(i*this->n+c_) = value;
}
void Matrix::assign2column(const size_t &c_,
const vector<double> &values) {
this->checkDim(0,c_,"ASSIGN2COLUMN");
this->checkSize(this->m,values.size(),"ASSIGN2COLUMN");
for(size_t i = 0; i < this->m; i++)
this->elements.at(i*this->n+c_) = values.at(i);
}
void Matrix::assign2column(const size_t &c_, const double *values,
const size_t &sz) {
vector<double> vec(values,values+sz);
this->assign2column(c_,vec);
}
vector<double> Matrix::diagonal() const {
size_t dim = min(this->m,this->n);
vector<double> diag_(dim,0.);
for(size_t i = 0; i < dim; i++)
diag_.at(i) = this->elements.at(i*this->n+i);
return diag_;
}
void Matrix::assign2diagonal(const double &value) {
size_t dim = min(this->m,this->n);
for(size_t i = 0; i < dim; i++)
this->elements.at(i*this->n+i) = value;
}
void Matrix::assign2diagonal(const vector<double> &values) {
size_t dim = min(this->m,this->n);
this->checkSize(dim,values.size(),"ASSIGN2DIAGONAL");
for(size_t i = 0; i < dim; i++)
this->elements.at(i*this->n+i) = values.at(i);
}
void Matrix::assign2diagonal(const double *values, const size_t &sz) {
vector<double> vec(values,values+sz);
this->assign2diagonal(vec);
}
void Matrix::swap_rows(const size_t &r1, const size_t &r2) {
this->checkDim(r1,0,"SWAP_ROW");
this->checkDim(r2,0,"SWAP_ROW");
double aux;
for(size_t j = 0; j < this->n; j++) {
aux = this->elements.at(r1*this->n+j);
this->elements.at(r1*this->n+j) =
this->elements.at(r2*this->n+j);
this->elements.at(r2*this->n+j) = aux;
}
}
void Matrix::swap_columns(const size_t &c1, const size_t &c2) {
this->checkDim(0,c1,"SWAP_COLUMN");
this->checkDim(0,c2,"SWAP_COLUMN");
double aux;
for(size_t i = 0; i < this->m; i++) {
aux = this->elements.at(i*this->n+c1);
this->elements.at(i*this->n+c1) =
this->elements.at(i*this->n+c2);
this->elements.at(i*this->n+c2) = aux;
}
}
void Matrix::self_concat_row(const double &cte) {
Matrix M(this->concat_row(cte));
this->swap(M);
}
void Matrix::self_concat_row(const vector<double> &values) {
Matrix M(this->concat_row(values));
this->swap(M);
}
void Matrix::self_concat_row(const Matrix &B) {
Matrix M(this->concat_row(B));
this->swap(M);
}
void Matrix::self_concat_column(const double &cte) {
Matrix M(this->concat_column(cte));
this->swap(M);
}
void Matrix::self_concat_column(const vector<double> &values) {
Matrix M(this->concat_column(values));
this->swap(M);
}
void Matrix::self_concat_column(const Matrix &B) {
Matrix M(this->concat_column(B));
this->swap(M);
}
void Matrix::self_delete_row(const size_t &r_) {
Matrix M(this->delete_row(r_));
this->swap(M);
}
void Matrix::self_delete_column(const size_t &c_) {
Matrix M(this->delete_column(c_));
this->swap(M);
}
Matrix Matrix::concat_row(const double &cte) const {
vector<double> values(this->n,cte);
return concat_row(values);
}
Matrix Matrix::concat_row(const vector<double> &values) const {
this->checkSize(this->n,values.size(),"CONCAT_ROW");
Matrix M(this->m+1,this->n);
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < M.n; j++)
M.elements.at(i*M.n+j) = this->elements.at(i*this->n+j);
for(size_t j = 0; j < M.n; j++)
M.elements.at(this->m*M.n+j) = values.at(j);
return M;
}
Matrix Matrix::concat_row(const Matrix &B) const {
this->checkSize(this->n,B.n,"CONCAT_ROW");
Matrix M(this->m+B.m,this->n);
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < M.n; j++)
M.elements.at(i*M.n+j) = this->elements.at(i*this->n+j);
for(size_t i = 0; i < B.m; i++)
for(size_t j = 0; j < M.n; j++)
M.elements.at((this->m+i)*M.n+j) =
B.elements.at(i*B.n+j);
return M;
}
Matrix Matrix::concat_column(const double &cte) const {
vector<double> values(this->m,cte);
return concat_column(values);
}
Matrix Matrix::concat_column(const vector<double> &values) const {
this->checkSize(this->m,values.size(),"CONCAT_COLUMN");
Matrix M(this->m,this->n+1);
for(size_t i = 0; i < M.m; i++)
for(size_t j = 0; j < this->n; j++)
M.elements.at(i*M.n+j) = this->elements.at(i*this->n+j);
for(size_t i = 0; i < M.m; i++)
M.elements.at(i*M.n+this->n) = values.at(i);
return M;
}
Matrix Matrix::concat_column(const Matrix &B) const {
this->checkSize(this->m,B.m,"CONCAT_COLUMN");
Matrix M(this->m,this->n+B.n);
for(size_t i = 0; i < M.m; i++)
for(size_t j = 0; j < this->n; j++)
M.elements.at(i*M.n+j) = this->elements.at(i*this->n+j);
for(size_t i = 0; i < M.m; i++)
for(size_t j = 0; j < B.n; j++)
M.elements.at(i*M.n+(this->n+j)) = B.elements.at(i*B.n+j);
return M;
}
Matrix Matrix::delete_row(const size_t &r_) const {
this->checkDim(r_,0,"DELETE_ROW");
Matrix M(this->m-1,this->n);
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
if(i != r_)
M.elements.at(((i<r_)?i:i-1)*M.n+j) =
this->elements.at(i*this->n+j);
return M;
}
Matrix Matrix::delete_column(const size_t &c_) const {
this->checkDim(0,c_,"DELETE_COLUMN");
Matrix M(this->m,this->n-1);
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
if(j != c_)
M.elements.at(i*M.n+((j<c_)?j:j-1)) =
this->elements.at(i*this->n+j);
return M;
}
// ===================================
size_t Matrix::rank() const {
size_t rk = 0;
this->checkSize((this->m)*(this->n),this->elements.size(),"RANK");
lapack_int m = this->m, n = this->n;
lapack_int lda = n, ldu = m, ldvt = n, info;
double *superb = new double[min(m,n)-1];
double *a = new double[m*n],
*s = new double[min(m,n)],
*u = new double[m*m],
*vt = new double[n*n];
for(size_t i = 0; i < this->elements.size(); i ++)
a[i] = this->elements.at(i);
info = LAPACKE_dgesvd( LAPACK_ROW_MAJOR, 'N', 'N', m, n, a, lda,
s, u, ldu, vt, ldvt, superb );
if(info < 0) // Check for invalid (NaN)
this->invalidArgument((int)info,"RANK");
if(info > 0) // Check for convergence
this->badConvergence("RANK");
for(int i = 0; i < min(m,n); i++)
rk += (my::isLikelyZero(s[i],max(this->m,this->n))) ? 0 : 1;
delete [] superb;
delete [] a;
delete [] s;
delete [] u;
delete [] vt;
return rk;
}
double Matrix::determinant() const {
this->ensureSquare("DETERMINANT");
double det;
switch(this->m) {
case 1:
det = this->elements.at(0);
break;
case 2:
det = this->elements.at(0)*this->elements.at(3) -
this->elements.at(1)*this->elements.at(2);
break;
case 3:
det = this->elements.at(0)*this->elements.at(4)*
this->elements.at(8)
+ this->elements.at(1)*this->elements.at(5)*
this->elements.at(6)
+ this->elements.at(2)*this->elements.at(3)*
this->elements.at(7)
- this->elements.at(2)*this->elements.at(4)*
this->elements.at(6)
- this->elements.at(0)*this->elements.at(5)*
this->elements.at(7)
- this->elements.at(1)*this->elements.at(3)*
this->elements.at(8);
break;
default:
det = 0;
for(size_t j = 0; j < this->n; j++)
det += this->cofactor(0,j)*this->elements.at(j); // i=0
}
return det;
}
double Matrix::trace() const {
this->ensureSquare("TRACE");
vector<double> diag(this->diagonal());
double total(0.);
for(vector<double>::iterator it = diag.begin();
it < diag.end(); it++) total += *it;
return total;
}
double Matrix::norm() const {
// for square matrices, this is the same as the "spectral norm",
// the "induced matrix 2-norm" or the "Euclidean norm"
if(this->m != 1 && this->n != 1) {
this->checkSize((this->m)*(this->n),this->elements.size(),
"NORM");
lapack_int m = this->m, n = this->n;
lapack_int lda = n, ldu = m, ldvt = n, info;
double *superb = new double[min(m,n)-1];
double *a = new double[m*n],
*s = new double[min(m,n)],
*u = new double[m*m],
*vt = new double[n*n];
for(size_t i = 0; i < this->elements.size(); i ++)
a[i] = this->elements.at(i);
info = LAPACKE_dgesvd( LAPACK_ROW_MAJOR, 'N', 'N', m, n, a, lda,
s, u, ldu, vt, ldvt, superb );
if(info < 0) // Check for invalid (NaN)
this->invalidArgument((int)info,"NORM");
if(info > 0) // Check for convergence
this->badConvergence("NORM");
double hSingVal = s[0];
for(int i = 1; i < min(m,n); i++)
if(s[i] > hSingVal)
hSingVal = s[i];
delete [] superb;
delete [] a;
delete [] s;
delete [] u;
delete [] vt;
return hSingVal;
} else
return sqrt(((this->m == 1) ? (*this)*(this->transpose()) :
(this->transpose())*(*this)).elements.at(0));
}
double Matrix::infinity_norm() const {
// Maximum absolute row sum norm
double infnorm = 0., sum_;
for(size_t i = 0; i < this->m; i++) {
sum_ = 0.;
for(size_t j = 0; j < this->n; j++)
sum_ += abs(this->elements.at(i*this->n+j));
if(sum_ > infnorm)
infnorm = sum_;
}
return infnorm;
}
double Matrix::frobenius_norm() const {
this->checkSize((this->m)*(this->n),this->elements.size(),
"FRBNORM");
double sum = 0.;
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
sum += pow(this->elements.at(i*this->n+j),2.);
return sqrt(sum);
}
double Matrix::condition_number() const
{
triplet<Matrix> SVD = this->svd();
vector<double> singular_values = SVD.second.diagonal();
return my::max(singular_values)/my::min(singular_values);
}
double Matrix::cofactor(const size_t &r_, const size_t &c_) const {
this->ensureSquare("COFACTOR");
Matrix CF(*this);
CF.self_delete_row(r_);
CF.self_delete_column(c_);
return (((r_+c_)%2)?-1:1)*CF.determinant();
}
Matrix Matrix::transpose() const {
Matrix T(this->n,this->m);
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
T.elements.at(j*this->m+i) = this->elements.at(i*this->n+j);
return T;
}
Matrix Matrix::adjoint() const {
this->ensureSquare("ADJOINT");
Matrix A(this->m,this->n);
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
A.elements.at(i*this->n+j) = cofactor(i,j);
return A.transpose();
}
Matrix Matrix::inverse() const {
this->ensureSquare("INVERSE");
this->ensureNonSingularity("INVERSE");
return this->adjoint()/this->determinant();
}
brace<Matrix> Matrix::eigen() const {
this->checkSize((this->n)*(this->n),this->elements.size(),"EIGEN");
this->ensureSquare("EIGEN");
lapack_int n = this->n, info;
double *a = new double[n*n],
*b = new double[n*n],
*alphar = new double[n],
*alphai = new double[n],
*beta = new double[n],
*vl = new double,
*vr = new double[n*n];
for(size_t i = 0; i < this->elements.size(); i ++) {
a[i] = this->elements.at(i);
b[i] = (i%(n+1) == 0) ? 1. : 0.;
}
info = LAPACKE_dggev( LAPACK_ROW_MAJOR, 'N', 'V', n, a, n, b, n,
alphar, alphai, beta, vl, 1, vr, n );
if(info < 0) // Check for invalid (NaN)
this->invalidArgument((int)info,"EIGEN");
if(info > 0) // Check for convergence
this->badConvergence("EIGEN");
Matrix EVAL(n,n),
EVEC(n,n,vr,n*n);
vector<double> lambda(n,0.);
for(int i = 0; i < n; i++) {
lambda.at(i) = (abs(alphai[i]) <= EPS) ? ((abs(beta[i]) <= EPS)
? NAN : alphar[i]/beta[i] ) : -NAN;
}
EVAL.assign2diagonal(lambda);
delete [] a;
delete [] b;
delete [] alphar;
delete [] alphai;
delete [] beta;
delete vl;
delete [] vr;
return make_brace<Matrix>(EVAL,EVEC);
}
triplet<Matrix> Matrix::lu_p_factorization() const {
lapack_int m = this->m, n = this->n, info;
double *a = new double[m*n];
lapack_int *ipiv = new lapack_int[max(1,min(m,n))];
for(size_t i = 0; i < this->elements.size(); i ++) {
a[i] = this->elements.at(i);
}
info = LAPACKE_dgetrf( LAPACK_ROW_MAJOR, m, n, a, n, ipiv );
if(info < 0) // Check for invalid (NaN)
this->invalidArgument((int)info,"LU_P_FACTORIZATION");
if(info > 0) // Check for convergence
cerr << ">> Warning! Matrix U is singular." << endl;
Matrix L(m,min(m,n)),
U(min(m,n),n),
P(m,m);
vector<double> ones(min(m,n),1.);
L.assign2diagonal(ones);
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
if(j >= i)
U.at(i,j) = a[i*n+j];
else
L.at(i,j) = a[i*n+j];
vector<size_t> seq;
size_t aux;
for(int i = 0; i < m; i++)
seq.push_back(i);
for(int i = 0; i < min(m,n); i++) {
aux = seq.at(i);
seq.at(i) = seq.at(ipiv[i]-1);
seq.at(ipiv[i]-1) = aux;
}
for(int i = 0; i < m; i++)
P.at(i,seq.at(i)) = 1;
delete [] a;
delete [] ipiv;
return make_triplet<Matrix>(L,U,P);
}
brace<Matrix> Matrix::qr_factorization() const {
lapack_int m = this->m, n = this->n, info;
double *a = new double[m*n];
double *tau = new double[max(1,min(m,n))];
for(size_t i = 0; i < this->elements.size(); i ++) {
a[i] = this->elements.at(i);
}
info = LAPACKE_dgeqrf( LAPACK_ROW_MAJOR, m, n, a, n, tau );
if(info < 0) // Check for invalid (NaN)
this->invalidArgument((int)info,"QR_FACTORIZATION");
/* The matrix Q is represented as a product of elementary reflectors
*
* Q = H(1) H(2) . . . H(k), where k = min(m,n).
*
* Each H(i) has the form
*
* H(i) = I - tau * v * v'
*
* where tau is a real scalar, and v is a real vector with
* v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in
* A(i+1:m,i), and tau in TAU(i).*/
Matrix Q(m,min(m,n)),
R(min(m,n),n),
H(identityMatrix(m)),
v(m,1);
vector<double> ones(min(m,n),1.);
Q.assign2diagonal(ones);
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
if(j >= i)
R.at(i,j) = a[i*n+j];
else
Q.at(i,j) = a[i*n+j];
for(int i = 0; i < min(m,n); i++) {
v = column_vector(Q.column(i));
H *= identityMatrix(m)-(v*v.transpose())*tau[i];
}
Q = H;
if(m > n)
for(int i = n; i < m; i++)
Q.self_delete_column(Q.n-1);
delete [] a;
delete [] tau;
return make_brace<Matrix>(Q,R);
}
brace<Matrix> Matrix::lq_factorization() const {
lapack_int m = this->m, n = this->n, info;
double *a = new double[m*n];
double *tau = new double[max(1,min(m,n))];
for(size_t i = 0; i < this->elements.size(); i ++) {
a[i] = this->elements.at(i);
}
info = LAPACKE_dgelqf( LAPACK_ROW_MAJOR, m, n, a, n, tau );
if(info < 0) // Check for invalid (NaN)
this->invalidArgument((int)info,"LQ_FACTORIZATION");
Matrix L(m,min(m,n)),
Q(min(m,n),n),
H(identityMatrix(n)),
v(n,1);
vector<double> ones(min(m,n),1.);
Q.assign2diagonal(ones);
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
if(j <= i)
L.at(i,j) = a[i*n+j];
else
Q.at(i,j) = a[i*n+j];
for(int i = 0; i < min(m,n); i++) {
v = row_vector(Q.row(i));
H *= identityMatrix(n)-(v.transpose()*v)*tau[i];
}
Q = H.transpose();
if(m < n)
for(int i = m; i < n; i++)
Q.self_delete_row(Q.m-1);
delete [] a;
delete [] tau;
return make_brace<Matrix>(L,Q);
}
triplet<Matrix> Matrix::svd() const {
this->checkSize((this->m)*(this->n),this->elements.size(),"SVD");
lapack_int m = this->m, n = this->n;
lapack_int lda = n, ldu = m, ldvt = n, info;
double *superb = new double[min(m,n)-1];
double *a = new double[m*n],
*s = new double[min(m,n)],
*u = new double[m*m],
*vt = new double[n*n];
for(size_t i = 0; i < this->elements.size(); i ++)
a[i] = this->elements.at(i);
info = LAPACKE_dgesvd( LAPACK_ROW_MAJOR, 'A', 'A', m, n, a, lda,
s, u, ldu, vt, ldvt, superb );
if(info < 0) // Check for invalid (NaN)
this->invalidArgument((int)info,"SVD");
if(info > 0) // Check for convergence
this->badConvergence("SVD");
// Adjust zeros
for(size_t i = 0; i < min(this->m,this->n); i++)
if(my::isLikelyZero(s[i],max(this->m,this->n)))
s[i] = 0.;
for(int i = 0; i < m*m; i++)
if(my::isLikelyZero(u[i],max(this->m,this->n)))
u[i] = 0.;
for(int i = 0; i < n*n; i++)
if(my::isLikelyZero(vt[i],max(this->m,this->n)))
vt[i] = 0.;
// Create matrices
Matrix S(m,n),
U(m,m,u,m*m),
VT(n,n,vt,n*n);
S.assign2diagonal(s,min(m,n));
delete [] superb;
delete [] a;
delete [] s;
delete [] u;
delete [] vt;
// Return matrices U, Sigma and V
// To retrieve original matrix: U*Sigma*V.transpose()
return make_triplet<Matrix>(U,S,VT.transpose());
}
Matrix Matrix::pseudoinverse() const {
triplet<Matrix> SVD = this->svd();
vector<double> sv = SVD.second.diagonal();
double maxsv = 0;
for(size_t i = 0; i < sv.size(); i++)
if(maxsv < sv.at(i))
maxsv = sv.at(i);
for(size_t i = 0; i < sv.size(); i++) {
if(sv.at(i) <= this->m*this->n*EPS)
sv.at(i) = 0.;
else
sv.at(i) = 1./sv.at(i);
}
SVD.second.assign2diagonal(sv);
return (SVD.first*SVD.second*SVD.third.transpose()).transpose();
}
// =========
double Matrix::min_all(const bool &absolute) const
{
double minelem = (absolute)? abs(this->elements.front()) :
this->elements.front();
for(size_t i = 1; i < this->elements.size(); i++)
if((absolute)? abs(this->elements.at(i)) < minelem :
this->elements.at(i) < minelem)
minelem = (absolute)? abs(this->elements.at(i)) :
this->elements.at(i);
return minelem;
}
double Matrix::max_all(const bool &absolute) const
{
double maxelem = (absolute)? abs(this->elements.front()) :
this->elements.front();
for(size_t i = 1; i < this->elements.size(); i++)
if((absolute)? abs(this->elements.at(i)) > maxelem :
this->elements.at(i) > maxelem)
maxelem = (absolute)? abs(this->elements.at(i)) :
this->elements.at(i);
return maxelem;
}
// =========
Matrix Matrix::operator+(const double &value) const {
Matrix A(*this);
A += value;
return A;
}
void Matrix::operator+=(const double &value) {
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
this->elements.at(i*this->n+j) += value;
}
Matrix Matrix::operator-(const double &value) const {
Matrix A(*this);
A -= value;
return A;
}
void Matrix::operator-=(const double &value) {
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
this->elements.at(i*this->n+j) -= value;
}
Matrix Matrix::operator*(const double &value) const {
Matrix A(*this);
A *= value;
return A;
}
void Matrix::operator*=(const double &value) {
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
this->elements.at(i*this->n+j) *= value;
}
Matrix Matrix::operator/(const double &value) const {
Matrix A(*this);
A /= value;
return A;
}
void Matrix::operator/=(const double &value) {
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
this->elements.at(i*this->n+j) /= value;
}
Matrix Matrix::operator+(const Matrix &B) const {
Matrix A(*this);
A += B;
return A;
}
void Matrix::operator+=(const Matrix &B) {
this->ensureSameSize(B,"OPERATOR+");
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
this->elements.at(i*this->n+j) += B.elements.
at(i*this->n+j);
}
Matrix Matrix::operator-(const Matrix &B) const {
Matrix A(*this);
A -= B;
return A;
}
void Matrix::operator-=(const Matrix &B) {
this->ensureSameSize(B,"OPERATOR-");
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
this->elements.at(i*this->n+j) -= B.elements.
at(i*this->n+j);
}
Matrix Matrix::operator*(const Matrix &B) const {
this->checkSize(this->n,B.m,"OPERATOR*");
Matrix R(this->m,B.n);
for(size_t i = 0; i < this->m; i++)
for(size_t j = 0; j < this->n; j++)
for(size_t k = 0; k < B.n; k++) {
R.elements.at(i*B.n+k) += this->elements.
at(i*this->n+j)*B.elements.at(j*B.n+k);
if(abs(R.elements.at(i*B.n+k)) <= this->m*EPS)
R.elements.at(i*B.n+k) = 0.;
}
return R;
}
void Matrix::operator*=(const Matrix &B) {
Matrix A = (*this)*B;
this->swap(A);
}
bool Matrix::operator==(const Matrix &B) const {
if(this->m != B.m || this->n != B.n)
return false;
else {
bool chk = true;
for(size_t i = 0; i < this->m; i++) {
for(size_t j = 0; j < this->n; j++) {
if(abs(this->elements.at(i*this->n+j)-
B.elements.at(i*B.n+j)) > 0.5*EPS) {
chk = false;
break;
}
}
if(!chk) break;
}
return chk;
}
}
bool Matrix::operator!=(const Matrix &B) const {
return !((*this) == B);
}
// ======
Matrix operator+(const double &lhs, const Matrix &rhs) {
return rhs+lhs;
}
Matrix operator-(const double &lhs, const Matrix &rhs) {
return rhs*(-1.)+lhs;
}
Matrix operator*(const double &lhs, const Matrix &rhs) {
return rhs*lhs;
}
Matrix operator/(const double &lhs, const Matrix &rhs) {
// This is not an inverse! It's an element-wise division
Matrix result(rhs);
for(size_t i = 0; i < result.m; i++)
for(size_t j = 0; j < result.n; j++)
result.at(i,j) = lhs/result.at(i,j);
return result;
}
// ======
bool Matrix::isFullRank() const {
return this->rank() == min(this->m,this->n);
}
bool Matrix::isOrthogonal() const {
Matrix O = (*this)*(this->transpose());
return (O == identityMatrix(O.m));
}
bool Matrix::isDiagonal() const {
Matrix D = diagonalMatrix(this->diagonal());
if(this->m != this->n) {
if(this->m > this->n) {
vector<double> zeros(this->n,0.);
for(size_t i = this->n; i < this->m; i++)
D.self_concat_row(zeros);
} else {
vector<double> zeros(this->m,0.);
for(size_t i = this->m; i < this->n; i++)
D.self_concat_column(zeros);
}
}
return (*this == D);
}
bool Matrix::isPositiveDefinite() const {
//real symmetric matrix
if(!(this->isSymmetric()))
return false;
else {
// if all its eigenvalues are positive.
cout << "not implemented yet!" << endl;
return false;
}
}
bool Matrix::isSingular() const {
return (my::isLikelyZero(this->determinant()));
}
bool Matrix::isSymmetric() const {
return (*this == this->transpose());
}
bool Matrix::isSkewSymmetric() const {
return (*this == this->transpose()*(-1.));
}
bool Matrix::isValid() const {
bool chk = true;
for(vector<double>::const_iterator it = this->elements.begin();
it != this->elements.end(); it++)
{
if(std::isnan(*it) || my::isinf(*it))
{
chk = false;
break;
}
}
return chk;
}
void Matrix::adjust_elements(const double &tol)
{
for(size_t i = 0; i < this->elements.size(); i++)
if(my::isLikelyZero(this->elements.at(i),this->m*this->n) ||
abs(this->elements.at(i)) < tol)
this->elements.at(i) = 0.;
}
void Matrix::saveAs(const string &namefile) const
{
ofstream matrixfile;
matrixfile.open(namefile);
if (matrixfile.is_open())
{
for(size_t i = 0; i < this->m; i++)
{
for(size_t j = 0; j < this->n; j++)
matrixfile << this->elements.at(i*(this->n)+j)
<< ((j+1 == this->n) ? "" : "\t");
matrixfile << endl;
}
}
else
{
cerr << "Unable to open " << namefile << " file!" << endl;
}
matrixfile.close();
}
// =====================================================================
Matrix column_vector(const vector<double> &vec) {
Matrix A(vec.size(),1,vec);
return A;
}
Matrix column_vector(const size_t &qty, const double &val) {
vector<double> vec(qty,val);
Matrix A(qty,1,vec);
return A;
}
Matrix row_vector(const vector<double> &vec) {
Matrix A(1,vec.size(),vec);
return A;
}
Matrix row_vector(const size_t &qty, const double &val) {
vector<double> vec(qty,val);
Matrix A(1,qty,vec);
return A;
}
Matrix subMatrix(const Matrix &M, const size_t &fstr,
const size_t &fstc, const size_t &lstr, const size_t &lstc) {
cout << "row: " << fstr << " " << lstr << endl;
cout << "col: " << fstc << " " << lstc << endl;
cout << "M: " << M.m << " " << M.n << endl;
if(fstr > lstr || lstr >= M.m || fstc > lstc || lstc >= M.n) {
string MSG = "in SUBMATRIX, index exceeds matrix dimension";
throw std::out_of_range(MSG.c_str());
}
Matrix A(lstr-fstr+1,lstc-fstc+1);
cout << A.m << " " << A.n << endl;
for(size_t i = 0; i < A.m; i++)
for(size_t j = 0; j < A.n; j++)
A.at(i,j) = M.at(i+fstr,j+fstc);
return A;
}
Matrix identityMatrix(const size_t &N) {
Matrix A(N,N);
A.assign2diagonal(1.);
return A;
}
Matrix diagonalMatrix(const vector<double> &vec) {
Matrix A(vec.size(),vec.size());
A.assign2diagonal(vec);
return A;
}
Matrix linear_AASTtoRowVector_VAR(const AAST &tree, const size_t &n_var)
{
Matrix A, b(n_var, 1);
vector<double> aux(n_var, 0.);
double cnst = tree.eval_with_variables(aux);
aux.at(0) = 1.;
A = row_vector(aux);
b.at(0) = tree.eval_with_variables(aux) - cnst;
for(size_t i = 1; i < n_var; i++)
{
aux.assign(n_var, 0.);
aux.at(i) = 1.;
A.self_concat_row(row_vector(aux));
b.at(i) = tree.eval_with_variables(aux) - cnst;
}
return ((A.pseudoinverse()*b).transpose()).concat_column(cnst);
}
Matrix linear_AASTtoRowVector_UNK(const AAST &tree, const size_t &n_unk)
{
Matrix A, b(n_unk, 1);
vector<double> aux(n_unk, 0.);
double cnst = tree.eval_with_unknowns(aux);
aux.at(0) = 1.;
A = row_vector(aux);
b.at(0) = tree.eval_with_unknowns(aux) - cnst;
for(size_t i = 1; i < n_unk; i++)
{
aux.assign(n_unk, 0.);
aux.at(i) = 1.;
A.self_concat_row(row_vector(aux));
b.at(i) = tree.eval_with_unknowns(aux) - cnst;
}
return ((A.pseudoinverse()*b).transpose()).concat_column(cnst);
}
// =====================================================================
#endif
| {
"alphanum_fraction": 0.6131388858,
"avg_line_length": 28.6650980392,
"ext": "h",
"hexsha": "6e39a15043b1c4db644bb6621f8d601960348d59",
"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": "e99c12019c7b8730ab478e5ca5c956fca36371ee",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "iperetta/system-modelling",
"max_forks_repo_path": "cMatrix.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e99c12019c7b8730ab478e5ca5c956fca36371ee",
"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": "iperetta/system-modelling",
"max_issues_repo_path": "cMatrix.h",
"max_line_length": 73,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e99c12019c7b8730ab478e5ca5c956fca36371ee",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "iperetta/system-modelling",
"max_stars_repo_path": "cMatrix.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 11383,
"size": 36548
} |
//
// mclib_pluto.c
// to read in pluto AMR chombo files
//
// Created by Tyler Parsotan on 11/26/19.
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <dirent.h>
#include <limits.h>
#include "hdf5.h"
#include <math.h>
#include <time.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_sf_bessel.h>
#include "mclib.h"
#include <omp.h>
void readPlutoChombo( char pluto_file[200], double r_inj, double fps, double **x, double **y, double **szx, double **szy, double **r,\
double **theta, double **velx, double **vely, double **dens, double **pres, double **gamma, double **dens_lab, double **temp, int *number, int ph_inj_switch, double min_r, double max_r, double min_theta, double max_theta, FILE *fPtr)
{
hid_t file, dset, space, group, attr;
herr_t status;
hsize_t dims[1]={0}; //hold number of processes in each level
int i=0, j=0, k=0, l=0, m=0, r_count=0, num_dims=0, num_levels=0, num_vars=4, logr=0;
int nbx=0, nby=0, nbz=0, total_size=0, total_box_size=0, offset=0, elem_factor=0;
box2d prob_domain[1]={0,0,0,0};
char level[200]="";
double ph_rmin=0, ph_rmax=0, ph_thetamin=0, ph_thetamax=0, r_grid_innercorner=0, r_grid_outercorner=0, theta_grid_innercorner=0, theta_grid_outercorner=0;
int *level_dims=NULL, *box_offset=NULL;
double *radii=NULL, *angles=NULL, *dradii=NULL, *dangles=NULL;
double *dombeg1=NULL, *dombeg2=NULL, *dombeg3=NULL, *dx=NULL, *g_x2stretch=NULL, *g_x3stretch=NULL;
double *all_data=NULL, *x1_buffer=NULL, *x2_buffer=NULL, *dx1_buffer=NULL, *dx2_buffer=NULL;
double *dens_buffer=NULL, *pres_buffer=NULL, *vel_x2_buffer=NULL, *vel_x1_buffer=NULL;
if (ph_inj_switch==0)
{
ph_rmin=min_r;
ph_rmax=max_r;
ph_thetamin=min_theta-2*0.017453292519943295; //min_theta - 2*Pi/180 (2 degrees)
ph_thetamax=max_theta+2*0.017453292519943295; //max_theta + 2*Pi/180 (2 degrees)
}
//define dataset for boxes of each level
hid_t box_dtype = H5Tcreate (H5T_COMPOUND, sizeof(box2d));
H5Tinsert(box_dtype, "lo_i", HOFFSET(box2d, lo_i), H5T_NATIVE_INT);
H5Tinsert(box_dtype, "lo_j", HOFFSET(box2d, lo_j), H5T_NATIVE_INT);
H5Tinsert(box_dtype, "hi_i", HOFFSET(box2d, hi_i), H5T_NATIVE_INT);
H5Tinsert(box_dtype, "hi_j", HOFFSET(box2d, hi_j), H5T_NATIVE_INT);
//open the pluto file
file = H5Fopen (pluto_file, H5F_ACC_RDONLY, H5P_DEFAULT);
fprintf(fPtr, ">> MCRaT: Reading positional, density, pressure, and velocity information...\n");
fflush(fPtr);
//1. read in the number of dims
group = H5Gopen (file, "/Chombo_global", H5P_DEFAULT);
attr = H5Aopen (group, "SpaceDim", H5P_DEFAULT);
status = H5Aread (attr, H5T_NATIVE_INT, &num_dims);
status = H5Aclose (attr);
status = H5Gclose (group);
//printf("readPlutoChombo spacedim: %d\n", num_dims);
//2. get the number of levels
attr = H5Aopen (file, "num_levels", H5P_DEFAULT);
status = H5Aread (attr, H5T_NATIVE_INT, &num_levels);
status = H5Aclose (attr);
//printf("readPlutoChombo num_levels: %d\n", num_levels);
dombeg1=malloc(num_levels*sizeof(double));
dombeg2=malloc(num_levels*sizeof(double));
dombeg3=malloc(num_levels*sizeof(double));
dx=malloc(num_levels*sizeof(double));
g_x2stretch=malloc(num_levels*sizeof(double));
g_x3stretch=malloc(num_levels*sizeof(double));
level_dims=malloc(num_levels*sizeof(int));
//3. get number of variables to read in (should be 4 in non-MHD case)
attr = H5Aopen (file, "num_components", H5P_DEFAULT);
status = H5Aread (attr, H5T_NATIVE_INT, &num_vars);
status = H5Aclose (attr);
//printf("readPlutoChombo num_vars: %d\n", num_vars);
//get the total number of values that I need to allocate memory for
for (i=0;i<num_levels;i++)
{
snprintf(level, sizeof(level), "level_%d", i);
//printf("Opening level %d Boxes\n", i);
group = H5Gopen(file, level, H5P_DEFAULT);
dset= H5Dopen(group, "data:datatype=0", H5P_DEFAULT);
//get dimensions of array and save it
space = H5Dget_space (dset);
H5Sget_simple_extent_dims(space, dims, NULL); //save dimesnions in dims
total_size+=dims[0];
*(level_dims+i)=dims[0];
status = H5Sclose (space);
H5Dclose(dset);
H5Gclose(group);
}
//printf("The total number of elements is %d\n", total_size);
//now allocate space to save data
all_data=malloc(total_size*sizeof (double));
//and allocate arrays to hold r and theta values to calculate them on the fly
x1_buffer=malloc((total_size/num_vars)*sizeof (double));
x2_buffer=malloc((total_size/num_vars)*sizeof (double));
dx1_buffer=malloc((total_size/num_vars)*sizeof (double));
dx2_buffer=malloc((total_size/num_vars)*sizeof (double));
vel_x1_buffer= malloc ((total_size/num_vars) * sizeof (double));
vel_x2_buffer=malloc ((total_size/num_vars) * sizeof (double));
dens_buffer= malloc ((total_size/num_vars) * sizeof (double));
pres_buffer=malloc ((total_size/num_vars) * sizeof (double));
offset=0;
//read in the data
for (i=0;i<num_levels;i++)
{
snprintf(level, sizeof(level), "level_%d", i);
//printf("Opening level %d Boxes\n", i);
group = H5Gopen(file, level, H5P_DEFAULT);
//read in the data
dset= H5Dopen(group, "data:datatype=0", H5P_DEFAULT);
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,(all_data+offset));
H5Dclose(dset);
//printf("First few data %e %e %e Last few data %e %e\n", *(all_data+offset), *(all_data+offset+1), *(all_data+offset+2), *(all_data+offset+(*(level_dims+i))-2), *(all_data+offset+(*(level_dims+i))-1));
//read in the box offsets in all_data
dset= H5Dopen(group, "data:offsets=0", H5P_DEFAULT);
space = H5Dget_space (dset);
H5Sget_simple_extent_dims(space, dims, NULL); //save dimesnions in dims
box_offset=malloc(dims[0]*sizeof(int));
status = H5Sclose (space);
status = H5Dread (dset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, box_offset);
H5Dclose(dset);
//open various properties about that refinement level
attr = H5Aopen (group, "prob_domain", H5P_DEFAULT);
status = H5Aread (attr, box_dtype, &prob_domain);
status = H5Aclose (attr);
//printf("Prob_domain %d %d %d %d\n", prob_domain->lo_i, prob_domain->lo_j, prob_domain->hi_i, prob_domain->hi_j);
attr = H5Aopen (group, "dx", H5P_DEFAULT);
status = H5Aread (attr, H5T_NATIVE_DOUBLE, (dx+i));
status = H5Aclose (attr);
//printf("dx %e\n", *(dx+i));
attr = H5Aopen (group, "logr", H5P_DEFAULT);
status = H5Aread (attr, H5T_NATIVE_INT, &logr);
status = H5Aclose (attr);
//printf("logr %d\n", logr);
attr = H5Aopen (group, "domBeg1", H5P_DEFAULT);
status = H5Aread (attr, H5T_NATIVE_DOUBLE, (dombeg1+i));
status = H5Aclose (attr);
//printf("dombeg1 %e\n", *(dombeg1+i));
//set default just in case
*(dombeg2+i)=0;
*(dombeg3+i)=0;
if (num_dims==2)
{
attr = H5Aopen (group, "g_x2stretch", H5P_DEFAULT);
status = H5Aread (attr, H5T_NATIVE_DOUBLE, (g_x2stretch+i));
status = H5Aclose (attr);
//printf("g_x2stretch %e\n", *(g_x2stretch+i));
attr = H5Aopen (group, "domBeg2", H5P_DEFAULT);
status = H5Aread (attr, H5T_NATIVE_DOUBLE, (dombeg2+i));
status = H5Aclose (attr);
//printf("dombeg2 %e\n", *(dombeg2+i));
}
else if (num_dims==3)
{
attr = H5Aopen (group, "g_x3stretch", H5P_DEFAULT);
status = H5Aread (attr, H5T_NATIVE_DOUBLE, (g_x3stretch+i));
status = H5Aclose (attr);
attr = H5Aopen (group, "domBeg3", H5P_DEFAULT);
status = H5Aread (attr, H5T_NATIVE_DOUBLE, (dombeg3+i));
status = H5Aclose (attr);
}
//read in the boxes
dset= H5Dopen(group, "boxes", H5P_DEFAULT);
//get dimensions of array and save it
space = H5Dget_space (dset);
H5Sget_simple_extent_dims(space, dims, NULL); //save dimesnions in dims
box2d box_data[dims[0]];
status = H5Dread (dset, box_dtype, H5S_ALL, H5S_ALL, H5P_DEFAULT,box_data);
status = H5Sclose (space);
H5Dclose(dset);
radii=malloc( (prob_domain->hi_i - prob_domain->lo_i +1) * sizeof (double ));
angles=malloc( (prob_domain->hi_j - prob_domain->lo_j +1) * sizeof (double ));
dradii=malloc( (prob_domain->hi_i - prob_domain->lo_i +1) * sizeof (double ));
dangles=malloc( (prob_domain->hi_j - prob_domain->lo_j +1) * sizeof (double ));
//create the arrays that hold the refinement level radii and angles
for (j=0;j<(prob_domain->hi_i - prob_domain->lo_i +1);j++)
{
if (logr==0)
{
*(radii+j)=(*(dombeg1+i)) + (*(dx+i)) * (prob_domain->lo_i + j + 0.5);
*(dradii+j)=(*(dx+i));
}
else
{
*(radii+j)=(*(dombeg1+i)) * 0.5 * (exp((*(dx+i)) * (prob_domain->lo_i + j + 1)) + exp((*(dx+i)) * (prob_domain->lo_i + j)) );
*(dradii+j)=(*(dombeg1+i)) * (exp((*(dx+i)) * (prob_domain->lo_i + j + 1)) - exp((*(dx+i)) * (prob_domain->lo_i + j)) );
}
//if (i==2) printf("radii: %0.8e dr: %0.8e\n", *(radii+j), *(dradii+j));
}
for (j=0;j<(prob_domain->hi_j - prob_domain->lo_j +1);j++)
{
*(angles+j)=(*(dombeg2+i)) + (*(dx+i)) * (*(g_x2stretch+i)) * (prob_domain->lo_j + j + 0.5);
*(dangles+j)=(*(dx+i))*(*(g_x2stretch+i));
}
//go through the boxes to create the r and theta arrays
total_box_size=0;
for (j=0; j<dims[0]; j++)
{
//printf("i %d %d %d %d %d \n", j, box_data[j].lo_i, box_data[j].lo_j, box_data[j].hi_i, box_data[j].hi_j);
nbx=box_data[j].hi_i-box_data[j].lo_i+1;
nby=1;
nbz=1;
if (num_dims >1)
{
nby=box_data[j].hi_j-box_data[j].lo_j+1;
}
/* for future 3D support
else if (dim>2)
{
nbz=box_data[j].hi_k-box_data[j].lo_k+1;
}
*/
//loop over each variable values of box
for (k=0;k<num_vars;k++)
{
//loop over the radii
for (l=0; l<nby; l++)
{
//loop over the angles
for (m=0 ;m<nbx ;m++)
{
switch (k)
{
case 0:
//when k is 0 save the radii, caus eonly need to do once and also save the densities
#if GEOMETRY == SPHERICAL
*(x1_buffer+offset/num_vars+(*(box_offset+j))/num_vars+ l*nbx +m )= (*(radii+box_data[j].lo_i+m))*HYDRO_L_SCALE;
*(x2_buffer+(offset+(*(box_offset+j)))/num_vars + l*nbx +m )=(*(angles+box_data[j].lo_j+l));
*(dx1_buffer+(offset+(*(box_offset+j)))/num_vars + l*nbx +m)=(*(dradii+box_data[j].lo_i+m))*HYDRO_L_SCALE;
*(dx2_buffer+ (offset+(*(box_offset+j)))/num_vars + l*nbx +m )=(*(dangles+box_data[j].lo_j+l));
#elif GEOMETRY == CARTESIAN
*(x1_buffer+offset/num_vars+(*(box_offset+j))/num_vars+ l*nbx +m )= (*(radii+box_data[j].lo_i+m))*HYDRO_L_SCALE;
*(x2_buffer+(offset+(*(box_offset+j)))/num_vars + l*nbx +m )=(*(angles+box_data[j].lo_j+l))*HYDRO_L_SCALE;
*(dx1_buffer+(offset+(*(box_offset+j)))/num_vars + l*nbx +m)=(*(dradii+box_data[j].lo_i+m))*HYDRO_L_SCALE;
*(dx2_buffer+ (offset+(*(box_offset+j)))/num_vars + l*nbx +m )=(*(dangles+box_data[j].lo_j+l))*HYDRO_L_SCALE;
#endif
*(dens_buffer+ (offset+(*(box_offset+j)))/num_vars + l*nbx +m)=(*(all_data+offset+(*(box_offset+j))+ k*nbx*nby + l*nbx +m ));
break;
case 1:
*(vel_x1_buffer+ (offset+(*(box_offset+j)))/num_vars + l*nbx +m)=(*(all_data+offset+(*(box_offset+j))+ k*nbx*nby + l*nbx +m ));
break;
case 2:
*(vel_x2_buffer+ (offset+(*(box_offset+j)))/num_vars + l*nbx +m)=(*(all_data+offset+(*(box_offset+j))+ k*nbx*nby + l*nbx +m ));
break;
case 3:
*(pres_buffer+ (offset+(*(box_offset+j)))/num_vars + l*nbx +m)=(*(all_data+offset+(*(box_offset+j))+ k*nbx*nby + l*nbx +m ));
break;
default:
break;
}
}
}
}
/*
// this was for testing, the actual nested loop is below
if (i==2 && j==dims[0]-1)
{
r_count=0;
for (k=0;k<1;k++)
{
//loop over the radii
for (l=0; l<nby; l++)
{
//loop over the angles
for (m=0 ;m<nbx ;m++)
{
printf("count: %d idx: %d all_data val: %0.8e r: %e theta %e\n", (*(box_offset+j))+r_count, (*(box_offset+j))+k*nbx*nby + l*nby +m, *(all_data+offset+(*(box_offset+j))+ k*nbx*nby + l*nbx +m ), *(radii+box_data[j].lo_i+m), *(angles+box_data[j].lo_j+l));
r_count++;
}
printf("\n");
}
printf("\n");
}
for (k=0;k<64;k++)
{
printf("r: %e, theta %e dens data: %e\n",*(x1_buffer+ (offset+(*(box_offset+j)))/num_vars+k), *(x2_buffer+ (offset+(*(box_offset+j)))/num_vars +k), *(dens_buffer+ (offset+(*(box_offset+j)))/num_vars +k) );
}
printf("\n");
}
*/
}
offset+=(*(level_dims+i));
H5Gclose(group);
free(radii); free(angles); free(dradii); free(dangles); free(box_offset);
}
status = H5Fclose (file);
free(dombeg1); free(dombeg2); free(dombeg3); free(dx); free(g_x2stretch); free(g_x3stretch); free(all_data);
//have all the data so need to go through and decide which values we will be keeping based on phtoon ranges we want to keep
//fill in radius array and find in how many places r > injection radius
#if SYNCHROTRON_SWITCH == ON
elem_factor=2;
#else
elem_factor=0;
#endif
r_count=0;
while (r_count==0)
{
r_count=0;
elem_factor++;
for (i=0;i<(total_size/num_vars);i++)
{
if (ph_inj_switch==0)
{
#if GEOMETRY == SPHERICAL
r_grid_innercorner = (*(x1_buffer+i)) - 0.5 * (*(dx1_buffer+i));
r_grid_outercorner = (*(x1_buffer+i)) + 0.5 * (*(dx1_buffer+i));
theta_grid_innercorner = (*(x2_buffer+i)) - 0.5 * (*(dx2_buffer+i));
theta_grid_outercorner = (*(x2_buffer+i)) + 0.5 * (*(dx2_buffer+i));
#elif GEOMETRY == CARTESIAN
r_grid_innercorner = pow((*(x1_buffer+i) - *(dx1_buffer+i)/2.0) * ((*(x1_buffer+i) - *(dx1_buffer+i)/2.0))+(*(x2_buffer+i) - *(dx2_buffer+i)/2.0) * (*(x2_buffer+i) - *(dx2_buffer+i)/2.0),0.5);
r_grid_outercorner = pow((*(x1_buffer+i) + *(dx1_buffer+i)/2.0) * ((*(x1_buffer+i) + *(dx1_buffer+i)/2.0))+(*(x2_buffer+i) + *(dx2_buffer+i)/2.0) * (*(x2_buffer+i) + *(dx2_buffer+i)/2.0),0.5);
theta_grid_innercorner = acos( (*(x2_buffer+i) - *(dx2_buffer+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner
theta_grid_outercorner = acos( (*(x2_buffer+i) + *(dx2_buffer+i)/2.0) /r_grid_outercorner);
#endif
if (((ph_rmin - elem_factor*C_LIGHT/fps) <= r_grid_outercorner) && (r_grid_innercorner <= (ph_rmax + elem_factor*C_LIGHT/fps) ) && (theta_grid_outercorner >= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax) )
{
r_count++;
}
}
else
{
if ((*(x1_buffer+i)) > (0.95*r_inj) )
{
r_count++;
}
}
}
//printf( "r_count: %d\n", r_count);
}
fprintf(fPtr, "Elem factor: %d Ph_rmin: %e rmax: %e Chosen FLASH min_r: %e max_r: %e min_theta: %e degrees max_theta: %e degrees\n", elem_factor, ph_rmin, ph_rmax, ph_rmin - (elem_factor*C_LIGHT/fps), ph_rmax + (elem_factor*C_LIGHT/fps), ph_thetamin*180/M_PI, ph_thetamax*180/M_PI);
fflush(fPtr);
//allocate memory to hold processed data
(*pres)=malloc (r_count * sizeof (double ));
(*velx)=malloc (r_count * sizeof (double ));
(*vely)=malloc (r_count * sizeof (double ));
(*dens)=malloc (r_count * sizeof (double ));
(*x)=malloc (r_count * sizeof (double ));
(*y)=malloc (r_count * sizeof (double ));
(*r)=malloc (r_count * sizeof (double ));
(*theta)=malloc (r_count * sizeof (double ));
(*gamma)=malloc (r_count * sizeof (double ));
(*dens_lab)=malloc (r_count * sizeof (double ));
(*szx)=malloc (r_count * sizeof (double ));
(*szy)=malloc (r_count * sizeof (double ));
(*temp)=malloc (r_count * sizeof (double ));
//assign values based on r> 0.95*r_inj
j=0;
for (i=0;i<(total_size/num_vars);i++)
{
if (ph_inj_switch==0)
{
#if GEOMETRY == SPHERICAL
r_grid_innercorner = (*(x1_buffer+i)) - 0.5 * (*(dx1_buffer+i));
r_grid_outercorner = (*(x1_buffer+i)) + 0.5 * (*(dx1_buffer+i));
theta_grid_innercorner = (*(x2_buffer+i)) - 0.5 * (*(dx2_buffer+i));
theta_grid_outercorner = (*(x2_buffer+i)) + 0.5 * (*(dx2_buffer+i));
#elif GEOMETRY == CARTESIAN
r_grid_innercorner = pow((*(x1_buffer+i) - *(dx1_buffer+i)/2.0) * ((*(x1_buffer+i) - *(dx1_buffer+i)/2.0))+(*(x2_buffer+i) - *(dx2_buffer+i)/2.0) * (*(x2_buffer+i) - *(dx2_buffer+i)/2.0),0.5);
r_grid_outercorner = pow((*(x1_buffer+i) + *(dx1_buffer+i)/2.0) * ((*(x1_buffer+i) + *(dx1_buffer+i)/2.0))+(*(x2_buffer+i) + *(dx2_buffer+i)/2.0) * (*(x2_buffer+i) + *(dx2_buffer+i)/2.0),0.5);
theta_grid_innercorner = acos( (*(x2_buffer+i) - *(dx2_buffer+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner
theta_grid_outercorner = acos( (*(x2_buffer+i) + *(dx2_buffer+i)/2.0) /r_grid_outercorner);
#endif
if (((ph_rmin - elem_factor*C_LIGHT/fps) <= r_grid_outercorner) && (r_grid_innercorner <= (ph_rmax + elem_factor*C_LIGHT/fps) ) && (theta_grid_outercorner >= ph_thetamin) && (theta_grid_innercorner <= ph_thetamax))
{
(*pres)[j]=(*(pres_buffer+i));
(*velx)[j]= (*(vel_x1_buffer+i))*sin((*(x2_buffer+i))) + (*(vel_x2_buffer+i))*cos((*(x2_buffer+i))) ; //convert from spherical to cartesian
(*vely)[j]= (*(vel_x1_buffer+i))*cos((*(x2_buffer+i))) - (*(vel_x2_buffer+i))*sin((*(x2_buffer+i))); //z axis is actually y axis in 2D
(*dens)[j]=(*(dens_buffer+i));
(*x)[j]=(*(x1_buffer+i))*sin((*(x2_buffer+i)));
(*y)[j]=(*(x1_buffer+i))*cos((*(x2_buffer+i)));
(*r)[j]=(*(x1_buffer+i));
(*szx)[j]=(*(dx1_buffer+i));
(*szy)[j]=(*(dx2_buffer+i));
(*theta)[j]=(*(x2_buffer+i));//theta in radians in relation to jet axis
(*gamma)[j]=1/pow(1.0-( (*(vel_x1_buffer+i))*(*(vel_x1_buffer+i)) + (*(vel_x2_buffer+i))*(*(vel_x2_buffer+i)) ),0.5); //v is in units of c
(*dens_lab)[j]= (*(dens_buffer+i)) /pow(1.0-( (*(vel_x1_buffer+i))*(*(vel_x1_buffer+i)) + (*(vel_x2_buffer+i))*(*(vel_x2_buffer+i)) ),0.5);
(*temp)[j]=pow(3*(*(pres_buffer+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
j++;
}
}
else
{
if ((*(x1_buffer+i)) > (0.95*r_inj) )
{
(*pres)[j]=(*(pres_buffer+i));
(*velx)[j]= (*(vel_x1_buffer+i))*sin((*(x2_buffer+i))) + (*(vel_x2_buffer+i))*cos((*(x2_buffer+i))) ; //convert from spherical to cartesian
(*vely)[j]= (*(vel_x1_buffer+i))*cos((*(x2_buffer+i))) - (*(vel_x2_buffer+i))*sin((*(x2_buffer+i))); //z axis is actually y axis in 2D
(*dens)[j]=(*(dens_buffer+i));
(*x)[j]=(*(x1_buffer+i))*sin((*(x2_buffer+i)));
(*y)[j]=(*(x1_buffer+i))*cos((*(x2_buffer+i)));
(*r)[j]=(*(x1_buffer+i));
(*szx)[j]=(*(dx1_buffer+i));
(*szy)[j]=(*(dx2_buffer+i));
(*theta)[j]=(*(x2_buffer+i));//theta in radians in relation to jet axis
(*gamma)[j]=1/pow(1.0-( (*(vel_x1_buffer+i))*(*(vel_x1_buffer+i)) + (*(vel_x2_buffer+i))*(*(vel_x2_buffer+i)) ),0.5); //v is in units of c
(*dens_lab)[j]= (*(dens_buffer+i)) /pow(1.0-( (*(vel_x1_buffer+i))*(*(vel_x1_buffer+i)) + (*(vel_x2_buffer+i))*(*(vel_x2_buffer+i)) ),0.5);
(*temp)[j]=pow(3*(*(pres_buffer+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
j++;
}
}
}
//fprintf(fPtr, "number: %d\n", r_count);
*number=r_count;
free(x1_buffer); free(x2_buffer); free(dx1_buffer); free(dx2_buffer); free(dens_buffer); free(pres_buffer); free(vel_x1_buffer); free(vel_x2_buffer);
}
void modifyPlutoName(char file[200], char prefix[200], int frame)
{
int lim1=0, lim2=0, lim3=0;
char test[200]="" ;
//if (strcmp(DIM_SWITCH, dim_2d_str)==0)
#if DIMENSIONS == 2
{
//2D case
lim1=10;
lim2=100;
lim3=1000;
}
#else
{
//3d case
lim1=100;
lim2=1000;
lim3=10000;
}
#endif
if (frame<lim1)
{
snprintf(test,sizeof(test), "%s%.3d%d.hdf5",prefix,000,frame);
}
else if (frame<lim2)
{
snprintf(test,sizeof(test), "%s%.2d%d.hdf5",prefix,00,frame);
}
else if (frame<lim3)
{
snprintf(test,sizeof(test), "%s%d%d.hdf5",prefix,0,frame);
}
else
{
snprintf(test,sizeof(test), "%s%d.hdf5",prefix,frame);
}
strncpy(file, test, sizeof(test));//had to do this workaround for some weird reason
}
| {
"alphanum_fraction": 0.5254928055,
"avg_line_length": 44.612244898,
"ext": "c",
"hexsha": "54472e4e5a26547ab956a9b4164099d18d804edc",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-03-19T09:13:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-19T09:13:42.000Z",
"max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "outflows/MCRaT",
"max_forks_repo_path": "Src/mclib_pluto.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14",
"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": "outflows/MCRaT",
"max_issues_repo_path": "Src/mclib_pluto.c",
"max_line_length": 286,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "outflows/MCRaT",
"max_stars_repo_path": "Src/mclib_pluto.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7037,
"size": 24046
} |
#pragma once
#include "utility/types.h"
#include <gsl/gsl>
#include <memory>
struct nk_context;
struct nk_user_font;
struct nk_buffer;
///
namespace cws80 {
class GraphicsDevice;
struct FontRequest;
//
class NkScreen {
public:
NkScreen();
~NkScreen();
void init(GraphicsDevice &gdev, uint w, uint h, gsl::span<const FontRequest> fontreqs);
void clear();
bool should_render() const;
void render(void *draw_context);
void update();
nk_context *context() const;
nk_user_font *font(uint id) const;
uint width() const;
uint height() const;
private:
struct Impl;
std::unique_ptr<Impl> P;
};
} // namespace cws80
| {
"alphanum_fraction": 0.676161919,
"avg_line_length": 17.1025641026,
"ext": "h",
"hexsha": "81d0424dbb6533333a4fd8b7d297602a57579fa6",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "jpcima/cws80",
"max_forks_repo_path": "sources/ui/cws80_ui_nk.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_issues_repo_issues_event_max_datetime": "2019-06-23T21:33:33.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-05-21T12:56:22.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "jpcima/cws80",
"max_issues_repo_path": "sources/ui/cws80_ui_nk.h",
"max_line_length": 91,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "ce37a49caed50a4b7baccfed288c2f5555af91c7",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "jpcima/cws80",
"max_stars_repo_path": "sources/ui/cws80_ui_nk.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": 171,
"size": 667
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sf_gamma.h>
double
f(double x, void * params)
{
int m = *(int *) params;
double f = gsl_pow_int(x, m) + 1.0;
return f;
}
int
main (int argc, char *argv[])
{
gsl_integration_fixed_workspace * w;
const gsl_integration_fixed_type * T = gsl_integration_fixed_hermite;
int m = 10;
int n = 6;
double expected, result;
gsl_function F;
if (argc > 1)
m = atoi(argv[1]);
if (argc > 2)
n = atoi(argv[2]);
w = gsl_integration_fixed_alloc(T, n, 0.0, 1.0, 0.0, 0.0);
F.function = &f;
F.params = &m;
gsl_integration_fixed(&F, &result, w);
if (m % 2 == 0)
expected = M_SQRTPI + gsl_sf_gamma(0.5*(1.0 + m));
else
expected = M_SQRTPI;
printf ("m = %d\n", m);
printf ("intervals = %zu\n", gsl_integration_fixed_n(w));
printf ("result = % .18f\n", result);
printf ("exact result = % .18f\n", expected);
printf ("actual error = % .18f\n", result - expected);
gsl_integration_fixed_free (w);
return 0;
}
| {
"alphanum_fraction": 0.6,
"avg_line_length": 20.7692307692,
"ext": "c",
"hexsha": "7638a5b8381d417a1436e6c3ceddefd2c8012aa1",
"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/doc/examples/integration2.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/integration2.c",
"max_line_length": 71,
"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/integration2.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": 356,
"size": 1080
} |
/* Copyright 2019-2020 Canaan Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "compiler_defs.h"
#include <cstring>
#include <gsl/gsl-lite.hpp>
BEGIN_NS_NNCASE_RUNTIME
class span_reader
{
public:
span_reader(gsl::span<const gsl::byte> span)
: span_(span)
{
}
bool empty() const noexcept { return span_.empty(); }
size_t avail() const noexcept { return span_.size_bytes(); }
template <class T>
T read()
{
auto value = *reinterpret_cast<const T *>(span_.data());
advance(sizeof(T));
return value;
}
template <class T>
T read_unaligned()
{
alignas(T) uint8_t storage[sizeof(T)];
std::memcpy(storage, span_.data(), sizeof(T));
advance(sizeof(T));
return *reinterpret_cast<const T *>(storage);
}
template <class T>
void read(T &value)
{
value = *reinterpret_cast<const T *>(span_.data());
advance(sizeof(T));
}
template <class T>
void read_span(gsl::span<const T> &span, size_t size)
{
span = { reinterpret_cast<const T *>(span_.data()), size };
advance(sizeof(T) * size);
}
template <class T = gsl::byte>
gsl::span<const T> read_span(size_t size)
{
gsl::span<const T> span(reinterpret_cast<const T *>(span_.data()), size);
advance(sizeof(T) * size);
return span;
}
void read_avail(gsl::span<const gsl::byte> &span)
{
span = span_;
span_ = {};
}
gsl::span<const gsl::byte> read_avail()
{
auto span = span_;
span_ = {};
return span;
}
gsl::span<const gsl::byte> peek_avail()
{
return span_;
}
template <class T>
T peek()
{
auto value = *reinterpret_cast<const T *>(span_.data());
return value;
}
template <class T>
T peek_unaligned()
{
T value;
std::memcpy(&value, span_.data(), sizeof(T));
return value;
}
template <class T>
T peek_unaligned_with_offset(size_t offset)
{
T value;
std::memcpy(&value, span_.data() + offset, sizeof(T));
return value;
}
template <class T>
const T *get_ref()
{
auto ptr = reinterpret_cast<const T *>(span_.data());
advance(sizeof(T));
return ptr;
}
template <class T>
void get_ref(const T *&ptr)
{
ptr = get_ref<T>();
}
void skip(size_t count)
{
advance(count);
}
private:
void advance(size_t count)
{
span_ = span_.subspan(count);
}
private:
gsl::span<const gsl::byte> span_;
};
END_NS_NNCASE_RUNTIME
| {
"alphanum_fraction": 0.5886016817,
"avg_line_length": 22.4545454545,
"ext": "h",
"hexsha": "e3bb0f8bf63845d1eb6f1e1dc5a1564b6e767c95",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T09:48:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-21T01:27:37.000Z",
"max_forks_repo_head_hexsha": "61e41170faed249303295d184f611f27cfefce9d",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "13129176346/nncase",
"max_forks_repo_path": "include/nncase/runtime/span_reader.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "61e41170faed249303295d184f611f27cfefce9d",
"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": "13129176346/nncase",
"max_issues_repo_path": "include/nncase/runtime/span_reader.h",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0ce252641826d65e12621347992cc9865874e6e1",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "zhen8838/kendryte-standalone-sdk",
"max_stars_repo_path": "lib/nncase/v1/include/nncase/runtime/span_reader.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T09:53:44.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-31T09:53:44.000Z",
"num_tokens": 779,
"size": 3211
} |
/*
* Copyright 2009-2019 The VOTCA-MPIP Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* author: Denis Andrienko
*/
#ifndef __VOTCA_CTP_EIGEN_H
#define __VOTCA_CTP_EIGEN_H
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <votca/tools/eigen.h>
#include <Eigen/Eigenvalues>
/*
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_eigen.h>
*/
#ifdef DEBUG_LINALG
#include <chrono>
#endif
namespace boost { namespace numeric { namespace ublas {
// specialization for double precision
template<class F, class A>
inline matrix<double,F,A> // prod( m1, m2 )
prod(const matrix<double,F,A> &m1, const matrix<double,F,A> &m2)
{
#ifdef DEBUG_LINALG
auto start = std::chrono::system_clock::now();
#endif
boost::numeric::ublas::matrix<double,F,A> AxB( m1.size1(), m2.size2() );
// Note that a Map<Type> m(&data) gives a view into the data (can change it)
// while assignments Matrix<Type> m = Map< Matrix<Type> > (&data)
// lead to a data copy and lost connection between the reference and matrix
Eigen::Map<const Eigen::MatrixXd> mA_( &(m1.data()[0]), m1.size2(), m1.size1() );
Eigen::Map<const Eigen::MatrixXd> mB_( &(m2.data()[0]), m2.size2(), m2.size1() );
Eigen::Map<Eigen::MatrixXd> AxB_( &(AxB.data()[0]), AxB.size2(), AxB.size1() );
AxB_ = mB_*mA_;
#ifdef DEBUG_LINALG
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "\n... ... ... \x1b[0;34mEigen "
<< "[" << m1.size1() << "x" << m1.size2() << "]"
<< "*[" << m2.size1() << "x" << m2.size2() << "]"
<< " time: " << elapsed_seconds.count()
<< "s\x1b[0;39m";
#endif
return AxB;
}
// specialization for single precision
template<class F, class A>
inline matrix<float, F, A> // prod( m1, m2 )
prod(const matrix<float, F, A> &m1, const matrix<float, F, A> &m2) {
#ifdef DEBUG_LINALG
auto start = std::chrono::system_clock::now();
#endif
boost::numeric::ublas::matrix<float, F, A> AxB(m1.size1(), m2.size2());
Eigen::Map<const Eigen::MatrixXf> mA_(&(m1.data()[0]), m1.size2(), m1.size1());
Eigen::Map<const Eigen::MatrixXf> mB_(&(m2.data()[0]), m2.size2(), m2.size1());
Eigen::Map<Eigen::MatrixXf> AxB_(&(AxB.data()[0]), AxB.size2(), AxB.size1());
AxB_ = mB_*mA_;
#ifdef DEBUG_LINALG
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "\n... ... ... \x1b[0;34mEigen "
<< "[" << m1.size1() << "x" << m1.size2() << "]"
<< "*[" << m2.size1() << "x" << m2.size2() << "]"
<< " time: " << elapsed_seconds.count()
<< "s\x1b[0;39m";
#endif
return AxB;
}
}}}
namespace votca { namespace ctp { namespace linalg {
inline void invert_symm( const ub::matrix<double> &A, ub::matrix<double> &V){
throw "Inversion of a matrix, linalg_invert, is not implemented in eigen.h";
}
/**
* \brief eigenvalues of a symmetric matrix A*x=E*x
* @param E vector of eigenvalues
* @param V input: matrix to diagonalize
* @param V output: eigenvectors
*
* This function wraps Eigen::EigenSolver
*
*/
inline void eigenvalues_symm(const ub::matrix<double> &A,
ub::vector<double> &E,
ub::matrix<double> &V)
{
#ifdef DEBUG_LINALG
auto start = std::chrono::system_clock::now();
#endif
/*
gsl_error_handler_t *handler = gsl_set_error_handler_off();
const size_t N = A.size1();
V.resize(N, N, false);
// gsl does not handle conversion of a symmetric_matrix
ub::matrix<double> _A( N,N );
//make copy of A as A is destroyed by GSL
_A = A;
E.resize(N, false);
V.resize(N, N, false);
gsl_matrix_view A_view = gsl_matrix_view_array(&_A(0,0), N, N);
gsl_vector_view E_view = gsl_vector_view_array(&E(0), N);
gsl_matrix_view V_view = gsl_matrix_view_array(&V(0,0), N, N);
gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(N);
int status = gsl_eigen_symmv(&A_view.matrix, &E_view.vector, &V_view.matrix, w);
assert(status == 0);
gsl_eigen_symmv_sort(&E_view.vector, &V_view.matrix, GSL_EIGEN_SORT_VAL_ASC);
gsl_eigen_symmv_free(w);
gsl_set_error_handler(handler);
std::cout << "\nREFERENCE";
std::cout << "\n A" << A;
std::cout << "\n E" << E;
std::cout << "\n V" << V;
std::cout << "\nREFERENCE\n";
*/
Eigen::Map<const Eigen::MatrixXd> A_( &(A.data()[0]), A.size2(), A.size1() );
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(A_.transpose());
/*
std::cout << "\nEIGEN";
std::cout << "\n E\n" << es.eigenvalues();
std::cout << "\n V\n" << es.eigenvectors();
std::cout << "\nEIGEN";
*/
// copy back to UBLAS objects
Eigen::Map<Eigen::VectorXd>( &E(0), A.size2() ) = es.eigenvalues();
Eigen::Map<Eigen::MatrixXd>( &V(0,0), A.size2(), A.size1() ) = es.eigenvectors().transpose();
#ifdef DEBUG_LINALG
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::cout << "\n... ... ... \x1b[0;34mEigen Eigenvalues"
<< "[" << A.size1() << "x" << A.size2() << "]"
<< " time: " << elapsed_seconds.count()
<< "s\x1b[0;39m";
#endif
}
}}}
#endif // __VOTCA_CTP_EIGEN_H
| {
"alphanum_fraction": 0.6037377257,
"avg_line_length": 31.7286432161,
"ext": "h",
"hexsha": "8cd8b44130f9316d566b160019a382d96361a86d",
"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": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "jimbach/ctp",
"max_forks_repo_path": "include/votca/ctp/eigen.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b",
"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": "jimbach/ctp",
"max_issues_repo_path": "include/votca/ctp/eigen.h",
"max_line_length": 97,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e5b33f074f81c6e6859dfaacada1b6c992c67c2b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "jimbach/ctp",
"max_stars_repo_path": "include/votca/ctp/eigen.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1839,
"size": 6314
} |
#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_her2 (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int uplo = 121;
int N = 1;
int lda = 1;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { -0.821f, 0.954f };
float X[] = { 0.532f, 0.802f };
int incX = -1;
float Y[] = { 0.016f, -0.334f };
int incY = -1;
float A_expected[] = { -0.302288f, 0.0f };
cblas_cher2(order, uplo, 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, "cher2(case 1450) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, "cher2(case 1450) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int N = 1;
int lda = 1;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { -0.821f, 0.954f };
float X[] = { 0.532f, 0.802f };
int incX = -1;
float Y[] = { 0.016f, -0.334f };
int incY = -1;
float A_expected[] = { -0.302288f, 0.0f };
cblas_cher2(order, uplo, 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, "cher2(case 1451) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, "cher2(case 1451) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int N = 1;
int lda = 1;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { -0.821f, 0.954f };
float X[] = { 0.532f, 0.802f };
int incX = -1;
float Y[] = { 0.016f, -0.334f };
int incY = -1;
float A_expected[] = { -0.302288f, 0.0f };
cblas_cher2(order, uplo, 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, "cher2(case 1452) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, "cher2(case 1452) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int N = 1;
int lda = 1;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { -0.821f, 0.954f };
float X[] = { 0.532f, 0.802f };
int incX = -1;
float Y[] = { 0.016f, -0.334f };
int incY = -1;
float A_expected[] = { -0.302288f, 0.0f };
cblas_cher2(order, uplo, 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, "cher2(case 1453) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], flteps, "cher2(case 1453) imag");
};
};
};
{
int order = 101;
int uplo = 121;
int N = 1;
int lda = 1;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.334, 0.286 };
double X[] = { -0.14, -0.135 };
int incX = -1;
double Y[] = { 0.455, 0.358 };
int incY = -1;
double A_expected[] = { -0.264521, 0.0 };
cblas_zher2(order, uplo, 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, "zher2(case 1454) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, "zher2(case 1454) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int N = 1;
int lda = 1;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.334, 0.286 };
double X[] = { -0.14, -0.135 };
int incX = -1;
double Y[] = { 0.455, 0.358 };
int incY = -1;
double A_expected[] = { -0.264521, 0.0 };
cblas_zher2(order, uplo, 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, "zher2(case 1455) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, "zher2(case 1455) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int N = 1;
int lda = 1;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.334, 0.286 };
double X[] = { -0.14, -0.135 };
int incX = -1;
double Y[] = { 0.455, 0.358 };
int incY = -1;
double A_expected[] = { -0.264521, 0.0 };
cblas_zher2(order, uplo, 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, "zher2(case 1456) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, "zher2(case 1456) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int N = 1;
int lda = 1;
double alpha[2] = {-0.3, 0.1};
double A[] = { -0.334, 0.286 };
double X[] = { -0.14, -0.135 };
int incX = -1;
double Y[] = { 0.455, 0.358 };
int incY = -1;
double A_expected[] = { -0.264521, 0.0 };
cblas_zher2(order, uplo, 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, "zher2(case 1457) real");
gsl_test_rel(A[2*i+1], A_expected[2*i+1], dbleps, "zher2(case 1457) imag");
};
};
};
}
| {
"alphanum_fraction": 0.5013208697,
"avg_line_length": 25.1071428571,
"ext": "c",
"hexsha": "5b43dd1a957c32dff6279ef3f3d495c10c33a553",
"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_her2.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_her2.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_her2.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": 2115,
"size": 4921
} |
//===--- Sudoku/Solver.h ---===//
//
// Solver functions acting on a Board<Options>&
// Declarations are in Solver.fwd.h
//===----------------------------------------------------------------------===//
#pragma once
#include "Solvers_find.h"
#include "Solvers_remove_option.h"
#include "Solvers_set_option.h"
#include "Sudoku/Board.h"
#include "Sudoku/Location.h"
#include "Sudoku/Location_Utilities.h"
#include "Sudoku/Options.h"
#include "Sudoku/Size.h"
#include "Sudoku/Value.h"
#include <gsl/gsl>
#include <vector>
#include <algorithm> // minmax
#include <type_traits> // is_base_of
#include "Solver.fwd.h" // Forward declarations
#include <cassert>
namespace Sudoku
{
// Check if only one option remaining
// IF true: process answer
template<int N, typename Options>
inline int single_option(
Board<Options, N>& board, // NOLINT(runtime/references)
const Location<N> loc)
{
assert(is_valid(loc));
if (const Value answer{get_answer(board.at(loc))})
{
return single_option(board, loc, answer);
}
return 0;
}
// Process answer from [loc], update board_ options
// Remove option from rest of row, col and block
template<int N, typename Options>
inline int single_option(
Board<Options, N>& board, // NOLINT(runtime/references)
const Location<N> loc,
const Value value)
{
{
assert(is_valid(loc));
assert(is_valid<N>(value));
assert(board.at(loc).test(value));
}
int changes{};
changes += set_Value(board, loc, value);
changes += remove_option_section(board, board.row(loc), loc, value);
changes += remove_option_section(board, board.col(loc), loc, value);
changes += remove_option_section(board, board.block(loc), loc, value);
return changes;
}
// if 2 options in element:
// find exact pair in section:
// remove form other elements in section
template<int N, typename Options>
inline int dual_option(
Board<Options, N>& board, // NOLINT(runtime/references)
const Location<N> loc)
{
using Location = Location<N>;
{
assert(is_valid(loc));
assert(board.at(loc).count() == 2);
}
const auto sorted_loc = [loc](const Location L)
{
const auto result = std::minmax(loc, L);
return std::vector<Location>{result.first, result.second};
};
int changes{};
const Options& item{board.at(loc)};
const auto mask = [](Options x) noexcept
{
x[Value{0}] = false;
return x;
}(item);
for (int i{}; i < full_size<N>; ++i)
{
// find exact same in board
if (board[Location(i)] == item && Location(i) != loc)
{
// Remove values for rest of shared elements
if (is_same_row(loc, Location(i)))
{
changes += remove_option_section(
board, board.row(loc), sorted_loc(Location(i)), mask);
}
else if (is_same_col(loc, Location(i)))
{
changes += remove_option_section(
board, board.col(loc), sorted_loc(Location(i)), mask);
}
// run not if already answered
if (is_same_block(loc, Location(i)) && !item.is_answer())
{ // NOTE this is slow
changes += remove_option_section(
board, board.block(loc), sorted_loc(Location(i)), mask);
}
}
}
return changes;
}
// Find subsets in any related sections,
// and remove the values from rest of these sections.
template<int N, typename Options>
inline int multi_option(
Board<Options, N>& board, // NOLINT(runtime/references)
const Location<N> loc)
{
assert(is_valid(loc));
return multi_option(board, loc, board.at(loc).count());
}
// Find subsets in any related section,
// and remove the values from rest of these sections.
template<int N, typename Options>
constexpr int multi_option(
Board<Options, N>& board, // NOLINT(runtime/references)
const Location<N> loc,
const size_t count)
{
assert(is_valid(loc));
// set execution domain & specializations
switch (count)
{
case 0: [[fallthrough]]; // already answered
case elem_size<N>: return 0; // no result anyway
case 1: return single_option(board, loc);
case 2: return dual_option(board, loc);
default: assert(count < elem_size<N>); break;
}
int changes{}; // performance counter
const Options& item{board.at(loc)}; // input item, to match with
assert(item.count() == count);
const auto mask = [](Options x) noexcept
{
x[Value{0}] = false;
return x;
}(item);
const auto list = list_where_subset(board, item);
// Further select per section.
// When (subset size == #options) then: all answers in this selection.
// Therefore: Remove values for rest of section.
if (const auto in_row{get_same_row(loc, list)}; in_row.size() == count)
{
changes += remove_option_section(board, board.row(loc), in_row, mask);
}
if (const auto in_col{get_same_col(loc, list)}; in_col.size() == count)
{
changes += remove_option_section(board, board.col(loc), in_col, mask);
}
if (const auto in_block{get_same_block(loc, list)};
in_block.size() == count)
{
// NOTE this is slow
changes +=
remove_option_section(board, board.block(loc), in_block, mask);
}
return changes;
}
// Solver: Find options appearing only once in a section and set as answer
template<int N, typename Options, typename SectionT>
inline int unique_in_section(
Board<Options, N>& board, // NOLINT(runtime/references)
const SectionT section)
{
{
static_assert(Board_Section::traits::is_Section_v<SectionT>);
}
const auto worker = appearance_once<N>(section);
return set_uniques(board, section, worker);
}
// Solver: find and process values appearing 1 to base_size times in section:
// [row/col] IF all in same block -> remove from rest of block
// [block] IF all in same row/col -> remove from rest of row/col
template<int N, typename Options, typename SectionT>
inline int section_exclusive(
Board<Options, N>& board, // NOLINT(runtime/references)
const SectionT section)
{
{
static_assert(Board_Section::traits::is_Section_v<SectionT>);
static_assert(std::is_same_v<typename SectionT::value_type, Options>);
}
int changes{}; // performance counter
size_t i{2};
auto appearing = appearance_sets<N>(section);
const auto renew_appearing = [&i, &a = appearing, §ion]()
{
i = 2;
a = appearance_sets<N>(section);
};
while (i < appearing.size()) // won't run if condition fails
{
// unique specialization
if (appearing[1].count_all() > 0)
{
changes += set_uniques(board, section, appearing[1]);
renew_appearing();
continue;
}
if (appearing.at(i).count_all() > 0)
{ // for [row/col]: if in same block: remove from rest block
// for [block]: if in same row/col: remove from rest row/col
if (const int tmp_ = set_section_locals(
board, section, gsl::narrow_cast<int>(i), appearing.at(i)))
{
changes += tmp_;
renew_appearing();
continue;
}
}
++i;
}
return changes;
}
// cell containing 2 options
// find in board_ size() == 2
// find exact same in rest board
// IF pair in same row/col -> remove values from rest row/col
// IF same block -> remove values from rest block
// repeat until end of board_
// repeat until end of board_
// cell containing 2 options
// find in board_ size() == 2
// find exact same in rest row
// IF found: remove values from rest row
// find exact same in rest col
// find exact same in rest block
} // namespace Sudoku
| {
"alphanum_fraction": 0.6774059735,
"avg_line_length": 27.3939393939,
"ext": "h",
"hexsha": "c12f2f098d178423db81c7078d6b96df1a0066e9",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-04-20T16:26:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-04-20T16:26:42.000Z",
"max_forks_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Farwaykorse/fwkSudoku",
"max_forks_repo_path": "Sudoku/Strategic/Solver.h",
"max_issues_count": 38,
"max_issues_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692",
"max_issues_repo_issues_event_max_datetime": "2021-07-17T01:22:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-28T18:15:15.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Farwaykorse/fwkSudoku",
"max_issues_repo_path": "Sudoku/Strategic/Solver.h",
"max_line_length": 80,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "05652d80fae2780f1327467225580e2c67dfa692",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Farwaykorse/fwkSudoku",
"max_stars_repo_path": "Sudoku/Strategic/Solver.h",
"max_stars_repo_stars_event_max_datetime": "2019-08-18T19:26:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-17T18:27:16.000Z",
"num_tokens": 1881,
"size": 7232
} |
/* linalg/lu.c
*
* Copyright (C) 2020 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
static int LU_band_decomp_L2 (const size_t M, const size_t lb, const size_t ub,
gsl_matrix * AB, gsl_vector_uint * ipiv);
/* Factorise a (p,q) banded M x N matrix A into,
*
* P A = L U
*
* where P is a permutation matrix, L is unit lower triangular and U
* is upper triangular.
*
* L is stored in the strict lower triangular part of the input
* matrix. The diagonal elements of L are unity and are not stored.
*
* U is stored in the diagonal and upper triangular part of the
* input matrix.
*
* P is stored in the permutation p. Column j of P is column k of the
* identity matrix, where k = permutation->data[j]
*
* Inputs: M - number of rows in matrix
* lb - lower bandwidth
* ub - upper bandwidth
* AB - matrix in band storage format, N-by-(2*p + q + 1)
* piv - pivot vector, size MIN(M, N)
*/
int
gsl_linalg_LU_band_decomp (const size_t M, const size_t lb, const size_t ub, gsl_matrix * AB, gsl_vector_uint * piv)
{
const size_t N = AB->size1;
const size_t minMN = GSL_MIN(M, N);
if (lb >= M)
{
GSL_ERROR ("lower bandwidth must be less than M", GSL_EDOM);
}
else if (ub >= N)
{
GSL_ERROR ("upper bandwidth must be less than N", GSL_EDOM);
}
else if (AB->size2 != 2*lb + ub + 1)
{
GSL_ERROR ("matrix size inconsistent with bandwidths", GSL_EBADLEN);
}
else if (piv->size != minMN)
{
GSL_ERROR ("pivot vector must have length MIN(M,N)", GSL_EBADLEN);
}
else
{
int status;
status = LU_band_decomp_L2 (M, lb, ub, AB, piv);
return status;
}
}
int
gsl_linalg_LU_band_solve (const size_t lb, const size_t ub, const gsl_matrix * LUB,
const gsl_vector_uint * piv, const gsl_vector * b, gsl_vector * x)
{
const size_t N = LUB->size1;
if (N != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else if (N != b->size)
{
GSL_ERROR ("matrix size must match rhs size", GSL_EBADLEN);
}
else if (lb >= N)
{
GSL_ERROR ("lower bandwidth must be less than N", GSL_EDOM);
}
else if (ub >= N)
{
GSL_ERROR ("upper bandwidth must be less than N", GSL_EDOM);
}
else if (LUB->size2 != 2*lb + ub + 1)
{
GSL_ERROR ("matrix size inconsistent with bandwidths", GSL_EBADLEN);
}
else if (piv->size != N)
{
GSL_ERROR ("pivot vector must have length N", GSL_EBADLEN);
}
else
{
int status;
gsl_vector_memcpy(x, b);
status = gsl_linalg_LU_band_svx(lb, ub, LUB, piv, x);
return status;
}
}
int
gsl_linalg_LU_band_svx (const size_t lb, const size_t ub, const gsl_matrix * LUB,
const gsl_vector_uint * piv, gsl_vector * x)
{
const size_t N = LUB->size1;
if (N != x->size)
{
GSL_ERROR ("matrix size must match solution/rhs size", GSL_EBADLEN);
}
else if (lb >= N)
{
GSL_ERROR ("lower bandwidth must be less than N", GSL_EDOM);
}
else if (ub >= N)
{
GSL_ERROR ("upper bandwidth must be less than N", GSL_EDOM);
}
else if (LUB->size2 != 2*lb + ub + 1)
{
GSL_ERROR ("matrix size inconsistent with bandwidths", GSL_EBADLEN);
}
else if (piv->size != N)
{
GSL_ERROR ("pivot vector must have length N", GSL_EBADLEN);
}
else
{
if (lb > 0)
{
size_t j;
for (j = 0; j < N - 1; ++j)
{
size_t pj = gsl_vector_uint_get(piv, j);
double * xj = gsl_vector_ptr(x, j);
size_t lm = GSL_MIN(lb, N - j - 1);
gsl_vector_view xv = gsl_vector_subvector(x, j + 1, lm);
gsl_vector_const_view yv = gsl_matrix_const_subrow(LUB, j, lb + ub + 1, lm);
if (j != pj)
{
double xl = gsl_vector_get(x, pj);
gsl_vector_set(x, pj, *xj);
*xj = xl;
}
gsl_blas_daxpy(-(*xj), &yv.vector, &xv.vector);
}
}
/* solve U x = b */
cblas_dtbsv(CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit,
(int) N, (int) (lb + ub), LUB->data, LUB->tda,
x->data, x->stride);
return GSL_SUCCESS;
}
}
int
gsl_linalg_LU_band_unpack (const size_t M, const size_t lb, const size_t ub, const gsl_matrix * LUB,
const gsl_vector_uint * piv, gsl_matrix * L, gsl_matrix * U)
{
const size_t N = LUB->size1;
const size_t minMN = GSL_MIN(M, N);
if (ub >= N)
{
GSL_ERROR ("upper bandwidth must be < N", GSL_EDOM);
}
else if (lb >= M)
{
GSL_ERROR ("lower bandwidth must be < M", GSL_EDOM);
}
else if (LUB->size2 != 2*lb + ub + 1)
{
GSL_ERROR ("matrix size inconsistent with bandwidths", GSL_EBADLEN);
}
else if (piv->size != minMN)
{
GSL_ERROR ("pivot vector must have length MIN(M,N)", GSL_EBADLEN);
}
else if (L->size1 != M || L->size2 != minMN)
{
GSL_ERROR ("L matrix has wrong dimensions", GSL_EBADLEN);
}
else if (U->size1 != minMN || U->size2 != N)
{
GSL_ERROR ("U matrix has wrong dimensions", GSL_EBADLEN);
}
else
{
const size_t ub_U = lb + ub;
size_t j;
gsl_matrix_set_identity(L);
gsl_matrix_set_zero(U);
/* compute L */
if (lb > 0)
{
const size_t jstart = (M > N) ? minMN : minMN - 1;
size_t j;
for (j = jstart; j > 0 && j--; )
{
size_t pj = gsl_vector_uint_get(piv, j);
size_t lm = GSL_MIN(lb, M - j - 1);
gsl_vector_const_view xv = gsl_matrix_const_subrow(LUB, j, lb + ub + 1, lm);
gsl_vector_const_view yv = gsl_matrix_const_subrow(L, j, 0, minMN);
gsl_matrix_view m = gsl_matrix_submatrix(L, j + 1, 0, lm, minMN);
gsl_blas_dger(1.0, &xv.vector, &yv.vector, &m.matrix);
if (j != pj)
{
gsl_vector_view Lj = gsl_matrix_row(L, j);
gsl_vector_view Lpj = gsl_matrix_row(L, pj);
gsl_blas_dswap(&Lj.vector, &Lpj.vector);
}
}
}
/* fill in U */
for (j = 0; j <= GSL_MIN(ub_U, N - 1); ++j)
{
gsl_vector_const_view src = gsl_matrix_const_subcolumn(LUB, ub_U - j, j, GSL_MIN(M, N - j));
gsl_vector_view dest = gsl_matrix_superdiagonal(U, j);
gsl_vector_memcpy(&dest.vector, &src.vector);
}
return GSL_SUCCESS;
}
}
/*
LU_band_decomp_L2
LU decomposition with partial pivoting using Level 2 BLAS
Inputs: M - number of rows in matrix
lb - lower bandwidth
ub - upper bandwidth
AB - on input, matrix to be factored; on output, L and U factors
N-by-(2*p + q + 1)
ipiv - (output) array containing row swaps
Notes:
1) Based on LAPACK DGBTF2
*/
static int
LU_band_decomp_L2 (const size_t M, const size_t lb, const size_t ub,
gsl_matrix * AB, gsl_vector_uint * ipiv)
{
const size_t N = AB->size1;
const size_t minMN = GSL_MIN(M, N);
if (ipiv->size != minMN)
{
GSL_ERROR ("ipiv length must equal MIN(M,N)", GSL_EBADLEN);
}
else if (lb >= M)
{
GSL_ERROR ("lower bandwidth must be less than M", GSL_EDOM);
}
else if (ub >= N)
{
GSL_ERROR ("upper bandwidth must be less than N", GSL_EDOM);
}
else if (AB->size2 != 2*lb + ub + 1)
{
GSL_ERROR ("matrix size inconsistent with bandwidths", GSL_EBADLEN);
}
else
{
const size_t ub_U = lb + ub; /* upper bandwidth of U factor */
const size_t ldab = AB->size2;
size_t ju = 0;
size_t j;
if (lb > 0)
{
/* initialize fill-in elements to zero */
gsl_matrix_view m = gsl_matrix_submatrix(AB, 0, 0, N, lb);
gsl_matrix_set_zero(&m.matrix);
}
for (j = 0; j < minMN; ++j)
{
size_t lbj = GSL_MIN(lb, M - j - 1); /* subdiagonal elements in column j */
gsl_vector_view x = gsl_matrix_subrow(AB, j, ub_U, lbj + 1);
gsl_vector_view y;
CBLAS_INDEX_t j_pivot = gsl_blas_idamax(&x.vector);
double * ptr;
gsl_vector_uint_set(ipiv, j, j + j_pivot);
ptr = gsl_matrix_ptr(AB, j, ub_U + j_pivot);
if (*ptr != 0.0)
ju = GSL_MAX(ju, GSL_MIN(j + ub + j_pivot, N - 1));
if (j_pivot != 0)
{
double *ptr2;
/* swap columns */
x = gsl_vector_view_array_with_stride(ptr, ldab - 1, ju - j + 1);
ptr2 = gsl_matrix_ptr(AB, j, ub_U);
y = gsl_vector_view_array_with_stride(ptr2, ldab - 1, ju - j + 1);
gsl_blas_dswap(&x.vector, &y.vector);
}
if (lbj > 0)
{
double tmp = gsl_matrix_get(AB, j, ub_U);
x = gsl_matrix_subrow(AB, j, ub_U + 1, lbj);
gsl_blas_dscal(1.0 / tmp, &x.vector);
if (ju > j)
{
gsl_matrix_view m = gsl_matrix_submatrix(AB, j + 1, ub_U, ju - j, lbj);
ptr = gsl_matrix_ptr(AB, j + 1, ub_U - 1);
y = gsl_vector_view_array_with_stride(ptr, ldab - 1, ju - j);
m.matrix.tda = ldab - 1; /* unskew matrix */
gsl_blas_dger(-1.0, &y.vector, &x.vector, &m.matrix);
}
}
}
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.56134074,
"avg_line_length": 28.783197832,
"ext": "c",
"hexsha": "02805b4987a343d038f39d62a3b4d6a68acb6ce9",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/lu_band.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/lu_band.c",
"max_line_length": 116,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/lu_band.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": 3027,
"size": 10621
} |
/* linalg/ldlt.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.
*/
/* L D L^T decomposition of a symmetric positive semi-definite matrix */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
static double ldlt_norm1(const gsl_matrix * A);
static int ldlt_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params);
/*
gsl_linalg_ldlt_decomp()
Perform L D L^T decomposition of a symmetric positive
semi-definite matrix using lower triangle
Inputs: A - (input) symmetric, positive semi-definite matrix
(output) lower triangle contains L factor;
diagonal contains D
Return: success/error
Notes:
1) Based on algorithm 4.1.1 of Golub and Van Loan, Matrix Computations (4th ed).
2) The first subrow A(1, 2:end) is used as temporary workspace
3) The 1-norm ||A||_1 of the original matrix is stored in the upper right corner on output
*/
int
gsl_linalg_ldlt_decomp (gsl_matrix * A)
{
const size_t M = A->size1;
const size_t N = A->size2;
if (M != N)
{
GSL_ERROR ("LDLT decomposition requires square matrix", GSL_ENOTSQR);
}
else
{
size_t i, j;
double a00, anorm;
gsl_vector_view work, v;
/* check for quick return */
if (N == 1)
return GSL_SUCCESS;
/* compute ||A||_1 */
anorm = ldlt_norm1(A);
/* special case first column */
a00 = gsl_matrix_get(A, 0, 0);
if (a00 == 0.0)
{
GSL_ERROR ("matrix is singular", GSL_EDOM);
}
v = gsl_matrix_subcolumn(A, 0, 1, N - 1);
gsl_vector_scale(&v.vector, 1.0 / a00);
/* use first subrow A(1, 2:end) as temporary workspace */
work = gsl_matrix_subrow(A, 0, 1, N - 1);
for (j = 1; j < N; ++j)
{
gsl_vector_view w = gsl_vector_subvector(&work.vector, 0, j);
double ajj = gsl_matrix_get(A, j, j);
double dval;
for (i = 0; i < j; ++i)
{
double aii = gsl_matrix_get(A, i, i);
double aji = gsl_matrix_get(A, j, i);
gsl_vector_set(&w.vector, i, aji * aii);
}
v = gsl_matrix_subrow(A, j, 0, j); /* A(j,1:j-1) */
gsl_blas_ddot(&v.vector, &w.vector, &dval);
ajj -= dval;
if (ajj == 0.0)
{
GSL_ERROR ("matrix is singular", GSL_EDOM);
}
gsl_matrix_set(A, j, j, ajj);
if (j < N - 1)
{
double ajjinv = 1.0 / ajj;
gsl_matrix_view m = gsl_matrix_submatrix(A, j + 1, 0, N - j - 1, j); /* A(j+1:n, 1:j-1) */
v = gsl_matrix_subcolumn(A, j, j + 1, N - j - 1); /* A(j+1:n, j) */
gsl_blas_dgemv(CblasNoTrans, -ajjinv, &m.matrix, &w.vector, ajjinv, &v.vector);
}
}
/* save ||A||_1 in upper right corner */
gsl_matrix_set(A, 0, N - 1, anorm);
return GSL_SUCCESS;
}
}
int
gsl_linalg_ldlt_solve (const gsl_matrix * LDLT,
const gsl_vector * b,
gsl_vector * x)
{
if (LDLT->size1 != LDLT->size2)
{
GSL_ERROR ("LDLT matrix must be square", GSL_ENOTSQR);
}
else if (LDLT->size1 != b->size)
{
GSL_ERROR ("matrix size must match b size", GSL_EBADLEN);
}
else if (LDLT->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
int status;
/* copy x <- b */
gsl_vector_memcpy (x, b);
status = gsl_linalg_ldlt_svx(LDLT, x);
return status;
}
}
int
gsl_linalg_ldlt_svx (const gsl_matrix * LDLT,
gsl_vector * x)
{
if (LDLT->size1 != LDLT->size2)
{
GSL_ERROR ("LDLT matrix must be square", GSL_ENOTSQR);
}
else if (LDLT->size2 != x->size)
{
GSL_ERROR ("matrix size must match solution size", GSL_EBADLEN);
}
else
{
gsl_vector_const_view diag = gsl_matrix_const_diagonal(LDLT);
/* solve for z using forward-substitution, L z = b */
gsl_blas_dtrsv (CblasLower, CblasNoTrans, CblasUnit, LDLT, x);
/* solve for y, D y = z */
gsl_vector_div(x, &diag.vector);
/* perform back-substitution, L^T x = y */
gsl_blas_dtrsv (CblasLower, CblasTrans, CblasUnit, LDLT, x);
return GSL_SUCCESS;
}
}
int
gsl_linalg_ldlt_rcond (const gsl_matrix * LDLT, double * rcond,
gsl_vector * work)
{
const size_t M = LDLT->size1;
const size_t N = LDLT->size2;
if (M != N)
{
GSL_ERROR ("LDLT matrix must be square", GSL_ENOTSQR);
}
else if (work->size != 3 * N)
{
GSL_ERROR ("work vector must have length 3*N", GSL_EBADLEN);
}
else
{
int status;
double Anorm; /* ||A||_1 */
double Ainvnorm; /* ||A^{-1}||_1 */
if (N == 1)
Anorm = fabs(gsl_matrix_get(LDLT, 0, 0));
else
Anorm = gsl_matrix_get(LDLT, 0, N - 1);
*rcond = 0.0;
/* don't continue if matrix is singular */
if (Anorm == 0.0)
return GSL_SUCCESS;
/* estimate ||A^{-1}||_1 */
status = gsl_linalg_invnorm1(N, ldlt_Ainv, (void *) LDLT, &Ainvnorm, work);
if (status)
return status;
if (Ainvnorm != 0.0)
*rcond = (1.0 / Anorm) / Ainvnorm;
return GSL_SUCCESS;
}
}
/* compute 1-norm of symmetric matrix stored in lower triangle */
static double
ldlt_norm1(const gsl_matrix * A)
{
const size_t N = A->size1;
double max = 0.0;
size_t i, j;
for (j = 0; j < N; ++j)
{
gsl_vector_const_view v = gsl_matrix_const_subcolumn(A, j, j, N - j);
double sum = gsl_blas_dasum(&v.vector);
/* now add symmetric elements from above diagonal */
for (i = 0; i < j; ++i)
{
double Aij = gsl_matrix_get(A, i, j);
sum += fabs(Aij);
}
if (sum > max)
max = sum;
}
return max;
}
/* x := A^{-1} x = A^{-t} x, A = L D L^T */
static int
ldlt_Ainv(CBLAS_TRANSPOSE_t TransA, gsl_vector * x, void * params)
{
int status;
gsl_matrix * A = (gsl_matrix * ) params;
gsl_vector_const_view diag = gsl_matrix_const_diagonal(A);
(void) TransA; /* unused parameter warning */
/* compute L^{-1} x */
status = gsl_blas_dtrsv(CblasLower, CblasNoTrans, CblasUnit, A, x);
if (status)
return status;
/* compute D^{-1} x */
gsl_vector_div(x, &diag.vector);
/* compute L^{-t} x */
status = gsl_blas_dtrsv(CblasLower, CblasTrans, CblasUnit, A, x);
if (status)
return status;
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.5840444264,
"avg_line_length": 26.0883392226,
"ext": "c",
"hexsha": "aee78472a5477453e72a1ee58d5eea2dc774b003",
"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/linalg/ldlt.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/linalg/ldlt.c",
"max_line_length": 104,
"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/linalg/ldlt.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": 2202,
"size": 7383
} |
/*
* Copyright 2020 Makani Technologies LLC
*
* 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 SIM_PHYSICS_DVL_AERO_DATABASE_H_
#define SIM_PHYSICS_DVL_AERO_DATABASE_H_
#include <gsl/gsl_vector.h>
#include <stddef.h>
#include <stdint.h>
#include <string>
#include <vector>
#include "common/c_math/force_moment.h"
#include "common/c_math/linalg.h"
#include "common/c_math/vec3.h"
#include "common/macros.h"
#include "sim/physics/aero_types.h"
#include "system/labels.h"
class DvlAeroDatabase {
public:
explicit DvlAeroDatabase(const std::string &filename);
~DvlAeroDatabase();
// Returns the total force-moment coefficient at a specific (alpha,
// beta, omega_hat, flap deflection) operating point.
void CalcForceMomentCoeff(double alpha, double beta, const Vec3 &omega_hat,
const Vec &flaps, ForceMoment *cfm,
double thrust_coeff) const {
CalcForceMomentCoeff(alpha, beta, omega_hat, flaps, cfm, thrust_coeff,
nullptr);
}
// See function above. Optionally returns the breakdown of the
// force-moment coefficient into control and stability derivatives
// if aero_coeffs is not null.
void CalcForceMomentCoeff(double alpha, double beta, const Vec3 &omega_hat,
const Vec &flaps, ForceMoment *cfm,
double thrust_coeff,
DvlAeroCoeffs *aero_coeffs) const;
int32_t num_flaps() const { return num_flaps_; }
double reynolds_number() const { return reynolds_number_; }
private:
// Returns true if the database passes basic sign checks.
bool IsValid() const;
// Returns the total force-moment coefficient at a specific (alpha,
// beta, omega_hat, flap deflection) operating point and the
// breakdown of this value into control and stability derivatives.
void CalcDvlAeroCoeffs(double alpha, double beta, const Vec &flaps,
DvlAeroCoeffs *coeffs) const;
void LookupForceMomentCoeff2D(const gsl_vector &cfm_data, size_t size1,
size_t size2, int32_t s0, int32_t t0, double ds,
double dt, ForceMoment *cfm) const;
void LookupForceMomentCoeff3D(const gsl_vector &cfm_data, int32_t indices[],
double du, double dv, double dw,
ForceMoment *cfm) const;
// Number of flaps used in database.
int32_t num_flaps_;
// Reynolds number [#] at which the database was calculated.
double reynolds_number_;
// List of angles-of-attack [rad] used in database look-up table.
gsl_vector *alphas_;
// List of sideslip angles [rad] used in database look-up table.
gsl_vector *betas_;
// Vector of lists of flap deflections [rad], one list for each
// flap, used in database look-up table.
std::vector<gsl_vector *> deltas_;
// Tensor grid of force-moment coefficients at zero flap deflections
// over angle-of-attack and sideslip, stored as a vector.
gsl_vector *cfm_;
// Tensor grid of force-moment stability derivatives at zero flap
// deflections over angle-of-attack and sideslip, stored as a
// vector.
gsl_vector *dcfm_dp_;
gsl_vector *dcfm_dq_;
gsl_vector *dcfm_dr_;
// Vector of tensor grids of increments to the force-moment
// coefficients, due to flap deflections, for each flap. The tensor
// grid is over angle-of-attack, sideslip, and flap deflection, and
// is stored as a vector.
std::vector<gsl_vector *> flap_cfms_;
// Vector of tensor grids of increments to the force-moment
// stability derivatives, due to flap deflections, for each flap.
// The tensor grid is over angle-of-attack, sideslip, and flap
// deflection, and is stored as a vector.
std::vector<gsl_vector *> flap_dcfm_dps_;
std::vector<gsl_vector *> flap_dcfm_dqs_;
std::vector<gsl_vector *> flap_dcfm_drs_;
DISALLOW_COPY_AND_ASSIGN(DvlAeroDatabase);
};
#endif // SIM_PHYSICS_DVL_AERO_DATABASE_H_
| {
"alphanum_fraction": 0.6979212738,
"avg_line_length": 37.3719008264,
"ext": "h",
"hexsha": "0f6ba9632584b9a51e320cd2100138c42ff3be0f",
"lang": "C",
"max_forks_count": 107,
"max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z",
"max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "leozz37/makani",
"max_forks_repo_path": "sim/physics/dvl_aero_database.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b",
"max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "leozz37/makani",
"max_issues_repo_path": "sim/physics/dvl_aero_database.h",
"max_line_length": 80,
"max_stars_count": 1178,
"max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "leozz37/makani",
"max_stars_repo_path": "sim/physics/dvl_aero_database.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z",
"num_tokens": 1095,
"size": 4522
} |
/*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: lymastee@hotmail.com
*
* This file is part of the gslib project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#ifndef rtree_77e9ff20_6040_46f3_b87d_ab64a4ac506a_h
#define rtree_77e9ff20_6040_46f3_b87d_ab64a4ac506a_h
#include <gslib/error.h>
#include <gslib/tree.h>
#include <gslib/utility.h>
__gslib_begin__
class __gs_novtable rtree_spec abstract
{
public:
enum type
{
spec_line,
/* more... */
};
virtual ~rtree_spec() {}
virtual type get_type() const = 0;
virtual bool query_overlap(const rectf& rc) const = 0;
virtual bool query_overlap(const pointf& p1, const pointf& p2) const = 0;
};
class rtree_spec_line:
public rtree_spec
{
public:
rtree_spec_line(const pointf& p1, const pointf& p2): _p1(p1), _p2(p2) {}
virtual type get_type() const override { return spec_line; }
virtual bool query_overlap(const rectf& rc) const override { return is_line_rect_overlapped(_p1, _p2, rc); }
virtual bool query_overlap(const pointf& p1, const pointf& p2) const override
{
vec2 intsp, d1, d2;
d1.sub(_p2, _p1);
d2.sub(p2, p1);
if(is_parallel(d1, d2))
return false;
intersectp_linear_linear(intsp, _p1, p1, d1, d2);
float t1 = linear_reparameterize(_p1, _p2, intsp);
if(t1 < 0.f || t1 > 1.f)
return false;
float t2 = linear_reparameterize(p1, p2, intsp);
return t2 >= 0.f && t2 <= 1.f;
}
private:
pointf _p1, _p2;
};
template<class _bind, int _bsize = sizeof(_bind)>
class rtree_entity
{
public:
typedef rtree_entity<_bind, _bsize> myref;
typedef _bind bind_type;
typedef const _bind& bind_arg;
protected:
rectf _rect;
bind_type _bind_arg;
rtree_spec* _spec = nullptr;
public:
rtree_entity() {}
rtree_entity(bind_arg ba, const rectf& rc): _rect(rc), _bind_arg(ba) {}
~rtree_entity() { set_spec(nullptr); }
const rectf& const_rect() const { return _rect; }
rectf& get_rect() { return _rect; }
bind_arg get_bind_arg() const { return _bind_arg; }
rtree_spec* get_spec() const { return _spec; }
void set_rect(const rectf& rc) { _rect = rc; }
void set_bind_arg(bind_arg ba) { _bind_arg = ba; }
void set_spec(rtree_spec* spec)
{
if(_spec)
delete _spec;
_spec = spec;
}
rtree_spec* detach_spec()
{
auto* spec = _spec;
_spec = nullptr;
return spec;
}
};
template<class _bind>
class rtree_entity<_bind, sizeof(void*)>
{
public:
typedef rtree_entity<_bind, sizeof(void*)> myref;
typedef _bind bind_type;
typedef _bind bind_arg;
protected:
rectf _rect;
bind_type _bind_arg = 0;
rtree_spec* _spec = nullptr;
public:
rtree_entity() {}
rtree_entity(bind_arg ba, const rectf& rc): _rect(rc), _bind_arg(ba) {}
~rtree_entity() { set_spec(nullptr); }
const rectf& const_rect() const { return _rect; }
rectf& get_rect() { return _rect; }
bind_arg get_bind_arg() const { return _bind_arg; }
rtree_spec* get_spec() const { return _spec; }
void set_rect(const rectf& rc) { _rect = rc; }
void set_bind_arg(bind_arg ba) { _bind_arg = ba; }
void set_spec(rtree_spec* spec)
{
if(_spec)
delete _spec;
_spec = spec;
}
rtree_spec* detach_spec()
{
auto* spec = _spec;
_spec = nullptr;
return spec;
}
};
template<class _entity>
using rtree_node = _treenode_cpy_wrapper<_entity>;
template<class _rect>
static float calc_enlarge_area(const _rect& rc1, const _rect& rc2, float s)
{
assert(s == rc1.area());
float s2 = rc2.area();
_rect u, d;
union_rect(u, rc1, rc2);
if(intersect_rect(d, rc1, rc2))
return u.area() - s - s2 + d.area();
return u.area() - s - s2;
}
template<class _rect>
static float calc_enlarge_area(const _rect& rc1, const _rect& rc2)
{
return calc_enlarge_area(rc1, rc2, rc1.area());
}
inline float calc_orientation(const float coef[3], const pointf& p)
{
assert(coef);
return coef[0] * p.x + coef[1] * p.y + coef[2];
}
inline void calc_perpendicular_bisector(float coef[3], const pointf& p1, const pointf& p2)
{
assert(coef);
pointf c;
c.x = (p1.x + p2.x) * 0.5f;
c.y = (p1.y + p2.y) * 0.5f;
float d[2];
d[0] = p1.y - p2.y;
d[1] = p1.x - p2.x;
if(abs(d[0]) < 1e-5f) {
coef[0] = 1.f;
coef[1] = -c.x;
coef[2] = 0.f;
}
else if(abs(d[1]) < 1e-5f) {
coef[0] = -c.y;
coef[1] = 1.f;
coef[2] = 0.f;
}
else {
coef[0] = d[1] / d[0];
coef[1] = 1.f;
coef[2] = -c.x * coef[0] - c.y;
}
/* test orientation */
float t = calc_orientation(coef, p1);
if(t > 0.f) {
coef[0] = -coef[0];
coef[1] = -coef[1];
coef[2] = -coef[2];
}
}
template<class _tree>
class rtree_finder
{
public:
typedef _tree mytree;
typedef typename _tree::value value;
typedef typename _tree::iterator iterator;
typedef typename _tree::const_iterator const_iterator;
typedef typename value::bind_arg bind_arg;
protected:
mytree& _mytree;
public:
rtree_finder(mytree& mt): _mytree(mt) {}
iterator find(bind_arg ba, const rectf& rc) const { return find(_mytree.get_root(), ba, rc); }
protected:
iterator find(iterator p, bind_arg ba, const rectf& rc) const
{
assert(p.is_valid());
if(!is_rect_intersected(rc, p->const_rect()))
return iterator(nullptr);
if(p.is_leaf())
return (p->get_bind_arg() == ba) ? p : iterator(nullptr);
for(auto i = p.child(); i.is_valid(); i.to_next()) {
auto f = find(i, ba, rc);
if(f.is_valid())
return f;
}
return iterator(nullptr);
}
};
/*
* Here we implement an algorithm for the bulk loading. For a set of input inserting into
* the rtree, original insert was a waste.
* The algorithm was very similar to the STR insert as the following paper stated:
* http://www.dtic.mil/dtic/tr/fulltext/u2/a324493.pdf
*/
template<int _max_record, int _min_record, class _tree>
class rtree_str_load
{
public:
typedef _tree mytree;
typedef typename _tree::value value;
typedef typename _tree::wrapper wrapper;
typedef typename _tree::iterator iterator;
typedef typename _tree::const_iterator const_iterator;
typedef typename _tree::value value;
typedef typename value::bind_arg bind_arg;
typedef list<value> value_list;
static const int max_record = _max_record;
static const int min_record = _min_record;
struct bulk_node;
typedef list<bulk_node*> bulk_list;
typedef list<wrapper*> wrapper_list;
struct bulk_node:
public value
{
pointf center;
wrapper* assoc_wrapper;
public:
bulk_node(const value& v):
value(v)
{
auto& rc = v.const_rect();
center.x = 0.5f * (rc.left + rc.right);
center.y = 0.5f * (rc.top + rc.bottom);
assoc_wrapper = nullptr;
}
bulk_node(wrapper* w):
value(w->get_ref())
{
auto& v = w->get_ref();
auto& rc = v.const_rect();
center.x = 0.5f * (rc.left + rc.right);
center.y = 0.5f * (rc.top + rc.bottom);
assoc_wrapper = w;
}
};
public:
rtree_str_load(mytree& tr): _mytree(tr) {}
template<class _vsl>
void load(const _vsl& input)
{
wrapper_list in, out;
for(auto& p : input) {
auto* w = new wrapper;
w->born();
auto& v = w->get_ref();
v.set_bind_arg(p.get_bind_arg());
v.set_rect(p.const_rect());
v.set_spec(p.detach_spec());
in.push_back(w);
}
for(;;) {
int s = packing(out, in);
if(s == 1) {
_mytree.set_root(out.front());
return;
}
out.swap(in);
out.clear();
}
}
protected:
mytree& _mytree;
protected:
void set_as_children(wrapper* p, wrapper_list& ch)
{
assert(p);
assert(!ch.empty());
int size = (int)ch.size();
if(size == 1) {
p->acquire_children(wrapper::children(ch.front()));
return;
}
auto i = ch.begin(), j = std::next(i), end = ch.end();
for(; j != end; i = j ++)
wrapper::children::join(*i, *j);
p->acquire_children(wrapper::children(ch.front(), ch.back(), (int)ch.size()));
}
void set_bound_rect(wrapper* p)
{
assert(p);
float l = FLT_MAX, t = FLT_MAX, r = -FLT_MAX, b = -FLT_MAX;
p->for_each([&](wrapper* w) {
assert(w);
auto& v = w->get_ref();
auto& rc = v.get_rect();
l = gs_min(l, rc.left);
t = gs_min(t, rc.top);
r = gs_max(r, rc.right);
b = gs_max(b, rc.bottom);
});
p->born();
auto& v = p->get_ref();
rectf rc;
rc.set_ltrb(l, t, r, b);
v.set_rect(rc);
}
int packing(wrapper_list& output, wrapper_list& input)
{
assert(output.empty());
assert(!input.empty());
int size = (int)input.size();
if(size <= max_record) {
auto* p = new wrapper;
set_as_children(p, input);
set_bound_rect(p);
output.push_back(p);
return 1;
}
list<bulk_node> bulks;
for(auto* w : input)
bulks.push_back(bulk_node(w));
bulks.sort([](const bulk_node& n1, const bulk_node& n2)-> bool {
return n1.center.x < n2.center.x;
});
float rough_slice_count = sqrtf((float)size / max_record);
float rough_slice_size = (float)size / rough_slice_count;
int slice_size = (int)(rough_slice_size + 0.5f);
int full_slice_count = size / slice_size;
int slice_count = (size % slice_size) ? full_slice_count + 1 : full_slice_count;
auto* slices = new list<bulk_node*>[slice_count];
assert(slices);
auto i = bulks.begin(), end = bulks.end();
bool ascend = true;
auto asc_pr = [](const bulk_node* n1, const bulk_node* n2)-> bool { return n1->center.y < n2->center.y; };
auto desc_pr = [](const bulk_node* n1, const bulk_node* n2)-> bool { return n1->center.y > n2->center.y; };
for(int j = 0, k = 0; i != end; ++ i) {
assert(k < slice_count);
slices[k].push_back(&(*i));
if(++ j >= slice_size) {
assert((int)slices[k].size() == slice_size);
ascend ? slices[k].sort(asc_pr) : slices[k].sort(desc_pr);
ascend = !ascend;
j = 0, k ++;
}
}
if(slice_count != full_slice_count) {
assert(full_slice_count + 1 == slice_count);
ascend ? slices[full_slice_count].sort(asc_pr) : slices[full_slice_count].sort(desc_pr);
}
/* join the list */
vector<bulk_node*> sorted;
for(int j = 0; j < slice_count; j ++)
sorted.insert(sorted.end(), slices[j].begin(), slices[j].end());
divide(output, sorted);
delete [] slices;
return (int)output.size();
}
void divide(wrapper_list& output, vector<bulk_node*>& sorted)
{
int size = (int)sorted.size();
for(int i = 0; i < size; i += max_record) {
int left = size - i;
if(left < max_record + min_record) {
if(left <= max_record) {
wrapper_list ch;
for(int j = i; j < size; j ++)
ch.push_back(sorted.at(j)->assoc_wrapper);
auto* w = new wrapper;
set_as_children(w, ch);
set_bound_rect(w);
output.push_back(w);
}
else {
int size1 = left / 2;
int size2 = left - size1;
wrapper_list ch1, ch2;
for(int j = 0; j < size1; j ++)
ch1.push_back(sorted.at(j + i)->assoc_wrapper);
for(int j = i + size1; j < size; j ++)
ch2.push_back(sorted.at(j)->assoc_wrapper);
auto* w1 = new wrapper;
auto* w2 = new wrapper;
set_as_children(w1, ch1);
set_bound_rect(w1);
set_as_children(w2, ch2);
set_bound_rect(w2);
output.push_back(w1);
output.push_back(w2);
}
return;
}
wrapper_list ch;
for(int j = 0; j < max_record; j ++)
ch.push_back(sorted.at(i + j)->assoc_wrapper);
auto* w = new wrapper;
set_as_children(w, ch);
set_bound_rect(w);
output.push_back(w);
}
}
};
template<int _max_record, int _min_record, class _tree>
class rtree_alg_base
{
public:
typedef _tree mytree;
typedef typename _tree::value value;
typedef typename _tree::wrapper wrapper;
typedef typename _tree::iterator iterator;
typedef typename _tree::const_iterator const_iterator;
typedef typename _tree::value value;
typedef typename value::bind_arg bind_arg;
typedef rtree_finder<mytree> finder;
typedef list<value> value_list;
static const int max_record = _max_record;
static const int min_record = _min_record;
public:
rtree_alg_base(mytree& tr): _mytree(tr) {}
protected:
mytree& _mytree;
protected:
static void self_transfer(mytree& mt, iterator i, iterator dp)
{
assert(i.is_valid() && dp.is_valid());
mytree t;
mt.detach(t, i);
mt.attach(t, mt.birth_tail(dp));
}
static void update_subtree_rect(iterator p)
{
assert(p.is_valid() && !p.is_leaf());
auto i = p.child();
rectf rc = i->const_rect();
for(i.to_next(); i.is_valid(); i.to_next())
union_rect(rc, rc, i->const_rect());
p->set_rect(rc);
}
static void update_rect_recursively(iterator p)
{
assert(p.is_valid() && !p.is_leaf());
auto i = p.child();
rectf rc = i->const_rect();
for(i.to_next(); i.is_valid(); i.to_next())
union_rect(rc, rc, i->const_rect());
if(p->const_rect() != rc) {
p->set_rect(rc);
auto g = p.parent();
if(g.is_valid())
update_rect_recursively(g);
}
}
static void update_rect_recursively(iterator p, iterator i)
{
assert(p.is_valid() && i.is_valid() && (i.parent() == p));
rectf rc = p->const_rect();
union_rect(rc, rc, i->const_rect());
if(p->const_rect() != rc) {
p->set_rect(rc);
auto g = p.parent();
if(g.is_valid())
update_rect_recursively(g, p);
}
}
static void collect_leaves(value_list& candidates, iterator i)
{
assert(i.is_valid());
if(i.is_leaf()) {
candidates.push_back(*i);
return;
}
for(auto j = i.child(); j.is_valid(); j.to_next())
collect_leaves(candidates, j);
}
protected:
void split_binary(iterator p, iterator i, iterator j)
{
assert(p.is_valid() && (p.childs() == max_record + 1));
assert(i.is_valid() && j.is_valid() && (i.parent() == p) && (j.parent() == p));
auto g = p.parent();
iterator q;
if(g.is_valid())
q = _mytree.insert_after(p);
else {
mytree mt;
auto r = mt.insert(iterator(nullptr));
r->set_rect(p->const_rect());
auto p1 = mt.birth(r);
auto p2 = mt.birth_tail(r);
mt.attach(_mytree, p1);
mt.swap(_mytree);
p = p1;
q = p2;
}
int max_split = max_record + 1 - min_record;
/* retrieve the split line */
auto c1 = i->const_rect().center();
auto c2 = j->const_rect().center();
float coef[3];
calc_perpendicular_bisector(coef, c1, c2);
/* sort them by signed distance */
typedef multimap<float, iterator> sort_by_sd;
sort_by_sd sbsd;
float muler = 1.f / sqrtf(coef[0] * coef[0] + coef[1] * coef[1]);
for(auto m = p.child(); m.is_valid(); m.to_next()) {
if(m != i && m != j) {
float d = muler * calc_orientation(coef, m->const_rect().center());
sbsd.insert(std::make_pair(d, m));
}
}
/* dump to a random access container */
typedef vector<iterator> sd_queue;
assert(sbsd.size() == max_record - 1);
int divpos = -1, idx = 0;
sd_queue sdq;
sdq.resize(sbsd.size());
for(auto n = sbsd.begin(); n != sbsd.end(); ++ n, ++ idx) {
sdq.at(idx) = n->second;
if((divpos < 0) && (n->first >= 0.f))
divpos = idx;
}
if(divpos < 0)
divpos = 0;
/* clamp */
if(divpos < min_record)
divpos = min_record;
else if(divpos > max_split)
divpos = max_split;
/* transfer from p to q */
self_transfer(_mytree, j, q);
for(auto pos = divpos; pos != (int)sdq.size(); ++ pos)
self_transfer(_mytree, sdq.at(pos), q);
/* update p, q's rect */
update_subtree_rect(p);
update_subtree_rect(q);
}
};
/*
* It's a bit weird that the Guttman's paper said that:
* "PickNext simply chooses any of the remaining entries"
* Does this algorithm actually useful, or maybe I implemented it wrong.
* Use quadratic split in preference.
* plus TODO:
* R* algorithm to be implemented, but undone.
*/
template<int _max_record, int _min_record, class _tree>
class linear_split_alg:
public rtree_alg_base<_max_record, _min_record, _tree>
{
public:
linear_split_alg(mytree& tr):
rtree_alg_base<_max_record, _min_record, _tree>(tr)
{
/* better be static_assert! */
assert((min_record * 2 <= max_record) &&
"min_record should be less than half max_record."
);
}
iterator insert(bind_arg ba, const rectf& rc)
{
if(!_mytree.is_valid()) {
auto i = _mytree.insert(iterator(nullptr));
*i = value(ba, rc);
return i;
}
auto i = find_insert_position(_mytree.get_root());
if(i.is_valid()) {
assert(i.childs() < max_record);
auto j = _mytree.birth_tail(i);
*j = value(ba, rc);
update_rect_recursively(i, j);
return j;
}
i = find_first_leaf(_mytree.get_root());
assert(i.is_valid() && i.is_leaf());
auto p = i.parent();
if(!p.is_valid()) {
assert(i == _mytree.get_root());
auto j = _mytree.birth(i);
auto k = _mytree.birth_tail(i);
*j = *i;
*k = value(ba, rc);
rectf new_rc;
union_rect(new_rc, i->const_rect(), rc);
i->set_bind_arg(0);
i->set_rect(new_rc);
return k;
}
assert(p.childs() == max_record);
/* temporarily insert into p, then split */
auto j = _mytree.birth_tail(p);
*j = value(ba, rc);
update_rect_recursively(p, j);
do { p = adjust_tree(p); }
while(p.is_valid());
return j;
}
void remove(bind_arg ba, const rectf& rc)
{
auto f = finder(_mytree).find(ba, rc);
if(!f.is_valid())
return;
assert(f.is_leaf());
if(f.is_root()) {
_mytree.clear();
return;
}
auto p = f.parent();
assert(p.is_valid());
_mytree.erase(f);
if(p.childs() >= min_record) {
update_rect_recursively(p);
return;
}
value_list candidates;
do { p = condense_tree(candidates, p); }
while(p.is_valid());
reinsert(candidates);
}
protected:
iterator find_insert_position(iterator i)
{
assert(i.is_valid());
if(i.is_leaf())
return iterator(nullptr);
auto j = i.child();
if(j.is_leaf())
return (i.childs() < max_record) ? i : iterator(nullptr);
for(; j.is_valid(); j.to_next()) {
auto r = find_insert_position(j);
if(r.is_valid())
return r;
}
return iterator(nullptr);
}
iterator find_first_leaf(iterator i)
{
assert(i.is_valid());
return i.is_leaf() ? i : find_first_leaf(i.child());
}
iterator find_extreme_u(iterator p)
{
assert(p.is_valid() && !p.is_leaf());
auto i = p.child();
assert(i.is_valid());
float m = i->const_rect().width();
auto r = i;
for(i.to_next(); i.is_valid(); i.to_next()) {
float u = i->const_rect().width();
if(u > m)
r = i, m = u;
}
return r;
}
iterator find_extreme_v_but_not(iterator p, iterator c)
{
assert(p.is_valid() && !p.is_leaf());
assert(c.is_valid() && (c.parent() == p));
iterator r;
float m = -FLT_MAX;
for(auto i = p.child(); i.is_valid(); i.to_next()) {
if(i == c)
continue;
float v = i->const_rect().height();
if(v > m)
r = i, m = v;
}
assert(r.is_valid());
return r;
}
void split(iterator p)
{
assert(p.is_valid() && (p.childs() == max_record + 1));
auto i = find_extreme_u(p);
auto j = find_extreme_v_but_not(p, i);
split_binary(p, i, j);
}
iterator adjust_tree(iterator i)
{
assert(i.is_valid() && !i.is_leaf());
assert(i.childs() == max_record + 1);
auto p = i.parent();
split(i);
if(!p.is_valid())
return iterator(nullptr);
return (p.childs() <= max_record) ? iterator(nullptr) : p;
}
iterator condense_tree(value_list& candidates, iterator i)
{
assert(i.is_valid() && !i.is_leaf());
assert(i.childs() < min_record);
if(i.is_root()) {
if(i.childs() == 1) {
/* height decrease */
mytree t;
_mytree.detach(t, i.child());
_mytree.swap(t);
}
return iterator(nullptr);
}
collect_leaves(candidates, i);
auto p = i.parent();
assert(p.is_valid());
_mytree.erase(i);
if(p.childs() >= min_record) {
update_subtree_rect(p);
return iterator(nullptr);
}
return p;
}
void reinsert(value_list& candidates)
{
if(candidates.empty())
return;
std::for_each(candidates.begin(), candidates.end(), [this](const value& val) {
this->insert(val.get_bind_arg(), val.const_rect());
});
}
};
template<int _max_record, int _min_record, class _tree>
class quadratic_split_alg:
public rtree_alg_base<_max_record, _min_record, _tree>
{
public:
quadratic_split_alg(mytree& tr):
rtree_alg_base<_max_record, _min_record, _tree>(tr)
{
/* better be static_assert! */
assert((min_record * 2 <= max_record) &&
"min_record should be less than half max_record."
);
}
iterator insert(bind_arg ba, const rectf& rc)
{
if(!_mytree.is_valid()) {
auto i = _mytree.insert(iterator(nullptr));
*i = value(ba, rc);
return i;
}
auto i = find_insert_position(_mytree.get_root(), rc);
assert(i.is_valid());
auto p = i.parent();
if(!p.is_valid()) {
assert(i == _mytree.get_root());
auto j = _mytree.birth(i);
auto k = _mytree.birth_tail(i);
*j = *i;
*k = value(ba, rc);
rectf new_rc;
union_rect(new_rc, i->const_rect(), rc);
i->set_bind_arg(0);
i->set_rect(new_rc);
return k;
}
if(p.childs() < max_record) {
auto j = _mytree.birth_tail(p);
*j = value(ba, rc);
update_rect_recursively(p, j);
return j;
}
/* temporarily insert into p, then split */
auto j = _mytree.birth_tail(p);
*j = value(ba, rc);
update_rect_recursively(p, j);
do { p = adjust_tree(p); }
while(p.is_valid());
return j;
}
void remove(bind_arg ba, const rectf& rc)
{
auto f = finder(_mytree).find(ba, rc);
if(!f.is_valid())
return;
assert(f.is_leaf());
if(f.is_root()) {
_mytree.clear();
return;
}
auto p = f.parent();
assert(p.is_valid());
_mytree.erase(f);
if(p.childs() >= min_record) {
update_rect_recursively(p);
return;
}
value_list candidates;
do { p = condense_tree(candidates, p); }
while(p.is_valid());
reinsert(candidates);
}
protected:
iterator find_least_enlargement(iterator i, const rectf& rc)
{
assert(i.is_valid());
auto c = i.child();
auto ret = c;
float enlargement = FLT_MAX;
for(; c.is_valid(); c = c.next()) {
const rectf& oldrc = c->const_rect();
float oldarea = oldrc.area();
rectf fr;
union_rect(fr, oldrc, rc);
float area = fr.area();
float enlarge = area - oldarea;
if(enlarge < enlargement) {
enlargement = enlarge;
ret = c;
}
}
return ret;
}
float find_biggest_enlargement(iterator& i, iterator& j, iterator p)
{
assert(p.is_valid() && !p.is_leaf());
assert(p.childs() == max_record + 1);
iterator f = p.child(), g;
assert(f.next().is_valid());
float m = find_biggest_enlargement(g, f, f.next(), p.last_child());
i = f, j = g;
for(f.to_next(); f != p.last_child(); f.to_next()) {
float n = find_biggest_enlargement(g, f, f.next(), p.last_child());
if(n > m) {
m = n;
i = f, j = g;
}
}
return m;
}
float find_biggest_enlargement(iterator& j, iterator i, iterator from, iterator to)
{
assert(i.is_valid() && from.is_valid() && to.is_valid());
iterator t = from;
float s = i->const_rect().area();
float m = calc_enlarge_area(i->const_rect(), t->const_rect(), s);
j = t;
if(t == to)
return m;
for(t.to_next();; t.to_next()) {
float n = calc_enlarge_area(i->const_rect(), t->const_rect(), s);
if(n > m) { m = n, j = t; }
if(t == to)
break;
}
return m;
}
iterator find_insert_position(iterator i, const rectf& rc)
{
if(i.is_leaf())
return i;
auto trygetch = i.child();
if(trygetch.is_leaf())
return trygetch;
auto j = find_least_enlargement(i, rc);
assert(j.is_valid());
return find_insert_position(j, rc);
}
void split(iterator p)
{
assert(p.is_valid() && (p.childs() == max_record + 1));
iterator i, j;
find_biggest_enlargement(i, j, p);
split_binary(p, i, j);
}
iterator adjust_tree(iterator i)
{
assert(i.is_valid() && !i.is_leaf());
assert(i.childs() == max_record + 1);
auto p = i.parent();
split(i);
if(!p.is_valid())
return iterator(nullptr);
return (p.childs() <= max_record) ? iterator(nullptr) : p;
}
iterator condense_tree(value_list& candidates, iterator i)
{
assert(i.is_valid() && !i.is_leaf());
assert(i.childs() < min_record);
if(i.is_root()) {
if(i.childs() == 1) {
/* height decrease */
mytree t;
_mytree.detach(t, i.child());
_mytree.swap(t);
}
return iterator(nullptr);
}
collect_leaves(candidates, i);
auto p = i.parent();
assert(p.is_valid());
_mytree.erase(i);
if(p.childs() >= min_record) {
update_subtree_rect(p);
return iterator(nullptr);
}
return p;
}
void reinsert(value_list& candidates)
{
if(candidates.empty())
return;
std::for_each(candidates.begin(), candidates.end(), [this](const value& val) {
this->insert(val.get_bind_arg(), val.const_rect());
});
}
};
template<class _ty,
class _alg,
class _wrapper = rtree_node<_ty>,
class _alloc = _tree_allocator<_wrapper>
>
class rtree:
public tree<_ty, _wrapper, _alloc>
{
public:
typedef _ty value;
typedef _wrapper wrapper;
typedef _alloc alloc;
typedef _alg alg;
typedef rtree<_ty, _alg, _wrapper, _alloc> myref;
typedef tree<_ty, _wrapper, _alloc> superref;
typedef typename superref::iterator iterator;
typedef typename superref::const_iterator const_iterator;
typedef typename value::bind_arg bind_arg;
typedef unordered_set<bind_arg> lookup_table;
public:
template<class _querier, class _cont>
int query(const _querier& q, _cont& out) const
{
if(!is_valid())
return 0;
lookup_table lookups;
auto i = get_root();
return query_overlapped(i, q, lookups, out);
}
template<class _cont>
int query(const pointf& p1, const pointf& p2, _cont& out) const
{
if(!is_valid())
return 0;
lookup_table lookups;
rectf rc;
rc.set_by_pts(p1, p2);
auto i = get_root();
return query_overlapped(i, p1, p2, rc, lookups, out);
}
iterator insert(bind_arg ba, const rectf& rc) { return alg(*this).insert(ba, rc); }
void remove(bind_arg ba, const rectf& rc) { alg(*this).remove(ba, rc); }
bool empty() const { return !is_valid(); }
iterator insert_line(bind_arg ba, const pointf& p1, const pointf& p2)
{
rectf rc;
rc.set_by_pts(p1, p2);
iterator i = insert(ba, rc);
assert(i);
i->set_spec(new rtree_spec_line(p1, p2));
return i;
}
template<class _vsl>
void insert(const _vsl& input)
{
if(input.size() == 1) {
auto& p = input.front();
insert(p.get_bind_arg(), p.const_rect());
return;
}
rtree_str_load<alg::max_record, alg::min_record, alg::mytree>(*this).load(input);
}
void tracing() const
{
if(!is_valid())
return;
auto r = get_root();
trace_subtree(r);
trace_layer(r);
}
protected:
template<class _cont>
int query_overlapped(const_iterator i, const rectf& q, lookup_table& lookups, _cont& out) const
{
assert(i.is_valid());
const auto& rc = i->const_rect();
if(!is_rect_intersected(rc, q))
return 0;
if(i.is_leaf()) {
if(lookups.find(i->get_bind_arg()) != lookups.end())
return 0;
lookups.insert(i->get_bind_arg());
out.push_back(i->get_bind_arg());
return 1;
}
int c = 0;
for(auto j = i.child(); j.is_valid(); j = j.next())
c += query_overlapped(j, q, lookups, out);
return c;
}
template<class _cont>
int query_overlapped(const_iterator i, const pointf& q, lookup_table& lookups, _cont& out) const
{
assert(i.is_valid());
const auto& rc = i->const_rect();
if(!rc.in_rect(q))
return 0;
if(i.is_leaf()) {
if(lookups.find(i->get_bind_arg()) != lookups.end())
return 0;
lookups.insert(i->get_bind_arg());
out.push_back(i->get_bind_arg());
return 1;
}
int c = 0;
for(auto j = i.child(); j.is_valid(); j = j.next())
c += query_overlapped(j, q, lookups, out);
return c;
}
template<class _cont>
int query_overlapped(const_iterator i, const pointf& p1, const pointf& p2, const rectf& rc, lookup_table& lookups, _cont& out) const
{
assert(i.is_valid());
if(i.is_leaf()) {
auto* spec = i->get_spec();
bool isovl = spec ? spec->query_overlap(p1, p2) : is_rect_intersected(i->const_rect(), rc);
if(isovl && lookups.find(i->get_bind_arg()) == lookups.end()) {
lookups.insert(i->get_bind_arg());
out.push_back(i->get_bind_arg());
return 1;
}
return 0;
}
if(!is_rect_intersected(i->const_rect(), rc))
return 0;
int c = 0;
for(auto j = i.child(); j.is_valid(); j = j.next())
c += query_overlapped(j, p1, p2, rc, lookups, out);
return c;
}
void trace_layer(const_iterator i) const
{
assert(i.is_valid());
int r = rand() % 256;
int g = rand() % 256;
int b = rand() % 256;
string cr;
cr.format(_t("rgb(%d,%d,%d)"), r, g, b);
trace(_t("@!\n"));
trace(_t("@&strokeColor=%s;\n"), cr.c_str());
trace(_t("@&withArrow=false;\n"));
for(auto j = i; j.is_valid(); j = j.next()) {
const auto& rc = j->const_rect();
trace(_t("@rect %f, %f, %f, %f;\n"), rc.left, rc.top, rc.right, rc.bottom);
}
trace(_t("@@\n"));
}
void trace_subtree(const_iterator i) const
{
assert(i.is_valid());
if(i.is_leaf())
return;
for(auto j = i.child(); j.is_valid(); j = j.next())
trace_subtree(j);
trace_layer(i.child());
}
};
__gslib_end__
#endif
| {
"alphanum_fraction": 0.5199651359,
"avg_line_length": 32.4902654867,
"ext": "h",
"hexsha": "d8f03962889c06dabdc127842baf6c1eadab4e05",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/gslib/rtree.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/gslib/rtree.h",
"max_line_length": 137,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/gslib/rtree.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": 9113,
"size": 36714
} |
#ifndef Single_Pin_Subchannel_h
#define Single_Pin_Subchannel_h
#include <vector>
// Trilinos includes
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_RCP.hpp"
// SCALE includes
#include "Nemesis/harness/DBC.hh"
// vendored includes
#include <gsl/gsl>
namespace enrico {
//===========================================================================//
/*!
* \class Single_Pin_Subchannel
* \brief Solve subchannel flow in single channel.
*
* This class implements a two-equation subchannel model involving
* conservation of energy and axial momentum. No lateral flow is accounted
* for. The model excludes friction momentum losses and any spacer grid
* effects. It is useful for giving qualitatively-correct behavior but
* should not be used for actual analysis.
*/
//===========================================================================//
class Single_Pin_Subchannel {
public:
//@{
//! Typedefs
using RCP_PL = Teuchos::RCP<Teuchos::ParameterList>;
//@}
enum Verbosity { NONE, LOW, HIGH };
private:
// >>> DATA
// Solve parameters
double d_tol;
int d_max_iters;
Verbosity d_verbosity;
// Axial grid
std::vector<double> d_delta_z;
// Channel geometry
double d_area;
// Flow conditions
double d_mdot;
double d_T_inlet;
double d_p_exit;
public:
// Constructor
Single_Pin_Subchannel(RCP_PL& parameters, const std::vector<double>& delta_z);
// Set channel area (cm^2)
void set_channel_area(double area)
{
// Channel area internally is needed in m^2
Expects(area > 0.0);
d_area = 1e-4 * area;
}
// Set mass flow rate (kg/s)
void set_mass_flow_rate(double mdot)
{
Expects(mdot > 0.0);
Expects(mdot < 2.0);
d_mdot = mdot;
}
// Set inlet temperature (K)
void set_inlet_temperature(double T)
{
Expects(T > 0);
Expects(T < 1000);
d_T_inlet = T;
}
// Set exit pressure (Pa)
void set_exit_pressure(double p)
{
Expects(p > 0);
Expects(p < 2.2e7);
d_p_exit = p;
}
// Solve for single subchannel given power distribution
void solve(const std::vector<double>& power,
std::vector<double>& temperature,
std::vector<double>& density);
};
//---------------------------------------------------------------------------//
} // end namespace enrico
//---------------------------------------------------------------------------//
#endif // Single_Pin_Subchannel_h
//---------------------------------------------------------------------------//
// end of Single_Pin_Subchannel.h
//---------------------------------------------------------------------------//
| {
"alphanum_fraction": 0.5601675552,
"avg_line_length": 24.0917431193,
"ext": "h",
"hexsha": "53808424cb2845baccc7ebffeef57eafd9ed10b1",
"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/smrt/Single_Pin_Subchannel.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/smrt/Single_Pin_Subchannel.h",
"max_line_length": 80,
"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/smrt/Single_Pin_Subchannel.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 600,
"size": 2626
} |
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cblas.h>
#include "tests.h"
void
test_syrk (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
float alpha = -1.0f;
float beta = 0.1f;
float A[] = { 0.412f, -0.229f };
int lda = 1;
float C[] = { 0.628f, -0.664f, -0.268f, 0.096f };
int ldc = 2;
float C_expected[] = { -0.106944f, 0.027948f, -0.268f, -0.042841f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1566)");
}
};
};
{
int order = 102;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
float alpha = -1.0f;
float beta = 0.1f;
float A[] = { 0.101f, -0.653f };
int lda = 2;
float C[] = { 0.432f, 0.107f, -0.952f, -0.532f };
int ldc = 2;
float C_expected[] = { 0.032999f, 0.107f, -0.029247f, -0.479609f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1567)");
}
};
};
{
int order = 101;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
float alpha = 1.0f;
float beta = 0.1f;
float A[] = { 0.79f, 0.595f };
int lda = 2;
float C[] = { 0.257f, 0.183f, -0.021f, -0.053f };
int ldc = 2;
float C_expected[] = { 0.6498f, 0.48835f, -0.021f, 0.348725f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1568)");
}
};
};
{
int order = 102;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
float alpha = 1.0f;
float beta = 0.1f;
float A[] = { -0.181f, -0.654f };
int lda = 1;
float C[] = { -0.4f, 0.615f, 0.147f, -0.163f };
int ldc = 2;
float C_expected[] = { -0.007239f, 0.615f, 0.133074f, 0.411416f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1569)");
}
};
};
{
int order = 101;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
float alpha = 0.0f;
float beta = -1.0f;
float A[] = { -0.191f, 0.584f };
int lda = 1;
float C[] = { -0.719f, -0.681f, -0.003f, 0.544f };
int ldc = 2;
float C_expected[] = { 0.719f, -0.681f, 0.003f, -0.544f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1570)");
}
};
};
{
int order = 102;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
float alpha = 0.0f;
float beta = -1.0f;
float A[] = { 0.788f, 0.041f };
int lda = 2;
float C[] = { 0.029f, 0.365f, 0.739f, -0.769f };
int ldc = 2;
float C_expected[] = { -0.029f, -0.365f, 0.739f, 0.769f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1571)");
}
};
};
{
int order = 101;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
float alpha = -0.3f;
float beta = -1.0f;
float A[] = { 0.733f, 0.678f };
int lda = 2;
float C[] = { -0.941f, 0.96f, 0.07f, -0.295f };
int ldc = 2;
float C_expected[] = { 0.779813f, 0.96f, -0.219092f, 0.157095f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1572)");
}
};
};
{
int order = 102;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
float alpha = -0.3f;
float beta = -1.0f;
float A[] = { -0.87f, 0.675f };
int lda = 1;
float C[] = { -0.602f, -0.432f, -0.984f, 0.384f };
int ldc = 2;
float C_expected[] = { 0.37493f, 0.608175f, -0.984f, -0.520687f };
cblas_ssyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], flteps, "ssyrk(case 1573)");
}
};
};
{
int order = 101;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
double alpha = 0.1;
double beta = -0.3;
double A[] = { 0.169, -0.875 };
int lda = 1;
double C[] = { 0.159, 0.277, 0.865, 0.346 };
int ldc = 2;
double C_expected[] = { -0.0448439, -0.0978875, 0.865, -0.0272375 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1574)");
}
};
};
{
int order = 102;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
double alpha = 0.1;
double beta = -0.3;
double A[] = { 0.536, -0.725 };
int lda = 2;
double C[] = { 0.154, -0.445, -0.841, -0.91 };
int ldc = 2;
double C_expected[] = { -0.0174704, -0.445, 0.21344, 0.3255625 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1575)");
}
};
};
{
int order = 101;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
double alpha = 0;
double beta = -1;
double A[] = { -0.07, 0.8 };
int lda = 2;
double C[] = { 0.823, -0.88, -0.136, 0.793 };
int ldc = 2;
double C_expected[] = { -0.823, 0.88, -0.136, -0.793 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1576)");
}
};
};
{
int order = 102;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
double alpha = 0;
double beta = -1;
double A[] = { -0.058, 0.649 };
int lda = 1;
double C[] = { -0.187, 0.294, -0.004, -0.933 };
int ldc = 2;
double C_expected[] = { 0.187, 0.294, 0.004, 0.933 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1577)");
}
};
};
{
int order = 101;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
double alpha = 1;
double beta = -1;
double A[] = { 0.263, -0.289 };
int lda = 1;
double C[] = { 0.554, -0.679, 0.993, 0.758 };
int ldc = 2;
double C_expected[] = { -0.484831, -0.679, -1.069007, -0.674479 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1578)");
}
};
};
{
int order = 102;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
double alpha = 1;
double beta = -1;
double A[] = { -0.265, -0.837 };
int lda = 2;
double C[] = { -0.994, 0.967, -0.34, -0.069 };
int ldc = 2;
double C_expected[] = { 1.064225, -0.745195, -0.34, 0.769569 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1579)");
}
};
};
{
int order = 101;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
double alpha = -0.3;
double beta = 1;
double A[] = { -0.464, 0.394 };
int lda = 2;
double C[] = { -0.45, -0.447, 0.649, 0.055 };
int ldc = 2;
double C_expected[] = { -0.5145888, -0.447, 0.7038448, 0.0084292 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1580)");
}
};
};
{
int order = 102;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
double alpha = -0.3;
double beta = 1;
double A[] = { 0.815, 0.168 };
int lda = 1;
double C[] = { 0.817, -0.957, -0.395, -0.382 };
int ldc = 2;
double C_expected[] = { 0.6177325, -0.998076, -0.395, -0.3904672 };
cblas_dsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[i], C_expected[i], dbleps, "dsyrk(case 1581)");
}
};
};
{
int order = 101;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
float alpha[2] = {0.0f, 0.0f};
float beta[2] = {-0.3f, 0.1f};
float A[] = { 0.447f, -0.507f, -0.425f, 0.701f };
int lda = 1;
float C[] = { 0.16f, -0.245f, 0.922f, -0.437f, 0.24f, 0.008f, -0.095f, 0.749f };
int ldc = 2;
float C_expected[] = { -0.0235f, 0.0895f, -0.2329f, 0.2233f, 0.24f, 0.008f, -0.0464f, -0.2342f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1582) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1582) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
float alpha[2] = {0.0f, 0.0f};
float beta[2] = {-0.3f, 0.1f};
float A[] = { -0.421f, -0.435f, -0.914f, -0.493f };
int lda = 2;
float C[] = { -0.761f, -0.38f, 0.043f, -0.999f, 0.779f, 0.238f, 0.082f, 0.394f };
int ldc = 2;
float C_expected[] = { 0.2663f, 0.0379f, 0.043f, -0.999f, -0.2575f, 0.0065f, -0.064f, -0.11f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1583) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1583) imag");
};
};
};
{
int order = 101;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
float alpha[2] = {-1.0f, 0.0f};
float beta[2] = {-0.3f, 0.1f};
float A[] = { 0.827f, -0.896f, 0.417f, 0.865f };
int lda = 2;
float C[] = { -0.349f, -0.31f, 0.972f, 0.794f, -0.906f, -0.595f, -0.089f, -0.333f };
int ldc = 2;
float C_expected[] = { 0.254587f, 1.54008f, -1.4909f, -0.482723f, -0.906f, -0.595f, 0.634336f, -0.63041f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1584) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1584) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
float alpha[2] = {-1.0f, 0.0f};
float beta[2] = {-0.3f, 0.1f};
float A[] = { 0.607f, 0.747f, -0.889f, 0.333f };
int lda = 1;
float C[] = { 0.244f, 0.564f, 0.009f, 0.578f, -0.827f, 0.558f, -0.337f, 0.731f };
int ldc = 2;
float C_expected[] = { 0.05996f, -1.05166f, 0.009f, 0.578f, 0.980674f, 0.211852f, -0.651432f, 0.339074f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1585) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1585) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
float alpha[2] = {1.0f, 0.0f};
float beta[2] = {0.0f, 1.0f};
float A[] = { 0.784f, -0.281f, -0.88f, 0.479f };
int lda = 1;
float C[] = { 0.491f, 0.531f, 0.805f, -0.097f, 0.728f, 0.674f, -0.705f, -0.754f };
int ldc = 2;
float C_expected[] = { 0.004695f, 0.050392f, 0.805f, -0.097f, -1.22932f, 1.35082f, 1.29896f, -1.54804f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1586) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1586) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
float alpha[2] = {1.0f, 0.0f};
float beta[2] = {0.0f, 1.0f};
float A[] = { 0.272f, -0.146f, 0.155f, 0.038f };
int lda = 2;
float C[] = { 0.533f, -0.41f, -0.904f, 0.301f, -0.836f, 0.57f, -0.374f, -0.293f };
int ldc = 2;
float C_expected[] = { 0.462668f, 0.453576f, -0.253292f, -0.916294f, -0.836f, 0.57f, 0.315581f, -0.36222f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1587) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1587) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
float alpha[2] = {0.0f, 1.0f};
float beta[2] = {-1.0f, 0.0f};
float A[] = { -0.055f, -0.127f, -0.896f, -0.625f };
int lda = 2;
float C[] = { -0.619f, 0.511f, -0.877f, 0.557f, -0.801f, -0.437f, -0.922f, 0.332f };
int ldc = 2;
float C_expected[] = { 0.60503f, -0.524104f, -0.877f, 0.557f, 0.652833f, 0.406905f, -0.198f, 0.080191f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1588) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1588) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
float alpha[2] = {0.0f, 1.0f};
float beta[2] = {-1.0f, 0.0f};
float A[] = { -0.528f, 0.759f, -0.079f, 0.952f };
int lda = 1;
float C[] = { 0.775f, 0.855f, 0.786f, 0.525f, 0.85f, 0.044f, 0.658f, 0.947f };
int ldc = 2;
float C_expected[] = { 0.026504f, -1.1523f, -0.223383f, -1.20586f, 0.85f, 0.044f, -0.507584f, -1.84706f };
cblas_csyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], flteps, "csyrk(case 1589) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], flteps, "csyrk(case 1589) imag");
};
};
};
{
int order = 101;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
double alpha[2] = {1, 0};
double beta[2] = {1, 0};
double A[] = { -0.049, -0.687, -0.434, 0.294 };
int lda = 1;
double C[] = { 0.937, -0.113, 0.796, 0.293, 0.876, -0.199, -0.757, -0.103 };
int ldc = 2;
double C_expected[] = { 0.467432, -0.045674, 1.019244, 0.576752, 0.876, -0.199, -0.65508, -0.358192 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1590) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1590) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int trans = 111;
int N = 2;
int K = 1;
double alpha[2] = {1, 0};
double beta[2] = {1, 0};
double A[] = { 0.359, -0.364, 0.926, -0.69 };
int lda = 2;
double C[] = { 0.306, 0.249, 0.28, 0.229, 0.866, 0.092, 0.886, -0.283 };
int ldc = 2;
double C_expected[] = { 0.302385, -0.012352, 0.28, 0.229, 0.947274, -0.492774, 1.267376, -1.56088 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1591) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1591) imag");
};
};
};
{
int order = 101;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {0, 0};
double A[] = { 0.607, 0.555, -0.85, 0.831 };
int lda = 2;
double C[] = { 0.069, 0.368, 0.551, -0.912, -0.243, -0.063, -0.924, 0.192 };
int ldc = 2;
double C_expected[] = { -0.0855042, -0.1960886, 0.2898798, -0.1075156, -0.243, -0.063, 0.1316883, 0.4270039 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1592) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1592) imag");
};
};
};
{
int order = 102;
int uplo = 121;
int trans = 112;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {0, 0};
double A[] = { 0.427, 0.86, -0.136, 0.002 };
int lda = 1;
double C[] = { 0.398, -0.47, 0.011, -0.547, -0.106, 0.016, 0.681, 0.246 };
int ldc = 2;
double C_expected[] = { 0.0937373, -0.2760591, 0.011, -0.547, 0.0295482, 0.0288526, -0.0054932, 0.0020124 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1593) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1593) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {1, 0};
double A[] = { 0.718, 0.023, 0.355, -0.492 };
int lda = 1;
double C[] = { -0.637, -0.727, -0.475, -0.776, 0.802, -0.55, -0.837, 0.222 };
int ldc = 2;
double C_expected[] = { -0.7948013, -0.6854089, -0.475, -0.776, 0.7566473, -0.4198521, -0.7672563, 0.3151921 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1594) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1594) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int trans = 111;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {1, 0};
double A[] = { 0.209, 0.139, -0.202, -0.223 };
int lda = 2;
double C[] = { -0.695, 0.524, 0.212, -0.88, -0.752, 0.291, 0.684, -0.124 };
int ldc = 2;
double C_expected[] = { -0.7081182, 0.5090054, 0.2228348, -0.8587166, -0.752, 0.291, 0.6776683, -0.1519201 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1595) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1595) imag");
};
};
};
{
int order = 101;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {1, 0};
double A[] = { -0.365, -0.624, 0.632, 0.348 };
int lda = 2;
double C[] = { 0.877, 0.927, -0.377, 0.967, 0.008, 0.292, -0.779, 0.794 };
int ldc = 2;
double C_expected[] = { 0.9082933, 0.7647289, -0.377, 0.967, 0.0641972, 0.4470636, -0.9064832, 0.6898704 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1596) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1596) imag");
};
};
};
{
int order = 102;
int uplo = 122;
int trans = 112;
int N = 2;
int K = 1;
double alpha[2] = {-0.3, 0.1};
double beta[2] = {1, 0};
double A[] = { -0.067, -0.586, 0.208, 0.331 };
int lda = 1;
double C[] = { 0.584, -0.454, 0.93, 0.782, 0.489, -0.278, 0.081, -0.919 };
int ldc = 2;
double C_expected[] = { 0.6778197, -0.5114479, 0.8903975, 0.8432225, 0.489, -0.278, 0.0871195, -0.9669385 };
cblas_zsyrk(order, uplo, trans, N, K, alpha, A, lda, beta, C, ldc);
{
int i;
for (i = 0; i < 4; i++) {
gsl_test_rel(C[2*i], C_expected[2*i], dbleps, "zsyrk(case 1597) real");
gsl_test_rel(C[2*i+1], C_expected[2*i+1], dbleps, "zsyrk(case 1597) imag");
};
};
};
}
| {
"alphanum_fraction": 0.5083341504,
"avg_line_length": 26.6989528796,
"ext": "c",
"hexsha": "21531d526b94751fe27f2a218571ea81b395040f",
"lang": "C",
"max_forks_count": 224,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z",
"max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "utdsimmons/ohpc",
"max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_syrk.c",
"max_issues_count": 1096,
"max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "utdsimmons/ohpc",
"max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_syrk.c",
"max_line_length": 114,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_syrk.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z",
"num_tokens": 9224,
"size": 20398
} |
// The first test on 25/3/80 contains no information about
// infection because ewes had not been exposed to the donors at this time
// The first test date is end of March which we consider start of April
// Time is counted in months at the start of each month, so month 0 is 1 April 1980
// A seroconversion observed at the start of month m means the seroconversion
// occurred before the start of month m, eg in month m-1 or before
// Sheep are assumed to be born on the 1st April of each year, ie months 0, 12 and 24
// A sheep's last month is the last month it was tested. We assume that it is immediately removed
// This means that a +ve sheep is not infectious on its last_month
// We assume, however, that a sheep is potentially infected and infectious at most one month prior to
// its first positive month
// Donor sheep 72 is assumed infectious at the start, because its dam tests positive within 3 months of birth
// Donor 22 is assumed to be latent at the start due to it being removed after 3.5 years,
// so it may have just been infected at the start
#include <model.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include "sheep_data.h"
#define P_inv_gamma gsl_cdf_gamma_Pinv // invverse cumulative gamma dist
#define P_inc_gamma gsl_sf_gamma_inc_P // regularised incomplete Gamma function
#define lngamma gsl_sf_lngamma // ln Gamma function
#define NUMBER_DONORS 2
#define NUMBER_SHEEP 45
#define INTRO_MONTHS 3
#define V0 11
const uint intro_months[] = {0, 12, 24};
typedef struct {
double a;
double *lambda;
double *Lambda;
double *b;
double *B;
double **W4;
double *W2;
} parameters_t;
double u(int, int, double*);
double lngexpan(double, double, int*);
double ln_inc_gamma_star(double, double);
double w(int, int, int, int, parameters_t*);
double Prob_seroconvert(int, int, parameters_t*);
extern double R0(double, double, double, int, double*);
void Variables(struct variables *V)
{
int i;
Var(V, 0, "month");
Var(V, 1, "expected number infected");
Var(V, 2, "expected number infectious");
Var(V, 3, "cumulative seroconversions");
Var(V, 4, "seroconversion rate");
Var(V, 5, "expected number seroconverted");
Var(V, 6, "cumulative field infected");
Var(V, 7, "cumulative housed infected");
Var(V, 8, "cumulative poor condition infected");
Var(V, 9, "cumulative total infected");
Var(V, 10, "infections");
for (i = 0; i < INTRO_MONTHS+1; i++)
Var(V, V0+i, "P_seropos");
}
void Parameters(int trt, int ind, double *p, struct parameterset *Q)
{
Par(Q, 0, Real, "beta_{field}", Exponential, 0.02);
Par(Q, 1, Real, "beta_{housed}", Gamma, 2.0, 0.1);
Par(Q, 2, Real, "a", Uniform, 1.e-3, 100.);
Par(Q, 3, Real, "k1", Exponential, 24.0);
Par(Q, 5, Real, "L", Uniform, 0., 60.);
Par(Q, 7, Int, "tau", Uniform, 1, 4);
Par(Q, 8, Real, "beta_{pc}", Gamma, 2.0, 1.0);
Par(Q, 10, Real, "beta_{housed}/beta_{field}", Der);
Par(Q, 12, Real, "E[inf_{field}]", Der);
Par(Q, 13, Real, "E[inf_{housed}]", Der);
Par(Q, 14, Real, "E[inf]", Der);
Par(Q, 16, Real, "s_{median,1}", Der);
Par(Q, 17, Real, "s_{median,2}", Der);
Par(Q, 18, Real, "s_{95,1}", Der);
Par(Q, 19, Real, "s_{95,2}", Der);
}
int Model(const uint trt, const uint ind, const uint nmonths, double *p, double **V, TimePoints *Data)
{
int i, j, n, m;
double *Einf_field, *Einf_housed;
double **p_seropos = V, pinf;
double beta_field = p[0];
double beta_housed = p[1];
double beta_pc = p[8];
double S_a = p[2];
double S_b1 = S_a/p[3];
double S_b2 = S_a/p[3];
double L = p[5];
int tau = lrint(p[7]);
double *num_infectious = doublevector(nmonths);
double *num_infected = doublevector(nmonths);
// double *num_seroconverted = doublevector(nmonths);
double *L_cdf = doublevector(nmonths);
// double *S_cdf = doublevector(nmonths);
parameters_t pars;
pars.Lambda = doublevector(nmonths);
pars.lambda = doublevector(nmonths);
pars.B = doublevector(nmonths);
pars.b = doublevector(nmonths);
pars.W4 = doublematrix(nmonths, nmonths);
pars.W2 = doublevector(nmonths);
pars.a = S_a;
// cumulative distribution of latent period
for (m = 0; m < nmonths; m++) {
// L_cdf[m] = gsl_cdf_gamma_P((double)m, L_a, 1./L_b);
L_cdf[m] = (m < L? 0: 1);
// S_cdf[m] = gsl_cdf_gamma_P((double)m, pars.a, 1./pars.b);
}
// calculate expected number of infectious ewes and force of infection, lambda
// the two donor ewes and the lamb are infected at start of experiment
int donors_lamb[] = {0, 1, 44};
for (i = 0; i < NUMBER_DONORS+1; i++) {
j = donors_lamb[i];
for (m = sheep_intro_month[j]; m < sheep_last_month[j]; m++) {
num_infected[m]++;
if (j == 0)
num_infectious[m]++;
else
num_infectious[m] += L_cdf[m-sheep_intro_month[j]];
}
}
for (m = 0; m < nmonths; m++) {
// calculate force of infection
// ewes are housed for tau months (1 to 4) ending in March
if (21 <= m && m < 24)
// transmission rate for poor conditioned housed ewes in winter 1982
pars.lambda[m] = num_infectious[m]*beta_pc;
else if (4-tau <= (m+4)%12 && (m+4)%12 <= 3)
// transmission rate for housed ewes in winter
pars.lambda[m] = num_infectious[m]*beta_housed;
else
// field transmission rate
pars.lambda[m] = num_infectious[m]*beta_field;
// cumulative lambda used for prob of uninfected
if (m > 1)
pars.Lambda[m] = pars.Lambda[m-1]+pars.lambda[m-1];
for (j = NUMBER_DONORS; j < NUMBER_SHEEP; j++)
if (use_sheep[j] && negatives[j] > ind && sheep_intro_month[j] <= m && m < sheep_last_month[j]) {
// probability this sheep is infected during this month m
pinf = (1.-exp(-pars.lambda[m]))*u(sheep_intro_month[j], m, pars.Lambda);
for (n = m+1; n < sheep_last_month[j]; n++) {
num_infected[n] += pinf;
num_infectious[n] += pinf*L_cdf[n-1-m];
// num_seroconverted[i] += pinf*S_cdf[n-1-m];
}
}
}
// monthly seroconversion rates
for (m = 0; m < nmonths; m++)
if (m == 22)
// increased seroconversion rate in winter 1982 due to poor condition and
pars.b[m] = S_b2;
else
pars.b[m] = S_b1;
// cumulative seroconversion rate
for (m = 1; m < nmonths; m++)
pars.B[m] = pars.B[m-1] + pars.b[m-1];
// W4 and W2 per month
for (m = 0; m < nmonths; m++) {
for (n = 0; n < m; n++)
pars.W4[n][m] = w(n, m, n+1, m+1, &pars)
- w(n, m, n+1, m, &pars)
- w(n, m, n, m+1, &pars)
+ w(n, m, n, m, &pars);
pars.W2[m] = w(m, m, m, m+1, &pars);
}
// calculate the probability that a randomly selected sheep seroconverts in month m
for (j = 0; j < INTRO_MONTHS; j++)
for (m = intro_months[j]; m < nmonths; m++)
p_seropos[m][V0+j] = Prob_seroconvert(intro_months[j], m, &pars);
// 3 sheep were born in month 12, were removed in month 20 and retested in month 36, all were negative
j = 13;
// save lambda
double *lambda_s = doublevector(nmonths);
double *Lambda_s = doublevector(nmonths);
for (m = sheep_last_month[j]; m < sheep_last_test_month[j]; m++) {
lambda_s[m] = pars.lambda[m];
Lambda_s[m] = pars.Lambda[m];
}
// set lambda=0 for the months from removal (last_month) until testing and recalculate Lambda
for (m = sheep_last_month[j]; m < sheep_last_test_month[j]; m++)
pars.lambda[m] = 0;
for (m = sheep_last_month[j]+1; m < sheep_last_test_month[j]; m++)
pars.Lambda[m] = pars.Lambda[m-1];
// recalculate prob of seroconverting for these 3 sheep
for (m = sheep_last_month[j]; m < sheep_last_test_month[j]; m++) {
for (n = sheep_last_month[j]; n < m; n++)
pars.W4[n][m] = w(n, m, n+1, m+1, &pars)
- w(n, m, n+1, m, &pars)
- w(n, m, n, m+1, &pars)
+ w(n, m, n, m, &pars);
pars.W2[m] = w(m, m, m, m+1, &pars);
}
for (m = sheep_intro_month[j]; m < sheep_last_test_month[j]; m++)
p_seropos[m][V0+sheep_var[j]] = Prob_seroconvert(sheep_intro_month[j], m, &pars);
// restore lambda
for (m = sheep_last_month[j]; m < sheep_last_test_month[j]; m++) {
pars.lambda[m] = lambda_s[m];
pars.Lambda[m] = Lambda_s[m];
}
free(lambda_s);
free(Lambda_s);
/******************** OUTPUT ***********************/
if (Data->mode == OUTPUT) {
for (m = 0; m < nmonths; m++)
V[m][0] = m;
// expected number of infected sheep in month m
for (m = 0; m < nmonths-1; m++)
V[m][1] = num_infected[m];
V[nmonths-1][1] = V[nmonths-2][1];
// expected number of infectious sheep in month m
for (m = 0; m < nmonths-1; m++)
V[m][2] = num_infectious[m];
V[nmonths-1][2] = V[nmonths-2][2];
// expected number of seroconverted sheep in month m
// for (m = 0; m < nmonths-1; m++)
// V[m][5] = num_seroconverted[m];
// V[nmonths-1][5] = V[nmonths-2][5];
// expected number of seroconversions by the end of each month m
// (which is the start of month m+1)
// done this way because earlier observed seroconversions are recorded at start of month
V[0][4] = 0;
for (j = NUMBER_DONORS; j < NUMBER_SHEEP; j++)
if (use_sheep[j] && negatives[j] > ind)
for (m = sheep_intro_month[j]; m < sheep_last_month[j]; m++)
V[m+1][4] += p_seropos[m][V0+sheep_var[j]];
// cumulative expected number of seroconversions by end of month m
// (which is the start of month m+1)
V[0][3] = 0;
for (m = 0; m <nmonths-1; m++)
V[m+1][3] = V[m][3]+V[m+1][4];
// expected number of infection events in each month m partitioned by route
Einf_field = doublevector(nmonths);
Einf_housed = doublevector(nmonths);
for (j = NUMBER_DONORS; j < NUMBER_SHEEP; j++)
if (use_sheep[j] && negatives[j] > ind) {
for (m = sheep_intro_month[j]; m < sheep_last_month[j]; m++)
if (4-tau <= (m+4)%12 && (m+4)%12 <= 3)
Einf_housed[m] += (1.-exp(-pars.lambda[m]))*u(sheep_intro_month[j], m , pars.Lambda);
else
Einf_field[m] += (1.-exp(-pars.lambda[m]))*u(sheep_intro_month[j], m, pars.Lambda);
}
for (m = 0; m < nmonths; m++)
V[m][10] = Einf_field[m]+Einf_housed[m];
for (m = 1; m < nmonths; m++) {
Einf_field[m] += Einf_field[m-1];
Einf_housed[m] += Einf_housed[m-1];
}
for (m = 0; m < nmonths; m++) {
V[m][6] = Einf_field[m];
V[m][7] = Einf_housed[m];
V[m][9] = V[m][6]+V[m][7];
}
free(Einf_field);
free(Einf_housed);
}
free(L_cdf);
// free(S_cdf);
free(num_infected);
free(num_infectious);
// free(num_seroconverted);
free(pars.lambda);
free(pars.Lambda);
free(pars.b);
free(pars.B);
free(pars.W4[0]);
free(pars.W4);
free(pars.W2);
return SUCCESS;
}
double P_pos(int j, int s1, int s2, double **V)
{
int m;
double sum = 0;
for (m = s1; m < s2; m++)
sum += V[m][V0+sheep_var[j]];
return sum;
}
double logLikelihood(const uint trt, const uint ind, const double *p, double **V, const TimePoints *Data)
{
int j, pos_idx;
double lnL = 0;
for (j = NUMBER_DONORS; j < NUMBER_SHEEP; j++)
if (use_sheep[j] && negatives[j] > ind) {
pos_idx = sheep_pos_index[j];
if (pos_idx > 0)
// ewe is first seropositive at start of month m, therefore it seroconverted
// sometime in the months from the last test to the month prior to seroconverting
lnL += log(P_pos(j, lrint(Data->t[pos_idx-1][0]), sheep_pos_month[j], V));
else
// ewe never seroconverted
lnL += log(1. - P_pos(j, sheep_intro_month[j], sheep_last_test_month[j], V));
}
return lnL;
}
void OutputModel(int trt, int ind, double *Output, double *V)
{
int i;
for (i = 1; i < V0+INTRO_MONTHS+1; i++)
Output[i] = V[i];
}
void OutputData(int trt, int ind, double *Output, double *Var, double *Data, uint *value, int index)
{
Output[3] = Data[47];
Output[4] = Data[48];
Output[5] = Data[49];
// remove dam to lamb infection from data to match model output
if (lrint(Data[0]) == 3)
Output[4] = 0;
if (lrint(Data[0]) >= 3)
Output[3] -= 1;
}
int f0(int trt, int ind, double *x, double *y, double *p, TimePoints *TP)
{
// R0 2 month housed
int i, n = 2;
if (x == NULL) return n;
for (i = 0; i < n; i++) {
x[i] = 100*i+1;
y[i] = R0(x[i], 2., 0.1, 5, p);
}
return n;
}
int f1(int trt, int ind, double *x, double *y, double *p, TimePoints *TP)
{
// R0 0 months housed
int i, n = 2;
if (x == NULL) return n;
for (i = 0; i < n; i++) {
x[i] = 100*i+1;
y[i] = R0(x[i], 0., 0.1, 5, p);
}
return n;
}
int f2(int trt, int ind, double *x, double *y, double *p, TimePoints *TP)
{
// R0 for 25 sheep housed for different durations
int i, n = 14;
if (x == NULL) return n;
for (i = 0; i < n; i++) {
x[i] = i;
y[i] = R0(25., x[i]*12./365., 0.1, 5, p);
}
return n;
}
int f3(int trt, int ind, double *x, double *y, double *p, TimePoints *TP)
{
// CDF of normal seroconversion period
int i, n = 1000;
if (x == NULL) return n;
double S_a = p[2];
double S_k1 = p[3];
for (i = 0; i < n; i++) {
x[i] = (double)i/20.;
// y[i] = gsl_ran_gamma_pdf(x[i], a, 1./b);
y[i] = gsl_cdf_gamma_P(x[i], S_a, S_k1);
}
return n;
}
void function_list(functions_t *F)
{
F->n_func = 3;
F->function_list = (function_ptr*) malloc(F->n_func*sizeof(function_ptr));
F->function_list[0] = f0;
F->function_list[1] = f1;
F->function_list[2] = f2;
// F->function_list[3] = f3;
}
double u(int m0, int m, double *Lambda)
{
// The probability a sheep is uninfected at the start of month m
// given it was introduced into the flock in month m0
if (m == m0)
return 1;
else
return exp(-Lambda[m]+Lambda[m0]);
}
double lngseries(double a, double x, int *ierr)
{
double giant = HUGE_VAL/1000., eps = 1e-15;
double t = 1./a, v = t;
double p, q, lnigam;
int k = 0;
*ierr = 0;
while ((fabs(t/v) > eps) && *ierr == 0) {
p = (a+k)/(a+k+1);
q = k+1;
t *= -x*p/q;
v += t;
k += 1;
if (t > giant)
*ierr = 1;
}
if (*ierr == 0)
if (lngamma(a) < log(giant))
lnigam = log(v)-lngamma(a);
else {
lnigam = 0;
*ierr = 1;
}
else {
lnigam = 0;
*ierr = 1;
}
return lnigam;
}
double lngexpan(double a, double x, int *ierr)
{
double giant = HUGE_VAL/1000., eps = 1e-15;
double t = 1, v = t;
double p, lnigam;
int k = 0;
*ierr = 0;
if (x > log(giant)) {
*ierr = 1;
return 0;
}
while ((fabs(t/v) > eps) && *ierr == 0) {
p = 1-a+k;
t *= p/x;
v += t;
k += 1;
if (t > giant)
*ierr = 1;
}
if (*ierr == 0)
if (lngamma(a) < log(giant))
lnigam = log(v)+x-log(x)-lngamma(a);
else {
lnigam = 0;
*ierr = 1;
}
else {
lnigam = 0;
*ierr = 1;
}
return lnigam;
}
double ln_inc_gamma_star(double a, double z)
{
int ierr;
double lnigam;
if (z < -50) {
lnigam = lngexpan(a, -z, &ierr);
if (ierr != 0)
printf("error1\n");
}
else {
lnigam = lngseries(a, z, &ierr);
if (ierr != 0)
printf("error2\n");
}
return lnigam;
}
double w(int n, int m, int t, int s, parameters_t *p)
{
double a = p->a;
double l = p->lambda[n];
double b = p->b[n];
double r = (b-l)/b;
double Z, z, v;
if (m-n <= 1 && t == m && s == m)
return 0;
Z = p->B[m] - p->B[n] + b*(n-t) + p->b[m]*(s-m);
if (Z == 0)
return 0;
z = r*Z;
if (z <= 0)
v = exp(a*log(Z) - l*Z/b + ln_inc_gamma_star(a, z));
else
v = exp(-a*log(r) - l*Z/b + log(P_inc_gamma(a, z)));
return exp(-l*(t-n))*(v - P_inc_gamma(a, Z));
}
double Prob_seroconvert(int m0, int m, parameters_t *p)
{
int n;
double P_m = 0;
for (n = m0; n < m; n++)
P_m += u(m0, n, p->Lambda)*p->W4[n][m];
P_m -= u(m0, m, p->Lambda)*p->W2[m];
return min(max(0, P_m), 1);
}
void Residual(int trt, int ind, double *R, double *V, double *p, double *Data, uint *value)
{
R[3] = V[3]-Data[47];
R[4] = V[4]-Data[48];
}
void DerivedParameters(int trt, int ind, int nmonths, double *p, double **V, TimePoints *Data)
{
// int i, j, m;
// double pinf;
double beta_field = p[0];
double beta_housed = p[1];
double S_a = p[2];
double S_b1 = S_a/p[3];
double S_b2 = S_a/p[3];
// double L_mu = p[5];
// double L_sd = p[6];
// double *num_infectious = doublevector(nmonths);
// double *Lambda = doublevector(nmonths);
// double *lambda = doublevector(nmonths);
// double *B = doublevector(nmonths);
// double *b = doublevector(nmonths);
// double *L_cdf = doublevector(nmonths);
p[10] = beta_housed/beta_field;
p[16] = P_inv_gamma(0.5, S_a, 1./S_b1);
p[17] = P_inv_gamma(0.5, S_a, 1./S_b2);
p[18] = P_inv_gamma(0.95, S_a, 1./S_b1);
p[19] = P_inv_gamma(0.95, S_a, 1./S_b2);
return;
// p[6] = gsl_cdf_exponential_Pinv(0.5, mu);
// p[22] = gsl_cdf_exponential_Pinv(0.5, mu2);
// p[15] = gsl_cdf_exponential_Pinv(0.025, mu);
// p[16] = gsl_cdf_exponential_Pinv(0.975, mu);
// p[20] = 6./16.*(1.-exp(-(0.75*beta_field)*(fmax(0, 4*12-L_mu))));
// p[23] = 6./16.*(1.-exp(-(0.25*beta_housed)*(fmax(0, 4*12-L_mu))));
// for (m = 0; m < nmonths; m++)
// L_cdf[m] = (m < L_mu? 0: 1);
// // calculate expected number of infectious ewes and force of infection, lambda
// // the two donor sheep are infectious at start of experiment
// for (j = 0; j < 2; j++)
// for (m = 0; m < sheep_last_month[j]; m++)
// num_infectious[m]++;
// // ewe 44 - infected by dam
// for (m = sheep_intro_month[44]; m < sheep_last_month[44]; m++)
// num_infectious[m] += L_cdf[m-sheep_intro_month[44]];
// for (m = 0; m < nmonths; m++) {
// // calculate force of infection
// if ((m+3)%12 < 3)
// // transmission rate for housed ewes (in winter Jan-Mar)
// lambda[m] = num_infectious[m]*beta_housed;
// else
// // field transmission rate
// lambda[m] = num_infectious[m]*beta_field;
// // cumulative lambda for prob of uninfected
// if (m > 1)
// Lambda[m] = Lambda[m-1]+lambda[m-1];
// for (j = NUMBER_DONORS; j < NUMBER_SHEEP; j++)
// if (use_sheep[j] && sheep_intro_month[j] <= m && m < sheep_last_month[j]) {
// pinf = (1.-exp(-lambda[m]))*u(sheep_intro_month[j], m, Lambda);
// for (i = m; i < sheep_last_month[j]; i++)
// num_infectious[i] += pinf*L_cdf[i-m];
// }
// }
// p[12] = 0;
// p[13] = 0;
// for (j = NUMBER_DONORS; j < NUMBER_SHEEP; j++)
// if (use_sheep[j]) {
// for (m = sheep_intro_month[j]; m < sheep_last_month[j]; m++)
// if ((m+3)%12 < 3)
// p[13] += (1.-exp(-lambda[m]))*u(sheep_intro_month[j], m, Lambda);
// else
// p[12] += (1.-exp(-lambda[m]))*u(sheep_intro_month[j], m, Lambda);
// }
// p[14] = p[12]+p[13];
// free(lambda);
// free(Lambda);
// free(B);
// free(b);
// free(num_infectious);
// free(L_cdf);
}
void WAIC(int trt, int ind, double **lnL, double **V, double *p, const TimePoints *Data) {}
void PredictData(int trt, int ind, double *Output, double *V, double *p, gsl_rng *stream) {}
void SimulateData(int trt, int ind, double *Output, double *V, double *p, double *Data, uint *value, gsl_rng *stream) {}
double timestep(void) {return 1;}
void GlobalParameters() {}
double UserPDF(double x) {return 0;}
void HyperParameters(Treatments T, Hyperparameters *H) {}
void SaturatedModel(int trt, int ind, double **V, double *p, const TimePoints *Data) {}
| {
"alphanum_fraction": 0.5844347296,
"avg_line_length": 30.4049459042,
"ext": "c",
"hexsha": "307e9a825775ac076ece3327506799cd627d9639",
"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": "00771289509727b5b25e3776a0964555f227442d",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "nicksavill/maedi-visna-epidemiology",
"max_forks_repo_path": "Houwers/model136.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "nicksavill/maedi-visna-epidemiology",
"max_issues_repo_path": "Houwers/model136.c",
"max_line_length": 120,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "00771289509727b5b25e3776a0964555f227442d",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "nicksavill/maedi-visna-epidemiology",
"max_stars_repo_path": "Houwers/model136.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6894,
"size": 19672
} |
// SPDX-License-Identifier: MIT
// The MIT License (MIT)
//
// Copyright (c) 2014-2018, Institute for Software & Systems Engineering
// Copyright (c) 2018-2019, Johannes Leupolz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef PEMC_EXECUTABLE_MODEL_TEMPORARY_STATE_STORAGE_H_
#define PEMC_EXECUTABLE_MODEL_TEMPORARY_STATE_STORAGE_H_
#include <vector>
#include <gsl/span>
#include <cstdint>
#include <atomic>
#include <boost/align/aligned_allocator.hpp>
#include "pemc/basic/tsc_index.h"
#include "pemc/basic/probability.h"
#include "pemc/basic/label.h"
#include "pemc/basic/model_capacity.h"
#include "pemc/basic/raw_memory.h"
#include "pemc/formula/formula.h"
namespace pemc {
/// We store states in a contiguous array, indexed by a continuous variable.
/// The TemporaryStateStorage is not thread safe.
class TemporaryStateStorage {
private:
// The length in bytes of a state vector required for the analysis model.
int32_t modelStateVectorSize = 0;
// Extra bytes in state vector for preStateStorage modifiers.
int32_t preStateStorageModifierStateVectorSize = 0;
// The length in bytes of the state vector of the analysis model with the extra bytes
// required for the preStateStorage modifiers
int32_t stateVectorSize = 0;
// The number of saved states
StateIndex savedStates = 0;
// The number of states that can be cached and the number of reserved states.
StateIndex totalCapacity;
// the memory that contains the serialized states
std::vector<gsl::byte> stateMemory;
void resizeStateBuffer();
public:
TemporaryStateStorage(StateIndex _capacity);
StateIndex getNumberOfSavedStates();
gsl::span<gsl::byte> operator [](size_t idx);
StateIndex getFreshStateIndex();
void setStateVectorSize(int32_t _modelStateVectorSize, int32_t _preStateStorageModifierStateVectorSize);
void clear();
};
}
#endif // PEMC_EXECUTABLE_MODEL_TEMPORARY_STATE_STORAGE_H_
| {
"alphanum_fraction": 0.7490131579,
"avg_line_length": 36.6265060241,
"ext": "h",
"hexsha": "2d5e914ead62eda978b71601ee9930f8d9960683",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "joleuger/pemc",
"max_forks_repo_path": "pemc/executable_model/temporary_state_storage.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "joleuger/pemc",
"max_issues_repo_path": "pemc/executable_model/temporary_state_storage.h",
"max_line_length": 110,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "joleuger/pemc",
"max_stars_repo_path": "pemc/executable_model/temporary_state_storage.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 689,
"size": 3040
} |
/* movstat/medacc.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.
*
* Original copyright notice:
* Copyright (c) 2011 ashelly.myopenid.com under <http://www.opensource.org/licenses/mit-license>
*/
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_movstat.h>
#define ItemLess(a,b) ((a)<(b))
#define ItemMean(a,b) (((a)+(b))/2)
#define minCt(m) (((m)->ct-1)/2) /* count of items in minheap */
#define maxCt(m) (((m)->ct)/2) /* count of items in maxheap */
typedef double medacc_type_t;
typedef struct
{
int n; /* window size */
int idx; /* position in circular queue */
int ct; /* count of items in queue */
medacc_type_t *data; /* circular queue of values, size k */
int *pos; /* index into `heap` for each value, size 2*k */
int *heap; /* max/median/min heap holding indices into `data` */
} medacc_state_t;
static size_t medacc_size(const size_t n);
static int medacc_init(const size_t n, void * vstate);
static int medacc_insert(const medacc_type_t x, void * vstate);
static int medacc_delete(void * vstate);
static int medacc_get(void * params, medacc_type_t * result, const void * vstate);
static int mmless(const medacc_state_t * state, const int i, const int j);
static int mmexchange(medacc_state_t * state, const int i, const int j);
static int mmCmpExch(medacc_state_t * state, const int i, const int j);
static void minSortDown(medacc_state_t * state, int i);
static void maxSortDown(medacc_state_t * state, int i);
static int minSortUp(medacc_state_t * state, int i);
static int maxSortUp(medacc_state_t * state, int i);
static size_t
medacc_size(const size_t n)
{
size_t size = 0;
size += sizeof(medacc_state_t);
size += n * sizeof(medacc_type_t);
size += 2 * n * sizeof(int);
return size;
}
static int
medacc_init(const size_t n, void * vstate)
{
medacc_state_t * state = (medacc_state_t *) vstate;
int k = (int) n;
state->n = n;
state->ct = 0;
state->idx = 0;
state->data = (medacc_type_t *) ((unsigned char *) vstate + sizeof(medacc_state_t));
state->pos = (int *) ((unsigned char *) state->data + n * sizeof(medacc_type_t));
state->heap = state->pos + n + (n/2); /* points to middle of storage */
/* set up initial heap fill pattern: median,max,min,max,... */
while (k--)
{
state->pos[k] = ((k + 1)/2) * ((k & 1) ? -1 : 1);
state->heap[state->pos[k]] = k;
}
return GSL_SUCCESS;
}
static int
medacc_insert(const medacc_type_t x, void * vstate)
{
medacc_state_t * state = (medacc_state_t *) vstate;
int isNew = (state->ct < (int) state->n);
int p = state->pos[state->idx];
medacc_type_t old = state->data[state->idx];
state->data[state->idx] = x;
state->idx = (state->idx + 1) % state->n;
state->ct += isNew;
if (p > 0) /* new item is in minHeap */
{
if (!isNew && ItemLess(old, x))
minSortDown(state, p * 2);
else if (minSortUp(state, p))
maxSortDown(state, -1);
}
else if (p < 0) /* new item is in maxHeap */
{
if (!isNew && ItemLess(x, old))
maxSortDown(state, p * 2);
else if (maxSortUp(state, p))
minSortDown(state, 1);
}
else /* new item is at median */
{
if (maxCt(state))
maxSortDown(state, -1);
if (minCt(state))
minSortDown(state, 1);
}
return GSL_SUCCESS;
}
static int
medacc_delete(void * vstate)
{
medacc_state_t * state = (medacc_state_t *) vstate;
if (state->ct > 0)
{
int p = state->pos[(state->idx - state->ct + state->n) % state->n];
if (p > 0) /* oldest item is in minHeap */
{
mmexchange(state, p, minCt(state));
--(state->ct);
minSortDown(state, 2 * p);
}
else if (p < 0) /* oldest item is in maxHeap */
{
mmexchange(state, p, maxCt(state));
--(state->ct);
maxSortDown(state, 2 * p);
}
else if (p == 0) /* oldest item is at median */
{
}
}
return GSL_SUCCESS;
}
/* returns median (or average of 2 when item count is even) */
static int
medacc_get(void * params, medacc_type_t * result, const void * vstate)
{
const medacc_state_t * state = (const medacc_state_t *) vstate;
medacc_type_t median = state->data[state->heap[0]];
(void) params;
if ((state->ct & 1) == 0)
median = ItemMean(median, state->data[state->heap[-1]]);
*result = median;
return GSL_SUCCESS;
}
/* returns 1 if heap[i] < heap[j] */
static int
mmless(const medacc_state_t * state, const int i, const int j)
{
return ItemLess(state->data[state->heap[i]], state->data[state->heap[j]]);
}
/* swaps items i and j in heap, maintains indexes */
static int
mmexchange(medacc_state_t * state, const int i, const int j)
{
int t = state->heap[i];
state->heap[i] = state->heap[j];
state->heap[j] = t;
state->pos[state->heap[i]] = i;
state->pos[state->heap[j]] = j;
return 1;
}
/* swaps items i and j if i < j; returns true if swapped */
static int
mmCmpExch(medacc_state_t * state, const int i, const int j)
{
return (mmless(state, i, j) && mmexchange(state , i, j));
}
/* maintains minheap property for all items below i/2. */
static void
minSortDown(medacc_state_t * state, int i)
{
for (; i <= minCt(state); i *= 2)
{
if (i > 1 && i < minCt(state) && mmless(state, i + 1, i))
++i;
if (!mmCmpExch(state, i, i / 2))
break;
}
}
/* maintains maxheap property for all items below i/2. (negative indexes) */
static void
maxSortDown(medacc_state_t * state, int i)
{
for (; i >= -maxCt(state); i *= 2)
{
if (i < -1 && i > -maxCt(state) && mmless(state, i, i - 1))
--i;
if (!mmCmpExch(state, i / 2, i))
break;
}
}
/* maintains minheap property for all items above i, including median
returns true if median changed */
static int
minSortUp(medacc_state_t * state, int i)
{
while (i > 0 && mmCmpExch(state, i, i / 2))
i /= 2;
return (i == 0);
}
/* maintains maxheap property for all items above i, including median
returns true if median changed */
static int
maxSortUp(medacc_state_t * state, int i)
{
while (i<0 && mmCmpExch(state, i / 2, i))
i /= 2;
return (i == 0);
}
static const gsl_movstat_accum median_accum_type =
{
medacc_size,
medacc_init,
medacc_insert,
NULL, /* XXX FIXME */
medacc_get
};
const gsl_movstat_accum *gsl_movstat_accum_median = &median_accum_type;
| {
"alphanum_fraction": 0.6248970629,
"avg_line_length": 27.1865671642,
"ext": "c",
"hexsha": "b1eec0349e3233056cd8d70c68b07a0848c885c4",
"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/movstat/medacc.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/movstat/medacc.c",
"max_line_length": 97,
"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/movstat/medacc.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": 2170,
"size": 7286
} |
/* examples/C/ssmfe/precond_expert.c */
/* Laplacian on a square grid (using SPRAL_SSMFE_EXPERT routines) */
#include "spral.h"
#include <stdlib.h>
#include <stdio.h>
#include <cblas.h>
#include <math.h>
/* Header that implements Laplacian and preconditioners */
#include "laplace2d.h"
#include "ldltf.h"
int test_core(void);
int test_core_d(int, int);
int test_core_z(int, int);
int test_expert(void);
int test_expert_d(int);
int test_expert_z(int);
int test_ssmfe(void);
int test_ssmfe_d(int);
int test_ssmfe_z(int);
void zdcopy( int n, double complex* x, double* y );
void dzcopy( int n, double* y, double complex* x );
void vector_operations_d
( struct spral_ssmfe_rcid rci,
int n, int m, int kw, int ind[m],
double W[kw][m][n],
double rr[3][2*m][2*m],
double U[m]);
void vector_operations_z
( struct spral_ssmfe_rciz rci,
int n, int m, int kw, int ind[m],
double complex W[kw][m][n],
double complex rr[3][2*m][2*m],
double complex U[m]);
int main(void) {
int errors = 0;
int err;
fprintf(stdout, "testing ssmfe_core...\n");
err = test_core();
errors += err;
fprintf(stdout, "%d errors\n", err);
fprintf(stdout, "testing ssmfe_expert...\n");
err = test_expert();
errors += err;
fprintf(stdout, "%d errors\n", err);
fprintf(stdout, "testing ssmfe...\n");
err = test_ssmfe();
errors += err;
fprintf(stdout, "%d errors\n", err);
fprintf(stdout, "=============================\n");
fprintf(stdout, "Total number of errors = %d\n", errors);
return errors;
}
int test_core(void) {
int errors = 0;
int err;
fprintf(stdout, "testing standard_double...");
err = test_core_d(0, 0);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing generalized_double...");
err = test_core_d(1, 0);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing largest_double...");
err = test_core_d(0, 1);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing standard_double_complex...");
err = test_core_z(0, 0);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing generalized_double_complex...");
err = test_core_z(1, 0);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing largest_double_complex...");
err = test_core_z(0, 1);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
return errors;
}
int test_core_d(int problem, int largest) {
const int ngrid = 20; /* grid points along each side */
const int n = ngrid*ngrid; /* problem size */
const int nep = 5; /* eigenpairs wanted */
const int m = 3; /* dimension of the iterated subspace */
const int ncon_x = 5;
const double lambda_x[] = { /* expected eigenvalues */
4.4676695e-02,
1.1119274e-01,
1.1119274e-01,
1.7770878e-01,
2.2040061e-01
};
const double lambda_lx[] = { /* expected eigenvalues in 'largest' mode */
-7.9553233,
-7.8888073,
-7.8888073,
-7.8222912,
-7.7795994
};
int errors;
int state = SPRAL_RANDOM_INITIAL_SEED; /* PRNG state */
int ind[m]; /* permutation index */
double lambda[n]; /* eigenvalues storage */
double X[n][n]; /* eigenvectors storage */
/* Work arrays */
double lmd[m];
double rr[3][2*m][2*m];
double W[8][m][n];
double U[m][n];
double V[m];
/* Derived types */
struct spral_ssmfe_rcid rci; /* reverse communication data */
struct spral_ssmfe_core_options options;/* options */
void *keep; /* private data */
struct spral_ssmfe_inform inform; /* information */
/* Initialize options to default values */
spral_ssmfe_core_default_options(&options);
/* Initialize W to lin indep vectors by randomizing */
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
W[0][j][i] = spral_random_real(&state, true);
int ncon = 0; /* number of converged eigenpairs */
rci.job = 0; keep = NULL;
while(true) { /* reverse communication loop */
if ( largest != 0 )
spral_ssmfe_largest_double(&rci, problem, nep, m, lmd,
&rr[0][0][0], ind, &keep, &options, &inform);
else
spral_ssmfe_double(&rci, problem, nep, 0, m, lmd,
&rr[0][0][0], ind, &keep, &options, &inform);
switch ( rci.job ) {
case 1:
apply_laplacian(
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0]
);
if ( largest != 0 )
cblas_dscal( n*rci.nx, -1.0, &W[rci.ky][rci.jy][0], 1 );
break;
case 2:
if ( largest != 0 )
cblas_dcopy(
n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1
);
else
apply_gauss_seidel_step (
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0]
);
break;
case 3:
cblas_dcopy(
n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1
);
break;
case 4:
for ( int i = 0; i < m; i++ ) {
if ( inform.converged[i] != 0 )
continue;
if ( inform.err_X[i] > 0 && inform.err_X[i] < 1e-6 )
inform.converged[i] = 1;
}
break;
case 5:
if ( rci.i < 0 ) continue;
for(int k=0; k<rci.nx; k++) {
int j = ncon + k;
lambda[j] = lmd[rci.jx + k];
cblas_dcopy( n, &W[0][rci.jx + k][0], 1, &X[j][0], 1 );
}
ncon += rci.nx;
if ( ncon >= nep || inform.iteration > 300 )
goto finished;
break;
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
vector_operations_d( rci, n, m, 8, ind, W, rr, V );
break;
case 21: // Fall through to 22
case 22:
if( ncon > 0 ) {
cblas_dgemm(
CblasColMajor, CblasTrans, CblasNoTrans, ncon, rci.nx, n,
1.0, &X[0][0], n, &W[rci.ky][rci.jy][0], n, 0.0, &U[0][0], n
);
cblas_dgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.nx, ncon,
-1.0, &X[0][0], n, &U[0][0], n, 1.0, &W[rci.kx][rci.jx][0], n
);
if ( problem != 0 )
cblas_dgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.nx, ncon,
-1.0, &X[0][0], n, &U[0][0], n, 1.0, &W[rci.ky][rci.jy][0], n
);
}
break;
case 999:
if( rci.k == 0 ) {
if( rci.jx > 1 ) {
for(int j=0; j<rci.jx; j++)
for(int i=0; i<n; i++)
W[0][j][i] = spral_random_real(&state, true);
}
}
break;
default:
goto finished;
}
}
finished:
errors = 0;
if ( inform.flag != 0 ) errors++;
if ( ncon != ncon_x ) errors++;
if ( largest != 0 ) {
for ( int i = 0; i < ncon && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_lx[i]) > 1e-6 ) errors++;
}
else {
for ( int i = 0; i < ncon && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_x[i]) > 1e-6 ) errors++;
}
spral_ssmfe_core_free(&keep, &inform);
return errors;
}
int test_core_z(int problem, int largest) {
const int ngrid = 20; /* grid points along each side */
const int n = ngrid*ngrid; /* problem size */
const int nep = 5; /* eigenpairs wanted */
const int m = 3; /* dimension of the iterated subspace */
const int ncon_x = 5; /* expected number of converged eigenpairs */
const double lambda_x[] = { /* expected eigenvalues */
4.4676695e-02,
1.1119274e-01,
1.1119274e-01,
1.7770878e-01,
2.2040061e-01
};
const double lambda_lx[] = { /* expected eigenvalues in 'largest' mode */
-7.9553233,
-7.8888073,
-7.8888073,
-7.8222912,
-7.7795994
};
const double complex ZERO = 0.0;
const double complex ONE = 1.0;
const double complex MINUS_ONE = -1.0;
int errors;
int state = SPRAL_RANDOM_INITIAL_SEED; /* PRNG state */
int ind[m]; /* permutation index */
double lambda[n]; /* eigenvalues storage */
double complex X[n][n]; /* eigenvectors storage */
/* Work arrays */
double lmd[m];
double complex rr[3][2*m][2*m];
double complex W[8][m][n];
double complex U[m][n];
double complex V[m];
/* Derived types */
struct spral_ssmfe_rciz rci; /* reverse communication data */
struct spral_ssmfe_core_options options;/* options */
void *keep; /* private data */
struct spral_ssmfe_inform inform; /* information */
/* Initialize options to default values */
spral_ssmfe_core_default_options(&options);
/* Initialize W to lin indep vectors by randomizing */
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
W[0][j][i] = spral_random_real(&state, true);
int ncon = 0; /* number of converged eigenpairs */
rci.job = 0; keep = NULL;
while(true) { /* reverse communication loop */
if ( largest != 0 )
spral_ssmfe_largest_double_complex(&rci, problem, nep, m, lmd,
&rr[0][0][0], ind, &keep, &options, &inform);
else
spral_ssmfe_double_complex(&rci, problem, nep, 0, m, lmd,
&rr[0][0][0], ind, &keep, &options, &inform);
switch ( rci.job ) {
case 1:
apply_laplacian_z(
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0]
);
if ( largest != 0 )
cblas_zscal( n*rci.nx, &MINUS_ONE, &W[rci.ky][rci.jy][0], 1 );
break;
case 2:
if ( largest != 0 )
cblas_zcopy(
n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1
);
else
apply_gauss_seidel_step_z (
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0]
);
break;
case 3:
cblas_zcopy(
n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1
);
break;
case 4:
for ( int i = 0; i < m; i++ ) {
if ( inform.converged[i] != 0 )
continue;
if ( inform.err_X[i] > 0 && inform.err_X[i] < 1e-6 )
inform.converged[i] = 1;
}
break;
case 5:
if ( rci.i < 0 ) continue;
for(int k=0; k<rci.nx; k++) {
int j = ncon + k;
lambda[j] = lmd[rci.jx + k];
cblas_zcopy( n, &W[0][rci.jx + k][0], 1, &X[j][0], 1 );
}
ncon += rci.nx;
if ( ncon >= nep || inform.iteration > 300 )
goto finished;
break;
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
vector_operations_z( rci, n, m, 8, ind, W, rr, V );
break;
case 21: // Fall through to 22
case 22:
if( ncon > 0 ) {
cblas_zgemm(
CblasColMajor, CblasTrans, CblasNoTrans, ncon, rci.nx, n,
&ONE, &X[0][0], n, &W[rci.ky][rci.jy][0], n, &ZERO, &U[0][0], n
);
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.nx, ncon,
&MINUS_ONE, &X[0][0], n, &U[0][0], n, &ONE,
&W[rci.kx][rci.jx][0], n
);
if ( problem != 0 )
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.nx, ncon,
&MINUS_ONE, &X[0][0], n, &U[0][0], n, &ONE,
&W[rci.ky][rci.jy][0], n
);
}
break;
case 999:
if( rci.k == 0 ) {
if( rci.jx > 1 ) {
for(int j=0; j<rci.jx; j++)
for(int i=0; i<n; i++)
W[0][j][i] = spral_random_real(&state, true);
}
}
break;
default:
goto finished;
}
}
finished:
errors = 0;
if ( inform.flag != 0 ) errors++;
if ( ncon != ncon_x ) errors++;
if ( largest != 0 ) {
for ( int i = 0; i < ncon && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_lx[i]) > 1e-6 ) errors++;
}
else {
for ( int i = 0; i < ncon && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_x[i]) > 1e-6 ) errors++;
}
spral_ssmfe_core_free(&keep, &inform);
return errors;
}
int test_expert(void) {
int errors = 0;
int err;
fprintf(stdout, "testing standard_double...");
err = test_expert_d(0);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing generalized_double...");
err = test_expert_d(1);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing standard_shift_double...");
err = test_expert_d(2);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing generalized_shift_double...");
err = test_expert_d(3);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing buckling_double...");
err = test_expert_d(4);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing standard_double_complex...");
err = test_expert_z(0);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing generalized_double_complex...");
err = test_expert_z(1);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing standard_shift_double_complex...");
err = test_expert_z(2);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing generalized_shift_double_complex...");
err = test_expert_z(3);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing buckling_double_complex...");
err = test_expert_z(4);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
return errors;
}
int test_expert_d(int problem) {
const int ngrid = 20; /* grid points along each side */
const int n = ngrid*ngrid; /* problem size */
const int m = 3; /* dimension of the iterated subspace */
const int ncon_x = 6;
const double lambda_x[] = {
4.4676695e-02,
1.1119274e-01,
1.1119274e-01,
1.7770878e-01,
2.2040061e-01,
2.2040061e-01
};
const double lambda_six[] = {
9.5108266e-01,
9.5108266e-01,
8.8141871e-01,
8.8141871e-01,
8.4187478e-01,
8.4187478e-01
};
int errors;
int nep = 5;
int state = SPRAL_RANDOM_INITIAL_SEED; /* PRNG state */
int ind[m]; /* permutation index */
int ipiv[n]; /* LDLT pivot index */
double sigma; /* shift */
double A[n][n]; /* matrix */
double LDLT[n][n]; /* factors */
double lambda[n]; /* eigenvalues */
double X[n][n]; /* eigenvectors */
/* Work arrays */
double work[n][n]; /* work array for dsytrf */
double rr[3][2*m][2*m];
double W[8][m][n];
double U[m][n];
double V[m];
/* Derived types */
struct spral_ssmfe_rcid rci; /* reverse communication data */
struct spral_ssmfe_options options; /* options */
void *keep; /* private data */
struct spral_ssmfe_inform inform; /* information */
if ( problem > 1 ) {
sigma = 1.0;
set_laplacian_matrix(ngrid, ngrid, n, A);
for(int j=0; j<n; j++)
for(int i=0; i<n; i++)
LDLT[j][i] = (i==j) ? A[j][i] - sigma
: A[j][i];
cwrap_dsytrf('L', n, &LDLT[0][0], n, ipiv, &work[0][0], n*n);
int i = num_neg_D(n, n, LDLT, ipiv); /* all evalues to left of sigma */
if ( i < nep ) nep = i;
}
/* Initialize options to default values */
spral_ssmfe_default_options(&options);
/* gap between the last converged eigenvalue and the rest of the spectrum
* must be at least 0.1 times average gap between computed eigenvalues */
options.left_gap = -0.1;
/* block size is small, convergence may be slow, allow more iterations */
options.max_iterations = 300;
/* Initialize W to lin indep vectors by randomizing */
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
W[0][j][i] = spral_random_real(&state, true);
int ncon = 0; /* number of converged eigenpairs */
rci.job = 0; keep = NULL;
while(true) { /* reverse communication loop */
switch ( problem ) {
case 0:
spral_ssmfe_expert_standard_double(&rci, nep, n, lambda,
m, &rr[0][0][0], ind, &keep, &options, &inform);
break;
case 1:
spral_ssmfe_expert_generalized_double(&rci, nep, n, lambda,
m, &rr[0][0][0], ind, &keep, &options, &inform);
break;
case 2:
spral_ssmfe_expert_standard_shift_double(&rci, sigma, nep, 0, n, lambda,
m, &rr[0][0][0], ind, &keep, &options, &inform);
break;
case 3:
spral_ssmfe_expert_generalized_shift_double(
&rci, sigma, nep, 0, n, lambda,
m, &rr[0][0][0], ind, &keep, &options, &inform);
break;
case 4:
spral_ssmfe_expert_buckling_double(
&rci, sigma, nep, 0, n, lambda,
m, &rr[0][0][0], ind, &keep, &options, &inform);
break;
}
switch ( rci.job ) {
case 1:
if ( problem < 4 )
apply_laplacian(
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0]
);
else
cblas_dcopy
( n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1 );
break;
case 2:
if ( problem < 2 )
apply_gauss_seidel_step (
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0]
);
else
cblas_dcopy
( n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1 );
break;
case 3:
if ( problem < 4 )
cblas_dcopy
( n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1 );
else
apply_laplacian(
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0]
);
break;
case 5:
if ( rci.i < 0 ) continue;
for(int k=0; k<rci.nx; k++) {
int j = ncon + k;
cblas_dcopy( n, &W[0][rci.jx+k][0], 1, &X[j][0], 1 );
}
ncon += rci.nx;
break;
case 9:
cblas_dcopy(
n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1
);
cwrap_dsytrs(
'L', n, rci.nx, &LDLT[0][0], n, ipiv, &W[rci.ky][rci.jy][0], n
);
break;
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
vector_operations_d( rci, n, m, 8, ind, W, rr, V );
break;
case 21: // Fall through to 22
case 22:
if( ncon > 0 ) {
cblas_dgemm(
CblasColMajor, CblasTrans, CblasNoTrans, ncon, rci.nx, n,
1.0, &X[0][0], n, &W[rci.ky][rci.jy][0], n, 0.0, &U[0][0], n
);
cblas_dgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.nx, ncon,
-1.0, &X[0][0], n, &U[0][0], n, 1.0, &W[rci.kx][rci.jx][0], n
);
if ( problem == 1 || problem == 3 )
cblas_dgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.nx, ncon,
-1.0, &X[0][0], n, &U[0][0], n, 1.0, &W[rci.ky][rci.jy][0], n
);
else if ( problem == 4 )
apply_laplacian(
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0],
&W[rci.ky][rci.jy][0]
);
}
break;
case 999:
if( rci.k == 0 ) {
if( rci.jx > 1 ) {
for(int j=0; j<rci.jx; j++)
for(int i=0; i<n; i++)
W[0][j][i] = spral_random_real(&state, true);
}
}
break;
default:
goto finished;
}
}
finished:
errors = 0;
if ( inform.flag != 0 ) errors++;
if ( ncon != ncon_x ) errors++;
if ( problem < 2 ) {
for ( int i = 0; i < ncon && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_x[i]) > 1e-6 ) errors++;
}
else {
for ( int i = 0; i < ncon && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_six[i]) > 1e-6 ) errors++;
}
spral_ssmfe_expert_free(&keep, &inform);
return errors;
}
int test_expert_z(int problem) {
const int ngrid = 20; /* grid points along each side */
const int n = ngrid*ngrid; /* problem size */
const int m = 3; /* dimension of the iterated subspace */
const int ncon_x = 6;
const double lambda_x[] = {
4.4676695e-02,
1.1119274e-01,
1.1119274e-01,
1.7770878e-01,
2.2040061e-01,
2.2040061e-01
};
const double lambda_six[] = {
9.5108266e-01,
9.5108266e-01,
8.8141871e-01,
8.8141871e-01,
8.4187478e-01,
8.4187478e-01
};
const double complex ZERO = 0.0;
const double complex ONE = 1.0;
const double complex NONE = -1.0;
int errors;
int nep = 5;
int state = SPRAL_RANDOM_INITIAL_SEED; /* PRNG state */
int ind[m]; /* permutation index */
int ipiv[n]; /* LDLT pivot index */
double sigma; /* shift */
double lambda[n]; /* eigenvalues */
double complex X[n][n]; /* eigenvectors */
/* Work arrays */
double B[n][n];
double LDLT[n][n];
double work[n][n];
double complex rr[3][2*m][2*m];
double complex W[8][m][n];
double complex U[m][n];
double complex V[m];
/* Derived types */
struct spral_ssmfe_rciz rci; /* reverse communication data */
struct spral_ssmfe_options options; /* options */
void *keep; /* private data */
struct spral_ssmfe_inform inform; /* information */
if ( problem > 1 ) {
sigma = 1.0;
// set_laplacian_matrix_z(ngrid, ngrid, n, A);
set_laplacian_matrix(ngrid, ngrid, n, B);
for(int j=0; j<n; j++)
for(int i=0; i<n; i++)
LDLT[j][i] = (i==j) ? B[j][i] - sigma
: B[j][i];
// LDLT[j][i] = (i==j) ? A[j][i] - sigma
// : A[j][i];
cwrap_dsytrf('L', n, &LDLT[0][0], n, ipiv, &work[0][0], n*n);
}
/* Initialize options to default values */
spral_ssmfe_default_options(&options);
/* gap between the last converged eigenvalue and the rest of the spectrum
* must be at least 0.1 times average gap between computed eigenvalues */
options.left_gap = -0.1;
/* block size is small, convergence may be slow, allow more iterations */
options.max_iterations = 200;
/* Initialize W to lin indep vectors by randomizing */
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
W[0][j][i] = spral_random_real(&state, true);
int ncon = 0; /* number of converged eigenpairs */
rci.job = 0; keep = NULL;
while(true) { /* reverse communication loop */
switch ( problem ) {
case 0:
spral_ssmfe_expert_standard_double_complex(&rci, nep, n, lambda,
m, &rr[0][0][0], ind, &keep, &options, &inform);
break;
case 1:
spral_ssmfe_expert_generalized_double_complex(&rci, nep, n, lambda,
m, &rr[0][0][0], ind, &keep, &options, &inform);
break;
case 2:
spral_ssmfe_expert_standard_shift_double_complex(
&rci, sigma, nep, 0, n, lambda,
m, &rr[0][0][0], ind, &keep, &options, &inform);
break;
case 3:
spral_ssmfe_expert_generalized_shift_double_complex(
&rci, sigma, nep, 0, n, lambda,
m, &rr[0][0][0], ind, &keep, &options, &inform);
break;
case 4:
spral_ssmfe_expert_buckling_double_complex(
&rci, sigma, nep, 0, n, lambda,
m, &rr[0][0][0], ind, &keep, &options, &inform);
break;
}
switch ( rci.job ) {
case 1:
if ( problem < 4 )
apply_laplacian_z(
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0]
);
else
cblas_zcopy
( n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1 );
break;
case 2:
if ( problem < 2 )
apply_gauss_seidel_step_z (
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0]
);
else
cblas_zcopy
( n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1 );
break;
case 3:
if ( problem < 4 )
cblas_zcopy
( n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1 );
else
apply_laplacian_z(
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0], &W[rci.ky][rci.jy][0]
);
break;
case 5:
if ( rci.i < 0 ) continue;
for(int k=0; k<rci.nx; k++) {
int j = ncon + k;
cblas_zcopy( n, &W[0][rci.jx+k][0], 1, &X[j][0], 1 );
}
ncon += rci.nx;
break;
case 9:
for(int i=0; i<n; i++)
for(int j=0; j<rci.nx; j++)
work[j][i] = W[rci.kx][rci.jx + j][i];
cwrap_dsytrs(
'L', n, rci.nx, &LDLT[0][0], n, ipiv, &work[0][0], n
);
for(int i=0; i<n; i++)
for(int j=0; j<rci.nx; j++)
W[rci.ky][rci.jy + j][i] = work[j][i];
break;
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
vector_operations_z( rci, n, m, 8, ind, W, rr, V );
break;
case 21: // Fall through to 22
case 22:
if( ncon > 0 ) {
cblas_zgemm(
CblasColMajor, CblasTrans, CblasNoTrans, ncon, rci.nx, n,
&ONE, &X[0][0], n, &W[rci.ky][rci.jy][0], n, &ZERO, &U[0][0], n
);
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.nx, ncon,
&NONE, &X[0][0], n, &U[0][0], n, &ONE, &W[rci.kx][rci.jx][0], n
);
if ( problem == 1 || problem == 3 )
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.nx, ncon,
&NONE, &X[0][0], n, &U[0][0], n, &ONE, &W[rci.ky][rci.jy][0], n
);
else if ( problem == 4 )
apply_laplacian_z(
ngrid, ngrid, rci.nx, &W[rci.kx][rci.jx][0],
&W[rci.ky][rci.jy][0]
);
}
break;
case 999:
if( rci.k == 0 ) {
if( rci.jx > 1 ) {
for(int j=0; j<rci.jx; j++)
for(int i=0; i<n; i++)
W[0][j][i] = spral_random_real(&state, true);
}
}
break;
default:
goto finished;
}
}
finished:
errors = 0;
if ( inform.flag != 0 ) errors++;
if ( ncon != ncon_x ) errors++;
if ( problem < 2 ) {
for ( int i = 0; i < ncon && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_x[i]) > 1e-6 ) errors++;
}
else {
for ( int i = 0; i < ncon && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_six[i]) > 1e-6 ) errors++;
}
spral_ssmfe_expert_free(&keep, &inform);
return errors;
}
int test_ssmfe(void) {
int errors = 0;
int err;
fprintf(stdout, "testing standard_double...");
err = test_ssmfe_d(0);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing generalized_double...");
err = test_ssmfe_d(1);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing standard_shift_double...");
err = test_ssmfe_d(2);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing generalized_shift_double...");
err = test_ssmfe_d(3);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing buckling_double...");
err = test_ssmfe_d(4);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing standard_double_complex...");
err = test_ssmfe_z(0);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing generalized_double_complex...");
err = test_ssmfe_z(1);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing standard_shift_double_complex...");
err = test_ssmfe_z(2);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing generalized_shift_double_complex...");
err = test_ssmfe_z(3);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
fprintf(stdout, "testing buckling_double_complex...");
err = test_ssmfe_z(4);
if ( err != 0 )
fprintf(stdout, "%d errors\n", err);
else
fprintf(stdout, "ok\n");
errors += err;
return errors;
}
int test_ssmfe_d(int problem) {
const int m = 20; /* grid points along each side */
const int n = m*m; /* problem size */
const int ncon_x = 6;
const double sigma = 1.0; /* shift */
const double lambda_x[] = {
4.4676695e-02,
1.1119274e-01,
1.1119274e-01,
1.7770878e-01,
2.2040061e-01,
2.2040061e-01
};
const double lambda_six[] = {
8.4187478e-01,
8.4187478e-01,
8.8141871e-01,
8.8141871e-01,
9.5108266e-01,
9.5108266e-01
};
int errors;
int nep = 5;
int ipiv[n]; /* LDLT pivot index */
double lambda[n]; /* eigenvalues */
double X[n][n]; /* eigenvectors */
double A[n][n]; /* matrix */
double LDLT[n][n]; /* factors */
double work[n][n]; /* work array for dsytrf */
struct spral_ssmfe_rcid rci; /* reverse communication data */
struct spral_ssmfe_options options; /* options */
void *keep; /* private data */
struct spral_ssmfe_inform inform; /* information */
if ( problem > 1 ) {
set_laplacian_matrix( m, m, n, A );
for(int j=0; j<n; j++)
for(int i=0; i<n; i++)
LDLT[j][i] = (i==j) ? A[j][i] - sigma
: A[j][i];
cwrap_dsytrf( 'L', n, &LDLT[0][0], n, ipiv, &work[0][0], n*n );
}
/* Initialize options to default values */
spral_ssmfe_default_options(&options);
/* gap between the last converged eigenvalue and the rest of the spectrum
* must be at least 0.1 times average gap between computed eigenvalues */
options.left_gap = -0.1;
rci.job = 0; keep = NULL;
while(true) { /* reverse communication loop */
switch ( problem ) {
case 0:
spral_ssmfe_standard_double( &rci, nep, 2*nep, lambda, n, &X[0][0], n,
&keep, &options, &inform );
break;
case 1:
spral_ssmfe_standard_double( &rci, nep, 2*nep, lambda, n, &X[0][0], n,
&keep, &options, &inform );
break;
case 2:
spral_ssmfe_standard_shift_double( &rci, sigma, nep, 0, n, lambda,
n, &X[0][0], n, &keep, &options, &inform );
break;
case 3:
spral_ssmfe_generalized_shift_double( &rci, sigma, nep, 0, n, lambda,
n, &X[0][0], n, &keep, &options, &inform );
break;
case 4:
spral_ssmfe_buckling_double( &rci, sigma, nep, 0, n, lambda,
n, &X[0][0], n, &keep, &options, &inform );
break;
}
switch ( rci.job ) {
case 1:
if ( problem < 4 )
apply_laplacian(m, m, rci.nx, rci.x, rci.y);
else
cblas_dcopy( n*rci.nx, rci.x, 1, rci.y, 1 );
break;
case 2:
if ( problem < 2 )
apply_gauss_seidel_step(m, m, rci.nx, rci.x, rci.y);
break;
case 3:
if ( problem < 4 )
cblas_dcopy( n*rci.nx, rci.x, 1, rci.y, 1 );
else
apply_laplacian(m, m, rci.nx, rci.x, rci.y);
break;
case 9:
cblas_dcopy( n*rci.nx, rci.x, 1, rci.y, 1 );
cwrap_dsytrs( 'L', n, rci.nx, &LDLT[0][0], n, ipiv, rci.y, n );
break;
default:
goto finished;
}
}
finished:
errors = 0;
if ( inform.flag != 0 ) errors++;
if ( inform.left != ncon_x ) errors++;
if ( problem < 2 ) {
for ( int i = 0; i < inform.left && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_x[i]) > 1e-6 ) errors++;
}
else {
for ( int i = 0; i < inform.left && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_six[i]) > 1e-6 ) errors++;
}
spral_ssmfe_free_double(&keep, &inform);
return errors;
}
int test_ssmfe_z(int problem) {
const int m = 20; /* grid points along each side */
const int n = m*m; /* problem size */
const int ncon_x = 6;
const double sigma = 1.0; /* shift */
const double lambda_x[] = {
4.4676695e-02,
1.1119274e-01,
1.1119274e-01,
1.7770878e-01,
2.2040061e-01,
2.2040061e-01
};
const double lambda_six[] = {
8.4187478e-01,
8.4187478e-01,
8.8141871e-01,
8.8141871e-01,
9.5108266e-01,
9.5108266e-01
};
int errors;
int nep = 5;
int ipiv[n]; /* LDLT pivot index */
double lambda[n]; /* eigenvalues */
double complex X[n][n]; /* eigenvectors */
double A[n][n]; /* matrix */
double LDLT[n][n]; /* factors */
double work[n][n]; /* work array for dsytrf */
struct spral_ssmfe_rciz rci; /* reverse communication data */
struct spral_ssmfe_options options; /* options */
void *keep; /* private data */
struct spral_ssmfe_inform inform; /* information */
if ( problem > 1 ) {
set_laplacian_matrix( m, m, n, A );
for(int j=0; j<n; j++)
for(int i=0; i<n; i++)
LDLT[j][i] = (i==j) ? A[j][i] - sigma
: A[j][i];
cwrap_dsytrf( 'L', n, &LDLT[0][0], n, ipiv, &work[0][0], n*n );
}
/* Initialize options to default values */
spral_ssmfe_default_options(&options);
/* gap between the last converged eigenvalue and the rest of the spectrum
* must be at least 0.1 times average gap between computed eigenvalues */
options.left_gap = -0.1;
rci.job = 0; keep = NULL;
while(true) { /* reverse communication loop */
switch ( problem ) {
case 0:
spral_ssmfe_standard_double_complex(
&rci, nep, 2*nep, lambda, n, &X[0][0], n,
&keep, &options, &inform );
break;
case 1:
spral_ssmfe_standard_double_complex(
&rci, nep, 2*nep, lambda, n, &X[0][0], n,
&keep, &options, &inform );
break;
case 2:
spral_ssmfe_standard_shift_double_complex(
&rci, sigma, nep, 0, n, lambda,
n, &X[0][0], n, &keep, &options, &inform );
break;
case 3:
spral_ssmfe_generalized_shift_double_complex(
&rci, sigma, nep, 0, n, lambda,
n, &X[0][0], n, &keep, &options, &inform );
break;
case 4:
spral_ssmfe_buckling_double_complex(
&rci, sigma, nep, 0, n, lambda,
n, &X[0][0], n, &keep, &options, &inform );
break;
}
switch ( rci.job ) {
case 1:
if ( problem < 4 )
apply_laplacian_z( m, m, rci.nx, rci.x, rci.y );
else
cblas_zcopy( n*rci.nx, rci.x, 1, rci.y, 1 );
break;
case 2:
if ( problem < 2 )
apply_gauss_seidel_step_z( m, m, rci.nx, rci.x, rci.y );
break;
case 3:
if ( problem < 4 )
cblas_zcopy( n*rci.nx, rci.x, 1, rci.y, 1 );
else
apply_laplacian_z( m, m, rci.nx, rci.x, rci.y );
break;
case 9:
zdcopy( n*rci.nx, rci.x, &work[0][0] );
cwrap_dsytrs( 'L', n, rci.nx, &LDLT[0][0], n, ipiv, &work[0][0], n );
dzcopy( n*rci.nx, &work[0][0], rci.y );
break;
default:
goto finished;
}
}
finished:
errors = 0;
if ( inform.flag != 0 ) errors++;
if ( inform.left != ncon_x ) errors++;
if ( problem < 2 ) {
for ( int i = 0; i < inform.left && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_x[i]) > 1e-6 ) errors++;
}
else {
for ( int i = 0; i < inform.left && i < ncon_x; i++ )
if ( fabs(lambda[i] - lambda_six[i]) > 1e-6 ) errors++;
}
if ( problem == -2 ) {
printf("%d eigenpairs converged in %d iterations\n", inform.left, inform.iteration);
for(int i=0; i<inform.left; i++)
printf(" lambda[%1d] = %13.7e\n", i, lambda[i]);
}
spral_ssmfe_free_double_complex(&keep, &inform);
return errors;
}
void zdcopy( int n, double complex* x, double* y ) {
for ( int i = 0; i < n; i++ )
y[i] = x[i];
}
void dzcopy( int n, double* x, double complex* y ) {
for ( int i = 0; i < n; i++ )
y[i] = x[i];
}
void vector_operations_d
( struct spral_ssmfe_rcid rci,
int n, int m, int kw, int ind[m],
double W[kw][m][n],
double rr[3][2*m][2*m],
double U[m]) {
switch ( rci.job ) {
case 11:
if ( rci.i == 0 ) {
if ( rci.kx != rci.ky || rci.jx > rci.jy ) {
cblas_dcopy(
n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1
);
} else if ( rci.jx < rci.jy ) {
for(int j=rci.nx-1; j>=0; j--)
cblas_dcopy(
n, &W[rci.kx][rci.jx+j][0], 1, &W[rci.ky][rci.jy+j][0], 1
);
}
} else {
for(int i=0; i<n; i++) {
for(int j=0; j<rci.nx; j++)
U[j] = W[rci.kx][ind[j]][i];
for(int j=0; j<rci.nx; j++)
W[rci.kx][j][i] = U[j];
if(rci.ky != rci.kx) {
for(int j=0; j<rci.nx; j++)
U[j] = W[rci.ky][ind[j]][i];
for(int j=0; j<rci.nx; j++)
W[rci.ky][j][i] = U[j];
}
}
}
break;
case 12:
for(int i=0; i<rci.nx; i++)
rr[rci.k][rci.j+i][rci.i+i] =
cblas_ddot(
n, &W[rci.kx][rci.jx+i][0], 1, &W[rci.ky][rci.jy+i][0], 1
);
break;
case 13:
for(int i=0; i<rci.nx; i++) {
if( rci.kx == rci.ky ) {
double s = cblas_dnrm2(n, &W[rci.kx][rci.jx+i][0], 1);
if( s > 0 )
cblas_dscal(n, 1/s, &W[rci.kx][rci.jx+i][0], 1);
} else {
double s = sqrt(fabs(cblas_ddot(
n, &W[rci.kx][rci.jx+i][0], 1, &W[rci.ky][rci.jy+i][0], 1)
));
if ( s > 0 ) {
cblas_dscal(n, 1/s, &W[rci.kx][rci.jx+i][0], 1);
cblas_dscal(n, 1/s, &W[rci.ky][rci.jy+i][0], 1);
} else {
for(int j=0; j<n; j++)
W[rci.ky][rci.jy+i][j] = 0.0;
}
}
}
break;
case 14:
for(int i=0; i<rci.nx; i++) {
double s = -rr[rci.k][rci.j+i][rci.i+i];
cblas_daxpy(
n, s, &W[rci.kx][rci.jx+i][0], 1, &W[rci.ky][rci.jy+i][0], 1
);
}
break;
case 15:
if ( rci.nx > 0 && rci.ny > 0 )
cblas_dgemm(
CblasColMajor, CblasTrans, CblasNoTrans, rci.nx, rci.ny, n,
rci.alpha, &W[rci.kx][rci.jx][0], n, &W[rci.ky][rci.jy][0], n,
rci.beta, &rr[rci.k][rci.j][rci.i], 2*m
);
break;
case 16: // Fall through to 17
case 17:
if( rci.job == 17 ) {
cblas_dgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.ny, rci.nx,
1.0, &W[rci.kx][rci.jx][0], n, &rr[rci.k][rci.j][rci.i], 2*m,
0.0, &W[rci.ky][rci.jy][0], n
);
cblas_dcopy(
n*rci.ny, &W[rci.ky][rci.jy][0], 1, &W[rci.kx][rci.jx][0], 1
);
} else {
cblas_dgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.ny, rci.nx,
rci.alpha, &W[rci.kx][rci.jx][0], n, &rr[rci.k][rci.j][rci.i],
2*m, rci.beta, &W[rci.ky][rci.jy][0], n
);
}
break;
}
}
void vector_operations_z
( struct spral_ssmfe_rciz rci,
int n, int m, int kw, int ind[m],
double complex W[kw][m][n],
double complex rr[3][2*m][2*m],
double complex U[m]) {
const double complex ZERO = 0.0;
const double complex ONE = 1.0;
double complex z;
switch ( rci.job ) {
case 11:
if ( rci.i == 0 ) {
if ( rci.kx != rci.ky || rci.jx > rci.jy ) {
cblas_zcopy(
n*rci.nx, &W[rci.kx][rci.jx][0], 1, &W[rci.ky][rci.jy][0], 1
);
} else if ( rci.jx < rci.jy ) {
for(int j=rci.nx-1; j>=0; j--)
cblas_zcopy(
n, &W[rci.kx][rci.jx+j][0], 1, &W[rci.ky][rci.jy+j][0], 1
);
}
} else {
for(int i=0; i<n; i++) {
for(int j=0; j<rci.nx; j++)
U[j] = W[rci.kx][ind[j]][i];
for(int j=0; j<rci.nx; j++)
W[rci.kx][j][i] = U[j];
if(rci.ky != rci.kx) {
for(int j=0; j<rci.nx; j++)
U[j] = W[rci.ky][ind[j]][i];
for(int j=0; j<rci.nx; j++)
W[rci.ky][j][i] = U[j];
}
}
}
break;
case 12:
for(int i=0; i<rci.nx; i++) {
cblas_zdotc_sub(
n, &W[rci.kx][rci.jx+i][0], 1, &W[rci.ky][rci.jy+i][0], 1, &z
);
rr[rci.k][rci.j+i][rci.i+i] = z;
}
break;
case 13:
for(int i=0; i<rci.nx; i++) {
if( rci.kx == rci.ky ) {
double s = cblas_dznrm2(n, &W[rci.kx][rci.jx+i][0], 1);
if( s > 0 ) {
z = ONE/s;
cblas_zscal(n, &z, &W[rci.kx][rci.jx+i][0], 1);
}
} else {
cblas_zdotc_sub(
n, &W[rci.kx][rci.jx+i][0], 1, &W[rci.ky][rci.jy+i][0], 1, &z
);
double s = sqrt(fabs(z));
if ( s > 0 ) {
z = ONE/s;
cblas_zscal(n, &z, &W[rci.kx][rci.jx+i][0], 1);
cblas_zscal(n, &z, &W[rci.ky][rci.jy+i][0], 1);
} else {
for(int j=0; j<n; j++)
W[rci.ky][rci.jy+i][j] = 0.0;
}
}
}
break;
case 14:
for(int i=0; i<rci.nx; i++) {
double s = -rr[rci.k][rci.j+i][rci.i+i];
z = s;
cblas_zaxpy(
n, &z, &W[rci.kx][rci.jx+i][0], 1, &W[rci.ky][rci.jy+i][0], 1
);
}
break;
case 15:
if ( rci.nx > 0 && rci.ny > 0 )
cblas_zgemm(
CblasColMajor, CblasTrans, CblasNoTrans, rci.nx, rci.ny, n,
&rci.alpha, &W[rci.kx][rci.jx][0], n, &W[rci.ky][rci.jy][0], n,
&rci.beta, &rr[rci.k][rci.j][rci.i], 2*m
);
break;
case 16: // Fall through to 17
case 17:
if( rci.job == 17 ) {
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.ny, rci.nx,
&ONE, &W[rci.kx][rci.jx][0], n, &rr[rci.k][rci.j][rci.i], 2*m,
&ZERO, &W[rci.ky][rci.jy][0], n
);
cblas_zcopy(
n*rci.ny, &W[rci.ky][rci.jy][0], 1, &W[rci.kx][rci.jx][0], 1
);
} else {
cblas_zgemm(
CblasColMajor, CblasNoTrans, CblasNoTrans, n, rci.ny, rci.nx,
&rci.alpha, &W[rci.kx][rci.jx][0], n, &rr[rci.k][rci.j][rci.i],
2*m, &rci.beta, &W[rci.ky][rci.jy][0], n
);
}
break;
}
}
| {
"alphanum_fraction": 0.4841242376,
"avg_line_length": 30.5578321216,
"ext": "c",
"hexsha": "81765f03f0fb908a41fbba2a29b78869800387d1",
"lang": "C",
"max_forks_count": 19,
"max_forks_repo_forks_event_max_datetime": "2022-02-28T14:58:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-09-30T20:52:47.000Z",
"max_forks_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "mjacobse/spral",
"max_forks_repo_path": "tests/ssmfe/ssmfe_ciface.c",
"max_issues_count": 51,
"max_issues_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898",
"max_issues_repo_issues_event_max_datetime": "2022-03-11T12:52:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-09-20T19:01:18.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "mjacobse/spral",
"max_issues_repo_path": "tests/ssmfe/ssmfe_ciface.c",
"max_line_length": 87,
"max_stars_count": 76,
"max_stars_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mjacobse/spral",
"max_stars_repo_path": "tests/ssmfe/ssmfe_ciface.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T00:11:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-03T13:58:37.000Z",
"num_tokens": 15503,
"size": 46234
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cblas.h>
#include <gsl/gsl_interp.h>
#include "allvars.h"
#include "proto.h"
#define SNR (120.0)
int n_con_sim=301, n_line_sim=301;
double sim_error=10.0*1.0/SNR, sim_rel_error=1.0/SNR;
double *PQmat, *PSmat, *Peigens, *Peigens_mat, *Peigens_vecs;
gsl_rng_type const * gsl_T_sim;
gsl_rng * gsl_r_sim;
gsl_interp_accel *gsl_acc, *gsl_acc_error;
gsl_interp *gsl_linear, *gsl_linear_error;
void simulate_con(double sigma, double tau, double alpha, double ave_con)
{
FILE *fscon_out;
double *Py, *Prandvec;
int i, info;
Py = array_malloc(n_con_sim);
Prandvec = array_malloc(n_con_sim);
simulate_con_init();
set_covar_Simmat(sigma, tau, alpha);
memcpy(PQmat, PSmat, n_con_sim*n_con_sim*sizeof(double));
/* eigen_sym_mat(PQmat, n_con_sim, Peigens, &info);
memcpy(Peigens_vecs, PQmat, n_con_sim*n_con_sim*sizeof(double));
for(i=0; i<n_con_sim; i++)
{
for(j=0; j<n_con_sim; j++)
Peigens_mat[i*n_con_sim+j] = 0.0;
Peigens_mat[i*n_con_sim+i] = sqrt(Peigens[i]);
}*/
for(i=0;i<n_con_sim; i++)
{
Prandvec[i] = gsl_ran_gaussian(gsl_r_sim, 1.0);
}
Chol_decomp_U(PQmat, n_con_sim, &info);
multiply_matvec(PQmat, Prandvec, n_con_sim, Py);
// multiply_matvec(Peigens_mat, Prandvec, n_con_sim, Pybuf);
// multiply_matvec(Peigens_vecs, Pybuf, n_con_sim, Py);
gsl_rng_set(gsl_r_sim, time(NULL));
for(i=0;i<n_con_sim;i++)
{
Fcon[i] = Py[i] + ave_con + sim_error * gsl_ran_gaussian(gsl_r_sim, 1.0);
Fcerrs[i] = sim_error;
}
fscon_out = fopen("data/sim_con.txt", "w");
for(i=0;i<n_con_sim;i++)
{
if(Tcon[i]>150.0)
fprintf(fscon_out, "%f\t%f\t%f\n", Tcon[i], Fcon[i], Fcerrs[i]);
}
gsl_interp_init(gsl_linear, Tcon, Fcon, n_con_sim);
gsl_interp_init(gsl_linear_error, Tcon, Fcerrs, n_con_sim);
fclose(fscon_out);
}
void simulate_con_init()
{
int i;
double Tcon_min, Tcon_max, Tline_min, Tline_max, dTs;
PSmat = array_malloc(n_con_sim*n_con_sim);
PQmat = array_malloc(n_con_sim*n_con_sim);
Peigens = array_malloc(n_con_sim);
Peigens_vecs = array_malloc(n_con_sim*n_con_sim);
Peigens_mat = array_malloc(n_con_sim*n_con_sim);
Tcon = array_malloc(n_con_sim);
Fcon = array_malloc(n_con_sim);
Fcerrs = array_malloc(n_con_sim);
Tcon_min = 0.0;
Tcon_max = 300.0;
dTs = (Tcon_max - Tcon_min) / (n_con_sim-1.0);
for(i=0; i<n_con_sim; i++)
{
Tcon[i] = dTs * i + Tcon_min;
}
Tline = array_malloc(n_line_sim);
Fline = array_malloc(n_line_sim);
Flerrs = array_malloc(n_line_sim);
Tline_min = 0.0;
Tline_max = 300.0;
dTs = (Tline_max - Tline_min) / (n_line_sim-1.0);
for(i=0; i<n_line_sim; i++)
{
Tline[i] = dTs * i + Tline_min;
}
gsl_acc = gsl_interp_accel_alloc();
gsl_acc_error = gsl_interp_accel_alloc();
gsl_linear = gsl_interp_alloc(gsl_interp_linear, n_con_sim);
gsl_linear_error = gsl_interp_alloc(gsl_interp_linear, n_con_sim);
gsl_T_sim = gsl_rng_default;
gsl_r_sim = gsl_rng_alloc (gsl_T_sim);
//gsl_rng_set(gsl_r_sim, 12);
gsl_rng_set(gsl_r_sim, time(NULL));
return;
}
void set_covar_Simmat(double sigma, double tau, double alpha)
{
double t1, t2, nerr;
int i, j;
for(i=0; i<n_con_sim; i++)
{
t1 = Tcon[i];
for(j=0; j<=i; j++)
{
t2 = Tcon[j];
PSmat[i*n_con_sim+j] = sigma*sigma* exp (- pow (fabs(t1-t2) / tau, alpha));
PSmat[j*n_con_sim+i] = PSmat[i*n_con_sim+j];
}
nerr = 0.0; //sim_error;
PSmat[i*n_con_sim+i] += nerr * nerr;
}
return;
}
void simulate_line()
{
int i, j;
double flux, err, tline, tcon, taup, norm, fcon, fcon_err;
double dtau, sig;
int type=1;
dtau = 30.0/(ntau-1.0);
for(i=0; i<ntau; i++)
{
TF_tau[i] = dtau * i;
TF[i] = 0.0;
}
// top-hat transfer function
FILE *ftf;
ftf=fopen("data/transfer_sim.txt", "w");
norm = 0.0;
for(i=0; i<ntau; i++)
{
if(type==0) // two top-hats
{
if(TF_tau[i]<=5.0)
TF[i] = 0.0;
else if(TF_tau[i]<10.0)
TF[i] = 1.0;
else if(TF_tau[i]<15.0)
TF[i] = 0.0;
else if(TF_tau[i]<20.0)
TF[i] = 2.0;
else
TF[i] = 0.0;
norm += TF[i] * dtau;
}
if(type==1) // two Gaussians
{
sig = 2.5;
TF[i] = exp(-0.5*pow(TF_tau[i]-10.0, 2.0)/sig/sig) + exp(-0.5*pow(TF_tau[i]-18.0, 2.0)/sig/sig);
norm += TF[i] * dtau;
}
}
for(i=0; i<ntau; i++)
{
TF[i] /= norm;
fprintf(ftf, "%f %f\n", TF_tau[i], TF[i]);
}
fclose(ftf);
FILE *fp;
fp = fopen("data/sim_line.txt", "w");
for(i=0; i<n_line_sim; i++)
{
flux = 0.0;
err = 0.0;
tline = Tline[i]; //4540.0 + 70.0/(nline_data-1.0) * i;
for(j=0; j<ntau; j++)
{
taup = TF_tau[j];
tcon = tline - taup;
if(tcon >=Tcon[0] && tcon <= Tcon[n_con_sim-1])
{
fcon = gsl_interp_eval(gsl_linear, Tcon, Fcon, tcon, gsl_acc);
fcon_err = gsl_interp_eval(gsl_linear_error, Tcon, Fcerrs, tcon, gsl_acc_error);
flux += fcon * TF[j];
err += pow(fcon_err *TF[j] * dtau, 2);
}
}
flux *= dtau;
err = sqrt(err);
Fline[i] = flux;
Flerrs[i] = sim_error;
}
gsl_rng_set(gsl_r_sim, time(NULL)); // reset the seed of the random generator
for(i=0; i<n_line_sim; i++)
{
if(Tline[i]>170.0)
fprintf(fp, "%f %f %f\n", Tline[i], Fline[i] + Flerrs[i]*gsl_ran_gaussian(gsl_r_sim, 1.0), Flerrs[i]);
}
fclose(fp);
} | {
"alphanum_fraction": 0.6169753641,
"avg_line_length": 23.764957265,
"ext": "c",
"hexsha": "10e73ab9f18ceb423136a79dbdc69fc56eed8881",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-04-12T11:48:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-12-29T06:04:13.000Z",
"max_forks_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/MICA",
"max_forks_repo_path": "src/sim.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"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": "LiyrAstroph/MICA",
"max_issues_repo_path": "src/sim.c",
"max_line_length": 108,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2592b8ad3011880898f557a69b22cad63fcd47e0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/MICA",
"max_stars_repo_path": "src/sim.c",
"max_stars_repo_stars_event_max_datetime": "2016-10-25T06:32:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-25T06:32:33.000Z",
"num_tokens": 2045,
"size": 5561
} |
/*
* Copyright (c) 2016-2021 lymastee, All rights reserved.
* Contact: lymastee@hotmail.com
*
* This file is part of the gslib project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#ifndef rendersysd3d11_8555fd57_19e9_4747_97b5_8d3bfb0fb50f_h
#define rendersysd3d11_8555fd57_19e9_4747_97b5_8d3bfb0fb50f_h
#include <gslib/type.h>
#include <ariel/rendersys.h>
__ariel_begin__
class rendersys_d3d11:
public rendersys
{
public:
rendersys_d3d11();
virtual ~rendersys_d3d11();
virtual bool setup(uint hwnd, const configs& cfg) override;
virtual void destroy() override;
virtual void setup_pipeline_state() override;
virtual render_blob* compile_shader_from_file(const gchar* file, const gchar* entry, const gchar* sm, render_include* inc) override;
virtual render_blob* compile_shader_from_memory(const char* src, int len, const gchar* name, const gchar* entry, const gchar* sm, render_include* inc) override;
virtual vertex_shader* create_vertex_shader(const void* ptr, size_t len) override;
virtual pixel_shader* create_pixel_shader(const void* ptr, size_t len) override;
virtual compute_shader* create_compute_shader(const void* ptr, size_t len) override;
virtual geometry_shader* create_geometry_shader(const void* ptr, size_t len) override;
virtual hull_shader* create_hull_shader(const void* ptr, size_t len) override;
virtual domain_shader* create_domain_shader(const void* ptr, size_t len) override;
virtual vertex_format* create_vertex_format(const void* ptr, size_t len, vertex_format_desc vfdesc[], uint n) override;
virtual vertex_buffer* create_vertex_buffer(uint stride, uint count, bool read, bool write, uint usage, const void* ptr) override;
virtual index_buffer* create_index_buffer(uint count, bool read, bool write, uint usage, const void* ptr) override;
virtual constant_buffer* create_constant_buffer(uint stride, bool read, bool write, const void* ptr) override;
virtual shader_resource_view* create_shader_resource_view(render_resource* res) override;
virtual depth_stencil_view* create_depth_stencil_view(render_resource* res) override;
virtual unordered_access_view* create_unordered_access_view(render_resource* res) override;
virtual sampler_state* create_sampler_state(sampler_state_filter filter) override;
virtual texture2d* create_texture2d(const image& img, uint mips, uint usage, uint bindflags, uint cpuflags, uint miscflags) override;
virtual texture2d* create_texture2d(int width, int height, uint format, uint mips, uint usage, uint bindflags, uint cpuflags, uint miscflags) override;
virtual void load_with_mips(texture2d* tex, const image& img) override;
virtual void update_buffer(void* buf, int size, const void* ptr) override;
virtual void set_vertex_format(vertex_format* vfmt) override;
virtual void set_vertex_buffer(vertex_buffer* vb, uint stride, uint offset) override;
virtual void set_index_buffer(index_buffer* ib, uint offset) override;
virtual void begin_render() override;
virtual void end_render() override;
virtual void set_render_option(render_option opt, uint val) override;
virtual void set_vertex_shader(vertex_shader* vs) override;
virtual void set_pixel_shader(pixel_shader* ps) override;
virtual void set_geometry_shader(geometry_shader* gs) override;
virtual void set_viewport(const viewport& vp) override;
virtual void set_constant_buffer(uint slot, constant_buffer* cb, shader_type st) override;
virtual void set_sampler_state(uint slot, sampler_state* sstate, shader_type st) override;
virtual void set_shader_resource(uint slot, shader_resource_view* srv, shader_type st) override;
virtual void draw(uint count, uint start) override;
virtual void draw_indexed(uint count, uint start, int base) override;
virtual void capture_screen(image& img, const rectf& rc, int buff_id) override;
virtual void enable_alpha_blend(bool b) override;
virtual void enable_depth(bool b) override;
protected:
D3D_DRIVER_TYPE _drvtype = D3D_DRIVER_TYPE_NULL;
D3D_FEATURE_LEVEL _level = D3D_FEATURE_LEVEL_11_0;
render_device* _device = nullptr;
render_context* _context = nullptr;
render_swap_chain* _swapchain = nullptr;
render_target_view* _rtview = nullptr;
render_blend_state* _blendstate = nullptr;
depth_stencil_view* _dsview = nullptr;
render_raster_state* _rasterstate = nullptr;
render_depth_state* _depthstate = nullptr;
uint _msaa_x = 0;
bool _vsync = false;
bool _fullscreen = false;
bool _msaa = false;
protected:
void install_configs(const configs& cfg);
public:
render_device* get_device() const { return _device; }
render_context* get_immediate_context() const { return _context; }
};
template<class res_class>
inline render_resource* convert_to_resource(res_class* p)
{ return static_cast<render_resource*>(p); }
__ariel_end__
#endif
| {
"alphanum_fraction": 0.7345007099,
"avg_line_length": 55.1217391304,
"ext": "h",
"hexsha": "d454485979fddc39220ec6f3229dc34c345005e3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/ariel/rendersysd3d11.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/ariel/rendersysd3d11.h",
"max_line_length": 165,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/ariel/rendersysd3d11.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": 1437,
"size": 6339
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <math.h>
#include <unistd.h>
#include <limits.h>
#include <sys/time.h>
#include <zlib.h>
#ifdef INTEL_COMPILER
#include "mkl.h"
#else
#include <cblas.h>
#endif
//#define FIBS_UNIT 1000
#define DEFAULT_NDIGITS 10
#define SZBUF 1024
#define SZBYTE 256
#define N_GENOTYPES 4
#define NA_GENO_CHAR (N_GENOTYPES-1)
#define DEFAULT_ROW_SIZE 100000
#define DEFAULT_SIZE_MATRIX 1000000
#define DEFAULT_SIZE_HEADER 100000
#define DEFAULT_DELIMS " \t\r\n"
#define SZ_LONG_BUF 1000000
#define DEFAULT_TPED_NUM_HEADER_COLS 4
#define DEFAULT_TFAM_NUM_HEADER_COLS 6
#define DEFAULT_TPED_SNPID_INDEX 1
#define DEFAULT_PHENO_NUM_HEADER_COLS 2
struct HFILE {
int gzflag; // 1 if gz if used
int wflag; // r(0)/w(1) for plain, rb(0)/wb(1) for gz
int nheadercols; // # of header columns (0 if nrows=0)
int nvaluecols; // # of value cols (0 if nrows=0)
int nrows; // # of rows
FILE* fp; // plain file handle
gzFile gzfp; // gzip file handle
};
// Input routines
void close_file (struct HFILE* fhp);
struct HFILE open_file(char* filename, int gzflag, int wflag);
struct HFILE open_file_with_suffix(char* prefix, char* suffix, int gzflag, int wflag);
//void read_matrix_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int symmetric, int* p_nmiss, unsigned char** matrix, char*** headers);
void read_matrix_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int* p_nmiss, unsigned char** matrix, char*** headers);
unsigned char* tokenize_tped_line_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, char* lbuf, unsigned char* values, char** headers, int* p_nvalues, int* p_nmiss );
void emmax_error( const char* format, ... );
void print_help(void);
FILE* readfile(char* filename);
void print_help(void) {
fprintf(stderr,"Usage: emmax_kin [tpedf]\n");
fprintf(stderr,"Required parameters\n");
fprintf(stderr,"\t[tpedf] : tped file\n");
fprintf(stderr,"Optional parameters\n");
fprintf(stderr,"\t-d [# digits] : precision of the kinship values (default : 10)\n");
fprintf(stderr,"\t-M [float] : maximum memory in GB (default: 4.0)\n");
fprintf(stderr,"\t-s : compute IBS kinship matrix (default is Balding-Nicholas)\n");
fprintf(stderr,"\t-v : turn on verbose mode\n");
fprintf(stderr,"\t-r : randomly fill missing genotypes (default is imputation by average)\n");
fprintf(stderr,"\t-x : include non-autosomal chromosomes in computing kinship matrices\n");
fprintf(stderr,"\t-S [int] : set random seed\n");
fprintf(stderr,"\t-m [float] : MAF threshold (default is 0)\n");
fprintf(stderr,"\t-c [float] : Call rate threshold (default is 0)\n");
}
//void read_matrix_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int symmetric, int* p_nmiss, unsigned char** matrix, char*** headers) {
void read_matrix_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, int* p_nmiss, unsigned char** matrix, char*** headers) {
char* lbuf = (char*) malloc(sizeof(char*) * SZ_LONG_BUF);
int szmat = DEFAULT_SIZE_MATRIX;
int szheader = DEFAULT_SIZE_HEADER;
unsigned char* cmat = (unsigned char*) malloc(sizeof(unsigned char) * szmat );
char** cheaders = (char**) malloc(sizeof(char*) * szheader );
int nvalues, i, j, nmiss;
fhp->nheadercols = nheadercols;
nmiss = 0;
while( tokenize_tped_line_with_col_headers(fhp, nheadercols, delims, lbuf, &cmat[fhp->nrows*fhp->nvaluecols], &cheaders[fhp->nrows*fhp->nheadercols], &nvalues, &nmiss) != NULL ) {
if ( fhp->nrows == 1 ) {
fhp->nvaluecols = nvalues;
}
else if ( fhp->nvaluecols != nvalues ) {
emmax_error("The column size %d do not match to %d at line %d\n",nvalues,fhp->nvaluecols,fhp->nrows);
}
if ( (fhp->nrows+1)*(fhp->nvaluecols) > szheader ) {
szheader *= 2;
fprintf(stderr,"Header size is doubled to %d\n",szheader);
cheaders = (char**) realloc( cheaders, sizeof(char*) * szheader );
}
if ( (fhp->nrows+1)*(fhp->nvaluecols) > szheader ) {
szmat *= 2;
fprintf(stderr,"Matrix size is doubled to %d\n",szmat);
cmat = (unsigned char*) realloc( cmat, sizeof(unsigned char) * szmat );
}
}
free(lbuf);
*p_nmiss = nmiss;
unsigned char* fmat = (unsigned char*) malloc(sizeof(unsigned char)*fhp->nrows*fhp->nvaluecols);
char** fheaders = (char**) malloc(sizeof(char*)*fhp->nrows*fhp->nheadercols);
for(i=0; i < fhp->nrows; ++i) {
for(j=0; j < fhp->nvaluecols; ++j) {
fmat[i+j*fhp->nrows] = cmat[i*fhp->nvaluecols+j];
}
for(j=0; j < fhp->nheadercols; ++j) {
fheaders[i+j*fhp->nrows] = cheaders[i*fhp->nheadercols+j];
}
}
free(cmat);
free(cheaders);
if ( matrix != NULL ) {
if ( *matrix != NULL ) {
free(*matrix);
}
*matrix = fmat;
}
if ( headers != NULL ) {
if ( *headers != NULL ) {
free(*headers);
}
*headers = fheaders;
}
}
unsigned char* tokenize_tped_line_with_col_headers( struct HFILE* fhp, int nheadercols, char* delims, char* lbuf, unsigned char* values, char** headers, int* p_nvalues, int* p_nmiss ) {
int j;
char *token;
unsigned char ctoken;
char *ret = (fhp->gzflag == 1) ? gzgets(fhp->gzfp, lbuf, SZ_LONG_BUF) : fgets( lbuf, SZ_LONG_BUF, fhp->fp );
int nmiss = 0;
if ( ret == NULL ) {
return NULL;
}
if ( fhp->nheadercols != nheadercols ) {
emmax_error("# of header columns mismatch (%d vs %d) at line %d",fhp->nheadercols,nheadercols,fhp->nrows);
}
//fprintf(stderr,"tokenize-line called %s\n",lbuf);
token = strtok(lbuf, delims);
for( j=0; token != NULL; ++j ) {
if ( j < nheadercols ) {
headers[j] = strdup(token);
}
// if zero_miss_flag is set, assume the genotypes are encoded 0,1,2
// Additively encodes the two genotypes in the following way
// when (j-nheadercols) is even, 0->MISSING, add 1->0, 2->1
// when (j-nheadercols) is odd, check 0-0 consistency, and add 1->0, 2->1
else {
ctoken = (unsigned char)(token[0]-'0');
if ( ctoken > 2 ) {
fprintf(stderr,"Unrecognized token %s\n",token);
abort();
}
if ( (j-nheadercols) % 2 == 0 ) {
values[(j-nheadercols)/2] = ctoken;
}
else {
if ( ( ctoken > 0 ) && ( values[(j-nheadercols)/2] == 0 ) ) {
fprintf(stderr,"Unmatched token pair 0 %s\n",token);
abort();
}
else if ( ( ctoken == 0 ) && ( values[(j-nheadercols)/2] > 0 ) ) {
fprintf(stderr,"Unmatched token pair - %d 0\n",(int)values[(j-nheadercols)/2]);
abort();
}
values[(j-nheadercols)/2] = (unsigned char)(values[(j-nheadercols)/2]+ctoken);
}
}
token = strtok(NULL, delims);
}
//fprintf(stderr,"tokenize-line ended %d %d\n",j,nheadercols);
if ( (j-nheadercols) % 2 != 0 ) {
fprintf(stderr,"Number of value tokens are not even %d\n",j-nheadercols);
abort();
}
*p_nvalues = (j-nheadercols)/2;
*p_nmiss += nmiss;
++(fhp->nrows);
if ( j < nheadercols ) {
fprintf(stderr,"Number of header columns are %d, but only %d columns were observed\n", nheadercols, j);
abort();
}
return values;
}
// open_file_with_suffix()
// - [prefix].[suffix] : file name to open
// - gzflag : gzip flag (use gzfp if gzflag=1, otherwise use fp)
// - wflag : write flag (1 if write mode otherwise read mode
struct HFILE open_file_with_suffix(char* prefix, char* suffix, int gzflag, int wflag) {
char filename[SZBUF];
sprintf(filename,"%s.%s",prefix,suffix);
return open_file(filename,gzflag,wflag);
}
// open_file()
// - filename : file name to open
// - gzflag : gzip flag (use gzfp if gzflag=1, otherwise use fp)
// - wflag : write flag (1 if write mode otherwise read mode)
struct HFILE open_file(char* filename, int gzflag, int wflag) {
struct HFILE fh;
fh.gzflag = gzflag;
fh.wflag = wflag;
fh.nheadercols = 0;
fh.nvaluecols = 0;
fh.nrows = 0;
if ( gzflag == 1 ) {
char* mode = (wflag == 1) ? "wb" : "rb";
fh.gzfp = gzopen(filename,mode);
fh.fp = NULL;
if ( fh.gzfp == NULL ) {
emmax_error("Cannot open file %s for reading",filename);
}
}
else {
char* mode = (wflag == 1) ? "w" : "r";
fh.gzfp = (gzFile) NULL;
fh.fp = fopen(filename,mode);
if ( fh.fp == NULL ) {
emmax_error("Cannot open file %s for writing",filename);
}
}
return fh;
}
void emmax_error( const char* format, ... ) {
va_list args;
fprintf(stderr, "ERROR: ");
va_start (args, format);
vfprintf(stderr, format, args);
va_end (args);
fprintf(stderr,"\n");
abort();
}
void close_file(struct HFILE* fhp) {
if ( fhp->gzflag == 1 ) {
gzclose(fhp->gzfp);
fhp->gzfp = NULL;
}
else {
fclose(fhp->fp);
fhp->fp = NULL;
}
}
int main(int argc, char** argv) {
int i, j, n, c, ac0, ac1, ac2, nmiss, nelems, nex, n_sum_nin, nin, nex_maf, nex_call_rate, nex_autosomal;
int verbose, ndigits, tped_nheadercols, tfam_nheadercols, flag_autosomal, rand_fill_flag, ibs_flag, n_unit_lines;
unsigned char *snprow;
char *suffix, buf[SZBUF];
double f, max_memory_GB, maf_thres, call_rate_thres, aaf, call_rate;
//long *fibs_sums, *scores, mean_score;
double *kin, *snpunit;
char *tpedf, *delims, *lbuf;
char **tfam_headers, **tped_headers;
struct HFILE tpedh, tfamh, kinsh;
struct timeval tv;
// set default params
gettimeofday(&tv, NULL);
srand((unsigned int)tv.tv_usec);
delims = DEFAULT_DELIMS;
tped_nheadercols = DEFAULT_TPED_NUM_HEADER_COLS;
tfam_nheadercols = DEFAULT_TFAM_NUM_HEADER_COLS;
tped_headers = tfam_headers = NULL;
tpedf = lbuf = 0;
flag_autosomal = 1;
rand_fill_flag = 0;
ibs_flag = 0;
verbose = 0;
ndigits = DEFAULT_NDIGITS;
max_memory_GB = 4.0; // 4.0GB
maf_thres = 0.0;
call_rate_thres = 0.0;
// read arguments and update params
while ((c = getopt(argc, argv, "d:rsc:vxS:M:m:c:")) != -1 ) {
switch(c) {
case 'd': // precision of digits
ndigits = atoi(optarg);
break;
case 'r':
rand_fill_flag = 1;
break;
case 's':
ibs_flag = 1;
break;
case 'v':
verbose = 1;
break;
case 'x':
flag_autosomal = 0;
break;
case 'S':
srand(atoi(optarg));
break;
case 'M':
max_memory_GB = atof(optarg);
break;
case 'm':
maf_thres = atof(optarg);
break;
case 'c':
call_rate_thres = atof(optarg);
break;
default:
fprintf(stderr,"Error : Unknown option unsigned character %c\n",c);
abort();
}
}
// Sanity check for the number of required parameters
if ( argc != optind + 1 ) {
print_help();
abort();
}
// Read required parameters
tpedf = argv[optind++];
if ( verbose) fprintf(stderr,"\nReading TFAM file %s.tfam ....\n",tpedf);
tfamh = open_file_with_suffix(tpedf, "tfam", 0, 0);
//read_matrix_with_col_headers( &tfamh, tfam_nheadercols, delims, 0, &nmiss, NULL, &tfam_headers);
read_matrix_with_col_headers( &tfamh, tfam_nheadercols, delims, &nmiss, NULL, &tfam_headers);
n = tfamh.nrows; // n is # of individuals
if ( verbose ) fprintf(stderr,"Identified %d individuals from TFAM file\n",n);
// compute the # of lines to read together
// we would need two n*n matrix, and n*m matrix
// (n*n + n*m)*sizeof(double) < M*1e9
// m < M*1e9/sizeof(double)/n - n
n_unit_lines = (int)floor((max_memory_GB * 1.0e9 / sizeof(double) / n - n)/2)*2;
n_sum_nin = 0;
#ifdef INTEL_COMPILER
char cn = 'N', ct = 'T';
double one = 1.;
#endif
if ( verbose ) fprintf(stderr,"Setting # unit lines = %d to fit the memory requirement\n",n_unit_lines);
snprow = (unsigned char*)malloc(sizeof(unsigned char)*n);
tped_headers = (char**)malloc(sizeof(char*)*n);
lbuf = (char*) malloc(sizeof(char*) * SZ_LONG_BUF);
kin = (double*)calloc(n*n, sizeof(double));
snpunit = (double*)malloc(n*n_unit_lines * sizeof(double));
if ( verbose) fprintf(stderr,"Reading TPED file %s.tped ....\n",tpedf);
tpedh = open_file_with_suffix(tpedf, "tped", 0, 0);
tpedh.nheadercols = tped_nheadercols;
nex_autosomal = nex_maf = nex_call_rate = 0;
for ( i=0, nin=0, nex = 0; tokenize_tped_line_with_col_headers( &tpedh, tped_nheadercols, delims, lbuf, snprow, tped_headers, &nelems, &nmiss) != NULL; ++i) {
if ( ( verbose ) && ( i % 10000 ) == 0 ) fprintf(stderr,"Reading %d SNPs\n",i);
if ( ( flag_autosomal == 1 ) && ( ( atoi(tped_headers[0]) == 0 ) || ( atoi(tped_headers[0]) > 22 ) ) ) // if SNP is not in autosomal chromosomes
//if ( ( flag_autosomal == 1 ) && ( atoi(tped_headers[0]) > 22 ) ) // if SNP is not in autosomal chromosomes
{
++nex; // # excluded snps from the last unit
++nex_autosomal;
continue;
}
if ( nelems != n ) {
emmax_error("Number of values %d in line %d do not match to %d, the number of columns\n", nelems, tpedh.nvaluecols, n);
}
/*
Perform rapid kinship generate IBS, BN, NCOR matrix
--------------------
IBS pairwise matrix
--------------------
i/j 0 1 2 3
0 NA NA NA NA
1 NA 2 1 0
2 NA 1 2 1
3 NA 0 1 2
In fact is what it does is
X = (m*n) genotype matrix (1,2,3 coded)
Xn = X-2
K = (t(Xn) %*% Xn)/(2*m)
------------------
* NA column may be just averaged or predicted based on r2 with previous SNP
with a certain window size
---------------------
pairwise BN matrix
--------------------
X : (m*n) genotype matrix
Xn : (m*n) matrix each row standardized, missing assigned to 0
K = t(Xn) %*% Xn / L
--------------------
*/
ac0 = ac1 = ac2 = 0;
for(j=0; j < n; ++j) {
if ( snprow[j] > 0 ) {
if ( snprow[j] < 2 ) {
fprintf(stderr,"Invalid snprow[%d] value %d at line %d, individual %d\n",j,(int)snprow[j],i,j);
}
snprow[j] -= 2; // from 2,3,4 to 0,1,2 coding
switch(snprow[j]) {
case 0:
++ac0;
break;
case 1:
++ac1;
break;
case 2:
++ac2;
break;
default:
emmax_error("Unknown allele %s, converted to %d\n",buf,(int)snprow[j]);
break;
}
}
else {
snprow[j] = (unsigned char)NA_GENO_CHAR;
}
}
call_rate = (double)(ac0+ac1+ac2)/(double)n;
//fprintf(stderr,"CallRate = %lf\n", call_rate);
if ( call_rate <= call_rate_thres ) {
++nex;
++nex_call_rate;
continue;
}
aaf = (double)(ac1+2*ac2)/(double)(2*(ac0+ac1+ac2));
if ( ( aaf <= maf_thres ) || ( 1.-aaf <= maf_thres ) ) {
++nex;
++nex_maf;
continue;
}
if ( rand_fill_flag == 1 ) {
for(j=0; j < n; ++j) {
if ( snprow[j] == (unsigned char)NA_GENO_CHAR ) {
if ( (rand() / (double) RAND_MAX) > aaf ) {
if ( (rand() / (double) RAND_MAX) > aaf ) {
snprow[j] = (unsigned char)2;
//ac1 += 2;
++ac2;
}
else {
snprow[j] = (unsigned char)1;
++ac1;
//++ac0;
//++ac1;
}
}
else {
if ( (rand() / (double) RAND_MAX) > aaf ) {
snprow[j] = (unsigned char)1;
++ac1;
//++ac0;
//++ac1;
}
else {
snprow[j] = (unsigned char)0;
++ac0;
//ac0 += 2;
}
}
}
}
aaf = (double)(ac1+2*ac2)/(double)(2*(ac0+ac1+ac2));
//aaf = (double)ac1/(double)(ac0+ac1);
}
// copy current values to arrays
// Xn = [-1,1] - two rows per SNP : IBS matrix
// Xn ~ N(0,1) : BN matrix
if ( ibs_flag == 1 ) {
for(j=0; j < n; ++j) {
if ( snprow[j] == (unsigned char)NA_GENO_CHAR ) {
snpunit[nin+ j*n_unit_lines] = 2.*aaf-1.;
snpunit[nin+1+j*n_unit_lines] = 2.*aaf-1.;
}
else {
if ( snprow[j] == 0 ) {
snpunit[nin+ j*n_unit_lines] = -1.;
snpunit[nin+1+j*n_unit_lines] = -1.;
}
else if ( snprow[j] == 1 ) {
snpunit[nin+ j*n_unit_lines] = 1.;
snpunit[nin+1+j*n_unit_lines] = -1.;
}
else if ( snprow[j] == 2 ) {
snpunit[nin+ j*n_unit_lines] = 1.;
snpunit[nin+1+j*n_unit_lines] = 1.;
}
else {
emmax_error("Invalid genotype %d\n",snprow[j]);
}
}
}
nin += 2;
}
else {
for(j=0; j < n; ++j) {
if ( snprow[j] == (unsigned char)NA_GENO_CHAR ) {
snpunit[nin+j*n_unit_lines] = 0.;
}
else {
snpunit[nin+j*n_unit_lines] = ((double)snprow[j]-(aaf*2.))/sqrt(4*aaf*(1-aaf));
}
}
++nin;
}
// check if nin == n_unit_lines
if ( nin >= n_unit_lines ) {
if ( verbose ) {
fprintf(stderr,"At SNP %d, intermediately computing kinship matrix with %d SNPs..\n",i,n_unit_lines);
}
// kin = kin + t(snpunit)%*%(snpunit)
#ifdef INTEL_COMPILER
dgemm(&ct,&cn,&n,&n,&n_unit_lines,&one,snpunit,&n_unit_lines,snpunit,&n_unit_lines,&one,kin,&n);
#else
cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n, n, n_unit_lines, 1.0, snpunit, n_unit_lines, snpunit, n_unit_lines, 1.0, kin, n);
#endif
memset(snpunit, 0, sizeof(double)*n_unit_lines*n);
n_sum_nin += nin;
nin = 0;
}
}
close_file(&tpedh);
if ( verbose ) {
fprintf(stderr,"Succesfully finished reading TPED file\n");
}
if ( nin > 0 ) {
if ( verbose ) {
fprintf(stderr,"Computing kinship matrix with the remaining %d SNPs..\n",nin);
}
#ifdef INTEL_COMPILER
dgemm(&ct,&cn,&n,&n,&n_unit_lines,&one,snpunit,&n_unit_lines,snpunit,&n_unit_lines,&one,kin,&n);
#else
cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n, n, n_unit_lines, 1.0, snpunit, n_unit_lines, snpunit, n_unit_lines, 1.0, kin, n);
#endif
n_sum_nin += nin;
}
if ( ibs_flag == 1 ) {
if ( rand_fill_flag == 1 ) {
suffix = "rIBS.kinf";
}
else {
suffix = "aIBS.kinf";
}
}
else {
if ( rand_fill_flag == 1 ) {
suffix = "rBN.kinf";
}
else {
suffix = "aBN.kinf";
}
}
kinsh = open_file_with_suffix( tpedf, suffix, 0, 1 );
if ( verbose ) fprintf(stderr,"Printing the kinship matrix to file %s.%s\n",tpedf,suffix);
for(i=0; i < n; ++i) {
for(j=0; j < n; ++j) {
if ( j > 0 ) fprintf(kinsh.fp,"\t");
f = (double)kin[i+j*n]/(double)(n_sum_nin);
if ( ibs_flag == 1 ) {
fprintf(kinsh.fp,"%-.*lf",ndigits,0.5*f+0.5);
}
else {
fprintf(kinsh.fp,"%-.*lf",ndigits,f);
}
}
fprintf(kinsh.fp,"\n");
}
close_file(&kinsh);
free(snprow);
free(kin);
free(snpunit);
free(lbuf);
free(tped_headers);
free(tfam_headers);
return 0;
}
| {
"alphanum_fraction": 0.6080786026,
"avg_line_length": 29.7402597403,
"ext": "c",
"hexsha": "5e67228a536e4a2fccf07bd7d258d7a3051e3b97",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-06-26T15:01:39.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-26T15:01:39.000Z",
"max_forks_repo_head_hexsha": "b214b602a8f7f90e13ab4b9ddeba811b67c03a19",
"max_forks_repo_licenses": [
"Intel"
],
"max_forks_repo_name": "slowkoni/EPI-EMMAX",
"max_forks_repo_path": "emmax-kin.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "b214b602a8f7f90e13ab4b9ddeba811b67c03a19",
"max_issues_repo_issues_event_max_datetime": "2021-06-23T09:15:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-06-23T09:15:17.000Z",
"max_issues_repo_licenses": [
"Intel"
],
"max_issues_repo_name": "slowkoni/EPI-EMMAX",
"max_issues_repo_path": "emmax-kin.c",
"max_line_length": 185,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b214b602a8f7f90e13ab4b9ddeba811b67c03a19",
"max_stars_repo_licenses": [
"Intel"
],
"max_stars_repo_name": "slowkoni/EPI-EMMAX",
"max_stars_repo_path": "emmax-kin.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6049,
"size": 18320
} |
#pragma once
#include "CesiumGltfWriter/Library.h"
#include <CesiumJsonWriter/ExtensionWriterContext.h>
#include <gsl/span>
// forward declarations
namespace CesiumGltf {
struct Model;
}
namespace CesiumGltfWriter {
/**
* @brief The result of writing a glTF with
* {@link GltfWriter::writeGltf} or {@link GltfWriter::writeGlb}
*/
struct CESIUMGLTFWRITER_API GltfWriterResult {
/**
* @brief The final generated std::vector<std::byte> of the glTF or glb.
*/
std::vector<std::byte> gltfBytes;
/**
* @brief Errors, if any, that occurred during the write process.
*/
std::vector<std::string> errors;
/**
* @brief Warnings, if any, that occurred during the write process.
*/
std::vector<std::string> warnings;
};
/**
* @brief Options for how to write a glTF.
*/
struct CESIUMGLTFWRITER_API GltfWriterOptions {
/**
* @brief If the glTF JSON should be pretty printed. Usable with glTF or GLB
* (not advised).
*/
bool prettyPrint = false;
/**
* @brief Byte alignment of the GLB binary chunk. When using 64-bit types in
* EXT_mesh_features or EXT_feature_metadata this value should be set to 8.
*/
size_t binaryChunkByteAlignment = 4;
};
/**
* @brief Writes glTF.
*/
class CESIUMGLTFWRITER_API GltfWriter {
public:
/**
* @brief Constructs a new instance.
*/
GltfWriter();
/**
* @brief Gets the context used to control how glTF extensions are written.
*/
CesiumJsonWriter::ExtensionWriterContext& getExtensions();
/**
* @brief Gets the context used to control how glTF extensions are written.
*/
const CesiumJsonWriter::ExtensionWriterContext& getExtensions() const;
/**
* @brief Serializes the provided model into a glTF JSON byte vector.
*
* @details Ignores internal data such as {@link CesiumGltf::BufferCesium}
* and {@link CesiumGltf::ImageCesium} when serializing the glTF. Internal
* data must either be converted to data uris or saved as external files. The
* buffer.uri and image.uri fields must be set accordingly prior to calling
* this function.
*
* @param model The model.
* @param options Options for how to write the glTF.
* @return The result of writing the glTF.
*/
GltfWriterResult writeGltf(
const CesiumGltf::Model& model,
const GltfWriterOptions& options = GltfWriterOptions()) const;
/**
* @brief Serializes the provided model into a glb byte vector.
*
* @details The first buffer object implicitly refers to the GLB binary chunk
* and should not have a uri. Ignores internal data such as
* {@link CesiumGltf::BufferCesium} and {@link CesiumGltf::ImageCesium}.
*
* @param model The model.
* @param bufferData The buffer data to store in the GLB binary chunk.
* @param options Options for how to write the glb.
* @return The result of writing the glb.
*/
GltfWriterResult writeGlb(
const CesiumGltf::Model& model,
const gsl::span<const std::byte>& bufferData,
const GltfWriterOptions& options = GltfWriterOptions()) const;
private:
CesiumJsonWriter::ExtensionWriterContext _context;
};
} // namespace CesiumGltfWriter
| {
"alphanum_fraction": 0.7023506989,
"avg_line_length": 27.8584070796,
"ext": "h",
"hexsha": "9cedeee58340a0244aaa0b5cab255ed3cac7c918",
"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": "9493b9baebea601bd00d8139f2000e41ba4505ef",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "yieryi/cesium-native",
"max_forks_repo_path": "CesiumGltfWriter/include/CesiumGltfWriter/GltfWriter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef",
"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": "yieryi/cesium-native",
"max_issues_repo_path": "CesiumGltfWriter/include/CesiumGltfWriter/GltfWriter.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9493b9baebea601bd00d8139f2000e41ba4505ef",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "yieryi/cesium-native",
"max_stars_repo_path": "CesiumGltfWriter/include/CesiumGltfWriter/GltfWriter.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 850,
"size": 3148
} |
/**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
**/
#ifndef PLASMA_CORE_LAPACK_H
#define PLASMA_CORE_LAPACK_H
#if defined(HAVE_MKL) || defined(PLASMA_WITH_MKL)
#define MKL_Complex16 double _Complex
#define MKL_Complex8 float _Complex
#include <mkl_cblas.h>
#include <mkl_lapacke.h>
// MKL LAPACKE doesn't provide LAPACK_GLOBAL macro, so define it here.
// MKL provides all 3 name manglings (foo, foo_, FOO); pick foo_.
#ifndef LAPACK_GLOBAL
#define LAPACK_GLOBAL(lcname,UCNAME) lcname##_
#endif
#elif defined(HAVE_ESSL) || defined(PLASMA_WITH_ESSL)
// GCC + ESSL(BLAS) + LAPACKE/CBLAS from LAPACK
#include <cblas.h>
#include <lapacke.h>
#ifndef LAPACK_GLOBAL
#define LAPACK_GLOBAL(lcname,UCNAME) lcname##_
#endif
#else
#include <cblas.h>
#include <lapacke.h>
// Original cblas.h does: enum CBLAS_ORDER {...};
// Intel mkl_cblas.h does: typedef enum {...} CBLAS_ORDER;
// LAPACK cblas.h does: typedef enum {...} CBLAS_ORDER;
// OpenBLAS cblas.h does: typedef enum CBLAS_ORDER {...} CBLAS_ORDER;
// We use (CBLAS_ORDER), so add these typedefs for original cblas.h
#ifdef CBLAS_ADD_TYPEDEF
typedef enum CBLAS_ORDER CBLAS_ORDER;
typedef enum CBLAS_TRANSPOSE CBLAS_TRANSPOSE;
typedef enum CBLAS_UPLO CBLAS_UPLO;
typedef enum CBLAS_DIAG CBLAS_DIAG;
typedef enum CBLAS_SIDE CBLAS_SIDE;
#endif
#endif
#ifndef lapack_int
#define lapack_int int
#endif
#include "core_lapack_s.h"
#include "core_lapack_d.h"
#include "core_lapack_c.h"
#include "core_lapack_z.h"
#endif // PLASMA_CORE_LAPACK_H
| {
"alphanum_fraction": 0.7052941176,
"avg_line_length": 27.868852459,
"ext": "h",
"hexsha": "79a2f2ef8c8b37c7dae87e999924b0a9ba93dcab",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-01-14T02:02:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-03T13:52:42.000Z",
"max_forks_repo_head_hexsha": "704252200078c59f5fee541302b76fcfc04c3e90",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "panakour1/plasma",
"max_forks_repo_path": "include/core_lapack.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "704252200078c59f5fee541302b76fcfc04c3e90",
"max_issues_repo_issues_event_max_datetime": "2022-03-09T18:00:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-09-14T13:17:51.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "panakour1/plasma",
"max_issues_repo_path": "include/core_lapack.h",
"max_line_length": 74,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "704252200078c59f5fee541302b76fcfc04c3e90",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "panakour1/plasma",
"max_stars_repo_path": "include/core_lapack.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-30T01:39:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-07T13:52:02.000Z",
"num_tokens": 530,
"size": 1700
} |
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include "../include/type.h"
#include "../include/util.h"
#include "../include/myfunc.h"
#include "../include/global.h"
double rho = 0.9;
double cutoff = 0.0001;
clock_t dur = 0;
// char *optarg;
// int optind = 0;
int main(int argc, char *argv[]) {
char *inputf = "input.txt", *outputf = (char*)malloc(sizeof(char)*MAX_CHAR);
char str_line[MAX_LINE], *title_element_list[100];
int nthread = 1, batch_size = 1, opt, row_num = 0, i = 0;
while ((opt = getopt(argc, argv, "t:bc:o:i:")) != -1) {
switch (opt) {
case 't':
nthread = atoi(optarg);
break;
case 'b':
batch_size = 0;
break;
case 'c':
cutoff = atof(optarg);
break;
case 'o':
// strcpy(outputf, optarg);
// strcat(outputf, "/rMATS_Result_P.txt");
outputf = optarg;
break;
case 'i':
inputf = optarg;
break;
default: /* '?' */
fprintf(stderr, "Usage: %s [-t nthread] [-c] cutoff [-o] output folder [-i] input file\n", argv[0]);
exit(EXIT_FAILURE);
}
}
printf("number of thread=%d; input file=%s; output folder=%s; cutoff=%g;\n",\
nthread, inputf, outputf, cutoff);
if (optind > argc) {
fprintf(stderr, "Expected argument after options\n");
exit(EXIT_FAILURE);
}
if (nthread > MAXTHREAD) {
printf("nthread (%d) should be less than MAXTHREAD (%d)\n", nthread, MAXTHREAD);
exit(0);
}
diff_list_node *list = (diff_list_node*)malloc(sizeof(diff_list_node));
list->data = NULL, list->next = NULL, list->end = list;
row_num = parse_file(inputf, list, title_element_list);
clock_t start, diff;
start = clock();
odiff *datum[row_num];
diff_list_node *node = list;
double *prob[row_num];
for (i = 0; i < row_num; ++i) {
node = node->next;
datum[i] = node->data;
}
mp_threadpool(nthread, row_num, thread_wrapper_for_LT, (void**)datum, (void**)prob);
diff = clock() - start;
int msec = diff * 1000 / CLOCKS_PER_SEC;
printf("Total Wallclock time taken %d seconds %d milliseconds\n", msec/1000, msec%1000);
printf("Wallclock time per thread taken %d seconds %d milliseconds\n", msec/1000/nthread, (msec%1000)/nthread);
FILE *ifp = NULL, *ofp = NULL;
if ((ifp = fopen(inputf, "r")) == NULL) {
printf("Fail to open %s!", inputf);
return -1;
}
if ((ofp = fopen(outputf, "w")) == NULL) {
printf("Fail to open %s!", outputf);
return -1;
}
// original comment: analyze the title of the inputed data file to find the
// information of how much simulation are involved
fgets(str_line, MAX_LINE, ifp);
str_line[strlen(str_line)-1] = 0;
fprintf(ofp, "%s\tPValue\n", str_line);
for (i = 0; i < row_num; ++i) {
fgets(str_line, MAX_LINE, ifp);
str_line[strlen(str_line)-1] = 0;
fprintf(ofp, "%s\t%.12g\n", str_line, *prob[i]);
}
fclose(ifp);
fclose(ofp);
msec = dur * 1000 / CLOCKS_PER_SEC;
printf("Time for func(single thread): %d seconds %d milliseconds\n", msec/1000, msec%1000);
return 0;
}
| {
"alphanum_fraction": 0.5689953811,
"avg_line_length": 30.1217391304,
"ext": "c",
"hexsha": "3611301b19b7664b7248259235c36b0b55f3e2e4",
"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": "c651509a5d32799315054fa37a2210fab2aae5e5",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "Aslic/rmats_turbo_4.1.0",
"max_forks_repo_path": "rMATS_C/src/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c651509a5d32799315054fa37a2210fab2aae5e5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "Aslic/rmats_turbo_4.1.0",
"max_issues_repo_path": "rMATS_C/src/main.c",
"max_line_length": 115,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c651509a5d32799315054fa37a2210fab2aae5e5",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "Aslic/rmats_turbo_4.1.0",
"max_stars_repo_path": "rMATS_C/src/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 982,
"size": 3464
} |
#ifndef COVAR_H_
#define COVAR_H_
#include <stdio.h>
#include <gsl/gsl_statistics_double.h>
#include <gsl/gsl_matrix_double.h>
#include <vector>
// \TODO: trim excess comments
// \TODO: split this into an implementation file
/*
* Okay, so here's what we need
* 1) A data structure to store the data points (vector?)
* 2) A way of packaging the data points (struct of floats?)
* 3) A method to push new data points onto the data structure
*
* So the above is an API towards collecting data. On the ROS side,
* 1) As new messages from the ROS topic arrives, we need the
* data_structure.push() to happen
*
* Next, we need a method for generating the covariance matrix. This
* should happen after the data collection period has expired. What needs
* to happen when we generate the covariance matrix?
* 1) Convert the data_structure into a gsl_matrix
* 2) Don't forget to allocate another gsl_matrix which will hold the
* resulting covariance matrix.
* 3) Double for-loop to generate the variance-covariance value for each
* element of the matrix
*/
// the covariance matrix of our odometry topic tracks six variables
// as in, think of each data point as a six-dimensional point with the
// following axes: x, y, z, roll, pitch, yaw
#define ODOM_COVAR_MAT_VARSIZE 6
// struct odom_struct
// {
// double x;
// double y;
// double z;
// double roll;
// double pitch;
// double yaw;
// };
// Since we're traversing through the data points using a loop, maybe it'd
// be better to use an array of doubles rather than a struct
// double * data_point = new data_point[6];
// We establish the convention here:
// index: 0 1 2 3 4 5
// axis: x, y, z, roll, pitch, yaw
// However, from a maintainability perspective, relying on a double
// pointer is bad - there is no way of guaranteeing the fixed six-element
// size that we want for data point
// \TODO: create a better container (i.e. class) for each data point that
// has as a member method
// 1) the square bracket operator, for fetching an element
class covar
{
private:
gsl_matrix *covar_mat;
std::vector<double*> *data_points;
public:
covar()
{
data_points = new std::vector<double*>;
covar_mat = gsl_matrix_alloc(ODOM_COVAR_MAT_VARSIZE,
ODOM_COVAR_MAT_VARSIZE);
}
~covar()
{
delete covar_mat;
covar_mat = 0;
delete data_points;
data_points = 0;
}
// We expect the input to be a double array with six elements
bool insert(double* data_point)
{
// double * temp = new double[6];
data_points->push_back(data_point);
return true;
}
void print_dp()
{
for (int i = 0; i < data_points->size(); i++)
{
printf("%i: %f %f %f %f %f %f\n",
i,
(*data_points)[i][0],
(*data_points)[i][1],
(*data_points)[i][2],
(*data_points)[i][3],
(*data_points)[i][4],
(*data_points)[i][5]);
}
}
void print_mat()
{
for (int i = 0; i < covar_mat->size1; i++)
{
printf("\n");
for (int j = 0; j < covar_mat->size2; j++)
{
printf("%f", covar_mat->data[covar_mat->size2*i+j]);
if(j < covar_mat->size2 - 1) printf(", ");
}
}
printf("\n");
}
// \TODO: if covar_mat not available, deny get_mat
bool get_mat(double* array)
{
for(int i = 0; i < 36; i++)
array[i] = gsl_matrix_get(covar_mat,
i/6, //row
i%6); //column
return true;
}
bool generate_covar()
{
/* no point in generating a covariance matrix if we don't have
* the data points to do so
*/
int i, j;
int rsize = data_points->size();
if(rsize <= 1) return false;
gsl_vector_view a, b;
gsl_matrix *A;
A = gsl_matrix_alloc(rsize, ODOM_COVAR_MAT_VARSIZE);
/* the covariance matrix should already be instantiated by the
* class constructor
*/
// covar_mat = gsl_matrix_alloc(ODOM_COVAR_MAT_VARSIZE,
// ODOM_COVAR_MAT_VARSIZE);
// convert data_points into gsl_matrix A
for ( i = 0; i < rsize; i++)
for ( j = 0; j < ODOM_COVAR_MAT_VARSIZE; j++)
gsl_matrix_set (A, i, j, (*data_points)[i][j]);
// generate the var-covar values based on A
// insert these values into covar_mat
for (i = 0; i < A->size2; i++) {
for (j = 0; j < A->size2; j++) {
a = gsl_matrix_column (A, i);
b = gsl_matrix_column (A, j);
double cov = gsl_stats_covariance(a.vector.data,
a.vector.stride,
b.vector.data,
b.vector.stride,
rsize);
gsl_matrix_set (covar_mat, i, j, cov);
}
}
return true;
}
};
#endif // COVAR_H_
| {
"alphanum_fraction": 0.5010270455,
"avg_line_length": 33.3828571429,
"ext": "h",
"hexsha": "34e7e81ebfd72697f802e128e5c120a908eaee1c",
"lang": "C",
"max_forks_count": 26,
"max_forks_repo_forks_event_max_datetime": "2022-02-22T10:10:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-07-04T04:32:54.000Z",
"max_forks_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "joeyzhu00/FusionAD",
"max_forks_repo_path": "src/utility/covar/include/covar.h",
"max_issues_count": 167,
"max_issues_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac",
"max_issues_repo_issues_event_max_datetime": "2019-04-30T21:57:01.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-05-17T03:48:11.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "joeyzhu00/FusionAD",
"max_issues_repo_path": "src/utility/covar/include/covar.h",
"max_line_length": 75,
"max_stars_count": 33,
"max_stars_repo_head_hexsha": "7c912e399b9fcfa657d623f74be64921fc1a11ac",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "joeyzhu00/FusionAD",
"max_stars_repo_path": "src/utility/covar/include/covar.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-17T09:18:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-03T19:45:42.000Z",
"num_tokens": 1353,
"size": 5842
} |
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_vector.h>
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
//#include <gsl/gsl_ran_gaussian.h>
int main (int argc, char *argv[]){
double a = gsl_sf_erf(1);
printf("The random number we get is %f.", a);
exit(0);
} | {
"alphanum_fraction": 0.6543624161,
"avg_line_length": 21.2857142857,
"ext": "c",
"hexsha": "059237f67fa9f250f0adf4df0b8c6495ad31dca1",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-02-25T18:59:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-25T18:59:03.000Z",
"max_forks_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ShreyaR/WorkerPoolSelection",
"max_forks_repo_path": "EM/Test/testNormalDraw.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002",
"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": "ShreyaR/WorkerPoolSelection",
"max_issues_repo_path": "EM/Test/testNormalDraw.c",
"max_line_length": 49,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "03e0bfeda422975c118efe91fe31045f9c27f002",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ShreyaR/WorkerPoolSelection",
"max_stars_repo_path": "EM/Test/testNormalDraw.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 95,
"size": 298
} |
#include "transform_animation.h"
#include "entities/entities.h"
#include <gsl/gsl_poly.h>
#include <gsl/gsl_math.h>
#include "utility/logging.h"
// from x^0 ... x^(len)
static const double drop_in_coeffients[] = { 0.0, -2.0, -3.0, 1.0 };
static void no_op_release(void *data) { }
static void simple_release(void *data) { if (data != NULL) { free(data); } }
typedef struct {
double duration;
double scale;
uint8_t flags;
} drop_in_data;
static void drop_in_get_transform(
double t, ANIMATION_PLAYBACK_MODE mode, int reverse, void *pdata, double *m_out) {
drop_in_data *data = pdata;
double clamped_t;
if (mode == PLAY_ONCE) {
if (reverse) {
clamped_t = GSL_MAX(t, -data->duration);
clamped_t = data->duration + clamped_t;
} else {
clamped_t = GSL_MIN(t, data->duration);
}
} else if (mode == LOOP) {
double full_iterations = floor(t / data->duration);
clamped_t = t - (full_iterations * data->duration);
} else if (mode == OSCILLATE) {
int full_iterations = floor(t / data->duration);
if (GSL_IS_EVEN(full_iterations)) { // same as loop
clamped_t = t - (full_iterations * data->duration);
} else { // invert it
clamped_t = t - (full_iterations * data->duration);
clamped_t = data->duration - clamped_t;
}
}
uint8_t flags = data->flags;
double translation[4];
double value = data->scale * gsl_poly_eval(drop_in_coeffients, 4, clamped_t - 0.6);
gsl_matrix_view out_view = gsl_matrix_view_array(m_out, 4, 4);
gsl_matrix_set_identity(&out_view.matrix);
gsl_vector_view tview = gsl_matrix_column(&out_view.matrix, 3);
if (flags & XFORM_TRANSLATION_X) { gsl_vector_set(&tview.vector, 0, value); }
if (flags & XFORM_TRANSLATION_Y) { gsl_vector_set(&tview.vector, 1, value); }
if (flags & XFORM_TRANSLATION_Z) { gsl_vector_set(&tview.vector, 2, value); }
}
animation_channel build_drop_in_channel(uint8_t apply_to, double scale) {
drop_in_data *data = calloc(1, sizeof(drop_in_data));
data->duration = 5;
data->scale = scale;
data->flags = apply_to;
animation_channel retval = {
.data=data,
.get_transform=drop_in_get_transform,
.release_resources=simple_release
};
return retval;
}
static const uint8_t CONSTANT_TRANSLATION = (1<<0);
static const uint8_t CONSTANT_X_AXIS = (1<<1);
static const uint8_t CONSTANT_Y_AXIS = (1<<2);
static const uint8_t CONSTANT_Z_AXIS = (1<<3);
typedef struct {
gsl_matrix *basis;
uint8_t constant_component_flags;
double *frame_data;
size_t entries_per_frame;
double duration; // seconds
} optimized_keyframe_data;
static void optimized_keyframe_get_transform(
double t, ANIMATION_PLAYBACK_MODE mode, int reverse, void *data, double *m_out) {
// look through the collection of keyframes and determine indices for
// the left and right frames bounding the provided `t`.
// doublesPerFrame, flat array for frame data store
// pack into (time, then optional translation, basis vectors, etc)
}
animation_channel build_optimized_keyframe_channel(
keyframe *keyframes, size_t nframes) {
animation_channel retval = {
.data=NULL,
.get_transform=optimized_keyframe_get_transform,
.release_resources=simple_release
};
// TODO
return retval;
}
void animate_entity(double deltaT, entity_info* e) {
animation_state *state = &e->animation_state;
// update time trackers
double scaledT = deltaT * state->playback_speed;
state->current_cycle_time += scaledT;
state->time_in_transition += scaledT;
state->transition_cycle_time += scaledT;
}
transform_animation_type const transform_animation = {
.build_optimized_keyframe_channel=build_optimized_keyframe_channel,
.build_drop_in_channel=build_drop_in_channel,
.animate_entity=animate_entity
};
| {
"alphanum_fraction": 0.7173051519,
"avg_line_length": 31.8067226891,
"ext": "c",
"hexsha": "4ab7c6eb2a4044caa1c4a67119c3013c87f98b84",
"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": "src/animations/transform_animation.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": "src/animations/transform_animation.c",
"max_line_length": 86,
"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": "src/animations/transform_animation.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1007,
"size": 3785
} |
#include <stdlib.h> // malloc
#include <stdio.h> // printf
#include <math.h> // fabs, sqrt, etc.
#include <time.h> // time
#include <unistd.h> // getpid
#include <gsl/gsl_rng.h> // GNU Scientific Library
#include <gsl/gsl_cdf.h> // GNU Scientific Library
#include <gsl/gsl_randist.h> // GNU Scientific Library
double dvonmises(double* x, double mu, double nu,
double kappa1, double kappa2, double lambda) {
double phi = x[0];
double psi = x[1];
double kernal = exp( kappa1*cos(phi - mu) + kappa2*cos(psi-nu) +
lambda*sin(phi-mu)*sin(psi-nu));
return kernal;
}
void rvonmises2(int* ptrn, double* ptrmu, double* ptrnu,
double* ptrkappa1, double* ptrkappa2, double* ptrlambda,
double* phiout, double* psiout)
{
// Assign the variables
int n = *ptrn;
double mu = *ptrmu;
double nu = *ptrnu;
double kappa1 = *ptrkappa1;
double kappa2 = *ptrkappa2;
double lambda = *ptrlambda;
double modeh;
// If Unimodal...
if(lambda*lambda<(kappa1*kappa2)) {
double x[] = {mu, nu};
modeh = dvonmises(x,mu,nu,kappa1,kappa2,lambda);
}
//If Bimodal...
if(lambda*lambda>(kappa1*kappa2)) {
double psi =
acos(kappa2/fabs(lambda)*sqrt((lambda*lambda+kappa1*kappa1)/(lambda*lambda+kappa2*kappa2)));
double phi =
acos(kappa1/fabs(lambda)*sqrt((lambda*lambda+kappa2*kappa2)/(lambda*lambda+kappa1*kappa1)));
//Caclulate the 4 possible maximum if lambda >0
if(lambda>0.0){
double x1[] = {mu+psi , nu+phi};
double x2[] = {mu-psi , nu-phi};
double mode1 = dvonmises(x1,mu,nu,kappa1,kappa2,lambda);
double mode2 = dvonmises(x2,mu,nu,kappa1,kappa2,lambda);
modeh = fmax(mode1,mode2);
}
if(lambda<0.0){
double x1[] = {mu-phi , nu+psi};
double x2[] = {mu+psi , nu-psi};
double mode1 = dvonmises(x1,mu,nu,kappa1,kappa2,lambda);
double mode2 = dvonmises(x2,mu,nu,kappa1,kappa2,lambda);
modeh = fmax(mode1,mode2);
}
}
//implement the rejection sampler now that we can use the mode to get alpha
double pi = acos(-1);
double height_of_sample_density = 1/(4*pi*pi);
double alpha = height_of_sample_density/modeh;
//printf("%s","mode height\n");
//printf("%f\n",modeh);
gsl_rng* r = gsl_rng_alloc (gsl_rng_taus);
int seed = time(NULL)*getpid();
gsl_rng_set(r,seed);
int i = 0;
while( i < n){
//sample from the sample envelope: the uniform
double two_uniforms[0];
//evaluate the density at those uniforms
two_uniforms[0] = gsl_ran_flat(r, -pi, pi);
two_uniforms[1] = gsl_ran_flat(r, -pi, pi);
double f_x = dvonmises(two_uniforms,mu,nu,kappa1,kappa2,lambda);
double e_x = height_of_sample_density/alpha;
// Test if U <= f_x/e_x and store the uniforms if they work
double U = gsl_ran_flat(r,0,1);
if( U <= f_x/e_x){
phiout[i] = two_uniforms[0];
psiout[i] = two_uniforms[1];
i +=1;
}
}
}
int main(int argc, char* argv[]) {
if ( argc != 7 ) {
fprintf(stderr,"usage: %s nreps mu nu kappa1 kappa2 lambda\n",argv[0]);
return 1;
}
if (argv[7]=0){
fprintf(stderr,"lambda cannot be 0");
return 1;
}
// Simulation parameters
int n = atoi(argv[1]);
double mu = atof(argv[2]);
double nu = atof(argv[3]);
double kappa1 = atof(argv[4]);
double kappa2 = atof(argv[5]);
double lambda = atof(argv[6]);
//because our rvonmises funciton is void, we must allocate memor to psi and phi
//so that we can get results and call them later
double* phiout = (double*) malloc(n*sizeof(double));
double* psiout = (double*) malloc(n*sizeof(double));
rvonmises2(&n,&mu,&nu,&kappa1,&kappa2,&lambda,phiout,psiout);
printf("%s %s\n","phi","psi");
for(int i = 0; i < n; i++){
printf("%f %f\n",phiout[i],psiout[i]);
}
free(phiout);
free(psiout);
return 0;//to get it to work, comment this out
}
| {
"alphanum_fraction": 0.6180625631,
"avg_line_length": 32.7603305785,
"ext": "c",
"hexsha": "a12bb95822ee0f26ec2beca365d988bf8b865f5a",
"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": "b17fb0d4aeee8788ecb454de4ebd1f187be9a85e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bryanwhiting/randomCsampler",
"max_forks_repo_path": "rvonmises2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b17fb0d4aeee8788ecb454de4ebd1f187be9a85e",
"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": "bryanwhiting/randomCsampler",
"max_issues_repo_path": "rvonmises2.c",
"max_line_length": 97,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b17fb0d4aeee8788ecb454de4ebd1f187be9a85e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bryanwhiting/randomCsampler",
"max_stars_repo_path": "rvonmises2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1269,
"size": 3964
} |
#include <math.h>
#include <stdlib.h>
#if !defined(__APPLE__)
#include <malloc.h>
#endif
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <string.h>
#include <fftw3.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_sf_expint.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include "../cosmolike_core/theory/basics.c"
#include "../cosmolike_core/theory/structs.c"
#include "../cosmolike_core/theory/parameters.c"
#include "../cosmolike_core/emu17/P_cb/emu.c"
#include "../cosmolike_core/theory/recompute.c"
#include "../cosmolike_core/theory/cosmo3D.c"
#include "../cosmolike_core/theory/redshift_spline.c"
#include "../cosmolike_core/theory/halo.c"
#include "../cosmolike_core/theory/HOD.c"
#include "../cosmolike_core/theory/pt.c"
#include "../cosmolike_core/theory/cosmo2D_fourier.c"
#include "../cosmolike_core/theory/IA.c"
#include "../cosmolike_core/theory/cluster.c"
#include "../cosmolike_core/theory/BAO.c"
#include "../cosmolike_core/theory/external_prior.c"
#include "../cosmolike_core/theory/GRS.c"
#include "init_WFIRST_forecasts.c"
#include "like_grs.c"
double C_shear_tomo_sys(double ell,int z1,int z2);
double C_cgl_tomo_sys(double ell_Cluster,int zl,int nN, int zs);
double C_gl_tomo_sys(double ell,int zl,int zs);
void set_data_shear(int Ncl, double *ell, double *data, int start);
void set_data_ggl(int Ncl, double *ell, double *data, int start);
void set_data_clustering(int Ncl, double *ell, double *data, int start);
void set_data_cluster_N(double *data, int start);
void set_data_cgl(double *ell_Cluster, double *data, int start);
double log_L_3x2pt_clusterN_clusterWL_GRS_SN();
double log_L_3x2pt_clusterN_clusterWL_GRS();
void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope);
double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double GRSB1, double GRSB2, double GRSB3, double GRSB4, double GRSB5, double GRSB6, double GRSB7, double SIGMAP1, double SIGMAP2, double SIGMAP3, double SIGMAP4, double SIGMAP5, double SIGMAP6, double SIGMAP7,double SIGMAZ, double PSHOT, double KSTAR);
void write_vector_wrapper(char *details, input_cosmo_params ic, input_nuisance_params in);
double log_like_wrapper(input_cosmo_params ic, input_nuisance_params in, input_nuisance_params_grs ingr);
int get_N_tomo_shear(void);
int get_N_tomo_clustering(void);
int get_N_ggl(void);
int get_N_ell(void);
int get_N_tomo_shear(void){
return tomo.shear_Nbin;
}
int get_N_tomo_clustering(void){
return tomo.clustering_Nbin;
}
int get_N_ggl(void){
return tomo.ggl_Npowerspectra;
}
int get_N_ell(void){
return like.Ncl;
}
double C_shear_tomo_sys(double ell, int z1, int z2)
{
double C;
// C= C_shear_tomo_nointerp(ell,z1,z2);
// if(like.IA==1) C+=C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2);
if(like.IA!=1) C= C_shear_tomo_nointerp(ell,z1,z2);
//if(like.IA==1) C= C_shear_shear_IA(ell,z1,z2);
if(like.IA==1) C = C_shear_tomo_nointerp(ell,z1,z2)+C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2);
if(like.IA==2) C += C_II_lin_nointerp(ell,z1,z2)+C_GI_lin_nointerp(ell,z1,z2);
if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[z1])*(1.0+nuisance.shear_calibration_m[z2]);
//printf("%le %d %d %le\n",ell,z1,z2,C_shear_tomo_nointerp(ell,z1,z2)+C_II_JB_nointerp(ell,z1,z2)+C_GI_JB_nointerp(ell,z1,z2));
return C;
}
double C_gl_tomo_sys(double ell,int zl,int zs)
{
double C;
// C=C_gl_tomo_nointerp(ell,zl,zs);
// if(like.IA==1) C += C_gI_nointerp(ell,zl,zs);
if(like.IA!=1) C=C_gl_tomo_nointerp(ell,zl,zs);
if(like.IA==1) C = C_ggl_IA(ell,zl,zs);
if(like.IA==2) C += C_gI_lin_nointerp(ell,zl,zs);
if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);
return C;
}
double C_cgl_tomo_sys(double ell_Cluster, int zl,int nN, int zs)
{
double C;
C=C_cgl_tomo_nointerp(ell_Cluster,zl,nN,zs);
//if(like.IA!=0) C +=
if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);
return C;
}
void set_data_shear(int Ncl, double *ell, double *data, int start)
{
int i,z1,z2,nz;
double a;
for (nz = 0; nz < tomo.shear_Npowerspectra; nz++){
z1 = Z1(nz); z2 = Z2(nz);
for (i = 0; i < Ncl; i++){
if (ell[i] < like.lmax_shear){ data[Ncl*nz+i] = C_shear_tomo_sys(ell[i],z1,z2);}
else {data[Ncl*nz+i] = 0.;}
}
}
}
void set_data_ggl(int Ncl, double *ell, double *data, int start)
{
int i, zl,zs,nz;
for (nz = 0; nz < tomo.ggl_Npowerspectra; nz++){
zl = ZL(nz); zs = ZS(nz);
for (i = 0; i < Ncl; i++){
if (test_kmax(ell[i],zl)){
data[start+(Ncl*nz)+i] = C_gl_tomo_sys(ell[i],zl,zs);
}
else{
data[start+(Ncl*nz)+i] = 0.;
}
}
}
}
void set_data_clustering(int Ncl, double *ell, double *data, int start){
int i, nz;
for (nz = 0; nz < tomo.clustering_Npowerspectra; nz++){
//printf("%d %e %e\n",nz, gbias.b[nz][1],pf_photoz(gbias.b[nz][1],nz));
for (i = 0; i < Ncl; i++){
if (test_kmax(ell[i],nz)){data[start+(Ncl*nz)+i] = C_cl_tomo_nointerp(ell[i],nz,nz);}
else{data[start+(Ncl*nz)+i] = 0.;}
//printf("%d %d %le %le\n",nz,nz,ell[i],data[Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra + nz)+i]);
}
}
}
void set_data_cluster_N(double *data, int start){
int nN, nz;
for (nz = 0; nz < tomo.cluster_Nbin; nz++){
for (nN = 0; nN < Cluster.N200_Nbin; nN++){
data[start+Cluster.N200_Nbin*nz+nN] = N_N200(nz, nN);
}
}
}
void set_data_cgl(double *ell_Cluster, double *data, int start)
{
int zl,zs,nN,nz,i,j;
for(nN = 0; nN < Cluster.N200_Nbin; nN++){
for (nz = 0; nz < tomo.cgl_Npowerspectra; nz++){
zl = ZC(nz); zs = ZSC(nz);
for (i = 0; i < Cluster.lbin; i++){
j = start;
j += (nz*Cluster.N200_Nbin+nN)*Cluster.lbin +i;
data[j] = C_cgl_tomo_sys(ell_Cluster[i],zl,nN,zs);
}
}
}
}
int set_cosmology_params(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu)
{
cosmology.Omega_m=OMM;
cosmology.Omega_v= 1.0-cosmology.Omega_m;
cosmology.sigma_8=S8;
cosmology.n_spec= NS;
cosmology.w0=W0;
cosmology.wa=WA;
cosmology.omb=OMB;
cosmology.h0=H0;
cosmology.MGSigma=MGSigma;
cosmology.MGmu=MGmu;
if (cosmology.Omega_m < 0.05 || cosmology.Omega_m > 0.6) return 0;
if (cosmology.omb < 0.04 || cosmology.omb > 0.055) return 0;
if (cosmology.sigma_8 < 0.5 || cosmology.sigma_8 > 1.1) return 0;
if (cosmology.n_spec < 0.84 || cosmology.n_spec > 1.06) return 0;
if (cosmology.w0 < -2.1 || cosmology.w0 > -0.0) return 0;
if (cosmology.wa < -2.6 || cosmology.wa > 2.6) return 0;
if (cosmology.h0 < 0.4 || cosmology.h0 > 0.9) return 0;
//CH BEGINS
//CH: to use for running planck15_BA0_w0_wa prior alone)
//printf("like_fourier.c from WFIRST_forecasts: cosmology bounds set for running with planck15_BA0_w0_wa prior\n");
//if (cosmology.Omega_m < 0.05 || cosmology.Omega_m > 0.6) return 0;
//if (cosmology.omb < 0.01 || cosmology.omb > 0.1) return 0;
//if (cosmology.sigma_8 < 0.5 || cosmology.sigma_8 > 1.1) return 0;
//if (cosmology.n_spec < 0.84 || cosmology.n_spec > 1.06) return 0;
//if (cosmology.w0 < -2.1 || cosmology.w0 > 1.5) return 0;
//if (cosmology.wa < -5.0 || cosmology.wa > 2.6) return 0;
//if (cosmology.h0 < 0.3 || cosmology.h0 > 0.9) return 0;
//CH ENDS
return 1;
}
void set_nuisance_shear_calib(double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10)
{
nuisance.shear_calibration_m[0] = M1;
nuisance.shear_calibration_m[1] = M2;
nuisance.shear_calibration_m[2] = M3;
nuisance.shear_calibration_m[3] = M4;
nuisance.shear_calibration_m[4] = M5;
nuisance.shear_calibration_m[5] = M6;
nuisance.shear_calibration_m[6] = M7;
nuisance.shear_calibration_m[7] = M8;
nuisance.shear_calibration_m[8] = M9;
nuisance.shear_calibration_m[9] = M10;
}
int set_nuisance_shear_photoz(double SP1,double SP2,double SP3,double SP4,double SP5,double SP6,double SP7,double SP8,double SP9,double SP10,double SPS1)
{
int i;
nuisance.bias_zphot_shear[0]=SP1;
nuisance.bias_zphot_shear[1]=SP2;
nuisance.bias_zphot_shear[2]=SP3;
nuisance.bias_zphot_shear[3]=SP4;
nuisance.bias_zphot_shear[4]=SP5;
nuisance.bias_zphot_shear[5]=SP6;
nuisance.bias_zphot_shear[6]=SP7;
nuisance.bias_zphot_shear[7]=SP8;
nuisance.bias_zphot_shear[8]=SP9;
nuisance.bias_zphot_shear[9]=SP10;
for (i=0;i<tomo.shear_Nbin; i++){
nuisance.sigma_zphot_shear[i]=SPS1;
if (nuisance.sigma_zphot_shear[i]<0.001) return 0;
}
return 1;
}
int set_nuisance_clustering_photoz(double CP1,double CP2,double CP3,double CP4,double CP5,double CP6,double CP7,double CP8,double CP9,double CP10,double CPS1)
{
int i;
nuisance.bias_zphot_clustering[0]=CP1;
nuisance.bias_zphot_clustering[1]=CP2;
nuisance.bias_zphot_clustering[2]=CP3;
nuisance.bias_zphot_clustering[3]=CP4;
nuisance.bias_zphot_clustering[4]=CP5;
nuisance.bias_zphot_clustering[5]=CP6;
nuisance.bias_zphot_clustering[6]=CP7;
nuisance.bias_zphot_clustering[7]=CP8;
nuisance.bias_zphot_clustering[8]=CP9;
nuisance.bias_zphot_clustering[9]=CP10;
for (i=0;i<tomo.clustering_Nbin; i++){
nuisance.sigma_zphot_clustering[i]=CPS1;
if (nuisance.sigma_zphot_clustering[i]<0.001) return 0;
}
return 1;
}
int set_nuisance_ia(double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q)
{
nuisance.A_ia=A_ia;
nuisance.beta_ia=beta_ia;
nuisance.eta_ia=eta_ia;
nuisance.eta_ia_highz=eta_ia_highz;
nuisance.LF_alpha=LF_alpha;
nuisance.LF_P=LF_P;
nuisance.LF_Q=LF_Q;
nuisance.LF_red_alpha=LF_red_alpha;
nuisance.LF_red_P=LF_red_P;
nuisance.LF_red_Q=LF_red_Q;
if (nuisance.A_ia < 0.0 || nuisance.A_ia > 10.0) return 0;
if (nuisance.beta_ia < -1.0 || nuisance.beta_ia > 3.0) return 0;
if (nuisance.eta_ia < -3.0 || nuisance.eta_ia> 3.0) return 0;
if (nuisance.eta_ia_highz < -1.0 || nuisance.eta_ia_highz> 1.0) return 0;
// if(like.IA!=0){
// if (check_LF()) return 0;
// }
return 1;
}
int set_nuisance_cluster_Mobs(double cluster_Mobs_lgN0, double cluster_Mobs_alpha, double cluster_Mobs_beta, double cluster_Mobs_sigma0, double cluster_Mobs_sigma_qm, double cluster_Mobs_sigma_qz)
{
// nuisance.cluster_Mobs_lgM0 = mass_obs_norm; //fiducial : 1.72+log(1.e+14*0.7); could use e.g. sigma = 0.2 Gaussian prior
// nuisance.cluster_Mobs_alpha = mass_obs_slope; //fiducial: 1.08; e.g. sigma = 0.1 Gaussian prior
// nuisance.cluster_Mobs_beta = mass_z_slope; //fiducial: 0.0; e.g. sigma = 0.1 Gaussian prior
// nuisance.cluster_Mobs_sigma = mass_obs_scatter; //fiducial 0.25; e.g. sigma = 0.05 Gaussian prior
// fiducial values and priors from Murata et al. (2018) except for redshift-related parameters
nuisance.cluster_Mobs_lgN0 = cluster_Mobs_lgN0; //fiducial: 3.207, flat prior [0.5, 5.0]
nuisance.cluster_Mobs_alpha = cluster_Mobs_alpha; //fiducial: 0.993, flat prior [0.0, 2.0]
nuisance.cluster_Mobs_beta = cluster_Mobs_beta; //fiducial: 0.0, flat prior [-1.5, 1.5]
nuisance.cluster_Mobs_sigma0 = cluster_Mobs_sigma0; //fiducial: 0.456, flat prior [0.0, 1.5]
nuisance.cluster_Mobs_sigma_qm = cluster_Mobs_sigma_qm; //fiducial: 0.0, flat prior [-1.5, 1.5]
nuisance.cluster_Mobs_sigma_qz = cluster_Mobs_sigma_qz; //fiducial: 0.0, flat prior [-1.5, 1.5]
if (nuisance.cluster_Mobs_lgN0 < 0.5 || nuisance.cluster_Mobs_lgN0 > 5.0) return 0;
if (nuisance.cluster_Mobs_alpha < 0.00001 || nuisance.cluster_Mobs_alpha > 2.0) return 0;
if (nuisance.cluster_Mobs_beta < -1.5 || nuisance.cluster_Mobs_beta > 1.5) return 0;
if (nuisance.cluster_Mobs_sigma0 < 0.00001|| nuisance.cluster_Mobs_sigma0 > 1.5) return 0;
if (nuisance.cluster_Mobs_sigma_qm < -1.5 && nuisance.cluster_Mobs_sigma_qm > 1.5) return 0;
if (nuisance.cluster_Mobs_sigma_qz < -1.5 && nuisance.cluster_Mobs_sigma_qz > 1.5)return 0;
return 1;
}
int set_nuisance_gbias(double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8,double B9, double B10)
{
int i;
gbias.b[0] = B1;
gbias.b[1] = B2;
gbias.b[2] = B3;
gbias.b[3] = B4;
gbias.b[4] = B5;
gbias.b[5] = B6;
gbias.b[6] = B7;
gbias.b[7] = B8;
gbias.b[8] = B9;
gbias.b[9] = B10;
if(like.bias==1){
for (i = 0; i < 10; i++){
if (gbias.b[i] < 0.8 || gbias.b[i] > 3.0) return 0;
}
}
return 1;
}
double log_L_clusterMobs_WFIRST()
{
double log_L = 0.;
int i;
log_L -= pow((nuisance.cluster_Mobs_lgN0 - prior.cluster_Mobs_lgM0[0])/ prior.cluster_Mobs_lgM0[1],2.0);
log_L -= pow((nuisance.cluster_Mobs_alpha - prior.cluster_Mobs_alpha[0])/ prior.cluster_Mobs_alpha[1],2.0);
log_L -= pow((nuisance.cluster_Mobs_beta - prior.cluster_Mobs_beta[0])/ prior.cluster_Mobs_beta[1],2.0);
log_L -= pow((nuisance.cluster_Mobs_sigma0 - prior.cluster_Mobs_sigma0[0])/ prior.cluster_Mobs_sigma0[1],2.0);
log_L -= pow((nuisance.cluster_Mobs_sigma_qm - prior.cluster_Mobs_sigma_qm[0])/ prior.cluster_Mobs_sigma_qm[1],2.0);
log_L -= pow((nuisance.cluster_Mobs_sigma_qz - prior.cluster_Mobs_sigma_qz[0])/ prior.cluster_Mobs_sigma_qz[1],2.0);
log_L = 0.5*log_L;
return log_L;
}
double log_L_3x2pt_clusterN_clusterWL_GRS_SN()
{
double log_L = 0.;
int n_param = 7;
double param_fid[n_param], param_diff[n_param];
int c, r;
double table[7][7]={{5.49220273e+05,2.33044116e+05,1.47504189e+05,-5.92824792e+03,-2.08565457e+03,-4.86800735e+05,4.48613425e+04},{2.33044116e+05,2.30971497e+05,3.54103600e+04,-6.40553809e+03,-2.59356689e+03,-8.01835609e+04,3.04467069e+04},{1.47504189e+05,3.54103600e+04,6.49198594e+04,-4.10636480e+02,2.04259100e+01,-1.74504277e+05,1.95029955e+04},{-5.92824792e+03,-6.40553809e+03,-4.10636480e+02,3.86909977e+03,6.54697110e+02,7.12569941e+01,-9.99312405e+02},{-2.08565457e+03,-2.59356689e+03,2.04259100e+01,6.54697110e+02,1.57299983e+02,-1.33066811e+02,-2.86375759e+02},{-4.86800735e+05,-8.01835609e+04,-1.74504277e+05,7.12569941e+01,-1.33066811e+02,9.98008316e+05,-1.24566696e+05},{4.48613425e+04,3.04467069e+04,1.95029955e+04,-9.99312405e+02,-2.86375759e+02 -1.24566696e+05,5.51799238e+04}};
param_diff[0] = cosmology.Omega_m-prior.Omega_m;
param_diff[1] = cosmology.sigma_8-prior.sigma_8;
param_diff[2] = cosmology.n_spec-prior.n_spec;
param_diff[3] = cosmology.w0-prior.w0;
param_diff[4] = cosmology.wa-prior.wa;
param_diff[5] = cosmology.omb-prior.omb;
param_diff[6] = cosmology.h0-prior.h0;
log_L = -0.5*do_matrix_mult_invcov(n_param,table, param_diff);
return log_L;
}
double log_L_3x2pt_clusterN_clusterWL_GRS()
{
double log_L = 0.;
int n_param = 7;
double param_fid[n_param], param_diff[n_param];
int c, r;
double table[7][7]={{5.43798917e+05,2.33044116e+05,1.47504189e+05,-9.33646911e+03,-2.56808086e+03 -4.86800735e+05,4.48613258e+04},{2.33044116e+05,2.30971497e+05,3.54103600e+04,-6.40553809e+03,-2.59356689e+03,-8.01835609e+04,3.04467069e+04},{1.47504189e+05,3.54103600e+04,6.49198594e+04 -4.10636480e+02,2.04259100e+01,-1.74504277e+05,1.95029955e+04},{-9.33646911e+03,-6.40553809e+03,-4.10636480e+02,1.46051254e+03,3.62655979e+02,7.12569941e+01,-9.99337099e+02},{-2.56808086e+03,-2.59356689e+03,2.04259100e+01,3.62655979e+02,1.09984619e+02,-1.33066811e+02,-2.86374538e+02},{-4.86800735e+05,-8.01835609e+04,-1.74504277e+05,7.12569941e+01,-1.33066811e+02,9.98008316e+05 -1.24566696e+05},{4.48613258e+04,3.04467069e+04,1.95029955e+04,-9.99337099e+02,-2.86374538e+02,-1.24566696e+05,5.51799219e+04}};
param_diff[0] = cosmology.Omega_m-prior.Omega_m;
param_diff[1] = cosmology.sigma_8-prior.sigma_8;
param_diff[2] = cosmology.n_spec-prior.n_spec;
param_diff[3] = cosmology.w0-prior.w0;
param_diff[4] = cosmology.wa-prior.wa;
param_diff[5] = cosmology.omb-prior.omb;
param_diff[6] = cosmology.h0-prior.h0;
log_L = -0.5*do_matrix_mult_invcov(n_param,table, param_diff);
return log_L;
}
double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double GRSB1, double GRSB2, double GRSB3, double GRSB4, double GRSB5, double GRSB6, double GRSB7, double SIGMAP1, double SIGMAP2, double SIGMAP3, double SIGMAP4, double SIGMAP5, double SIGMAP6, double SIGMAP7,double SIGMAZ, double PSHOT, double KSTAR)
{
int i,j,k,m=0,l;
static double *pred;
static double *ell;
static double *ell_Cluster;
static double darg;
double chisqr,a,log_L_prior=0.0;
if(ell==0){
pred= create_double_vector(0, like.Ndata-1);
ell= create_double_vector(0, like.Ncl-1);
darg=(log(like.lmax)-log(like.lmin))/like.Ncl;
for (l=0;l<like.Ncl;l++){
ell[l]=exp(log(like.lmin)+(l+0.5)*darg);
}
ell_Cluster= create_double_vector(0, Cluster.lbin-1);
darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin;
for (l=0;l<Cluster.lbin;l++){
ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg);
}
}
if (set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu)==0){
printf("Cosmology out of bounds\n");
return -1.0e12;
}
set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10);
if (set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10,SPS1)==0){
printf("Shear photo-z sigma too small\n");
return -1.0e12;
}
if (set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10,CPS1)==0){
printf("Clustering photo-z sigma too small\n");
return -1.0e12;
}
if (set_nuisance_ia(A_ia,beta_ia,eta_ia,eta_ia_highz,LF_alpha,LF_P,LF_Q,LF_red_alpha,LF_red_P,LF_red_Q)==0){
printf("IA parameters out of bounds\n");
return -1.0e12;
}
if (set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10)==0){
printf("Bias out of bounds\n");
return -1.0e12;
}
if (set_nuisance_cluster_Mobs(mass_obs_norm, mass_obs_slope, mass_z_slope, mass_obs_scatter_norm, mass_obs_scatter_mass_slope, mass_obs_scatter_z_slope)==0){
printf("Mobs out of bounds\n");
return -1.0e12;
}
//printf("like %le %le %le %le %le %le %le %le\n",cosmology.Omega_m, cosmology.Omega_v,cosmology.sigma_8,cosmology.n_spec,cosmology.w0,cosmology.wa,cosmology.omb,cosmology.h0);
// printf("like %le %le %le %le\n",gbias.b[0][0], gbias.b[1][0], gbias.b[2][0], gbias.b[3][0]);
// for (i=0; i<10; i++){
// printf("nuisance %le %le %le\n",nuisance.shear_calibration_m[i],nuisance.bias_zphot_shear[i],nuisance.sigma_zphot_shear[i]);
// }
log_L_prior=log_L_3x2pt_clusterN_clusterWL_GRS();
//log_L_prior+=log_L_3x2pt_clusterN_clusterWL_GRS_SN();
// if(like.wlphotoz!=0) log_L_prior+=log_L_wlphotoz();
// if(like.clphotoz!=0) log_L_prior+=log_L_clphotoz();
// if(like.shearcalib==1) log_L_prior+=log_L_shear_calib();
// if(strcmp(like.ext_data,"WFIRST_SN")==0) log_L_prior+=log_L_SN_WFIRST_w0wa();
// if(like.GRS==1) log_L_prior+=log_like_GRS(OMM, S8, NS, W0,WA, OMB, H0, MGSigma, MGmu, GRSB1, GRSB2, GRSB3, GRSB4, GRSB5, GRSB6, GRSB7, SIGMAP1, SIGMAP2, SIGMAP3, SIGMAP4, SIGMAP5, SIGMAP6, SIGMAP7,SIGMAZ, PSHOT, KSTAR);
// if(like.clusterMobs==1) log_L_prior+=log_L_clusterMobs_WFIRST();
//printf("%d %d %d %d\n",like.BAO,like.wlphotoz,like.clphotoz,like.shearcalib);
// printf("logl %le %le %le %le\n",log_L_shear_calib(),log_L_wlphotoz(),log_L_clphotoz(),log_L_clusterMobs());
int start=0;
// if(like.shear_shear==1) {
// set_data_shear(like.Ncl, ell, pred, start);
// start=start+like.Ncl*tomo.shear_Npowerspectra;
// }
// if(like.shear_pos==1){
// set_data_ggl(like.Ncl, ell, pred, start);
// start=start+like.Ncl*tomo.ggl_Npowerspectra;
// }
// if(like.pos_pos==1){
// set_data_clustering(like.Ncl,ell,pred, start);
// start=start+like.Ncl*tomo.clustering_Npowerspectra;
// }
// if(like.clusterN==1){
// set_data_cluster_N(pred,start);
// start= start+tomo.cluster_Nbin*Cluster.N200_Nbin;
// }
// if(like.clusterWL==1){
// set_data_cgl(ell_Cluster,pred, start);
// }
chisqr=0.0;
// for (i=0; i<like.Ndata; i++){
// for (j=0; j<like.Ndata; j++){
// a=(pred[i]-data_read(1,i))*invcov_read(1,i,j)*(pred[j]-data_read(1,j));
// chisqr=chisqr+a;
// }
// if (fabs(data_read(1,i)) < 1.e-25){
// printf("%d %le %le %le\n",i,data_read(1,i),pred[i],invcov_read(1,i,i));
// }
// }
// if (chisqr<0.0){
// printf("error: chisqr = %le\n",chisqr);
// //exit(EXIT_FAILURE);
// }
// if (like.GRS == 1){
// printf("like_grs activated!\n");
// log_L_GRS = log_like_GRS(cosmology.Omega_m, cosmology.sigma_8, cosmology.n_spec, cosmology.w0,cosmology.wa, cosmology.omb, cosmology.h0,-42.,-42.,-42.,-42.,-42.,-42.,-42.,-42.,-42.,-42.,-42.,-42.,-42.,-42.,-42.,-42.,-42.);
// }
//printf("%le\n",chisqr);
// return -0.5*chisqr+log_L_prior+log_L_GRS;
return -0.5*chisqr+log_L_prior;
}
void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5,double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope)
{
int i,j,k,m=0,l;
static double *pred;
static double *ell;
static double *ell_Cluster;
static double darg;
double chisqr,a,log_L_prior=0.0;
if(ell==0){
pred= create_double_vector(0, like.Ndata-1);
ell= create_double_vector(0, like.Ncl-1);
darg=(log(like.lmax)-log(like.lmin))/like.Ncl;
for (l=0;l<like.Ncl;l++){
ell[l]=exp(log(like.lmin)+(l+0.5)*darg);
}
ell_Cluster= create_double_vector(0, Cluster.lbin-1);
darg=(log(Cluster.l_max)-log(Cluster.l_min))/Cluster.lbin;
for (l=0;l<Cluster.lbin;l++){
ell_Cluster[l]=exp(log(Cluster.l_min)+(l+0.5)*darg);
}
}
// for (l=0;l<like.Ncl;l++){
// printf("%d %le\n",i,ell[l]);
// }
set_cosmology_params(OMM,S8,NS,W0,WA,OMB,H0,MGSigma,MGmu);
set_nuisance_shear_calib(M1,M2,M3,M4,M5,M6,M7,M8,M9,M10);
set_nuisance_shear_photoz(SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8,SP9,SP10,SPS1);
set_nuisance_clustering_photoz(CP1,CP2,CP3,CP4,CP5,CP6,CP7,CP8,CP9,CP10,CPS1);
set_nuisance_ia(A_ia,beta_ia,eta_ia,eta_ia_highz,LF_alpha,LF_P,LF_Q,LF_red_alpha,LF_red_P,LF_red_Q);
set_nuisance_gbias(B1,B2,B3,B4,B5,B6,B7,B8,B9,B10);
set_nuisance_cluster_Mobs(mass_obs_norm,mass_obs_slope,mass_z_slope,mass_obs_scatter_norm,mass_obs_scatter_mass_slope,mass_obs_scatter_z_slope);
int start=0;
if(like.shear_shear==1) {
set_data_shear(like.Ncl, ell, pred, start);
start=start+like.Ncl*tomo.shear_Npowerspectra;
}
if(like.shear_pos==1){
//printf("ggl\n");
set_data_ggl(like.Ncl, ell, pred, start);
start=start+like.Ncl*tomo.ggl_Npowerspectra;
}
if(like.pos_pos==1){
//printf("clustering\n");
set_data_clustering(like.Ncl,ell,pred, start);
start=start+like.Ncl*tomo.clustering_Npowerspectra;
}
if(like.clusterN==1){
set_data_cluster_N(pred,start);
start= start+tomo.cluster_Nbin*Cluster.N200_Nbin;
}
if(like.clusterWL==1){
set_data_cgl(ell_Cluster,pred, start);
}
FILE *F;
char filename[300];
if (strstr(details,"FM") != NULL){
sprintf(filename,"%s",details);
}
else {sprintf(filename,"datav/%s_%s_%s",survey.name,like.probes,details);}
F=fopen(filename,"w");
for (i=0;i<like.Ndata; i++){
fprintf(F,"%d %le\n",i,pred[i]);
//printf("%d %le\n",i,pred[i]);
}
fclose(F);
}
void write_vector_wrapper(char *details, input_cosmo_params ic, input_nuisance_params in)
{
compute_data_vector(details, ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu,
in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9],
in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4],
in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9],
in.source_z_s,
in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4],
in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9],
in.lens_z_s,
in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4],
in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9],
in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz,
in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5],
in.m_lambda[0], in.m_lambda[1], in.m_lambda[2], in.m_lambda[3],
in.m_lambda[4], in.m_lambda[5]);
}
double log_like_wrapper(input_cosmo_params ic, input_nuisance_params in,input_nuisance_params_grs ingr)
{
double like = log_multi_like(ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu,
in.bias[0], in.bias[1], in.bias[2], in.bias[3],in.bias[4], in.bias[5], in.bias[6], in.bias[7],in.bias[8], in.bias[9],
in.source_z_bias[0], in.source_z_bias[1], in.source_z_bias[2], in.source_z_bias[3], in.source_z_bias[4],
in.source_z_bias[5], in.source_z_bias[6], in.source_z_bias[7], in.source_z_bias[8], in.source_z_bias[9],
in.source_z_s,
in.lens_z_bias[0], in.lens_z_bias[1], in.lens_z_bias[2], in.lens_z_bias[3], in.lens_z_bias[4],
in.lens_z_bias[5], in.lens_z_bias[6], in.lens_z_bias[7], in.lens_z_bias[8], in.lens_z_bias[9],
in.lens_z_s,
in.shear_m[0], in.shear_m[1], in.shear_m[2], in.shear_m[3], in.shear_m[4],
in.shear_m[5], in.shear_m[6], in.shear_m[7], in.shear_m[8], in.shear_m[9],
in.A_ia, in.beta_ia, in.eta_ia, in.eta_ia_highz,
in.lf[0], in.lf[1], in.lf[2], in.lf[3], in.lf[4], in.lf[5],
in.m_lambda[0], in.m_lambda[1], in.m_lambda[2], in.m_lambda[3],
in.m_lambda[4], in.m_lambda[5],ingr.grsbias[0],ingr.grsbias[1],ingr.grsbias[2],ingr.grsbias[3],ingr.grsbias[4],ingr.grsbias[5],ingr.grsbias[6],ingr.grssigmap[0],ingr.grssigmap[1],ingr.grssigmap[2],ingr.grssigmap[3],ingr.grssigmap[4],ingr.grssigmap[5],ingr.grssigmap[6],ingr.grssigmaz,ingr.grspshot,ingr.grskstar);
return like;
}
void save_zdistr_sources(int zs){
double z,dz =(redshift.shear_zdistrpar_zmax-redshift.shear_zdistrpar_zmin)/300.0;
printf("Printing redshift distribution n(z) for source redshift bin %d\n",zs);
FILE *F1;
char filename[300];
sprintf(filename,"zdistris/pessi_zdist_sources_bin%d.txt",zs);
F1 = fopen(filename,"w");
for (z =redshift.shear_zdistrpar_zmin; z< redshift.shear_zdistrpar_zmax; z+= dz){
fprintf(F1,"%e %e\n", z, zdistr_photoz(z,zs));
}
}
void save_zdistr_lenses(int zl){
double z,dz =(redshift.clustering_zdistrpar_zmax-redshift.clustering_zdistrpar_zmin)/300.0;
printf("Printing redshift distribution n(z) and bias b(z) for lens redshift bin %d\n",zl);
FILE *F1;
char filename[300];
sprintf(filename,"zdistris/pessi_zdist_lenses_bin%d.txt", zl);
F1 = fopen(filename,"w");
for (z =redshift.clustering_zdistrpar_zmin; z< redshift.clustering_zdistrpar_zmax; z+= dz){
fprintf(F1,"%e %e\n", z, pf_photoz(z,zl));
}
}
int main(int argc, char** argv)
{
clock_t begin, end;
double time_spent,loglike=0.0;
int i;
/* here, do your time-consuming job */
init_cosmo_runmode("halofit");
init_binning_fourier(25,30.0,15000.0,4000.0,21.0,10,10);
if(strcmp(argv[1],"opti")==0) init_priors("photo_opti","shear_opti","none","none");
if(strcmp(argv[1],"pessi")==0) init_priors("photo_pessi","shear_pessi","none","none");
init_survey(argv[2]);
if(strcmp(argv[2],"WFIRST")==0) init_galaxies("zdistris/zdistri_WFIRST_LSST_lensing_fine_bin","zdistris/zdistri_WFIRST_LSST_clustering_fine_bin", "gaussian", "gaussian", "SN10");
init_clusters();
init_IA("none", "none");
init_probes(argv[3]);
if(strcmp(argv[1],"opti")==0) compute_data_vector(argv[1],0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.01,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.01,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0);
if(strcmp(argv[1],"pessi")==0) compute_data_vector(argv[1],0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0);
// init_data_inv("cov/WFIRST_3x2pt_inv","datav/WFIRST_all_2pt_fid_opti");
// begin = clock();
// loglike=log_multi_like(0.3156,0.831,0.9645,-1.,0.,0.0491685,0.6727,0.,0.,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.0005,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,3.207,0.993,0.0,0.456,0.0,0.0);
// printf("%le\n",loglike);
// // printf("knonlin %le\n",nonlinear_scale_computation(1.0));
// // printf("knonlin %le\n",nonlinear_scale_computation(0.5));
// end = clock();
// time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
// printf("timespent %le\n",time_spent);
//CH BEGINS
//for testing Planck15_BAO_w0wa prior alone
//compute_data_vector("fid",3.50989e-01,8.04675e-01,9.64061e-01,-5.05518e-01,-1.46884e+00,5.46245e-02,6.39839e-01,0.,0.,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.01,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.72+log(1.e+14*0.7),1.08,0.0,0.25,0.9,0.9,0.9,0.9);
//expect 0.0 for the following
//log_multi_like(3.50989e-01,8.04675e-01.1,9.64061e-01,-5.05518e-01,-1.46884e+00,5.46245e-02,6.39839e-01,0.,0.,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.01,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.72+log(1.e+14*0.7),1.08,0.0,0.25,0.9,0.9,0.9,0.9);
//expect -13.195605 for the following
//log_multi_like(0.35449914, 0.81272201,0.97370111, -0.51057289,-1.48353327,0.05517077,0.64623714,0.,0.,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0,2.1,2.2,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.05,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.01,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,5.92,1.1,-0.47,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.72+log(1.e+14*0.7),1.08,0.0,0.25,0.9,0.9,0.9,0.9);
//CH ENDS
return 0;
}
| {
"alphanum_fraction": 0.6969465425,
"avg_line_length": 48.8893678161,
"ext": "c",
"hexsha": "078aa1f5ea47d5835e301268b5030149138d558e",
"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": "aa65774dc1870450723b0a13449681e37d0f979c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CosmoLike/WFIRST_forecasts",
"max_forks_repo_path": "like_fourier.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "aa65774dc1870450723b0a13449681e37d0f979c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "CosmoLike/WFIRST_forecasts",
"max_issues_repo_path": "like_fourier.c",
"max_line_length": 1197,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "aa65774dc1870450723b0a13449681e37d0f979c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CosmoLike/WFIRST_forecasts",
"max_stars_repo_path": "like_fourier.c",
"max_stars_repo_stars_event_max_datetime": "2019-08-21T00:36:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-21T00:36:40.000Z",
"num_tokens": 13733,
"size": 34027
} |
/*
This code is written by <albanese@fbk.it>.
(C) 2010 mlpy Developers.
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/>.
*/
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#define MIN( A , B ) ((A) < (B) ? (A) : (B))
#define INIT_STD 0
#define INIT_PLUSPLUS 1
void init_std(double *data, /* data points (nn points x pp dimensions) */
double *means, /* means (kk clusters x pp dimensions) */
int nn, /* number od data points */
int pp, /* number of dimensions */
int kk, /* number of clusters */
unsigned long seed /* random seed for init */
)
{
int n, p, k;
int *ridx;
const gsl_rng_type * T;
gsl_rng * r;
T = gsl_rng_default;
r = gsl_rng_alloc (T);
gsl_rng_set (r, seed);
ridx = (int *) malloc (nn * sizeof(int));
for (n=0; n<nn; n++)
ridx[n] = n;
gsl_ran_shuffle (r, ridx, nn, sizeof (int));
for (k=0; k<kk; k++)
for (p=0; p<pp; p++)
means[p + (k * pp)] = data[p + (ridx[k] * pp)];
free(ridx);
}
/* for init_plus */
void
dist_min(double *a, double *b, int nn)
{
int n;
for (n=0; n<nn; n++)
a[n] = MIN (a[n], b[n]);
}
/* for init_plus */
int
idx_max(double *a, int nn)
{
int n, idx = 0;
double max = -DBL_MAX;
for (n=0; n<nn; n++)
if (a[n] > max)
{
max = a[n];
idx = n;
}
return idx;
}
void
init_plus(double *data, /* data points (nn points x pp dimensions) */
double *means, /* means (kk clusters x pp dimensions) */
int nn, /* number od data points */
int pp, /* number of dimensions */
int kk, /* number of clusters */
unsigned long seed /* random seed for init */
)
{
int n, p, k;
double *dist, *distk;
int sidx;
const gsl_rng_type *T;
gsl_rng *r;
T = gsl_rng_default;
r = gsl_rng_alloc (T);
gsl_rng_set (r, seed);
dist = (double *) malloc (nn * sizeof(double));
distk = (double *) malloc (nn * sizeof(double));
/* first mean (randomly selected) */
sidx = (int) gsl_rng_uniform_int (r, nn);
gsl_rng_free(r);
for (p=0; p<pp; p++)
means[p] = data[p + (sidx * pp)];
/* initialize dist */
for (n=0; n<nn; n++) /* for each data point */
dist[n] = DBL_MAX;
for (k=0; k<kk-1; k++)
{
/* for each data point x compute distance from mean k */
for (n=0; n<nn; n++)
{
distk[n] = 0.0;
for (p=0; p<pp; p++)
distk[n] += pow(data[p + (n * pp)] - means[p + (k * pp)], 2);
}
/* for each data point x, compute the distance between x and */
/* the nearest center that has already been chosen */
dist_min (dist, distk, nn);
/* add one new data point as a new center, using */
sidx = idx_max (dist, nn);
for (p=0; p<pp; p++)
means[p + ((k+1) * pp)] = data[p + (sidx * pp)];
}
free(dist);
free(distk);
}
/* assignment step */
int
a_step(double *data, /* data points (nn x pp) */
double *means, /* means (kk x pp) */
int *cls, /* cluster assignement for each data point (nn) */
int *nelems, /* number of elements of each cluster (kk) */
int nn, /* number od data points */
int pp, /* number of dimensions */
int kk /* number of clusters */
)
{
int n, p, k, kn = 0;
double dist, dmin;
int changed = 0;
for (k=0; k<kk; k++)
nelems[k] = 0;
for (n=0; n<nn; n++) /* for each data point */
{
dmin = DBL_MAX;
for (k=0; k<kk; k++) /* for each cluster */
{
/* compute distance */
dist = 0.0;
for (p=0; p<pp; p++)
dist += pow(data[p + (n * pp)] - means[p + (k * pp)], 2);
/* remember the cluster k if dist < dmin */
if (dist < dmin)
{
dmin = dist;
kn = k;
}
}
/* if the cluster assignement change */
if (kn != cls[n])
changed++;
/* update clusters and number of elements of each cluster */
cls[n] = kn;
nelems[kn]++;
}
return changed;
}
/* update step */
int
u_step(double *data, /* data points (nn x pp) */
double *means, /* means (kk x pp) */
int *cls, /* cluster assignement for each data point (nn) */
int *nelems, /* number of elements of each cluster (kk) */
int nn, /* number od data points */
int pp, /* number of dimensions */
int kk /* number of clusters */
)
{
int n, p, k;
/* reset means */
for (k=0; k<kk; k++)
for (p=0; p<pp; p++)
means[p + (k * pp)] = 0.0;
for (n=0; n<nn; n++) /* for each data point */
for (p=0; p<pp; p++) /* for each dimension */
means[p + (cls[n] * pp)] += data[p + (n * pp)];
for (k=0; k<kk; k++)
if (nelems[k] > 0)
for (p=0; p<pp; p++)
means[p + (k * pp)] /= nelems[k];
return 1;
}
int
km(double *data, /* data points (nn x pp) */
double *means, /* initialized means (kk x pp) */
int *cls, /* cluster assignement for each data point (nn) */
int nn, /* number od data points */
int pp, /* number of dimensions */
int kk /* number of clusters */
)
{
int n;
int ret, steps = 0;
int changed = -1;
int *nelems; /* number of elements of each cluster (kk) */
nelems = (int *) malloc (kk * sizeof(int));
/* init cls */
for (n=0; n<nn; n++)
cls[n] = -1.0;
/* k-means algorithm */
while (changed != 0)
{
changed = a_step (data, means, cls, nelems, nn, pp, kk);
ret = u_step (data, means, cls, nelems, nn, pp, kk);
steps++;
}
free(nelems);
return steps;
}
| {
"alphanum_fraction": 0.5090001513,
"avg_line_length": 24.9471698113,
"ext": "c",
"hexsha": "6dff44308bd0533db76fa58db7dc5de19dc767cd",
"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": "e52a6e88d4469284a071c0b96d009f6684dbb2ea",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "TonyZPW/CRC4Docker",
"max_forks_repo_path": "src/mlpy-3.5.0/mlpy/kmeans/c_kmeans.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e52a6e88d4469284a071c0b96d009f6684dbb2ea",
"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": "TonyZPW/CRC4Docker",
"max_issues_repo_path": "src/mlpy-3.5.0/mlpy/kmeans/c_kmeans.c",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5ee26f9a590b727693202d8ad3b6460970304bd9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "xuanxiaoliqu/CRC4Docker",
"max_stars_repo_path": "src/mlpy-3.5.0/mlpy/kmeans/c_kmeans.c",
"max_stars_repo_stars_event_max_datetime": "2020-10-26T12:02:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-26T12:02:08.000Z",
"num_tokens": 1956,
"size": 6611
} |
/**
*
* @file qwrapper_slaset.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @date 2010-11-15
* @generated s Tue Jan 7 11:44:58 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_slaset(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum uplo, int M, int N,
float alpha, float beta,
float *A, int LDA)
{
DAG_CORE_LASET;
QUARK_Insert_Task(quark, CORE_slaset_quark, task_flags,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &M, VALUE,
sizeof(int), &N, VALUE,
sizeof(float), &alpha, VALUE,
sizeof(float), &beta, VALUE,
sizeof(float)*LDA*N, A, OUTPUT,
sizeof(int), &LDA, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_slaset_quark = PCORE_slaset_quark
#define CORE_slaset_quark PCORE_slaset_quark
#endif
void CORE_slaset_quark(Quark *quark)
{
PLASMA_enum uplo;
int M;
int N;
float alpha;
float beta;
float *A;
int LDA;
quark_unpack_args_7(quark, uplo, M, N, alpha, beta, A, LDA);
LAPACKE_slaset_work(
LAPACK_COL_MAJOR,
lapack_const(uplo),
M, N, alpha, beta, A, LDA);
}
| {
"alphanum_fraction": 0.5119189511,
"avg_line_length": 27.5081967213,
"ext": "c",
"hexsha": "a730207684a1b45f57bd8d53068852b26496b5a0",
"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_slaset.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_slaset.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_slaset.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 444,
"size": 1678
} |
/* specfunc/mathieu_radfunc.c
*
* Copyright (C) 2002 Lowell Johnson
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: L. Johnson */
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_sf_mathieu.h>
int gsl_sf_mathieu_Mc_e(int kind, int order, double qq, double zz,
gsl_sf_result *result)
{
int even_odd, kk, mm, status;
double maxerr = 1e-14, amax, pi = M_PI, fn, factor;
double coeff[GSL_SF_MATHIEU_COEFF], fc;
double j1c, z2c, j1pc, z2pc;
double u1, u2;
gsl_sf_result aa;
/* Check for out of bounds parameters. */
if (qq <= 0.0)
{
GSL_ERROR("q must be greater than zero", GSL_EINVAL);
}
if (kind < 1 || kind > 2)
{
GSL_ERROR("kind must be 1 or 2", GSL_EINVAL);
}
mm = 0;
amax = 0.0;
fn = 0.0;
u1 = sqrt(qq)*exp(-1.0*zz);
u2 = sqrt(qq)*exp(zz);
even_odd = 0;
if (order % 2 != 0)
even_odd = 1;
/* Compute the characteristic value. */
status = gsl_sf_mathieu_a_e(order, qq, &aa);
if (status != GSL_SUCCESS)
{
return status;
}
/* Compute the series coefficients. */
status = gsl_sf_mathieu_a_coeff(order, qq, aa.val, coeff);
if (status != GSL_SUCCESS)
{
return status;
}
if (even_odd == 0)
{
for (kk=0; kk<GSL_SF_MATHIEU_COEFF; kk++)
{
amax = GSL_MAX(amax, fabs(coeff[kk]));
if (fabs(coeff[kk])/amax < maxerr)
break;
j1c = gsl_sf_bessel_Jn(kk, u1);
if (kind == 1)
{
z2c = gsl_sf_bessel_Jn(kk, u2);
}
else /* kind = 2 */
{
z2c = gsl_sf_bessel_Yn(kk, u2);
}
fc = pow(-1.0, 0.5*order+kk)*coeff[kk];
fn += fc*j1c*z2c;
}
fn *= sqrt(pi/2.0)/coeff[0];
}
else
{
for (kk=0; kk<GSL_SF_MATHIEU_COEFF; kk++)
{
amax = GSL_MAX(amax, fabs(coeff[kk]));
if (fabs(coeff[kk])/amax < maxerr)
break;
j1c = gsl_sf_bessel_Jn(kk, u1);
j1pc = gsl_sf_bessel_Jn(kk+1, u1);
if (kind == 1)
{
z2c = gsl_sf_bessel_Jn(kk, u2);
z2pc = gsl_sf_bessel_Jn(kk+1, u2);
}
else /* kind = 2 */
{
z2c = gsl_sf_bessel_Yn(kk, u2);
z2pc = gsl_sf_bessel_Yn(kk+1, u2);
}
fc = pow(-1.0, 0.5*(order-1)+kk)*coeff[kk];
fn += fc*(j1c*z2pc + j1pc*z2c);
}
fn *= sqrt(pi/2.0)/coeff[0];
}
result->val = fn;
result->err = 2.0*GSL_DBL_EPSILON;
factor = fabs(fn);
if (factor > 1.0)
result->err *= factor;
return GSL_SUCCESS;
}
int gsl_sf_mathieu_Ms_e(int kind, int order, double qq, double zz,
gsl_sf_result *result)
{
int even_odd, kk, mm, status;
double maxerr = 1e-14, amax, pi = M_PI, fn, factor;
double coeff[GSL_SF_MATHIEU_COEFF], fc;
double j1c, z2c, j1mc, z2mc, j1pc, z2pc;
double u1, u2;
gsl_sf_result aa;
/* Check for out of bounds parameters. */
if (qq <= 0.0)
{
GSL_ERROR("q must be greater than zero", GSL_EINVAL);
}
if (kind < 1 || kind > 2)
{
GSL_ERROR("kind must be 1 or 2", GSL_EINVAL);
}
/* Handle the trivial cases where order = 0. */
if (order == 0)
{
result->val = 0.0;
result->err = 0.0;
return GSL_SUCCESS;
}
mm = 0;
amax = 0.0;
fn = 0.0;
u1 = sqrt(qq)*exp(-1.0*zz);
u2 = sqrt(qq)*exp(zz);
even_odd = 0;
if (order % 2 != 0)
even_odd = 1;
/* Compute the characteristic value. */
status = gsl_sf_mathieu_b_e(order, qq, &aa);
if (status != GSL_SUCCESS)
{
return status;
}
/* Compute the series coefficients. */
status = gsl_sf_mathieu_b_coeff(order, qq, aa.val, coeff);
if (status != GSL_SUCCESS)
{
return status;
}
if (even_odd == 0)
{
for (kk=0; kk<GSL_SF_MATHIEU_COEFF; kk++)
{
amax = GSL_MAX(amax, fabs(coeff[kk]));
if (fabs(coeff[kk])/amax < maxerr)
break;
j1mc = gsl_sf_bessel_Jn(kk, u1);
j1pc = gsl_sf_bessel_Jn(kk+2, u1);
if (kind == 1)
{
z2mc = gsl_sf_bessel_Jn(kk, u2);
z2pc = gsl_sf_bessel_Jn(kk+2, u2);
}
else /* kind = 2 */
{
z2mc = gsl_sf_bessel_Yn(kk, u2);
z2pc = gsl_sf_bessel_Yn(kk+2, u2);
}
fc = pow(-1.0, 0.5*order+kk+1)*coeff[kk];
fn += fc*(j1mc*z2pc - j1pc*z2mc);
}
fn *= sqrt(pi/2.0)/coeff[0];
}
else
{
for (kk=0; kk<GSL_SF_MATHIEU_COEFF; kk++)
{
amax = GSL_MAX(amax, fabs(coeff[kk]));
if (fabs(coeff[kk])/amax < maxerr)
break;
j1c = gsl_sf_bessel_Jn(kk, u1);
j1pc = gsl_sf_bessel_Jn(kk+1, u1);
if (kind == 1)
{
z2c = gsl_sf_bessel_Jn(kk, u2);
z2pc = gsl_sf_bessel_Jn(kk+1, u2);
}
else /* kind = 2 */
{
z2c = gsl_sf_bessel_Yn(kk, u2);
z2pc = gsl_sf_bessel_Yn(kk+1, u2);
}
fc = pow(-1.0, 0.5*(order-1)+kk)*coeff[kk];
fn += fc*(j1c*z2pc - j1pc*z2c);
}
fn *= sqrt(pi/2.0)/coeff[0];
}
result->val = fn;
result->err = 2.0*GSL_DBL_EPSILON;
factor = fabs(fn);
if (factor > 1.0)
result->err *= factor;
return GSL_SUCCESS;
}
int gsl_sf_mathieu_Mc_array(int kind, int nmin, int nmax, double qq,
double zz, gsl_sf_mathieu_workspace *work,
double result_array[])
{
int even_odd, order, ii, kk, mm, status;
double maxerr = 1e-14, amax, pi = M_PI, fn;
double coeff[GSL_SF_MATHIEU_COEFF], fc;
double j1c, z2c, j1pc, z2pc;
double u1, u2;
double *aa = work->aa;
/* Initialize the result array to zeroes. */
for (ii=0; ii<nmax-nmin+1; ii++)
result_array[ii] = 0.0;
/* Check for out of bounds parameters. */
if (qq <= 0.0)
{
GSL_ERROR("q must be greater than zero", GSL_EINVAL);
}
if (kind < 1 || kind > 2)
{
GSL_ERROR("kind must be 1 or 2", GSL_EINVAL);
}
mm = 0;
amax = 0.0;
u1 = sqrt(qq)*exp(-1.0*zz);
u2 = sqrt(qq)*exp(zz);
/* Compute all eigenvalues up to nmax. */
gsl_sf_mathieu_a_array(0, nmax, qq, work, aa);
for (ii=0, order=nmin; order<=nmax; ii++, order++)
{
fn = 0.0;
even_odd = 0;
if (order % 2 != 0)
even_odd = 1;
/* Compute the series coefficients. */
status = gsl_sf_mathieu_a_coeff(order, qq, aa[order], coeff);
if (status != GSL_SUCCESS)
{
return status;
}
if (even_odd == 0)
{
for (kk=0; kk<GSL_SF_MATHIEU_COEFF; kk++)
{
amax = GSL_MAX(amax, fabs(coeff[kk]));
if (fabs(coeff[kk])/amax < maxerr)
break;
j1c = gsl_sf_bessel_Jn(kk, u1);
if (kind == 1)
{
z2c = gsl_sf_bessel_Jn(kk, u2);
}
else /* kind = 2 */
{
z2c = gsl_sf_bessel_Yn(kk, u2);
}
fc = pow(-1.0, 0.5*order+kk)*coeff[kk];
fn += fc*j1c*z2c;
}
fn *= sqrt(pi/2.0)/coeff[0];
}
else
{
for (kk=0; kk<GSL_SF_MATHIEU_COEFF; kk++)
{
amax = GSL_MAX(amax, fabs(coeff[kk]));
if (fabs(coeff[kk])/amax < maxerr)
break;
j1c = gsl_sf_bessel_Jn(kk, u1);
j1pc = gsl_sf_bessel_Jn(kk+1, u1);
if (kind == 1)
{
z2c = gsl_sf_bessel_Jn(kk, u2);
z2pc = gsl_sf_bessel_Jn(kk+1, u2);
}
else /* kind = 2 */
{
z2c = gsl_sf_bessel_Yn(kk, u2);
z2pc = gsl_sf_bessel_Yn(kk+1, u2);
}
fc = pow(-1.0, 0.5*(order-1)+kk)*coeff[kk];
fn += fc*(j1c*z2pc + j1pc*z2c);
}
fn *= sqrt(pi/2.0)/coeff[0];
}
result_array[ii] = fn;
} /* order loop */
return GSL_SUCCESS;
}
int gsl_sf_mathieu_Ms_array(int kind, int nmin, int nmax, double qq,
double zz, gsl_sf_mathieu_workspace *work,
double result_array[])
{
int even_odd, order, ii, kk, mm, status;
double maxerr = 1e-14, amax, pi = M_PI, fn;
double coeff[GSL_SF_MATHIEU_COEFF], fc;
double j1c, z2c, j1mc, z2mc, j1pc, z2pc;
double u1, u2;
double *bb = work->bb;
/* Initialize the result array to zeroes. */
for (ii=0; ii<nmax-nmin+1; ii++)
result_array[ii] = 0.0;
/* Check for out of bounds parameters. */
if (qq <= 0.0)
{
GSL_ERROR("q must be greater than zero", GSL_EINVAL);
}
if (kind < 1 || kind > 2)
{
GSL_ERROR("kind must be 1 or 2", GSL_EINVAL);
}
mm = 0;
amax = 0.0;
u1 = sqrt(qq)*exp(-1.0*zz);
u2 = sqrt(qq)*exp(zz);
/* Compute all eigenvalues up to nmax. */
gsl_sf_mathieu_b_array(0, nmax, qq, work, bb);
for (ii=0, order=nmin; order<=nmax; ii++, order++)
{
fn = 0.0;
even_odd = 0;
if (order % 2 != 0)
even_odd = 1;
/* Handle the trivial cases where order = 0. */
if (order == 0)
{
result_array[ii] = 0.0;
continue;
}
/* Compute the series coefficients. */
status = gsl_sf_mathieu_b_coeff(order, qq, bb[order], coeff);
if (status != GSL_SUCCESS)
{
return status;
}
if (even_odd == 0)
{
for (kk=0; kk<GSL_SF_MATHIEU_COEFF; kk++)
{
amax = GSL_MAX(amax, fabs(coeff[kk]));
if (fabs(coeff[kk])/amax < maxerr)
break;
j1mc = gsl_sf_bessel_Jn(kk, u1);
j1pc = gsl_sf_bessel_Jn(kk+2, u1);
if (kind == 1)
{
z2mc = gsl_sf_bessel_Jn(kk, u2);
z2pc = gsl_sf_bessel_Jn(kk+2, u2);
}
else /* kind = 2 */
{
z2mc = gsl_sf_bessel_Yn(kk, u2);
z2pc = gsl_sf_bessel_Yn(kk+2, u2);
}
fc = pow(-1.0, 0.5*order+kk+1)*coeff[kk];
fn += fc*(j1mc*z2pc - j1pc*z2mc);
}
fn *= sqrt(pi/2.0)/coeff[0];
}
else
{
for (kk=0; kk<GSL_SF_MATHIEU_COEFF; kk++)
{
amax = GSL_MAX(amax, fabs(coeff[kk]));
if (fabs(coeff[kk])/amax < maxerr)
break;
j1c = gsl_sf_bessel_Jn(kk, u1);
j1pc = gsl_sf_bessel_Jn(kk+1, u1);
if (kind == 1)
{
z2c = gsl_sf_bessel_Jn(kk, u2);
z2pc = gsl_sf_bessel_Jn(kk+1, u2);
}
else /* kind = 2 */
{
z2c = gsl_sf_bessel_Yn(kk, u2);
z2pc = gsl_sf_bessel_Yn(kk+1, u2);
}
fc = pow(-1.0, 0.5*(order-1)+kk)*coeff[kk];
fn += fc*(j1c*z2pc - j1pc*z2c);
}
fn *= sqrt(pi/2.0)/coeff[0];
}
result_array[ii] = fn;
} /* order loop */
return GSL_SUCCESS;
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_mathieu_Mc(int kind, int order, double qq, double zz)
{
EVAL_RESULT(gsl_sf_mathieu_Mc_e(kind, order, qq, zz, &result));
}
double gsl_sf_mathieu_Ms(int kind, int order, double qq, double zz)
{
EVAL_RESULT(gsl_sf_mathieu_Ms_e(kind, order, qq, zz, &result));
}
| {
"alphanum_fraction": 0.5008801408,
"avg_line_length": 25.506122449,
"ext": "c",
"hexsha": "bdac8dd3adb4f8906837b889561116e2337296d2",
"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": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/mathieu_radfunc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"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": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/mathieu_radfunc.c",
"max_line_length": 76,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017",
"max_stars_repo_path": "gsl-2.4/specfunc/mathieu_radfunc.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z",
"num_tokens": 4006,
"size": 12498
} |
#ifndef _INC_MAXMULTIMIN_
#define _INC_MAXMULTIMIN_
#include <pthread.h> // for debug info
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_rng.h>
struct estimate_thetas_params;
/**
* compute the gradient matrix for the length setting theta values
* dC/dTheta = (C-nugget) * (1/2)*(x_i - x_j)^(alpha) * alpha / (thetaLength)
*
* this is a fn-ptr which will be set when the cov function is setup
* the different target fns are in emulator.c called derivative_l_<covfnname>
*
* @param covsub the covariance matrix with the nugget term subtracted
* @param thetaLength the current value of the length scale we're differentiating wrt
* @param index, the direction we're looking in
* @return dCdTheta the matrix of the derivative of C wrt index
*
*/
void (*makeGradMatLength)(gsl_matrix *dCdTheta, gsl_matrix* xmodel,
double thetaLength, int index, int nmodel_points, int nparams);
void maxWithMultiMin(struct estimate_thetas_params *params);
double evalFnMulti(const gsl_vector* theta_vec, void* params_in);
void gradFnMulti(const gsl_vector* theta_vec, void* params_in, gsl_vector * grad_vec);
double getGradientCn(gsl_matrix * dCdtheta, gsl_matrix *cinverse,
gsl_vector* training_vector,int nmodel_points, int nthetas);
void evalFnGradMulti(const gsl_vector* theta_vec, void* params,
double* fnval, gsl_vector * grad_vec);
double estimateSigma(gsl_matrix* cinverse, void* params_in);
double estimateSigmaFull(gsl_vector *thetas, void* params_in);
int doOptimizeMultiMin( double(*fn)(const gsl_vector*, void*),
void(*gradientFn)(const gsl_vector*,void*, gsl_vector*),
void(*fnGradFn)(const gsl_vector*, void*, double*, gsl_vector*),
gsl_vector *thetaInit, gsl_vector* thetaFinal, void* args);
void set_random_init_value(gsl_rng* rand, gsl_vector* x, gsl_matrix* ranges,int nthetas);
#endif
| {
"alphanum_fraction": 0.733935743,
"avg_line_length": 34.3448275862,
"ext": "h",
"hexsha": "bb272807d0aa10508ffc272212063ff15870f8f1",
"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": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MADAI/MADAIEmulator",
"max_forks_repo_path": "src/libEmu/maxmultimin.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"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": "MADAI/MADAIEmulator",
"max_issues_repo_path": "src/libEmu/maxmultimin.h",
"max_line_length": 90,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jackdawjackdaw/emulator",
"max_stars_repo_path": "src/libEmu/maxmultimin.h",
"max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z",
"num_tokens": 518,
"size": 1992
} |
// MIT License
//
// Copyright (c) 2020 SunnyCase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include "object.h"
#include "utility.h"
#include <chino/io.h>
#include <chino/threading.h>
#include <gsl/gsl-lite.hpp>
namespace chino::io
{
#if defined(_MSC_VER)
#pragma section(".CHDRV$A", long, read) // Begin drivers
#pragma section(".CHDRV$C", long, read) // Drivers
#pragma section(".CHDRV$Z", long, read) // End drivers
#define EXPORT_DRIVER(x) __declspec(allocate(".CHDRV$C")) const ::chino::io::driver *CHINO_CONCAT(_drv_, __COUNTER__) = &x
#pragma section(".CHHDR$A", long, read) // Begin hardware device registrations
#pragma section(".CHHDR$C", long, read) // Hardware device registrations
#pragma section(".CHHDR$Z", long, read) // End hardware device registrations
#define EXPORT_HARDWARE(x) __declspec(allocate(".CHHDR$C")) const ::chino::io::hardware_device_registration *CHINO_CONCAT(_hdr_, __COUNTER__) = &x
#elif defined(__GNUC__)
#define EXPORT_DRIVER(x) __attribute__((unused, section(".chdrv"))) const ::chino::io::driver *CHINO_CONCAT(_drv_, __COUNTER__) = &x
#define EXPORT_HARDWARE(x) __attribute__((unused, section(".chhdr"))) const ::chino::io::hardware_device_registration *CHINO_CONCAT(_hdr_, __COUNTER__) = &x
#else
#error "Unsupported compiler"
#endif
struct driver;
struct device;
struct file;
#define DEFINE_DEV_TYPE(x, v) x = v,
enum class device_type
{
#include "device_types.def"
COUNT
};
#undef DEFINE_DEV_TYPE
enum class driver_type
{
hardware,
console
};
struct hardware_device_registration
{
const driver &drv;
};
typedef result<void, error_code> (*driver_add_device_t)(const driver &drv, const hardware_device_registration &hdr);
typedef result<void, error_code> (*driver_attach_device_t)(const driver &drv, device &bottom_dev, std::string_view args);
typedef result<file *, error_code> (*driver_open_device_t)(device &dev, std::string_view filename, create_disposition create_disp);
typedef result<void, error_code> (*driver_close_device_t)(file &file);
typedef result<size_t, error_code> (*driver_read_device_t)(file &file, gsl::span<gsl::byte> buffer);
typedef result<void, error_code> (*driver_write_device_t)(file &file, gsl::span<const gsl::byte> buffer);
struct driver_operations
{
driver_add_device_t add_device;
driver_attach_device_t attach_device;
driver_open_device_t open_device;
driver_close_device_t close_device;
driver_read_device_t read_device;
driver_write_device_t write_device;
};
struct driver
{
driver_type type = driver_type::hardware;
std::string_view name;
driver_operations ops;
};
struct device : ob::object
{
const driver &drv;
device_type type;
threading::sched_spinlock syncroot;
template <class T = uint8_t>
T &extension() noexcept { return *reinterpret_cast<T *>(reinterpret_cast<uint8_t *>(this) + sizeof(device)); }
};
struct device_extension
{
device &dev() noexcept { return *reinterpret_cast<device *>(reinterpret_cast<uint8_t *>(this) - sizeof(device)); }
};
struct file : ob::object
{
device &dev;
size_t offset;
threading::sched_spinlock syncroot;
template <class T = uint8_t>
T &extension() noexcept { return *reinterpret_cast<T *>(reinterpret_cast<uint8_t *>(this) + sizeof(file)); }
};
struct file_extension
{
io::file &file() noexcept { return *reinterpret_cast<io::file *>(reinterpret_cast<uint8_t *>(this) - sizeof(device)); }
};
result<device *, error_code> create_device(const driver &drv, device_type type, size_t extension_size) noexcept;
result<device *, error_code> create_device(std::string_view name, const driver &drv, device_type type, size_t extension_size) noexcept;
result<file *, error_code> create_file(device &dev, size_t extension_size) noexcept;
result<file *, error_code> open_file(device &dev, access_mask access, std::string_view filename, create_disposition create_disp = create_disposition::open_existing) noexcept;
result<size_t, error_code> read_file(file &file, gsl::span<gsl::byte> buffer) noexcept;
result<void, error_code> write_file(file &file, gsl::span<const gsl::byte> buffer) noexcept;
result<void, error_code> close_file(file &file) noexcept;
}
| {
"alphanum_fraction": 0.7520582041,
"avg_line_length": 38.9776119403,
"ext": "h",
"hexsha": "4e99c1b29d58c90cdfd41db515ee7da7dd343649",
"lang": "C",
"max_forks_count": 20,
"max_forks_repo_forks_event_max_datetime": "2021-09-13T10:14:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-05-18T03:54:08.000Z",
"max_forks_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dotnetGame/chino-os",
"max_forks_repo_path": "src/ddk/include/chino/ddk/io.h",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2",
"max_issues_repo_issues_event_max_datetime": "2020-04-30T14:46:51.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-05-15T02:15:33.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dotnetGame/chino-os",
"max_issues_repo_path": "src/ddk/include/chino/ddk/io.h",
"max_line_length": 174,
"max_stars_count": 137,
"max_stars_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "chino-os/chino-os",
"max_stars_repo_path": "src/ddk/include/chino/ddk/io.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-10T11:42:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-04-28T09:50:17.000Z",
"num_tokens": 1244,
"size": 5223
} |
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
// //////////////////////////////////////////////////////////
// // //
// // hybridMANTIS v1.0 //
// // fastDETECT2 - C code //
// // (optical photons transport) //
// // //
// // used for Load Balancing //
// // //
// //////////////////////////////////////////////////////////
//
//
//
//
// ****Disclaimer****
// This software and documentation (the "Software") were developed at the Food and Drug Administration (FDA) by employees of the Federal Government in
// the course of their official duties. Pursuant to Title 17, Section 105 of the United States Code, this work is not subject to copyright protection
// and is in the public domain. Permission is hereby granted, free of charge, to any person obtaining a copy of the Software, to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, or sell copies of the
// Software or derivatives, and to permit persons to whom the Software is furnished to do so. FDA assumes no responsibility whatsoever for use by other
// parties of the Software, its source code, documentation or compiled executables, and makes no guarantees, expressed or implied, about its quality,
// reliability, or any other characteristic. Further, use of this code in no way implies endorsement by the FDA or confers any advantage in regulatory
// decisions. Although this software can be redistributed and/or modified freely, we ask that any derivative works bear some notice that they are
// derived from it, and any modified versions bear some notice that they have been modified.
//
// Detailed comments are available in "hybridMANTIS_cuda_ver1_0.cu" and "hybridMANTIS_c_ver1_0.c" files.
//
// Associated publication: Sharma Diksha, Badal Andreu and Badano Aldo, "hybridMANTIS: a CPU-GPU Monte Carlo method for modeling indirect x-ray detectors with
// columnar scintillators". Physics in Medicine and Biology, 57(8), pp. 2357–2372 (2012)
//
//
// File: hybridMANTIS_c_ver1_0_LB.c
// Author: Diksha Sharma (US Food and Drug Administration)
// Email: diksha.sharma@fda.hhs.gov
// Last updated: Apr 13, 2012
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////
//
// Header libraries
//
/////////////////////////////////////////
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/////////////////////////////////////////
//
// Global variables
//
/////////////////////////////////////////
#define max_photon_per_EDE 900000 // maximum number of optical photons that can be generated per energy deposition event (EDE)
#ifndef USING_CUDA
#define mybufsizeT 2304000 // CPU buffer size: # of events sent to the CPU
#endif
/////////////////////////////////////////
//
// Include kernel program
//
/////////////////////////////////////////
#include "kernel_cuda_c_ver1_0_LB.cu"
////////////////////////////////////////////////////////////////////////////
// MAIN PROGRAM //
////////////////////////////////////////////////////////////////////////////
#ifndef USING_CUDA
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// cpuoptlb(): Performs optical transport for finding optimal load using load balancing in the CPU
// Input arguments: cptime, cpubufsize
//
// cptime: time taken by GPU to call this routine
// cpubufsize: CPU buffer size defined by user in PENELOPE tally code. Only to be used for load balancing. This is different from 'mybufsize'.
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void cpuoptlb_(double *cptime, int *cpubufsize)
{
float dcos[3]={0}; // directional cosines
float normal[3]={0}; // normal to surface in case of TIR
float pos[3] = {0}; // new position
float old_pos[3] = {0}; // source coordinates
// command line arguments
float xdetector, ydetector, radius, height, n_C, n_IC, top_absfrac, bulk_abscoeff, beta, d_min, lbound_x, lbound_y, ubound_x, ubound_y, d_max, yield, sensorRefl;
int pixelsize, num_primary, min_optphotons, max_optphotons, num_bins;
int nbytes = (*cpubufsize)*sizeof(struct start_info);
struct start_info *structa;
structa = (struct start_info*) malloc(nbytes);
if( structa == NULL )
printf("\n Struct start_info array CANNOT BE ALLOCATED - %d !!", (*cpubufsize));
// get cpu time
clock_t start, end;
double num_sec;
// get current time stamp to initialize seed input for RNG
time_t seconds;
seconds = time (NULL);
struct timeval tv;
gettimeofday(&tv,NULL);
float rr=0.0f, theta=0.0f;
float r=0.0f; // random number
float norm=0.0f;
int jj=0;
// initialize random number generator (RANECU)
int seed_input = 271828182 ; // ranecu seed input
int seed[2];
// gsl variables
const gsl_rng_type * Tgsl;
gsl_rng * rgsl;
double mu_gsl;
int my_index=0;
int result_algo = 0;
unsigned long long int *num_rebound;
// output image variables
int xdim = 0;
int ydim = 0;
int indexi=0, indexj=0;
// create a generator chosen by the environment variable GSL_RNG_TYPE
gsl_rng_env_setup();
Tgsl = gsl_rng_default;
rgsl = gsl_rng_alloc (Tgsl);
// copy to local variables from PENELOPE buffers
xdetector = inputargs_.detx; // x dimension of detector (in um). x in (0,xdetector)
ydetector = inputargs_.dety; // y dimension of detector (in um). y in (0,ydetector)
height = inputargs_.detheight; // height of column and thickness of detector (in um). z in range (-H/2, H/2)
radius = inputargs_.detradius; // radius of column (in um).
n_C = inputargs_.detnC; // refractive index of columns
n_IC = inputargs_.detnIC; // refractive index of intercolumnar material
top_absfrac = inputargs_.dettop; // column's top surface absorption fraction (0.0, 0.5, 0.98)
bulk_abscoeff = inputargs_.detbulk; // column's bulk absorption coefficient (in um^-1) (0.001, 0.1 cm^-1)
beta = inputargs_.detbeta; // roughness coefficient of column walls
d_min = inputargs_.detdmin; // minimum distance a photon can travel when transmitted from a column
d_max = inputargs_.detdmax;
lbound_x = inputargs_.detlboundx; // x lower bound of region of interest of output image (in um)
lbound_y = inputargs_.detlboundy; // y lower bound (in um)
ubound_x = inputargs_.detuboundx; // x upper bound (in um)
ubound_y = inputargs_.detuboundy; // y upper bound (in um)
yield = inputargs_.detyield; // yield (/eV)
pixelsize = inputargs_.detpixel; // 1 pixel = pixelsize microns (in um)
sensorRefl = inputargs_.detsensorRefl; // Non-Ideal sensor reflectivity (%)
num_primary = inputargs_.mynumhist; // total number of primaries to be simulated
min_optphotons = inputargs_.minphotons; // minimum number of optical photons detected to be included in PHS
max_optphotons = inputargs_.maxphotons; // maximum number of optical photons detected to be included in PHS
num_bins = inputargs_.mynumbins; // number of bins for genrating PHS
// dimensions of PRF image
xdim = ceil((ubound_x - lbound_x)/pixelsize);
ydim = ceil((ubound_y - lbound_y)/pixelsize);
unsigned long long int myimage[xdim][ydim];
// memory for storing histogram of # photons detected/primary
int *h_num_detected_prim = 0;
h_num_detected_prim = (int*)malloc(sizeof(int)*num_primary);
for(indexj=0; indexj < num_primary; indexj++)
h_num_detected_prim[indexj] = 0;
// start the clock
start = clock();
for(my_index = 0; my_index < (*cpubufsize); my_index++) // iterate over x-rays
{
// reset the global counters
num_generatedT = 0;
num_detectT=0;
num_abs_topT=0;
num_abs_bulkT=0;
num_lostT=0;
num_outofcolT=0;
num_theta1T=0;
photon_distanceT=0.0f;
// copying fortran buffer into *structa
// units in the penelope output file are in cm. Convert to microns.
structa[my_index].str_x = optical_.xbufopt[my_index] * 10000.0f; // x-coordinate of interaction event.
structa[my_index].str_y = optical_.ybufopt[my_index] * 10000.0f; // y-coordinate
structa[my_index].str_z = optical_.zbufopt[my_index] * 10000.0f; // z-coordinate
structa[my_index].str_E = optical_.debufopt[my_index]; // energy deposited
structa[my_index].str_histnum = optical_.nbufopt[my_index]; // x-ray history number
// sample # optical photons based on light yield and energy deposited for this interaction event (using Poisson distribution)
mu_gsl = (double)structa[my_index].str_E * yield;
structa[my_index].str_N = gsl_ran_poisson(rgsl,mu_gsl);
if(structa[my_index].str_N > max_photon_per_EDE)
{
printf("\n\n CPU str_n exceeds max photons. program is exiting - %d !! \n\n",structa[my_index].str_N);
exit(0);
}
num_rebound = (unsigned long long int*) malloc(structa[my_index].str_N*sizeof(unsigned long long int));
if(num_rebound == NULL)
printf("\n Error allocating num_rebound memory !\n");
// initialize the RANECU generator in a position far away from the previous history:
seed_input = (int)(seconds/3600+tv.tv_usec); // seed input=seconds passed since 1970+current time in micro secs
init_PRNG(my_index, 50000, seed_input, seed); // intialize RNG
for(jj=0; jj<structa[my_index].str_N; jj++)
num_rebound[jj] = 0;
// reset the vectors
dcos[0]=0.0f; dcos[1]=0.0f; dcos[2]=0.0f;
normal[0]=0.0f; normal[1]=0.0f; normal[2]=0.0f;
// set starting location of photon
pos[0] = structa[my_index].str_x; pos[1] = structa[my_index].str_y; pos[2] = structa[my_index].str_z;
old_pos[0] = structa[my_index].str_x; old_pos[1] = structa[my_index].str_y; old_pos[2] = structa[my_index].str_z;
// initializing the direction cosines for the first particle in each core
r = (ranecu(seed) * 2.0f) - 1.0f; // random number between (-1,1)
while(fabs(r) <= 0.01f)
{
r = (ranecu(seed) * 2.0f) - 1.0f;
}
dcos[2] = r; // random number between (-1,1)
rr = sqrt(1.0f-r*r);
theta=ranecu(seed)*twopipen;
dcos[0]=rr*cos(theta);
dcos[1]=rr*sin(theta);
norm = sqrt(dcos[0]*dcos[0] + dcos[1]*dcos[1] + dcos[2]*dcos[2]);
if ((norm < (1.0f - epsilon)) || (norm > (1.0f + epsilon))) // normalize
{
dcos[0] = dcos[0]/norm;
dcos[1] = dcos[1]/norm;
dcos[2] = dcos[2]/norm;
}
local_counterT=0;
while(local_counterT < structa[my_index].str_N)
{
absorbedT = 0;
detectT = 0;
bulk_absT = 0;
// set starting location of photon
pos[0] = structa[my_index].str_x; pos[1] = structa[my_index].str_y; pos[2] = structa[my_index].str_z;
old_pos[0] = structa[my_index].str_x; old_pos[1] = structa[my_index].str_y; old_pos[2] = structa[my_index].str_z;
num_generatedT++;
result_algo = 0;
while(result_algo == 0)
{
result_algo = algoT(normal, old_pos, pos, dcos, num_rebound, seed, structa[my_index], &myimage[0][0], xdetector, ydetector, radius, height, n_C, n_IC, top_absfrac, bulk_abscoeff, beta, d_min, pixelsize, lbound_x, lbound_y, ubound_x, ubound_y, sensorRefl, d_max, ydim, h_num_detected_prim);
}
}
// release resources
free(num_rebound);
} // my_index loop ends
// end the clock
end = clock();
num_sec = (double)((end - start)/CLOCKS_PER_SEC);
*cptime = num_sec;
// release resources
free(structa);
free(h_num_detected_prim);
return;
} // C main() ends
#endif
| {
"alphanum_fraction": 0.6134446833,
"avg_line_length": 40.8581081081,
"ext": "c",
"hexsha": "be9f33e7d7296786f8b658f9515a8c78dcfc04d9",
"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": "8e2d374baaad27b3eae62fab34bea7675eb1ee4d",
"max_forks_repo_licenses": [
"BSD-Source-Code"
],
"max_forks_repo_name": "diamfda/hybridmantis",
"max_forks_repo_path": "main/hybridMANTIS_c_ver1_0_LB.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8e2d374baaad27b3eae62fab34bea7675eb1ee4d",
"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": "diamfda/hybridmantis",
"max_issues_repo_path": "main/hybridMANTIS_c_ver1_0_LB.c",
"max_line_length": 301,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8e2d374baaad27b3eae62fab34bea7675eb1ee4d",
"max_stars_repo_licenses": [
"BSD-Source-Code"
],
"max_stars_repo_name": "diamfda/hybridmantis",
"max_stars_repo_path": "main/hybridMANTIS_c_ver1_0_LB.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3414,
"size": 12094
} |
#include "coneOS.h"
#include <cblas.h>
#include <math.h>
// x = b*a
inline void setAsScaledArray(double *x, const double * a,const double b,int len) {
int i;
for( i=0;i<len;++i ) x[i] = b*a[i];
}
// a*= b
inline void scaleArray(double * a,const double b,int len){
//b_dscal(len,b,a,1);
cblas_dscal(len,b,a,1);
}
// x'*y
inline double innerProd(const double * x, const double * y, int len){
//return b_ddot(len, x,1,y,1);
return cblas_ddot(len, x,1,y,1);
}
// ||v||_2
inline double calcNorm(const double * v,int len){
//return b_dnrm2(len, v, 1);
return cblas_dnrm2(len, v, 1);
}
inline double calcNormInf(const double *a, int l){
double tmp, max = 0.0;
int i;
for ( i=0; i<l; ++i){
tmp = fabs(a[i]);
if(tmp > max) max = tmp;
}
return max;
}
// ||v||_2^2
inline double calcNormSq(const double * v,int len){
double nrm = calcNorm(v,len);
return nrm*nrm;
}
// daxpy a += sc*b
inline void addScaledArray(double * a, const double * b, int n, const double sc){
//b_daxpy(n, sc, b, 1, a, 1);
cblas_daxpy(n, sc, b, 1, a, 1);
}
inline double calcNormDiff(const double *a,const double *b, int l) {
double nmDiff = 0.0, tmp;
int i;
for ( i=0; i<l; ++i ){
tmp = (a[i] - b[i]);
nmDiff += tmp * tmp;
}
return sqrt(nmDiff);
}
inline double calcNormInfDiff(const double *a, const double *b, int l) {
double tmp, max = 0.0;
int i;
for ( i=0; i<l; ++i){
tmp = fabs(a[i] - b[i]);
if(tmp > max) max = tmp;
}
return max;
}
inline void accumByAtrans(Data * d, const double *x, double *y)
{
cblas_dgemv(CblasColMajor, CblasTrans, d->m, d->n, 1.0, d->Ax, d->m, x, 1, 1.0, y, 1);
}
inline void accumByA(Data * d, const double *x, double *y)
{
cblas_dgemv(CblasColMajor, CblasNoTrans, d->m, d->n, 1.0, d->Ax, d->m, x, 1, 1.0, y, 1);
}
/*
inline void b_daxpy(const int n, const double alpha, const double *x, const int incx, double *y, const int incy)
{
daxpy(&n,&alpha,x,&incx,y,&incy);
//cblas_daxpy(n,alpha,x,incx,y,incy);
}
inline void b_dsyr(char Uplo, const int N, const double alpha, const double *X, const int incX, double *A, const int lda)
{
//dsyr(&Uplo,&N,&alpha,X,&incX,A,&lda);
cblas_dsyr(CblasColMajor, Uplo, N, alpha, X, incX, A, lda);
}
inline void b_dscal(const int N, const double alpha, double *X, const int incX)
{
//dscal(&N,&alpha,X,&incX);
cblas_dscal(N,alpha,X,incX);
}
inline double b_ddot(const int n, const double *x, const int incx, const double *y, const int incy)
{
//return ddot(&n,x,&incx,y,&incy);
return cblas_ddot(n,x,incx,y,incy);
}
inline double b_dnrm2(const int N, const double *X, const int incX)
{
return cblas_dnrm2(N,X,incX);
//return dnrm2(&N,X,&incX);
}
inline void b_dgemm(
char TransA,
char TransB,
const int M,
const int N,
const int K,
const double alpha,
const double *A,
const int lda,
const double *B,
const int ldb,
const double beta,
double *C,
const int ldc){
dgemm(&TransA, &TransB, &M, &N, &K,&alpha,A,&lda,B,&ldb,&beta,C,&ldc);
//cblas_dgemm();
}
inline void b_dgemv(char Trans,
const int m,
const int n,
const double alpha,
const double *a,
const int lda,
const double *x,
const int incx,
const double beta,
double *y,
const int incy){
dgemv(&Trans,&m,&n,&alpha,a,&lda,x,&incx,&beta,y,&incy);
}
inline void b_dtrsv(char Uplo, char TransA, char Diag, const int N, const double *A, const int lda, double *X, const int incX)
{
dtrsv(&Uplo, &TransA, &Diag, &N, A, &lda, X, &incX);
}
inline void b_dsymv(char Uplo, const int N, const double alpha, const double *A,
const int lda, const double *X, const int incX, const double beta,
double *Y, const int incY){
dsymv(&Uplo, &N, &alpha, A, &lda, X, &incX, beta, Y, &incY);
}
*/
| {
"alphanum_fraction": 0.571255159,
"avg_line_length": 26.0696202532,
"ext": "c",
"hexsha": "ed5f27ba056a3b3bb5045211afe875d21676ff3b",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-12-20T19:38:22.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-26T23:10:34.000Z",
"max_forks_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "cvxgrp/coneos",
"max_forks_repo_path": "coneOSdense/linAlg.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "cvxgrp/coneos",
"max_issues_repo_path": "coneOSdense/linAlg.c",
"max_line_length": 126,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "cvxgrp/coneos",
"max_stars_repo_path": "coneOSdense/linAlg.c",
"max_stars_repo_stars_event_max_datetime": "2015-08-29T07:42:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-08-29T07:42:29.000Z",
"num_tokens": 1369,
"size": 4119
} |
/*
FRACTAL - A program growing fractals to benchmark parallelization and drawing
libraries.
Copyright 2009-2021, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file graphic.c
* \brief Source file to define the graphic drawing data and functions.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2009-2021, Javier Burguete Tolosa.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <glib.h>
#include <png.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include <gtk/gtk.h>
#include <GL/glew.h>
#include "config.h"
#include "fractal.h"
#include "image.h"
#include "text.h"
#include "graphic.h"
unsigned int window_width = 480; ///< Graphic window width.
unsigned int window_height = 480; ///< Graphic window height.
/**
* Function to init the graphic data.
* \return 1 on success, 0 on error.
*/
int
graphic_init (Graphic * graphic, ///< Draw struct.
char *logo_name) ///< Logo PNG file name.
{
const GLfloat projection_matrix[16] = {
1., 0., 0., 0.,
0, 1., 0., 0.,
0., 0, 0., 0.,
0., 0., 0., 1.
};
const char *vs_3D_source =
"attribute highp vec3 position;"
"attribute lowp vec3 color;"
"varying lowp vec3 fcolor;"
"uniform highp mat4 matrix;"
"void main ()"
"{gl_Position = matrix * vec4 (position, 1.f); fcolor = color;}";
const char *fs_source =
"varying lowp vec3 fcolor;"
"void main () {gl_FragColor = vec4 (fcolor, 1.f);}";
const char *vertex_name = "position";
const char *color_name = "color";
const char *matrix_name = "matrix";
// GLSL version
const char *version = "#version 120\n"; // OpenGL 2.1
const char *vs_3D_sources[3] = { version, INIT_GL_GLES, vs_3D_source };
const char *fs_sources[3] = { version, INIT_GL_GLES, fs_source };
const char *error_message;
GLint k;
GLuint vs, fs;
GLenum glew_status;
#if DEBUG
printf ("graphic_init: start\n");
fflush (stdout);
#endif
// Initing GLEW
#if DEBUG
printf ("Initing GLEW\n");
fflush (stdout);
#endif
glew_status = glewInit ();
if (glew_status != GLEW_OK)
{
printf ("ERROR! glewInit: %s\n", glewGetErrorString (glew_status));
return 0;
}
#if DEBUG
printf ("graphic_init: compiling fragment shader\n");
fflush (stdout);
#endif
fs = glCreateShader (GL_FRAGMENT_SHADER);
glShaderSource (fs, 3, fs_sources, NULL);
glCompileShader (fs);
glGetShaderiv (fs, GL_COMPILE_STATUS, &k);
if (!k)
{
error_message = "unable to compile the fragment shader";
goto exit_on_error;
}
#if DEBUG
printf ("graphic_init: compiling 3D vertex shader\n");
fflush (stdout);
#endif
vs = glCreateShader (GL_VERTEX_SHADER);
glShaderSource (vs, 3, vs_3D_sources, NULL);
glCompileShader (vs);
glGetShaderiv (vs, GL_COMPILE_STATUS, &k);
if (!k)
{
glDeleteShader (fs);
error_message = "unable to compile the 3D vertex shader";
goto exit_on_error;
}
graphic->program_3D = glCreateProgram ();
glAttachShader (graphic->program_3D, vs);
glAttachShader (graphic->program_3D, fs);
glLinkProgram (graphic->program_3D);
glDeleteShader (vs);
glDeleteShader (fs);
glGetProgramiv (graphic->program_3D, GL_LINK_STATUS, &k);
if (!k)
{
error_message = "unable to link the program 3D";
goto exit_on_error;
}
graphic->attribute_3D_position
= glGetAttribLocation (graphic->program_3D, vertex_name);
if (graphic->attribute_3D_position == -1)
{
error_message = "could not bind attribute";
goto exit_on_error;
}
graphic->attribute_3D_color
= glGetAttribLocation (graphic->program_3D, color_name);
if (graphic->attribute_3D_color == -1)
{
error_message = "could not bind attribute";
goto exit_on_error;
}
graphic->uniform_3D_matrix
= glGetUniformLocation (graphic->program_3D, matrix_name);
if (graphic->uniform_3D_matrix == -1)
{
error_message = "could not bind uniform";
goto exit_on_error;
}
memcpy (graphic->projection_matrix, projection_matrix, 16 * sizeof (GLfloat));
#if DEBUG
printf ("graphic_init: initing logo\n");
fflush (stdout);
#endif
if (logo_name)
{
graphic->logo = image_new (logo_name);
if (!graphic->logo)
{
error_message = "unable to open the logo";
goto exit_on_error;
}
if (!image_init (graphic->logo))
{
error_message = "unable to init the logo";
goto exit_on_error;
}
}
else
graphic->logo = NULL;
#if DEBUG
printf ("graphic_init: initing text\n");
fflush (stdout);
#endif
if (!text_init (graphic->text))
{
error_message = "unable to init the text";
goto exit_on_error;
}
#if DEBUG
printf ("graphic_init: end\n");
fflush (stdout);
#endif
return 1;
exit_on_error:
printf ("ERROR! %s\n", error_message);
#if DEBUG
printf ("graphic_init: end\n");
fflush (stdout);
#endif
return 0;
}
/**
* Function to free the memory used by graphic drawing functions.
*/
void
graphic_destroy (Graphic * graphic) ///< Graphic struct.
{
#if DEBUG
printf ("graphic_destroy: start\n");
fflush (stdout);
#endif
text_destroy (graphic->text);
image_destroy (graphic->logo);
#if DEBUG
printf ("graphic_destroy: end\n");
fflush (stdout);
#endif
}
/**
* Function to draw the fractal.
*/
void
graphic_render (Graphic * graphic) ///< Graphic struct.
{
// Rectangle matrix
const Point3D square_vertices[4] = {
{{0., 0., 0.}, {0., 0., 0.}},
{{length, 0., 0.}, {0., 0., 0.}},
{{length, width, 0.}, {0., 0., 0.}},
{{0., width, 0.}, {0., 0., 0.}}
};
const GLushort square_indices[4] = { 0, 1, 2, 3 };
const GLfloat black[4] = { 0., 0., 0., 1. };
const char *str_version = "Fractal 3.4.15";
float cp, sp, ct, st, w, h, sx, sy;
GLuint vbo_square, ibo_square, vbo_points;
#if DEBUG
printf ("graphic_render: start\n");
fflush (stdout);
#endif
// Drawing a white background
glClearColor (1., 1., 1., 0.);
glClear (GL_COLOR_BUFFER_BIT);
#if DEBUG
printf ("graphic_render: ending if no fractal\n");
fflush (stdout);
#endif
// Ending if no fractal
if (!medium)
goto end_draw;
#if DEBUG
printf ("graphic_render: checking the fractal type\n");
fflush (stdout);
#endif
// Checking if 3D or 2D fractal
glUseProgram (graphic->program_3D);
if (fractal_3D)
{
// Projection matrix
sincosf (graphic->phi, &sp, &cp);
sincosf (graphic->theta, &st, &ct);
w = graphic->xmax - graphic->xmin;
h = graphic->ymax - graphic->ymin;
graphic->projection_matrix[0] = 2. * cp / w;
graphic->projection_matrix[1] = 2. * ct * sp / h;
graphic->projection_matrix[4] = -2. * sp / w;
graphic->projection_matrix[5] = 2. * ct * cp / h;
graphic->projection_matrix[9] = 2. * st / h;
graphic->projection_matrix[12] = -1.;
graphic->projection_matrix[13] = -1. - 2. * graphic->ymin / h;
glUniformMatrix4fv (graphic->uniform_3D_matrix, 1, GL_FALSE,
graphic->projection_matrix);
// Drawing a black rectangle
glGenBuffers (1, &vbo_square);
glBindBuffer (GL_ARRAY_BUFFER, vbo_square);
glBufferData (GL_ARRAY_BUFFER, sizeof (square_vertices), square_vertices,
GL_DYNAMIC_DRAW);
glGenBuffers (1, &ibo_square);
glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, ibo_square);
glBufferData (GL_ELEMENT_ARRAY_BUFFER, sizeof (square_indices),
square_indices, GL_DYNAMIC_DRAW);
glBindBuffer (GL_ARRAY_BUFFER, vbo_square);
glEnableVertexAttribArray (graphic->attribute_3D_position);
glVertexAttribPointer (graphic->attribute_3D_position,
3, GL_FLOAT, GL_FALSE, sizeof (Point3D), NULL);
glEnableVertexAttribArray (graphic->attribute_3D_color);
glVertexAttribPointer (graphic->attribute_3D_color,
3,
GL_FLOAT,
GL_FALSE,
sizeof (Point3D),
(GLvoid *) offsetof (Point3D, c));
glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, ibo_square);
glDrawElements (GL_LINE_LOOP, 4, GL_UNSIGNED_SHORT, 0);
glDeleteBuffers (1, &ibo_square);
glDeleteBuffers (1, &vbo_square);
glDisableVertexAttribArray (graphic->attribute_3D_color);
glDisableVertexAttribArray (graphic->attribute_3D_position);
}
else
{
// Projection matrix
graphic->projection_matrix[0] = 2. / width;
graphic->projection_matrix[5] = 2. / height;
graphic->projection_matrix[12] = graphic->projection_matrix[13] = -1.;
graphic->projection_matrix[1] = graphic->projection_matrix[4]
= graphic->projection_matrix[9] = 0.;
glUniformMatrix4fv (graphic->uniform_3D_matrix, 1, GL_FALSE,
graphic->projection_matrix);
}
#if DEBUG
printf ("graphic_render: drawing the fractal points\n");
fflush (stdout);
#endif
// Drawing the fractal points
glGenBuffers (1, &vbo_points);
glBindBuffer (GL_ARRAY_BUFFER, vbo_points);
glBufferData (GL_ARRAY_BUFFER, npoints * sizeof (Point3D), point,
GL_DYNAMIC_DRAW);
glEnableVertexAttribArray (graphic->attribute_3D_position);
glVertexAttribPointer (graphic->attribute_3D_position,
3, GL_FLOAT, GL_FALSE, sizeof (Point3D), NULL);
glEnableVertexAttribArray (graphic->attribute_3D_color);
glVertexAttribPointer (graphic->attribute_3D_color,
3,
GL_FLOAT,
GL_FALSE,
sizeof (Point3D), (GLvoid *) offsetof (Point3D, c));
glDrawArrays (GL_POINTS, 0, npoints);
glDeleteBuffers (1, &vbo_points);
glDisableVertexAttribArray (graphic->attribute_3D_color);
glDisableVertexAttribArray (graphic->attribute_3D_position);
end_draw:
// OpenGL properties
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
#if DEBUG
printf ("graphic_render: drawing the logo\n");
fflush (stdout);
#endif
// Drawing the logo
image_draw (graphic->logo, 0, 0, window_width, window_height);
#if DEBUG
printf ("graphic_render: displaying the program version\n");
fflush (stdout);
#endif
// Displaying the program version
sx = 0.15 * 12. / window_width;
sy = 0.15 * 12. / window_height;
text_draw (graphic->text, (char *) str_version,
0.99 - 7. * strlen (str_version) * sx, -0.99, sx, sy, black);
// Disabling OpenGL properties
glDisable (GL_BLEND);
#if DEBUG
printf ("graphic_render: displaying the draw\n");
fflush (stdout);
#endif
#if DEBUG
printf ("graphic_render: end\n");
fflush (stdout);
#endif
}
/**
* Function to save the draw in a PNG file.
*/
void
graphic_save (char *file_name) ///< File name.
{
png_struct *png;
png_info *info;
png_byte **row_pointers;
GLubyte *pixels;
FILE *file;
unsigned int i, row_bytes, pointers_bytes, pixels_bytes;
#if DEBUG
printf ("graphic_save: start\n");
fflush (stdout);
#endif
// Creating the PNG header
png = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png)
return;
info = png_create_info_struct (png);
if (!info)
return;
file = fopen (file_name, "wb");
if (!file)
return;
if (setjmp (png_jmpbuf (png)))
{
printf ("Error png_init_io\n");
exit (0);
}
png_init_io (png, file);
if (setjmp (png_jmpbuf (png)))
{
printf ("Error png_set_IHDR\n");
exit (0);
}
png_set_IHDR (png,
info,
window_width,
window_height,
8,
PNG_COLOR_TYPE_RGBA,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
if (setjmp (png_jmpbuf (png)))
{
printf ("Error png_write_info\n");
exit (0);
}
png_write_info (png, info);
// Getting the OpenGL pixels
glViewport (0, 0, window_width, window_height);
row_bytes = 4 * window_width;
pixels_bytes = row_bytes * window_height;
pixels = (GLubyte *) g_slice_alloc (pixels_bytes);
glReadPixels (0, 0, window_width, window_height, GL_RGBA, GL_UNSIGNED_BYTE,
pixels);
// Saving the pixels in the PNG order
pointers_bytes = window_height * sizeof (png_byte *);
row_pointers = (png_byte **) g_slice_alloc (pointers_bytes);
for (i = 0; i < window_height; ++i)
{
row_pointers[i] = (png_byte *) g_slice_alloc (row_bytes);
memcpy (row_pointers[i], pixels + (window_height - 1 - i) * row_bytes,
row_bytes);
}
if (setjmp (png_jmpbuf (png)))
{
printf ("Error png_write_image\n");
exit (0);
}
png_write_image (png, row_pointers);
// Freeing memory
for (i = 0; i < window_height; ++i)
g_slice_free1 (row_bytes, row_pointers[i]);
g_slice_free1 (pointers_bytes, row_pointers);
g_slice_free1 (pixels_bytes, pixels);
// Saving the file
if (setjmp (png_jmpbuf (png)))
{
printf ("Error png_write_end\n");
exit (0);
}
png_write_end (png, NULL);
fclose (file);
// Freeing memory
png_destroy_write_struct (&png, &info);
#if DEBUG
printf ("graphic_save: end\n");
fflush (stdout);
#endif
}
| {
"alphanum_fraction": 0.6525284363,
"avg_line_length": 28.7850098619,
"ext": "c",
"hexsha": "93ddc66d6c2cd7fdfd389bdde47e3aaa3509693d",
"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": "95d711dcb7b385556fb77794bc01737b21e99774",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/fractal",
"max_forks_repo_path": "3.4.15/graphic.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/fractal",
"max_issues_repo_path": "3.4.15/graphic.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/fractal",
"max_stars_repo_path": "3.4.15/graphic.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3886,
"size": 14594
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include <gsl/gsl>
#include <string>
namespace cb::breakpad {
/**
* What information should breakpad minidumps contain?
*/
enum class Content {
/**
* Default content (threads+stack+env+arguments)
*/
Default
};
/**
* Settings for Breakpad crash catcher.
*/
struct Settings {
/**
* Default constructor initialize the object to be in a disabled state
*/
Settings() = default;
/**
* Initialize the Breakpad object from the specified JSON structure
* which looks like:
*
* {
* "enabled" : true,
* "minidump_dir" : "/var/crash",
* "content" : "default"
* }
*
* @param json The json to parse
* @throws std::invalid_argument if the json dosn't look as expected
*/
explicit Settings(const nlohmann::json& json);
bool enabled{false};
std::string minidump_dir;
Content content{Content::Default};
};
} // namespace cb::breakpad
std::string to_string(cb::breakpad::Content content);
| {
"alphanum_fraction": 0.6365384615,
"avg_line_length": 25.1612903226,
"ext": "h",
"hexsha": "c1fb6a10456517e230968055b6d05cf8d2d403d0",
"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": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4",
"max_forks_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_forks_repo_name": "BenHuddleston/kv_engine",
"max_forks_repo_path": "utilities/breakpad_settings.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_issues_repo_name": "BenHuddleston/kv_engine",
"max_issues_repo_path": "utilities/breakpad_settings.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "78123c9aa2c2feb24b7c31eecc862bf2ed6325e4",
"max_stars_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_stars_repo_name": "BenHuddleston/kv_engine",
"max_stars_repo_path": "utilities/breakpad_settings.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 386,
"size": 1560
} |
/*****************************************************************\
__
/ /
/ / __ __
/ /______ _______ / / / / ________ __ __
/ ______ \ /_____ \ / / / / / _____ | / / / /
/ / | / _______| / / / / / / /____/ / / / / /
/ / / / / _____ / / / / / / _______/ / / / /
/ / / / / /____/ / / / / / / |______ / |______/ /
/_/ /_/ |________/ / / / / \_______/ \_______ /
/_/ /_/ / /
/ /
High Level Game Framework /_/
---------------------------------------------------------------
Copyright (c) 2007-2011 - Rodrigo Braz Monteiro.
This file is subject to the terms of halley_license.txt.
\*****************************************************************/
#pragma once
#include <memory>
#include "halley/data_structures/vector.h"
#include <gsl/gsl>
#include "halley/core/api/audio_api.h"
struct OggVorbis_File;
#if defined(_MSC_VER) || defined(__clang__)
using OggOffsetType = int64_t;
#else
using OggOffsetType = long int;
#endif
namespace Halley {
class ResourceData;
class ResourceDataReader;
class VorbisData {
public:
VorbisData(std::shared_ptr<ResourceData> resource, bool open);
~VorbisData();
size_t read(gsl::span<Vector<float>> dst);
size_t read(AudioMultiChannelSamples dst, size_t nChannels);
size_t getNumSamples() const; // Per channel
int getSampleRate() const;
int getNumChannels() const;
void close();
void reset();
void seek(double t);
void seek(size_t sample);
size_t tell() const;
size_t getSizeBytes() const;
private:
void open();
static size_t vorbisRead(void* ptr, size_t size, size_t nmemb, void* datasource);
static int vorbisSeek(void *datasource, OggOffsetType offset, int whence);
static int vorbisClose(void *datasource);
static long vorbisTell(void *datasource);
std::shared_ptr<ResourceData> resource;
std::shared_ptr<ResourceDataReader> stream;
OggVorbis_File* file;
bool streaming;
long long pos;
};
}
| {
"alphanum_fraction": 0.534741784,
"avg_line_length": 27.6623376623,
"ext": "h",
"hexsha": "3a69756808d6fb623ee8ef7133f2c0b820a392a7",
"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/engine/audio/include/halley/audio/vorbis_dec.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/engine/audio/include/halley/audio/vorbis_dec.h",
"max_line_length": 83,
"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/engine/audio/include/halley/audio/vorbis_dec.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 544,
"size": 2130
} |
/* matrix/gsl_matrix_short.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_SHORT_H__
#define __GSL_MATRIX_SHORT_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_short.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;
short * data;
gsl_block_short * block;
int owner;
} gsl_matrix_short;
typedef struct
{
gsl_matrix_short matrix;
} _gsl_matrix_short_view;
typedef _gsl_matrix_short_view gsl_matrix_short_view;
typedef struct
{
gsl_matrix_short matrix;
} _gsl_matrix_short_const_view;
typedef const _gsl_matrix_short_const_view gsl_matrix_short_const_view;
/* Allocation */
GSL_FUN gsl_matrix_short *
gsl_matrix_short_alloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_short *
gsl_matrix_short_calloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_short *
gsl_matrix_short_alloc_from_block (gsl_block_short * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_FUN gsl_matrix_short *
gsl_matrix_short_alloc_from_matrix (gsl_matrix_short * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_FUN gsl_vector_short *
gsl_vector_short_alloc_row_from_matrix (gsl_matrix_short * m,
const size_t i);
GSL_FUN gsl_vector_short *
gsl_vector_short_alloc_col_from_matrix (gsl_matrix_short * m,
const size_t j);
GSL_FUN void gsl_matrix_short_free (gsl_matrix_short * m);
/* Views */
GSL_FUN _gsl_matrix_short_view
gsl_matrix_short_submatrix (gsl_matrix_short * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_short_view
gsl_matrix_short_row (gsl_matrix_short * m, const size_t i);
GSL_FUN _gsl_vector_short_view
gsl_matrix_short_column (gsl_matrix_short * m, const size_t j);
GSL_FUN _gsl_vector_short_view
gsl_matrix_short_diagonal (gsl_matrix_short * m);
GSL_FUN _gsl_vector_short_view
gsl_matrix_short_subdiagonal (gsl_matrix_short * m, const size_t k);
GSL_FUN _gsl_vector_short_view
gsl_matrix_short_superdiagonal (gsl_matrix_short * m, const size_t k);
GSL_FUN _gsl_vector_short_view
gsl_matrix_short_subrow (gsl_matrix_short * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_short_view
gsl_matrix_short_subcolumn (gsl_matrix_short * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_short_view
gsl_matrix_short_view_array (short * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_short_view
gsl_matrix_short_view_array_with_tda (short * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_short_view
gsl_matrix_short_view_vector (gsl_vector_short * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_short_view
gsl_matrix_short_view_vector_with_tda (gsl_vector_short * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_short_const_view
gsl_matrix_short_const_submatrix (const gsl_matrix_short * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_short_const_view
gsl_matrix_short_const_row (const gsl_matrix_short * m,
const size_t i);
GSL_FUN _gsl_vector_short_const_view
gsl_matrix_short_const_column (const gsl_matrix_short * m,
const size_t j);
GSL_FUN _gsl_vector_short_const_view
gsl_matrix_short_const_diagonal (const gsl_matrix_short * m);
GSL_FUN _gsl_vector_short_const_view
gsl_matrix_short_const_subdiagonal (const gsl_matrix_short * m,
const size_t k);
GSL_FUN _gsl_vector_short_const_view
gsl_matrix_short_const_superdiagonal (const gsl_matrix_short * m,
const size_t k);
GSL_FUN _gsl_vector_short_const_view
gsl_matrix_short_const_subrow (const gsl_matrix_short * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_short_const_view
gsl_matrix_short_const_subcolumn (const gsl_matrix_short * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_short_const_view
gsl_matrix_short_const_view_array (const short * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_short_const_view
gsl_matrix_short_const_view_array_with_tda (const short * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_short_const_view
gsl_matrix_short_const_view_vector (const gsl_vector_short * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_short_const_view
gsl_matrix_short_const_view_vector_with_tda (const gsl_vector_short * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_FUN void gsl_matrix_short_set_zero (gsl_matrix_short * m);
GSL_FUN void gsl_matrix_short_set_identity (gsl_matrix_short * m);
GSL_FUN void gsl_matrix_short_set_all (gsl_matrix_short * m, short x);
GSL_FUN int gsl_matrix_short_fread (FILE * stream, gsl_matrix_short * m) ;
GSL_FUN int gsl_matrix_short_fwrite (FILE * stream, const gsl_matrix_short * m) ;
GSL_FUN int gsl_matrix_short_fscanf (FILE * stream, gsl_matrix_short * m);
GSL_FUN int gsl_matrix_short_fprintf (FILE * stream, const gsl_matrix_short * m, const char * format);
GSL_FUN int gsl_matrix_short_memcpy(gsl_matrix_short * dest, const gsl_matrix_short * src);
GSL_FUN int gsl_matrix_short_swap(gsl_matrix_short * m1, gsl_matrix_short * m2);
GSL_FUN int gsl_matrix_short_swap_rows(gsl_matrix_short * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_short_swap_columns(gsl_matrix_short * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_short_swap_rowcol(gsl_matrix_short * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_short_transpose (gsl_matrix_short * m);
GSL_FUN int gsl_matrix_short_transpose_memcpy (gsl_matrix_short * dest, const gsl_matrix_short * src);
GSL_FUN short gsl_matrix_short_max (const gsl_matrix_short * m);
GSL_FUN short gsl_matrix_short_min (const gsl_matrix_short * m);
GSL_FUN void gsl_matrix_short_minmax (const gsl_matrix_short * m, short * min_out, short * max_out);
GSL_FUN void gsl_matrix_short_max_index (const gsl_matrix_short * m, size_t * imax, size_t *jmax);
GSL_FUN void gsl_matrix_short_min_index (const gsl_matrix_short * m, size_t * imin, size_t *jmin);
GSL_FUN void gsl_matrix_short_minmax_index (const gsl_matrix_short * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_FUN int gsl_matrix_short_isnull (const gsl_matrix_short * m);
GSL_FUN int gsl_matrix_short_ispos (const gsl_matrix_short * m);
GSL_FUN int gsl_matrix_short_isneg (const gsl_matrix_short * m);
GSL_FUN int gsl_matrix_short_isnonneg (const gsl_matrix_short * m);
GSL_FUN int gsl_matrix_short_add (gsl_matrix_short * a, const gsl_matrix_short * b);
GSL_FUN int gsl_matrix_short_sub (gsl_matrix_short * a, const gsl_matrix_short * b);
GSL_FUN int gsl_matrix_short_mul_elements (gsl_matrix_short * a, const gsl_matrix_short * b);
GSL_FUN int gsl_matrix_short_div_elements (gsl_matrix_short * a, const gsl_matrix_short * b);
GSL_FUN int gsl_matrix_short_scale (gsl_matrix_short * a, const double x);
GSL_FUN int gsl_matrix_short_add_constant (gsl_matrix_short * a, const double x);
GSL_FUN int gsl_matrix_short_add_diagonal (gsl_matrix_short * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_FUN int gsl_matrix_short_get_row(gsl_vector_short * v, const gsl_matrix_short * m, const size_t i);
GSL_FUN int gsl_matrix_short_get_col(gsl_vector_short * v, const gsl_matrix_short * m, const size_t j);
GSL_FUN int gsl_matrix_short_set_row(gsl_matrix_short * m, const size_t i, const gsl_vector_short * v);
GSL_FUN int gsl_matrix_short_set_col(gsl_matrix_short * m, const size_t j, const gsl_vector_short * v);
/***********************************************************************/
/* inline functions if you are using GCC */
GSL_FUN INLINE_DECL short gsl_matrix_short_get(const gsl_matrix_short * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL void gsl_matrix_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const short x);
GSL_FUN INLINE_DECL short * gsl_matrix_short_ptr(gsl_matrix_short * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL const short * gsl_matrix_short_const_ptr(const gsl_matrix_short * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
short
gsl_matrix_short_get(const gsl_matrix_short * 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_short_set(gsl_matrix_short * m, const size_t i, const size_t j, const 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
short *
gsl_matrix_short_ptr(gsl_matrix_short * 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 (short *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
const short *
gsl_matrix_short_const_ptr(const gsl_matrix_short * 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 short *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_SHORT_H__ */
| {
"alphanum_fraction": 0.6460455362,
"avg_line_length": 37.1922005571,
"ext": "h",
"hexsha": "7aed526b1358ea69e34ce41fbced21744cdfff83",
"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_short.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_short.h",
"max_line_length": 133,
"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_short.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3177,
"size": 13352
} |
/**
*
* @file example_dpotrf.c
*
* PLASMA testing routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @brief Example of Cholesky factorization
*
* @version 2.6.0
* @author Bilel Hadri
* @date 2010-11-15
* @generated d Tue Jan 7 11:45:20 2014
*
**/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <plasma.h>
#include <cblas.h>
#include <lapacke.h>
#include <core_blas.h>
#include "testing_dmain.h"
static int check_factorization(int, int, double*, double*, int);
static void GENMAT_SYM_FULL(int m, int n, double *A)
{
srand48(time(NULL));
int j;
for (j = 0; j < m; ++j ) {
int i;
for( i = j; i < n; ++i ) {
double dran = drand48();
A[j*m+i] = A[i*m+j] = dran;
}
}
for(j = 0; j < m; ++j)
A[j*m+j] += 10 * m;
}
int testing_dgeqrf(int argc, char **argv)
{
int M = 1000;
int N = 1000;
int LDA = 1000;
int info_factorization;
double *A1 = (double *)malloc(LDA*N*sizeof(double));
double *A2 = (double *)malloc(LDA*N*sizeof(double));
#pragma omp register ([LDA*N]A2)
/* Check if unable to allocate memory */
if ((!A1)||(!A2)){
printf("Out of Memory \n ");
return EXIT_SUCCESS;
}
/* Initialize A1 and A2 for Symmetric Positive Matrix */
GENMAT_SYM_FULL(LDA, N, A1);
int i;
for(i = 0; i < N*LDA; ++i){
A2[i] = A1[i];
}
/* Plasma routines */
PLASMA_desc *T;
PLASMA_Alloc_Workspace_dgels(M, N, &T);
PLASMA_dgeqrf(M, N, A2, LDA, T);
/* Check the factorization */
info_factorization = check_factorization( M, N, A1, A2, LDA);
if ( info_factorization != 0 )
printf("-- Error in DPOTRF example ! \n");
else
printf("-- Run of DPOTRF example successful ! \n");
free(A1); free(A2);
return 0;
}
static int check_factorization(int M, int N, double *A1, double *A2, int LDA)
{
double Anorm, Rnorm;
double Anorm1, Rnorm1;
double alpha;
int info_factorization;
int i,j;
double eps;
eps = LAPACKE_dlamch_work('e');
// double *Residual = (double *)malloc(M*N*sizeof(double));
// double *L1 = (double *)malloc(M*N*sizeof(double));
// double *L2 = (double *)malloc(M*N*sizeof(double));
double *work = (double *)malloc(N*sizeof(double));
LAPACKE_dgeqrf(LAPACK_COL_MAJOR, M, N, A1, M, work);
Rnorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, A1, M, work);
Anorm = LAPACKE_dlange_work(LAPACK_COL_MAJOR, lapack_const(PlasmaInfNorm), M, N, A2, LDA, work);
Rnorm1 = PLASMA_dlange(PlasmaInfNorm, M, N, A1, LDA);
Anorm1 = PLASMA_dlange(PlasmaInfNorm, M, N, A2, LDA);
printf("|Rnorm-Rnorm1|: %e, |Anorm-Anorm1|: %e\n", fabs(Rnorm-Rnorm1), fabs(Anorm-Anorm1));
printf("============\n");
printf("Checking the QR Factorization \n");
printf("-- ||L'L-A||_oo/(||A||_oo.N.eps) = %e \n",fabs(Rnorm-Anorm)/(Anorm));
if ( isnan(fabs(Rnorm-Anorm)/(Anorm)) || (fabs(Rnorm-Anorm)/(Anorm) > 10.0) ){
printf("-- Factorization is suspicious ! \n");
info_factorization = 1;
}
else{
printf("-- Factorization is CORRECT ! \n");
info_factorization = 0;
}
// free(Residual); free(L1); free(L2); free(work);
return info_factorization;
}
| {
"alphanum_fraction": 0.6082321587,
"avg_line_length": 25.5833333333,
"ext": "c",
"hexsha": "c43ef4e1707a4b4aa2125c6f3611162ac9c94c33",
"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_dgeqrf.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_dgeqrf.c",
"max_line_length": 100,
"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_dgeqrf.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1107,
"size": 3377
} |
/*
* Player - One Hell of a Robot Server
* Copyright (C) 2000 Brian Gerkey & Kasper Stoy
* gerkey@usc.edu kaspers@robotics.usc.edu
*
* This library is 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.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/**************************************************************************
* Desc: Useful pdf functions
* Author: Andrew Howard
* Date: 10 Dec 2002
* CVS: $Id: pf_pdf.c 6348 2008-04-17 02:53:17Z gerkey $
*************************************************************************/
#include <assert.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
//#include <gsl/gsl_rng.h>
//#include <gsl/gsl_randist.h>
#include "amcl/pf/pf_pdf.h"
// Random number generator seed value
static unsigned int pf_pdf_seed;
/**************************************************************************
* Gaussian
*************************************************************************/
// Create a gaussian pdf
pf_pdf_gaussian_t *pf_pdf_gaussian_alloc(pf_vector_t x, pf_matrix_t cx)
{
pf_matrix_t cd;
pf_pdf_gaussian_t *pdf;
pdf = calloc(1, sizeof(pf_pdf_gaussian_t));
pdf->x = x;
pdf->cx = cx;
//pdf->cxi = pf_matrix_inverse(cx, &pdf->cxdet);
// Decompose the convariance matrix into a rotation
// matrix and a diagonal matrix.
pf_matrix_unitary(&pdf->cr, &cd, pdf->cx);
pdf->cd.v[0] = sqrt(cd.m[0][0]);
pdf->cd.v[1] = sqrt(cd.m[1][1]);
pdf->cd.v[2] = sqrt(cd.m[2][2]);
// Initialize the random number generator
//pdf->rng = gsl_rng_alloc(gsl_rng_taus);
//gsl_rng_set(pdf->rng, ++pf_pdf_seed);
srand48(++pf_pdf_seed);
return pdf;
}
// Destroy the pdf
void pf_pdf_gaussian_free(pf_pdf_gaussian_t *pdf)
{
//gsl_rng_free(pdf->rng);
free(pdf);
return;
}
/*
// Compute the value of the pdf at some point [x].
double pf_pdf_gaussian_value(pf_pdf_gaussian_t *pdf, pf_vector_t x)
{
int i, j;
pf_vector_t z;
double zz, p;
z = pf_vector_sub(x, pdf->x);
zz = 0;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
zz += z.v[i] * pdf->cxi.m[i][j] * z.v[j];
p = 1 / (2 * M_PI * pdf->cxdet) * exp(-zz / 2);
return p;
}
*/
// Generate a sample from the pdf.
pf_vector_t pf_pdf_gaussian_sample(pf_pdf_gaussian_t *pdf)
{
int i, j;
pf_vector_t r;
pf_vector_t x;
// Generate a random vector
for (i = 0; i < 3; i++)
{
//r.v[i] = gsl_ran_gaussian(pdf->rng, pdf->cd.v[i]);
r.v[i] = pf_ran_gaussian(pdf->cd.v[i]);
}
for (i = 0; i < 3; i++)
{
x.v[i] = pdf->x.v[i];
for (j = 0; j < 3; j++)
x.v[i] += pdf->cr.m[i][j] * r.v[j];
}
return x;
}
// Draw randomly from a zero-mean Gaussian distribution, with standard
// deviation sigma.
// We use the polar form of the Box-Muller transformation, explained here:
// http://www.taygeta.com/random/gaussian.html
double pf_ran_gaussian(double sigma)
{
double x1, x2, w, r;
do
{
do { r = drand48(); } while (r==0.0);
x1 = 2.0 * r - 1.0;
do { r = drand48(); } while (r==0.0);
x2 = 2.0 * r - 1.0;
w = x1*x1 + x2*x2;
} while(w > 1.0 || w==0.0);
return(sigma * x2 * sqrt(-2.0*log(w)/w));
}
| {
"alphanum_fraction": 0.5816890292,
"avg_line_length": 25.8571428571,
"ext": "c",
"hexsha": "436a66c0f766e3f9b14d2e4dcfb1f9091de6c004",
"lang": "C",
"max_forks_count": 22,
"max_forks_repo_forks_event_max_datetime": "2022-03-13T03:06:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-13T07:16:12.000Z",
"max_forks_repo_head_hexsha": "af9370a1a8ce3dea893fe2c2e194bee433c1b734",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "0aqz0/SmartCar",
"max_forks_repo_path": "src/navigation/amcl/src/amcl/pf/pf_pdf.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "af9370a1a8ce3dea893fe2c2e194bee433c1b734",
"max_issues_repo_issues_event_max_datetime": "2021-09-14T02:30:55.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-09-03T06:19:13.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "0aqz0/SmartCar",
"max_issues_repo_path": "src/navigation/amcl/src/amcl/pf/pf_pdf.c",
"max_line_length": 77,
"max_stars_count": 59,
"max_stars_repo_head_hexsha": "af9370a1a8ce3dea893fe2c2e194bee433c1b734",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "0aqz0/SmartCar",
"max_stars_repo_path": "src/navigation/amcl/src/amcl/pf/pf_pdf.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T07:25:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-03T04:03:04.000Z",
"num_tokens": 1156,
"size": 3801
} |
#ifndef AMICI_MODEL_DIMENSIONS_H
#define AMICI_MODEL_DIMENSIONS_H
#include <gsl/gsl-lite.hpp>
#include <vector>
namespace amici {
/**
* @brief Container for model dimensions.
*
* Holds number of states, observables, etc.
*/
struct ModelDimensions {
/** Default ctor */
ModelDimensions() = default;
/**
* @brief Constructor with model dimensions
* @param nx_rdata Number of state variables
* @param nxtrue_rdata Number of state variables of the non-augmented model
* @param nx_solver Number of state variables with conservation laws applied
* @param nxtrue_solver Number of state variables of the non-augmented model
* with conservation laws applied
* @param nx_solver_reinit Number of state variables with conservation laws
* subject to reinitialization
* @param np Number of parameters
* @param nk Number of constants
* @param ny Number of observables
* @param nytrue Number of observables of the non-augmented model
* @param nz Number of event observables
* @param nztrue Number of event observables of the non-augmented model
* @param ne Number of events
* @param nJ Number of objective functions
* @param nw Number of repeating elements
* @param ndwdx Number of nonzero elements in the `x` derivative of the
* repeating elements
* @param ndwdp Number of nonzero elements in the `p` derivative of the
* repeating elements
* @param ndwdw Number of nonzero elements in the `w` derivative of the
* repeating elements
* @param ndxdotdw Number of nonzero elements in the \f$ w\f$ derivative of \f$ xdot\f$
* @param ndJydy Number of nonzero elements in the \f$ y\f$ derivative of \f$ dJy\f$ (shape `nytrue`)
* @param nnz Number of nonzero elements in Jacobian
* @param ubw Upper matrix bandwidth in the Jacobian
* @param lbw Lower matrix bandwidth in the Jacobian
*/
ModelDimensions(
const int nx_rdata, const int nxtrue_rdata, const int nx_solver,
const int nxtrue_solver, const int nx_solver_reinit, const int np,
const int nk, const int ny,
const int nytrue, const int nz, const int nztrue, const int ne,
const int nJ, const int nw, const int ndwdx, const int ndwdp,
const int ndwdw, const int ndxdotdw, std::vector<int> ndJydy,
const int nnz, const int ubw, const int lbw)
: nx_rdata(nx_rdata), nxtrue_rdata(nxtrue_rdata), nx_solver(nx_solver),
nxtrue_solver(nxtrue_solver), nx_solver_reinit(nx_solver_reinit),
np(np), nk(nk),
ny(ny), nytrue(nytrue), nz(nz), nztrue(nztrue),
ne(ne), nw(nw), ndwdx(ndwdx), ndwdp(ndwdp), ndwdw(ndwdw),
ndxdotdw(ndxdotdw), ndJydy(std::move(ndJydy)),
nnz(nnz), nJ(nJ), ubw(ubw), lbw(lbw) {
Expects(nxtrue_rdata >= 0);
Expects(nxtrue_rdata <= nx_rdata);
Expects(nxtrue_solver >= 0);
Expects(nx_solver <= nx_rdata);
Expects(nxtrue_solver <= nx_solver);
Expects(nx_solver_reinit >= 0);
Expects(nx_solver_reinit <= nx_solver);
Expects(np >= 0);
Expects(nk >= 0);
Expects(nytrue <= ny);
Expects(nytrue >= 0);
Expects(nztrue >= 0);
Expects(nztrue <= nz);
Expects(ne >= 0);
Expects(nw >= 0);
Expects(ndwdx >= 0);
Expects(ndwdx <= nw * nx_solver);
Expects(ndwdp >= 0);
Expects(ndwdp <= nw * np);
Expects(ndwdw >= 0);
Expects(ndwdw <= nw * nw);
Expects(ndxdotdw >= 0);
Expects(nnz >= 0);
Expects(nJ >= 0);
Expects(ubw >= 0);
Expects(lbw >= 0);
}
/** Number of states */
int nx_rdata{0};
/** Number of states in the unaugmented system */
int nxtrue_rdata{0};
/** Number of states with conservation laws applied */
int nx_solver{0};
/**
* Number of states in the unaugmented system with conservation laws
* applied
*/
int nxtrue_solver{0};
/** Number of solver states subject to reinitialization */
int nx_solver_reinit{0};
/** Number of parameters */
int np{0};
/** Number of constants */
int nk{0};
/** Number of observables */
int ny{0};
/** Number of observables in the unaugmented system */
int nytrue{0};
/** Number of event outputs */
int nz{0};
/** Number of event outputs in the unaugmented system */
int nztrue{0};
/** Number of events */
int ne{0};
/** Number of common expressions */
int nw{0};
/**
* Number of nonzero elements in the `x` derivative of the
* repeating elements
*/
int ndwdx {0};
/**
* Number of nonzero elements in the `p` derivative of the
* repeating elements
*/
int ndwdp {0};
/**
* Number of nonzero elements in the `w` derivative of the
* repeating elements
*/
int ndwdw {0};
/** Number of nonzero elements in the \f$ w \f$ derivative of \f$ xdot \f$ */
int ndxdotdw {0};
/**
* Number of nonzero elements in the \f$ y \f$ derivative of
* \f$ dJy \f$ (dimension `nytrue`)
*/
std::vector<int> ndJydy;
/** Number of nonzero entries in Jacobian */
int nnz{0};
/** Dimension of the augmented objective function for 2nd order ASA */
int nJ{0};
/** Upper bandwidth of the Jacobian */
int ubw{0};
/** Lower bandwidth of the Jacobian */
int lbw{0};
};
} // namespace amici
#endif // AMICI_MODEL_DIMENSIONS_H
| {
"alphanum_fraction": 0.6210431655,
"avg_line_length": 31.5909090909,
"ext": "h",
"hexsha": "ca7f0f1af02fdb36f43c50a6d9cbe2768b1eab22",
"lang": "C",
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2022-03-23T12:43:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-09-02T09:32:43.000Z",
"max_forks_repo_head_hexsha": "4610a608d05731d245218c88015d8017f81087b5",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "AMICI-dev/AMICI",
"max_forks_repo_path": "include/amici/model_dimensions.h",
"max_issues_count": 589,
"max_issues_repo_head_hexsha": "4610a608d05731d245218c88015d8017f81087b5",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T17:32:27.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-08-07T21:56:42.000Z",
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "AMICI-dev/AMICI",
"max_issues_repo_path": "include/amici/model_dimensions.h",
"max_line_length": 105,
"max_stars_count": 44,
"max_stars_repo_head_hexsha": "4610a608d05731d245218c88015d8017f81087b5",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "AMICI-dev/AMICI",
"max_stars_repo_path": "include/amici/model_dimensions.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-23T21:25:27.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-17T07:12:07.000Z",
"num_tokens": 1484,
"size": 5560
} |
#ifndef setupdm_h
#define setupdm_h
#include <ceed.h>
#include <petsc.h>
#include <petscdmplex.h>
#include <petscfe.h>
#include "../include/structs.h"
// -----------------------------------------------------------------------------
// Setup DM
// -----------------------------------------------------------------------------
PetscErrorCode CreateBCLabel(DM dm, const char name[]);
// Create FE by degree
PetscErrorCode PetscFECreateByDegree(DM dm, PetscInt dim, PetscInt Nc,
PetscBool is_simplex, const char prefix[],
PetscInt order, PetscFE *fem);
// Read mesh and distribute DM in parallel
PetscErrorCode CreateDistributedDM(MPI_Comm comm, AppCtx app_ctx, DM *dm);
// Setup DM with FE space of appropriate degree
PetscErrorCode SetupDMByDegree(DM dm, AppCtx app_ctx, PetscInt order,
PetscBool boundary, PetscInt num_comp_u);
#endif // setupdm_h
| {
"alphanum_fraction": 0.5584551148,
"avg_line_length": 34.2142857143,
"ext": "h",
"hexsha": "57f610625e9893d079920aad66931f65ada33e12",
"lang": "C",
"max_forks_count": 41,
"max_forks_repo_forks_event_max_datetime": "2022-03-01T13:02:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-12-27T22:35:13.000Z",
"max_forks_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "AdelekeBankole/libCEED",
"max_forks_repo_path": "examples/solids/include/setup-dm.h",
"max_issues_count": 781,
"max_issues_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T21:34:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-12-22T17:20:35.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "AdelekeBankole/libCEED",
"max_issues_repo_path": "examples/solids/include/setup-dm.h",
"max_line_length": 80,
"max_stars_count": 123,
"max_stars_repo_head_hexsha": "aae8ce39fa1e28b745979a9cbffc67a790eb3f5e",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "AdelekeBankole/libCEED",
"max_stars_repo_path": "examples/solids/include/setup-dm.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T18:13:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-29T02:04:05.000Z",
"num_tokens": 192,
"size": 958
} |
#pragma once
#include "gl_helpers.h"
#include "GL_Loader.h"
#include "MappedGL.h"
#include "Range.h"
#include <handy/Guard.h>
#include <gsl/span>
#include <type_traits>
#include <vector>
namespace ad
{
struct [[nodiscard]] VertexArrayObject : public ResourceGuard<GLuint>
{
/// \note Deleting a bound VAO reverts the binding to zero
VertexArrayObject() :
ResourceGuard<GLuint>{reserve(glGenVertexArrays),
[](GLuint aIndex){glDeleteVertexArrays(1, &aIndex);}}
{}
};
/// \TODO understand when glDisableVertexAttribArray should actually be called
/// (likely not specially before destruction, but more when rendering other objects
/// since it is a current(i.e. global) VAO state)
/// \Note Well note even that: Activated vertex attribute array are per VAO, so changing VAO
// Already correctly handles that.
struct [[nodiscard]] VertexBufferObject : public ResourceGuard<GLuint>
{
VertexBufferObject() :
ResourceGuard<GLuint>{reserve(glGenBuffers),
[](GLuint aIndex){glDeleteBuffers(1, &aIndex);}}
{}
};
/// \brief A VertexArray with a vector of VertexBuffers
struct [[nodiscard]] VertexSpecification
{
VertexSpecification(VertexArrayObject aVertexArray={},
std::vector<VertexBufferObject> aVertexBuffers={}) :
mVertexArray{std::move(aVertexArray)},
mVertexBuffers{std::move(aVertexBuffers)}
{}
VertexArrayObject mVertexArray;
std::vector<VertexBufferObject> mVertexBuffers;
};
/// \brief Describes the attribute access from the shader (layout id, value type, normalization)
struct Attribute
{
enum class Access
{
Float,
Integer,
};
constexpr Attribute(GLuint aValue) :
mIndex(aValue)
{}
constexpr Attribute(GLuint aValue, Access aAccess, bool aNormalize=false) :
mIndex(aValue),
mTypeInShader(aAccess),
mNormalize(aNormalize)
{}
GLuint mIndex;
Access mTypeInShader{Access::Float};
bool mNormalize{false};
};
/// \brief The complete description of an attribute expected by OpenGL
struct AttributeDescription : public Attribute
{
GLuint mDimension;
size_t mOffset;
GLenum mDataType;
};
std::ostream & operator<<(std::ostream &aOut, const AttributeDescription & aDescription);
typedef std::initializer_list<AttributeDescription> AttributeDescriptionList;
template <class T_vertex>
VertexBufferObject loadVertexBuffer(const VertexArrayObject & aVertexArray,
const AttributeDescriptionList & aAttributes,
const gsl::span<T_vertex> aVertices,
GLuint aAttributeDivisor = 0)
{
glBindVertexArray(aVertexArray);
if (aAttributeDivisor)
{
for(const auto & attribute : aAttributes)
{
glVertexAttribDivisor(attribute.mIndex, aAttributeDivisor);
}
}
return makeLoadedVertexBuffer(aAttributes, aVertices);
}
template <class T_vertex>
void appendToVertexSpecification(VertexSpecification & aSpecification,
const AttributeDescriptionList & aAttributes,
const gsl::span<T_vertex> aVertices,
GLuint aAttributeDivisor = 0)
{
aSpecification.mVertexBuffers.push_back(
loadVertexBuffer(aSpecification.mVertexArray,
aAttributes,
std::move(aVertices),
aAttributeDivisor));
}
/// \brief Create a VertexBufferObject with provided attributes, load it with data.
///
/// This is the lowest level overload, with explicit attribute description and raw data pointer.
/// Other overloads end-up calling it.
VertexBufferObject makeLoadedVertexBuffer(AttributeDescriptionList aAttributes,
GLsizei aStride,
size_t aSize,
const GLvoid * aData);
template <class T_vertex>
VertexBufferObject makeLoadedVertexBuffer(AttributeDescriptionList aAttributes,
const gsl::span<T_vertex> aVertices)
{
return makeLoadedVertexBuffer(aAttributes,
sizeof(T_vertex),
aVertices.size_bytes(),
aVertices.data());
}
/***
* Buffer re-specification
*
* see: https://www.khronos.org/opengl/wiki/Buffer_Object_Streaming#Buffer_re-specification
***/
inline void respecifyBuffer(const VertexBufferObject & aVBO, const GLvoid * aData, GLsizei aSize)
{
glBindBuffer(GL_ARRAY_BUFFER, aVBO);
// Orphan the previous buffer
glBufferData(GL_ARRAY_BUFFER, aSize, NULL, GL_STATIC_DRAW);
// Copy value to new buffer
glBufferSubData(GL_ARRAY_BUFFER, 0, aSize, aData);
}
/// \brief Respecify the buffer with the same size (allowing potential optimizations)
inline void respecifyBuffer(const VertexBufferObject & aVBO, const GLvoid * aData)
{
GLint size;
glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
respecifyBuffer(aVBO, aData, size);
}
template <class T_vertex>
void respecifyBuffer(const VertexBufferObject & aVBO, const gsl::span<T_vertex> aVertices)
{
respecifyBuffer(aVBO,
aVertices.data(),
static_cast<GLsizei>(aVertices.size_bytes()));
}
} // namespace ad
| {
"alphanum_fraction": 0.6475691307,
"avg_line_length": 30.5690607735,
"ext": "h",
"hexsha": "00b90e948a2af69cbc34badd411e8a8447539d6a",
"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": "b426e5ca8b98dc2bd9c63335daba8aff9244f3fc",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "FranzPoize/graphics",
"max_forks_repo_path": "src/lib/renderer/renderer/VertexSpecification.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b426e5ca8b98dc2bd9c63335daba8aff9244f3fc",
"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": "FranzPoize/graphics",
"max_issues_repo_path": "src/lib/renderer/renderer/VertexSpecification.h",
"max_line_length": 97,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b426e5ca8b98dc2bd9c63335daba8aff9244f3fc",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "FranzPoize/graphics",
"max_stars_repo_path": "src/lib/renderer/renderer/VertexSpecification.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1111,
"size": 5533
} |
#ifndef CTETRA_SUM_H
#define CTETRA_SUM_H
#include <stdlib.h>
#include <stdbool.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include "input.h"
#include "ecache.h"
#include "evcache.h"
#include "submesh.h"
#include "fermi.h"
#include "weights.h"
double SumEnergy(double *E_Fermi, InputFn Efn, int na, int nb, int nc, int num_bands, double num_electrons, gsl_matrix *R, bool use_cache);
double SumEnergyFixedFermi(double E_Fermi, InputFn Efn, int na, int nb, int nc, int num_bands, gsl_matrix *R, bool use_cache);
double with_cache_SumEnergyFixedFermi(double E_Fermi, EnergyCache *Ecache);
double** partial_num_states(UEInputFn UEfn, int na, int nb, int nc, int num_bands, double num_total_electrons, gsl_matrix *R, double **Es, int num_E, double *E_Fermi, double **num_states_Fermi);
double one_band_n(double E_Fermi, int band_index, EvecCache *evCache);
#endif // CTETRA_SUM_H
| {
"alphanum_fraction": 0.7687366167,
"avg_line_length": 33.3571428571,
"ext": "h",
"hexsha": "de6ef8e76fd2e364620c8a2b30b20ecb2f482ed6",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tflovorn/ctetra",
"max_forks_repo_path": "sum.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_issues_repo_issues_event_max_datetime": "2016-11-30T15:23:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-11-19T22:44:14.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tflovorn/ctetra",
"max_issues_repo_path": "sum.h",
"max_line_length": 194,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1a788d6c36d4a0773d4a2fca4d23a8e4d1fd87a1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tflovorn/ctetra",
"max_stars_repo_path": "sum.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 283,
"size": 934
} |
/* -*- c++ -*- */
/*
* Copyright 2008,2012 Free Software Foundation, Inc.
*
* This file is part of GNU Radio
*
* GNU Radio 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, or (at your option)
* any later version.
*
* GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef INCLUDED_WAVELET_SQUASH_FF_IMPL_H
#define INCLUDED_WAVELET_SQUASH_FF_IMPL_H
#include <gnuradio/wavelet/api.h>
#include <gnuradio/wavelet/squash_ff.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
namespace gr {
namespace wavelet {
class WAVELET_API squash_ff_impl : public squash_ff
{
size_t d_inum;
size_t d_onum;
double *d_igrid;
double *d_iwork;
double *d_ogrid;
gsl_interp_accel *d_accel;
gsl_spline *d_spline;
public:
squash_ff_impl(const std::vector<float> &igrid,
const std::vector<float> &ogrid);
~squash_ff_impl();
int work(int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
};
} /* namespace wavelet */
} /* namespace gr */
#endif /* INCLUDED_WAVELET_WAVELET_FF_IMPL_H */
| {
"alphanum_fraction": 0.7031431898,
"avg_line_length": 28.1639344262,
"ext": "h",
"hexsha": "933ee5288c300ee145b68acb09b9f10f44b7c9dd",
"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": "64c149520ac6a7d44179c3f4a38f38add45dd5dc",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "v1259397/cosmic-gnuradio",
"max_forks_repo_path": "gnuradio-3.7.13.4/gr-wavelet/lib/squash_ff_impl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc",
"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": "v1259397/cosmic-gnuradio",
"max_issues_repo_path": "gnuradio-3.7.13.4/gr-wavelet/lib/squash_ff_impl.h",
"max_line_length": 71,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "64c149520ac6a7d44179c3f4a38f38add45dd5dc",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "v1259397/cosmic-gnuradio",
"max_stars_repo_path": "gnuradio-3.7.13.4/gr-wavelet/lib/squash_ff_impl.h",
"max_stars_repo_stars_event_max_datetime": "2021-03-09T07:32:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-09T07:32:37.000Z",
"num_tokens": 443,
"size": 1718
} |
/* Author: G. Jungman + modifications from O. Teytaud
*/
#ifndef __GSL_QRNG_H__
#define __GSL_QRNG_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.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
/* Once again, more inane C-style OOP... kill me now. */
/* Structure describing a type of generator.
*/
typedef struct
{
const char * name;
unsigned int max_dimension;
size_t (*state_size) (unsigned int dimension);
int (*init_state) (void * state, unsigned int dimension);
int (*get) (void * state, unsigned int dimension, double x[]);
}
gsl_qrng_type;
/* Structure describing a generator instance of a
* specified type, with generator-specific state info
* and dimension-specific info.
*/
typedef struct
{
const gsl_qrng_type * type;
unsigned int dimension;
size_t state_size;
void * state;
}
gsl_qrng;
/* Supported generator types.
*/
GSL_VAR const gsl_qrng_type * gsl_qrng_niederreiter_2;
GSL_VAR const gsl_qrng_type * gsl_qrng_sobol;
GSL_VAR const gsl_qrng_type * gsl_qrng_halton;
GSL_VAR const gsl_qrng_type * gsl_qrng_reversehalton;
/* Allocate and initialize a generator
* of the specified type, in the given
* space dimension.
*/
gsl_qrng * gsl_qrng_alloc (const gsl_qrng_type * T, unsigned int dimension);
/* Copy a generator. */
int gsl_qrng_memcpy (gsl_qrng * dest, const gsl_qrng * src);
/* Clone a generator. */
gsl_qrng * gsl_qrng_clone (const gsl_qrng * q);
/* Free a generator. */
void gsl_qrng_free (gsl_qrng * q);
/* Intialize a generator. */
void gsl_qrng_init (gsl_qrng * q);
/* Get the standardized name of the generator. */
const char * gsl_qrng_name (const gsl_qrng * q);
/* ISN'T THIS CONFUSING FOR PEOPLE?
WHAT IF SOMEBODY TRIES TO COPY WITH THIS ???
*/
size_t gsl_qrng_size (const gsl_qrng * q);
void * gsl_qrng_state (const gsl_qrng * q);
/* Retrieve next vector in sequence. */
INLINE_DECL int gsl_qrng_get (const gsl_qrng * q, double x[]);
#ifdef HAVE_INLINE
INLINE_FUN int gsl_qrng_get (const gsl_qrng * q, double x[])
{
return (q->type->get) (q->state, q->dimension, x);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* !__GSL_QRNG_H__ */
| {
"alphanum_fraction": 0.7222929936,
"avg_line_length": 21.0267857143,
"ext": "h",
"hexsha": "a1570ab0a52e3b19e08ac12d67ec09250f7259e9",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z",
"max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "snipekill/FPGen",
"max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_qrng.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"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": "snipekill/FPGen",
"max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_qrng.h",
"max_line_length": 76,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "snipekill/FPGen",
"max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_qrng.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z",
"num_tokens": 653,
"size": 2355
} |
/* interpolation/gsl_interp2d.h
*
* Copyright 2012 David Zaslavsky
*
* 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_INTERP2D_H__
#define __GSL_INTERP2D_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 <gsl/gsl_interp.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 {
const char* name;
unsigned int min_size;
void * (*alloc)(size_t xsize, size_t ysize);
int (*init)(void *, const double xa[], const double ya[], const double za[], size_t xsize, size_t ysize);
int (*eval)(const void *, const double xa[], const double ya[], const double za[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel*, gsl_interp_accel*, double* z);
int (*eval_deriv_x) (const void *, const double xa[], const double ya[], const double za[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel*, gsl_interp_accel*, double* z_p);
int (*eval_deriv_y) (const void *, const double xa[], const double ya[], const double za[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel*, gsl_interp_accel*, double* z_p);
int (*eval_deriv_xx) (const void *, const double xa[], const double ya[], const double za[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel*, gsl_interp_accel*, double* z_pp);
int (*eval_deriv_xy) (const void *, const double xa[], const double ya[], const double za[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel*, gsl_interp_accel*, double* z_pp);
int (*eval_deriv_yy) (const void *, const double xa[], const double ya[], const double za[], size_t xsize, size_t ysize, double x, double y, gsl_interp_accel*, gsl_interp_accel*, double* z_pp);
void (*free)(void *);
} gsl_interp2d_type;
typedef struct {
const gsl_interp2d_type * type; /* interpolation type */
double xmin; /* minimum value of x for which data have been provided */
double xmax; /* maximum value of x for which data have been provided */
double ymin; /* minimum value of y for which data have been provided */
double ymax; /* maximum value of y for which data have been provided */
size_t xsize; /* number of x values provided */
size_t ysize; /* number of y values provided */
void * state; /* internal state object specific to the interpolation type */
} gsl_interp2d;
/* available types */
GSL_VAR const gsl_interp2d_type * gsl_interp2d_bilinear;
GSL_VAR const gsl_interp2d_type * gsl_interp2d_bicubic;
GSL_FUN gsl_interp2d * gsl_interp2d_alloc(const gsl_interp2d_type * T, const size_t xsize,
const size_t ysize);
GSL_FUN const char * gsl_interp2d_name(const gsl_interp2d * interp);
GSL_FUN size_t gsl_interp2d_min_size(const gsl_interp2d * interp);
GSL_FUN size_t gsl_interp2d_type_min_size(const gsl_interp2d_type * T);
GSL_FUN int gsl_interp2d_set(const gsl_interp2d * interp, double zarr[],
const size_t i, const size_t j, const double z);
GSL_FUN double gsl_interp2d_get(const gsl_interp2d * interp, const double zarr[],
const size_t i, const size_t j);
GSL_FUN size_t gsl_interp2d_idx(const gsl_interp2d * interp,
const size_t i, const size_t j);
GSL_FUN int gsl_interp2d_init(gsl_interp2d * interp, const double xa[], const double ya[],
const double za[], const size_t xsize, const size_t ysize);
GSL_FUN void gsl_interp2d_free(gsl_interp2d * interp);
GSL_FUN double gsl_interp2d_eval(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[], const double x,
const double y, gsl_interp_accel * xa, gsl_interp_accel * ya);
GSL_FUN double gsl_interp2d_eval_extrap(const gsl_interp2d * interp,
const double xarr[], const double yarr[],
const double zarr[], const double x,
const double y, gsl_interp_accel * xa,
gsl_interp_accel * ya);
GSL_FUN int gsl_interp2d_eval_e(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y, gsl_interp_accel* xa,
gsl_interp_accel* ya, double * z);
#ifndef GSL_DISABLE_DEPRECATED
GSL_FUN int gsl_interp2d_eval_e_extrap(const gsl_interp2d * interp,
const double xarr[],
const double yarr[],
const double zarr[],
const double x,
const double y,
gsl_interp_accel * xa,
gsl_interp_accel * ya,
double * z);
#endif /* !GSL_DISABLE_DEPRECATED */
GSL_FUN int gsl_interp2d_eval_extrap_e(const gsl_interp2d * interp,
const double xarr[],
const double yarr[],
const double zarr[],
const double x,
const double y,
gsl_interp_accel * xa,
gsl_interp_accel * ya,
double * z);
GSL_FUN double gsl_interp2d_eval_deriv_x(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y, gsl_interp_accel * xa,
gsl_interp_accel * ya);
GSL_FUN int gsl_interp2d_eval_deriv_x_e(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z);
GSL_FUN double gsl_interp2d_eval_deriv_y(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel* xa, gsl_interp_accel* ya);
GSL_FUN int gsl_interp2d_eval_deriv_y_e(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z);
GSL_FUN double gsl_interp2d_eval_deriv_xx(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya);
GSL_FUN int gsl_interp2d_eval_deriv_xx_e(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z);
GSL_FUN double gsl_interp2d_eval_deriv_yy(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya);
GSL_FUN int gsl_interp2d_eval_deriv_yy_e(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z);
GSL_FUN double gsl_interp2d_eval_deriv_xy(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya);
GSL_FUN int gsl_interp2d_eval_deriv_xy_e(const gsl_interp2d * interp, const double xarr[],
const double yarr[], const double zarr[],
const double x, const double y,
gsl_interp_accel * xa, gsl_interp_accel * ya, double * z);
__END_DECLS
#endif /* __GSL_INTERP2D_H__ */
| {
"alphanum_fraction": 0.5975597252,
"avg_line_length": 52.7189189189,
"ext": "h",
"hexsha": "312cea19cdce6621d3f1f2c50557e5b0fe4a6f1f",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.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/gsl/gsl_interp2d.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_interp2d.h",
"max_line_length": 200,
"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/gsl/gsl_interp2d.h",
"max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z",
"num_tokens": 2085,
"size": 9753
} |
// PMILOS v2.0 (2020)
// Parallel Milne-Eddington inversion code
// (based on IDL code by D. Orozco & J.C. del Toro Iniesta)
// Authors: Manuel Cabrera, Juan P. Cobos, Luis Bellot Rubio (IAA-CSIC)
// Send questions and comments to Luis Bellot, lbellot@iaa.es
#include "mpi.h"
#include <time.h>
#include "defines.h"
#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include "/opt/local/cfitsio/cfitsio-3.350/include/fitsio.h" ///opt/local/cfitsio/cfitsio-3.350/include/
#include "utilsFits.h"
#include "readConfig.h"
#include "lib.h"
#include "milosUtils.h"
#include <unistd.h>
#include <complex.h>
#include <fftw3.h> //always after complex.h
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#include <libgen.h>
// ***************************** FUNCTIONS TO READ FITS FILE *********************************************************
int NTERMS=11;
Cuantic *cuantic; // Global variable with cuantic information
REAL *dtaux, *etai_gp3, *ext1, *ext2, *ext3, *ext4;
REAL *gp1, *gp2, *dt, *dti, *gp3, *gp4, *gp5, *gp6, *etai_2;
REAL *gp4_gp2_rhoq, *gp5_gp2_rhou, *gp6_gp2_rhov;
REAL *dgp1, *dgp2, *dgp3, *dgp4, *dgp5, *dgp6, *d_dt;
REAL *d_ei, *d_eq, *d_eu, *d_ev, *d_rq, *d_ru, *d_rv;
REAL *dfi, *dshi;
REAL CC, CC_2, sin_gm, azi_2, sinis, cosis, cosis_2, cosi, sina, cosa, sinda, cosda, sindi, cosdi, sinis_cosa, sinis_sina;
REAL *fi_p, *fi_b, *fi_r, *shi_p, *shi_b, *shi_r;
REAL *etain, *etaqn, *etaun, *etavn, *rhoqn, *rhoun, *rhovn;
REAL *etai, *etaq, *etau, *etav, *rhoq, *rhou, *rhov;
REAL *parcial1, *parcial2, *parcial3;
REAL *nubB, *nupB, *nurB;
REAL **uuGlobalInicial;
REAL **HGlobalInicial;
REAL **FGlobalInicial;
PRECISION *GMAC,*GMAC_DERIV, *G; // GAUSSIAN MUST BE IN DOUBLE PRECISION
PRECISION *dirConvPar; // AUX GLOBAL VECTOR for calculate direct convolutions
REAL *resultConv; // aux global vector for store direct convolution
REAL * opa;
int FGlobal, HGlobal, uuGlobal;
REAL *d_spectra, *spectra, *spectra_mac, *spectra_slight;
// GLOBAL variables for FFT calculation
fftw_complex * inSpectraFwPSF, *inSpectraBwPSF, *outSpectraFwPSF, *outSpectraBwPSF;
fftw_complex * inSpectraFwMAC, *inSpectraBwMAC, *outSpectraFwMAC, *outSpectraBwMAC;
fftw_plan planForwardPSF, planBackwardPSF;
fftw_plan planForwardMAC, planBackwardMAC;
fftw_complex * inFilterMAC, * inFilterMAC_DERIV, * outFilterMAC, * outFilterMAC_DERIV;
fftw_plan planFilterMAC, planFilterMAC_DERIV;
fftw_complex * fftw_G_PSF;
fftw_complex * fftw_G_PSF, * fftw_G_MAC_PSF, * fftw_G_MAC_DERIV_PSF;
fftw_complex * inPSF_MAC, * inMulMacPSF, * inPSF_MAC_DERIV, *inMulMacPSFDeriv, *outConvFilters, * outConvFiltersDeriv;
fftw_plan planForwardPSF_MAC, planForwardPSF_MAC_DERIV,planBackwardPSF_MAC, planBackwardPSF_MAC_DERIV;
//Convolutions values
int sizeG = 0;
PRECISION FWHM = 0;
ConfigControl configCrontrolFile;
_Complex double *z,* zden, * zdiv;
gsl_vector *eval;
gsl_matrix *evec;
gsl_eigen_symmv_workspace * workspace;
int main(int argc, char **argv)
{
int i; // indexes
int indexLine, free_params; // index to identify central line to read it
PRECISION initialLambda, step, finalLambda;
// INIT MPI PROGRAM
int numProcs, idProc;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numProcs);
MPI_Comm_rank(MPI_COMM_WORLD, &idProc);
/** DEFINE MPI TYPE TO SEND MODELS **/
MPI_Datatype mpiInitModel;
const int nitemsStructInitModel = 11;
int blocklenghtInitModel [11] = {1,1,1,1,1,1,1,1,1,1,1};
MPI_Datatype typesInitModel [11] = {MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE,MPI_DOUBLE};
MPI_Aint offsetsInitModel [11];
offsetsInitModel[0] = offsetof(Init_Model, eta0);
offsetsInitModel[1] = offsetof(Init_Model, B);
offsetsInitModel[2] = offsetof(Init_Model, vlos);
offsetsInitModel[3] = offsetof(Init_Model, dopp);
offsetsInitModel[4] = offsetof(Init_Model, aa);
offsetsInitModel[5] = offsetof(Init_Model, gm);
offsetsInitModel[6] = offsetof(Init_Model, az);
offsetsInitModel[7] = offsetof(Init_Model, S0);
offsetsInitModel[8] = offsetof(Init_Model, S1);
offsetsInitModel[9] = offsetof(Init_Model, mac);
offsetsInitModel[10] = offsetof(Init_Model, alfa);
MPI_Type_create_struct(nitemsStructInitModel, blocklenghtInitModel, offsetsInitModel, typesInitModel, &mpiInitModel);
MPI_Type_commit(&mpiInitModel);
MPI_Datatype mpiName;
const int nItemsStructName = 1;
int blocklenghName [1] = {PATH_MAX};
MPI_Datatype typesName [1] = {MPI_CHAR};
MPI_Aint offsetName [1];
offsetName[0] = offsetof(nameFile,name) ;
MPI_Type_create_struct(nItemsStructName,blocklenghName,offsetName,typesName,&mpiName);
MPI_Type_commit(&mpiName);
/************************************/
const int root=0;
// FINISH STARTING PROGRAM
PRECISION *wlines;
int nlambda, numPixels, indexPixel;
//*****
Init_Model INITIAL_MODEL;
PRECISION * deltaLambda, * PSF;
int N_SAMPLES_PSF;
time_t newestFileTimeInitial; // time for newest file in case invert all directory
// CONFIGURACION DE PARAMETROS A INVERTIR
//---------------------------------------
float * slight = NULL;
int nl_straylight, ns_straylight, nx_straylight=0,ny_straylight=0;
int * vMask = NULL, numRowsMask, numColsMask;
int nRowsMask, nColsMask;
int numberOfFileSpectra;
nameFile * vInputFileSpectra = NULL; // was a space HERE
nameFile * vInputFileSpectraParalell = NULL;
nameFile * vInputFileSpectraDiv2Parallel = NULL;
nameFile * vOutputNameModels = NULL;
nameFile * vOutputNameModelsParalell = NULL;
nameFile * vOutputNameModelsDiv2Parallel = NULL;
nameFile * vOutputNameSynthesisAdjusted = NULL;
nameFile * vOutputNameSynthesisAdjustedParallel = NULL;
nameFile * vOutputNameSynthesisAdjustedDiv2Parallel = NULL;
nameFile * vInputFileSpectraLocal = NULL;
nameFile * vOutputNameModelsLocal = NULL;
nameFile * vOutputNameSynthesisAdjustedLocal = NULL;
tpuntero listFileNamesReaded = NULL;
const char * nameInputFilePSF ;
FitsImage * fitsImage = NULL;
PRECISION dat[7];
double local_start, local_finish, local_elapsed, elapsed;
double local_start_execution, local_finish_execution, local_elapsed_execution, elapsed_execution;
double local_start_scatter, local_finish_scatter, local_elapsed_scatter, elapsed_scatter;
double local_start_gather, local_finish_gather, local_elapsed_gather, elapsed_gather;
Init_Model * resultsInitModel;
Init_Model * resultsInitModelTotal;
float * chisqrfTotal, *vChisqrf;
int * vNumIter, * vNumIterTotal; // to store the number of iterations used to converge for each pixel
float * vSpectraSplit, * vSpectraAdjustedSplit, * vSpectraAjustedTotal;
int sendcountsPixels [numProcs] ; // array describing how many elements to send to each process
int sendcountsSpectro [numProcs];
int sendcountsLambda [numProcs];
int sendcountsNameInputFiles [numProcs]; // how many files per process
int displsPixels [numProcs]; // array describing the displacements where each segment begins
int displsSpectro [numProcs];
int displsNameInputFiles [numProcs]; // how many
/********************* Read data input from file ******************************/
loadInitialValues(&configCrontrolFile);
if(!readInitFile(argv[1],&configCrontrolFile,(idProc==root))){
if(idProc==root)
printf("\n\nERROR READING INIT FILE. \n\n");
exit(EXIT_FAILURE);
}
// check if type of file is FITS, else exit
if(strcmp(configCrontrolFile.typeInputStokes,"fits")!=0){
if(idProc==root)
printf("\nERROR. The profiles must be given in FITS format.\n");
exit(EXIT_FAILURE);
}
// CHECK IF ONLY RECEIVED ONE FILE AND THE EXTENSION IS .FITS
if(!configCrontrolFile.invertDirectory && !configCrontrolFile.loopInversion){
if(configCrontrolFile.t1 == 0 && configCrontrolFile.t2 ==0){ // then process only one file
if(strcmp(file_ext(configCrontrolFile.ObservedProfiles),FITS_FILE)!=0){
if(idProc==root){
printf("\n-----------------------------------------------------------\n");
printf("\nERROR. A FITS file is expected in 'Observed Profiles'\n");
printf("\n-----------------------------------------------------------\n");
}
exit(EXIT_FAILURE);
}
}
}
nameInputFilePSF = configCrontrolFile.PSFFile;
FWHM = configCrontrolFile.FWHM;
/***************** READ INIT MODEL ********************************/
if(!readInitialModel(&INITIAL_MODEL,configCrontrolFile.InitialGuessModel)){
printf("\nERROR READING INITIAL MODEL. STOP \n");
exit(EXIT_FAILURE);
}
checkInitialModel(&INITIAL_MODEL);
if(INITIAL_MODEL.alfa<1 && access(configCrontrolFile.StrayLightFile,F_OK)){
printf("\nERROR. Filling factor is less than 1 and straylight file %s does not exist\n",configCrontrolFile.StrayLightFile);
exit(EXIT_FAILURE);
}
if(configCrontrolFile.fix[10]==0) NTERMS--;
if(INITIAL_MODEL.mac ==0 && configCrontrolFile.fix[9]==0){
NTERMS--;
}
// allocate memory for eigen values
eval = gsl_vector_alloc (NTERMS);
evec = gsl_matrix_alloc (NTERMS, NTERMS);
workspace = gsl_eigen_symmv_alloc (NTERMS);
/***************** READ WAVELENGTH FROM GRID OR FITS ********************************/
PRECISION * vGlobalLambda, *vOffsetsLambda;
if(configCrontrolFile.useMallaGrid){ // read lambda from grid file
if(idProc==root){
printf("------------------------------------------------------------------------------------\n");
printf("\nReading wavelength grid file: %s\n",configCrontrolFile.MallaGrid);
// printf("\n------------------------------------------------------------------------------------");
}
indexLine = readMallaGrid(configCrontrolFile.MallaGrid, &initialLambda, &step, &finalLambda, (idProc==root));
if(idProc==root){
// printf("------------------------------------------------------------------------------------------\n");
}
nlambda = ((finalLambda-initialLambda)/step)+1;
vOffsetsLambda = calloc(nlambda,sizeof(PRECISION));
vOffsetsLambda[0] = initialLambda;
for(i=1;i<nlambda;i++){
vOffsetsLambda[i] = vOffsetsLambda[i-1]+step;
}
// pass to amstrong
initialLambda = initialLambda/1000;
step = step/1000;
finalLambda = finalLambda/1000;
vGlobalLambda = calloc(nlambda,sizeof(PRECISION));
if(idProc==root){
printf("\nNumber of wavelengths in the wavelength grid: %d\n",nlambda);
// printf("\n-------------------------------------------------------------------------------\n");
printf("\nReading atomic parameter files: %s\n",configCrontrolFile.AtomicParametersFile);
}
configCrontrolFile.CentralWaveLenght = readFileCuanticLines(configCrontrolFile.AtomicParametersFile,dat,indexLine,(idProc==root));
if(configCrontrolFile.CentralWaveLenght==0){
printf("\n SPECTRAL LINE NOT FOUND, CHECK THE ATOMIC PARAMETERS FILE. ");
printf("\n INPUT CENTRAL WAVELENGTH: %f",configCrontrolFile.CentralWaveLenght);
exit(1);
}
vGlobalLambda[0]=configCrontrolFile.CentralWaveLenght+(initialLambda);
for(i=1;i<nlambda;i++){
vGlobalLambda[i]=vGlobalLambda[i-1]+step;
}
}
else{
if(idProc==root){
printf("------------------------------------------------------------------------------------\n");
printf("\nReading wavelength file: %s\n",configCrontrolFile.WavelengthFile);
}
vGlobalLambda = readFitsLambdaToArray(configCrontrolFile.WavelengthFile,&indexLine,&nlambda);
if(vGlobalLambda==NULL){
printf("\n WAVELENGTH FILE WAS NOT READ PROPERLY, please check it.\n");
free(vGlobalLambda);
exit(EXIT_FAILURE);
}
if(idProc==root){
printf("\nNumber of wavelengths in the wavelength file: %d\n",nlambda);
//printf("\n-------------------------------------------------------------------------------\n");
//printf("\n-------------------------------------------------------------------------------");
printf("\nReading atomic parameter file: %s\n",configCrontrolFile.AtomicParametersFile);
}
configCrontrolFile.CentralWaveLenght = readFileCuanticLines(configCrontrolFile.AtomicParametersFile,dat,indexLine,(idProc==root));
if(configCrontrolFile.CentralWaveLenght==0){
printf("\n SPECTRAL LINE NOT FOUND, CHECK ATOMIC PARAMETER FILE. INPUT CENTRAL WAVELENGTH: %f",configCrontrolFile.CentralWaveLenght);
exit(1);
}
}
MPI_Barrier(MPI_COMM_WORLD);
/*********************************************** INITIALIZE VARIABLES *********************************/
REAL * vSigma = malloc((nlambda*NPARMS)*sizeof(REAL));
for(i=0;i<nlambda*NPARMS;i++){
vSigma[i] = configCrontrolFile.noise;
}
CC = PI / 180.0;
CC_2 = CC * 2;
wlines = (PRECISION *)calloc(2, sizeof(PRECISION));
wlines[0] = 1;
wlines[1] = configCrontrolFile.CentralWaveLenght;
numPixels=0;
printf(configCrontrolFile.StrayLightFile);
/******************* APPLY GAUSSIAN, CREATE CUANTINC AND INITIALIZE DINAMYC MEMORY*******************/
MPI_Barrier(MPI_COMM_WORLD);
cuantic = create_cuantic(dat,(idProc==root));
MPI_Barrier(MPI_COMM_WORLD);
/**************************************** READ FITS STRAY LIGHT ******************************/
if( configCrontrolFile.fix[10] && access(configCrontrolFile.StrayLightFile,F_OK)!=-1){ // IF NOT EMPTY READ stray light file
if(strcmp(file_ext(configCrontrolFile.StrayLightFile),PER_FILE)==0){
slight = readPerStrayLightFile(configCrontrolFile.StrayLightFile,nlambda,vOffsetsLambda);
nl_straylight = nlambda;
}
else if(strcmp(file_ext(configCrontrolFile.StrayLightFile),FITS_FILE)==0){
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
slight= readFitsStrayLightFileSubSet(&configCrontrolFile,&nl_straylight,&ns_straylight,&nx_straylight, &ny_straylight);
}
else{
slight= readFitsStrayLightFile(&configCrontrolFile,&nl_straylight,&ns_straylight,&nx_straylight, &ny_straylight);
}
}
}
/**************************************** READ FITS MASK ******************************/
int shareVMask = 0;
if(idProc==root && access(configCrontrolFile.MaskFile,F_OK)!=-1){ // IF NOT EMPTY READ MASK FILE
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
vMask=readFitsMaskFileSubSet (configCrontrolFile.MaskFile,&numRowsMask,&numColsMask,&configCrontrolFile);
}
else{
vMask=readFitsMaskFile (configCrontrolFile.MaskFile,&numRowsMask,&numColsMask);
}
if(vMask==NULL){
printf("\n-----------------------------------------------------------------------");
printf("\nMask file not found or incorrect dimensions. Mask will not be used. ");
printf("\n---------------------------------------------------------------------\n");
}
else{
// readsub set of VMAS
shareVMask =1;
}
}
MPI_Barrier(MPI_COMM_WORLD); // Wait UNTIL THE IMAGE HAS BEEN READED COMPLETELY
// BROADCAST THE NUMBER OF LAMBDAS READS FROM THE FILE AND THE NUMBER OF PIXELS
MPI_Bcast(&numRowsMask, 1, MPI_INT, root , MPI_COMM_WORLD);
MPI_Bcast(&numColsMask, 1, MPI_INT, root , MPI_COMM_WORLD);
MPI_Bcast(&shareVMask, 1, MPI_INT, root , MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
if(shareVMask){
if(idProc!=root)
vMask = calloc(numRowsMask*numColsMask,sizeof(int));
MPI_Barrier(MPI_COMM_WORLD);
MPI_Bcast(vMask, numRowsMask*numColsMask, MPI_INT, root , MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
}
if(idProc==root){
free_params=0;
for(i=0;i<11;i++){
if(configCrontrolFile.fix[i])
free_params++;
}
}
// ************************** DEFINE PLANS TO EXECUTE MACROTURBULENCE IF NECESSARY **********************************************//
// MACROTURBULENCE PLANS
inFilterMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
outFilterMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
planFilterMAC = fftw_plan_dft_1d(nlambda, inFilterMAC, outFilterMAC, FFT_FORWARD, FFTW_MEASURE );
inFilterMAC_DERIV = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
outFilterMAC_DERIV = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
planFilterMAC_DERIV = fftw_plan_dft_1d(nlambda, inFilterMAC_DERIV, outFilterMAC_DERIV, FFT_FORWARD, FFTW_MEASURE );
inSpectraFwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
outSpectraFwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
planForwardMAC = fftw_plan_dft_1d(nlambda, inSpectraFwMAC, outSpectraFwMAC, FFT_FORWARD, FFTW_MEASURE );
inSpectraBwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
outSpectraBwMAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
planBackwardMAC = fftw_plan_dft_1d(nlambda, inSpectraBwMAC, outSpectraBwMAC, FFT_BACKWARD, FFTW_MEASURE );
// ******************************* IF PSF HAS BEEN SPECIFIED IN CONTROL FILE, READ PSF FILE OR CREATE GAUSSIAN FILTER ***********//
if(configCrontrolFile.ConvolveWithPSF){
if(configCrontrolFile.FWHM > 0){
G = fgauss_WL(FWHM,vGlobalLambda[1]-vGlobalLambda[0],vGlobalLambda[0],vGlobalLambda[nlambda/2],nlambda,&sizeG);
//char nameAux [4096];
//char obsAux [4096];
//if(configCrontrolFile.ObservedProfiles[0]!='\0'){
// strcpy(obsAux,configCrontrolFile.ObservedProfiles);
// strcpy(nameAux,dirname(obsAux));
//}
//else{
// strcpy(obsAux,configCrontrolFile.InitialGuessModel);
// strcpy(nameAux,dirname(obsAux));
//}
//strcat(nameAux,"/gaussian.psf");
//FILE *fptr = fopen(nameAux, "w");
if(idProc==root){
printf("\nGaussian PSF will be saved to file gaussian.psf \n");
FILE *fptr = fopen("gaussian.psf", "w");
if(fptr!=NULL){
int kk;
for (kk = 0; kk < nlambda; kk++)
{
fprintf(fptr,"\t%f\t%e\n", (vGlobalLambda[kk]-configCrontrolFile.CentralWaveLenght)*1000, G[kk]);
}
fclose(fptr);
}
else{
// printf("\nERROR !!! The output PSF file cannot be opened: %s",nameAux);
printf("\nERROR !!! The output PSF file cannot be opened: gaussian.psf");
}
}
}
else if(access(nameInputFilePSF,F_OK) != -1){
// read the number of lines
FILE *fp;
char ch;
N_SAMPLES_PSF=0;
//open file in read more
fp=fopen(nameInputFilePSF,"r");
if(fp==NULL)
{
printf("\n-------------------------------------------------------------------------------");
printf("PSF File \"%s\" does not exist!",nameInputFilePSF);
printf("\n-------------------------------------------------------------------------------");
return 0;
}
//read character by character and check for new line
while((ch=fgetc(fp))!=EOF)
{
if(ch=='\n')
N_SAMPLES_PSF++;
}
//close the file
fclose(fp);
if(N_SAMPLES_PSF>0){
deltaLambda = calloc(N_SAMPLES_PSF,sizeof(PRECISION));
PSF = calloc(N_SAMPLES_PSF,sizeof(PRECISION));
readPSFFile(deltaLambda,PSF,nameInputFilePSF,configCrontrolFile.CentralWaveLenght);
// CHECK if values of deltaLambda are in the same range of vLambda. To do that we truncate to 4 decimal places
if( (trunc(vOffsetsLambda[0])) < (trunc(deltaLambda[0])) || (trunc(vOffsetsLambda[nlambda-1])) > (trunc(deltaLambda[N_SAMPLES_PSF-1])) ){
if(idProc==root){
printf("\n\n ERROR: The wavelength range in the PSF file is smaller than the range in the grid file [%lf,%lf] [%lf,%lf] \n\n",deltaLambda[0],vOffsetsLambda[0],deltaLambda[N_SAMPLES_PSF-1],vOffsetsLambda[nlambda-1]);
}
exit(EXIT_FAILURE);
}
G = calloc(nlambda,sizeof(PRECISION));
double offset =0;
int posWL = 0;
for(i=0;i<nlambda && !posWL;i++){
if( fabs(trunc(vOffsetsLambda[i]))==0)
posWL = i;
}
if(posWL!= (nlambda/2)){ // move center to the middle of samples
offset = (((nlambda/2)-posWL)*step)*1000;
}
interpolationLinearPSF(deltaLambda, PSF, vOffsetsLambda , N_SAMPLES_PSF, G, nlambda,offset);
sizeG=nlambda;
}
else{
if(idProc==root)
printf("\n************** ERROR. THE PSF FILE is empty or damaged**************\n");
exit(EXIT_FAILURE);
}
if(idProc==root){
// printf("\n-------------------------------------------------------------------------------");
printf("\nPSF file read: %s\n", nameInputFilePSF);
// printf("\n-------------------------------------------------------------------------------\n");
}
}
//PSF FILTER PLANS
inSpectraFwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
outSpectraFwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
planForwardPSF = fftw_plan_dft_1d(nlambda, inSpectraFwPSF, outSpectraFwPSF, FFT_FORWARD, FFTW_MEASURE );
inSpectraBwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
outSpectraBwPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
planBackwardPSF = fftw_plan_dft_1d(nlambda, inSpectraBwPSF, outSpectraBwPSF, FFT_BACKWARD, FFTW_MEASURE );
fftw_complex * in = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nlambda);
int i;
for (i = 0; i < nlambda; i++)
{
in[i] = G[i] + 0 * _Complex_I;
}
fftw_G_PSF = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nlambda);
fftw_plan p = fftw_plan_dft_1d(nlambda, in, fftw_G_PSF, FFT_FORWARD, FFTW_MEASURE );
fftw_execute(p);
for (i = 0; i < nlambda; i++)
{
fftw_G_PSF[i] = fftw_G_PSF[i] / nlambda;
}
fftw_destroy_plan(p);
fftw_free(in);
inPSF_MAC = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
fftw_G_MAC_PSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
planForwardPSF_MAC = fftw_plan_dft_1d(nlambda, inPSF_MAC, fftw_G_MAC_PSF, FFT_FORWARD, FFTW_MEASURE );
inMulMacPSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
outConvFilters = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
planBackwardPSF_MAC = fftw_plan_dft_1d(nlambda, inMulMacPSF, outConvFilters, FFT_BACKWARD, FFTW_MEASURE );
inPSF_MAC_DERIV = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
fftw_G_MAC_DERIV_PSF = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
planForwardPSF_MAC_DERIV = fftw_plan_dft_1d(nlambda, inPSF_MAC_DERIV, fftw_G_MAC_DERIV_PSF, FFT_FORWARD, FFTW_MEASURE );
inMulMacPSFDeriv = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
outConvFiltersDeriv = (fftw_complex *) fftw_malloc(sizeof(fftw_complex) * nlambda);
planBackwardPSF_MAC_DERIV = fftw_plan_dft_1d(nlambda, inMulMacPSFDeriv, outConvFiltersDeriv, FFT_BACKWARD, FFTW_MEASURE );
}
/*****************************************************************************************************/
MPI_Barrier(MPI_COMM_WORLD);
// ROOT PROCESS READ IMAGE FROM FILE TO KNOW LIST OF FILES
if(idProc==root){
char auxObservedProfiles1 [256];
char auxObservedProfiles2 [256];
strcpy(auxObservedProfiles1,configCrontrolFile.ObservedProfiles);
strcpy(auxObservedProfiles2,configCrontrolFile.ObservedProfiles);
char * dirNameObservedProfiles = dirname(auxObservedProfiles1);
char * fileNameObservedProfiles = basename(auxObservedProfiles2);
char newObservedProfiles [256];
if(configCrontrolFile.outputPrefix[0]!='\0'){
strcpy(newObservedProfiles,configCrontrolFile.outputPrefix);
strcat(newObservedProfiles,fileNameObservedProfiles);
}
else{
strcpy(newObservedProfiles,fileNameObservedProfiles);
}
/*if(strcmp(dirNameObservedProfiles,".")!=0){
strcpy(newObservedProfiles,dirNameObservedProfiles);
strcat(newObservedProfiles,"/");
if(configCrontrolFile.outputPrefix[0]!='\0')
strcat(newObservedProfiles,configCrontrolFile.outputPrefix);
strcat(newObservedProfiles,fileNameObservedProfiles);
}
else{
if(configCrontrolFile.outputPrefix[0]!='\0'){
strcpy(newObservedProfiles,configCrontrolFile.outputPrefix);
strcat(newObservedProfiles,fileNameObservedProfiles);
}
else{
strcpy(newObservedProfiles,fileNameObservedProfiles);
}
}*/
if(configCrontrolFile.loopInversion){
if(configCrontrolFile.invertDirectory){ // read all directory
struct dirent **namelist;
char observedProAux[256];
char observedProAux2[256];
strcpy(observedProAux,configCrontrolFile.ObservedProfiles);
strcpy(observedProAux2,configCrontrolFile.ObservedProfiles);
char * dname = dirname(observedProAux);
char * bname = basename(observedProAux2);
int numFileDirectory = scandir(dname, &namelist, 0, alphasort);
if (numFileDirectory < 0)
perror("scandir");
else{
if(numFileDirectory>2){
numberOfFileSpectra=0;
for(i=0;i<numFileDirectory;i++){
char auxPathName[256];
strcpy(auxPathName,dname);
strcat(auxPathName,"/");
strcat(auxPathName,namelist[i]->d_name);
if(!isDirectory(auxPathName) && strcmp(namelist[i]->d_name,".")!=0 && strcmp(namelist[i]->d_name,"..")!=0 && strcmp(namelist[i]->d_name,"_mod")!=0){
numberOfFileSpectra++;
}
}
vInputFileSpectra = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));
vOutputNameModels = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));
vOutputNameSynthesisAdjusted = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));
int numberFiles[numberOfFileSpectra];
int indexNumberFiles = 0;
for(i=0;i<numFileDirectory;i++){
char auxPathName[256];
strcpy(auxPathName,dname);
strcat(auxPathName,"/");
strcat(auxPathName,namelist[i]->d_name);
if(!isDirectory(auxPathName) && strcmp(namelist[i]->d_name,".")!=0 && strcmp(namelist[i]->d_name,"..")!=0 && strcmp(namelist[i]->d_name,"_mod")!=0){
char pathAux [256];
strcpy(pathAux,dname);
strcat(pathAux,"/");
strcat(pathAux,namelist[i]->d_name);
char * subString = strstr(pathAux,configCrontrolFile.ObservedProfiles);
if(subString!=NULL){
char numChar [80];
mySubString(get_basefilename(namelist[i]->d_name),strlen(bname),strlen(get_basefilename(namelist[i]->d_name))-strlen(bname),numChar);
int numAux = atoi(numChar);
numberFiles[indexNumberFiles++] = numAux;
}
}
}
for(i=0;i<numberOfFileSpectra;i++){
char strIndex[5];
if(numberFiles[i]>=0 && numberFiles[i]<10)
sprintf(strIndex, "00%d", numberFiles[i]);
else if(numberFiles[i]>=10 && numberFiles[i]<100){
sprintf(strIndex, "0%d", numberFiles[i]);
}
else{
sprintf(strIndex, "%d", numberFiles[i]);
}
strcpy(vInputFileSpectra[i].name, configCrontrolFile.ObservedProfiles);
strcat(vInputFileSpectra[i].name, strIndex);
strcat(vInputFileSpectra[i].name, FITS_FILE);
// FILE NAME FOR OUTPUT MODELS
//strcpy(vOutputNameModels[i].name, configCrontrolFile.ObservedProfiles);
strcpy(vOutputNameModels[i].name,newObservedProfiles);
strcat(vOutputNameModels[i].name, strIndex);
strcat(vOutputNameModels[i].name, "_mod");
// if(configCrontrolFile.outputPrefix[0]!='\0'){
// strcat(vOutputNameModels[i].name, "_");
// strcat(vOutputNameModels[i].name, configCrontrolFile.outputPrefix);
// }
strcat(vOutputNameModels[i].name,FITS_FILE);
// FILE NAME FOR ADJUSTED SYNTHESIS
//strcpy(vOutputNameSynthesisAdjusted[i].name, configCrontrolFile.ObservedProfiles);
strcpy(vOutputNameSynthesisAdjusted[i].name,newObservedProfiles);
strcat(vOutputNameSynthesisAdjusted[i].name, strIndex);
strcat(vOutputNameSynthesisAdjusted[i].name, "_stokes");
/*if(configCrontrolFile.outputPrefix[0]!='\0'){
strcat(vOutputNameSynthesisAdjusted[i].name, "_");
strcat(vOutputNameSynthesisAdjusted[i].name, configCrontrolFile.outputPrefix);
}*/
strcat(vOutputNameSynthesisAdjusted[i].name,FITS_FILE);
}
}
}
}
else{ // read directory from number in t1
struct dirent **namelist;
char observedProAux[256];
char observedProAux2[256];
strcpy(observedProAux,configCrontrolFile.ObservedProfiles);
strcpy(observedProAux2,configCrontrolFile.ObservedProfiles);
char * dname = dirname(observedProAux);
char * bname = basename(observedProAux2);
int numFileDirectory = scandir(dname, &namelist, 0, alphasort);
if (numFileDirectory < 0){
perror("scandir");
exit(1);
}
int maxNumber = -1;
for(i=2;i<numFileDirectory;i++){
if(strcmp(namelist[i]->d_name,".")!=0 && strcmp(namelist[i]->d_name,"..")!=0){
char pathAux [256];
strcpy(pathAux,dname);
strcat(pathAux,"/");
strcat(pathAux,namelist[i]->d_name);
if(!isDirectory(pathAux)){
char * subString = strstr(pathAux,configCrontrolFile.ObservedProfiles);
if(subString!=NULL){
char numChar [80];
mySubString(get_basefilename(namelist[i]->d_name),strlen(bname),strlen(get_basefilename(namelist[i]->d_name))-strlen(bname),numChar);
int numAux = atoi(numChar);
if(numAux>maxNumber)
maxNumber = numAux;
}
}
}
}
if((maxNumber-configCrontrolFile.t1)+1>0){
numberOfFileSpectra = (maxNumber - configCrontrolFile.t1)+1;
vInputFileSpectra = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));
vOutputNameModels = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));
vOutputNameSynthesisAdjusted = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));
int indexName =0;
for(i=configCrontrolFile.t1;i<=maxNumber;i++){
char strIndex[5];
if(i>=0 && i<10){
sprintf(strIndex, "00%d", i);
}
else if(i>=10 && i<100){
sprintf(strIndex, "0%d", i);
}
else
sprintf(strIndex, "%d", i);
strcpy(vInputFileSpectra[indexName].name, configCrontrolFile.ObservedProfiles);
strcat(vInputFileSpectra[indexName].name, strIndex);
strcat(vInputFileSpectra[indexName].name, FITS_FILE);
// FILE NAME FOR OUTPUT MODELS
//strcpy(vOutputNameModels[indexName].name, configCrontrolFile.ObservedProfiles);
printf("%s\n", newObservedProfiles);
printf("%s\n", "line 738");
strcpy(vOutputNameModels[indexName].name,newObservedProfiles);
strcat(vOutputNameModels[indexName].name, strIndex);
strcat(vOutputNameModels[indexName].name, "_mod");
/*if(configCrontrolFile.outputPrefix[0]!='\0'){
strcat(vOutputNameModels[indexName].name, "_");
strcat(vOutputNameModels[indexName].name, configCrontrolFile.outputPrefix);
}*/
strcat(vOutputNameModels[indexName].name,FITS_FILE);
// FILE NAME FOR ADJUSTED SYNTHESIS
//strcpy(vOutputNameSynthesisAdjusted[indexName].name, configCrontrolFile.ObservedProfiles);
strcpy(vOutputNameSynthesisAdjusted[indexName].name, newObservedProfiles);
strcat(vOutputNameSynthesisAdjusted[indexName].name, strIndex);
strcat(vOutputNameSynthesisAdjusted[indexName].name, "_stokes");
/*if(configCrontrolFile.outputPrefix[0]!='\0'){
strcat(vOutputNameSynthesisAdjusted[indexName].name, "_");
strcat(vOutputNameSynthesisAdjusted[indexName].name, configCrontrolFile.outputPrefix);
}*/
strcat(vOutputNameSynthesisAdjusted[indexName].name,FITS_FILE);
indexName++;
}
}
}
for(i=0;i<numberOfFileSpectra;i++){
insert_in_linked_list(&listFileNamesReaded,vInputFileSpectra[i].name);
}
}
else{
// CHECK IF INPUT OBSERVED PROFILES COMES IN A DIRECTORY OR IS A FILE
if(configCrontrolFile.t1 == 0 && configCrontrolFile.t2 ==0){ // then process only one file
numberOfFileSpectra = 1;
vInputFileSpectra = (nameFile *)malloc(numberOfFileSpectra*sizeof(nameFile));
strcpy(vInputFileSpectra[0].name,configCrontrolFile.ObservedProfiles);
printf("%s\n", vInputFileSpectra[0].name);
vOutputNameModels = (nameFile *)malloc(numberOfFileSpectra*sizeof(nameFile));
if(configCrontrolFile.outputPrefix[0]!='\0'){
strcpy(vOutputNameModels[0].name,configCrontrolFile.outputPrefix);
get_basefilename_nofolder(configCrontrolFile.ObservedProfiles);
//strcat(vOutputNameModels[0].name,get_basefilename_nofolder(configCrontrolFile.ObservedProfiles)); // was initialguessmodel here
strcat(vOutputNameModels[0].name,MOD_FITS);
}
else {
strcpy(vOutputNameModels[0].name,get_basefilename(configCrontrolFile.InitialGuessModel)); // was initialguessmodel here
strcat(vOutputNameModels[0].name,MOD_FITS);
}
vOutputNameSynthesisAdjusted = (nameFile *)malloc(numberOfFileSpectra*sizeof(nameFile));
strcpy(vOutputNameSynthesisAdjusted[0].name,get_basefilename(configCrontrolFile.ObservedProfiles));
strcat(vOutputNameSynthesisAdjusted[0].name,STOKES_FIT_EXT);
}
else
{
numberOfFileSpectra = (configCrontrolFile.t2 - configCrontrolFile.t1)+1;
vInputFileSpectra = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));
vOutputNameModels = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));
vOutputNameSynthesisAdjusted = (nameFile *) malloc(numberOfFileSpectra*sizeof(nameFile));
int indexName = 0;
for(i=configCrontrolFile.t1;i<=configCrontrolFile.t2;i++){
char strIndex[5];
if(i>=0 && i<10){
sprintf(strIndex, "00%d", i);
}
else if(i>=10 && i<100){
sprintf(strIndex, "0%d", i);
}
else
sprintf(strIndex, "%d", i);
// FILE NAMES FOR INPUT IMAGES
strcpy(vInputFileSpectra[indexName].name, configCrontrolFile.ObservedProfiles);
strcat(vInputFileSpectra[indexName].name,strIndex);
strcat(vInputFileSpectra[indexName].name,FITS_FILE);
// FILE NAME FOR OUTPUT MODELS
//strcpy(vOutputNameModels[indexName].name, configCrontrolFile.ObservedProfiles);
printf("%s\n", "line 809");
strcpy(vOutputNameModels[indexName].name, newObservedProfiles);
strcat(vOutputNameModels[indexName].name, strIndex);
strcat(vOutputNameModels[indexName].name, "_mod");
/*if(configCrontrolFile.outputPrefix[0]!='\0'){
strcat(vOutputNameModels[indexName].name, "_");
strcat(vOutputNameModels[indexName].name, configCrontrolFile.outputPrefix);
}*/
strcat(vOutputNameModels[indexName].name,FITS_FILE);
// FILE NAME FOR ADJUSTED SYNTHESIS
//strcpy(vOutputNameSynthesisAdjusted[indexName].name, configCrontrolFile.ObservedProfiles);
strcpy(vOutputNameSynthesisAdjusted[indexName].name, newObservedProfiles);
strcat(vOutputNameSynthesisAdjusted[indexName].name, strIndex);
strcat(vOutputNameSynthesisAdjusted[indexName].name, "_stokes");
/*if(configCrontrolFile.outputPrefix[0]!='\0'){
strcat(vOutputNameSynthesisAdjusted[indexName].name, "_");
strcat(vOutputNameSynthesisAdjusted[indexName].name, configCrontrolFile.outputPrefix);
}*/
strcat(vOutputNameSynthesisAdjusted[indexName].name,FITS_FILE);
indexName++;
}
}
}
}
MPI_Barrier(MPI_COMM_WORLD); // Wait UNTIL THE IMAGE HAS BEEN READED COMPLETELY
// BROADCAST THE NUMBER OF LAMBDAS READS FROM THE FILE AND THE NUMBER OF PIXELS
MPI_Bcast(&numberOfFileSpectra, 1, MPI_INT, root , MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
/**
* What we do know is the following:
* --- If the number of files is greater than number of available processors , then scatter the list of files proporcionaly between N processores.
* --- If the number of files is less than number of available processors, then we process each fits file sequentially doing a scatter of N pixels in the each Fits File.
* */
int numFilesPerProcess = numberOfFileSpectra / numProcs;
int numFilesPerProcessParallel = numberOfFileSpectra % numProcs;
int numFilesPer2ProcessParallel=0;
if(numFilesPerProcessParallel>=(numProcs/2)){ // DIVIDE EACH FILE IN TWO PROCESS
numFilesPer2ProcessParallel = numProcs/2;
numFilesPerProcessParallel = numFilesPerProcessParallel - (numProcs/2);
}
else
{
numFilesPer2ProcessParallel = 0;
}
int sum = 0; // Sum of counts. Used to calculate displacements
for ( i = 0; i < numProcs; i++) {
sendcountsNameInputFiles[i] = numFilesPerProcess;
displsNameInputFiles[i] = sum;
sum += sendcountsNameInputFiles[i];
}
//**************************************** CREATE GROUPS FOR DIVIDE IMAGE IN 2 ********************************************/
MPI_Group world_group;
MPI_Comm_group(MPI_COMM_WORLD, &world_group);
int numGroups = numProcs/2;
MPI_Group vGroups [numGroups]; // will contain the numbers of process of each group
if(numProcs%2 ==0){
for(i=0;i<numProcs;i=i+2){
int ranks[2];
ranks[0] = i;
ranks[1] = i+1;
MPI_Group_incl(world_group, 2, ranks, &vGroups[i/2]);
}
}
else{
int indProc=0;
for(i=0;i<numGroups;i++){
if(i==(numGroups-1)){ // add resto
int ranks[3];
ranks[0]=indProc++;
ranks[1]=indProc++;
ranks[2]=indProc++;
MPI_Group_incl(world_group, 3, ranks, &vGroups[i]);
}
else{
int ranks[2];
ranks[0]=indProc++;
ranks[1]=indProc++;
MPI_Group_incl(world_group, 2, ranks, &vGroups[i]);
}
}
}
// Create the new communicator from that group of processes.
MPI_Comm vCommunicators[numGroups];
for(i=0;i<numGroups;i++){
MPI_Comm_create(MPI_COMM_WORLD, vGroups[i], &vCommunicators[i]);
}
MPI_Barrier(MPI_COMM_WORLD);
int myGroup = idProc/2;
if(myGroup==numGroups)
myGroup = myGroup-1;
int myGroupRank;
int groupRoot = 0; // process 0 of group will be the root
int myGroupSize;
if(numGroups>0){
MPI_Group_rank(vGroups[myGroup], &myGroupRank);
MPI_Group_size(vGroups[myGroup], &myGroupSize);
}
MPI_Barrier(MPI_COMM_WORLD);
//**************************************** END OF CREATE GROUPS FOR DIVIDE IMAGE IN 2 ********************************************/
if(idProc == root){
if(numFilesPerProcess>=1){
vInputFileSpectraDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));
vOutputNameModelsDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));
vOutputNameSynthesisAdjustedDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));
for(i=0;i<numFilesPer2ProcessParallel;i++){
strcpy(vInputFileSpectraDiv2Parallel[i].name,vInputFileSpectra[(numFilesPerProcess*numProcs)+i].name);
strcpy(vOutputNameModelsDiv2Parallel[i].name,vOutputNameModels[(numFilesPerProcess*numProcs)+i].name);
strcpy(vOutputNameSynthesisAdjustedDiv2Parallel[i].name,vOutputNameSynthesisAdjusted[(numFilesPerProcess*numProcs)+i].name);
}
if(numFilesPerProcessParallel>0){
vInputFileSpectraParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));
vOutputNameModelsParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));
vOutputNameSynthesisAdjustedParallel = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));
for(i=0;i<numFilesPerProcessParallel;i++){
strcpy(vInputFileSpectraParalell[i].name,vInputFileSpectra[(numFilesPerProcess*numProcs)+numFilesPer2ProcessParallel+i].name);
strcpy(vOutputNameModelsParalell[i].name,vOutputNameModels[(numFilesPerProcess*numProcs)+numFilesPer2ProcessParallel+i].name);
strcpy(vOutputNameSynthesisAdjustedParallel[i].name,vOutputNameSynthesisAdjusted[(numFilesPerProcess*numProcs)+numFilesPer2ProcessParallel+i].name);
}
}
nameFile * auxInput = (nameFile *)malloc((numFilesPerProcess*numProcs)*sizeof(nameFile));
nameFile * auxOutput = (nameFile *)malloc((numFilesPerProcess*numProcs)*sizeof(nameFile));
nameFile * auxOutputSynthesisAdjusted = (nameFile *)malloc((numFilesPerProcess*numProcs)*sizeof(nameFile));
for(i=0;i<(numFilesPerProcess*numProcs);i++){
strcpy(auxInput[i].name,vInputFileSpectra[i].name);
strcpy(auxOutput[i].name,vOutputNameModels[i].name);
strcpy(auxOutputSynthesisAdjusted[i].name,vOutputNameSynthesisAdjusted[i].name);
}
free(vInputFileSpectra);
free(vOutputNameModels);
free(vOutputNameSynthesisAdjusted);
vInputFileSpectra = auxInput;
vOutputNameModels = auxOutput;
vOutputNameSynthesisAdjusted = auxOutputSynthesisAdjusted;
}
else{
if(vInputFileSpectraDiv2Parallel!=NULL)
free(vInputFileSpectraDiv2Parallel);
if(vOutputNameModelsDiv2Parallel!=NULL)
free(vOutputNameModelsDiv2Parallel);
if(vOutputNameSynthesisAdjustedDiv2Parallel!=NULL)
free(vOutputNameSynthesisAdjustedDiv2Parallel);
if(vInputFileSpectraParalell!=NULL)
free(vInputFileSpectraParalell);
if(vOutputNameModelsParalell!=NULL)
free(vOutputNameModelsParalell);
if(vOutputNameSynthesisAdjustedParallel!=NULL)
free(vOutputNameSynthesisAdjustedParallel);
if(numFilesPer2ProcessParallel>0){
vInputFileSpectraDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));
vOutputNameModelsDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));
vOutputNameSynthesisAdjustedDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));
for(i=0;i<numFilesPer2ProcessParallel;i++){
strcpy(vInputFileSpectraDiv2Parallel[i].name,vInputFileSpectra[i].name);
strcpy(vOutputNameModelsDiv2Parallel[i].name,vOutputNameModels[i].name);
strcpy(vOutputNameSynthesisAdjustedDiv2Parallel[i].name,vOutputNameSynthesisAdjusted[i].name);
}
}
vInputFileSpectraParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));
vOutputNameModelsParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));
vOutputNameSynthesisAdjustedParallel = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));
for(i=0;i<numFilesPerProcessParallel;i++){
strcpy(vInputFileSpectraParalell[i].name,vInputFileSpectra[numFilesPer2ProcessParallel+i].name);
strcpy(vOutputNameModelsParalell[i].name,vOutputNameModels[numFilesPer2ProcessParallel+i].name);
strcpy(vOutputNameSynthesisAdjustedParallel[i].name,vOutputNameSynthesisAdjusted[numFilesPer2ProcessParallel+i].name);
}
free(vInputFileSpectra);
vInputFileSpectra = NULL;
free(vOutputNameModels);
vOutputNameModels = NULL;
free(vOutputNameSynthesisAdjusted);
vOutputNameSynthesisAdjusted = NULL;
}
}
MPI_Barrier(MPI_COMM_WORLD);
if(numFilesPer2ProcessParallel>0){ // CASE DIVIDE EACH IMAGE BETWEEN TWO PROCESS
if(idProc!=root){
vInputFileSpectraDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));
vOutputNameModelsDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));
vOutputNameSynthesisAdjustedDiv2Parallel = (nameFile *)malloc(numFilesPer2ProcessParallel*sizeof(nameFile));
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Bcast(vInputFileSpectraDiv2Parallel, numFilesPer2ProcessParallel,mpiName , root , MPI_COMM_WORLD);
MPI_Bcast(vOutputNameModelsDiv2Parallel, numFilesPer2ProcessParallel,mpiName , root , MPI_COMM_WORLD);
MPI_Bcast(vOutputNameSynthesisAdjustedDiv2Parallel, numFilesPer2ProcessParallel,mpiName , root , MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
}
if(numFilesPerProcessParallel>0){
if(idProc!=root){
vInputFileSpectraParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));
vOutputNameModelsParalell = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));
vOutputNameSynthesisAdjustedParallel = (nameFile *)malloc(numFilesPerProcessParallel*sizeof(nameFile));
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Bcast(vInputFileSpectraParalell, numFilesPerProcessParallel,mpiName , root , MPI_COMM_WORLD);
MPI_Bcast(vOutputNameModelsParalell, numFilesPerProcessParallel,mpiName , root , MPI_COMM_WORLD);
MPI_Bcast(vOutputNameSynthesisAdjustedParallel, numFilesPerProcessParallel,mpiName , root , MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
}
// PRINT INFORMATION
if(idProc==root){
//printf("\n-------------------------------------------------------------------------------");
printf("\nNumber of free parameters to be inverted: %d\n", free_params);
//printf("\n-------------------------------------------------------------------------------\n");
if(configCrontrolFile.ConvolveWithPSF && INITIAL_MODEL.mac>0){
//printf("\n-----------------------------------------------------------");
printf("\nConvolution with instrumental PSF will be performed. Macoturbulence is different from zero\n ");
//printf("\n-----------------------------------------------------------\n");
}
else if(configCrontrolFile.ConvolveWithPSF){
//printf("\n-----------------------------------------------------------");
printf("\nConvolution with instrumental PSF will be performed\n");
//printf("\n-----------------------------------------------------------\n");
}
else if(INITIAL_MODEL.mac>0){
printf("\n-----------------------------------------------------------");
//printf("\nConvolution will be performed: macroturbulence in initial model is different from zero\n");
//printf("\n-----------------------------------------------------------\n");
}
printf("\n--------------------------------- STARTING INVERSION -----------------------------------\n");
printf("\n ");
}
// MEMORY IF SCATTER IMAGES
FitsImage ** fitsImages;
fitsImages = (FitsImage **)malloc(numFilesPerProcessParallel*sizeof(FitsImage*));
MPI_Request * vMpiRequestScatter = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));
MPI_Request * vMpiRequestInitModel = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));
MPI_Request * vMpiRequestChisqr = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));
MPI_Request * vMpiRequestIter = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));
MPI_Request * vMpiRequestSpectraAd = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));
MPI_Request * vMpiRequestReduceExecution = malloc(numFilesPerProcessParallel*sizeof(MPI_Request));
int * vNumPixelsImage = malloc(numFilesPerProcessParallel*sizeof(int));
Init_Model ** resultsInitModel_L = (Init_Model **)malloc(numFilesPerProcessParallel*sizeof(Init_Model*));
Init_Model ** resultsInitModelTotal_L = (Init_Model **)malloc(numFilesPerProcessParallel*sizeof(Init_Model*));
float ** chisqrfTotal_L = (float **) malloc(numFilesPerProcessParallel*sizeof(float*));
float **vChisqrf_L = (float **) malloc(numFilesPerProcessParallel*sizeof(float*));
int **vNumIter_L = (int **) malloc(numFilesPerProcessParallel*sizeof(int*));
int **vNumIterTotal_L = (int **) malloc(numFilesPerProcessParallel*sizeof(int*));
float **vSpectraSplit_L = (float **) malloc(numFilesPerProcessParallel*sizeof(float*));
float **vSpectraAdjustedSplit_L = (float **) malloc(numFilesPerProcessParallel*sizeof(float*));
float **vSpectraAjustedTotal_L = (float **) malloc(numFilesPerProcessParallel*sizeof(float*));
int sendcountsPixels_L [numFilesPerProcessParallel][numProcs] ; // array describing how many elements to send to each process
int sendcountsSpectro_L [numFilesPerProcessParallel][numProcs];
int sendcountsLambda_L [numFilesPerProcessParallel][numProcs];
int displsPixels_L [numFilesPerProcessParallel][numProcs]; // array describing the displacements where each segment begins
int displsSpectro_L [numFilesPerProcessParallel][numProcs];
//int displsLambda [numProcs];
double * vElapsed_execution = calloc(numFilesPerProcessParallel,sizeof(double));
int indexInputFits;
if(numFilesPerProcess>=1){
vInputFileSpectraLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));
vOutputNameModelsLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));
vOutputNameSynthesisAdjustedLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));
if( root == idProc){
MPI_Scatterv(vInputFileSpectra, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vInputFileSpectraLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
MPI_Scatterv(vOutputNameModels, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vOutputNameModelsLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
MPI_Scatterv(vOutputNameSynthesisAdjusted, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vOutputNameSynthesisAdjustedLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
}
else{
MPI_Scatterv(NULL, NULL,NULL, mpiName, vInputFileSpectraLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
MPI_Scatterv(NULL, NULL,NULL, mpiName, vOutputNameModelsLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
MPI_Scatterv(NULL, NULL,NULL, mpiName, vOutputNameSynthesisAdjustedLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
}
MPI_Barrier(MPI_COMM_WORLD);
}
if(numFilesPerProcessParallel){
// FIRST SCATTER ALL PIXELS BETWEEN ALL PROCESS
clock_t t = clock();
for(indexInputFits=0;indexInputFits<numFilesPerProcessParallel;indexInputFits++){
if(idProc==root){
if((access(vInputFileSpectraParalell[indexInputFits].name,F_OK)!=-1)){
clock_t t = clock();
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
fitsImages[indexInputFits] = readFitsSpectroImageRectangular(vInputFileSpectraParalell[indexInputFits].name,&configCrontrolFile,1,nlambda);
}
else{
fitsImages[indexInputFits] = readFitsSpectroImage(vInputFileSpectraParalell[indexInputFits].name,1,nlambda);
}
// CHECK SIZE MASK FILE
if(vMask!=NULL && (numRowsMask!=fitsImages[indexInputFits]->rows || numColsMask!=fitsImages[indexInputFits]->cols) ){
printf("\n-----------------------------------------------------------");
printf("\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND MASK FILE %s [rows: %d , cols: %d ] ARE DIFFERENT. ",vInputFileSpectraParalell[indexInputFits].name, fitsImages[indexInputFits]->rows, fitsImages[indexInputFits]->cols,configCrontrolFile.MaskFile,numRowsMask,numColsMask);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
// CHECK SIZE STRAY LIGHT
if(slight!=NULL){
if(nl_straylight!=nlambda){
printf("\n-----------------------------------------------------------");
printf("\n Number of wavelengths in straylight file %d is different from wavelength grid file %d",nl_straylight,nlambda);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
if(nx_straylight!=0 && ny_straylight!=0){
if(nx_straylight!= fitsImages[indexInputFits]->rows || ny_straylight !=fitsImages[indexInputFits]->cols ){
printf("\n-----------------------------------------------------------");
printf("\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND STRAYLIGHT FILE %s [rows: %d , cols: %d ] ARE DIFFERENT. ",vInputFileSpectraParalell[indexInputFits].name, fitsImages[indexInputFits]->rows, fitsImages[indexInputFits]->cols,configCrontrolFile.StrayLightFile,nx_straylight,ny_straylight);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
}
}
t = clock() - t;
PRECISION timeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds
//printf("\n-----------------------------------------------------------");
printf("\nTIME TO READ CUBE %s: %5.2f s. PIXELS READ: %d",vInputFileSpectraParalell[indexInputFits].name, timeReadImage,fitsImages[indexInputFits]->numPixels);
//printf("\n-----------------------------------------------------------\n");
vNumPixelsImage[indexInputFits] = fitsImages[indexInputFits]->numPixels;
}
}
MPI_Barrier(MPI_COMM_WORLD); // Wait UNTIL THE IMAGE HAS BEEN READED COMPLETELY
// BROADCAST THE NUMBER OF PIXELS
MPI_Bcast(&vNumPixelsImage[indexInputFits], 1, MPI_INT, root , MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD); // WAIT UNTIL G HAS BEEN READ
// IF THE NUMBER OF PIXELS IS NOT GREATER THAN 0 WE DON'T CONITUNUE
if(vNumPixelsImage[indexInputFits] > 0){
if(idProc == root){
//printf("\n-----------------------------------------------------------");
printf("\nDOING INVERSION: %s \n",vInputFileSpectraParalell[indexInputFits].name );
//printf("\n-----------------------------------------------------------\n");
resultsInitModelTotal_L[indexInputFits] = calloc (vNumPixelsImage[indexInputFits] , sizeof(Init_Model));
chisqrfTotal_L[indexInputFits] = calloc (vNumPixelsImage[indexInputFits] , sizeof(float));
vNumIterTotal_L[indexInputFits] = calloc (vNumPixelsImage[indexInputFits], sizeof(int));
if(configCrontrolFile.SaveSynthesisAdjusted)
vSpectraAjustedTotal_L[indexInputFits] = calloc (vNumPixelsImage[indexInputFits]*nlambda*NPARMS,sizeof(float));
}
// allocate memory in all processes
int numPixelsProceso = vNumPixelsImage[indexInputFits]/(numProcs);
int resto = vNumPixelsImage[indexInputFits] % (numProcs);
int sum = 0; // Sum of counts. Used to calculate displacements
int sumSpectro = 0;
int sumLambda = 0;
sendcountsPixels_L[indexInputFits][0] = 0;
sendcountsSpectro_L[indexInputFits][0] = 0;
sendcountsLambda_L[indexInputFits][0] = 0;
displsPixels_L[indexInputFits][0] = 0;
displsSpectro_L[indexInputFits][0] = 0;
for ( i = 0; i < numProcs; i++) {
sendcountsPixels_L[indexInputFits][i] = numPixelsProceso;
if (resto > 0) {
sendcountsPixels_L[indexInputFits][i]++;
resto--;
}
sendcountsSpectro_L[indexInputFits][i] = (sendcountsPixels_L[indexInputFits][i])*nlambda*NPARMS;
sendcountsLambda_L[indexInputFits][i] = (sendcountsPixels_L[indexInputFits][i])*nlambda;
displsPixels_L[indexInputFits][i] = sum;
displsSpectro_L[indexInputFits][i] = sumSpectro;
//displsLambda[i] = sumLambda;
sum += sendcountsPixels_L[indexInputFits][i];
sumSpectro += sendcountsSpectro_L[indexInputFits][i];
sumLambda += sendcountsLambda_L[indexInputFits][i];
}
MPI_Barrier(MPI_COMM_WORLD); // Wait until all processes have their vlambda
local_start = MPI_Wtime();
// SCATTER VPIXELS
vSpectraSplit_L[indexInputFits] = calloc(sendcountsSpectro_L[indexInputFits][idProc],sizeof(float));
if(configCrontrolFile.SaveSynthesisAdjusted)
vSpectraAdjustedSplit_L[indexInputFits] = calloc(sendcountsSpectro_L[indexInputFits][idProc],sizeof(float));
local_start_scatter = MPI_Wtime();
MPI_Barrier(MPI_COMM_WORLD); // Wait until all processes have their vlambda
if( root == idProc){
//MPI_Scatterv(fitsImages[indexInputFits]->spectroImagen, sendcountsSpectro_L[indexInputFits], displsSpectro_L[indexInputFits], MPI_FLOAT, vSpectraSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, root, MPI_COMM_WORLD);
MPI_Iscatterv(fitsImages[indexInputFits]->spectroImagen, sendcountsSpectro_L[indexInputFits], displsSpectro_L[indexInputFits], MPI_FLOAT, vSpectraSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestScatter[indexInputFits]);
}
else{
//MPI_Scatterv(NULL, NULL,NULL, MPI_FLOAT, vSpectraSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, root, MPI_COMM_WORLD);
MPI_Iscatterv(NULL, NULL,NULL, MPI_FLOAT, vSpectraSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestScatter[indexInputFits]);
}
local_finish_scatter = MPI_Wtime();
resultsInitModel_L[indexInputFits] = calloc(sendcountsPixels_L[indexInputFits][idProc], sizeof(Init_Model));
vChisqrf_L[indexInputFits] = calloc(sendcountsPixels_L[indexInputFits][idProc], sizeof(float));
vNumIter_L[indexInputFits] = calloc(sendcountsPixels_L[indexInputFits][idProc], sizeof(int));
}
else if (idProc==root){
printf("\n-----------------------------------------------------------");
printf("\n------------- FITS FILE CANNOT BE READ %s ",vInputFileSpectraParalell[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
}
MPI_Waitall(numFilesPerProcessParallel,vMpiRequestScatter,MPI_STATUSES_IGNORE);
if(idProc==root){
t = clock() - t;
PRECISION timeTotalExecution = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds
//printf("\n-----------------------------------------------------------");
printf("\nTOTAL TIME TO READ AND SCATTER CUBES: %6.2f s",timeTotalExecution);
printf("\n----------------------------------------------------------------------------------------\n");
}
}
AllocateMemoryDerivedSynthesis(nlambda);
//*************************************** ONE IMAGE PER PROCESSOR *********************************
if(numFilesPerProcessParallel){
//clock_t t = clock();
// EACH PROC PROCESS THER PIXELS
for(indexInputFits=0;indexInputFits<numFilesPerProcessParallel;indexInputFits++){
if(vNumPixelsImage[indexInputFits] > 0){
local_start_execution = MPI_Wtime();
for(indexPixel = 0; indexPixel < sendcountsPixels_L[indexInputFits][idProc]; indexPixel++){
int invertir = 1;
if(vMask!=NULL && !vMask[ displsPixels_L[indexInputFits][idProc] + indexPixel]){
invertir=0;
}
if(invertir){
float * vAuxSpectraSplit = vSpectraSplit_L[indexInputFits];
//Initial Model
Init_Model initModel;
initModel.eta0 = INITIAL_MODEL.eta0;
initModel.B = INITIAL_MODEL.B;
initModel.gm = INITIAL_MODEL.gm;
initModel.az = INITIAL_MODEL.az;
initModel.vlos = INITIAL_MODEL.vlos; //km/s 0
initModel.mac = INITIAL_MODEL.mac;
initModel.dopp = INITIAL_MODEL.dopp;
initModel.aa = INITIAL_MODEL.aa;
initModel.alfa = INITIAL_MODEL.alfa;
initModel.S0 = INITIAL_MODEL.S0;
initModel.S1 = INITIAL_MODEL.S1;
// CLASSICAL ESTIMATES TO GET B, GAMMA, vlos, azimuth
estimacionesClasicas(wlines[1], vGlobalLambda, nlambda, vAuxSpectraSplit+(indexPixel*(nlambda*NPARMS)), &initModel,1);
if (isnan(initModel.B))
initModel.B = 1;
if (isnan(initModel.vlos))
initModel.vlos = 1e-3;
if (isnan(initModel.gm))
initModel.gm = 1;
if (isnan(initModel.az))
initModel.az = 1;
// INVERSION RTE
float * slightPixel;
if(slight==NULL)
slightPixel = NULL;
else{
if(nx_straylight && ny_straylight){
slightPixel = slight+ (nlambda*NPARMS*indexPixel)+displsSpectro_L[indexInputFits][idProc];
}
else {
slightPixel = slight;
}
}
vNumIter_L[indexInputFits][indexPixel] = -1;
lm_mils(cuantic, wlines, vGlobalLambda, nlambda, vAuxSpectraSplit+(indexPixel*(nlambda*NPARMS)), nlambda, &initModel, spectra, &(vChisqrf_L[indexInputFits][indexPixel]), slightPixel, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles,
configCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma, configCrontrolFile.noise, configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&(vNumIter_L[indexInputFits][indexPixel]),configCrontrolFile.mu,configCrontrolFile.logclambda);
resultsInitModel_L[indexInputFits][indexPixel] = initModel;
if(configCrontrolFile.SaveSynthesisAdjusted){
int kk;
for (kk = 0; kk < (nlambda * NPARMS); kk++)
{
vSpectraAdjustedSplit_L[indexInputFits][ (indexPixel*(nlambda * NPARMS))+kk] = spectra[kk] ;
}
}
}
else{
Init_Model initModel;
initModel.eta0 = 0;
initModel.B = 0;
initModel.gm = 0;
initModel.az = 0;
initModel.vlos = 0; //km/s 0
initModel.mac = 0;
initModel.dopp = 0;
initModel.aa = 0;
initModel.alfa = 0;
initModel.S0 = 0;
initModel.S1 = 0;
resultsInitModel_L[indexInputFits][indexPixel] = initModel;
if(configCrontrolFile.SaveSynthesisAdjusted){
int kk;
for (kk = 0; kk < (nlambda * NPARMS); kk++)
{
vSpectraAdjustedSplit_L[indexInputFits][ (indexPixel*(nlambda * NPARMS))+kk] = 0 ;
}
}
}
}
/*MPI_Igatherv(resultsInitModel_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], mpiInitModel, resultsInitModelTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], mpiInitModel, root, MPI_COMM_WORLD,&vMpiRequestInitModel[indexInputFits]);
MPI_Igatherv(vChisqrf_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], MPI_FLOAT, chisqrfTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestChisqr[indexInputFits]);
MPI_Igatherv(vNumIter_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], MPI_INT, vNumIterTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], MPI_INT, root, MPI_COMM_WORLD,&vMpiRequestIter[indexInputFits]);
if(configCrontrolFile.SaveSynthesisAdjusted)
MPI_Igatherv(vSpectraAdjustedSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, vSpectraAjustedTotal_L[indexInputFits], sendcountsSpectro_L[indexInputFits], displsSpectro_L[indexInputFits], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestSpectraAd[indexInputFits]);
local_elapsed_execution = MPI_Wtime() - local_start_execution;
MPI_Ireduce(&local_elapsed_execution, &vElapsed_execution[indexInputFits], 1, MPI_DOUBLE, MPI_MAX, root, MPI_COMM_WORLD,&vMpiRequestReduceExecution[indexInputFits]);*/
MPI_Gatherv(resultsInitModel_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], mpiInitModel, resultsInitModelTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], mpiInitModel, root, MPI_COMM_WORLD);
MPI_Gatherv(vChisqrf_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], MPI_FLOAT, chisqrfTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], MPI_FLOAT, root, MPI_COMM_WORLD);
MPI_Gatherv(vNumIter_L[indexInputFits], sendcountsPixels_L[indexInputFits][idProc], MPI_INT, vNumIterTotal_L[indexInputFits], sendcountsPixels_L[indexInputFits], displsPixels_L[indexInputFits], MPI_INT, root, MPI_COMM_WORLD);
if(configCrontrolFile.SaveSynthesisAdjusted)
MPI_Gatherv(vSpectraAdjustedSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, vSpectraAjustedTotal_L[indexInputFits], sendcountsSpectro_L[indexInputFits], displsSpectro_L[indexInputFits], MPI_FLOAT, root, MPI_COMM_WORLD);
local_elapsed_execution = MPI_Wtime() - local_start_execution;
MPI_Reduce(&local_elapsed_execution, &vElapsed_execution[indexInputFits], 1, MPI_DOUBLE, MPI_MAX, root, MPI_COMM_WORLD);
}
}
if(idProc==root){
int indexInputFits = 0;
do{
/*MPI_Wait(&vMpiRequestInitModel[indexInputFits],MPI_STATUS_IGNORE);
MPI_Wait(&vMpiRequestChisqr[indexInputFits],MPI_STATUS_IGNORE);
MPI_Wait(&vMpiRequestIter[indexInputFits],MPI_STATUS_IGNORE);
MPI_Wait(&vMpiRequestReduceExecution[indexInputFits],MPI_STATUS_IGNORE);
if(configCrontrolFile.SaveSynthesisAdjusted)
MPI_Wait(&vMpiRequestSpectraAd[indexInputFits],MPI_STATUS_IGNORE);*/
double timeWriteImage;
clock_t t;
t = clock();
printf("%s\n",vOutputNameModelsParalell[indexInputFits].name);
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
if(!writeFitsImageModelsSubSet(vOutputNameModelsParalell[indexInputFits].name,fitsImages[indexInputFits]->rows_original,fitsImages[indexInputFits]->cols_original,configCrontrolFile,resultsInitModelTotal_L[indexInputFits],chisqrfTotal_L[indexInputFits],vNumIterTotal_L[indexInputFits],configCrontrolFile.saveChisqr)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT MODELS: %s",vOutputNameModelsParalell[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
}
else{
if(!writeFitsImageModels(vOutputNameModelsParalell[indexInputFits].name,fitsImages[indexInputFits]->rows,fitsImages[indexInputFits]->cols,resultsInitModelTotal_L[indexInputFits],chisqrfTotal_L[indexInputFits],vNumIterTotal_L[indexInputFits],configCrontrolFile.saveChisqr)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT MODELS: %s",vOutputNameModelsParalell[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
}
t = clock() - t;
timeWriteImage = ((double)t)/CLOCKS_PER_SEC; // in seconds
// PROCESS FILE OF SYNTETIC PROFILES
if(configCrontrolFile.SaveSynthesisAdjusted){
fitsImages[indexInputFits]->pixels = calloc(fitsImages[indexInputFits]->numPixels, sizeof(vpixels));
for( i=0;i<fitsImages[indexInputFits]->numPixels;i++){
fitsImages[indexInputFits]->pixels[i].spectro = calloc ((fitsImages[indexInputFits]->numStokes*fitsImages[indexInputFits]->nLambdas),sizeof(float));
}
for(indexPixel=0;indexPixel<fitsImages[indexInputFits]->numPixels;indexPixel++)
{
int kk;
for (kk = 0; kk < (nlambda * NPARMS); kk++)
{
fitsImages[indexInputFits]->pixels[indexPixel].spectro[kk] = vSpectraAjustedTotal_L[indexInputFits][kk+(indexPixel*(nlambda * NPARMS))] ;
}
}
// WRITE SINTHETIC PROFILES TO FITS FILE
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
if(!writeFitsImageProfilesSubSet(vOutputNameSynthesisAdjustedParallel[indexInputFits].name,vInputFileSpectraParalell[indexInputFits].name,fitsImages[indexInputFits],configCrontrolFile)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT PROFILES: %s",vOutputNameSynthesisAdjustedParallel[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
}
else{
if(!writeFitsImageProfiles(vOutputNameSynthesisAdjustedParallel[indexInputFits].name,vInputFileSpectraParalell[indexInputFits].name,fitsImages[indexInputFits])){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT PROFILES: %s",vOutputNameSynthesisAdjustedParallel[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
}
for( i=0;i<fitsImages[indexInputFits]->numPixels;i++){
free(fitsImages[indexInputFits]->pixels[i].spectro);
fitsImages[indexInputFits]->pixels[i].spectro = NULL;
}
free(fitsImages[indexInputFits]->pixels);
fitsImages[indexInputFits]->pixels = NULL;
}
free(resultsInitModelTotal_L[indexInputFits]);
free(chisqrfTotal_L[indexInputFits]);
free(vNumIterTotal_L[indexInputFits]);
if(configCrontrolFile.SaveSynthesisAdjusted){
free(vSpectraAjustedTotal_L[indexInputFits]);
}
printf("\n----------------------------------------------------------------------------------------------------");
printf("\nCUBE %s INVERTED USING ALL CORES! EXECUTION TIME: %6.2f s", vInputFileSpectraParalell[indexInputFits].name,vElapsed_execution[indexInputFits]);
//printf("\n EXECUTION TIME = %lf s.\n", vElapsed_execution[indexInputFits]);
printf("\nTIME TO WRITE FITS IMAGE: %5.2f s.", timeWriteImage);
printf("\n----------------------------------------------------------------------------------------------------\n");
freeFitsImage(fitsImages[indexInputFits]);
indexInputFits++;
}while(indexInputFits<numFilesPerProcessParallel);
}
free(fitsImages);
free(vMpiRequestScatter);
free(vMpiRequestInitModel);
free(vMpiRequestChisqr);
free(vMpiRequestIter);
free(vMpiRequestSpectraAd);
free(vNumPixelsImage);
free(vMpiRequestReduceExecution);
free(resultsInitModel_L);
free(resultsInitModelTotal_L);
free(chisqrfTotal_L);
free(vChisqrf_L);
free(vNumIter_L);
free(vNumIterTotal_L);
free(vSpectraSplit_L);
free(vSpectraAdjustedSplit_L);
free(vSpectraAjustedTotal_L);
//MPI_Barrier(MPI_COMM_WORLD);
}
if(numFilesPerProcess>=1){ // ONE IMAGE PER PROCESSOR
Init_Model *vModels;
/*vInputFileSpectraLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));
vOutputNameModelsLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));
vOutputNameSynthesisAdjustedLocal = (nameFile *) malloc(sendcountsNameInputFiles[idProc]*sizeof(nameFile));
if( root == idProc){
MPI_Scatterv(vInputFileSpectra, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vInputFileSpectraLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
MPI_Scatterv(vOutputNameModels, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vOutputNameModelsLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
MPI_Scatterv(vOutputNameSynthesisAdjusted, sendcountsNameInputFiles, displsNameInputFiles, mpiName, vOutputNameSynthesisAdjustedLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
}
else{
MPI_Scatterv(NULL, NULL,NULL, mpiName, vInputFileSpectraLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
MPI_Scatterv(NULL, NULL,NULL, mpiName, vOutputNameModelsLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
MPI_Scatterv(NULL, NULL,NULL, mpiName, vOutputNameSynthesisAdjustedLocal, sendcountsNameInputFiles[idProc], mpiName, root, MPI_COMM_WORLD);
}
MPI_Barrier(MPI_COMM_WORLD);*/
// PROCESS INVERSION OVER EACH FILE ON THE CURRENT PROCESSOR
int indexInputFits;
for(indexInputFits=0;indexInputFits<sendcountsNameInputFiles[idProc];indexInputFits++){
/****************************************************************************************************/
// READ PIXELS FROM IMAGE
PRECISION timeReadImage ;
clock_t t, timeTotal;
t = clock();
timeTotal = clock();
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
fitsImage = readFitsSpectroImageRectangular(vInputFileSpectraLocal[indexInputFits].name,&configCrontrolFile,0,nlambda);
}
else
fitsImage = readFitsSpectroImage(vInputFileSpectraLocal[indexInputFits].name,0,nlambda);
if(vMask!=NULL && (numRowsMask!=fitsImage->rows || numColsMask!=fitsImage->cols)){
printf("\n-----------------------------------------------------------");
printf("\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND MASK FILE %s [rows: %d , cols: %d ] ARE DIFFERENT. ",vInputFileSpectraLocal[indexInputFits].name, fitsImage->rows, fitsImage->cols,configCrontrolFile.MaskFile,numRowsMask,numColsMask);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
// CHECK SIZE STRAY LIGHT
if(slight!=NULL){
if(nl_straylight!=nlambda){
printf("\n-----------------------------------------------------------");
printf("\n Number of wavelengths in straylight file %d is different from wavelength grid file %d",nl_straylight,nlambda);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
if(nx_straylight!=0 && ny_straylight!=0){
if(nx_straylight!= fitsImage->rows || ny_straylight !=fitsImage->cols ){
printf("\n-----------------------------------------------------------");
printf("\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND STRAYLIGHT FILE %s [rows: %d , cols: %d ] ARE DIFFERENT. ",vInputFileSpectraParalell[indexInputFits].name, fitsImage->rows, fitsImage->cols,configCrontrolFile.StrayLightFile,nx_straylight,ny_straylight);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
}
}
t = clock() - t;
timeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds
//printf("\n-----------------------------------------------------------------------------------------");
printf("ID:%3d --> TIME TO READ CUBE %s: %5.2f s. PIXELS READ: %d",idProc, vInputFileSpectraLocal[indexInputFits].name, timeReadImage,fitsImage->numPixels);
//printf("\n-----------------------------------------------------------------------------------------\n");
if(fitsImage!=NULL){
// FITS IMAGE TO STORE OUTPUT PROFILES ADJUSTED
FitsImage * imageStokesAdjust = NULL;
if(configCrontrolFile.SaveSynthesisAdjusted){
imageStokesAdjust = malloc(sizeof(FitsImage));
imageStokesAdjust->rows = fitsImage->rows;
imageStokesAdjust->cols = fitsImage->cols;
imageStokesAdjust->nLambdas = fitsImage->nLambdas;
imageStokesAdjust->numStokes = fitsImage->numStokes;
imageStokesAdjust->pos_col = fitsImage->pos_col;
imageStokesAdjust->pos_row = fitsImage->pos_row;
imageStokesAdjust->pos_lambda = fitsImage->pos_lambda;
imageStokesAdjust->pos_stokes_parameters = fitsImage->pos_stokes_parameters;
imageStokesAdjust->numPixels = fitsImage->numPixels;
imageStokesAdjust->pixels = calloc(imageStokesAdjust->numPixels, sizeof(vpixels));
imageStokesAdjust->naxes = fitsImage->naxes;
imageStokesAdjust->vCard = fitsImage->vCard;
imageStokesAdjust->vKeyname = fitsImage->vKeyname;
imageStokesAdjust->nkeys = fitsImage->nkeys;
imageStokesAdjust->naxis = fitsImage->naxis;
imageStokesAdjust->bitpix = fitsImage->bitpix;
imageStokesAdjust->rows_original = fitsImage->rows_original;
imageStokesAdjust->cols_original = fitsImage->cols_original;
imageStokesAdjust->naxes_original = fitsImage->naxes_original;
for( i=0;i<imageStokesAdjust->numPixels;i++){
imageStokesAdjust->pixels[i].spectro = calloc (nlambda*NPARMS,sizeof(float));
}
}
//***************************************** INIT MEMORY WITH SIZE OF LAMBDA ****************************************************//
int indexPixel = 0;
// ALLOCATE MEMORY FOR STORE THE RESULTS
vModels = calloc (fitsImage->numPixels , sizeof(Init_Model));
vChisqrf = calloc (fitsImage->numPixels , sizeof(float));
vNumIter = calloc (fitsImage->numPixels, sizeof(int));
//t = clock();
//printf("\n------------------------------------------------------------------------------------------");
printf("\nID:%3d --> DOING INVERSION: %s\n",idProc,vInputFileSpectraLocal[indexInputFits].name);
//printf("\n------------------------------------------------------------------------------------------/n");
printf("\n ");
for(indexPixel = 0; indexPixel < fitsImage->numPixels; indexPixel++){
int invertir =1;
if(vMask!=NULL && !vMask[indexPixel]){
invertir=0;
}
if(invertir){
//Initial Model
Init_Model initModel;
initModel.eta0 = INITIAL_MODEL.eta0;
initModel.B = INITIAL_MODEL.B; //200 700
initModel.gm = INITIAL_MODEL.gm;
initModel.az = INITIAL_MODEL.az;
initModel.vlos = INITIAL_MODEL.vlos; //km/s 0
initModel.mac = INITIAL_MODEL.mac;
initModel.dopp = INITIAL_MODEL.dopp;
initModel.aa = INITIAL_MODEL.aa;
initModel.alfa = INITIAL_MODEL.alfa; //0.38; //stray light factor
initModel.S0 = INITIAL_MODEL.S0;
initModel.S1 = INITIAL_MODEL.S1;
// CLASSICAL ESTIMATES TO GET B, GAMMA, vlos, azimuth
estimacionesClasicas(wlines[1], vGlobalLambda, nlambda, fitsImage->pixels[indexPixel].spectro, &initModel,1);
if (isnan(initModel.B))
initModel.B = 1;
if (isnan(initModel.vlos))
initModel.vlos = 1e-3;
if (isnan(initModel.gm))
initModel.gm = 1;
if (isnan(initModel.az))
initModel.az = 1;
// INVERSION RTE
float * slightPixel;
if(slight==NULL)
slightPixel = NULL;
else{
if(nx_straylight && ny_straylight){
slightPixel = slight+ (nlambda*NPARMS*indexPixel);
}
else {
slightPixel = slight;
}
}
vNumIter[indexPixel] = -1;
lm_mils(cuantic, wlines, vGlobalLambda, nlambda, fitsImage->pixels[indexPixel].spectro, nlambda, &initModel, spectra, &vChisqrf[indexPixel], slightPixel, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles,
configCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma, configCrontrolFile.noise, configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&vNumIter[indexPixel],configCrontrolFile.mu,configCrontrolFile.logclambda);
vModels[indexPixel] = initModel;
if(configCrontrolFile.SaveSynthesisAdjusted){
int kk;
for (kk = 0; kk < (nlambda * NPARMS); kk++)
{
imageStokesAdjust->pixels[indexPixel].spectro[kk] = spectra[kk] ;
}
}
}else
{
Init_Model initModel;
initModel.eta0 = 0;
initModel.B = 0; //200 700
initModel.gm = 0;
initModel.az = 0;
initModel.vlos = 0; //km/s 0
initModel.mac = 0;
initModel.dopp = 0;
initModel.aa = 0;
initModel.alfa = 0; //0.38; //stray light factor
initModel.S0 = 0;
initModel.S1 = 0;
vModels[indexPixel] = initModel;
if(configCrontrolFile.SaveSynthesisAdjusted){
int kk;
for (kk = 0; kk < (nlambda * NPARMS); kk++)
{
imageStokesAdjust->pixels[indexPixel].spectro[kk] = 0 ;
}
}
}
}
clock_t t_write = clock();
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
if(!writeFitsImageModelsSubSet(vOutputNameModelsLocal[indexInputFits].name,fitsImage->rows_original,fitsImage->cols_original,configCrontrolFile,vModels,vChisqrf,vNumIter,configCrontrolFile.saveChisqr)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT MODELS: %s",vOutputNameModelsParalell[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
if(configCrontrolFile.SaveSynthesisAdjusted){
// WRITE SINTHETIC PROFILES TO FITS FILE
if(!writeFitsImageProfilesSubSet(vOutputNameSynthesisAdjustedLocal[indexInputFits].name,vInputFileSpectraLocal[indexInputFits].name,imageStokesAdjust,configCrontrolFile)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT PROFILES: %s",vOutputNameSynthesisAdjustedLocal[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
}
}
else{
if(!writeFitsImageModels(vOutputNameModelsLocal[indexInputFits].name,fitsImage->rows,fitsImage->cols,vModels,vChisqrf,vNumIter,configCrontrolFile.saveChisqr)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT MODELS: %s",vOutputNameModelsLocal[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
if(configCrontrolFile.SaveSynthesisAdjusted){
// WRITE SINTHETIC PROFILES TO FITS FILE
if(!writeFitsImageProfiles(vOutputNameSynthesisAdjustedLocal[indexInputFits].name,vInputFileSpectraLocal[indexInputFits].name,imageStokesAdjust)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT PROFILES: %s",vOutputNameSynthesisAdjustedLocal[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
}
}
// PROCESS FILE OF SYNTETIC PROFILES
timeTotal = clock() - timeTotal;
t_write = clock() - t_write;
PRECISION timeTotalExecution = ((PRECISION)timeTotal)/CLOCKS_PER_SEC; // in seconds
//printf("\n----------------------------------------------------------------------------------------------------");
printf("\nID:%3d --> CUBE %s INVERTED USING ONE CORE! TIME: %6.2f s", idProc, vInputFileSpectraLocal[indexInputFits].name,timeTotalExecution);
//printf("\n----------------------------------------------------------------------------------------------------\n");
PRECISION timeToWriteImage = ((PRECISION)t_write)/CLOCKS_PER_SEC; // in seconds
//printf("\n----------------------------------------------------------------------------------------------------");
printf("\nID:%3d --> TIME TO WRITE FITS CUBE: %5.2f s", idProc, timeToWriteImage);
printf("\n----------------------------------------------------------------------------------------------------\n");
if(imageStokesAdjust!=NULL){
for( i=0;i<imageStokesAdjust->numPixels;i++){
free(imageStokesAdjust->pixels[i].spectro);
}
free(imageStokesAdjust->pixels);
free(imageStokesAdjust);
}
free(vModels);
free(vChisqrf);
free(vNumIter);
}
else{
printf("\n-----------------------------------------------------------");
printf("\nID:%3d --> FILE %s WITH PROFILES CANNOT BE READ ************",idProc, vInputFileSpectraLocal[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
freeFitsImage(fitsImage);
//FreeMemoryDerivedSynthesis();
}
free(vInputFileSpectraLocal);
free(vOutputNameModelsLocal);
free(vOutputNameSynthesisAdjustedLocal);
vInputFileSpectraLocal = NULL;
vOutputNameModelsLocal = NULL;
vOutputNameSynthesisAdjustedLocal = NULL;
}
if(numFilesPer2ProcessParallel>0){ // CASE DIVIDE EACH IMAGE BETWEEN TWO PROCESS
// Get the group or processes of the default communicator
// EACH GROUP PROCESS ONE IMAGE
MPI_Barrier(vCommunicators[myGroup]);
numPixels=0;
clock_t timeTotal;
if(myGroupRank==groupRoot && access(vInputFileSpectraDiv2Parallel[myGroup].name,F_OK)!=-1){
clock_t t = clock();
timeTotal = clock();
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
fitsImage = readFitsSpectroImageRectangular(vInputFileSpectraDiv2Parallel[myGroup].name,&configCrontrolFile,1,nlambda);
}
else
fitsImage = readFitsSpectroImage(vInputFileSpectraDiv2Parallel[myGroup].name,1,nlambda);
if(vMask!=NULL && (numRowsMask!=fitsImage->rows || numColsMask!=fitsImage->cols)){
printf("\n-----------------------------------------------------------");
printf("\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND MASK FILE %s [rows: %d , cols: %d ] ARE DIFFERENT. ",vInputFileSpectraDiv2Parallel[myGroup].name, fitsImage->rows, fitsImage->cols,configCrontrolFile.MaskFile,numRowsMask,numColsMask);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
// CHECK SIZE STRAY LIGHT
if(slight!=NULL){
if(nl_straylight!=nlambda){
printf("\n-----------------------------------------------------------");
printf("\n Number of wavelengths in straylight file %d is different from wavelength grid file %d",nl_straylight,nlambda);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
if(nx_straylight!=0 && ny_straylight!=0){
if(nx_straylight!= fitsImage->rows || ny_straylight !=fitsImage->cols ){
printf("\n-----------------------------------------------------------");
printf("\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND STRAYLIGHT FILE %s [rows: %d , cols: %d ] ARE DIFFERENT. ",vInputFileSpectraParalell[indexInputFits].name, fitsImage->rows, fitsImage->cols,configCrontrolFile.StrayLightFile,nx_straylight,ny_straylight);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
}
}
t = clock() - t;
PRECISION timeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds
//printf("\n-----------------------------------------------------------");
printf("\nTIME TO READ CUBE %s: %5.2f s. PIXELS READ: %d",vInputFileSpectraDiv2Parallel[myGroup].name, timeReadImage,fitsImage->numPixels);
//printf("\n-----------------------------------------------------------\n");
numPixels = fitsImage->numPixels;
}
MPI_Barrier(vCommunicators[myGroup]); // Wait UNTIL THE IMAGE HAS BEEN READED COMPLETELY by my group
MPI_Bcast(&numPixels, 1, MPI_INT, groupRoot , vCommunicators[myGroup]);
MPI_Barrier(vCommunicators[myGroup]);
if(numPixels > 0){
if(myGroupRank==groupRoot){
//printf("\n-----------------------------------------------------------");
printf("\nDOING INVERSION: %s \n",vInputFileSpectraDiv2Parallel[myGroup].name );
//printf("\n-----------------------------------------------------------");
resultsInitModelTotal = calloc (numPixels , sizeof(Init_Model));
chisqrfTotal = calloc (numPixels , sizeof(float));
vNumIterTotal = calloc (numPixels, sizeof(int));
if(configCrontrolFile.SaveSynthesisAdjusted)
vSpectraAjustedTotal = calloc (numPixels*nlambda*NPARMS,sizeof(float));
}
int numPixelsProceso = numPixels/myGroupSize;
int resto = numPixels % myGroupSize;
int sum = 0; // Sum of counts. Used to calculate displacements
int sumSpectro = 0;
int sumLambda = 0;
int sendcountsDiv2Pixels [myGroupSize] ; // array describing how many elements to send to each process
int sendcountsDiv2Spectro [myGroupSize];
int sendcountsDiv2Lambda [myGroupSize];
int displsDiv2Pixels [myGroupSize];
int displsDiv2Spectro [myGroupSize];
for ( i = 0; i < myGroupSize; i++) {
sendcountsDiv2Pixels[i] = numPixelsProceso;
if (resto > 0) {
sendcountsDiv2Pixels[i]++;
resto--;
}
sendcountsDiv2Spectro[i] = sendcountsDiv2Pixels[i]*nlambda*NPARMS;
sendcountsDiv2Lambda[i] = sendcountsDiv2Pixels[i]*nlambda;
displsDiv2Pixels[i] = sum;
displsDiv2Spectro[i] = sumSpectro;
sum += sendcountsDiv2Pixels[i];
sumSpectro += sendcountsDiv2Spectro[i];
sumLambda += sendcountsDiv2Lambda[i];
}
MPI_Barrier(vCommunicators[myGroup]);
// SCATTER VPIXELS
local_start = MPI_Wtime();
local_start_scatter = MPI_Wtime();
vSpectraSplit = calloc(sendcountsDiv2Spectro[myGroupRank],sizeof(float));
if(configCrontrolFile.SaveSynthesisAdjusted)
vSpectraAdjustedSplit = calloc(sendcountsDiv2Spectro[myGroupRank],sizeof(float));
if(myGroupRank==groupRoot){
MPI_Scatterv(fitsImage->spectroImagen, sendcountsDiv2Spectro, displsDiv2Spectro, MPI_FLOAT, vSpectraSplit, sendcountsDiv2Spectro[myGroupRank], MPI_FLOAT, groupRoot, vCommunicators[myGroup]);
}
else{
MPI_Scatterv(NULL, NULL,NULL, MPI_FLOAT, vSpectraSplit, sendcountsDiv2Spectro[myGroupRank], MPI_FLOAT, groupRoot, vCommunicators[myGroup]);
}
local_finish_scatter = MPI_Wtime();
resultsInitModel = calloc(sendcountsDiv2Pixels[myGroupRank], sizeof(Init_Model));
vChisqrf = calloc(sendcountsDiv2Pixels[myGroupRank], sizeof(float));
vNumIter = calloc(sendcountsDiv2Pixels[myGroupRank], sizeof(int));
local_start_execution = MPI_Wtime();
for(indexPixel = 0; indexPixel < sendcountsDiv2Pixels[myGroupRank]; indexPixel++){
int invertir = 1;
if(vMask!=NULL && !vMask[ displsDiv2Pixels[myGroupRank] + indexPixel]){
invertir=0;
}
if(invertir){
//Initial Model
Init_Model initModel;
initModel.eta0 = INITIAL_MODEL.eta0;
initModel.B = INITIAL_MODEL.B;
initModel.gm = INITIAL_MODEL.gm;
initModel.az = INITIAL_MODEL.az;
initModel.vlos = INITIAL_MODEL.vlos; //km/s 0
initModel.mac = INITIAL_MODEL.mac;
initModel.dopp = INITIAL_MODEL.dopp;
initModel.aa = INITIAL_MODEL.aa;
initModel.alfa = INITIAL_MODEL.alfa;
initModel.S0 = INITIAL_MODEL.S0;
initModel.S1 = INITIAL_MODEL.S1;
// CLASSICAL ESTIMATES TO GET B, GAMMA, vlos, azimuth
estimacionesClasicas(wlines[1], vGlobalLambda, nlambda, vSpectraSplit+(indexPixel*(nlambda*NPARMS)), &initModel,1);
if (isnan(initModel.B))
initModel.B = 1;
if (isnan(initModel.vlos))
initModel.vlos = 1e-3;
if (isnan(initModel.gm))
initModel.gm = 1;
if (isnan(initModel.az))
initModel.az = 1;
// INVERSION RTE
float * slightPixel;
if(slight==NULL)
slightPixel = NULL;
else{
if(nx_straylight && ny_straylight){
slightPixel = slight+ (nlambda*NPARMS* indexPixel) + displsDiv2Spectro[myGroupRank];
}
else {
slightPixel = slight;
}
}
vNumIter[indexPixel] = -1;
lm_mils(cuantic, wlines, vGlobalLambda, nlambda, vSpectraSplit+(indexPixel*(nlambda*NPARMS)), nlambda, &initModel, spectra, &vChisqrf[indexPixel], slightPixel, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles,
configCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma, configCrontrolFile.noise,configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&vNumIter[indexPixel],configCrontrolFile.mu,configCrontrolFile.logclambda);
resultsInitModel[indexPixel] = initModel;
if(configCrontrolFile.SaveSynthesisAdjusted){
int kk;
for (kk = 0; kk < (nlambda * NPARMS); kk++)
{
vSpectraAdjustedSplit[ (indexPixel*(nlambda * NPARMS))+kk] = spectra[kk] ;
}
}
}
else{
//Initial Model
Init_Model initModel;
initModel.eta0 = 0;
initModel.B = 0;
initModel.gm = 0;
initModel.az = 0;
initModel.vlos = 0; //km/s 0
initModel.mac = 0;
initModel.dopp = 0;
initModel.aa = 0;
initModel.alfa = 0;
initModel.S0 = 0;
initModel.S1 = 0;
resultsInitModel[indexPixel] = initModel;
if(configCrontrolFile.SaveSynthesisAdjusted){
int kk;
for (kk = 0; kk < (nlambda * NPARMS); kk++)
{
vSpectraAdjustedSplit[ (indexPixel*(nlambda * NPARMS))+kk] = 0 ;
}
}
}
}
local_finish_execution = MPI_Wtime();
local_start_gather = MPI_Wtime();
MPI_Gatherv(resultsInitModel, sendcountsDiv2Pixels[myGroupRank], mpiInitModel, resultsInitModelTotal, sendcountsDiv2Pixels, displsDiv2Pixels, mpiInitModel, groupRoot, vCommunicators[myGroup]);
MPI_Gatherv(vChisqrf, sendcountsDiv2Pixels[myGroupRank], MPI_FLOAT, chisqrfTotal, sendcountsDiv2Pixels, displsDiv2Pixels, MPI_FLOAT, groupRoot, vCommunicators[myGroup]);
MPI_Gatherv(vNumIter, sendcountsDiv2Pixels[myGroupRank], MPI_INT, vNumIterTotal, sendcountsDiv2Pixels, displsDiv2Pixels, MPI_INT, groupRoot, vCommunicators[myGroup]);
if(configCrontrolFile.SaveSynthesisAdjusted)
MPI_Gatherv(vSpectraAdjustedSplit, sendcountsDiv2Spectro[myGroupRank], MPI_FLOAT, vSpectraAjustedTotal, sendcountsDiv2Spectro, displsDiv2Spectro, MPI_FLOAT, groupRoot, vCommunicators[myGroup]);
local_finish_gather = MPI_Wtime();
local_finish = MPI_Wtime();
local_elapsed = local_finish - local_start;
local_elapsed_execution = local_finish_execution - local_start_execution;
local_elapsed_scatter = local_finish_scatter - local_start_scatter;
local_elapsed_gather = local_finish_gather - local_start_gather;
MPI_Reduce(&local_elapsed, &elapsed, 1, MPI_DOUBLE, MPI_MAX, groupRoot, vCommunicators[myGroup]);
MPI_Reduce(&local_elapsed_execution, &elapsed_execution, 1, MPI_DOUBLE, MPI_MAX, groupRoot, vCommunicators[myGroup]);
MPI_Reduce(&local_elapsed_scatter, &elapsed_scatter, 1, MPI_DOUBLE, MPI_MAX, groupRoot, vCommunicators[myGroup]);
MPI_Reduce(&local_elapsed_gather, &elapsed_gather, 1, MPI_DOUBLE, MPI_MAX, groupRoot, vCommunicators[myGroup]);
if(myGroupRank==groupRoot){
/*printf("\n Elapsed SCATTER time = %lf seconds\n", elapsed_scatter);
printf("\n-----------------------------------\n");
printf("\n Elapsed GATHER time = %lf seconds\n", elapsed_gather);
printf("\n-----------------------------------\n");
printf("\n-----------------------------------------------------------");
printf("\n MAX EXECUTION time = %lf seconds", elapsed_execution);
printf("\n-----------------------------------------------------------\n");
printf("\n Elapsed TOTAL time = %lf seconds\n", elapsed);
printf("\n-----------------------------------\n");*/
double timeWriteImage;
clock_t t;
t = clock();
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
if(!writeFitsImageModelsSubSet(vOutputNameModelsDiv2Parallel[myGroup].name,fitsImage->rows_original,fitsImage->cols_original,configCrontrolFile,resultsInitModelTotal,chisqrfTotal,vNumIterTotal,configCrontrolFile.saveChisqr)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT MODELS: %s",vOutputNameModelsParalell[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
}
else{
if(!writeFitsImageModels(vOutputNameModelsDiv2Parallel[myGroup].name,fitsImage->rows,fitsImage->cols,resultsInitModelTotal,chisqrfTotal,vNumIterTotal,configCrontrolFile.saveChisqr)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT MODELS: %s",vOutputNameModelsDiv2Parallel[myGroup].name);
printf("\n-----------------------------------------------------------\n");
}
}
t = clock() - t;
timeWriteImage = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("\n------------------------------------------------------------------------------------------\n");
printf("TIME TO WRITE FITS CUBE: %5.2f s.", timeWriteImage);
//printf("\n-----------------------------------------------------------\n");
if(configCrontrolFile.SaveSynthesisAdjusted){
fitsImage->pixels = calloc(fitsImage->numPixels, sizeof(vpixels));
for( i=0;i<fitsImage->numPixels;i++){
fitsImage->pixels[i].spectro = calloc ((fitsImage->numStokes*fitsImage->nLambdas),sizeof(float));
}
for(indexPixel=0;indexPixel<numPixels;indexPixel++)
{
int kk;
for (kk = 0; kk < (nlambda * NPARMS); kk++)
{
fitsImage->pixels[indexPixel].spectro[kk] = vSpectraAjustedTotal[kk+(indexPixel*(nlambda * NPARMS))] ;
}
}
// WRITE SINTHETIC PROFILES TO FITS FILE
if(!writeFitsImageProfiles(vOutputNameSynthesisAdjustedDiv2Parallel[myGroup].name,vInputFileSpectraDiv2Parallel[myGroup].name,fitsImage)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT PROFILES: %s",vOutputNameSynthesisAdjustedDiv2Parallel[myGroup].name);
printf("\n-----------------------------------------------------------\n");
}
for( i=0;i<fitsImage->numPixels;i++){
free(fitsImage->pixels[i].spectro);
fitsImage->pixels[i].spectro = NULL;
}
free(fitsImage->pixels);
fitsImage->pixels = NULL;
}
timeTotal = clock() - timeTotal;
PRECISION timeTotalExecution = ((PRECISION)timeTotal)/CLOCKS_PER_SEC; // in seconds
free(resultsInitModelTotal);
free(chisqrfTotal);
free(vNumIterTotal);
if(configCrontrolFile.SaveSynthesisAdjusted){
free(vSpectraAjustedTotal);
}
//printf("\n----------------------------------------------------------------------------------------------------");
printf("\nCUBE %s INVERTED USING TWO CORES. TIME: %7.2f s", vInputFileSpectraDiv2Parallel[myGroup].name,timeTotalExecution);
printf("\n------------------------------------------------------------------------------------------\n");
}
else{
if(configCrontrolFile.SaveSynthesisAdjusted)
free(vSpectraAdjustedSplit);
free(vSpectraSplit);
free(resultsInitModel);
free(vChisqrf);
free(vNumIter);
}
}
else
{
if(myGroupRank==groupRoot){
printf("\n-----------------------------------------------------------");
printf("\nFITS FILE CANNOT BE READ: %s ",vInputFileSpectraDiv2Parallel[myGroup].name);
printf("\n-----------------------------------------------------------\n");
}
}
if(myGroupRank==groupRoot){
freeFitsImage(fitsImage);
}
}
if(configCrontrolFile.loopInversion){
MPI_Barrier(MPI_COMM_WORLD);
int fileNew = 0;
int exitProgram = 0;
char newestFileName [256];
do{
if(idProc==root){
time_t start_time,current_time;
fileNew = 0;
int directory = 1;
time(&start_time);
printf("\n-----------------------------------------------------------");
printf("\n\tWAITING FOR NEW DATA CUBES IN DIRECTORY");
printf("\n-----------------------------------------------------------");
printf("\n");
do{
DIR *d;
struct dirent *dir;
char observedProfilesAux[256];
strcpy(observedProfilesAux,configCrontrolFile.ObservedProfiles);
char * dname = dirname(observedProfilesAux);
//d = opendir(dname);
struct dirent **namelist;
int numFiles = scandir(dname, &namelist, 0, alphasort);
if(numFiles>0){
for(i=2;i<numFiles && !fileNew;i++){
if(strcmp(namelist[i]->d_name,".")!=0 && strcmp(namelist[i]->d_name,"..")!=0 && strstr(namelist[i]->d_name,"_mod_")==NULL && strstr(namelist[i]->d_name,"_stokes_")==NULL){
char pathAux[256];
strcpy(pathAux,dname);
strcat(pathAux,"/");
//strcat(pathAux,dir->d_name);
strcat(pathAux,namelist[i]->d_name);
//stat(pathAux,&filestat);
if(!isDirectory(pathAux) && !checkNameInLista(listFileNamesReaded,pathAux)){
insert_in_linked_list(&listFileNamesReaded,pathAux);
fileNew = 1;
strcpy(newestFileName,pathAux);
printf("\n-----------------------------------------------------------");
printf("\nTHERE IS A NEW DATA CUBE IN DIRECTORY: %s",newestFileName);
printf("\n-----------------------------------------------------------");
printf("\n");
}
}
}
}
else{
printf("\nERROR, the path %s does not point to a valid directory\n. ",dname);
exit(1);
}
time(¤t_time);
if(difftime(current_time,start_time)>=TIMEOUT_FILE)
exitProgram = 1;
else
sleep(5);
}while(!fileNew && !exitProgram);
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Bcast(&fileNew, 1, MPI_INT, root , MPI_COMM_WORLD);
MPI_Bcast(&exitProgram, 1, MPI_INT, root , MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
FitsImage * fitsImageLoop;
int numPixelImageLoop;
Init_Model * resultsInitModelLoop;
Init_Model * resultsInitModelTotalLoop;
float * chisqrfTotalLoop;
float * vChisqrfLoop;
int * vNumIterLoop;
int * vNumIterTotalLoop;
int sendcountsPixelsLoop [numProcs] ; // array describing how many elements to send to each process
int sendcountsSpectroLoop [numProcs];
int sendcountsLambdaLoop [numProcs];
int displsPixelsLoop[numProcs];
int displsSpectroLoop [numProcs];
float * vSpectraSplitLoop;
float * vSpectraAdjustedSplitLoop;
float * vSpectraAjustedTotalLoop;
if(fileNew){
if(idProc==root){
if((access(newestFileName,F_OK)!=-1)){
clock_t t = clock();
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
fitsImageLoop = readFitsSpectroImageRectangular(newestFileName,&configCrontrolFile,1,nlambda);
}
else{
fitsImageLoop = readFitsSpectroImage(newestFileName,1,nlambda);
}
// CHECK SIZE MASK FILE
if(vMask!=NULL && (numRowsMask!=fitsImageLoop->rows || numColsMask!=fitsImageLoop->cols) ){
printf("\n-----------------------------------------------------------");
printf("\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND MASK FILE %s [rows: %d , cols: %d ] ARE DIFFERENT. ",vInputFileSpectraParalell[indexInputFits].name, fitsImages[indexInputFits]->rows, fitsImages[indexInputFits]->cols,configCrontrolFile.MaskFile,numRowsMask,numColsMask);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
// CHECK SIZE STRAY LIGHT
if(slight!=NULL){
if(nl_straylight!=nlambda){
printf("\n-----------------------------------------------------------");
printf("\n Number of wavelengths in straylight file %d is different from wavelength grid file %d",nl_straylight,nlambda);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
if(nx_straylight!=0 && ny_straylight!=0){
if(nx_straylight!= fitsImageLoop->rows || ny_straylight !=fitsImageLoop->cols ){
printf("\n-----------------------------------------------------------");
printf("\n DIMENSIONS OF IMAGE %s [rows: %d , cols: %d ] AND STRAYLIGHT FILE %s [rows: %d , cols: %d ] ARE DIFFERENT. ",newestFileName, fitsImageLoop->rows, fitsImageLoop->cols,configCrontrolFile.StrayLightFile,nx_straylight,ny_straylight);
printf("\n-----------------------------------------------------------\n");
exit(EXIT_FAILURE);
}
}
}
t = clock() - t;
PRECISION timeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds
//printf("\n-----------------------------------------------------------");
printf("\nTIME TO READ CUBE %s: %5.2f s. PIXELS READ: %d ",newestFileName, timeReadImage,fitsImageLoop->numPixels);
//printf("\n-----------------------------------------------------------\n");
numPixelImageLoop = fitsImageLoop->numPixels;
}
}
MPI_Barrier(MPI_COMM_WORLD); // Wait UNTIL THE IMAGE HAS BEEN READ COMPLETELY
// BROADCAST THE NUMBER OF PIXELS
MPI_Bcast(&numPixelImageLoop, 1, MPI_INT, root , MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD); // WAIT UNTIL numPixelImageLoop HAS BEEN READ
// IF THE NUMBER OF PIXELS IS NOT GREATER THAN 0 WE DON'T CONITUNUE
if(numPixelImageLoop > 0){
if(idProc == root){
//printf("\n-----------------------------------------------------------");
printf("\nDOING INVERSION: %s \n",newestFileName );
//printf("\n-----------------------------------------------------------");
resultsInitModelTotalLoop = calloc (numPixelImageLoop , sizeof(Init_Model));
chisqrfTotalLoop = calloc (numPixelImageLoop , sizeof(float));
vNumIterTotalLoop = calloc (numPixelImageLoop, sizeof(int));
if(configCrontrolFile.SaveSynthesisAdjusted)
vSpectraAjustedTotalLoop = calloc (numPixelImageLoop*nlambda*NPARMS,sizeof(float));
}
// allocate memory in all processes
int numPixelsProceso = numPixelImageLoop/(numProcs);
int resto = numPixelImageLoop % (numProcs);
int sum = 0; // Sum of counts. Used to calculate displacements
int sumSpectro = 0;
int sumLambda = 0;
sendcountsPixelsLoop[0] = 0;
sendcountsSpectroLoop[0] = 0;
sendcountsLambdaLoop[0] = 0;
displsPixelsLoop[0] = 0;
displsSpectroLoop[0] = 0;
for ( i = 0; i < numProcs; i++) {
sendcountsPixelsLoop[i] = numPixelsProceso;
if (resto > 0) {
sendcountsPixelsLoop[i]++;
resto--;
}
sendcountsSpectroLoop[i] = (sendcountsPixelsLoop[i])*nlambda*NPARMS;
sendcountsLambdaLoop[i] = (sendcountsPixelsLoop[i])*nlambda;
displsPixelsLoop[i] = sum;
displsSpectroLoop[i] = sumSpectro;
sum += sendcountsPixelsLoop[i];
sumSpectro += sendcountsSpectroLoop[i];
sumLambda += sendcountsLambdaLoop[i];
}
MPI_Barrier(MPI_COMM_WORLD); // Wait until all processes have their vlambda
// SCATTER VPIXELS
vSpectraSplitLoop = calloc(sendcountsSpectroLoop[idProc],sizeof(float));
if(configCrontrolFile.SaveSynthesisAdjusted)
vSpectraAdjustedSplitLoop = calloc(sendcountsSpectroLoop[idProc],sizeof(float));
MPI_Barrier(MPI_COMM_WORLD); // Wait until all processes have their vlambda
if( root == idProc){
MPI_Scatterv(fitsImageLoop->spectroImagen, sendcountsSpectroLoop, displsSpectroLoop, MPI_FLOAT, vSpectraSplitLoop, sendcountsSpectroLoop[idProc], MPI_FLOAT, root, MPI_COMM_WORLD);
//MPI_Iscatterv(fitsImageLoop->spectroImagen, sendcountsSpectroLoop, displsSpectroLoop, MPI_FLOAT, vSpectraSplitLoop, sendcountsSpectroLoop[idProc], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestScatter[indexInputFits]);
}
else{
MPI_Scatterv(NULL, NULL,NULL, MPI_FLOAT, vSpectraSplitLoop, sendcountsSpectroLoop[idProc], MPI_FLOAT, root, MPI_COMM_WORLD);
//MPI_Iscatterv(NULL, NULL,NULL, MPI_FLOAT, vSpectraSplit_L[indexInputFits], sendcountsSpectro_L[indexInputFits][idProc], MPI_FLOAT, root, MPI_COMM_WORLD,&vMpiRequestScatter[indexInputFits]);
}
resultsInitModelLoop = calloc(sendcountsPixelsLoop[idProc], sizeof(Init_Model));
vChisqrfLoop = calloc(sendcountsPixelsLoop[idProc], sizeof(float));
vNumIterLoop = calloc(sendcountsPixelsLoop[idProc], sizeof(int));
}
else if (idProc==root){
printf("\n-----------------------------------------------------------");
printf("\n------------ FITS FILE CANNOT BE READ: %s ",vInputFileSpectraParalell[indexInputFits].name);
printf("\n-----------------------------------------------------------\n");
}
// DO INVERSION
if(numPixelImageLoop > 0){
local_start_execution = MPI_Wtime();
for(indexPixel = 0; indexPixel < sendcountsPixelsLoop[idProc]; indexPixel++){
int invertir = 1;
if(vMask!=NULL && !vMask[ displsPixelsLoop[idProc] + indexPixel]){
invertir=0;
}
if(invertir){
float * vAuxSpectraSplit = vSpectraSplitLoop;
//Initial Model
Init_Model initModel;
initModel.eta0 = INITIAL_MODEL.eta0;
initModel.B = INITIAL_MODEL.B;
initModel.gm = INITIAL_MODEL.gm;
initModel.az = INITIAL_MODEL.az;
initModel.vlos = INITIAL_MODEL.vlos; //km/s 0
initModel.mac = INITIAL_MODEL.mac;
initModel.dopp = INITIAL_MODEL.dopp;
initModel.aa = INITIAL_MODEL.aa;
initModel.alfa = INITIAL_MODEL.alfa;
initModel.S0 = INITIAL_MODEL.S0;
initModel.S1 = INITIAL_MODEL.S1;
// CLASSICAL ESTIMATES TO GET B, GAMMA, vlos, azimuth
estimacionesClasicas(wlines[1], vGlobalLambda, nlambda, vAuxSpectraSplit+(indexPixel*(nlambda*NPARMS)), &initModel,1);
if (isnan(initModel.B))
initModel.B = 1;
if (isnan(initModel.vlos))
initModel.vlos = 1e-3;
if (isnan(initModel.gm))
initModel.gm = 1;
if (isnan(initModel.az))
initModel.az = 1;
// INVERSION RTE
float * slightPixel;
if(slight==NULL)
slightPixel = NULL;
else{
if(nx_straylight && ny_straylight){
slightPixel = slight+ (nlambda*NPARMS*indexPixel)+displsSpectroLoop[idProc];
}
else {
slightPixel = slight;
}
}
vNumIterLoop[indexPixel] = -1;
lm_mils(cuantic, wlines, vGlobalLambda, nlambda, vAuxSpectraSplit+(indexPixel*(nlambda*NPARMS)), nlambda, &initModel, spectra, &(vChisqrfLoop[indexPixel]), slightPixel, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles,
configCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma, configCrontrolFile.noise, configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&(vNumIterLoop[indexPixel]),configCrontrolFile.mu,configCrontrolFile.logclambda);
resultsInitModelLoop[indexPixel] = initModel;
if(configCrontrolFile.SaveSynthesisAdjusted){
int kk;
for (kk = 0; kk < (nlambda * NPARMS); kk++)
{
vSpectraAdjustedSplitLoop[ (indexPixel*(nlambda * NPARMS))+kk] = spectra[kk] ;
}
}
}
else{
Init_Model initModel;
initModel.eta0 = 0;
initModel.B = 0;
initModel.gm = 0;
initModel.az = 0;
initModel.vlos = 0; //km/s 0
initModel.mac = 0;
initModel.dopp = 0;
initModel.aa = 0;
initModel.alfa = 0;
initModel.S0 = 0;
initModel.S1 = 0;
resultsInitModelLoop[indexPixel] = initModel;
if(configCrontrolFile.SaveSynthesisAdjusted){
int kk;
for (kk = 0; kk < (nlambda * NPARMS); kk++)
{
vSpectraAdjustedSplitLoop[ (indexPixel*(nlambda * NPARMS))+kk] = 0 ;
}
}
}
}
//printf("\n ESTOY EN EL PROCESO %d Y HE TERMINADO MIS PIXELS. \n",idProc);
MPI_Gatherv(resultsInitModelLoop, sendcountsPixelsLoop[idProc], mpiInitModel, resultsInitModelTotalLoop, sendcountsPixelsLoop, displsPixelsLoop, mpiInitModel, root, MPI_COMM_WORLD);
MPI_Gatherv(vChisqrfLoop, sendcountsPixelsLoop[idProc], MPI_FLOAT, chisqrfTotalLoop, sendcountsPixelsLoop, displsPixelsLoop, MPI_FLOAT, root, MPI_COMM_WORLD);
MPI_Gatherv(vNumIterLoop, sendcountsPixelsLoop[idProc], MPI_INT, vNumIterTotalLoop, sendcountsPixelsLoop, displsPixelsLoop, MPI_INT, root, MPI_COMM_WORLD);
//printf("\n ESTOY EN EL PROCESO %d GATHER REALIZADO . \n",idProc);
if(configCrontrolFile.SaveSynthesisAdjusted)
MPI_Gatherv(vSpectraAdjustedSplitLoop, sendcountsSpectroLoop[idProc], MPI_FLOAT, vSpectraAjustedTotalLoop, sendcountsSpectroLoop, displsSpectroLoop, MPI_FLOAT, root, MPI_COMM_WORLD);
local_elapsed_execution = MPI_Wtime() - local_start_execution;
MPI_Reduce(&local_elapsed_execution, &elapsed_execution, 1, MPI_DOUBLE, MPI_MAX, root, MPI_COMM_WORLD);
if(idProc==root){
char outputNameModelsLoop[256];
char outputNameSynthesisAdjustedLoop[256];
char auxObservedProfiles1 [256];
char auxObservedProfiles2 [256];
strcpy(auxObservedProfiles1,newestFileName);
strcpy(auxObservedProfiles2,newestFileName);
char * dirNameObservedProfiles = dirname(auxObservedProfiles1);
char * fileNameObservedProfiles = basename(auxObservedProfiles2);
/*if(strcmp(dirNameObservedProfiles,".")!=0){
strcpy(outputNameModelsLoop,dirNameObservedProfiles);
strcat(outputNameModelsLoop,"/");
strcpy(outputNameSynthesisAdjustedLoop,dirNameObservedProfiles);
strcat(outputNameSynthesisAdjustedLoop,"/");
if(configCrontrolFile.outputPrefix[0]!='\0'){
strcat(outputNameModelsLoop,configCrontrolFile.outputPrefix);
strcat(outputNameSynthesisAdjustedLoop,configCrontrolFile.outputPrefix);
}
strcat(outputNameModelsLoop,fileNameObservedProfiles);
strcat(outputNameSynthesisAdjustedLoop,fileNameObservedProfiles);
}
else{
if(configCrontrolFile.outputPrefix[0]!='\0'){
strcpy(outputNameModelsLoop,configCrontrolFile.outputPrefix);
strcat(outputNameModelsLoop,fileNameObservedProfiles);
strcpy(outputNameSynthesisAdjustedLoop,configCrontrolFile.outputPrefix);
strcat(outputNameSynthesisAdjustedLoop,fileNameObservedProfiles);
}
else{
strcpy(outputNameModelsLoop,fileNameObservedProfiles);
strcpy(outputNameSynthesisAdjustedLoop,fileNameObservedProfiles);
}
}*/
if(configCrontrolFile.outputPrefix[0]!='\0'){
strcpy(outputNameModelsLoop,configCrontrolFile.outputPrefix);
printf("%s", fileNameObservedProfiles);
strcat(outputNameModelsLoop,fileNameObservedProfiles);
strcpy(outputNameSynthesisAdjustedLoop,configCrontrolFile.outputPrefix);
strcat(outputNameSynthesisAdjustedLoop,fileNameObservedProfiles);
}
else{
strcpy(outputNameModelsLoop,fileNameObservedProfiles);
strcpy(outputNameSynthesisAdjustedLoop,fileNameObservedProfiles);
}
//strcpy(outputNameModelsLoop,get_basefilename(newestFileName));
printf("%s", "line 2405");
strcat(outputNameModelsLoop, "_mod");
/*if(configCrontrolFile.outputPrefix[0]!='\0'){
strcat(outputNameModelsLoop, "_");
strcat(outputNameModelsLoop, configCrontrolFile.outputPrefix);
}*/
strcat(outputNameModelsLoop,FITS_FILE);
//strcpy(outputNameSynthesisAdjustedLoop,get_basefilename(newestFileName));
strcat(outputNameSynthesisAdjustedLoop, "_stokes");
/*if(configCrontrolFile.outputPrefix[0]!='\0'){
strcat(outputNameSynthesisAdjustedLoop, "_");
strcat(outputNameSynthesisAdjustedLoop, configCrontrolFile.outputPrefix);
}*/
strcat(outputNameSynthesisAdjustedLoop,FITS_FILE);
double timeWriteImage;
clock_t t;
t = clock();
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
if(!writeFitsImageModelsSubSet(outputNameModelsLoop,fitsImageLoop->rows_original,fitsImageLoop->cols_original,configCrontrolFile,resultsInitModelTotalLoop,chisqrfTotalLoop,vNumIterTotalLoop,configCrontrolFile.saveChisqr)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT MODELS: %s",outputNameModelsLoop);
printf("\n-----------------------------------------------------------\n");
}
}
else{
if(!writeFitsImageModels(outputNameModelsLoop,fitsImageLoop->rows,fitsImageLoop->cols,resultsInitModelTotalLoop,chisqrfTotalLoop,vNumIterTotalLoop,configCrontrolFile.saveChisqr)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT MODELS: %s",outputNameModelsLoop);
printf("\n-----------------------------------------------------------\n");
}
}
t = clock() - t;
timeWriteImage = ((double)t)/CLOCKS_PER_SEC; // in seconds
// PROCESS FILE OF SYNTETIC PROFILES
if(configCrontrolFile.SaveSynthesisAdjusted){
free(fitsImageLoop->pixels);
fitsImageLoop->pixels = calloc(fitsImageLoop->numPixels, sizeof(vpixels));
for( i=0;i<fitsImageLoop->numPixels;i++){
fitsImageLoop->pixels[i].spectro = calloc ((fitsImageLoop->numStokes*fitsImageLoop->nLambdas),sizeof(float));
}
for(indexPixel=0;indexPixel<fitsImageLoop->numPixels;indexPixel++)
{
int kk;
for (kk = 0; kk < (nlambda * NPARMS); kk++)
{
fitsImageLoop->pixels[indexPixel].spectro[kk] = vSpectraAjustedTotalLoop[kk+(indexPixel*(nlambda * NPARMS))] ;
}
}
// WRITE SINTHETIC PROFILES TO FITS FILE
if(configCrontrolFile.subx1 > 0 && configCrontrolFile.subx2 >0 && configCrontrolFile.suby1 > 0 && configCrontrolFile.suby2>0){
if(!writeFitsImageProfilesSubSet(outputNameSynthesisAdjustedLoop,newestFileName,fitsImageLoop,configCrontrolFile)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT PROFILES: %s",outputNameSynthesisAdjustedLoop);
printf("\n-----------------------------------------------------------\n");
}
}
else{
if(!writeFitsImageProfiles(outputNameSynthesisAdjustedLoop,newestFileName,fitsImageLoop)){
printf("\n-----------------------------------------------------------");
printf("\nERROR WRITING OUTPUT PROFILES: %s",outputNameSynthesisAdjustedLoop);
printf("\n-----------------------------------------------------------\n");
}
}
for( i=0;i<fitsImageLoop->numPixels;i++){
free(fitsImageLoop->pixels[i].spectro);
fitsImageLoop->pixels[i].spectro = NULL;
}
free(fitsImageLoop->pixels);
fitsImageLoop->pixels = NULL;
}
free(resultsInitModelTotalLoop);
free(chisqrfTotalLoop);
free(vNumIterTotalLoop);
if(configCrontrolFile.SaveSynthesisAdjusted){
free(vSpectraAjustedTotalLoop);
}
printf("\n----------------------------------------------------------------------------------------------------");
printf("\nCUBE %s INVERTED! EXECUTION TIME: %6.2f s", newestFileName,elapsed_execution);
printf("\nTIME TO WRITE FITS : %5.2f ", timeWriteImage);
printf("\n----------------------------------------------------------------------------------------------------\n");
freeFitsImage(fitsImageLoop);
}
}
MPI_Barrier(MPI_COMM_WORLD);
free(resultsInitModelLoop);
free(vChisqrfLoop);
free(vNumIterLoop);
free(vSpectraSplitLoop);
if(configCrontrolFile.SaveSynthesisAdjusted)
free(vSpectraAdjustedSplitLoop);
fileNew = 0;
}
}while(!exitProgram);
}
deleteList(&listFileNamesReaded);
FreeMemoryDerivedSynthesis();
fftw_free(inFilterMAC);
fftw_free(outFilterMAC);
fftw_destroy_plan(planFilterMAC);
fftw_free(inFilterMAC_DERIV);
fftw_free(outFilterMAC_DERIV);
fftw_destroy_plan(planFilterMAC_DERIV);
fftw_free(inSpectraFwMAC);
fftw_free(outSpectraFwMAC);
fftw_destroy_plan(planForwardMAC);
fftw_free(inSpectraBwMAC);
fftw_free(outSpectraBwMAC);
fftw_destroy_plan(planBackwardMAC);
if(configCrontrolFile.ConvolveWithPSF){
fftw_free(inSpectraFwPSF);
fftw_free(outSpectraFwPSF);
fftw_destroy_plan(planForwardPSF);
fftw_free(inSpectraBwPSF);
fftw_free(outSpectraBwPSF);
fftw_destroy_plan(planBackwardPSF);
fftw_free(fftw_G_PSF);
fftw_free(fftw_G_MAC_PSF);
fftw_free(fftw_G_MAC_DERIV_PSF);
fftw_free(inPSF_MAC);
fftw_free(inMulMacPSF);
fftw_free(inPSF_MAC_DERIV);
fftw_free(inMulMacPSFDeriv);
fftw_free(outConvFilters);
fftw_free(outConvFiltersDeriv);
fftw_destroy_plan(planForwardPSF_MAC);
fftw_destroy_plan(planForwardPSF_MAC_DERIV);
fftw_destroy_plan(planBackwardPSF_MAC);
fftw_destroy_plan(planBackwardPSF_MAC_DERIV);
}
if(vInputFileSpectra != NULL) free(vInputFileSpectra);
if(vInputFileSpectraParalell != NULL) free(vInputFileSpectraParalell);
if(vInputFileSpectraDiv2Parallel != NULL) free(vInputFileSpectraDiv2Parallel);
if(vOutputNameModels != NULL) free(vOutputNameModels);
if(vOutputNameModelsParalell != NULL) free(vOutputNameModelsParalell);
if(vOutputNameModelsDiv2Parallel != NULL) free(vOutputNameModelsDiv2Parallel);
if(vOutputNameSynthesisAdjusted != NULL) free(vOutputNameSynthesisAdjusted);
if(vOutputNameSynthesisAdjustedParallel != NULL) free(vOutputNameSynthesisAdjustedParallel);
if(vOutputNameSynthesisAdjustedDiv2Parallel != NULL) free(vOutputNameSynthesisAdjustedDiv2Parallel);
if(vInputFileSpectraLocal != NULL) free(vInputFileSpectraLocal);
if(vOutputNameModelsLocal != NULL) free(vOutputNameModelsLocal);
if(vOutputNameSynthesisAdjustedLocal != NULL) free(vOutputNameSynthesisAdjustedLocal);
free(cuantic);
free(wlines);
free(vGlobalLambda);
// FREE TYPE OF MPI
MPI_Type_free(&mpiInitModel);
MPI_Finalize() ;
free(G);
free(vSigma);
gsl_eigen_symmv_free (workspace);
gsl_vector_free(eval);
gsl_matrix_free(evec);
return 0;
}
| {
"alphanum_fraction": 0.6568531486,
"avg_line_length": 46.16801854,
"ext": "c",
"hexsha": "7f122ed6cd1057ce55b0231ffb8ccf2bfc293cb4",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-09-09T19:10:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-14T12:12:02.000Z",
"max_forks_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dcalc/hrt_pipeline",
"max_forks_repo_path": "p-milos/src/pmilos.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178",
"max_issues_repo_issues_event_max_datetime": "2022-03-24T14:18:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-11-05T14:03:07.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dcalc/hrt_pipeline",
"max_issues_repo_path": "p-milos/src/pmilos.c",
"max_line_length": 321,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dcalc/hrt_pipeline",
"max_stars_repo_path": "p-milos/src/pmilos.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 32365,
"size": 119529
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_blas.h>
#include <omp.h>
#include "util.h"
int main(int argc, char *argv[]) {
char* input_fileName1 = argv[1];
char* input_fileName2 = argv[2];
int N_doc_bg = atoi(argv[3]);
int N_kw = atoi(argv[4]);
int N_obs = atoi(argv[5]);
int N_iter = atoi(argv[6]);
double sec_budget = atoi(argv[7]) / 100.0;
char* output_fileName = argv[8];
int N_doc = 480000 / 2;
int fixed_padding = 2 * log(2) * (64 + log(N_doc) / log(2)) / sec_budget;
printf("Padding: %d\n", fixed_padding);
int* matrix = (int*) malloc(sizeof(int) * N_obs * N_obs);
int* matrix_bg = (int*) malloc(sizeof(int) * N_kw * N_kw);
int* matrix_padded = (int*) malloc(sizeof(int) * N_obs * N_obs);
int* true_index = (int*) malloc(sizeof(int) * N_kw);
int* permutation = (int*) malloc(sizeof(int) * N_obs);
gsl_matrix* matrix_obs;
for (int round = 0; round < 10; round++)
{
char input_fileName1_extend[40];
char input_fileName2_extend[40];
sprintf(input_fileName1_extend, "%s%d", input_fileName1, round);
sprintf(input_fileName2_extend, "%s%d", input_fileName2, round);
// Setup
struct timeval tv1,tv2;
gettimeofday(&tv1, NULL);
read_matrix(&true_index, &matrix_bg, 1.0*N_doc/N_doc_bg, N_kw, input_fileName2_extend);
read_matrix(&true_index, &matrix, 1.0, N_obs, input_fileName1_extend);
gettimeofday(&tv2, NULL);
printf("Reading done: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
fflush(stdout);
for (int iter = 0; iter < 10; iter++)
{
printf("Run %d\n", iter);
matrix_obs = gsl_matrix_alloc(N_obs, N_obs);
gettimeofday(&tv1, NULL);
pad_matrix(&matrix_padded, &matrix, N_obs, N_doc, sec_budget, fixed_padding);
gettimeofday(&tv2, NULL);
printf("Padding done: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
fflush(stdout);
gettimeofday(&tv1, NULL);
observe_matrix(matrix_obs, &matrix_padded, N_obs);
gettimeofday(&tv2, NULL);
printf("Observed matrix generated: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
fflush(stdout);
// Permute observed matrix randomly and attack
gettimeofday(&tv1, NULL);
attack(matrix_obs, &matrix_bg, &permutation, N_kw, N_obs, N_doc, sec_budget, fixed_padding, N_iter);
gettimeofday(&tv2, NULL);
printf("Main attack done: %f.\n", (tv2.tv_usec - tv1.tv_usec) / 1000000.0 + (tv2.tv_sec - tv1.tv_sec));
fflush(stdout);
char output_fileName_full[40];
sprintf(output_fileName_full, "%s%d-%d", output_fileName, round, iter);
print_result(output_fileName_full, &permutation, &true_index, N_obs);
//sprintf(output_fileName_full, "%s%d-%d-full", output_fileName, round, iter);
//print_full_result(output_fileName_full, &permutation, &true_index, N_obs);
}
}
free(matrix);
free(matrix_padded);
gsl_matrix_free(matrix_obs);
return(0);
}
double log_score(int idx1, int idx2, gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_doc, double sec_budget, int fixed_padding)
{
int idx1_m = (*permutation)[idx1];
int idx2_m = (*permutation)[idx2];
if (idx1 == idx2)
{
int N_upper = 3 * sqrt((*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]) / (double) N_doc);
int N_lower = (*matrix)[idx1_m*N_kw + idx2_m] - N_upper;
N_upper = (*matrix)[idx1_m*N_kw + idx2_m] + N_upper;
int count_total = (int) gsl_matrix_get(matrix_obs, idx1, idx2);
double score = 0;
double prob = (*matrix)[idx1_m*N_kw + idx2_m] / (double) N_doc;
for (int kk = N_lower; kk < N_upper+1; kk+=20)
score += gsl_ran_binomial_pdf(kk, prob, N_doc) * gsl_ran_laplace_pdf(count_total - fixed_padding - 2*kk, 2.0/sec_budget);
if (score == 0)
return(-500.0);
}
int n1 = (int) gsl_matrix_get(matrix_obs, idx1, idx1) - (*matrix)[idx1_m*N_kw + idx1_m];
int n2 = (int) gsl_matrix_get(matrix_obs, idx2, idx2) - (*matrix)[idx2_m*N_kw + idx2_m];
double mean = 0.5 * gsl_matrix_get(matrix_obs, idx2, idx2) / N_doc * n1 + 0.5 * gsl_matrix_get(matrix_obs, idx1, idx1) / N_doc * n2;
double var = 1.0 * (*matrix)[idx1_m*N_kw + idx2_m] / N_doc * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]);
var += 0.25 * n1 / N_doc * gsl_matrix_get(matrix_obs, idx2, idx2) * (2 * N_doc - gsl_matrix_get(matrix_obs, idx2, idx2)) / N_doc;
var += 0.25 * n2 / N_doc * gsl_matrix_get(matrix_obs, idx1, idx1) * (2 * N_doc - gsl_matrix_get(matrix_obs, idx1, idx1)) / N_doc;
int count_total = (int) gsl_matrix_get(matrix_obs, idx1, idx2);
int N_upper = 3 * sqrt((*matrix)[idx1_m*N_kw + idx2_m] * (N_doc - (*matrix)[idx1_m*N_kw + idx2_m]) / (double) N_doc);
int N_lower = (*matrix)[idx1_m*N_kw + idx2_m] - N_upper;
N_upper = (*matrix)[idx1_m*N_kw + idx2_m] + N_upper;
double score = 0;
double prob = (*matrix)[idx1_m*N_kw + idx2_m] / (double) N_doc;
for (int kk = N_lower; kk < N_upper+1; kk+=20)
score += gsl_ran_binomial_pdf(kk, prob, N_doc) * gsl_ran_gaussian_pdf(count_total - mean - kk, sqrt(var));
if (score == 0)
return(-500.0);
return(log(20*score));
}
void initial_solution(int** permutation, gsl_matrix* matrix_obs, int** matrix, int fixed_padding, int N_kw, int N_obs)
{
int* diff = (int*) malloc(sizeof(int) * N_kw);
int* index = (int*) malloc(sizeof(int) * N_kw);
int* occupied = (int*) malloc(sizeof(int) * N_kw);
for (int ii = 0; ii < N_kw; ii++)
occupied[ii] = -1;
for (int ii = 0; ii < N_obs; ii++)
{
// reset index
for (int jj = 0; jj < N_kw; jj++)
index[jj] = jj;
// compute differences
for (int jj = 0; jj < N_kw; jj++)
diff[jj] = abs(gsl_matrix_get(matrix_obs, ii, ii) - fixed_padding - 2*(*matrix)[jj*N_kw+jj]);
// sorting
for (int jj = 0; jj < N_kw-1; jj++)
{
for (int kk = 0; kk < N_kw-jj-1; kk++)
{
if (diff[kk] > diff[kk+1])
{
int temp = diff[kk+1];
diff[kk+1] = diff[kk];
diff[kk] = temp;
temp = index[kk+1];
index[kk+1] = index[kk];
index[kk] = temp;
}
}
}
// use the smallest index available
int idx = 0;
while (occupied[idx] > 0)
idx++;
// update the data structures
(*permutation)[ii] = index[idx];
occupied[idx] = 1;
}
}
void attack(gsl_matrix* matrix_obs, int** matrix, int** permutation, int N_kw, int N_obs, int N_doc, double sec_budget, int fixed_padding, int N_iter)
{
// Initialise data structures
double* score_matrix = (double*) malloc(sizeof(double) * N_obs * N_obs);
double* score_row1 = (double*) malloc(sizeof(double) * N_obs);
double* score_row2 = (double*) malloc(sizeof(double) * N_obs);
int* permutation_tmp = (int*) malloc(sizeof(int) * N_obs);
int* permutation_inv = (int*) malloc(sizeof(int) * N_kw);
// Initialise permutations
// Initial solution
initial_solution(permutation, matrix_obs, matrix, fixed_padding, N_kw, N_obs);
for (int ii = 0; ii < N_obs; ii++)
permutation_tmp[ii] = (*permutation)[ii];
for (int ii = 0; ii < N_kw; ii++)
permutation_inv[ii] = -1;
for (int ii = 0; ii < N_obs; ii++)
permutation_inv[permutation_tmp[ii]] = ii;
// Initialising RNG
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
struct timeval tv1,tv2;
gettimeofday(&tv1, NULL);
// Compute initial score
#pragma omp parallel for shared(score_matrix, matrix_obs, matrix)
for (int ii = 0; ii < N_obs * N_obs; ii++)
score_matrix[ii] = log_score((int) (ii / N_obs), ii % N_obs, matrix_obs, matrix, permutation, N_kw, N_doc, sec_budget, fixed_padding);
gettimeofday(&tv2, NULL);
printf("Initial score computed: %f.\n", (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec));
// Iterations of simulated annealing
double temp = (double) N_kw;
int N_stuck = 0;
for (int iter = 0; iter < N_iter; iter++)
{
/* Status code */
if (iter % (N_iter / 10) == 0)
{
gettimeofday(&tv1, NULL);
printf("Iteration: %d, %d, %d.\n", iter, N_stuck, (int) (tv1.tv_sec - tv2.tv_sec));
fflush(stdout);
gettimeofday(&tv2, NULL);
}
// used to be 10k
if (N_stuck >= N_kw * 20)
iter = N_iter;
/* Main code */
int idx1, idx2;
permutation_generation(&idx1, &idx2, &permutation_tmp, permutation, &permutation_inv, matrix_obs, matrix, fixed_padding, N_kw, N_obs, N_doc, sec_budget);
if (idx1 == idx2)
{
N_stuck += 1;
continue;
}
#pragma omp parallel for shared(score_row1)
for (int ii = 0; ii < N_obs; ii++)
score_row1[ii] = log_score(idx1, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc, sec_budget, fixed_padding);
if (idx2 >= 0)
#pragma omp parallel for shared(score_row2)
for (int ii = 0; ii < N_obs; ii++)
score_row2[ii] = log_score(idx2, ii, matrix_obs, matrix, &permutation_tmp, N_kw, N_doc, sec_budget, fixed_padding);
double score_diff = 0;
for (int ii = 0; ii < N_obs; ii++)
score_diff += score_row1[ii];
for (int ii = 0; ii < N_obs; ii++)
score_diff -= score_matrix[idx1*N_obs + ii];
if (idx2 >= 0)
{
for (int ii = 0; ii < N_obs; ii++)
score_diff += score_row2[ii];
for (int ii = 0; ii < N_obs; ii++)
score_diff -= score_matrix[idx2*N_obs + ii];
}
// compute difference in score, with exponentiation
score_diff = score_diff / temp;
if (score_diff < -40)
score_diff = 0;
else if (score_diff > 0)
score_diff = 1.01;
else
score_diff = exp(score_diff);
if (gsl_ran_flat(r, 0, 1) < score_diff)
{
// Update the scores
for (int ii = 0; ii < N_obs; ii++)
score_matrix[idx1*N_obs + ii] = score_row1[ii];
for (int ii = 0; ii < N_obs; ii++)
score_matrix[ii*N_obs + idx1] = score_row1[ii];
if (idx2 >= 0)
{
for (int ii = 0; ii < N_obs; ii++)
score_matrix[idx2*N_obs + ii] = score_row2[ii];
for (int ii = 0; ii < N_obs; ii++)
score_matrix[ii*N_obs + idx2] = score_row2[ii];
}
// Update the permutation
permutation_inv[(*permutation)[idx1]] = -1;
(*permutation)[idx1] = permutation_tmp[idx1];
permutation_inv[permutation_tmp[idx1]] = idx1;
if (idx2 >= 0)
{
(*permutation)[idx2] = permutation_tmp[idx2];
permutation_inv[permutation_tmp[idx2]] = idx2;
}
N_stuck = 0;
}
else
{
// Update the permutation
permutation_tmp[idx1] = (*permutation)[idx1];
if (idx2 >= 0)
permutation_tmp[idx2] = (*permutation)[idx2];
N_stuck += 1;
}
temp *= 0.995;
}
free(score_matrix);
free(score_row1);
free(score_row2);
gsl_rng_free(r);
}
void print_result(char* output_fileName, int** permutation, int** true_index, int N_obs)
{
FILE* fp = fopen(output_fileName, "w");
int count = 0;
for (int ii = 0; ii < N_obs; ii++)
{
//if (ii < 50)
// printf("%d, %d\n", (*permutation)[ii], (*true_index)[ii]);
if ((*permutation)[ii] == (*true_index)[ii])
count++;
}
fprintf(fp, "%d\n", count);
fclose(fp);
printf("Success: %d/%d.\n", count, N_obs);
}
void print_full_result(char* output_fileName, int** permutation, int** true_index, int N_obs)
{
FILE* fp = fopen(output_fileName, "w");
int count = 0;
for (int ii = 0; ii < N_obs; ii++)
if ((*permutation)[ii] == (*true_index)[ii])
count++;
fprintf(fp, "%d\n", count);
for (int ii = 0; ii < N_obs; ii++)
fprintf(fp, "%d,%d\n", (*permutation)[ii], (*true_index)[ii]);
fclose(fp);
} | {
"alphanum_fraction": 0.5636363636,
"avg_line_length": 35.6675749319,
"ext": "c",
"hexsha": "f6a2b17985bbd68ba4559b658ebb614779dd140e",
"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": "39602b0912b21afc45e73008e598f4377ba237eb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "RethinkingSSE/Attacks-on-SSE",
"max_forks_repo_path": "DP-EMM/attack_mp.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb",
"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": "RethinkingSSE/Attacks-on-SSE",
"max_issues_repo_path": "DP-EMM/attack_mp.c",
"max_line_length": 161,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "39602b0912b21afc45e73008e598f4377ba237eb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "RethinkingSSE/Attacks-on-SSE",
"max_stars_repo_path": "DP-EMM/attack_mp.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3788,
"size": 13090
} |
/// @file rainbow-gen-usersk.c
/// @brief A command-line tool for generating the user secret keys.
#include <rainbow_keypair.h>
#include <stdlib.h>
#include <stdio.h>
#include <api.h>
#include <utils.h>
#include <string.h>
#include <blas.h>
int main(int argc, char **argv) {
printf("%s\n", CRYPTO_ALGNAME);
printf("msk size: %lu\n", CRYPTO_MASTER_SECRET_KEY_BYTES);
printf("mpk size: %lu\n", CRYPTO_MASTER_PUBLIC_KEY_BYTES);
printf("hash size: %d\n", _HASH_LEN);
printf("signature size: %d\n\n", CRYPTO_BYTES);
if (!(4 == argc || 5 == argc)) {
printf("Usage:\n\n\trainbow-gen-usersk msk_file_name identity usk_file_name [upk_file_name]\n\n");
return -1;
}
uint8_t *_msk = malloc(CRYPTO_MASTER_SECRET_KEY_BYTES);
FILE *fp;
unsigned r;
fp = fopen(argv[1], "r");
if (NULL == fp) {
printf("fail to open master key file.\n");
return -1;
}
r = byte_fget(fp, _msk, CRYPTO_MASTER_SECRET_KEY_BYTES);
fclose(fp);
if (CRYPTO_MASTER_SECRET_KEY_BYTES != r) {
printf("fail to load key file.\n");
return -1;
}
unsigned char *_identity = malloc((_ID + 1) / 2);
r = 0;
generate_identity_hash(_identity, (unsigned char *) argv[2], strlen(argv[2]));
if (NULL == _identity) {
printf("fail to create identity hash.\n");
return -1;
}
printf("identity hash: ");
for (unsigned i = 0; i < _ID; i++) {
printf("%hhu ", gf16v_get_ele(_identity, i));
}
printf("\n\n");
uint8_t *_usk = malloc(sizeof(usk_t));
if (argc == 4) {
//calculate usk with mpk and ID
int re = calculate_usk((usk_t *) _usk, (msk_t *) _msk, _identity);
if (0 != re) {
printf("%s generate user-secret-key fails.\n", CRYPTO_ALGNAME);
return -1;
}
} else {
//calculate upk from usk (for debugging), if filename is given
uint8_t *_upk = malloc(sizeof(upk_t));
int re = calculate_usk_and_upk((usk_t *) _usk, (upk_t *) _upk, (msk_t *) _msk, _identity);
if (0 != re) {
printf("%s generate upk and usk fails.\n", CRYPTO_ALGNAME);
return -1;
}
//write upk to disk
fp = fopen(argv[4], "w+");
if (NULL == fp) {
printf("fail to write user public key file.\n");
return -1;
}
byte_fdump(fp, CRYPTO_ALGNAME " user-public-key", _upk,
CRYPTO_USER_PUBLIC_KEY_BYTES); //upk speichern und beschriften
fclose(fp);
free(_upk);
}
//write usk to disk
fp = fopen(argv[3], "w+");
if (NULL == fp) {
printf("fail to write user secret key file.\n");
return -1;
}
byte_fdump(fp, CRYPTO_ALGNAME " user secret key", _usk, sizeof(usk_t)); //usk speichern und beschriften
fclose(fp);
//free usk and rest
free(_msk);
free(_identity);
free(_usk);
return 0;
} | {
"alphanum_fraction": 0.5723951286,
"avg_line_length": 28.1523809524,
"ext": "c",
"hexsha": "1963170fed5be8d285c8c92e2f99b03882d20e71",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-01-18T14:16:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-18T14:16:30.000Z",
"max_forks_repo_head_hexsha": "f219cb091f15073c6e7f40fefbe1086f4314aae0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mnmuser/ibs-rainbow",
"max_forks_repo_path": "Reference_Implementation/rainbow-gen-usersk.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f219cb091f15073c6e7f40fefbe1086f4314aae0",
"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": "mnmuser/ibs-rainbow",
"max_issues_repo_path": "Reference_Implementation/rainbow-gen-usersk.c",
"max_line_length": 107,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f219cb091f15073c6e7f40fefbe1086f4314aae0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mnmuser/ibs-rainbow",
"max_stars_repo_path": "Reference_Implementation/rainbow-gen-usersk.c",
"max_stars_repo_stars_event_max_datetime": "2020-09-21T15:43:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-21T15:43:47.000Z",
"num_tokens": 849,
"size": 2956
} |
#include <api/components.h>
#include <api/kvstore_itf.h>
#include <common/string_view.h>
#include <common/utils.h> /* MiB */
#include <gsl/pointers> /* not_null */
#include <cstddef> /* size_t */
#include <memory> /* unique_ptr */
#include <stdexcept> /* runtime_error */
#include <string>
namespace
{
/* things which differ depending on the type of store used */
struct custom_store
{
virtual ~custom_store() {}
virtual std::size_t minimum_size(std::size_t s) const { return s; }
virtual component::uuid_t factory() const = 0;
virtual std::size_t presumed_allocation() const = 0;
virtual bool uses_numa_nodes() const { return false; }
virtual status_t rc_unknown_attribute() const { return E_NOT_SUPPORTED; }
virtual status_t rc_percent_used() const { return S_OK; }
virtual status_t rc_resize_locked() const { return E_LOCKED; }
virtual status_t rc_attribute_key_null_ptr() const { return E_BAD_PARAM; }
virtual status_t rc_attribute_key_not_found() const { return component::IKVStore::E_KEY_NOT_FOUND; }
virtual status_t rc_attribute_hashtable_expansion() const { return S_OK; }
virtual status_t rc_out_of_memory() const { return component::IKVStore::E_TOO_LARGE; }
virtual status_t rc_atomic_update() const { return S_OK; }
virtual status_t rc_allocate_pool_memory_size_0() const { return S_OK; }
virtual bool swap_updates_timestamp() const { return false; }
};
struct custom_mapstore
: public custom_store
{
virtual component::uuid_t factory() const override { return component::mapstore_factory; }
std::size_t minimum_size(std::size_t s) const override { return std::max(std::size_t(8), s); }
std::size_t presumed_allocation() const override { return 1ULL << DM_REGION_LOG_GRAIN_SIZE; }
bool uses_numa_nodes() const override { return true; }
status_t rc_unknown_attribute() const override { return E_INVALID_ARG; }
status_t rc_percent_used() const override { return rc_unknown_attribute(); }
status_t rc_resize_locked() const override { return E_INVAL; }
status_t rc_attribute_key_null_ptr() const override { return E_INVALID_ARG; }
status_t rc_attribute_key_not_found() const override { return rc_unknown_attribute(); }
status_t rc_attribute_hashtable_expansion() const override { return rc_unknown_attribute(); }
status_t rc_out_of_memory() const override { return E_INVAL; }
status_t rc_atomic_update() const override { return E_NOT_SUPPORTED; }
status_t rc_allocate_pool_memory_size_0() const override { return E_INVAL; }
};
struct custom_hstore
: public custom_store
{
virtual component::uuid_t factory() const override { return component::hstore_factory; }
std::size_t presumed_allocation() const override { return MiB(32); }
bool swap_updates_timestamp() const override { return true; }
};
struct custom_hstore_cc
: public custom_hstore
{
std::size_t presumed_allocation() const override { return MiB(32); }
};
custom_mapstore custom_mapstore_i{};
custom_hstore custom_hstore_i{};
custom_hstore_cc custom_hstore_cc_i{};
const std::map<std::string, gsl::not_null<custom_store *>, std::less<>> custom_map =
{
{ "mapstore", &custom_mapstore_i },
{ "hstore", &custom_hstore_i },
{ "hstore-cc", &custom_hstore_cc_i },
{ "hstore-mc", &custom_hstore_i },
{ "hstore-mr", &custom_hstore_i },
{ "hstore-mm", &custom_hstore_i },
};
}
gsl::not_null<custom_store *> locate_custom_store(common::string_view store)
{
const auto c_it = custom_map.find(store);
if ( c_it == custom_map.end() )
{
throw std::runtime_error(common::format("store {} not recognized", store));
}
return c_it->second;
}
auto make_kvstore(
common::string_view store
, gsl::not_null<custom_store *> c
, const component::IKVStore_factory::map_create & mc
) -> std::unique_ptr<component::IKVStore>
{
using IKVStore_factory = component::IKVStore_factory;
const std::string store_lib = "libcomponent-" + std::string(store) + ".so";
auto *comp = component::load_component(store_lib.c_str(), c->factory());
if ( ! comp )
{
throw std::runtime_error(common::format("failed to load component {}", store_lib));
}
const auto fact = make_itf_ref(static_cast<IKVStore_factory*>(comp->query_interface(IKVStore_factory::iid())));
const auto kvstore = fact->create(0, mc);
return std::unique_ptr<component::IKVStore>(kvstore);
}
| {
"alphanum_fraction": 0.7404157044,
"avg_line_length": 39.3636363636,
"ext": "h",
"hexsha": "7458b5315dbfd4895abcad64914a59bbc007585d",
"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": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "IBM/artemis",
"max_forks_repo_path": "src/components/store/test/src/make_kvstore.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1",
"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": "IBM/artemis",
"max_issues_repo_path": "src/components/store/test/src/make_kvstore.h",
"max_line_length": 112,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f655d6e952577de11b52e2f4ab6f48c73ce5dba1",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "IBM/artemis",
"max_stars_repo_path": "src/components/store/test/src/make_kvstore.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1105,
"size": 4330
} |
#pragma once
#include <sstream>
#include <gsl/string_span>
/*
String tokenizer that works like the ToEE vanilla one.
*/
class Tokenizer {
public:
explicit Tokenizer(const std::string &input) : mIn(input) {
}
bool NextToken();
bool IsQuotedString() const {
return mTokenType == TokenType::QuotedString;
}
bool IsNumber() const {
return mTokenType == TokenType::Number;
}
bool IsIdentifier() const {
return mTokenType == TokenType::Identifier;
}
bool IsIdentifier(const char *identifier) const;
const std::string &GetTokenText() const {
return mTokenText;
}
const bool& GetEnableEscapes() const {
return mEnableEscapes;
}
void SetEnableEscapes(bool enableEscapes) {
mEnableEscapes = enableEscapes;
}
int GetTokenInt() const {
return mTokenInt;
}
float GetTokenFloat() const {
return (float) mTokenFloat;
}
private:
enum class TokenType {
Number,
QuotedString,
Identifier,
Unknown
};
std::istringstream mIn;
std::string mTokenText;
TokenType mTokenType = TokenType::Unknown;
double mTokenFloat = 0;
int mTokenInt = 0;
std::string mLine; // Buffer for current line
size_t mLinePos; // Current position within mLine
int mLineNo = 0;
bool mEnableEscapes = true;
bool GetLine();
bool LineHasMoreChars() const;
bool ReadNumber();
bool ReadQuotedString();
bool ReadIdentifier();
// Character based reading on the input source
char PeekChar();
void SkipChar();
char TakeChar();
void UngetChar();
// Seeks past any control or space characters at current line pos
void SkipSpaceAndControl();
// Skips past comment at current line pos to end of line
void SkipComment();
};
| {
"alphanum_fraction": 0.7188633615,
"avg_line_length": 18.1758241758,
"ext": "h",
"hexsha": "f86d7ed5fe45785f1ef9a51ea01dae7344a1e284",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z",
"max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "edoipi/TemplePlus",
"max_forks_repo_path": "Infrastructure/include/infrastructure/tokenizer.h",
"max_issues_count": 457,
"max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "edoipi/TemplePlus",
"max_issues_repo_path": "Infrastructure/include/infrastructure/tokenizer.h",
"max_line_length": 66,
"max_stars_count": 69,
"max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "edoipi/TemplePlus",
"max_stars_repo_path": "Infrastructure/include/infrastructure/tokenizer.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z",
"num_tokens": 415,
"size": 1654
} |
// --------------------------------------------------------------------------
// 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: Erhan Kenar $
// $Authors: Vipul Patel $
// --------------------------------------------------------------------------
#ifndef OPENMS_COMPARISON_SPECTRA_COMPAREFOURIERTRANSFORM_H
#define OPENMS_COMPARISON_SPECTRA_COMPAREFOURIERTRANSFORM_H
#include <OpenMS/COMPARISON/SPECTRA/PeakSpectrumCompareFunctor.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_fft_real.h>
namespace OpenMS
{
/**
@brief Compare Discrete Cosines value from a Fourier transformation, also known as Discrete Cosines Transformation
The Direct Cosines Transformation based on the theory of the Fourier transformation.
In this class the Fast Fourier Transformation(FFT) algorithm of the gsl library is used. FFT has a run-time complexity of
n (log n). To get the Direct Cosines Transformation from a FFT there is preparation necessary. First the
input data has to be mirrored. This is necessary, because FFT needs data which has a periodic nature.
After the computation of FFT only the cosine values are important and stored in the Meta Data Array. So an inverse transformation of these values
to get the original spectrum is not available.
The comparison is done between two Meta Data Arrays, which contain the stored cosine values of their individual spectrum.
The advantage of this method is how the comparison works. There is only one sum which has to be count, no multiplication is needed.
Attention: only use the compare function, if the Spectrum was transformed earlier, else an error is going to appear.
Only use this method of transformation, if you are sure there exists enough free memory. This is a fast estimation, but it only gives one or
zero back.
@htmlinclude OpenMS_CompareFouriertransform.parameters
@ingroup SpectraComparison
*/
class OPENMS_DLLAPI CompareFouriertransform :
public PeakSpectrumCompareFunctor
{
public:
// @name Constructors and Destructors
// @{
/// default constructor
CompareFouriertransform();
/// copy constructor
CompareFouriertransform(const CompareFouriertransform & source);
/// destructor
virtual ~CompareFouriertransform();
// @}
// @name Operators
// @{
/// assignment operator
CompareFouriertransform & operator=(const CompareFouriertransform & source);
/**
@brief Dummy function
This function only returns 0 for any given PeakSpectrum, please use the other compare operator function
*/
double operator()(const PeakSpectrum &) const;
/**
@brief compare two PeakSpectrum by their Discrete Cosines Transformation.
This function compares two given PeakSpectrum about their Discrete Cosines Transformation.
First, a transformation has to be calculated. Please use the function transform() in this class, before calling this
function. The comparison works by summing the subtractions of each coefficient for all elements of both transformations. sum(_i=1)
^n x_i-y_i. If the sum is zero, both Spectra are identical in the real part and one is emitted, otherwise a zero.
*/
double operator()(const PeakSpectrum & spec1, const PeakSpectrum & spec2) const;
///
static PeakSpectrumCompareFunctor * create() { return new CompareFouriertransform(); }
///Returns the name used in the factory
static const String getProductName()
{
return "CompareFouriertransform";
}
/**
@brief calculate the Discrete Cosines Fourier Transformation.
This function transforms a given PeakSpectrum to a Discrete Cosines Fourier
Transformation. It stores only the part of the cosines of the FFT in the
FloatDataArray which is a container from the PeakSpectrum. Only call this
function, if you are sure there is no other transformation done earlier
over the same PeakSpectrum, because it isn't
checked if there already exists a transformation.
*/
void transform(PeakSpectrum & spec);
protected:
/**
@brief Search in the PeakSpectrum, if a Discrete Fourier transformation
occurs, if not an error is going to be thrown, else the index
of the occurrence is returned.
This function gives back the position, where the transformation was
saved in a FloatDataArray. If there is no entry, an error is thrown to
indicate that a transformation has to be calculated before calling this
comparison operator.
*/
UInt searchTransformation_(const PeakSpectrum & spec) const;
};
}
#endif /*OPENMS_COMPARISON_SPECTRA_COMPAREFOURIERTRANSFORM_H*/
| {
"alphanum_fraction": 0.6993984962,
"avg_line_length": 46.8309859155,
"ext": "h",
"hexsha": "b992f2827f6fb8498f54b1b36f9ab3ff39126605",
"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/COMPARISON/SPECTRA/CompareFouriertransform.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/COMPARISON/SPECTRA/CompareFouriertransform.h",
"max_line_length": 151,
"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/COMPARISON/SPECTRA/CompareFouriertransform.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": 1345,
"size": 6650
} |
#ifndef ESMCI_Mat_H
#define ESMCI_Mat_H
#include "ESMCI_Macros.h"
#include <stdexcept>
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
#include <initializer_list>
#include <complex.h>
#include <cblas.h>
#include <lapacke.h>
namespace ESMCI{
namespace MapperUtil{
/* A Matrix class
* The matrix class is used to create an n-dimensional matrix of values
*/
template<typename T>
class Matrix{
public:
Matrix(const std::vector<int> &dims, const std::vector<T> &data);
Matrix(std::initializer_list<int> dims, std::initializer_list<T> data);
Matrix(const std::vector<int> &dims, const T &val);
/* Get the matrix dimensions */
std::vector<int> get_dims(void ) const;
/* Get a reference to the data strored in the matrix */
const T *get_data_by_ref(void ) const;
T *get_data_by_ref(void );
/* Get the data stored in the matrix */
std::vector<T> get_data(void ) const;
/* Get the transpose of the matrix */
Matrix<T> transpose(void ) const;
/* Get the inverse of the matrix */
Matrix<T> inv(void ) const;
/* Get the pseudo inverse of the matrix */
Matrix<T> pinv(void ) const;
/* Returns true if the matrix, m, is equal to this matrix,
* false otherwise. This function uses a tolerance, tol, to
* compare the values stored in the matrix (unlike == that
* does not provide a tolerance)
*/
bool equals(const Matrix<T> &m, double tol) const;
/* Compare if two matrices are equal */
template<typename U>
friend bool operator==(const Matrix<U> &lhs, const Matrix<U> &rhs);
/* Compare if all values in the matrix is equal to val */
template<typename U>
friend bool operator==(const Matrix<U> &m, const U &val);
template<typename U>
friend bool operator==(const U &val, const Matrix<U> &m);
/* Operator to add/subtract/multiply two matrices */
template<typename U>
friend Matrix<U> operator+(const Matrix<U> &lhs, const Matrix<U> &rhs);
template<typename U>
friend Matrix<U> operator-(const Matrix<U> &lhs, const Matrix<U> &rhs);
template<typename U>
friend Matrix<U> operator*(const Matrix<U> &lhs, const Matrix<U> &rhs);
/* Operator to scale a matrix by a scalar */
template<typename U, typename V>
friend Matrix<U> operator*(const Matrix<U> &lhs, const V &rhs);
template<typename U, typename V>
friend Matrix<V> operator*(const U &lhs, const Matrix<V> &rhs);
template<typename U>
friend std::ostream& operator<<(std::ostream &ostr, const Matrix<U> &m);
private:
std::vector<int> dims_;
std::vector<T> data_;
};
template<typename T>
Matrix<T>::Matrix(const std::vector<int> &dims, const std::vector<T> &data):dims_(dims),data_(data)
{}
template<typename T>
Matrix<T>::Matrix(std::initializer_list<int> dims, std::initializer_list<T> data):dims_(dims.begin(),dims.end()),data_(data.begin(),data.end())
{}
template<typename T>
Matrix<T>::Matrix(const std::vector<int> &dims, const T& val):dims_(dims)
{
assert(dims.size() > 0);
int data_sz = std::accumulate(dims.begin(), dims.end(), 1, std::multiplies<int>());
assert(data_sz > 0);
data_.resize(data_sz, val);
}
template<typename T>
std::vector<int> Matrix<T>::get_dims(void ) const
{
return dims_;
}
template<typename T>
const T *Matrix<T>::get_data_by_ref(void ) const
{
return ((data_.size() > 0 ) ? (&(data_[0])) : NULL);
}
template<typename T>
T *Matrix<T>::get_data_by_ref(void )
{
return ((data_.size() > 0 ) ? (&(data_[0])) : NULL);
}
template<typename T>
std::vector<T> Matrix<T>::get_data(void ) const
{
return data_;
}
template<typename T>
Matrix<T> Matrix<T>::transpose(void ) const
{
assert(dims_.size() <= 2);
int nelems = static_cast<int>(data_.size());
if(dims_.size() == 1){
return Matrix<T>(dims_, data_);
}
else{
std::vector<int> dims(dims_.rbegin(), dims_.rend());
if((dims_[0] == 1) || dims_[1] == 1){
return Matrix<T>(dims, data_);
}
else{
// FIXME: Use inplace transpose
std::vector<T> data(data_.size(), static_cast<T>(0));
int nrows = dims_[0];
int ncols = dims_[1];
int tnrows = ncols;
int tncols = nrows;
for(int idx = 0; idx < nelems; idx++){
int ridx = idx/ncols;
int cidx = idx - ridx * ncols;
int tridx = cidx;
int tcidx = ridx;
int tidx = tridx * tncols + tcidx;
data[tidx] = data_[idx];
}
return Matrix<T>(dims, data);
}
}
}
/* Calculate the inverse of the matrix using LAPACK */
inline int LAPACK_Minv(int m, float *A)
{
lapack_int n = static_cast<lapack_int>(m);
lapack_int *ipiv = (lapack_int *)calloc(n+1, sizeof(lapack_int));
lapack_int info;
/* Calculate LU decomposition of the matrix */
info = LAPACKE_sgetrf(LAPACK_ROW_MAJOR, n, n, A, n, ipiv);
/* info == 0 => success */
if(info < 0){
std::cout << "LAPACKE_sgetrf failed, the "
<< -info << "th arg in input array, A[" << -info << "] = "
<< A[-info] << " is invalid\n";
return ESMF_FAILURE;
}
else if(info > 0){
std::cout << "LAPACKE_sgetrf failed, the U["
<< info << "," << info << "] = 0, U is singular and div by zero can occur"
<< " if used to solve a system of equations\n";
return ESMF_FAILURE;
}
/* Calculate the inverse of the matrix */
info = LAPACKE_sgetri(LAPACK_ROW_MAJOR, n, A, n, ipiv);
/* info == 0 => success */
if(info < 0){
std::cout << "LAPACKE_sgetri failed, the "
<< -info << "th arg in input array, A[" << -info << "] = "
<< A[-info] << " is invalid\n";
return ESMF_FAILURE;
}
else if(info > 0){
std::cout << "LAPACKE_sgetri failed, the U["
<< info << "," << info << "] = 0, the matrix is singular and its inverse "
<< "cannot be computed\n";
return ESMF_FAILURE;
}
free(ipiv);
return ESMF_SUCCESS;
}
/* Calculate the inverse of the matrix using LAPACK */
inline int LAPACK_Minv(int m, double *A)
{
lapack_int n = static_cast<lapack_int>(m);
lapack_int *ipiv = (lapack_int *)calloc(n+1, sizeof(lapack_int));
lapack_int info;
/* Calculate LU decomposition of the matrix */
info = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, n, n, A, n, ipiv);
/* info == 0 => success */
if(info < 0){
std::cout << "LAPACKE_dgetrf failed, the "
<< -info << "th arg in input array, A[" << -info << "] = "
<< A[-info] << " is invalid\n";
return ESMF_FAILURE;
}
else if(info > 0){
std::cout << "LAPACKE_dgetrf failed, the U["
<< info << "," << info << "] = 0, U is singular and div by zero can occur"
<< " if used to solve a system of equations\n";
return ESMF_FAILURE;
}
/* Calculate the inverse of the matrix */
info = LAPACKE_dgetri(LAPACK_ROW_MAJOR, n, A, n, ipiv);
/* info == 0 => success */
if(info < 0){
std::cout << "LAPACKE_dgetri failed, the "
<< -info << "th arg in input array, A[" << -info << "] = "
<< A[-info] << " is invalid\n";
return ESMF_FAILURE;
}
else if(info > 0){
std::cout << "LAPACKE_dgetri failed, the U["
<< info << "," << info << "] = 0, the matrix is singular and its inverse "
<< "cannot be computed\n";
return ESMF_FAILURE;
}
free(ipiv);
return ESMF_SUCCESS;
}
/* Calculate the inverse of the matrix */
template<typename T>
Matrix<T> Matrix<T>::inv(void ) const
{
Matrix<T> res = *this;
if(dims_.size() == 1){
return res;
}
// We are only concerned about 2d matrices for now
assert(dims_.size() == 2);
assert(std::adjacent_find(dims_.cbegin(), dims_.cend(), std::not_equal_to<T>()) == dims_.cend());
int ret = LAPACK_Minv(res.dims_[0], res.get_data_by_ref());
//assert(ret == ESMF_SUCCESS);
if(ret != ESMF_SUCCESS){
std::cerr << "Finding matrix inv failed for : \n" << *this << "\n";
std::string err_msg("LAPACK routine to find inv failed");
throw std::runtime_error(err_msg);
}
return res;
}
/* Compute pseudo inverse = Inverse(A_transpose * A) * A_transpose */
template<typename T>
Matrix<T> Matrix<T>::pinv(void ) const
{
Matrix<T> trans = transpose();
try{
// Left inverse
return ((trans * (*this)).inv() * trans);
}
catch(...){
// Right inverse
return (trans * ((*this) * trans).inv());
}
}
template<typename T>
bool Matrix<T>::equals(const Matrix<T> &m, double tol) const
{
std::vector<int> m_dims = m.get_dims();
std::vector<T> m_data = m.get_data();
if(m_dims != dims_){
return false;
}
if(m_data.size() != data_.size()){
return false;
}
for(typename std::vector<T>::const_iterator citer1 = m_data.cbegin(),
citer2 = data_.cbegin();
(citer1 != m_data.cend()) && (citer2 != data_.cend());
++citer1, ++citer2){
if(fabs(*citer1 - *citer2) > tol){
return false;
}
}
return true;
}
template<typename T>
bool operator==(const Matrix<T> &lhs, const Matrix<T> &rhs)
{
if(lhs.dims_ != rhs.dims_){
return false;
}
if(lhs.data_ != rhs.data_){
return false;
}
return true;
}
template<typename T>
bool operator==(const Matrix<T> &m, const T& val)
{
for(typename std::vector<T>::const_iterator citer = m.data_.cbegin();
citer != m.data_.cend(); ++citer){
if(*citer != val){
return false;
}
}
return true;
}
template<typename T>
bool operator==(const T &val, const Matrix<T> &m)
{
return (m == val);
}
template<typename T>
Matrix<T> operator+(const Matrix<T> &lhs, const Matrix<T> &rhs)
{
assert(lhs.dims_.size() == rhs.dims_.size());
assert(std::equal(lhs.dims_.begin(), lhs.dims_.end(), rhs.dims_.begin()));
Matrix<T> res = lhs;
std::transform(res.data_.begin(), res.data_.end(), rhs.data_.begin(),
res.data_.begin(), std::plus<T>());
return res;
}
template<typename U, typename V>
Matrix<U> operator+(const Matrix<U> &lhs, const V &rhs)
{
Matrix<U> res = lhs;
std::transform(res.data_.begin(), res.data_.end(),
res.data_.begin(),
std::bind1st(std::plus<U>(), static_cast<U>(rhs)));
return res;
}
template<typename U, typename V>
Matrix<V> operator+(const U &lhs, const Matrix<V> &rhs)
{
return rhs + lhs;
}
template<typename T>
Matrix<T> operator-(const Matrix<T> &lhs, const Matrix<T> &rhs)
{
assert(lhs.dims_.size() == rhs.dims_.size());
assert(std::equal(lhs.dims_.begin(), lhs.dims_.end(), rhs.dims_.begin()));
Matrix<T> res = lhs;
std::transform(res.data_.begin(), res.data_.end(), rhs.data_.begin(),
res.data_.begin(), std::minus<T>());
return res;
}
template<typename U, typename V>
Matrix<U> operator-(const Matrix<U> &lhs, const V &rhs)
{
Matrix<U> res = lhs;
std::transform(res.data_.begin(), res.data_.end(),
res.data_.begin(),
std::bind1st(std::minus<U>(), static_cast<U>(rhs)));
return res;
}
/* Multiply two matrices using BLAS
*/
inline int BLAS_Mmult(int m, int n, int k, int alpha,
const float *A, int lda, const float *B, int ldb,
int beta, float *C, int ldc)
{
/* cblas_sgemm has no return code ! */
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
return ESMF_SUCCESS;
}
/* Multiply two matrices using BLAS
*/
inline int BLAS_Mmult(int m, int n, int k, int alpha,
const double *A, int lda, const double *B, int ldb,
int beta, double *C, int ldc)
{
/* cblas_sgemm has no return code ! */
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
return ESMF_SUCCESS;
}
/* Multiply two matrices, currently uses BLAS routines for matrix
* multiplication
*/
template<typename T>
Matrix<T> operator*(const Matrix<T> &lhs, const Matrix<T> &rhs)
{
assert((lhs.dims_.size() > 0) && (rhs.dims_.size() > 0));
// No tensor products for now
assert((lhs.dims_.size() <= 2) && (rhs.dims_.size() <= 2));
assert(lhs.dims_[lhs.dims_.size()-1] == rhs.dims_[0]);
/* Determine inputs to the BLAS routine to perform
* matrix multiplication
*/
int m, n, k, alpha, lda, ldb, beta, ldc;
alpha = 1;
beta = 1;
std::vector<int> res_dims;
if(lhs.dims_.size() == 1){
res_dims.push_back(lhs.dims_[0]);
m = 1;
k = 1;
n = 1;
lda = 1;
ldb = 1;
ldc = 1;
}
else{
assert(lhs.dims_.size() == 2);
res_dims.push_back(lhs.dims_[0]);
res_dims.push_back(rhs.dims_[rhs.dims_.size()-1]);
m = lhs.dims_[0];
k = lhs.dims_[lhs.dims_.size() - 1];
n = rhs.dims_[rhs.dims_.size() - 1];
lda = k;
ldb = n;
ldc = n;
}
Matrix<T> res(res_dims, 0);
const T *A = lhs.get_data_by_ref();
const T *B = rhs.get_data_by_ref();
T *C = res.get_data_by_ref();
/* Use BLAS for multiplying the two matrices */
int ret = BLAS_Mmult(m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
assert(ret == ESMF_SUCCESS);
return res;
}
template<typename U, typename V>
Matrix<U> operator*(const Matrix<U> &lhs, const V &rhs)
{
Matrix<U> res = lhs;
std::transform(res.data_.begin(), res.data_.end(),
res.data_.begin(),
std::bind1st(std::multiplies<U>(), static_cast<U>(rhs)));
return res;
}
template<typename U, typename V>
Matrix<V> operator*(const U &lhs, const Matrix<V> &rhs)
{
return rhs * lhs;
}
template<typename T>
std::ostream& operator<<(std::ostream &ostr, const Matrix<T> &m)
{
std::vector<int> dim_wgts(m.dims_);
//std::vector<int> dim_wgts(m.dims_.size(), 0);
//std::partial_sum(m.dims_.rbegin(), m.dims_.rend(), dim_wgts.rbegin(), std::multiplies<int>());
std::vector<int> dim_wgts_counter(dim_wgts.size(), 0);
assert(dim_wgts.size() > 0);
std::size_t dim_wgts_counter_idx = dim_wgts.size() - 1;
for(typename std::vector<T>::const_iterator citer = m.data_.cbegin();
citer != m.data_.cend(); ++citer){
ostr << *citer << ", ";
dim_wgts_counter[dim_wgts_counter_idx]++;
if(dim_wgts_counter[dim_wgts_counter_idx] >=
dim_wgts[dim_wgts_counter_idx]){
while(dim_wgts_counter[dim_wgts_counter_idx]>=dim_wgts[dim_wgts_counter_idx]){
dim_wgts_counter[dim_wgts_counter_idx] = 0;
ostr << "\n";
if(dim_wgts_counter_idx > 0){
dim_wgts_counter[dim_wgts_counter_idx - 1]++;
dim_wgts_counter_idx--;
}
else{
break;
}
}
dim_wgts_counter_idx = dim_wgts.size() - 1;
}
}
return ostr;
}
} // namespace MapperUtil
} // namespace ESMCI
#endif //ESMCI_Mat_H
| {
"alphanum_fraction": 0.549515872,
"avg_line_length": 32.3128712871,
"ext": "h",
"hexsha": "f1a67170b579d4f6acee8e4ff417ebcd9972ac04",
"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": "0e1676300fc91000ecb43539cabf1f342d718fb3",
"max_forks_repo_licenses": [
"NCSA",
"Apache-2.0",
"MIT"
],
"max_forks_repo_name": "joeylamcy/gchp",
"max_forks_repo_path": "ESMF/src/Superstructure/Mapper/include/ESMCI_Mat.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "0e1676300fc91000ecb43539cabf1f342d718fb3",
"max_issues_repo_issues_event_max_datetime": "2022-03-04T16:12:02.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-04T16:12:02.000Z",
"max_issues_repo_licenses": [
"NCSA",
"Apache-2.0",
"MIT"
],
"max_issues_repo_name": "joeylamcy/gchp",
"max_issues_repo_path": "ESMF/src/Superstructure/Mapper/include/ESMCI_Mat.h",
"max_line_length": 147,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0e1676300fc91000ecb43539cabf1f342d718fb3",
"max_stars_repo_licenses": [
"NCSA",
"Apache-2.0",
"MIT"
],
"max_stars_repo_name": "joeylamcy/gchp",
"max_stars_repo_path": "ESMF/src/Superstructure/Mapper/include/ESMCI_Mat.h",
"max_stars_repo_stars_event_max_datetime": "2018-07-05T16:48:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-05T16:48:58.000Z",
"num_tokens": 4395,
"size": 16318
} |
/*
Copyright 2010-2011, D. E. Shaw Research.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* 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 D. E. Shaw Research 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
OWNER 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.
*/
#ifndef __r123_compat_gslrng_dot_h__
#define __r123_compat_gslrng_dot_h__
#include <gsl/gsl_rng.h>
#include <string.h>
/**
The macro: GSL_CBRNG(NAME, CBRNGNAME)
declares the necessary structs and constants that define a
gsl_rng_NAME type based on the counter-based RNG CBRNGNAME. For example:
Usage:
@code
#include <Random123/threefry.h>
#include <Random123/conventional/gsl_cbrng.h> // this file
GSL_CBRNG(cbrng, threefry4x32); // creates gsl_rng_cbrng
int main(int argc, char **argv){
gsl_rng *r = gsl_rng_alloc(gsl_rng_cbrng);
... use r as you would use any other gsl_rng ...
}
@endcode
It requires that NAME be the name of a CBRNG that follows the
naming and stylistic conventions of the Random123 library.
Note that wrapping a \ref CBRNG "counter-based PRNG" with a traditional API in
this way obscures much of the power of the CBRNG API.
Nevertheless, it may be of value to applications that are already
coded to work with GSL random number generators, and that wish
to use the RNGs in the Random123 library.
*/
#define GSL_CBRNG(NAME, CBRNGNAME) \
const gsl_rng_type *gsl_rng_##NAME; \
\
typedef struct{ \
CBRNGNAME##_ctr_t ctr; \
CBRNGNAME##_ctr_t r; \
CBRNGNAME##_key_t key; \
int elem; \
} NAME##_state; \
\
static unsigned long int NAME##_get(void *vstate){ \
NAME##_state *st = (NAME##_state *)vstate; \
const int N=sizeof(st->ctr.v)/sizeof(st->ctr.v[0]); \
if( st->elem == 0 ){ \
++st->ctr.v[0]; \
if( N>1 && st->ctr.v[0] == 0 ) ++st->ctr.v[1]; \
if( N>2 && st->ctr.v[1] == 0 ) ++st->ctr.v[2]; \
if( N>3 && st->ctr.v[2] == 0 ) ++st->ctr.v[3]; \
st->r = CBRNGNAME(st->ctr, st->key); \
st->elem = N; \
} \
return st->r.v[--st->elem]; \
} \
\
static double NAME##_get_double (void * vstate); \
\
static void NAME##_set(void *vstate, unsigned long int s){ \
NAME##_state *st = (NAME##_state *)vstate; \
st->elem = 0; \
/* Assume that key and ctr have an array member, v, \
as if they are r123arrayNxW. If not, this will fail \
to compile. In particular, this macro fails to compile \
when the underlying CBRNG requires use of keyinit */ \
memset(&st->ctr.v[0], 0, sizeof(st->ctr.v)); \
memset(&st->key.v[0], 0, sizeof(st->key.v)); \
/* GSL 1.15 documentation says this about gsl_rng_set: \
Note that the most generators only accept 32-bit seeds, with higher \
values being reduced modulo 2^32. For generators with smaller \
ranges the maximum seed value will typically be lower. \
so we won't jump through any hoops here to deal with \
high bits if sizeof(unsigned long) > sizeof(uint32_t). */ \
st->key.v[0] = s; \
} \
\
static const gsl_rng_type NAME##_type = { \
#NAME, \
~0UL>>((R123_W(CBRNGNAME##_ctr_t)>=8*sizeof(unsigned long))? 0 : (8*sizeof(unsigned long) - R123_W(CBRNGNAME##_ctr_t))), \
0, \
sizeof(NAME##_state), \
&NAME##_set, \
&NAME##_get, \
&NAME##_get_double \
}; \
\
static double \
NAME##_get_double (void * vstate) \
{ \
return NAME##_get (vstate)/(double)NAME##_type.max; \
} \
\
const gsl_rng_type *gsl_rng_##NAME = &NAME##_type
#endif
| {
"alphanum_fraction": 0.4545075705,
"avg_line_length": 54.9541984733,
"ext": "h",
"hexsha": "82bc90475ff632ab6626dc607c25944a64befcce",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-10-08T20:02:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-08-11T22:29:45.000Z",
"max_forks_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "maumueller/rehashing",
"max_forks_repo_path": "benchmark/askit_release/rkdtsrc/external/Random123/conventional/gsl_cbrng.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad",
"max_issues_repo_issues_event_max_datetime": "2020-10-09T04:27:39.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-10-06T09:47:52.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "maumueller/rehashing",
"max_issues_repo_path": "benchmark/askit_release/rkdtsrc/external/Random123/conventional/gsl_cbrng.h",
"max_line_length": 130,
"max_stars_count": 20,
"max_stars_repo_head_hexsha": "38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "maumueller/rehashing",
"max_stars_repo_path": "benchmark/askit_release/rkdtsrc/external/Random123/conventional/gsl_cbrng.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-22T20:48:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-14T20:08:08.000Z",
"num_tokens": 1345,
"size": 7199
} |
/*! \file allvars.h
* \brief declares global variables and structures.
*
* This file declares all global variables and structures. Further variables should be added here, and declared as
* \e \b extern. The actual existence of these variables is provided by the file \ref allvars.cxx. To produce
* \ref allvars.cxx from \ref allvars.h, do the following:
*
* \arg Erase all \#define's, typedef's, and enum's
* \arg add \#include "allvars.h", delete the \#ifndef ALLVARS_H conditional
* \arg delete all keywords 'extern'
* \arg delete all struct definitions enclosed in {...}, e.g.
* "extern struct global_data_all_processes {....} All;"
* becomes "struct global_data_all_processes All;"
*/
#ifndef ALLVARS_H
#define ALLVARS_H
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
#include <getopt.h>
#include <sys/stat.h>
#include <sys/timeb.h>
//gsl stuff
#include <gsl/gsl_heapsort.h>
//nbody code
#include <NBody.h>
#include <NBodyMath.h>
#include <KDTree.h>
#ifdef USEOPENMP
#include <omp.h>
#endif
#ifdef USEMPI
#include <mpi.h>
///Includes external global variables used for MPI version of code
#include "mpivar.h"
#endif
#include "../../src/gadgetitems.h"
#include "../../src/tipsy_structs.h"
//for morphological classifications (where tidal tails, or completely disrupted)
#define NUMMORPHCLASS 3;
#define QTIDAL 0.60
#define STIDAL 0.40
#define QLIMTIDAL 0.30
#define SLIMTIDAL 0.25
#define VFTIDAL 0.85
#define VFLIMTIDAL 0.50
#define V2TIDAL 0.6
#define V3TIDAL 0.4
#define V2LIMTIDAL 0.35
#define V3LIMTIDAL 0.30
#define ETIDAL 0.90
#define ELIMTIDAL 0.50
//number of bands in which to calculate magnitude
#define NBANDS 9
///define the particle types
//@{
#define NPARTTYPES 5
#define ALLTYPE 4
#define GASTYPE 0
#define DMTYPE 1
#define STARTYPE 2
#define BHTYPE 3
//@}
///\todo need to alter how stats are stored if one can update the number of quantiles stored
///the number of values that is used to characterize a bulk distribution
///where idea is 0=mean,1=sd,2-4=quantiles of 0.16,0.5,0.84
#define NDISTRIB 5
///max number of quantiles
#define MAXNQUANTS 11
///max number of radial bins
#define NRAD 1000
/// Structures and external variables
///for stars,gas, define lower limits for Z and sfr
#define MINGASZ 1e-7
#define MINSTARZ 1e-7
#define MINSFR 1e-3
///define sphi io block points for gadget
//@{
///self energy
#define sphioblock_u 0
///density
#define sphioblock_d 1
#ifdef SPHCOOLING
///mean molecular weight
#define sphioblock_mmw 2
///neutral hydrogen abundance
#define sphioblock_nha 3
#endif
///smoothing lengths
#define sphioblock_h
//@}
///define different reference frames
//@{
///cm ref
#define ICMFRAME 1
///particle with largest potential
#define IPOTFRAME 2
///most bound particle based in input data
#define IMBFRAME 3
//@}
///define omp number of elements threshold
#define ompunbindnum 1000
#define omppropnum 50000
///minimum number of particles for properties to be calculated
#define MINNPROP 10
///minimum number of particles for a profile to be calculated
#define MINNPROFILE 100
///minimum mass fraction of candidate structure for enclosed quantities to be useful
#define MINMASSFRAC 0.05
///some useful constants for gas
//@{
///mass of helium relative to hydrogen
#define M_HetoM_H 4.0026
//@}
using namespace std;
using namespace Math;
using namespace NBody;
///for potential calculation
struct PotInfo
{
///bucket size for tree calculation
int BucketSize;
///for tree potential calculation;
Double_t TreeThetaOpen;
///gravitational softening (here simple plummer)
Double_t eps;
///\todo When calculating the thermal internal energy of gas particles
///I should probably include some temperature floors and ceilings
///and perhaps some sound speed constrains. But I should produce
///properties of the baryonic material for all, gravitationally self-bound and grav+therm bound
PotInfo(){
BucketSize=8;
TreeThetaOpen=0.7;
eps=0.01;
}
};
///Options structure
struct Options
{
///filenames
//@{
///input particle data and output name
char *fname,*outname;
///halo catalog base name
char *halocatname;
///optional config file name
char *configname;
///optional stellar synthesis model file name
char *magname;
//@}
///number of files per particle data snapshot, if zero then tipsy file
int nfiles;
///number of files per halo catalog
int nfileshalocat;
///number of sph blocks in gadget file
int sphnio;
///defining units and cosmology
//@{
///length,m,v,grav units pressure unit, temperature
Double_t L, M, V, G, PUnit, TUnit;
///scalbodydata/utils/haloanalcode/e factor, Hubunit, h and cosmology
Double_t a,H,h, Omega_m, Omega_Lambda,rhoc;
///softening length and period (comove)
Double_t eps, p;
///background density and virial level
Double_t rhobg, virlevel;
int comove;
///for gas, mass fraction of hydrogen
Double_t Xh;
///for gas, boltzmann constant
Double_t Boltzmann;
///for gas, number of hydrogen atoms per sph particle
Double_t N_H;
///for gas, correction for helium to mass of sph particle /mh ie: Number of particles = M_p / (M_H*Xh+M_He*(1-Xh)) or even M_H*Xh+M_He*(1-Xh)*Y_Li+M_Li*(1-Xh)*(1-Y_Li) ...
Double_t N_He_corr;
///for gas, relation of specific internal energy to Temperature (u=3/2*k_B*(N_H*(Xh+(1-Xh)*N_He)*T
Double_t utoT;
///for gas, temperature threshold when calculating X-ray based spectroscopic-like temperature)
Double_t Tempthreshold;
///\todo may want some specific stuff for stars too
//@}
///store number of particles
Int_t npart[NPARTTYPES];
///structure that contains variables for potentialcalc
PotInfo pinfo;
Double_t error;
///quantile points for characterization of distribution
int nquants;
Double_t quants[MAXNQUANTS];
///minimum number a halo has to have to be analyzed
Int_t minnum;
///Kinetic/Potential Energy ratio
Double_t TVratio;
///number of mpi files that were written in parallel that must be read for group_catalog files
int mpinum;
///for calculaion of CM
Double_t cmfrac, cmadjustfac;
PotInfo uinfo;
///for calculating kinetic energy to a reference frame
int reframe;
///if no mass is stored
Double_t MassValue;
///if zoom simulations, store effective resolution
long int Neff;
///for verbose output
int verbose;
///store whether potential has been already calculated as object has been moved to particle with deepest potential well.
int ipotcalc;
///used to calculate kinetic reference frame about particle at bottom of potential well
Int_t Nbref;
Double_t fracbref;
///input STF/VELOCIraptor format flags
//@{
int iseparatefiles,ibinaryin;
//@}
///output format
int ibinaryout;
Options()
{
fname=outname=halocatname=NULL;
nfiles=1;
sphnio=2;
nfileshalocat=1;
L = 1.0;
M = 1.0;
V = 1.0;
PUnit=5.588e-14;//(assumes T in kelvin) makes pressure into ergs/cm^3 assuming standard gadget units (this is boltzmann's constant / proton mass *Massunit_g/(Lengthunit_cm)^3
TUnit=1.0;
MassValue=1.0;
p = 0.0;
a = 1.0;
H = 0.1;
h = 1.0;
Omega_m = 1.0;
Omega_Lambda = 0.0;
rhobg = 1.0;
virlevel = 50.;
comove=0;
G = 43.01;//for G in units of (km/s)^2 Mpc/1e10 Msun
rhoc=27.753;//for same units as above, of course missing factors of h^2
G = 43021.1349;//for G in units of (km/s)^2 kpc/1e10 Msun
rhoc=2.7753e-8;
Xh=0.76;
Boltzmann=log(6.94107285)-70.0*log(10.0); //ln of boltzmann in units of K^(-1) (km/s)^2 (1e10 Msun)
N_H=log(1.1892)+67.0*log(10.0); //number of hydrogen atoms per 10^10 Msun
N_He_corr=-log(Xh+M_HetoM_H*(1.0-Xh));
utoT=log(1.5)+Boltzmann+N_H+N_He_corr;
Tempthreshold=7.0*log(10.0);
error=1e-3;
nquants=3;
quants[0]=0.16;quants[1]=0.5;quants[2]=0.84;
for (int i=0;i<NPARTTYPES;i++) npart[i]=0;
minnum=20;
TVratio=-1.0;
mpinum=0;
cmfrac=0.1;
cmadjustfac=0.7;
Neff=-1;
reframe=IPOTFRAME;
verbose=0;
ipotcalc=1;
Nbref=10;
fracbref=0.05;
iseparatefiles=0;
ibinaryin=0;
ibinaryout=0;
}
};
///Radial profile data in spherical shells
struct RadPropData
{
///To store radial profiles
//@{
Int_t nbins;
int ptype;
Double_t *numinbin;
Double_t *radval;
Double_t *Menc;
Coordinate *velenc;
Matrix *sigmavenc;
Coordinate *Jenc;
Double_t *qenc;
Double_t *senc;
Matrix *eigvecenc;
///primarily for sph particles
Double_t *Den;
///gas/star particle info
Double_t *Tempenc;
Double_t *Tdispenc;
Double_t *Temenc;
Double_t *Tslenc;
#ifdef RADIATIVE
Double_t *Zmetenc;
Double_t *Tageenc;
#endif
//@}
RadPropData(){
//for (int i=0;i<NRAD;i++) {numinbin[i]=radval[i]=Menc[i]=0.;Jenc[i]=Coordinate(0,0,0);velenc[i]=Coordinate(0,0,0);qenc[i]=senc[i]=1.0;}
ptype=DMTYPE;
numinbin=NULL;radval=NULL;Menc=NULL;velenc=NULL;sigmavenc=NULL;Jenc=NULL;qenc=NULL;senc=NULL;eigvecenc=NULL;
Den=NULL;Tempenc=NULL;Tdispenc=NULL;Temenc=NULL;Tslenc=NULL;
#ifdef RADIATIVE
Zmetenc=NULL;
Tageenc=NULL;
#endif
}
void SetBins(int N) {
nbins=N;
if(numinbin!=NULL) delete[] numinbin;numinbin=new Double_t[nbins];
if(radval!=NULL) delete[] radval;radval=new Double_t[nbins];
if(Menc!=NULL) delete[] Menc;Menc=new Double_t[nbins];
if(velenc!=NULL) delete[] velenc;velenc=new Coordinate[nbins];
if(sigmavenc!=NULL) delete[] sigmavenc;sigmavenc=new Matrix[nbins];
if(Jenc!=NULL) delete[] Jenc;Jenc=new Coordinate[nbins];
if(qenc!=NULL) delete[] qenc;qenc=new Double_t[nbins];
if(senc!=NULL) delete[] senc;senc=new Double_t[nbins];
if(eigvecenc!=NULL) delete[] eigvecenc;eigvecenc=new Matrix[nbins];
if(Tempenc!=NULL) delete[] Tempenc;Tempenc=new Double_t[nbins];
if(Tdispenc!=NULL) delete[] Tdispenc;Tdispenc=new Double_t[nbins];
if(Temenc!=NULL) delete[] Temenc;Temenc=new Double_t[nbins];
if(Tslenc!=NULL) delete[] Tslenc;Tslenc=new Double_t[nbins];
if(Den!=NULL) delete[] Den;Den=new Double_t[nbins];
#ifdef RADIATIVE
if(Zmetenc!=NULL) delete[] Zmetenc;Zmetenc=new Double_t[nbins];
if(Tageenc!=NULL) delete[] Tageenc;Tageenc=new Double_t[nbins];
#endif
for (int i=0;i<nbins;i++) {numinbin[i]=radval[i]=Menc[i]=0;Jenc[i]=Coordinate(0,0,0);velenc[i]=Coordinate(0,0,0);qenc[i]=senc[i]=1.0;}
for (int i=0;i<nbins;i++) {Tempenc[i]=Tdispenc[i]=Den[i]=Temenc[i]=Tslenc[i]=0.;}
}
};
///Cylindrical profile data
struct CylPropData
{
///reference axis of cylinder
Coordinate zref;
///To store cylindrical profiles
//@{
Int_t nbins;
Double_t *numinbin;
Double_t *radval;
Double_t *Menc;
Coordinate *Jenc;
Coordinate *velenc;
Matrix *sigmavenc;
Double_t *zmean;
Double_t *Rmean;
Double_t *zdisp;
Double_t *Rdisp;
Double_t *qenc;
Double_t *senc;
Matrix *eigvecenc;
///primarily for sph particles
Double_t *Den;
///gas/star particle info
Double_t *Tempenc;
Double_t *Tdispenc;
Double_t *Temenc;
Double_t *Tslenc;
#ifdef RADIATIVE
Double_t *Zmetenc;
Double_t *Tageenc;
#endif
//@}
CylPropData(){
numinbin=NULL;radval=NULL;Menc=NULL;velenc=NULL;sigmavenc=NULL;Jenc=NULL;zmean=NULL;Rmean=NULL;zdisp=NULL;Rdisp=NULL;qenc=NULL;senc=NULL;eigvecenc=NULL;
Den=NULL;Tempenc=NULL;Tdispenc=NULL;Temenc=NULL;Tslenc=NULL;
#ifdef RADIATIVE
Zmetenc=NULL;
Tageenc=NULL;
#endif
}
void SetBins(int N) {
nbins=N;
if(numinbin!=NULL) delete[] numinbin;numinbin=new Double_t[nbins];
if(radval!=NULL) delete[] radval;radval=new Double_t[nbins];
if(Menc!=NULL) delete[] Menc;Menc=new Double_t[nbins];
if(velenc!=NULL) delete[] velenc;velenc=new Coordinate[nbins];
if(sigmavenc!=NULL) delete[] sigmavenc;sigmavenc=new Matrix[nbins];
if(Jenc!=NULL) delete[] Jenc;Jenc=new Coordinate[nbins];
if(zmean!=NULL) delete[] zmean;zmean=new Double_t[nbins];
if(Rmean!=NULL) delete[] Rmean;Rmean=new Double_t[nbins];
if(zdisp!=NULL) delete[] zdisp;zdisp=new Double_t[nbins];
if(Rdisp!=NULL) delete[] Rdisp;Rdisp=new Double_t[nbins];
if(qenc!=NULL) delete[] qenc;qenc=new Double_t[nbins];
if(senc!=NULL) delete[] senc;senc=new Double_t[nbins];
if(eigvecenc!=NULL) delete[] eigvecenc;eigvecenc=new Matrix[nbins];
if(Tempenc!=NULL) delete[] Tempenc;Tempenc=new Double_t[nbins];
if(Tdispenc!=NULL) delete[] Tdispenc;Tdispenc=new Double_t[nbins];
if(Temenc!=NULL) delete[] Temenc;Temenc=new Double_t[nbins];
if(Tslenc!=NULL) delete[] Tslenc;Tslenc=new Double_t[nbins];
if(Den!=NULL) delete[] Den;Den=new Double_t[nbins];
#ifdef RADIATIVE
if(Zmetenc!=NULL) delete[] Zmetenc;Zmetenc=new Double_t[nbins];
if(Tageenc!=NULL) delete[] Tageenc;Tageenc=new Double_t[nbins];
#endif
for (int i=0;i<nbins;i++) {numinbin[i]=radval[i]=Menc[i]=0.;Jenc[i]=velenc[i]=Coordinate(0,0,0);qenc[i]=senc[i]=1.0;zmean[i]=Rmean[i]=zdisp[i]=Rdisp[i]=0.;}
for (int i=0;i<nbins;i++) {Tempenc[i]=Tdispenc[i]=Den[i]=Temenc[i]=Tslenc[i]=0.;}
}
};
///Based on PropData in \ref allvars.h of STF/VELOCIraptor
///Here the data also stores the type of particles it corresponds to
struct PropData
{
///type of structure, dm, gas, star, etc
Int_t ptype;
///number of particles
Int_t num;
///centre of mass
Coordinate gcm, gcmvel;
///Position of most bound particle
Coordinate gpos, gvel;
///physical properties regarding mass, size
Double_t gmass,gsize,gMvir,gRvir,gRmbp,gmaxvel,gRmaxvel,gMmaxvel;
///physical properties for shape/mass distribution
Double_t gq,gs;
Matrix geigvec;
///physical properties for velocity
Double_t gsigma_v;
Matrix gveldisp;
///physical properties for dynamical state
Double_t Efrac,Pot,T;
///physical properties for dynamical state for specific particle types
Double_t Efractyped[NPARTTYPES],Pottyped[NPARTTYPES],Ttyped[NPARTTYPES];
///physical properties for angular momentum
Coordinate gJ;
///metallicity, temperature, pressure,etc
Double_t Temp[NDISTRIB];
#ifdef RADIATIVE
Double_t Zmet[NDISTRIB];
///stellar age
Double_t Tage[NDISTRIB];
///luminosity, which for gas which would probably be Infrared and radio bands
Double_t LUM[NBANDS];
#endif
///To store cylindrical profiles
RadPropData radprofile;
///To store cylindrical profiles
CylPropData cylprofile;
PropData(){
num=0;
gmass=gsize=gRmaxvel=Efrac=Pot=T=gcm[0]=gcm[1]=gcm[2]=gcmvel[0]=gcmvel[1]=gcmvel[2]=0.;
gveldisp=Matrix(0.);
gq=gs=1.0;
gRmbp=0.0;
for (int i=0;i<NDISTRIB;i++)Temp[i]=0;
#ifdef RADIATIVE
for (int i=0;i<NDISTRIB;i++)Zmet[i]=Tage[i]=0.;
for (int i=0;i<NBANDS;i++)LUM[i]=0;
#endif
}
};
///used to store halo particle id data
struct HaloParticleData{
///store the halo id
long unsigned haloID;
///number of particles, eventually used to store bound number
long unsigned NumberofParticles;
///number of particles of different types, eventually used to store bound number
Int_t NumofType[NPARTTYPES];
///number of all particles
long unsigned AllNumberofParticles;
///number of all particles of different types
Int_t AllNumofType[NPARTTYPES];
///offset of halo's particle in list of all particles in structures
Int_t noffset;
///array of particle ids
long unsigned *ParticleID;
HaloParticleData(long unsigned numinhalo=0){
AllNumberofParticles=NumberofParticles=numinhalo;
if (NumberofParticles>0) {
ParticleID=new long unsigned[NumberofParticles];
}
for (int i=0;i<NPARTTYPES;i++) AllNumofType[i]=NumofType[i]=0;
}
void Alloc(long unsigned ninhalos=0){
if (AllNumberofParticles>0){
delete[] ParticleID;
}
AllNumberofParticles=NumberofParticles=ninhalos;
if (AllNumberofParticles>0) {
ParticleID=new long unsigned[NumberofParticles];
}
}
~HaloParticleData(){
if (NumberofParticles>0){
delete[] ParticleID;
}
}
};
///External types for tipsy
//@{
#define TGASTYPE 0;
#define TDARKTYPE 1;
#define TSTARTYPE 2;
//@}
///note that for grouped particles type is 10+TYPE.
#define SUBSTRUCTTYPE 10;
#endif
| {
"alphanum_fraction": 0.6663156663,
"avg_line_length": 30.2014134276,
"ext": "h",
"hexsha": "92a5622150d210fe155c95f4befb0209dd8d4f5c",
"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": "f18cb8bf088065f9361fc537d4e5858962499a21",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "broukema/VELOCIraptor-STF",
"max_forks_repo_path": "stf/analysis/baryons/allvars.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f18cb8bf088065f9361fc537d4e5858962499a21",
"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": "broukema/VELOCIraptor-STF",
"max_issues_repo_path": "stf/analysis/baryons/allvars.h",
"max_line_length": 182,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f18cb8bf088065f9361fc537d4e5858962499a21",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "broukema/VELOCIraptor-STF",
"max_stars_repo_path": "stf/analysis/baryons/allvars.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5066,
"size": 17094
} |
// Copyright (c) 2015-2016, Massachusetts Institute of Technology
// Copyright (c) 2016-2017 Sandia Corporation
// Copyright (c) 2017 NTESS, LLC.
// This file is part of the Compressed Continuous Computation (C3) Library
// Author: Alex A. Gorodetsky
// Contact: alex@alexgorodetsky.com
// 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.
//Code
#ifndef LINALG_H
#define LINALG_H
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
/* #include "/System/Library/Frameworks/Accelerate.framework/Versions/Current/Frameworks/vecLib.framework/Headers/clapack.h" */
#define dgetri_(X, Y, Z, A , B, C, D ) \
( dgetri_( (__CLPK_integer *) X, Y, (__CLPK_integer *) Z, (__CLPK_integer *) A, \
B, (__CLPK_integer *)C , (__CLPK_integer *) D) )
#define dgetrf_(X, Y, Z, A ,B, C ) \
( dgetrf_( (__CLPK_integer *) X,(__CLPK_integer *) Y, Z, (__CLPK_integer *) A, \
(__CLPK_integer *) B, (__CLPK_integer *)C ))
#define dorgqr_(X,Y,Z,A,B,C,D,E,F) \
( dorgqr_( (__CLPK_integer *) X, (__CLPK_integer *) Y, (__CLPK_integer *) Z, A, \
(__CLPK_integer *) B, C , D, (__CLPK_integer *) E, (__CLPK_integer *)F) )
#define dgeqrf_(X, Y, Z, A , B, C, D, E ) \
( dgeqrf_( (__CLPK_integer *) X, (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, \
B, C, (__CLPK_integer *) D, (__CLPK_integer *) E) )
#define dorgrq_(X,Y,Z,A,B,C,D,E,F) \
( dorgrq_( (__CLPK_integer *) X, (__CLPK_integer *) Y, (__CLPK_integer *) Z, A, \
(__CLPK_integer *) B, C , D, (__CLPK_integer *) E, (__CLPK_integer *)F) )
#define dgerqf_(X, Y, Z, A , B, C, D, E ) \
( dgerqf_( (__CLPK_integer *) X, (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, \
B, C, (__CLPK_integer *) D, (__CLPK_integer *) E) )
#define dgesdd_(X,Y,Z,A,B,C,D,E,F,G,H,I,J,K) \
( dgesdd_(X, (__CLPK_integer *)Y, (__CLPK_integer *)Z, A, (__CLPK_integer *) B,\
C,D,(__CLPK_integer *) E, F, (__CLPK_integer *) G, H, (__CLPK_integer *) I,\
(__CLPK_integer *) J, (__CLPK_integer *) K ) )
#define dgebal_(X, Y, Z, A , B, C, D, E ) \
( dgebal_( X, (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, \
(__CLPK_integer *) B, (__CLPK_integer *)C, D, (__CLPK_integer *) E) )
#define dpotrf_(X,Y,Z,A,B) \
( dpotrf_(X, (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, (__CLPK_integer *) B ))
#define dpotri_(X,Y,Z,A,B) \
( dpotri_(X, (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, (__CLPK_integer *) B ))
#define dtrtri_(X,Y,Z,A,B,C) \
( dtrtri_(X,Y, (__CLPK_integer *)Z, A, (__CLPK_integer *) B, (__CLPK_integer *) C ))
#define dgesv_(X,Y,Z,A,B,C,D,E) \
( dgesv_((__CLPK_integer *)X, (__CLPK_integer *)Y, Z, (__CLPK_integer *) A, (__CLPK_integer *) B, \
C, (__CLPK_integer *) D, (__CLPK_integer *) E))
#define dhseqr_(X, Y, Z, A , B, C, D, E,F,G,H,I,J,K ) \
( dhseqr_( X, Y, (__CLPK_integer *)Z, (__CLPK_integer *)A, \
(__CLPK_integer *) B, C, (__CLPK_integer *)D, E, F, G, (__CLPK_integer *) H, \
I, (__CLPK_integer *) J, (__CLPK_integer *)K ) )
#define dsyev_(A,B,C,D,E,F,G,H,J) \
( dsyev_(A,B,(__CLPK_integer *) C,D,(__CLPK_integer *) E,F, \
G, (__CLPK_integer *) H, (__CLPK_integer *) J) )
#define dgeev_(X, Y, Z, A , B, C, D, E,F,G,H,I,J,K ) \
( dgeev_( X, Y, (__CLPK_integer *)Z, A, \
(__CLPK_integer *) B, C, D, E, (__CLPK_integer *) F, G, (__CLPK_integer *) H, \
I, (__CLPK_integer *) J, (__CLPK_integer *)K ) )
#define dstegr_(X,Y,Z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q) \
( dstegr_(X,Y,(__CLPK_integer *)Z,A,B,C,D,\
(__CLPK_integer *)E,(__CLPK_integer *)F,G,(__CLPK_integer *)H, \
I,J,(__CLPK_integer *)K,(__CLPK_integer *)L,M,(__CLPK_integer *)N, \
(__CLPK_integer *)O,(__CLPK_integer *)P,(__CLPK_integer *)Q))
#define dgelsd_(X,Y,Z,A,B,C,D,E,F,G,H,I,J,K) \
( dgelsd_( (__CLPK_integer *)X, (__CLPK_integer *)Y, (__CLPK_integer *)Z, \
(__CLPK_doublereal *)A, (__CLPK_integer *)B, (__CLPK_doublereal *)C, \
(__CLPK_integer *)D, (__CLPK_doublereal *) E, \
(__CLPK_doublereal *)F, (__CLPK_integer *)G, (__CLPK_doublereal *)H, \
(__CLPK_integer *)I, (__CLPK_integer *)J, (__CLPK_integer *)K))
#else
/* #include <gsl/gsl_cblas.h> */
#include <cblas.h>
void dgetri_(int * X, double *Y, int * Z, int * A, double *B, int *C , int * D);
void dgetrf_(int * X,int * Y, double*Z, int * A, int * B, int *C );
void dorgqr_(int * X, int * Y, int * Z, double *A,int * B, double *C , double *D, int * E, int *F);
void dgeqrf_(int *X, int *Y, double *Z, int * A, double * B, double * C, int * D, int * E);
void dgeev_(char * X, char *Y, int * Z, double *A, int * B, double * C, double *D, double *E,
int * F, double *G, int * H, double *, int *, int *K);
void dgebal_(char *X, int *Y, double *Z, int * A, int * B, int *C, double *D, int * E);
void dhseqr_(char *X, char *Y, int *Z, int *A,int * B, double *C, int *D,
double *E, double *F, double *G, int * H, double *, int *, int *K );
void dorgrq_(int * X, int * Y, int * Z, double *A,int * B, double *C , double *D, int * E, int *F);
void dgerqf_(int * X, int *Y, double *Z, int * A, double *B, double *C, int * D, int * E);
void dgesdd_(char *X, int * Y, int *Z, double *A, int * B,double * C,double * D,
int * E,double * F, int * G, double *H, int *, int *, int * K );
void dstev_(char *X, int *Y, double *Z, double *A, double *B, int *C, double *D, int * E);
void dsyev_(char *A,char *B,int * C,double *D,int * E,double *F, double *G, int* H, int * J);
void dpotrf_(char *X, int*Y, double *Z, int * A, int * B );
void dpotri_(char *X, int*Y, double *Z, int * A, int* B);
void dtrtri_(char *X,char*Y, int *Z, double *A, int * B, int * C);
void dgesv_(int *X, int *Y, double*Z, int * A, int * B,double*C, int * D, int * E);
void dgelsd_(int *X, int *Y, int *Z, double *A, int *B, double *C,
int *D, double * E, double *F, int *G, double *H, int *,int *, int *K);
#endif
#include "matrix_util.h"
void c3linalg_multiple_vec_mat(size_t, size_t, size_t, const double *, size_t,
const double *, size_t, double *,size_t);
void c3linalg_multiple_mat_vec(size_t, size_t, size_t, const double *, size_t,
const double *, size_t, double *,size_t);
int qr(size_t, size_t, double *, size_t);
void rq_with_rmult(size_t, size_t, double *, size_t, size_t, size_t, double *, size_t);
void svd(size_t, size_t, size_t, double *, double *, double *, double *);
size_t truncated_svd(size_t, size_t, size_t, double *, double **, double **, double **, double);
size_t pinv(size_t, size_t, size_t, double *, double *, double);
double norm2(double *, int);
double norm2diff(double *, double *, int);
double mean(double *, size_t);
double mean_size_t(size_t *, size_t);
struct mat * kron(const struct mat *, const struct mat *);
void kron_col(int, int, double *, int, int, int, double *, int, double *, int);
void vec_kron(size_t, size_t, double *, size_t, size_t, size_t,
double *, size_t, double *, double, double *);
void vec_kronl(size_t, size_t, double *, size_t, size_t, size_t,
double *, size_t, long double *, double, long double *);
// decompositions
struct fiber_list{
size_t index;
double * vals;
struct fiber_list * next;
};
struct fiber_info{
size_t nfibers;
struct fiber_list * head;
};
void AddFiber(struct fiber_list **, size_t, double *, size_t);
int IndexExists(struct fiber_list *, size_t);
double * getIndex(struct fiber_list *, size_t);
void DeleteFiberList(struct fiber_list **);
struct sk_decomp {
size_t n;
size_t m;
size_t rank;
size_t * rows_kept;
size_t * cols_kept;
size_t cross_rank;
double * cross_inv;
struct fiber_info * row_vals;
struct fiber_info * col_vals;
int success;
};
void init_skf(struct sk_decomp **, size_t, size_t, size_t);
void sk_decomp_to_full(struct sk_decomp *, double *);
void free_skf(struct sk_decomp **);
/* int comp_pivots(const double *, int, int, int *); */
int maxvol_rhs(const double *, size_t, size_t, size_t *, double *); //
int skeleton(double *, size_t, size_t, size_t, size_t *, size_t *, double);
int skeleton_func(double (*A)(int,int, int, void*), void *, size_t,
size_t, size_t, size_t *, size_t *, double);
int
skeleton_func2(int (*Ap)(double *, double, size_t, size_t, double *,
void *),
void *, struct sk_decomp **, double *, double *,
double);
void linear_ls(size_t, size_t, double *, double *, double *);
#endif
| {
"alphanum_fraction": 0.6057756246,
"avg_line_length": 50.1285714286,
"ext": "h",
"hexsha": "d5ad0581e6007f648dd0837c56e6ad60f97f8ae9",
"lang": "C",
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2021-11-24T01:58:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-09-18T19:46:27.000Z",
"max_forks_repo_head_hexsha": "ecfa401306457b9476c0252dc9cc086ec3fdacfb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "goroda/Compressed-Continuous-Computation",
"max_forks_repo_path": "c3/lib_linalg/linalg.h",
"max_issues_count": 10,
"max_issues_repo_head_hexsha": "ecfa401306457b9476c0252dc9cc086ec3fdacfb",
"max_issues_repo_issues_event_max_datetime": "2022-02-22T23:49:15.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-12-18T15:50:09.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "goroda/Compressed-Continuous-Computation",
"max_issues_repo_path": "c3/lib_linalg/linalg.h",
"max_line_length": 131,
"max_stars_count": 45,
"max_stars_repo_head_hexsha": "ecfa401306457b9476c0252dc9cc086ec3fdacfb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "goroda/Compressed-Continuous-Computation",
"max_stars_repo_path": "c3/lib_linalg/linalg.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-12T21:08:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-01T18:53:31.000Z",
"num_tokens": 3189,
"size": 10527
} |
#ifndef VKST_PLAT_FS_NOTIFY_WIN32_H
#define VKST_PLAT_FS_NOTIFY_WIN32_H
#ifndef VKST_PLAT_FS_NOTIFY_H
#error "Include fs_notify.h only"
#endif
#include "fs_notify.h"
#include <gsl.h>
#include <vector>
namespace plat {
class fs_notify final : public impl::fs_notify<fs_notify> {
public:
class watch {
public:
OVERLAPPED overlapped{};
plat::filesystem::path path{};
notify_delegate delegate{};
bool recursive{false};
HANDLE handle{INVALID_HANDLE_VALUE};
std::array<BYTE, 32 * 1024> buffer{};
watch_id id{UINT32_MAX};
bool stop{false};
bool refresh(bool clear = false) noexcept;
void notify(plat::filesystem::path changed_path, DWORD action) noexcept;
watch(plat::filesystem::path p, notify_delegate d, bool r) noexcept
: path{std::move(p)}, delegate{std::move(d)}, recursive{r} {}
watch() = default;
watch(watch const&) = delete;
watch& operator=(watch const&) = delete;
~watch() noexcept;
}; // struct watch
private:
std::vector<gsl::unique_ptr<watch>> _watches;
watch_id do_add(plat::filesystem::path path,
impl::fs_notify<fs_notify>::notify_delegate delegate,
bool recursive, std::error_code& ec) noexcept;
void do_remove(watch_id id) noexcept;
void do_tick() noexcept;
friend class impl::fs_notify<fs_notify>;
}; // class fs_notify
} // namespace plat
#endif // VKST_PLAT_FS_NOTIFY_WIN32_H | {
"alphanum_fraction": 0.6959887403,
"avg_line_length": 25.8363636364,
"ext": "h",
"hexsha": "f690e3026d9f20bc06868c41cc1603254f213d12",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c",
"max_forks_repo_licenses": [
"Zlib"
],
"max_forks_repo_name": "wesleygriffin/vkst",
"max_forks_repo_path": "src/plat/fs_notify_win32.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Zlib"
],
"max_issues_repo_name": "wesleygriffin/vkst",
"max_issues_repo_path": "src/plat/fs_notify_win32.h",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5f1210ef8aeecdd2bbc3904b0cc4dd09892f239c",
"max_stars_repo_licenses": [
"Zlib"
],
"max_stars_repo_name": "wesleygriffin/vkst",
"max_stars_repo_path": "src/plat/fs_notify_win32.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 362,
"size": 1421
} |
/* Routines for manipulating evolutionary rate matrices.
*
* There is no specific object for this module. Rate matrix
* operations use square nxn ESL_DMATRIX data objects. (The rmx
* module essentially subclasses the dmx module.)
*
* An instantaneous rate matrix is usually denoted by Q. A
* conditional probability matrix (for a specific t) is usually
* denoted by P. An exchangeability matrix is denoted by E.
* A stationary residue probability vector is denoted by pi.
*
* Two important relations among these:
*
* Q in terms of E and pi:
* $Q_{ij} = E_{ij} \pi_j$ for $i \neq j$;
* $Q_{ii} = -\sum_{j \neq i} Q_{ij}$
*
* P in terms of Q and t:
* $P = e^{tQ}$
*
* Contents:
* 1. Setting standard rate matrix models.
* 2. Debugging routines for validating or dumping rate matrices.
* 3. Other routines in the exposed ratematrix API.
* 4. Benchmark driver.
* 5. Regression test driver.
* 6. Unit tests.
* 7. Test driver.
* 8. Example.
* 9. Copyright/license information.
*
*
*
* See also:
* paml - i/o of rate matrices from/to data files in PAML format
*
*/
#include "esl_config.h"
#include <math.h>
#include "easel.h"
#include "esl_composition.h"
#include "esl_dmatrix.h"
#include "esl_vectorops.h"
#include "esl_ratematrix.h"
/*****************************************************************
* 1. Setting standard rate matrix models.
*****************************************************************/
/* Function: esl_rmx_SetWAG()
* Incept: SRE, Thu Mar 8 18:00:00 2007 [Janelia]
*
* Purpose: Sets a $20 \times 20$ rate matrix <Q> to WAG parameters.
* The caller allocated <Q>.
*
* If <pi> is non-<NULL>, it provides a vector of 20 amino
* acid stationary probabilities in Easel alphabetic order,
* A..Y, and the WAG stationary probabilities are set to
* these desired $\pi_i$. If <pi> is <NULL>, the default
* WAG stationary probabilities are used.
*
* The WAG parameters are a maximum likelihood
* parameterization obtained by Whelan and Goldman
* \citep{WhelanGoldman01}.
*
* Note: The data table was reformatted from wag.dat by the UTILITY1
* executable in the paml module. The wag.dat file was obtained from
* \url{http://www.ebi.ac.uk/goldman/WAG/wag.dat}. A copy
* is in formats/wag.dat.
*
* Args: Q - a 20x20 rate matrix to set, allocated by caller.
* pi - desired stationary probabilities A..Y, or
* NULL to use WAG defaults.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINVAL> if <Q> isn't a 20x20 general matrix; and
* the state of <Q> is undefined.
*/
int
esl_rmx_SetWAG(ESL_DMATRIX *Q, double *pi)
{
static double wagE[190] = {
1.027040, 0.738998, 0.030295, 1.582850, 0.021352, 6.174160, 0.210494, 0.398020, 0.046730, 0.081134,
1.416720, 0.306674, 0.865584, 0.567717, 0.049931, 0.316954, 0.248972, 0.930676, 0.570025, 0.679371,
0.249410, 0.193335, 0.170135, 0.039437, 0.127395, 1.059470, 0.030450, 0.138190, 0.906265, 0.074034,
0.479855, 2.584430, 0.088836, 0.373558, 0.890432, 0.323832, 0.397915, 0.384287, 0.084805, 0.154263,
2.115170, 0.061304, 0.499462, 3.170970, 0.257555, 0.893496, 0.390482, 0.103754, 0.315124, 1.190630,
0.174100, 0.404141, 4.257460, 0.934276, 4.854020, 0.509848, 0.265256, 5.429420, 0.947198, 0.096162,
1.125560, 3.956290, 0.554236, 3.012010, 0.131528, 0.198221, 1.438550, 0.109404, 0.423984, 0.682355,
0.161444, 0.243570, 0.696198, 0.099929, 0.556896, 0.415844, 0.171329, 0.195081, 0.908598, 0.098818,
0.616783, 5.469470, 0.099921, 0.330052, 4.294110, 0.113917, 3.894900, 0.869489, 1.545260, 1.543640,
0.933372, 0.551571, 0.528191, 0.147304, 0.439157, 0.102711, 0.584665, 2.137150, 0.186979, 5.351420,
0.497671, 0.683162, 0.635346, 0.679489, 3.035500, 3.370790, 1.407660, 1.071760, 0.704939, 0.545931,
1.341820, 0.740169, 0.319440, 0.967130, 0.344739, 0.493905, 3.974230, 1.613280, 1.028870, 1.224190,
2.121110, 0.512984, 0.374866, 0.822765, 0.171903, 0.225833, 0.473307, 1.458160, 1.386980, 0.326622,
1.516120, 2.030060, 0.795384, 0.857928, 0.554413, 4.378020, 2.006010, 1.002140, 0.152335, 0.588731,
0.649892, 0.187247, 0.118358, 7.821300, 0.305434, 1.800340, 2.058450, 0.196246, 0.314887, 0.301281,
0.251849, 0.232739, 1.388230, 0.113133, 0.717070, 0.129767, 0.156557, 1.529640, 0.336983, 0.262569,
0.212483, 0.137505, 0.665309, 0.515706, 0.071917, 0.139405, 0.215737, 1.163920, 0.523742, 0.110864,
0.365369, 0.240735, 0.543833, 0.325711, 0.196303, 6.454280, 0.103604, 3.873440, 0.420170, 0.133264,
0.398618, 0.428437, 1.086000, 0.216046, 0.227710, 0.381533, 0.786993, 0.291148, 0.314730, 2.485390};
static double wagpi[20];
int i,j,z;
if (Q->m != 20 || Q->n != 20 || Q->type != eslGENERAL)
ESL_EXCEPTION(eslEINVAL, "Q must be a 20x20 general matrix");
esl_composition_WAG(wagpi);
/* 1. Transfer the wag E lower triagonal matrix directly into Q. */
z = 0;
for (i = 0; i < 20; i++)
{
Q->mx[i][i] = 0.; /* code below depends on this zero initialization */
for (j = 0; j < i; j++) {
Q->mx[i][j] = wagE[z++];
Q->mx[j][i] = Q->mx[i][j];
}
}
/* 2. Set offdiagonals Q_ij = E_ij * pi_j */
for (i = 0; i < 20; i++)
for (j = 0; j < 20; j++)
if (pi != NULL) Q->mx[i][j] *= pi[j];
else Q->mx[i][j] *= wagpi[j];
/* 3. Set diagonal Q_ii to -\sum_{i \neq j} Q_ij */
for (i = 0; i < 20; i++)
Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], 20);
/* 4. Renormalize matrix to units of 1 substitution/site. */
if (pi != NULL) esl_rmx_ScaleTo(Q, pi, 1.0);
else esl_rmx_ScaleTo(Q, wagpi, 1.0);
return eslOK;
}
/* Function: esl_rmx_SetJukesCantor()
* Incept: SRE, Thu Mar 15 13:04:56 2007 [Janelia]
*
* Purpose: Sets a 4x4 rate matrix to a Jukes-Cantor model,
* scaled to units of 1t = 1.0 substitutions/site.
*
* Note: eigenvalues of Q are 0, -4\alpha, -4\alpha, -4\alpha
*/
int
esl_rmx_SetJukesCantor(ESL_DMATRIX *Q)
{
int i,j;
double pi[4] = { 0.25, 0.25, 0.25, 0.25 };
if (Q->m != 4 || Q->n != 4 || Q->type != eslGENERAL)
ESL_EXCEPTION(eslEINVAL, "Q must be a 4x4 general matrix");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++)
{
if (i != j) Q->mx[i][j] = 1.0;
else Q->mx[i][j] = 0.0;
}
Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], 4);
}
esl_rmx_ScaleTo(Q, pi, 1.0);
return eslOK;
}
/* Function: esl_rmx_SetKimura()
* Incept: SRE, Thu Mar 15 13:08:08 2007 [Janelia]
*
* Purpose: Sets a 4x4 rate matrix to a Kimura 2-parameter
* model, given transition and transversion
* relative rates <alpha> and <beta>, respectively,
* scaled to units of 1t = 1.0 substitutions/site.
*
* Note: eigenvalues of Q are 0, -4\alpha, -2(\alpha+\beta), -2(\alpha+\beta)
*/
int
esl_rmx_SetKimura(ESL_DMATRIX *Q, double alpha, double beta)
{
int i,j;
double pi[4] = { 0.25, 0.25, 0.25, 0.25 };
if (Q->m != 4 || Q->n != 4 || Q->type != eslGENERAL)
ESL_EXCEPTION(eslEINVAL, "Q must be a 4x4 general matrix");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++)
{
if (i != j) Q->mx[i][j] = ((i+j)%2)? beta : alpha; /* even=0=transition;odd=1=transversion */
else Q->mx[i][j] = 0.0;
}
Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], 4);
}
esl_rmx_ScaleTo(Q, pi, 1.0);
return eslOK;
}
/* Function: esl_rmx_SetF81()
* Incept: SRE, Thu Mar 15 13:33:30 2007 [Janelia]
*
* Purpose: Sets a 4x4 rate matrix to the F81 model (aka
* equal-input model) given stationary base
* compositions <pi>,
* scaled to units of 1t = 1.0 substitutions/site.
*/
int
esl_rmx_SetF81(ESL_DMATRIX *Q, double *pi)
{
int i,j;
if (Q->m != 4 || Q->n != 4 || Q->type != eslGENERAL)
ESL_EXCEPTION(eslEINVAL, "Q must be a 4x4 general matrix");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++)
{
if (i != j) Q->mx[i][j] = pi[j];
else Q->mx[i][j] = 0.0;
}
Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], 4);
}
esl_rmx_ScaleTo(Q, pi, 1.0);
return eslOK;
}
/* Function: esl_rmx_SetHKY()
* Incept: SRE, Thu Aug 12 08:26:39 2004 [St. Louis]
*
* Purpose: Given stationary base composition <pi> for ACGT, and
* transition and transversion relative rates <alpha> and
* <beta> respectively, sets the matrix <Q> to be the
* corresponding HKY (Hasegawa/Kishino/Yano) DNA rate
* matrix, scaled in units of 1t= 1.0 substitutions/site
* \citep{Hasegawa85}.
*
* Args: pi - stationary base composition A..T
* alpha - relative transition rate
* beta - relative transversion rate
*
*
* Returns: <eslOK>
*
* Xref:
*/
int
esl_rmx_SetHKY( ESL_DMATRIX *Q, double *pi, double alpha, double beta)
{
int i,j;
if (Q->m != 4 || Q->n != 4 || Q->type != eslGENERAL)
ESL_EXCEPTION(eslEINVAL, "Q must be a 4x4 general matrix");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++)
{
if (i != j) Q->mx[i][j] = ((i+j)%2)? pi[j]*beta : pi[j]*alpha; /* even=0=transition;odd=1=transversion */
else Q->mx[i][j] = 0.;
}
Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], 4);
}
esl_rmx_ScaleTo(Q, pi, 1.0);
return eslOK;
}
/*****************************************************************
* 2. Debugging routines for validating or dumping rate matrices.
*****************************************************************/
/* Function: esl_rmx_ValidateP()
* Incept: SRE, Sun Mar 11 10:30:50 2007 [Janelia]
*
* Purpose: Validates a conditional probability matrix <P>, whose
* elements $P_{ij}$ represent conditional probabilities
* $P(j \mid i)$; for example in a first-order Markov
* chain, or a continuous-time Markov transition process
* where <P> is for a particular $t$.
*
* Rows must sum to one, and each element $P_{ij}$ is a
* probability $0 \leq P_{ij} \leq 1$.
*
* <tol> specifies the floating-point tolerance to which
* the row sums must equal one: <fabs(sum-1.0) <= tol>.
*
* <errbuf> is an optional error message buffer. The caller
* may pass <NULL> or a pointer to a buffer of at least
* <eslERRBUFSIZE> characters.
*
* Args: P - matrix to validate
* tol - floating-point tolerance (0.00001, for example)
* errbuf - OPTIONAL: ptr to an error buffer of at least
* <eslERRBUFSIZE> characters.
*
* Returns: <eslOK> on successful validation.
* <eslFAIL> on failure, and if a non-<NULL> <errbuf> was
* provided by the caller, a message describing
* the reason for the failure is put there.
*
* Throws: (no abnormal error conditions)
*/
int
esl_rmx_ValidateP(ESL_DMATRIX *P, double tol, char *errbuf)
{
int i,j;
double sum;
if (P->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "P must be type eslGENERAL to be validated");
for (i = 0; i < P->n; i++)
{
sum = esl_vec_DSum(P->mx[i], P->m);
if (fabs(sum-1.0) > tol) ESL_FAIL(eslFAIL, errbuf, "row %d does not sum to 1.0", i);
for (j = 0; j < P->m; j++)
if (P->mx[i][j] < 0.0 || P->mx[i][j] > 1.0)
ESL_FAIL(eslFAIL, errbuf, "element %d,%d is not a probability (%f)", i,j,P->mx[i][j]);
}
return eslOK;
}
/* Function: esl_rmx_ValidateQ()
* Incept: SRE, Sun Mar 11 10:30:50 2007 [Janelia]
*
* Purpose: Validates an instantaneous rate matrix <Q> for a
* continuous-time Markov process, whose elements $q_{ij}$
* represent instantaneous transition rates $i \rightarrow
* j$.
*
* Rows satisfy the condition that
* $q_{ii} = -\sum_{i \neq j} q_{ij}$, and also
* that $q_{ij} \geq 0$ for all $j \neq i$.
*
* <tol> specifies the floating-point tolerance to which
* that condition must hold: <fabs(sum-q_ii) <= tol>.
*
* <errbuf> is an optional error message buffer. The caller
* may pass <NULL> or a pointer to a buffer of at least
* <eslERRBUFSIZE> characters.
*
* Args: Q - rate matrix to validate
* tol - floating-point tolerance (0.00001, for example)
* errbuf - OPTIONAL: ptr to an error buffer of at least
* <eslERRBUFSIZE> characters.
*
* Returns: <eslOK> on successful validation.
* <eslFAIL> on failure, and if a non-<NULL> <errbuf> was
* provided by the caller, a message describing
* the reason for the failure is put there.
*
* Throws: (no abnormal error conditions)
*/
int
esl_rmx_ValidateQ(ESL_DMATRIX *Q, double tol, char *errbuf)
{
int i,j;
double qi;
if (Q->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "Q must be type eslGENERAL to be validated");
if (Q->n != Q->m) ESL_EXCEPTION(eslEINVAL, "a rate matrix Q must be square");
for (i = 0; i < Q->n; i++)
{
qi = 0.;
for (j = 0; j < Q->m; j++)
{
if (i != j) {
if (Q->mx[i][j] < 0.) ESL_FAIL(eslFAIL, errbuf, "offdiag elem %d,%d < 0",i,j);
qi += Q->mx[i][j];
} else {
if (Q->mx[i][j] > 0.) ESL_FAIL(eslFAIL, errbuf, "diag elem %d,%d < 0", i,j);
}
}
if (fabs(qi + Q->mx[i][i]) > tol) ESL_FAIL(eslFAIL, errbuf, "row %d does not sum to 0.0", i);
}
return eslOK;
}
/*****************************************************************
* 3. Other routines in the exposed ratematrix API.
*****************************************************************/
/* Function: esl_rmx_ScaleTo()
* Incept: SRE, Tue Jul 13 16:05:16 2004 [St. Louis]
*
* Purpose: Rescales rate matrix <Q> so that expected substitution
* rate per dt is <unit>.
*
* Expected substitution rate is:
* $\sum_i \sum_j pi_i Q_ij \forall i \neq j$
*
* <unit> typically taken to be 1.0, so time units are substitutions/site.
* An exception is PAM, where <unit> = 0.01 for 1 PAM unit.
*
* Args: Q - rate matrix to normalize
* pi - stationary residue frequencies
* unit - expected subsitution rate per dt
* (1.0 = substitutions/site; 0.01 = PAMs)
*
* Returns: <eslOK> on success, and matrix Q is rescaled.
*
* Xref: STL8/p56.
*/
int
esl_rmx_ScaleTo(ESL_DMATRIX *Q, double *pi, double unit)
{
int i,j;
double sum = 0.;
if (Q->m != Q->n || Q->type != eslGENERAL)
ESL_EXCEPTION(eslEINVAL, "Q must be a square general matrix");
for (i = 0; i < Q->m; i++)
for (j = 0; j < Q->n; j++)
if (i != j) sum += pi[i] * Q->mx[i][j];
for (i = 0; i < Q->m; i++)
for (j = 0; j < Q->n; j++)
Q->mx[i][j] *= (unit / sum);
return eslOK;
}
/* Function: esl_rmx_E2Q()
* Incept: SRE, Tue Jul 13 15:52:41 2004 [St. Louis]
*
* Purpose: Given a lower triangular matrix ($j<i$) of
* residue exchangeabilities <E>, and a stationary residue
* frequency vector <pi>; assuming $E_{ij} = E_{ji}$;
* calculates a rate matrix <Q> as
*
* $Q_{ij} = E_{ij} * \pi_j$
*
* The resulting <Q> is not normalized to any particular
* number of substitutions/site/time unit. See
* <esl_rmx_ScaleTo()> for that.
*
* Args: E - symmetric residue "exchangeabilities";
* only lower triangular entries are used.
* pi - residue frequencies at stationarity.
* Q - RETURN: rate matrix, square (NxN).
* Caller allocates the memory for this.
*
* Returns: <eslOK> on success; Q is calculated and filled in.
*
* Xref: STL8/p56.
*/
int
esl_rmx_E2Q(ESL_DMATRIX *E, double *pi, ESL_DMATRIX *Q)
{
int i,j;
if (E->n != Q->n) ESL_EXCEPTION(eslEINVAL, "E and Q sizes differ");
/* Scale all off-diagonals to pi[j] * E[i][j].
*/
for (i = 0; i < E->n; i++)
for (j = 0; j < i; j++) /* only look at lower triangle of E. */
{
Q->mx[i][j] = pi[j] * E->mx[i][j];
Q->mx[j][i] = pi[i] * E->mx[i][j];
}
/* Set diagonal to -\sum of all j != i.
*/
for (i = 0; i < Q->n; i++)
{
Q->mx[i][i] = 0.; /* makes the vector sum work for j != i */
Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], Q->n);
}
return eslOK;
}
/* Function: esl_rmx_RelativeEntropy()
* Incept: SRE, Fri Mar 23 09:18:26 2007 [Janelia]
*
* Purpose: Given a conditional substitution probability matrix <P>,
* with stationary probabilities <pi>, calculate its
* relative entropy $H$:
*
* $H_t = \sum_{ij} P(j \mid i,t) \pi_i \log_2 \frac{P(j \mid i,t)} {\pi_j}$
*
* This assumes that the stationary probabilities are the
* same as the background (null model) probabilities.
*
* Returns: the relative entropy, $H$, in bits
*/
double
esl_rmx_RelativeEntropy(ESL_DMATRIX *P, double *pi)
{
double H = 0.;
int i,j;
for (i = 0; i < P->m; i++)
for (j = 0; j < P->n; j++)
H += P->mx[i][j] * pi[i] * log(P->mx[i][j] / pi[j]);
return H / eslCONST_LOG2;
}
/* Function: esl_rmx_ExpectedScore()
* Incept: SRE, Fri Mar 23 09:32:05 2007 [Janelia]
*
* Purpose: Given a conditional substitution probability matrix <P>
* with stationary probabilities <pi>, calculate its
* expected score:
*
* $ = \sum_{ij} \pi_j \pi_i \log_2 \frac{P(j \mid i,t)} {\pi_j}$
*
* This assumes that the stationary probabilities are the
* same as the background (null model) probabilities.
*
* Returns: the expected score, in bits
*/
double
esl_rmx_ExpectedScore(ESL_DMATRIX *P, double *pi)
{
double S = 0.;
int i,j;
for (i = 0; i < P->m; i++)
for (j = 0; j < P->n; j++)
S += pi[j] * pi[i] * log(P->mx[i][j] / pi[j]);
return S / eslCONST_LOG2;
}
/*****************************************************************
* 4. Benchmark driver
*****************************************************************/
#ifdef eslRATEMATRIX_BENCHMARK
/*
without GSL:
gcc -O2 -I. -L. -o benchmark -DeslRATEMATRIX_BENCHMARK esl_ratematrix.c -leasel -lm
with GSL:
gcc -g -Wall -I. -L. -o benchmark -DeslRATEMATRIX_BENCHMARK -DHAVE_LIBGSL esl_dmatrix.c esl_ratematrix.c -leasel -lgsl -lgslcblas -lm
*/
#include <esl_config.h>
#ifdef HAVE_LIBGSL
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#endif
#include "easel.h"
#include "esl_stopwatch.h"
#include "esl_dmatrix.h"
#include "esl_ratematrix.h"
int
main(void)
{
ESL_STOPWATCH *w = NULL;
ESL_DMATRIX *Q = NULL;
ESL_DMATRIX *P = NULL;
double t = 5.0;
int esl_iterations = 100;
int i;
#ifdef HAVE_LIBGSL
gsl_matrix *Qg = NULL;
gsl_matrix *Pg = NULL;
int gsl_iterations = 100;
#endif
w = esl_stopwatch_Create();
Q = esl_dmatrix_Create(20, 20);
P = esl_dmatrix_Create(20, 20);
esl_rmx_SetWAG(Q, NULL);
esl_stopwatch_Start(w);
for (i = 0; i < esl_iterations; i++)
esl_dmx_Exp(Q, t, P);
esl_stopwatch_Stop(w);
printf("Easel takes: %g sec\n", w->user / (double) esl_iterations);
#ifdef HAVE_LIBGSL
if (esl_dmx_MorphGSL(Q, &Qg) != eslOK) esl_fatal("morph to gsl_matrix failed");
if ((Pg = gsl_matrix_alloc(20, 20)) == NULL) esl_fatal("gsl alloc failed");
gsl_matrix_scale(Qg, t);
esl_stopwatch_Start(w);
for (i = 0; i < gsl_iterations; i++)
gsl_linalg_exponential_ss(Qg, Pg, GSL_PREC_DOUBLE);
esl_stopwatch_Stop(w);
printf(" GSL takes: %g sec\n", w->user / (double) gsl_iterations);
gsl_matrix_free(Qg);
gsl_matrix_free(Pg);
#endif /*HAVE_LIBGSL*/
esl_dmatrix_Destroy(Q);
esl_dmatrix_Destroy(P);
esl_stopwatch_Destroy(w);
return 0;
}
#endif /*eslRATEMATRIX_BENCHMARK*/
/*****************************************************************
* 5. Regression test driver
*****************************************************************/
#ifdef eslRATEMATRIX_REGRESSION
#ifdef HAVE_LIBGSL
/* This tests rate matrix exponentiation against the GSL's
* undocumented implementation of a matrix exponential.
*/
/*
gcc -g -Wall -I. -L. -o ratematrix_regression -DeslRATEMATRIX_REGRESSION -DHAVE_LIBGSL esl_dmatrix.c esl_ratematrix.c -leasel -lgsl -lgslcblas -lm
*/
#include "esl_config.h"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include "easel.h"
#include "esl_dmatrix.h"
#include "esl_ratematrix.h"
int
main(void)
{
char errbuf[eslERRBUFSIZE];
char *alphabet = "ACDEFGHIKLMNPQRSTVWY";
ESL_DMATRIX *Q = NULL;
ESL_DMATRIX *P = NULL;
gsl_matrix *Qg = NULL;
gsl_matrix *Pg = NULL;
ESL_DMATRIX *Pge = NULL;
double t = 15.0;
if ((Q = esl_dmatrix_Create(20, 20)) == NULL) esl_fatal("malloc failed");
if ((P = esl_dmatrix_Create(20, 20)) == NULL) esl_fatal("malloc failed");
if (esl_rmx_SetWAG(Q, NULL) != eslOK) esl_fatal("_SetWAG() failed");
if (esl_rmx_ValidateQ(Q, 0.0001, errbuf) != eslOK) esl_fatal("Q validation failed: %s", errbuf);
if (esl_dmx_Exp(Q, t, P) != eslOK) esl_fatal("matrix exponentiation failed");
if (esl_rmx_ValidateP(P, 0.0001, errbuf) != eslOK) esl_fatal("P validation failed: %s", errbuf);
if (esl_dmx_MorphGSL(Q, &Qg) != eslOK) esl_fatal("morph to gsl_matrix failed");
if ((Pg = gsl_matrix_alloc(20, 20)) == NULL) esl_fatal("gsl alloc failed");
gsl_matrix_scale(Qg, t);
if (gsl_linalg_exponential_ss(Qg, Pg, GSL_PREC_DOUBLE) != 0) esl_fatal("gsl's exponentiation failed");
if (esl_dmx_UnmorphGSL(Pg, &Pge) != eslOK) esl_fatal("morph from gsl_matrix failed");
esl_dmatrix_Dump(stdout, P, alphabet, alphabet);
if (esl_dmatrix_Compare(Pge, P, 0.00001) != eslOK) esl_fatal("whoops, different answers.");
esl_dmatrix_Destroy(Q);
esl_dmatrix_Destroy(P);
esl_dmatrix_Destroy(Pge);
gsl_matrix_free(Qg);
gsl_matrix_free(Pg);
return 0;
}
#else
/* if we don't have GSL, then compile in a dummy main(), solely
* to quiet any tests that are verifying that all drivers compile
* and run. */
int main(void) { return 0; }
#endif /*HAVE_LIBGSL*/
#endif /*eslRATEMATRIX_REGRESSION*/
/*****************************************************************
* 6. Unit tests.
*****************************************************************/
#ifdef eslRATEMATRIX_TESTDRIVE
static void
utest_SetWAG(void)
{
char errbuf[eslERRBUFSIZE];
ESL_DMATRIX *Q = NULL;
ESL_DMATRIX *P = NULL;
double t = 50.0; /* sufficiently large to drive e^tQ to stationarity */
double pi[20];
int i;
if ((Q = esl_dmatrix_Create(20, 20)) == NULL) esl_fatal("malloc failed");
if ((P = esl_dmatrix_Create(20, 20)) == NULL) esl_fatal("malloc failed");
/* This tests that exponentiating WAG gives a stable conditional
* probability matrix solution. (It doesn't particularly test that
* WAG was set correctly, but how could we have screwed that up?)
*/
if (esl_rmx_SetWAG(Q, NULL) != eslOK) esl_fatal("_SetWAG() failed");
if (esl_dmx_Exp(Q, t, P) != eslOK) esl_fatal("matrix exponentiation failed");
if (esl_rmx_ValidateP(P, 1e-7, errbuf) != eslOK) esl_fatal("P validation failed: %s", errbuf);
if (esl_rmx_ValidateQ(Q, 1e-7, errbuf) != eslOK) esl_fatal("Q validation failed: %s", errbuf);
/* This tests setting WAG to different stationary pi's than default,
* then tests that exponentiating to large t reaches those stationaries.
*/
esl_vec_DSet(pi, 20, 0.05);
if (esl_rmx_SetWAG(Q, pi) != eslOK) esl_fatal("_SetWAG() failed");
if (esl_dmx_Exp(Q, t, P) != eslOK) esl_fatal("matrix exponentiation failed");
if (esl_rmx_ValidateP(P, 1e-7, errbuf) != eslOK) esl_fatal("P validation failed: %s", errbuf);
if (esl_rmx_ValidateQ(Q, 1e-7, errbuf) != eslOK) esl_fatal("Q validation failed: %s", errbuf);
for (i = 0; i < 20; i++)
if (esl_vec_DCompare(P->mx[i], pi, 20, 1e-7) != eslOK) esl_fatal("P didn't converge to right pi's");
esl_dmatrix_Destroy(Q);
esl_dmatrix_Destroy(P);
return;
}
#ifdef HAVE_LIBLAPACK
static void
utest_Diagonalization(void)
{
ESL_DMATRIX *P = NULL;
ESL_DMATRIX *P2 = NULL;
ESL_DMATRIX *C = NULL;
ESL_DMATRIX *D = NULL;
double *lambda = NULL; /* eigenvalues */
ESL_DMATRIX *U = NULL; /* left eigenvectors */
ESL_DMATRIX *Ui = NULL; /* inverse of U */
int i,j;
/* Create a J/C probability matrix for t=1:
* 1/4 + 3/4 e^{-4/3 at}
* 1/4 - 1/4 e^{-4/3 at}
*/
if ((P = esl_dmatrix_Create(4, 4)) == NULL) esl_fatal("malloc failed");
if ((C = esl_dmatrix_Create(4, 4)) == NULL) esl_fatal("malloc failed");
if ((Ui = esl_dmatrix_Create(4, 4)) == NULL) esl_fatal("malloc failed");
if ((D = esl_dmatrix_Create(4, 4)) == NULL) esl_fatal("malloc failed");
if ((P2 = esl_dmatrix_Create(4, 4)) == NULL) esl_fatal("malloc failed");
for (i = 0; i < 4; i++)
for (j = 0; j < 4; j++)
if (i == j) P->mx[i][j] = 0.25 + 0.75 * exp(-4./3.);
else P->mx[i][j] = 0.25 - 0.25 * exp(-4./3.);
/* Diagonalize it
*/
if (esl_dmx_Diagonalize(P, &lambda, NULL, &U, NULL) != eslOK) esl_fatal("diagonalization failed");
/* Calculate P^k by U [diag(lambda_i)]^k U^{-1}
*/
esl_dmatrix_SetZero(D);
for (i = 0; i < P->n; i++) D->mx[i][i] = lambda[i];
esl_dmx_Invert(U, Ui);
esl_dmx_Multiply(U, D, C);
esl_dmx_Multiply(C, Ui, P2);
if (esl_dmatrix_Compare(P, P2, 1e-7) != eslOK) esl_fatal("diagonalization unit test failed");
free(lambda);
esl_dmatrix_Destroy(P2);
esl_dmatrix_Destroy(Ui);
esl_dmatrix_Destroy(U);
esl_dmatrix_Destroy(D);
esl_dmatrix_Destroy(C);
esl_dmatrix_Destroy(P);
return;
}
#endif /*HAVE_LIBLAPACK*/
#endif /*eslRATEMATRIX_TESTDRIVE*/
/*****************************************************************
* 7. Test driver
*****************************************************************/
#ifdef eslRATEMATRIX_TESTDRIVE
/* gcc -g -Wall -o test -I. -L. -DeslRATEMATRIX_TESTDRIVE esl_ratematrix.c -leasel -lm
* ./test
*
* gcc -g -Wall -o test -I. -L. -DHAVE_LIBLAPACK -DeslRATEMATRIX_TESTDRIVE esl_ratematrix.c esl_dmatrix.c -leasel -llapack -lm
*/
#include "esl_config.h"
#include "easel.h"
#include "esl_ratematrix.h"
int
main(void)
{
utest_SetWAG();
#ifdef HAVE_LIBLAPACK
utest_Diagonalization();
#endif
return 0;
}
#endif /*eslRATEMATRIX_TESTDRIVE*/
/*****************************************************************
* 8. Example driver
*****************************************************************/
/*****************************************************************
* Easel - a library of C functions for biological sequence analysis
* Version h3.1b2; February 2015
* Copyright (C) 2015 Howard Hughes Medical Institute.
* Other copyrights also apply. See the COPYRIGHT file for a full list.
*
* Easel is distributed under the Janelia Farm Software License, a BSD
* license. See the LICENSE file for more details.
*
* SVN $Id: esl_ratematrix.c 849 2013-01-31 15:10:24Z eddys $
* SVN $URL: https://svn.janelia.org/eddylab/eddys/easel/branches/hmmer/3.1/esl_ratematrix.c $
*****************************************************************/
| {
"alphanum_fraction": 0.5699885616,
"avg_line_length": 33.7466827503,
"ext": "c",
"hexsha": "aee587e49c6866202eae26c886e34682f6cfe49f",
"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": "6c1beb53922471218386b7ed24e72fb093fe457c",
"max_forks_repo_licenses": [
"Linux-OpenIB"
],
"max_forks_repo_name": "YJY-98/PROSAVA",
"max_forks_repo_path": "Linux/easel/esl_ratematrix.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6c1beb53922471218386b7ed24e72fb093fe457c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Linux-OpenIB"
],
"max_issues_repo_name": "YJY-98/PROSAVA",
"max_issues_repo_path": "Linux/easel/esl_ratematrix.c",
"max_line_length": 148,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6c1beb53922471218386b7ed24e72fb093fe457c",
"max_stars_repo_licenses": [
"Linux-OpenIB"
],
"max_stars_repo_name": "YJY-98/PROSAVA",
"max_stars_repo_path": "Linux/easel/esl_ratematrix.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9249,
"size": 27976
} |
/* spdgemm.c
*
* Copyright (C) 2014 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_spmatrix.h>
#include <gsl/gsl_spblas.h>
#include <gsl/gsl_errno.h>
/*
gsl_spblas_dgemm()
Multiply two sparse matrices
Inputs: alpha - scalar factor
A - sparse matrix
B - sparse matrix
C - (output) C = alpha * A * B
Return: success or error
Notes:
1) based on CSparse routine cs_multiply
*/
int
gsl_spblas_dgemm(const double alpha, const gsl_spmatrix *A,
const gsl_spmatrix *B, gsl_spmatrix *C)
{
if (A->size2 != B->size1 || A->size1 != C->size1 || B->size2 != C->size2)
{
GSL_ERROR("matrix dimensions do not match", GSL_EBADLEN);
}
else if (A->sptype != B->sptype || A->sptype != C->sptype)
{
GSL_ERROR("matrix storage formats do not match", GSL_EINVAL);
}
else if (!GSL_SPMATRIX_ISCCS(A))
{
GSL_ERROR("compressed column format required", GSL_EINVAL);
}
else
{
int status = GSL_SUCCESS;
const size_t M = A->size1;
const size_t N = B->size2;
size_t *Bi = B->i;
size_t *Bp = B->p;
double *Bd = B->data;
size_t *w = (size_t *) A->work; /* workspace of length M */
double *x = (double *) C->work; /* workspace of length M */
size_t *Cp, *Ci;
double *Cd;
size_t j, p;
size_t nz = 0;
if (C->nzmax < A->nz + B->nz)
{
status = gsl_spmatrix_realloc(A->nz + B->nz, C);
if (status)
{
GSL_ERROR("unable to realloc matrix C", status);
}
}
/* initialize workspace to 0 */
for (j = 0; j < M; ++j)
w[j] = 0;
Cp = C->p;
Ci = C->i;
Cd = C->data;
for (j = 0; j < N; ++j)
{
if (nz + M > C->nzmax)
{
status = gsl_spmatrix_realloc(2 * C->nzmax + M, C);
if (status)
{
GSL_ERROR("unable to realloc matrix C", status);
}
/* these pointers could have changed due to reallocation */
Ci = C->i;
Cd = C->data;
}
Cp[j] = nz; /* column j of C starts here */
for (p = Bp[j]; p < Bp[j + 1]; ++p)
{
nz = gsl_spblas_scatter(A, Bi[p], Bd[p], w, x, j + 1, C, nz);
}
for (p = Cp[j]; p < nz; ++p)
Cd[p] = x[Ci[p]];
}
Cp[N] = nz;
C->nz = nz;
/* scale by alpha */
gsl_spmatrix_scale(C, alpha);
return status;
}
} /* gsl_spblas_dgemm() */
/*
gsl_spblas_scatter()
Keep a running total x -> x + alpha*A(:,j) for adding matrices together in CCS,
which will eventually be stored in C(:,j)
When a new non-zero element with row index i is found, update C->i with
the row index. C->data is updated only by the calling function after all
matrices have been added via this function.
Inputs: A - sparse matrix m-by-n
j - column index
alpha - scalar factor
w - keeps track which rows of column j have been added to C;
initialize to 0 prior to first call
x - column vector of length m
mark -
C - output matrix whose jth column will be added to A(:,j)
nz - (input/output) number of non-zeros in matrix C
Notes:
1) This function is designed to be called successively when adding multiple
matrices together. Column j of C is stored contiguously as per CCS but not
necessarily in order - ie: the row indices C->i may not be in ascending order.
2) based on CSparse routine cs_scatter
*/
size_t
gsl_spblas_scatter(const gsl_spmatrix *A, const size_t j, const double alpha,
size_t *w, double *x, const size_t mark, gsl_spmatrix *C,
size_t nz)
{
size_t p;
size_t *Ai = A->i;
size_t *Ap = A->p;
double *Ad = A->data;
size_t *Ci = C->i;
for (p = Ap[j]; p < Ap[j + 1]; ++p)
{
size_t i = Ai[p]; /* A(i,j) is nonzero */
if (w[i] < mark) /* check if row i has been stored in column j yet */
{
w[i] = mark; /* i is new entry in column j */
Ci[nz++] = i; /* add i to pattern of C(:,j) */
x[i] = alpha * Ad[p]; /* x(i) = alpha * A(i,j) */
}
else /* this (i,j) exists in C from a previous call */
{
x[i] += alpha * Ad[p]; /* add alpha*A(i,j) to C(i,j) */
}
}
return (nz) ;
} /* gsl_spblas_scatter() */
| {
"alphanum_fraction": 0.5526910049,
"avg_line_length": 29.0382513661,
"ext": "c",
"hexsha": "a58b25c4822752895bf99b3d1284b61d95e5414c",
"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": "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/spblas/spdgemm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"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": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/spblas/spdgemm.c",
"max_line_length": 85,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017",
"max_stars_repo_path": "gsl-2.4/spblas/spdgemm.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z",
"num_tokens": 1491,
"size": 5314
} |
#include <stdio.h>
#include <stdlib.h>
#include <cblas.h>
#include <sys/time.h>
#include "../ulmblas.h"
#define M 1024
#define K 128
#define N 1024
void
ULMBLAS(dgemm)(const enum Trans transA,
const enum Trans transB,
const int m,
const int n,
const int k,
const double alpha,
const double *A,
const int ldA,
const double *B,
const int ldB,
const double beta,
double *C,
const int ldC);
int main(){
// init
double (*a)[K] = (double (*)[K])malloc(sizeof(double)*M*K);
double (*b)[N] = (double (*)[N])malloc(sizeof(double)*N*K);
double (*c)[N] = (double (*)[N])malloc(sizeof(double)*M*N);
struct timeval stop, start;
for(int i=0;i<M;i++){
for(int j=0;j<K;j++){
a[i][j] = 0.33*(float)i+0.29*(float)j;
}
}
for(int i=0;i<K;i++){
for(int j=0;j<N;j++){
b[i][j] = 0.67*(float)i+0.98*(float)j;
}
}
//C=A*B^T
// openblas
for(int i=0;i<M;i++){
for(int j=0;j<N;j++){
c[i][j] = 0;
}
}
gettimeofday(&start, NULL);
cblas_dgemm(CblasRowMajor,
CblasNoTrans,
CblasNoTrans,
M,N,K,1,(double*)a,K,(double*)b,N,0,(double*)c,N);
gettimeofday(&stop, NULL);
printf("li took %lu get %lf\n", (stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec - start.tv_usec, c[1][1]);
// me
/*
for(int i=0;i<M;i++){
for(int j=0;j<N;j++){
c[i][j] = 0;
}
}
gettimeofday(&start, NULL);
for(int i=0;i<M;i++)
for(int j=0;j<N;j++){
double *cp = &c[i][j];
double *ap = a[i];
double *bp = b[j];
for(int p=0;p<K;p++){
*cp += *(ap++) * *(bp++);
}
}
gettimeofday(&stop, NULL);
printf("me took %lu get %lf\n", (stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec - start.tv_usec, c[1][1]);
*/
// ulm
for(int i=0;i<M;i++){
for(int j=0;j<N;j++){
c[i][j] = 0;
}
}
gettimeofday(&start, NULL);
ULMBLAS(dgemm)(Trans,
Trans,
M,N,K,1,(double*)a,K,(double*)b,N,0,(double*)c,N);
gettimeofday(&stop, NULL);
printf("ul took %lu get %lf\n", (stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec - start.tv_usec, c[1][1]);
return 0;
}
| {
"alphanum_fraction": 0.4833824148,
"avg_line_length": 27.0113636364,
"ext": "c",
"hexsha": "9422de977e9f348af3311e8bf20dc1672f7f7640",
"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": "cb3481ce242c88bcf9bfcb51c185ed002752c6e4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "hzhangxyz/ulmBLAS",
"max_forks_repo_path": "src/level3/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cb3481ce242c88bcf9bfcb51c185ed002752c6e4",
"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": "hzhangxyz/ulmBLAS",
"max_issues_repo_path": "src/level3/main.c",
"max_line_length": 114,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cb3481ce242c88bcf9bfcb51c185ed002752c6e4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "hzhangxyz/ulmBLAS",
"max_stars_repo_path": "src/level3/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 767,
"size": 2377
} |
#include <gsl/gsl_linalg.h>
/* user defined functions */
| {
"alphanum_fraction": 0.6949152542,
"avg_line_length": 11.8,
"ext": "h",
"hexsha": "bd27405f63ce51a305ec6317084801b471dd5db3",
"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": "bdb6c48820158e674a87985efa3335b14715f9f1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "yipf/lua-graphics",
"max_forks_repo_path": "src/yipf-gsl/yipf-gsl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bdb6c48820158e674a87985efa3335b14715f9f1",
"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": "yipf/lua-graphics",
"max_issues_repo_path": "src/yipf-gsl/yipf-gsl.h",
"max_line_length": 28,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "bdb6c48820158e674a87985efa3335b14715f9f1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "yipf/lua-graphics",
"max_stars_repo_path": "src/yipf-gsl/yipf-gsl.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T11:09:52.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-09T09:13:20.000Z",
"num_tokens": 15,
"size": 59
} |
/**
* @file feature.h
* @brief Speech recognition front end.
* @author John McDonough, Tobias Gehrig, Kenichi Kumatani, Friedrich Faubel
*/
#ifndef FEATURE_H
#define FEATURE_H
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_vector_complex.h>
#include "matrix/gslmatrix.h"
#include "stream/stream.h"
#include "common/mlist.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netdb.h>
#include <pthread.h>
#include "btk.h"
#ifdef HAVE_LIBFFTW3
#include <fftw3.h>
#endif /* #ifdef HAVE_LIBFFTW3 */
#include "feature/spectralestimator.h"
/* sflib and sndfile both define sf_perror so we put them into seperate namespaces */
namespace sndfile {
#include <sndfile.h>
}
void unpack_half_complex(gsl_vector_complex* tgt, const double* src);
void unpack_half_complex(gsl_vector_complex* tgt, const unsigned N2, const double* src, const unsigned N);
void pack_half_complex(double* tgt, const gsl_vector_complex* src, unsigned size = 0);
/**
* \defgroup AudioFeature Audio Feature Hierarchy
* This hierarchy of classes provides the capability for extracting audio
* features for use in automatic speech recognition.
*/
/*@{*/
/**
* \defgroup FileFeature File Feature.
*/
/*@{*/
// ----- definition for class `FileFeature' -----
//
class FileFeature : public VectorFloatFeatureStream {
public:
FileFeature(unsigned sz, const String& nm = "FileFeature") :
VectorFloatFeatureStream(sz, nm), feature_(NULL) {}
virtual ~FileFeature() {
if (feature_ != NULL)
gsl_matrix_float_free(feature_);
}
FileFeature& operator=(const FileFeature& f);
virtual const gsl_vector_float* next(int frame_no = -5);
unsigned size() const {
if (GSL_MATRIX_NCOLS(feature_) == 0)
throw j_error("Matrix not loaded yet.");
return (unsigned) GSL_MATRIX_NCOLS(feature_);
}
void bload(const String& fileName, bool old = false);
void copy(gsl_matrix_float* matrix);
private:
gsl_matrix_float* feature_;
};
typedef Inherit<FileFeature, VectorFloatFeatureStreamPtr> FileFeaturePtr;
/*@}*/
/**
* \defgroup ConversionbitToShort Conversion bit Short
*/
/*@{*/
// ----- definition of 'Conversion24bit2Short' -----
//
class Conversion24bit2Short : public VectorShortFeatureStream {
public:
Conversion24bit2Short(VectorCharFeatureStreamPtr& src,
const String& nm = "Conversion24bit2Short") :
VectorShortFeatureStream(src->size()/3, nm), src_(src) {};
virtual void reset() { src_->reset(); VectorShortFeatureStream::reset(); }
virtual const gsl_vector_short* next(int frame_no = -5);
private:
VectorCharFeatureStreamPtr src_;
};
typedef Inherit<Conversion24bit2Short, VectorShortFeatureStreamPtr> Conversion24bit2ShortPtr;
/*@}*/
/**
* \defgroup Conversion24bit2Float Conversion 24 bit 2 Float
*/
/*@{*/
// ----- definition of Conversion24bit2Float -----
//
class Conversion24bit2Float : public VectorFloatFeatureStream {
public:
Conversion24bit2Float(VectorCharFeatureStreamPtr& src,
const String& nm = "Conversion24bit2Float") :
VectorFloatFeatureStream(src->size()/3, nm), src_(src) {};
virtual void reset() { src_->reset(); VectorFloatFeatureStream::reset(); }
virtual const gsl_vector_float* next(int frame_no = -5);
private:
VectorCharFeatureStreamPtr src_;
};
typedef Inherit<Conversion24bit2Float, VectorFloatFeatureStreamPtr> Conversion24bit2FloatPtr;
/**
* \defgroup SampleFeature Sample Feature
*/
/*@{*/
// ----- definition for class `SampleFeature' -----
//
class SampleFeature;
typedef Inherit<SampleFeature, VectorFloatFeatureStreamPtr> SampleFeaturePtr;
class SampleFeature : public VectorFloatFeatureStream {
public:
SampleFeature(const String& fn = "", unsigned blockLen = 320,
unsigned shiftLen = 160, bool padZeros = false, const String& nm = "Sample");
virtual ~SampleFeature();
unsigned read(const String& fn, int format = 0, int samplerate = 16000,
int chX = 1, int chN = 1, int cfrom = 0, int to = -1, int outsamplerate = -1, float norm = 0.0);
void write(const String& fn, int format = sndfile::SF_FORMAT_WAV|sndfile::SF_FORMAT_PCM_16, int sampleRate = -1);
void cut(unsigned cfrom, unsigned cto);
void randomize(int startX, int endX, double sigma2);
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { cur_ = 0; VectorFloatFeatureStream::reset(); is_end_ = false; }
void exit(){ reset(); throw jiterator_error("end of samples!");}
const gsl_vector_float* data();
const gsl_vector* dataDouble();
void copySamples(SampleFeaturePtr& src, unsigned cfrom, unsigned to);
unsigned samplesN() const { return ttlsamples_; }
int getSampleRate() const { return samplerate_; }
int getChanN() const { return nChan_; }
void zeroMean();
void addWhiteNoise( float snr );
void setSamples(const gsl_vector* samples, unsigned sampleRate);
protected:
float* samples_;
float norm_;
unsigned ttlsamples_;
const unsigned shiftLen_;
int samplerate_;
int nChan_;
int format_;
unsigned cur_;
bool pad_zeros_;
gsl_vector_float* copy_fsamples_;
gsl_vector* copy_dsamples_;
private:
SampleFeature(const SampleFeature& s);
SampleFeature& operator=(const SampleFeature& s);
};
// ----- definition for class `SampleFeatureRunon' -----
//
class SampleFeatureRunon : public SampleFeature {
public:
SampleFeatureRunon(const String& fn = "", unsigned blockLen = 320,
unsigned shiftLen = 160, bool padZeros = false, const String& nm = "Sample") :
SampleFeature(fn, blockLen, shiftLen, padZeros, nm) { }
virtual void reset() { VectorFloatFeatureStream::reset(); }
virtual int frame_no() const { return (cur_ / shiftLen_) - 1; }
virtual int frameN() const { return (ttlsamples_ / shiftLen_) - 1; }
};
typedef Inherit<SampleFeatureRunon, SampleFeaturePtr> SampleFeatureRunonPtr;
/*@}*/
/**
* \defgroup IterativeSampleFeature Iterative Sample Feature for the single channel data
*/
/*@{*/
// ----- definition for class `IterativeSingleChannelSampleFeature' -----
//
class IterativeSingleChannelSampleFeature : public VectorFloatFeatureStream {
public:
public:
IterativeSingleChannelSampleFeature(unsigned blockLen = 320, const String& nm = "IterativeSingleChannelSampleFeature");
virtual ~IterativeSingleChannelSampleFeature();
void read(const String& fileName, int format = 0, int samplerate = 44100, int cfrom = 0, int cto = -1 );
unsigned samplesN() const { return ttlsamples_; }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
private:
float* samples_;
sndfile::SNDFILE* sndfile_;
sndfile::SF_INFO sfinfo_;
unsigned interval_;
unsigned blockN_;
unsigned sampleN_;
unsigned ttlsamples_;
const unsigned blockLen_;
unsigned cur_;
bool last_;
int cto_;
};
typedef Inherit<IterativeSingleChannelSampleFeature, VectorFloatFeatureStreamPtr> IterativeSingleChannelSampleFeaturePtr;
/*@}*/
/**
* \defgroup IterativeSampleFeature Iterative Sample Feature
*/
/*@{*/
// ----- definition for class `IterativeSampleFeature' -----
//
class IterativeSampleFeature : public VectorFloatFeatureStream {
public:
IterativeSampleFeature(unsigned chX, unsigned blockLen = 320, unsigned firstChanX = 0, const String& nm = "Iterative Sample");
virtual ~IterativeSampleFeature();
void read(const String& fileName, int format = 0, int samplerate = 44100, int chN = 1, int cfrom = 0, int cto = -1 );
unsigned samplesN() const { return ttlsamples_; }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
void changeFirstChannelID( unsigned firstChanX ){ firstChanX_ = firstChanX; }
private:
IterativeSampleFeature(const IterativeSampleFeature& s);
IterativeSampleFeature& operator=(const IterativeSampleFeature& s);
static float* allSamples_;
static sndfile::SNDFILE* sndfile_;
static sndfile::SF_INFO sfinfo_;
static unsigned interval_;
static unsigned blockN_;
static unsigned sampleN_;
static unsigned allSampleN_;
static unsigned ttlsamples_;
const unsigned blockLen_;
const unsigned chanX_;
unsigned firstChanX_;
unsigned cur_;
bool last_;
int cto_;
};
typedef Inherit<IterativeSampleFeature, VectorFloatFeatureStreamPtr> IterativeSampleFeaturePtr;
/*@}*/
/**
* \defgroup BlockSizeConversionFeature Block Size Conversion Feature
*/
/*@{*/
// ----- definition for class `BlockSizeConversionFeature' -----
//
class BlockSizeConversionFeature : public VectorFloatFeatureStream {
public:
BlockSizeConversionFeature(const VectorFloatFeatureStreamPtr& src,
unsigned blockLen = 320,
unsigned shiftLen = 160,
const String& nm = "BlockSizeConversionFeature");
virtual void reset() { curin_ = curout_ = 0; src_frame_no_ = -1; src_->reset(); VectorFloatFeatureStream::reset(); }
virtual const gsl_vector_float* next(int frame_no = -5);
private:
void inputLonger_();
void outputLonger_();
VectorFloatFeatureStreamPtr src_;
const unsigned inputLen_;
const unsigned blockLen_;
const unsigned shiftLen_;
const unsigned overlapLen_;
unsigned curin_;
unsigned curout_;
int src_frame_no_;
const gsl_vector_float* src_feat_;
};
typedef Inherit<BlockSizeConversionFeature, VectorFloatFeatureStreamPtr> BlockSizeConversionFeaturePtr;
/*@}*/
/**
* \defgroup BlockSizeConversionFeatureShort Block Size Conversion Feature Short
*/
/*@{*/
// ----- definition for class `BlockSizeConversionFeatureShort' -----
//
class BlockSizeConversionFeatureShort : public VectorShortFeatureStream {
public:
BlockSizeConversionFeatureShort(VectorShortFeatureStreamPtr& src,
unsigned blockLen = 320,
unsigned shiftLen = 160, const String& nm = "Block Size Conversion");
virtual void reset() { curin_ = curout_ = 0; src_->reset(); VectorShortFeatureStream::reset(); }
virtual const gsl_vector_short* next(int frame_no = -5);
private:
void inputLonger_();
void outputLonger_();
VectorShortFeatureStreamPtr src_;
const unsigned inputLen_;
const unsigned blockLen_;
const unsigned shiftLen_;
const unsigned overlapLen_;
unsigned curin_;
unsigned curout_;
const gsl_vector_short* src_feat_;
};
typedef Inherit<BlockSizeConversionFeatureShort, VectorShortFeatureStreamPtr> BlockSizeConversionFeatureShortPtr;
/*@}*/
#ifdef SMARTFLOW
namespace sflib {
#include "sflib.h"
}
/**
* \defgroup SmartFlowFeature Smart Flow Feature
*/
/*@{*/
// ----- definition for class `SmartFlowFeature' -----
//
class SmartFlowFeature : public VectorShortFeatureStream {
public:
SmartFlowFeature(sflib::sf_flow_sync* sfflow, unsigned blockLen = 320,
unsigned shiftLen = 160, const String& nm = "SmartFloatFeature") :
VectorShortFeatureStream(blockLen, nm),
sfflow_(sfflow), blockLen_(blockLen), shiftLen_(shiftLen) { }
virtual ~SmartFlowFeature() { }
virtual const gsl_vector_short* next(int frame_no = -5);
virtual void reset() { VectorShortFeatureStream::reset(); }
private:
sflib::sf_flow_sync* sfflow_;
const unsigned blockLen_;
const unsigned shiftLen_;
};
typedef Inherit<SmartFlowFeature, VectorShortFeatureStreamPtr> SmartFlowFeaturePtr;
#endif
/*@}*/
/**
* \defgroup PreemphasisFeature Preemphasis Feature
*/
/*@{*/
// ----- definition for class `PreemphasisFeature' -----
//
class PreemphasisFeature : public VectorFloatFeatureStream {
public:
PreemphasisFeature(const VectorFloatFeatureStreamPtr& samp, double mu = 0.95, const String& nm = "Preemphasis");
virtual ~PreemphasisFeature() { }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
void next_speaker();
#ifdef ENABLE_LEGACY_BTK_API
void nextSpeaker(){ next_speaker(); }
#endif
private:
VectorFloatFeatureStreamPtr samp_;
float prior_;
const double mu_;
};
typedef Inherit<PreemphasisFeature, VectorFloatFeatureStreamPtr> PreemphasisFeaturePtr;
/*@}*/
/**
* \defgroup HammingFeatureShort Hamming Feature Short
*/
/*@{*/
// ----- definition for class `HammingFeatureShort' -----
//
class HammingFeatureShort : public VectorFloatFeatureStream {
public:
HammingFeatureShort(const VectorShortFeatureStreamPtr& samp, const String& nm = "HammingShort");
virtual ~HammingFeatureShort() { delete[] window_; }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { samp_->reset(); VectorFloatFeatureStream::reset(); }
private:
VectorShortFeatureStreamPtr samp_;
unsigned windowLen_;
double* window_;
};
typedef Inherit<HammingFeatureShort, VectorFloatFeatureStreamPtr> HammingFeatureShortPtr;
/*@}*/
/**
* \defgroup HammingFeature Hamming Feature
*/
/*@{*/
// ----- definition for class `HammingFeature' -----
//
class HammingFeature : public VectorFloatFeatureStream {
public:
HammingFeature(const VectorFloatFeatureStreamPtr& samp, const String& nm = "Hamming");
virtual ~HammingFeature() { delete[] window_; }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { samp_->reset(); VectorFloatFeatureStream::reset(); }
private:
VectorFloatFeatureStreamPtr samp_;
unsigned windowLen_;
double* window_;
};
typedef Inherit<HammingFeature, VectorFloatFeatureStreamPtr> HammingFeaturePtr;
/*@}*/
/**
* \defgroup FFTFeature FFT Feature
*/
/*@{*/
// ----- definition for class `FFTFeature' -----
//
class FFTFeature : public VectorComplexFeatureStream {
public:
FFTFeature(const VectorFloatFeatureStreamPtr& samp, unsigned fftLen, const String& nm = "FFT");
virtual ~FFTFeature();
virtual const gsl_vector_complex* next(int frame_no = -5);
virtual void reset() { samp_->reset(); VectorComplexFeatureStream::reset(); }
unsigned fftLen() const { return fftLen_; }
unsigned windowLen() const { return windowLen_; }
unsigned nBlocks() const { return 4; }
unsigned subsamplerate() const { return 2; }
#ifdef ENABLE_LEGACY_BTK_API
unsigned subSampRate() { return subsamplerate(); }
#endif
private:
VectorFloatFeatureStreamPtr samp_;
unsigned fftLen_;
unsigned windowLen_;
double* samples_;
#ifdef HAVE_LIBFFTW3
fftw_plan fftwPlan_;
fftw_complex* output_;
#endif
};
typedef Inherit<FFTFeature, VectorComplexFeatureStreamPtr> FFTFeaturePtr;
/**
* \defgroup SpectralPowerFeature Spectral Power Feature
*/
/*@{*/
// ----- definition for class `SpectralPowerFeature' -----
//
class SpectralPowerFloatFeature : public VectorFloatFeatureStream {
public:
SpectralPowerFloatFeature(const VectorComplexFeatureStreamPtr& fft, unsigned powN = 0, const String& nm = "PowerFloat");
virtual ~SpectralPowerFloatFeature() { }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { fft_->reset(); VectorFloatFeatureStream::reset(); }
private:
VectorComplexFeatureStreamPtr fft_;
};
typedef Inherit<SpectralPowerFloatFeature, VectorFloatFeatureStreamPtr> SpectralPowerFloatFeaturePtr;
/*@}*/
/**
* \defgroup SpectralPowerFeature Spectral Power Feature
*/
/*@{*/
// ----- definition for class `SpectralPowerFeature' -----
//
class SpectralPowerFeature : public VectorFeatureStream {
public:
SpectralPowerFeature(const VectorComplexFeatureStreamPtr& fft, unsigned powN = 0, const String& nm = "Power");
virtual ~SpectralPowerFeature() { }
virtual const gsl_vector* next(int frame_no = -5);
virtual void reset() { fft_->reset(); VectorFeatureStream::reset(); }
private:
VectorComplexFeatureStreamPtr fft_;
};
typedef Inherit<SpectralPowerFeature, VectorFeatureStreamPtr> SpectralPowerFeaturePtr;
/*@}*/
/**
* \defgroup SignalPowerFeature Signal Power Feature
*/
/*@{*/
// ----- definition for class `SignalPowerFeature' -----
//
static const int ADCRANGE = 65536;
class SignalPowerFeature : public VectorFloatFeatureStream {
public:
SignalPowerFeature(const VectorFloatFeatureStreamPtr& samp, const String& nm = "Signal Power") :
VectorFloatFeatureStream(/* size= */ 1, nm), samp_(samp), range_(float(ADCRANGE) * float(ADCRANGE) / 4.0) { }
virtual ~SignalPowerFeature() { }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { samp_->reset(); VectorFloatFeatureStream::reset(); }
private:
VectorFloatFeatureStreamPtr samp_;
double range_;
};
typedef Inherit<SignalPowerFeature, VectorFloatFeatureStreamPtr> SignalPowerFeaturePtr;
/*@}*/
/**
* \defgroup ALogFeature A-Log Feature
*/
/*@{*/
// ----- definition for class `ALogFeature' -----
//
class ALogFeature : public VectorFloatFeatureStream {
public:
ALogFeature(const VectorFloatFeatureStreamPtr& samp, double m = 1.0, double a = 4.0,
bool runon = false, const String& nm = "ALogPower") :
VectorFloatFeatureStream(/* size= */ 1, nm), samp_(samp), m_(m), a_(a),
min_(HUGE_VAL), max_(-HUGE_VAL), minMaxFound_(false), runon_(runon) { }
virtual ~ALogFeature() { }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
void next_speaker() { min_ = HUGE_VAL; max_ = -HUGE_VAL; minMaxFound_ = false; }
#ifdef ENABLE_LEGACY_BTK_API
void nextSpeaker(){ next_speaker(); }
#endif
private:
void find_min_max_(const gsl_vector_float* block);
VectorFloatFeatureStreamPtr samp_;
double m_;
double a_;
double min_;
double max_;
bool minMaxFound_;
bool runon_;
};
typedef Inherit<ALogFeature, VectorFloatFeatureStreamPtr> ALogFeaturePtr;
/*@}*/
/**
* \defgroup NormalizeFeature Normalize Feature
*/
/*@{*/
// ----- definition for class `NormalizeFeature' -----
//
class NormalizeFeature : public VectorFloatFeatureStream {
public:
NormalizeFeature(const VectorFloatFeatureStreamPtr& samp, double min = 0.0, double max = 1.0,
bool runon = false, const String& nm = "Normalize");
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
void next_speaker() { xmin_ = HUGE_VAL; xmax_ = -HUGE_VAL; minMaxFound_ = false; }
#ifdef ENABLE_LEGACY_BTK_API
void nextSpeaker(){ next_speaker(); }
#endif
private:
void find_min_max_(const gsl_vector_float* block);
VectorFloatFeatureStreamPtr samp_;
double min_;
double max_;
double range_;
double xmin_;
double xmax_;
bool minMaxFound_;
bool runon_;
};
typedef Inherit<NormalizeFeature, VectorFloatFeatureStreamPtr> NormalizeFeaturePtr;
/*@}*/
/**
* \defgroup ThresholdFeature Threshold Feature
*/
/*@{*/
// ----- definition for class `ThresholdFeature' -----
//
class ThresholdFeature : public VectorFloatFeatureStream {
public:
ThresholdFeature(const VectorFloatFeatureStreamPtr& samp, double value = 0.0, double thresh = 1.0,
const String& mode = "upper", const String& nm = "Threshold");
virtual ~ThresholdFeature() { }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { samp_->reset(); VectorFloatFeatureStream::reset(); }
private:
VectorFloatFeatureStreamPtr samp_;
double value_;
double thresh_;
int compare_;
};
typedef Inherit<ThresholdFeature, VectorFloatFeatureStreamPtr> ThresholdFeaturePtr;
/*@}*/
/**
* \defgroup SpectralResamplingFeature Spectral Resampling Feature
*/
/*@{*/
// ----- definition for class `SpectralResamplingFeature' -----
//
class SpectralResamplingFeature : public VectorFeatureStream {
static const double SampleRatio;
public:
SpectralResamplingFeature(const VectorFeatureStreamPtr& src, double ratio = SampleRatio, unsigned len = 0,
const String& nm = "Resampling");
virtual ~SpectralResamplingFeature();
virtual const gsl_vector* next(int frame_no = -5);
virtual void reset() { src_->reset(); VectorFeatureStream::reset(); }
private:
VectorFeatureStreamPtr src_;
const double ratio_;
};
typedef Inherit<SpectralResamplingFeature, VectorFeatureStreamPtr> SpectralResamplingFeaturePtr;
/*@}*/
/**
* \defgroup SamplerateConversionFeature Samplerate Conversion Feature
*/
/*@{*/
// ----- definition for class `SamplerateConversionFeature' -----
//
#ifdef SRCONV
#include <samplerate.h>
class SamplerateConversionFeature : public VectorFloatFeatureStream {
public:
// ratio : Equal to input_sample_rate / output_sample_rate.
SamplerateConversionFeature(const VectorFloatFeatureStreamPtr& src, unsigned sourcerate = 22050, unsigned destrate = 16000,
unsigned len = 0, const String& method = "fastest", const String& nm = "SamplerateConversion");
virtual ~SamplerateConversionFeature();
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
private:
VectorFloatFeatureStreamPtr src_;
SRCSTATE_* state_;
SRC_DATA data_;
int error_;
unsigned dataInSamplesN_;
unsigned dataOutStartX_;
unsigned dataOutSamplesN_;
};
typedef Inherit<SamplerateConversionFeature, VectorFloatFeatureStreamPtr> SamplerateConversionFeaturePtr;
#endif
/*@}*/
/**
* \defgroup VTLNFeature VTLN Feature
*/
/*@{*/
// ----- definition for class `VTLNFeature' -----
//
// -------------------------------------------
// Piecewise linear: Y = X/Ratio for X < edge
// -------------------------------------------
class VTLNFeature : public VectorFeatureStream {
public:
VTLNFeature(const VectorFeatureStreamPtr& pow,
unsigned coeffN = 0, double ratio = 1.0, double edge = 1.0, int version = 1,
const String& nm = "VTLN");
virtual ~VTLNFeature() { }
virtual const gsl_vector* next(int frame_no = -5);
virtual void reset() { pow_->reset(); VectorFeatureStream::reset(); }
// specify the warp factor
void warp(double w) { ratio_ = w; }
void matrix(gsl_matrix* mat) const;
private:
virtual const gsl_vector* nextFF(int frame_no);
virtual const gsl_vector* nextOrg(int frame_no);
private:
VectorFeatureStreamPtr pow_;
double ratio_;
const double edge_;
const int version_;
gsl_vector* auxV_;
};
typedef Inherit<VTLNFeature, VectorFeatureStreamPtr> VTLNFeaturePtr;
/*@}*/
/**
* \defgroup MelFeature Mel Feature
*/
/*@{*/
// ----- definition for class 'MelFeature' -----
//
class MelFeature : public VectorFeatureStream {
class SparseMatrix_ {
public:
SparseMatrix_(unsigned m, unsigned n, unsigned version);
~SparseMatrix_();
void melScale(int powN, float rate, float low, float up, int filterN);
void melScaleOrg(int powN, float rate, float low, float up, int filterN);
void melScaleFF(int powN, float rate, float low, float up, int filterN);
gsl_vector* fmatrixBMulotOrg( gsl_vector* C, const gsl_vector* A) const;
gsl_vector* fmatrixBMulotFF( gsl_vector* C, const gsl_vector* A) const;
void fmatrixBMulot( gsl_vector* C, const gsl_vector* A) const;
void readBuffer(const String& fb);
void matrix(gsl_matrix* mat) const;
private:
void alloc_(unsigned m, unsigned n);
void dealloc_();
float mel_(float hz);
float hertz_(float m);
float** data_;
unsigned m_;
unsigned n_;
unsigned* offset_;// offset
unsigned* coefN_; // number of coefficients
float rate_; // sampling rate in Hz
int version_; // SparseMatrix_ version number, 1:Org, 2:Friedich's changes
};
public:
MelFeature(const VectorFeatureStreamPtr& mag, int powN = 0,
float rate = 16000.0, float low = 0.0, float up = 0.0,
unsigned filterN = 30, unsigned version = 1, const String& nm = "MelFFT");
virtual ~MelFeature();
virtual const gsl_vector* next(int frame_no = -5);
virtual void reset() { mag_->reset(); VectorFeatureStream::reset(); }
void read(const String& fileName);
void matrix(gsl_matrix* mat) const { mel_.matrix(mat); }
private:
// gsl_vector* _fmatrixBMulot(gsl_vector* C, const gsl_vector* A, FBMatrix* B) const;
const unsigned nmel_;
const unsigned powN_;
VectorFeatureStreamPtr mag_;
SparseMatrix_ mel_;
};
typedef Inherit<MelFeature, VectorFeatureStreamPtr> MelFeaturePtr;
// ----- definition for class 'SphinxMelFeature' -----
//
class SphinxMelFeature : public VectorFeatureStream {
class Boundary_ {
public:
Boundary_(unsigned min_k, unsigned max_k)
: min_k_(min_k), max_k_(max_k) { }
unsigned min_k_;
unsigned max_k_;
};
typedef vector<Boundary_> Boundaries_;
public:
SphinxMelFeature(const VectorFeatureStreamPtr& mag, unsigned fftN = 512, unsigned powerN = 0,
float sampleRate = 16000.0, float lowerF = 0.0, float upperF = 0.0,
unsigned filterN = 30, const String& nm = "SphinxMelFilterBank");
virtual ~SphinxMelFeature();
virtual const gsl_vector* next(int frame_no = -5);
virtual void reset() { mag_->reset(); VectorFeatureStream::reset(); }
void read(const String& fileName);
private:
static double melFrequency_(double frequency);
static double melInverseFrequency_(double frequency);
const unsigned fftN_;
const unsigned filterN_;
const unsigned powN_;
const double samplerate_;
VectorFeatureStreamPtr mag_;
gsl_matrix* filters_;
Boundaries_ boundaries_;
};
typedef Inherit<SphinxMelFeature, VectorFeatureStreamPtr> SphinxMelFeaturePtr;
/*@}*/
/**
* \defgroup LogFeature Log Feature
*/
/*@{*/
// ----- definition for class `LogFeature' -----
//
class LogFeature : public VectorFloatFeatureStream {
public:
LogFeature(const VectorFeatureStreamPtr& mel, double m = 1.0, double a = 1.0,
bool sphinxFlooring = false, const String& nm = "LogMel");
virtual ~LogFeature() { }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { mel_->reset(); VectorFloatFeatureStream::reset(); }
private:
const unsigned nmel_;
VectorFeatureStreamPtr mel_;
const double m_;
const double a_;
const bool SphinxFlooring_;
};
typedef Inherit<LogFeature, VectorFloatFeatureStreamPtr> LogFeaturePtr;
// ----- definition for class `FloatToDoubleConversionFeature' -----
//
class FloatToDoubleConversionFeature : public VectorFeatureStream {
public:
FloatToDoubleConversionFeature(const VectorFloatFeatureStreamPtr& src, const String& nm = "FloatToDoubleConversion") : VectorFeatureStream(src->size(), nm), src_(src) {};
virtual ~FloatToDoubleConversionFeature() { }
virtual const gsl_vector* next(int frame_no = -5);
virtual void reset() { src_->reset(); VectorFeatureStream::reset(); }
private:
VectorFloatFeatureStreamPtr src_;
};
typedef Inherit<FloatToDoubleConversionFeature, VectorFeatureStreamPtr> FloatToDoubleConversionFeaturePtr;
/*@}*/
/**
* \defgroup CepstralFeature Cepstral Feature
*/
/*@{*/
// ----- definition for class `CepstralFeature' -----
//
// type:
// 0 =
// 1 = Type 2 DCT
// 2 = Sphinx Legacy
class CepstralFeature : public VectorFloatFeatureStream {
public:
CepstralFeature(const VectorFloatFeatureStreamPtr& mel, unsigned ncep = 13,
int type = 1, const String& nm = "Cepstral");
virtual ~CepstralFeature() { gsl_matrix_float_free(cos_); }
virtual const gsl_vector_float* next(int frame_no = -5);
gsl_matrix* matrix() const;
virtual void reset() { mel_->reset(); VectorFloatFeatureStream::reset(); }
private:
void sphinxLegacy_();
gsl_matrix_float* cos_;
VectorFloatFeatureStreamPtr mel_;
};
typedef Inherit<CepstralFeature, VectorFloatFeatureStreamPtr> CepstralFeaturePtr;
/*@}*/
/**
* \defgroup MeanSubtractionFeature Mean Subtraction Feature
*/
/*@{*/
// ----- definition for class `MeanSubtractionFeature' -----
//
class MeanSubtractionFeature : public VectorFloatFeatureStream {
public:
MeanSubtractionFeature(const VectorFloatFeatureStreamPtr& src, const VectorFloatFeatureStreamPtr& weight = NULL, double devNormFactor = 0.0, bool runon = false, const String& nm = "Mean Subtraction");
virtual ~MeanSubtractionFeature();
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
const gsl_vector_float* mean() const { return mean_; }
void write(const String& fileName, bool variance = false) const;
void next_speaker();
#ifdef ENABLE_LEGACY_BTK_API
void nextSpeaker();
#endif
private:
const gsl_vector_float* nextRunon_(int frame_no);
const gsl_vector_float* nextBatch_(int frame_no);
void calcMeanVariance_();
void normalize_(const gsl_vector_float* srcVec);
static const float variance_floor_;
static const float before_wgt_;
static const float after_wgt;
static const unsigned framesN2change_;
VectorFloatFeatureStreamPtr src_;
VectorFloatFeatureStreamPtr wgt_;
gsl_vector_float* mean_;
gsl_vector_float* var_;
const double devNormFactor_;
unsigned framesN_;
bool runon_;
bool mean_var_found_;
};
typedef Inherit<MeanSubtractionFeature, VectorFloatFeatureStreamPtr> MeanSubtractionFeaturePtr;
/*@}*/
/**
* \defgroup FileMeanSubtractionFeature File Mean Subtraction Feature
*/
/*@{*/
// ----- definition for class `FileMeanSubtractionFeature' -----
//
class FileMeanSubtractionFeature : public VectorFloatFeatureStream {
public:
FileMeanSubtractionFeature(const VectorFloatFeatureStreamPtr& src,
double devNormFactor = 0.0, const String& nm = "File Mean Subtraction");
virtual ~FileMeanSubtractionFeature();
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
void read(const String& fileName, bool variance = false);
private:
static const float variance_floor_;
VectorFloatFeatureStreamPtr src_;
gsl_vector_float* mean_;
gsl_vector_float* variance_;
const double devNormFactor_;
};
typedef Inherit<FileMeanSubtractionFeature, VectorFloatFeatureStreamPtr> FileMeanSubtractionFeaturePtr;
/*@}*/
/**
* \defgroup AdjacentFeature Adjacent Feature
*/
/*@{*/
// ----- definition for class `AdjacentFeature' -----
//
class AdjacentFeature : public VectorFloatFeatureStream {
public:
AdjacentFeature(const VectorFloatFeatureStreamPtr& single, unsigned delta = 5,
const String& nm = "Adjacent");
virtual ~AdjacentFeature() { }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
private:
void buffer_next_frame_(int frame_no);
const unsigned delta_;
VectorFloatFeatureStreamPtr single_;
const unsigned singleSize_;
const unsigned plen_;
unsigned framesPadded_;
};
typedef Inherit<AdjacentFeature, VectorFloatFeatureStreamPtr> AdjacentFeaturePtr;
/*@}*/
/**
* \defgroup LinearTransformFeature Linear Transform Feature
*/
/*@{*/
// ----- definition for class `LinearTransformFeature' -----
//
class LinearTransformFeature : public VectorFloatFeatureStream {
public:
#if 0
LinearTransformFeature(const VectorFloatFeatureStreamPtr& src,
gsl_matrix_float* mat = NULL, unsigned sz = 0, const String& nm = "Transform");
#else
LinearTransformFeature(const VectorFloatFeatureStreamPtr& src, unsigned sz = 0, const String& nm = "Transform");
#endif
virtual ~LinearTransformFeature() { gsl_matrix_float_free(trans_); }
virtual const gsl_vector_float* next(int frame_no = -5);
gsl_matrix_float* matrix() const;
void load(const String& fileName, bool old = false);
void identity();
virtual void reset() { src_->reset(); VectorFloatFeatureStream::reset(); }
protected:
VectorFloatFeatureStreamPtr src_;
gsl_matrix_float* trans_;
};
typedef Inherit<LinearTransformFeature, VectorFloatFeatureStreamPtr> LinearTransformFeaturePtr;
/*@}*/
/**
* \defgroup StorageFeature Storage Feature
*/
/*@{*/
// ----- definition for class `StorageFeature' -----
//
class StorageFeature : public VectorFloatFeatureStream {
typedef vector<gsl_vector_float*> _StorageVector;
static const int MaxFrames;
public:
StorageFeature(const VectorFloatFeatureStreamPtr& src, const String& nm = "Storage");
virtual ~StorageFeature();
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { src_->reset(); VectorFloatFeatureStream::reset(); }
void write(const String& fileName, bool plainText = false) const;
void read(const String& fileName);
int evaluate();
private:
VectorFloatFeatureStreamPtr src_;
_StorageVector frames_;
};
typedef Inherit<StorageFeature, VectorFloatFeatureStreamPtr> StorageFeaturePtr;
/**
* \defgroup StaticStorageFeature Static Storage Feature
*/
/*@{*/
// ----- definition for class `StaticStorageFeature' -----
//
class StaticStorageFeature : public VectorFloatFeatureStream {
typedef vector<gsl_vector_float*> _StorageVector;
static const int MaxFrames;
public:
StaticStorageFeature(unsigned dim, const String& nm = "Static Storage");
virtual ~StaticStorageFeature();
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { VectorFloatFeatureStream::reset(); }
//void write(const String& fileName) const;
void read(const String& fileName);
int evaluate();
unsigned currentNFrames() const { return frame_no_; };
private:
//VectorFloatFeatureStreamPtr src_;
_StorageVector frames_;
int framesN_;
};
typedef Inherit<StaticStorageFeature, VectorFloatFeatureStreamPtr> StaticStorageFeaturePtr;
/*@}*/
/**
* \defgroup CircularStorageFeature Circular Storage Feature
*/
/*@{*/
// ----- definition for class `CircularStorageFeature' -----
//
class CircularStorageFeature : public VectorFloatFeatureStream {
typedef vector<gsl_vector_float*> _StorageVector;
static const int MaxFrames;
public:
CircularStorageFeature(const VectorFloatFeatureStreamPtr& src, unsigned framesN = 3, const String& nm = "CircularStorage");
virtual ~CircularStorageFeature();
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
private:
unsigned get_index_(int diff) const;
VectorFloatFeatureStreamPtr src_;
const unsigned framesN_;
_StorageVector frames_;
unsigned pointerX_;
};
typedef Inherit<CircularStorageFeature, VectorFloatFeatureStreamPtr> CircularStorageFeaturePtr;
/*@}*/
/**
* \defgroup FilterFeature Filter Feature
*/
/*@{*/
// ----- definition for class `FilterFeature' -----
//
class FilterFeature : public VectorFloatFeatureStream {
class Buffer_ {
public:
Buffer_(unsigned len, unsigned nsamp)
: len_(len), nsamp_(nsamp), offset_(int((nsamp_ - 1) / 2)),
zero_(0), samples_(new gsl_vector_float*[nsamp_])
{
assert (nsamp_ % 2 == 1);
for (unsigned i = 0; i < nsamp_; i++)
samples_[i] = gsl_vector_float_calloc(len_);
}
~Buffer_()
{
for (unsigned i = 0; i < nsamp_; i++)
gsl_vector_float_free(samples_[i]);
delete[] samples_;
}
const gsl_vector_float* sample(unsigned timeX) const {
return samples_[index_(timeX)];
}
const double sample(int timeX, unsigned binX) const {
unsigned idx = index_(timeX);
const gsl_vector_float* vec = samples_[idx];
return gsl_vector_float_get(vec, binX);
}
void nextSample(const gsl_vector_float* s = NULL) {
zero_ = (zero_ + 1) % nsamp_;
gsl_vector_float* nextBlock = samples_[(zero_ + offset_) % nsamp_];
if (s == NULL) {
gsl_vector_float_set_zero(nextBlock);
} else {
assert( s->size == len_ );
gsl_vector_float_memcpy(nextBlock, s);
}
}
void zero() {
for (unsigned i = 0; i < nsamp_; i++)
gsl_vector_float_set_zero(samples_[i]);
zero_ = nsamp_ - offset_;
}
void print() const {
for (int i = -offset_; i <= offset_; i++)
printf(" %4d", i);
printf("\n --------------------------------------------------------------------------------\n");
for (unsigned l = 0; l < len_; l++) {
for (int i = -offset_; i <= offset_; i++)
printf(" %10.4f", sample(i, l));
printf("\n");
}
}
private:
unsigned index_(int idx) const {
assert ( abs(idx) <= offset_);
unsigned ret = (zero_ + nsamp_ + idx) % nsamp_;
return ret;
}
const unsigned len_;
const unsigned nsamp_;
int offset_;
unsigned zero_; // index of most recent sample
gsl_vector_float** samples_;
};
public:
FilterFeature(const VectorFloatFeatureStreamPtr& src, gsl_vector* coeffA, const String& nm = "Filter");
virtual ~FilterFeature();
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
void printBuffer() const { buffer_.print(); }
private:
void buffer_next_frame_(int frame_no);
VectorFloatFeatureStreamPtr src_;
unsigned lenA_;
gsl_vector* coeffA_;
int offset_;
Buffer_ buffer_;
unsigned framesPadded_;
};
typedef Inherit<FilterFeature, VectorFloatFeatureStreamPtr> FilterFeaturePtr;
/*@}*/
/**
* \defgroup MergeFeature Merge Feature
*/
/*@{*/
// ----- definition for class `MergeFeature' -----
//
class MergeFeature : public VectorFloatFeatureStream {
typedef list<VectorFloatFeatureStreamPtr> FeatureList_;
typedef FeatureList_::iterator FeatureListIterator_;
typedef FeatureList_::const_iterator FeatureListConstIterator_;
public:
MergeFeature(VectorFloatFeatureStreamPtr& stat,
VectorFloatFeatureStreamPtr& delta,
VectorFloatFeatureStreamPtr& deltaDelta,
const String& nm = "Merge");
virtual ~MergeFeature() { }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
private:
FeatureList_ flist_;
};
typedef Inherit<MergeFeature, VectorFloatFeatureStreamPtr> MergeFeaturePtr;
/**
* \defgroup MultiModalFeature
*/
/*@{*/
// ----- definition for class `MultiModalFeature MergeFeature' -----
//
class MultiModalFeature : public VectorFloatFeatureStream {
typedef list<VectorFloatFeatureStreamPtr> FeatureList_;
typedef FeatureList_::iterator FeatureListIterator_;
typedef FeatureList_::const_iterator FeatureListConstIterator_;
public:
MultiModalFeature(unsigned nModality, unsigned totalVecSize, const String& nm = "Multi");
~MultiModalFeature();
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
void addModalFeature( VectorFloatFeatureStreamPtr &feature, unsigned samplePeriodinNanoSec=1 );
private:
unsigned *samplePeriods_; /* sample period (in nano sec.) */
unsigned minSamplePeriod_;
unsigned nModality_;
unsigned curr_vecsize_;
FeatureList_ flist_;
};
typedef Inherit<MultiModalFeature, VectorFloatFeatureStreamPtr> MultiModalFeaturePtr;
/*@}*/
/**
* \defgroup FeatureSet Feature Set
*/
/*@{*/
// ----- definition for class `FeatureSet' -----
//
class FeatureSet {
typedef List <VectorFloatFeatureStreamPtr> List_;
public:
FeatureSet(const String& nm = "FeatureSet") :
name_(nm), list_(nm) { }
const String& name() const { return name_; }
void add(VectorFloatFeatureStreamPtr& feat) { list_.add(feat->name(), feat); }
VectorFloatFeatureStreamPtr& feature(const String& nm) { return list_[nm]; }
private:
const String name_;
List_ list_;
};
typedef refcount_ptr<FeatureSet> FeatureSetPtr;
/*@}*/
void writeGSLMatrix(const String& fileName, const gsl_matrix* mat);
#ifdef JACK
#include <vector>
#include <jack/jack.h>
#include <jack/ringbuffer.h>
typedef struct {
jack_port_t *port;
jack_ringbuffer_t *buffer;
unsigned buffersize;
unsigned overrun;
bool can_process;
} jack_channel_t;
/**
* \defgroup Jack Jack Object
*/
/*@{*/
class Jack {
public:
Jack(const String& nm);
~Jack();
jack_channel_t* addPort(unsigned buffersize, const String& connection, const String& nm);
void start(void) { can_capture = true; };
unsigned getSampleRate() { return (unsigned)jack_get_sample_rate(client); }
private:
int process_callback (jack_nframes_t nframes);
static int _process_callback(jack_nframes_t nframes, void *arg) {
return static_cast<Jack *> (arg)->process_callback (nframes);
}
void shutdown_callback (void);
static void _shutdown_callback(void *arg) {
static_cast<Jack *> (arg)->shutdown_callback();
}
jack_client_t* client;
volatile bool can_capture;
volatile bool can_process;
vector<jack_channel_t*> channel;
};
typedef refcount_ptr<Jack> JackPtr;
/*@}*/
/**
* \defgroup JackFeature Jack Feature
*/
/*@{*/
// ----- definition for class `JackFeature' -----
//
class JackFeature;
typedef Inherit<JackFeature, VectorFloatFeatureStreamPtr> JackFeaturePtr;
class JackFeature : public VectorFloatFeatureStream {
public:
JackFeature(JackPtr& jack, unsigned blockLen, unsigned buffersize,
const String& connection, const String& nm);
virtual ~JackFeature() { }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { VectorFloatFeatureStream::reset(); }
private:
JackPtr jack_;
jack_channel_t* channel;
};
#endif
/*@}*/
/**
* \defgroup ZeroCrossingRateHammingFeature Zero Crossing Rate Hamming Feature
*/
/*@{*/
// ----- definition for class `ZeroCrossingRateHammingFeature' -----
//
class ZeroCrossingRateHammingFeature : public VectorFloatFeatureStream {
public:
ZeroCrossingRateHammingFeature(const VectorFloatFeatureStreamPtr& samp, const String& nm = "Zero Crossing Rate Hamming");
virtual ~ZeroCrossingRateHammingFeature() { delete[] window_; }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { samp_->reset(); VectorFloatFeatureStream::reset(); }
private:
VectorFloatFeatureStreamPtr samp_;
unsigned windowLen_;
double* window_;
};
typedef Inherit<ZeroCrossingRateHammingFeature, VectorFloatFeatureStreamPtr> ZeroCrossingRateHammingFeaturePtr;
/*@}*/
/**
* \defgroup YINPitchFeature YIN Pitch Feature
*/
/*@{*/
// ----- definition for class `YINPitchFeature' -----
//
class YINPitchFeature : public VectorFloatFeatureStream {
public:
YINPitchFeature(const VectorFloatFeatureStreamPtr& samp, unsigned samplerate = 16000, float threshold = 0.5, const String& nm = "YIN Pitch");
virtual ~YINPitchFeature() { }
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { samp_->reset(); VectorFloatFeatureStream::reset(); }
private:
float _getPitch(const gsl_vector_float *input, gsl_vector_float *yin, float tol);
VectorFloatFeatureStreamPtr samp_;
unsigned sr_;
float tr_;
};
typedef Inherit<YINPitchFeature, VectorFloatFeatureStreamPtr> YINPitchFeaturePtr;
/*@}*/
/**
* \defgroup SpikeFilter Spike Filter
*/
/*@{*/
// ----- definition for class `SpikeFilter' -----
//
class SpikeFilter : public VectorFloatFeatureStream {
public:
SpikeFilter(VectorFloatFeatureStreamPtr& src, unsigned tapN = 3, const String& nm = "Spike Filter");
virtual ~SpikeFilter();
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { src_->reset(); VectorFloatFeatureStream::reset(); }
private:
VectorFloatFeatureStreamPtr src_;
const unsigned adcN_;
const unsigned queueN_;
float* queue_;
const unsigned windowN_;
float* window_;
};
typedef Inherit<SpikeFilter, VectorFloatFeatureStreamPtr> SpikeFilterPtr;
/*@}*/
/**
* \defgroup SpikeFilter2 Spike Filter 2
*/
/*@{*/
// ----- definition for class `SpikeFilter2' -----
//
class SpikeFilter2 : public VectorFloatFeatureStream {
public:
SpikeFilter2(VectorFloatFeatureStreamPtr& src,
unsigned width = 3, float maxslope = 7000.0, float startslope = 100.0, float thresh = 15.0, float alpha = 0.2, unsigned verbose = 1,
const String& nm = "Spike Filter 2");
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset();
unsigned spikesN() const { return count_; }
private:
VectorFloatFeatureStreamPtr src_;
const unsigned adcN_;
const unsigned width_;
const float maxslope_;
const float startslope_;
const float thresh_;
float alpha_;
float beta_;
float meanslope_;
unsigned count_;
const unsigned verbose_;
};
typedef Inherit<SpikeFilter2, VectorFloatFeatureStreamPtr> SpikeFilter2Ptr;
/*@}*/
namespace sndfile {
#include <sndfile.h>
/**
* \defgroup SoundFile Sound File
*/
/*@{*/
// ----- definition for class `SoundFile' -----
//
class SoundFile {
public:
SoundFile(const String& fn,
int mode = sndfile::SFM_RDWR,
int format = sndfile::SF_FORMAT_WAV|sndfile::SF_FORMAT_PCM_16,
int samplerate = 16000,
int channels = 1,
bool normalize = false);
~SoundFile() { sf_close(sndfile_); }
sf_count_t frames() const { return sfinfo_.frames; }
int samplerate() const { return sfinfo_.samplerate; }
int channels() const { return sfinfo_.channels; }
int format() const { return sfinfo_.format; }
int sections() const { return sfinfo_.sections; }
int seekable() const { return sfinfo_.seekable; }
sf_count_t readf(float *ptr, sf_count_t frames)
{ return sf_readf_float(sndfile_, ptr, frames); }
sf_count_t writef(float *ptr, sf_count_t frames)
{ return sf_writef_float(sndfile_, ptr, frames); }
sf_count_t read(float *ptr, sf_count_t items)
{ return sf_read_float(sndfile_, ptr, items); }
sf_count_t write(float *ptr, sf_count_t items)
{ return sf_write_float(sndfile_, ptr, items); }
sf_count_t seek(sf_count_t frames, int whence = SEEK_SET)
{ return sf_seek(sndfile_, frames, whence); }
private:
SNDFILE* sndfile_;
SF_INFO sfinfo_;
};
}
typedef refcount_ptr<sndfile::SoundFile> SoundFilePtr;
/*@}*/
/**
* \defgroup DirectSampleFeature Direct Sample Feature
*/
/*@{*/
// ----- definition for class `DirectSampleFeature' -----
//
class DirectSampleFeature;
typedef Inherit<DirectSampleFeature, VectorFloatFeatureStreamPtr> DirectSampleFeaturePtr;
class DirectSampleFeature : public VectorFloatFeatureStream {
public:
DirectSampleFeature(const SoundFilePtr &sndfile,
unsigned blockLen = 320,
unsigned start = 0,
unsigned end = (unsigned)-1,
const String& nm = "DirectSample");
virtual ~DirectSampleFeature() {}
virtual const gsl_vector_float* next(int frame_no = -5);
int sampleRate() const { return sndfile_->samplerate(); }
int channels() const { return sndfile_->channels(); }
void setRegion(unsigned start = 0, unsigned end = (unsigned)-1) {
start_ = start;
end_ = end;
}
virtual void reset() {
sndfile_->seek(start_, SEEK_SET);
cur_ = 0;
VectorFloatFeatureStream::reset();
}
private:
SoundFilePtr sndfile_;
unsigned blockLen_;
unsigned start_;
unsigned end_;
unsigned cur_;
};
/*@}*/
/**
* \defgroup DirectSampleOutputFeature Direct Sample Output Feature
*/
/*@{*/
// ----- definition for class `DirectSampleOutputFeature' -----
//
class DirectSampleOutputFeature;
typedef Inherit<DirectSampleOutputFeature, VectorFloatFeatureStreamPtr> DirectSampleOutputFeaturePtr;
class DirectSampleOutputFeature : public VectorFloatFeatureStream {
public:
DirectSampleOutputFeature(const VectorFloatFeatureStreamPtr& src,
const SoundFilePtr &sndfile,
const String& nm = "DirectSampleOutput");
virtual ~DirectSampleOutputFeature() {}
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { src_->reset(); sndfile_->seek(0, SEEK_SET); VectorFloatFeatureStream::reset(); }
private:
VectorFloatFeatureStreamPtr src_;
SoundFilePtr sndfile_;
unsigned blockLen_;
};
/*@}*/
/**
* \defgroup ChannelExtractionFeature Channel Extraction Feature
*/
/*@{*/
// ----- definition for class `ChannelExtractionFeature' -----
//
class ChannelExtractionFeature;
typedef Inherit<ChannelExtractionFeature, VectorFloatFeatureStreamPtr> ChannelExtractionFeaturePtr;
class ChannelExtractionFeature : public VectorFloatFeatureStream {
public:
ChannelExtractionFeature(const VectorFloatFeatureStreamPtr& src,
unsigned chX = 0,
unsigned chN = 1,
const String& nm = "ChannelExtraction")
: VectorFloatFeatureStream(src->size()/chN, nm), src_(src), chX_(chX), chN_(chN)
{
assert(chX < chN);
assert((src->size() % chN) == 0);
}
virtual ~ChannelExtractionFeature() {}
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { src_->reset(); VectorFloatFeatureStream::reset(); }
private:
VectorFloatFeatureStreamPtr src_;
unsigned chX_;
unsigned chN_;
};
/*@}*/
/**
* \defgroup SignalInterferenceFeature Signal Interference Feature
*/
/*@{*/
// ----- definition for class SignalInterferenceFeature -----
//
class SignalInterferenceFeature;
typedef Inherit<SignalInterferenceFeature, VectorFloatFeatureStreamPtr> SignalInterferenceFeaturePtr;
class SignalInterferenceFeature : public VectorFloatFeatureStream{
public:
SignalInterferenceFeature(VectorFloatFeatureStreamPtr& signal, VectorFloatFeatureStreamPtr& interference, double dBInterference = 0.0, unsigned blockLen = 512, const String& nm = "Signal Interference");
virtual ~SignalInterferenceFeature() {};
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { signal_->reset(); interference_->reset(); VectorFloatFeatureStream::reset(); }
private:
VectorFloatFeatureStreamPtr signal_;
VectorFloatFeatureStreamPtr interference_;
const double level_;
};
/*@}*/
/**
* \defgroup AmplificationFeature Amplification Feature
*/
/*@{*/
// ----- definition for class `AmplificationFeature' -----
//
class AmplificationFeature;
typedef Inherit<AmplificationFeature, VectorFloatFeatureStreamPtr> AmplificationFeaturePtr;
class AmplificationFeature : public VectorFloatFeatureStream {
public:
AmplificationFeature(const VectorFloatFeatureStreamPtr& src,
double amplify = 1.0,
const String& nm = "Amplification")
: VectorFloatFeatureStream(src->size(), nm), src_(src), amplify_(amplify)
{}
virtual ~AmplificationFeature() {}
virtual const gsl_vector_float* next(int frame_no = -5);
virtual void reset() { src_->reset(); VectorFloatFeatureStream::reset(); }
private:
VectorFloatFeatureStreamPtr src_;
double amplify_;
};
// ----- definition for class `WriteSoundFile' -----
//
class WriteSoundFile {
public:
WriteSoundFile(const String& fn, int sampleRate, int nChan=1, int format = sndfile::SF_FORMAT_WAV|sndfile::SF_FORMAT_PCM_32);
~WriteSoundFile();
int write( gsl_vector *vector );
int writeInt( gsl_vector *vector );
int writeShort( gsl_vector *vector );
int writeFloat( gsl_vector *vector );
private:
sndfile::SNDFILE* sndfile_;
sndfile::SF_INFO sfinfo_;
};
typedef refcount_ptr<WriteSoundFile> WriteSoundFilePtr;
#endif
| {
"alphanum_fraction": 0.7025694768,
"avg_line_length": 27.306836248,
"ext": "h",
"hexsha": "8ab3ae7e52432b7ba0bc437024c20ffa57be5a88",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z",
"max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "musiclvme/distant_speech_recognition",
"max_forks_repo_path": "btk20_src/feature/feature.h",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "musiclvme/distant_speech_recognition",
"max_issues_repo_path": "btk20_src/feature/feature.h",
"max_line_length": 204,
"max_stars_count": 136,
"max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "musiclvme/distant_speech_recognition",
"max_stars_repo_path": "btk20_src/feature/feature.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z",
"num_tokens": 12429,
"size": 51528
} |
#ifndef ControlByRow_h
#define ControlByRow_h
/**
* @file
* $Revision: 1.2 $
* $Date: 2007/01/30 22:12:21 $
*
* Unless noted otherwise, the portions of Isis written by the USGS are
* public domain. See individual third-party library and package descriptions
* for intellectual property information, user agreements, and related
* information.
*
* Although Isis has been used by the USGS, no warranty, expressed or
* implied, is made by the USGS as to the accuracy and functioning of such
* software and related material nor shall the fact of distribution
* constitute any such warranty, and no responsibility is assumed by the
* USGS in connection therewith.
*
* For additional information, launch
* $ISISROOT/doc//documents/Disclaimers/Disclaimers.html
* in a browser or see the Privacy & Disclaimers page on the Isis website,
* http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on
* http://www.usgs.gov/privacy.html.
*/
#include <vector>
#include "ControlMeasure.h"
#include "ControlMeasureLogData.h"
#include "Statistics.h"
#include "CollectorMap.h"
#include "IString.h"
#include <gsl/gsl_math.h>
namespace Isis {
/**
* @brief Container for point collection
*/
struct PointData {
ControlMeasure refPoint;
ControlMeasure chpPoint;
};
/**
* @brief Less than test for Control point group
*
* This function tests the reference line numbers and returns true if the first
* point reference line is less than the second.
*
* @param p1 First PointData set to compare
* @param p2 Second PointData set to compare
*
* @return bool If first point reference line is less than the second
*/
inline bool PointLess(const PointData &p1, const PointData &p2) {
return (p1.refPoint.GetLine() < p2.refPoint.GetLine());
}
/**
* @brief Equality test for Control point group
*
* This function tests the reference line numbers for equality and returns true
* if the line references are equivalent, according to an approximation using an
* epsilon of 1.0e-6.
*
* @param p1 First PointData set to compare
* @param p2 Second PointData set to compare
*
* @return bool If the reference point lines are (approximately) equivalent
*/
inline bool PointEqual(const PointData &p1, const PointData &p2) {
return (gsl_fcmp(p1.refPoint.GetLine(), p2.refPoint.GetLine(), 1.0E-6) == 0);
}
/**
* @brief Collector for Control points within the same row for analysis
*
* This class is designed to be used as a Functor object collecting control net
* file and collapsing all column measures into on row. This is primarily used
* for analysis of coregistration results with one or more columns specified
* in the search/pattern chip strategy.
*
* @author ????-??-?? Unknown
*
* @internal
*/
class ControlByRow {
public:
/**
* @brief Structure to return control point statistics for row
*
* This structure contains the row statistics of merged control points.
* This will eventually be used to compute the spline interpolations for
* line and sample offsets.
*
*/
struct RowPoint {
RowPoint() : refLine(0.0), refSamp(0.0), chpLine(0.0), chpSamp(0.0),
total(0), count(0) { }
double refLine; //!< Reference line (row)
double refSamp; //!< Reference sample
double chpLine; //!< Registered line
double chpSamp; //!< Registered sample
int total; //!< Total points in row
int count; //!< Valid points found
Statistics rSStats;
Statistics cLStats;
Statistics cSStats;
Statistics cLOffset;
Statistics cSOffset;
Statistics GOFStats;
};
public:
/**
* @brief Default constructor
*/
ControlByRow() {
_minGOF = DBL_MIN;
_maxGOF = DBL_MAX;
}
/**
* @brief Constructor that sets the maximum goodness of fit tolerance
* @param maxGOF Value that specifies the maximum goodness of fit which is
* typically never expected to exceed 1.0 for a good fit.
*/
ControlByRow(double maxGOF) {
_minGOF = DBL_MIN;
_maxGOF = maxGOF;
}
/**
* @brief Constructor that sets the maximum goodness of fit tolerance
* @param minGOF Value of minimum goodness of fit. Allows user selectable
* adjustment to coregistration minimum tolerance
* @param maxGOF Value that specifies the maximum goodness of fit which is
* typically never expected to exceed 1.0 for a good fit.
*/
ControlByRow(double minGOF, double maxGOF) {
_minGOF = minGOF;
_maxGOF = maxGOF;
}
/**
* @brief Destructor
*/
~ControlByRow() { }
/**
* @brief Determines the number of points (rows) found valid
*
* The number returned is really the number of unique rows of coregistration
* chips gleened from the control net.
*
* @return unsigned int Row/line count
*/
inline unsigned int size() const {
return (_rowList.size());
}
/**
* @brief Set the minimum acceptable goodness of fit value
*
* This sets the minimum (absolute) value used to gleen valid points from
* the control net data.
*
* @param minGOF Minimum goodness of fit tolerance
*/
void setMinGOF(double minGOF) {
_minGOF = minGOF;
}
/**
* @brief Set the maximum acceptable goodness of fit value
*
* This sets the maximum (absolute) value used to gleen valid points from
* the control net data. This is intended to use to exclude wild points
* that exceed the level of reasonable tolerance. This is typically 1.0 for
* most coregistration algorithms.
*
* @param maxGOF Maximum goodness of fit tolerance
*/
void setMaxGOF(double maxGOF) {
_maxGOF = maxGOF;
}
/**
* @brief Operator used to add a point to the data set
*
* This method provides support for the STL for_each algorithm. This allows
* this class to be used as a functor object.
*
* @param p Point to tested for acceptance in the list
*/
void operator()(const PointData &p) {
addPoint(p);
return;
}
/**
* @brief Formal method of adding a control point to the data set
*
* This method will add the provided point to the collection of rows (or
* lines of points).
*
* @param p Point to add to the list
*/
void addPoint(const PointData &p) {
if(_rowList.exists(p.refPoint.GetLine())) {
PointList &r = _rowList.get(p.refPoint.GetLine());
r.push_back(p);
}
else {
PointList pl;
pl.push_back(p);
_rowList.add(p.refPoint.GetLine(), pl);
}
return;
}
/**
* @brief Returns a point at the ith location
*
* Traverses the list of points after computing the merge statistics for the
* ith row.
*
* @param i Index of point to return
*
* @return RowPoint Structure containing the (statistically) merged row
*/
RowPoint operator[](int i) const {
try {
return (computeStats(_rowList.getNth(i)));
}
catch(IException &oor) {
QString msg = "Requested value (" + toString(i) + ") not found";
throw IException(oor, IException::User, msg, _FILEINFO_);
}
}
private:
typedef std::vector<PointData> PointList; //!< Composite list
typedef CollectorMap<double, PointList, RobustFloatCompare> CNetRow; /**
* Nifty templated collector class works just
* nicely for merging rows of correlations
*/
double _minGOF; //!< Minimum acceptable goodness of fit
double _maxGOF; //!< Maximum acceptable goodness of fit
CNetRow _rowList; //!< Collection of merged rows/lines
/**
* @brief Convenience method for adding point to Statistics class
*
* The interface to the Isis Statistics class requires the value to be added
* by address. This method expedites the addition of values from say a
* function or method.
*
* @param value Value to add to Statistics class
* @param stats Statistics class to add the data point to
*/
inline void addToStats(double value, Statistics &stats) const {
stats.AddData(&value, 1);
return;
}
/**
* @brief All important method that computes statistics for a row
*
* This method computes the statistics for a potentially merged row of
* coregistration chips. It applies the minimum and maximum goodness of fit
* tolerance checks and add valid points to each statistical component of
* the merge.
*
* @param cols List of column chip registrations
*
* @return RowPoint Structure containing the statistics for row/line of
* merged registration columns
*/
RowPoint computeStats(const std::vector<PointData> &cols) const {
RowPoint rp;
rp.refLine = cols[0].refPoint.GetLine();
for(unsigned int i = 0; i < cols.size() ; i++) {
double regGOF =
cols[i].chpPoint.GetLogData(ControlMeasureLogData::GoodnessOfFit)
.GetNumericalValue();
if(fabs(regGOF) > _maxGOF) continue;
if(fabs(regGOF) < _minGOF) continue;
(rp.count)++;
addToStats(cols[i].refPoint.GetSample(), rp.rSStats);
addToStats(cols[i].chpPoint.GetLine(), rp.cLStats);
addToStats(cols[i].chpPoint.GetSample(), rp.cSStats);
addToStats(cols[i].chpPoint.GetLineResidual(), rp.cLOffset);
addToStats(cols[i].chpPoint.GetSampleResidual(), rp.cSOffset);
addToStats(regGOF, rp.GOFStats);
}
rp.total = cols.size();
rp.refSamp = rp.rSStats.Average();
rp.chpLine = rp.cLStats.Average();
rp.chpSamp = rp.cSStats.Average();
return (rp);
}
};
} // namespace Isis
#endif
| {
"alphanum_fraction": 0.6094724901,
"avg_line_length": 33.9038461538,
"ext": "h",
"hexsha": "fd1cbd97591b1f960d674b57704ae6c32c2737e0",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-07-12T06:05:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-12T06:05:03.000Z",
"max_forks_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "ihumphrey-usgs/ISIS3_old",
"max_forks_repo_path": "isis/src/control/apps/slither/ControlByRow.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108",
"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": "ihumphrey-usgs/ISIS3_old",
"max_issues_repo_path": "isis/src/control/apps/slither/ControlByRow.h",
"max_line_length": 82,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "ihumphrey-usgs/ISIS3_old",
"max_stars_repo_path": "isis/src/control/apps/slither/ControlByRow.h",
"max_stars_repo_stars_event_max_datetime": "2019-10-13T15:31:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-10-13T15:31:33.000Z",
"num_tokens": 2520,
"size": 10578
} |
/////////////////////////////////////////////////////////////////////
// = NMatrix
//
// A linear algebra library for scientific computation in Ruby.
// NMatrix is part of SciRuby.
//
// NMatrix was originally inspired by and derived from NArray, by
// Masahiro Tanaka: http://narray.rubyforge.org
//
// == Copyright Information
//
// SciRuby is Copyright (c) 2010 - 2014, Ruby Science Foundation
// NMatrix is Copyright (c) 2012 - 2014, John Woods and the Ruby Science Foundation
//
// Please see LICENSE.txt for additional copyright notices.
//
// == Contributing
//
// By contributing source code to SciRuby, you agree to be bound by
// our Contributor Agreement:
//
// * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement
//
// == getrs.h
//
// getrs function in native C++.
//
/*
* Automatically Tuned Linear Algebra Software v3.8.4
* (C) Copyright 1999 R. Clint Whaley
*
* 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. The name of the ATLAS group or the names of its contributers may
* not be used to endorse or promote products derived from this
* software without specific 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 ATLAS GROUP OR ITS 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.
*
*/
#ifndef POTRS_H
#define POTRS_H
extern "C" {
#if defined HAVE_CBLAS_H
#include <cblas.h>
#elif defined HAVE_ATLAS_CBLAS_H
#include <atlas/cblas.h>
#endif
}
namespace nm { namespace math {
/*
* Solves a system of linear equations A*X = B with a symmetric positive definite matrix A using the Cholesky factorization computed by POTRF.
*
* From ATLAS 3.8.0.
*/
template <typename DType, bool is_complex>
int potrs(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const int N, const int NRHS, const DType* A,
const int lda, DType* B, const int ldb)
{
// enum CBLAS_DIAG Lunit, Uunit; // These aren't used. Not sure why they're declared in ATLAS' src.
CBLAS_TRANSPOSE MyTrans = is_complex ? CblasConjTrans : CblasTrans;
if (!N || !NRHS) return 0;
const DType ONE = 1;
if (Order == CblasColMajor) {
if (Uplo == CblasUpper) {
nm::math::trsm<DType>(Order, CblasLeft, CblasUpper, MyTrans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb);
nm::math::trsm<DType>(Order, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb);
} else {
nm::math::trsm<DType>(Order, CblasLeft, CblasLower, CblasNoTrans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb);
nm::math::trsm<DType>(Order, CblasLeft, CblasLower, MyTrans, CblasNonUnit, N, NRHS, ONE, A, lda, B, ldb);
}
} else {
// There's some kind of scaling operation that normally happens here in ATLAS. Not sure what it does, so we'll only
// worry if something breaks. It probably has to do with their non-templated code and doesn't apply to us.
if (Uplo == CblasUpper) {
nm::math::trsm<DType>(Order, CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb);
nm::math::trsm<DType>(Order, CblasRight, CblasUpper, MyTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb);
} else {
nm::math::trsm<DType>(Order, CblasRight, CblasLower, MyTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb);
nm::math::trsm<DType>(Order, CblasRight, CblasLower, CblasNoTrans, CblasNonUnit, NRHS, N, ONE, A, lda, B, ldb);
}
}
return 0;
}
/*
* Function signature conversion for calling LAPACK's potrs functions as directly as possible.
*
* For documentation: http://www.netlib.org/lapack/double/dpotrs.f
*
* This function should normally go in math.cpp, but we need it to be available to nmatrix.cpp.
*/
template <typename DType, bool is_complex>
inline int clapack_potrs(const enum CBLAS_ORDER order, const enum CBLAS_UPLO uplo, const int n, const int nrhs,
const void* a, const int lda, void* b, const int ldb) {
return potrs<DType,is_complex>(order, uplo, n, nrhs, reinterpret_cast<const DType*>(a), lda, reinterpret_cast<DType*>(b), ldb);
}
} } // end nm::math
#endif // POTRS_H
| {
"alphanum_fraction": 0.6975544517,
"avg_line_length": 40.2615384615,
"ext": "h",
"hexsha": "6bc62ce49c2ab269973b63617d4c5a31d2d1697a",
"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": "cb2cd26195d544ac03b347e293c071faed6f90a6",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "blackwinter-attic/nmatrix",
"max_forks_repo_path": "ext/nmatrix/math/potrs.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cb2cd26195d544ac03b347e293c071faed6f90a6",
"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": "blackwinter-attic/nmatrix",
"max_issues_repo_path": "ext/nmatrix/math/potrs.h",
"max_line_length": 142,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cb2cd26195d544ac03b347e293c071faed6f90a6",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "blackwinter-attic/nmatrix",
"max_stars_repo_path": "ext/nmatrix/math/potrs.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1413,
"size": 5234
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** This file forms part of the Underworld geophysics modelling application. **
** **
** For full license and copyright information, please refer to the LICENSE.md file **
** located at the project root, or contact the authors. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#include <petsc.h>
#include <petscmat.h>
#include <petscvec.h>
#include <petscksp.h>
#include <petscpc.h>
#include <petscversion.h>
#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )
#if (PETSC_VERSION_MINOR >=6)
#include <petsc/private/kspimpl.h>
#else
#include <petsc-private/kspimpl.h>
#endif
#else
#include <private/kspimpl.h>
#endif
#include "common-driver-utils.h"
#include <StGermain/StGermain.h>
#include <StgDomain/StgDomain.h>
#include <StgFEM/StgFEM.h>
#include <PICellerator/PICellerator.h>
#include <Underworld/Underworld.h>
#include "Solvers/KSPSolvers/KSPSolvers.h"
#include "petsccompat.h"
#include "BSSCR.h"
#include "stokes_block_scaling.h"
#include "stokes_mvblock_scaling.h"
#include "mg.h"
#include "ksp_pressure_nullspace.h"
typedef struct {
int num_nsp_vecs;
Vec *nsp_vecs;
} nsp_data_t;
typedef struct {
KSP kspA11;
SLE_Solver *sleSolver;
} WendyContext;
//PetscErrorCode BSSCR_NSPRemoveAll(Vec v, void *_data);
PetscErrorCode BSSCR_KSPNormInfMonitor( KSP ksp, PetscInt iteration, PetscReal residualNorm, void *dummy);
PetscErrorCode BSSCR_KSPNormInfToNorm2Monitor( KSP ksp, PetscInt iteration, PetscReal residualNorm, void *dummy);
PetscErrorCode BSSCR_DRIVER_flex( KSP ksp, Mat stokes_A, Vec stokes_x, Vec stokes_b, Mat approxS, KSP ksp_K,
MatStokesBlockScaling BA, PetscTruth sym, KSP_BSSCR * bsscrp_self )
{
char name[PETSC_MAX_PATH_LEN];
char ubefore[100];
char uafter[100];
char pbefore[100];
char pafter[100];
PetscTruth flg, flg2, truth, useAcceleratingSmoothingMG, useFancySmoothingMG;
PetscTruth usePreviousGuess, useNormInfStoppingConditions, useNormInfMonitor, found, extractMats;
Mat K,G,D,C;
Vec u,p,f,h;
Mat S;
Vec h_hat,t,t2,q,v;
KSP ksp_inner;
KSP ksp_S;
KSP ksp_cleaner;
KSPType ksp_inner_type;
PetscTruth has_cnst_nullspace;
PC pc_S, pc_MG, pcInner;
PetscInt monitor_index,max_it,min_it;
Vec nsp_vec = PETSC_NULL;
PetscReal scr_rtol;
PetscReal inner_rtol;
PetscReal vSolver_rtol;
PetscScalar uNormInf, pNormInf;
PetscScalar uNorm, pNorm, rNorm, fNorm;
PetscInt uSize, pSize;
PetscInt lmin,lmax;
PetscInt iterations, rhs_iterations;
PetscReal min,max;
PetscReal p_sum;
MGContext mgCtx;
PC shellPC;
double t0, t1;
double mgSetupTime, rhsSolveTime, problemBuildTime, scrSolveTime, a11SingleSolveTime, solutionAnalysisTime;
Index nx,ny,nz;
PetscInt j,start,end;
static int been_here = 0; /* Ha Ha Ha !! */
/* get sub matrix / vector objects */
MatNestGetSubMat( stokes_A, 0,0, &K );
MatNestGetSubMat( stokes_A, 0,1, &G );
MatNestGetSubMat( stokes_A, 1,0, &D );
MatNestGetSubMat( stokes_A, 1,1, &C );
VecNestGetSubVec( stokes_x, 0, &u );
VecNestGetSubVec( stokes_x, 1, &p );
VecNestGetSubVec( stokes_b, 0, &f );
VecNestGetSubVec( stokes_b, 1, &h );
/* PetscPrintf( PETSC_COMM_WORLD, "\t Adress of stokes_x is %p\n", stokes_x); */
/* VecNorm( u, NORM_2, &uNorm ); */
/* PetscPrintf( PETSC_COMM_WORLD, "\t u Norm is %.6e in %s: address is %p\n",uNorm,__func__,u); */
/* VecNorm( p, NORM_2, &pNorm ); */
/* PetscPrintf( PETSC_COMM_WORLD, "\t p Norm is %.6e in %s: addres is %p\n",pNorm,__func__,p); */
/* Create Schur complement matrix */
problemBuildTime = MPI_Wtime();
//MatCreateSchurFromBlock( stokes_A, 0.0, "MatSchur_A11", &S );
MatCreateSchurComplement(K,K,G,D,C, &S);
/* configure inner solver */
if (ksp_K!=PETSC_NULL) {
MatSchurComplementSetKSP( S, ksp_K );
MatSchurComplementGetKSP( S, &ksp_inner );
}
else {
abort();
MatSchurComplementGetKSP( S, &ksp_inner );
KSPSetType( ksp_inner, "cg" );
}
KSPGetPC( ksp_inner, &pcInner );
/* If we're using multigrid, replace the preconditioner here
so we get the same options prefix. */
if(bsscrp_self->mg) {
mgSetupTime=setupMG( bsscrp_self, ksp_inner, pcInner, K, &mgCtx );
}
/* SETFROMOPTIONS MIGHT FUCK MG UP */
KSPSetOptionsPrefix( ksp_inner, "A11_" );
KSPSetFromOptions( ksp_inner );
useNormInfStoppingConditions = PETSC_FALSE;
PetscOptionsGetTruth( PETSC_NULL ,"-A11_use_norm_inf_stopping_condition", &useNormInfStoppingConditions, &found );
if(useNormInfStoppingConditions)
BSSCR_KSPSetNormInfConvergenceTest( ksp_inner );
useNormInfMonitor = PETSC_FALSE;
PetscOptionsGetTruth( PETSC_NULL, "-A11_ksp_norm_inf_monitor", &useNormInfMonitor, &found );
if(useNormInfMonitor)
KSPMonitorSet( ksp_inner, BSSCR_KSPNormInfMonitor, PETSC_NULL, PETSC_NULL );
useNormInfMonitor = PETSC_FALSE;
PetscOptionsGetTruth( PETSC_NULL, "-A11_ksp_norm_inf_to_norm_2_monitor", &useNormInfMonitor, &found );
if(useNormInfMonitor)
KSPMonitorSet( ksp_inner, BSSCR_KSPNormInfToNorm2Monitor, PETSC_NULL, PETSC_NULL );
/* create right hand side */
/* h_hat = G'*inv(K)*f - h */
MatGetVecs(K,PETSC_NULL,&t);
MatGetVecs( S, PETSC_NULL, &h_hat );
KSPSetOptionsPrefix( ksp_inner, "A11_" );
KSPSetFromOptions( ksp_inner );
problemBuildTime = MPI_Wtime() - problemBuildTime;
rhsSolveTime = MPI_Wtime();
KSPSolve(ksp_inner,f,t);/* t=f/K */
rhsSolveTime = MPI_Wtime() - rhsSolveTime;
KSPGetIterationNumber( ksp_inner, &rhs_iterations);
//bsscr_writeVec( t, "ts", "Writing t vector");
MatMult(D,t,h_hat);/* G'*t */
VecAXPY(h_hat, -1.0, h);/* h_hat = h_hat - h */
Stg_VecDestroy(&t);
//bsscr_writeVec( h_hat, "h_hat", "Writing h_hat Vector in Solver");
//MatSchurApplyReductionToVecFromBlock( S, stokes_b, h_hat );
/* create solver for S p = h_hat */
KSPCreate( PETSC_COMM_WORLD, &ksp_S );
KSPSetOptionsPrefix( ksp_S, "scr_");
Stg_KSPSetOperators( ksp_S, S,S, SAME_NONZERO_PATTERN );
KSPSetType( ksp_S, "cg" );
/* Build preconditioner for S */
KSPGetPC( ksp_S, &pc_S );
BSSCR_BSSCR_StokesCreatePCSchur2( K,G,D,C,approxS,pc_S,sym, bsscrp_self );
KSPSetFromOptions(ksp_S);
/* Set specific monitor test */
KSPGetTolerances( ksp_S, PETSC_NULL, PETSC_NULL, PETSC_NULL, &max_it );
//BSSCR_KSPLogSetMonitor( ksp_S, max_it, &monitor_index );
/* Pressure / Velocity Solve */
scrSolveTime = MPI_Wtime();
// PetscPrintf( PETSC_COMM_WORLD, "\t* Pressure / Velocity Solve \n");
usePreviousGuess = PETSC_FALSE;
if(been_here)
PetscOptionsGetTruth( PETSC_NULL, "-scr_use_previous_guess", &usePreviousGuess, &found );
if(usePreviousGuess) { /* Note this should actually look at checkpoint information */
KSPSetInitialGuessNonzero( ksp_S, PETSC_TRUE );
}
else {
KSPSetInitialGuessNonzero( ksp_S, PETSC_FALSE );
}
//KSPSetRelativeRhsConvergenceTest( ksp_S );
useNormInfStoppingConditions = PETSC_FALSE;
PetscOptionsGetTruth( PETSC_NULL ,"-scr_use_norm_inf_stopping_condition", &useNormInfStoppingConditions, &found );
if(useNormInfStoppingConditions)
BSSCR_KSPSetNormInfConvergenceTest(ksp_S);
useNormInfMonitor = PETSC_FALSE;
PetscOptionsGetTruth( PETSC_NULL, "-scr_ksp_norm_inf_monitor", &useNormInfMonitor, &found );
if(useNormInfMonitor)
KSPMonitorSet( ksp_S, BSSCR_KSPNormInfToNorm2Monitor, PETSC_NULL, PETSC_NULL );
// PetscPrintf( PETSC_COMM_WORLD, "\t* KSPSolve( ksp_S, h_hat, p )\n");
/* if h_hat needs to be fixed up ..take out any nullspace vectors here */
/* we want to check that there is no "noise" in the null-space in the h vector */
/* this causes problems when we are trying to solve a Jacobian system when the Residual is almost converged */
if(bsscrp_self->check_pressureNS){
bsscrp_self->buildPNS(ksp);/* build and set nullspace vectors on bsscr - which is on ksp (function pointer is set in KSPSetUp_BSSCR */
}
PetscScalar norm, a, a1, a2, hnorm, pnorm, gnorm;
MatNorm(G,NORM_INFINITY,&gnorm);
VecNorm(h_hat, NORM_2, &hnorm);
hnorm=hnorm/gnorm;
if((hnorm < 1e-6) && (hnorm > 1e-20)){
VecScale(h_hat,1.0/hnorm);
}
/* test to see if v or t are in nullspace of G and orthogonalize wrt h_hat if needed */
KSPRemovePressureNullspace_BSSCR(ksp, h_hat);
/***************************************/
/* set convergence test to use min_it */
found = PETSC_FALSE;
min_it = 0;
PetscOptionsGetInt( PETSC_NULL,"-scr_ksp_set_min_it_converge", &min_it, &found);
if(found && min_it > 0){
BSSCR_KSPSetConvergenceMinIts(ksp_S, min_it, bsscrp_self);
}
KSPSolve( ksp_S, h_hat, p );
sprintf(pafter,"psafter_%d",been_here);
// bsscr_writeVec( p, pafter, "Writing p Vector in Solver");
/***************************************/
if((hnorm < 1e-6) && (hnorm > 1e-20)){
VecScale(h_hat,hnorm);
VecScale(p,hnorm);
}
KSPRemovePressureNullspace_BSSCR(ksp, p);
scrSolveTime = MPI_Wtime() - scrSolveTime;
// PetscPrintf( PETSC_COMM_WORLD, " SCR Solve Finished in time: %lf seconds\n\n", scrSolveTime);
/* Resolve with this pressure to obtain solution for u */
/* obtain solution for u */
VecDuplicate( u, &t );
MatMult( G, p, t);
VecAYPX( t, -1.0, f ); /* t <- -t + f */
MatSchurComplementGetKSP( S, &ksp_inner );
a11SingleSolveTime = MPI_Wtime(); /* ---------------------------------- Final V Solve */
if(usePreviousGuess)
KSPSetInitialGuessNonzero( ksp_inner, PETSC_TRUE );
KSPSetOptionsPrefix( ksp_inner, "backsolveA11_" );
KSPSetFromOptions( ksp_inner );
KSPSolve( ksp_inner, t, u ); /* Solve, then restore default tolerance and initial guess */
a11SingleSolveTime = MPI_Wtime() - a11SingleSolveTime; /* ------------------ Final V Solve */
PetscPrintf( PETSC_COMM_WORLD, "SCR Solver Summary:\n\n");
if(bsscrp_self->mg)
PetscPrintf( PETSC_COMM_WORLD, " Multigrid setup: = %.4g secs \n", mgSetupTime);
PetscPrintf( PETSC_COMM_WORLD, " RHS / Pre Solve: = %.4g secs / %d its\n", rhsSolveTime, rhs_iterations);
KSPGetIterationNumber( ksp_S, &iterations);
PetscPrintf( PETSC_COMM_WORLD, " Pressure Solve: = %.4g secs / %d its\n", scrSolveTime, iterations);
KSPGetIterationNumber( ksp_inner, &iterations);
PetscPrintf( PETSC_COMM_WORLD, " Final V Solve: = %.4g secs / %d its\n\n", a11SingleSolveTime, iterations);
/* Analysis of solution:
This can be somewhat time consuming as it requires allocation / de-allocation,
computing vector norms etc. So we make it optional..
This should be put into a proper KSP monitor now?
*/
flg = PETSC_TRUE;
PetscOptionsGetTruth( PETSC_NULL, "-scr_ksp_solution_summary", &flg, &found );
if(flg) {
solutionAnalysisTime = MPI_Wtime();
VecGetSize( u, &uSize );
VecGetSize( p, &pSize );
VecDuplicate( u, &t2 );
MatMult( K, u, t2);
VecAYPX( t2, -1.0, t ); /* t2 <- -t2 + t ... should be the formal residual vector */
VecNorm( t2, NORM_2, &rNorm );
VecNorm( f, NORM_2, &fNorm );
PetscPrintf( PETSC_COMM_WORLD, " |f - K u - G p|/|f| = %.6e\n", rNorm/fNorm );
VecDuplicate( p, &q );
MatMult( D, u, q );
VecNorm( u, NORM_2, &uNorm );
VecNorm( q, NORM_2, &rNorm );
PetscPrintf( PETSC_COMM_WORLD, " |G^T u|_2/|u|_2 = %.6e\n", sqrt( (double) uSize / (double) pSize ) * rNorm / uNorm);
VecNorm( q, NORM_INFINITY, &rNorm );
PetscPrintf( PETSC_COMM_WORLD, " |G^T u|_infty/|u|_2 = %.6e\n", sqrt( (double) uSize ) * rNorm / uNorm);
VecNorm( u, NORM_INFINITY, &uNormInf );
VecNorm( u, NORM_2, &uNorm );
VecGetSize( u, &uSize );
VecNorm( p, NORM_INFINITY, &pNormInf );
VecNorm( p, NORM_2, &pNorm );
PetscPrintf( PETSC_COMM_WORLD, " |u|_{\\infty} = %.6e , u_rms = %.6e\n",
uNormInf, uNorm / sqrt( (double) uSize ) );
PetscPrintf( PETSC_COMM_WORLD, " |p|_{\\infty} = %.6e , p_rms = %.6e\n",
pNormInf, pNorm / sqrt( (double) pSize ) );
VecMax( u, &lmax, &max );
VecMin( u, &lmin, &min );
PetscPrintf( PETSC_COMM_WORLD, " min/max(u) = %.6e [%d] / %.6e [%d]\n",min,lmin,max,lmax);
VecMax( p, &lmax, &max );
VecMin( p, &lmin, &min );
PetscPrintf( PETSC_COMM_WORLD, " min/max(p) = %.6e [%d] / %.6e [%d]\n",min,lmin,max,lmax);
VecSum( p, &p_sum );
PetscPrintf( PETSC_COMM_WORLD, " \\sum_i p_i = %.6e \n", p_sum );
solutionAnalysisTime = MPI_Wtime() - solutionAnalysisTime;
PetscPrintf( PETSC_COMM_WORLD, "\n Time for this analysis = %.4g secs\n\n",solutionAnalysisTime);
Stg_VecDestroy(&t2 );
Stg_VecDestroy(&q );
}
if(bsscrp_self->mg) {
//MG_inner_solver_pcmg_shutdown( pcInner );
}
Stg_VecDestroy(&t );
// KSPLogDestroyMonitor( ksp_S );
Stg_KSPDestroy(&ksp_S );
//Stg_KSPDestroy(&ksp_inner );
Stg_VecDestroy(&h_hat );
Stg_MatDestroy(&S );
/* Destroy nullspace vector if it exists. */
if(nsp_vec)
Stg_VecDestroy(&nsp_vec);
//been_here = 1;
been_here++;
PetscFunctionReturn(0);
}
/*
A pointwise stopping condition (infinity norm)
To activate this stopping condition, I add this piece of code somewhere before the call to KSPSolve().
{
PetscTruth pw,flg;
pw = PETSC_FALSE;
PetscOptionsGetTruth(0,"-pointwise_stopping_condition", &pw,&flg);
if(pw==PETSC_TRUE) { KSPSetPointwiseConvergenceTest(ksp_T); }
}
You can activate a monitor for the max pointwise residual by using the cmd line option
-XXX_ksp_pointwise_monitor
where XXX is the solver prefix specified by the call KSPSetOptionsPrefix().
DAM
*/
typedef struct {
PetscTruth initialrtol; /* default relative residual decrease is computing from initial residual, not rhs */
PetscTruth mininitialrtol; /* default relative residual decrease is computing from min of initial residual and rhs */
Vec work;
PetscReal pointwise_max;
} KSPPWConvergedCtx;
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPPWConvergedCreate"
PetscErrorCode BSSCR_KSPPWConvergedCreate(void **ctx)
{
PetscErrorCode ierr;
KSPPWConvergedCtx *cctx;
PetscFunctionBegin;
ierr = Stg_PetscNew(KSPPWConvergedCtx,&cctx);CHKERRQ(ierr);
*ctx = cctx;
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPPWConvergedDestroy"
PetscErrorCode BSSCR_KSPPWConvergedDestroy(void *ctx)
{
PetscErrorCode ierr;
KSPPWConvergedCtx *cctx = (KSPPWConvergedCtx*) ctx;
PetscFunctionBegin;
if (cctx->work) {ierr = Stg_VecDestroy(&cctx->work);CHKERRQ(ierr);}
ierr = PetscFree(cctx);CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPNormInfConverged"
PetscErrorCode BSSCR_KSPNormInfConverged(KSP ksp,PetscInt n,PetscReal rnorm,KSPConvergedReason *reason,void *ctx)
{
PetscErrorCode ierr;
KSPPWConvergedCtx *cctx = (KSPPWConvergedCtx*)ctx;
KSPNormType normtype;
PetscReal min, max, R_max, R_min, R_Ninf;
Vec R, work, w1,w2;
PetscFunctionBegin;
PetscValidHeaderSpecific(ksp,KSP_COOKIE,1);
PetscValidPointer(reason,4);
*reason = KSP_CONVERGED_ITERATING;
ierr = VecDuplicate(ksp->vec_rhs,&work);CHKERRQ(ierr);
ierr = VecDuplicate(ksp->vec_rhs,&w1);CHKERRQ(ierr);
ierr = VecDuplicate(ksp->vec_rhs,&w2);CHKERRQ(ierr);
KSPBuildResidual( ksp, w1,w2, &R );
VecNorm( R, NORM_INFINITY, &R_Ninf );
//PetscPrintf( PETSC_COMM_WORLD, "Norm inf convergence %s\n ", ksp->prefix);
cctx->pointwise_max = R_Ninf;
ierr = KSPGetNormType(ksp,&normtype);
CHKERRQ(ierr);
if (normtype == KSP_NORM_NO)
Stg_SETERRQ(PETSC_ERR_ARG_WRONGSTATE,"Use BSSCR_KSPSkipConverged() with KSPNormType of KSP_NORM_NO");
if (!cctx)
Stg_SETERRQ(PETSC_ERR_ARG_NULL,"Convergence context must have been created with BSSCR_KSPDefaultConvergedCreate()");
if (!n) {
/* if user gives initial guess need to compute norm of b */
if (!ksp->guess_zero && !cctx->initialrtol) {
PetscReal snorm;
if (ksp->normtype == KSP_NORM_UNPRECONDITIONED || ksp->pc_side == PC_RIGHT) {
ierr = PetscInfo(ksp,"user has provided nonzero initial guess, computing 2-norm of RHS\n");
CHKERRQ(ierr);
ierr = VecNorm(ksp->vec_rhs,NORM_INFINITY,&snorm);CHKERRQ(ierr); /* <- b'*b */
PetscPrintf( PETSC_COMM_WORLD, "Non Zero Guess; RHS - %g\n", snorm);
}
else {
Vec z;
if (!cctx->work) {
ierr = VecDuplicate(ksp->vec_rhs,&cctx->work);CHKERRQ(ierr);
}
z = cctx->work;
ierr = KSP_PCApply(ksp,ksp->vec_rhs,z);CHKERRQ(ierr);
if (ksp->normtype == KSP_NORM_PRECONDITIONED) {
ierr = PetscInfo(ksp,"user has provided nonzero initial guess, computing 2-norm of preconditioned RHS\n");CHKERRQ(ierr);
ierr = VecNorm(z,NORM_INFINITY,&snorm);CHKERRQ(ierr); /* dp <- b'*B'*B*b */
}
else if (ksp->normtype == KSP_NORM_NATURAL) {
PetscScalar norm;
Vec bz;
ierr = PetscInfo(ksp,"user has provided nonzero initial guess, computing natural norm of RHS\n");CHKERRQ(ierr);
// ierr = VecDot(ksp->vec_rhs,z,&norm);
// snorm = sqrt(PetscAbsScalar(norm)); /* dp <- b'*B*b */
VecDuplicate( z, &bz );
VecPointwiseMult( bz, ksp->vec_rhs, z );
ierr = VecNorm(bz,NORM_INFINITY,&snorm);CHKERRQ(ierr);
Stg_VecDestroy(&bz);
}
}
/* handle special case of zero RHS and nonzero guess */
if (!snorm) {
ierr = PetscInfo(ksp,"Special case, user has provided nonzero initial guess and zero RHS\n");CHKERRQ(ierr);
snorm = rnorm;
}
if (cctx->mininitialrtol) {
ksp->rnorm0 = PetscMin(snorm,rnorm);
} else {
ksp->rnorm0 = snorm;
}
} else {
ksp->rnorm0 = rnorm;
}
ksp->ttol = PetscMax(ksp->rtol*ksp->rnorm0,ksp->abstol);
}
// if (n <= ksp->chknorm) PetscFunctionReturn(0);
if ( R_Ninf != R_Ninf ) {
ierr = PetscInfo(ksp,"Linear solver has created a not a number (NaN) as the pointwise residual norm, declaring divergence \n");CHKERRQ(ierr);
*reason = KSP_DIVERGED_NAN;
}
else
if (R_Ninf <= ksp->ttol) {
if (R_Ninf < ksp->abstol) {
ierr = PetscInfo3(ksp,"Linear solver has converged. Pointwise residual %G is less than absolute tolerance %G at iteration %D\n",R_Ninf,ksp->abstol,n);
CHKERRQ(ierr);
*reason = KSP_CONVERGED_ATOL;
}
else {
if (cctx->initialrtol) {
ierr = PetscInfo4(ksp,"Linear solver has converged. Norm_infinity %G is less than relative tolerance %G times initial Norm_infinity %G at iteration %D\n",R_Ninf,ksp->rtol,ksp->rnorm0,n);
CHKERRQ(ierr);
}
else {
ierr = PetscInfo4(ksp,"Linear solver has converged. Norm_infinity %G is less than relative tolerance %G times initial norm_infinity right hand side %G at iteration %D\n",R_Ninf,ksp->rtol,ksp->rnorm0,n);CHKERRQ(ierr);
}
*reason = KSP_CONVERGED_RTOL;
}
}
else
if (R_Ninf >= ksp->divtol*ksp->rnorm0) {
ierr = PetscInfo3(ksp,"Linear solver is diverging. Initial right hand size Norm_infinity value %G, current residual norm %G at iteration %D\n",ksp->rnorm0,R_Ninf,n);CHKERRQ(ierr);
*reason = KSP_DIVERGED_DTOL;
}
/* trash all work vectors here */
Stg_VecDestroy(&work);
Stg_VecDestroy(&w1);
Stg_VecDestroy(&w2);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPNormInfToNorm2Monitor"
PetscErrorCode BSSCR_KSPNormInfToNorm2Monitor(KSP ksp,PetscInt n,PetscReal rnorm, void *dummy)
{
PetscErrorCode ierr;
PetscViewerASCIIMonitor viewer = dummy ? (PetscViewer) dummy : PETSC_VIEWER_STDOUT_(((PetscObject)ksp)->comm);
PetscReal R_normInf, R_norm2;
PetscInt R_size;
Vec R, work, w1, w2;
PetscFunctionBegin;
ierr = VecDuplicate(ksp->vec_rhs,&work);CHKERRQ(ierr);
ierr = VecDuplicate(ksp->vec_rhs,&w1);CHKERRQ(ierr);
ierr = VecDuplicate(ksp->vec_rhs,&w2);CHKERRQ(ierr);
KSPBuildResidual( ksp, w1,w2, &R );
VecNorm( R, NORM_INFINITY, &R_normInf );
VecNorm( R, NORM_2, &R_norm2 );
VecGetSize( R, &R_size );
ierr = PetscViewerASCIIMonitorCreate(((PetscObject)ksp)->comm,"stdout",0,&viewer); CHKERRQ(ierr);
if(R_norm2 == 0.0) {
ierr = PetscViewerASCIIMonitorPrintf(viewer,"%3D KSP Residual Spikiness - INFINITY (%s) \n",
n, ((PetscObject)ksp)->prefix ? ((PetscObject)ksp)->prefix: "" );
CHKERRQ(ierr);
}
else{
ierr = PetscViewerASCIIMonitorPrintf(viewer,"%3D KSP Residual Spikiness %14.12e (%s) Max / Rms \n",
n, sqrt((double) R_size) * R_normInf / R_norm2,
((PetscObject)ksp)->prefix ? ((PetscObject)ksp)->prefix: "");
CHKERRQ(ierr);
}
ierr = PetscViewerASCIIMonitorDestroy(viewer);
CHKERRQ(ierr);
Stg_VecDestroy(&work);
Stg_VecDestroy(&w1);
Stg_VecDestroy(&w2);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPNormInfMonitor"
PetscErrorCode BSSCR_KSPNormInfMonitor(KSP ksp,PetscInt n,PetscReal rnorm, void *dummy)
{
PetscErrorCode ierr;
PetscViewerASCIIMonitor viewer;
PetscReal R_normInf;
Vec R, work, w1,w2;
PetscFunctionBegin;
ierr = VecDuplicate(ksp->vec_rhs,&work);CHKERRQ(ierr);
ierr = VecDuplicate(ksp->vec_rhs,&w1);CHKERRQ(ierr);
ierr = VecDuplicate(ksp->vec_rhs,&w2);CHKERRQ(ierr);
KSPBuildResidual( ksp, w1,w2, &R );
VecNorm( R, NORM_INFINITY, &R_normInf );
ierr = PetscViewerASCIIMonitorCreate(((PetscObject)ksp)->comm,"stdout",0,&viewer);
CHKERRQ(ierr);
ierr = PetscViewerASCIIMonitorPrintf(viewer,"%3D KSP Residual Ninf %14.12e (%s) \n",
n, R_normInf,
((PetscObject)ksp)->prefix ? ((PetscObject)ksp)->prefix: "");
CHKERRQ(ierr);
ierr = PetscViewerASCIIMonitorDestroy(viewer);
CHKERRQ(ierr);
Stg_VecDestroy(&work);
Stg_VecDestroy(&w1);
Stg_VecDestroy(&w2);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPNorm2RawMonitor"
PetscErrorCode BSSCR_KSPNorm2RawMonitor(KSP ksp,PetscInt n,PetscReal rnorm, void *dummy)
{
PetscErrorCode ierr;
PetscViewerASCIIMonitor viewer;
PetscReal R_norm2;
Vec R, work, w1,w2;
PetscFunctionBegin;
ierr = VecDuplicate(ksp->vec_rhs,&work);CHKERRQ(ierr);
ierr = VecDuplicate(ksp->vec_rhs,&w1);CHKERRQ(ierr);
ierr = VecDuplicate(ksp->vec_rhs,&w2);CHKERRQ(ierr);
KSPBuildResidual( ksp, w1,w2, &R );
VecNorm( R, NORM_2, &R_norm2 );
ierr = PetscViewerASCIIMonitorCreate(((PetscObject)ksp)->comm,"stdout",0,&viewer);
CHKERRQ(ierr);
ierr = PetscViewerASCIIMonitorPrintf(viewer,"%3D KSP Residual Norm2raw %14.12e (%s) \n",
n, R_norm2,
((PetscObject)ksp)->prefix ? ((PetscObject)ksp)->prefix: "");
CHKERRQ(ierr);
ierr = PetscViewerASCIIMonitorDestroy(viewer);
CHKERRQ(ierr);
Stg_VecDestroy(&work);
Stg_VecDestroy(&w1);
Stg_VecDestroy(&w2);
PetscFunctionReturn(0);
}
#undef __FUNCT__
#define __FUNCT__ "BSSCR_KSPSetNormInfConvergenceTest"
PetscErrorCode BSSCR_KSPSetNormInfConvergenceTest(KSP ksp)
{
KSPPWConvergedCtx *ctx;
PetscTruth monitor, flg;
char *opt;
const char *prefix;
BSSCR_KSPPWConvergedCreate( (void**)&ctx );
KSPGetOptionsPrefix( ksp, &prefix );
#if(PETSC_VERSION_MAJOR == 3)
KSPSetConvergenceTest( ksp, BSSCR_KSPNormInfConverged, ctx, BSSCR_KSPPWConvergedDestroy ); // 3.0.0 only
#else
KSPSetConvergenceTest( ksp, BSSCR_KSPNormInfConverged, ctx ); // 2.3.3
#endif
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.6177813903,
"avg_line_length": 35.1989100817,
"ext": "c",
"hexsha": "56d1e4784399dfc4b5544d0677d08e90abd9e2f8",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-08-25T04:54:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-12-14T21:57:46.000Z",
"max_forks_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "longgangfan/underworld2",
"max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/bsscr-driver.c",
"max_issues_count": 561,
"max_issues_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_issues_repo_issues_event_max_datetime": "2022-03-22T23:37:29.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-29T06:05:50.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "longgangfan/underworld2",
"max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/bsscr-driver.c",
"max_line_length": 236,
"max_stars_count": 116,
"max_stars_repo_head_hexsha": "5c8acc17fa4d97e86a62b13b8bfb2af6e81a8ee4",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "longgangfan/underworld2",
"max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/bsscr-driver.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T04:12:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-28T10:30:55.000Z",
"num_tokens": 7682,
"size": 25836
} |
#include <stdio.h>
#include <gsl/gsl_blas.h>
#include <time.h>
#include <stdlib.h>
#include <limits.h>
//gcc program.c -lgsl -lgslcblas -lm -o program
void saveTime(FILE *fp, char *type, int vSize, clock_t start, clock_t end) {
//save time and size to file
fprintf(fp, "%s, %d, %f\n", type, vSize, ((double) (end - start)) / CLOCKS_PER_SEC);
}
void ddot(FILE *fp, int vSize, gsl_vector *A, gsl_vector *B) {
clock_t start, end;
double result = 0;
start = clock();
gsl_blas_ddot(A, B, &result);
end = clock();
//save time and size to file
saveTime(fp, "ddot", vSize, start, end);
}
void dgemv(FILE *fp, int vSize, gsl_vector *A) {
clock_t start, end;
gsl_matrix *M = gsl_matrix_alloc(vSize, vSize);
gsl_vector *B = gsl_vector_alloc(vSize);
for(int i = 0; i < vSize; i++) {
for(int j = 0; j < vSize; j++) {
gsl_matrix_set(M, i, j, (double) rand() * i / (double) (rand() + 1));
}
gsl_vector_set(B, i, rand() * i / (rand() + 1));
}
start = clock();
gsl_blas_dgemv(CblasNoTrans, 1.0, M, A, 0.0, B);
end = clock();
saveTime(fp, "dgemv", vSize, start, end);
gsl_matrix_free(M);
gsl_vector_free(B);
}
void measure(FILE *fp, int size) {
gsl_vector *x = gsl_vector_alloc(size);
gsl_vector *y = gsl_vector_alloc(size);
for(int t = 0; t < 10; t++) {
for(int i = 0; i < size; i++) {
gsl_vector_set(x, i, rand() * i / (rand() + 1));
gsl_vector_set(y, i, rand() * i / (rand() + 1));
}
ddot(fp, size, x, y);
dgemv(fp, size, x);
}
gsl_vector_free(x);
gsl_vector_free(y);
}
int main (void) {
//uruchomić i zmierzyć czasy działania obydwu funkcji dla różnych rozmiarów wektorów -> 10 pomiarów dla każdego rozmiaru wektora
FILE *fp;
srand(time(NULL));
fp = fopen("wyniki.csv", "w+");
fprintf(fp, "typ, rozmiar, czas\n"); //make headline
for(int i = 100; i < 1000; i += 100) {
int n = i;
measure(fp, n);
n += i;
}
fclose(fp);
return 0;
}
| {
"alphanum_fraction": 0.5730282376,
"avg_line_length": 26,
"ext": "c",
"hexsha": "d5812851fc54f0a7102cf7e09ea2fc6397814f7f",
"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": "58efc9185a149992951c1c2875ffb72d07d0bd55",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "katabana/numerical-methods",
"max_forks_repo_path": "lab2/program.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "58efc9185a149992951c1c2875ffb72d07d0bd55",
"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": "katabana/numerical-methods",
"max_issues_repo_path": "lab2/program.c",
"max_line_length": 152,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "58efc9185a149992951c1c2875ffb72d07d0bd55",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "katabana/numerical-methods",
"max_stars_repo_path": "lab2/program.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 693,
"size": 2054
} |
#pragma once
#include "Core/Pointers.h"
#include "Graphics/GraphicsResource.h"
#include "Graphics/TextureInfo.h"
#include <glad/gl.h>
#include <gsl/span>
#include <vector>
class Texture;
struct Viewport;
namespace Fb
{
enum class DepthStencilType
{
None,
Depth24Stencil8,
Depth32FStencil8
};
enum class Target
{
Framebuffer = GL_FRAMEBUFFER,
ReadFramebuffer = GL_READ_FRAMEBUFFER,
DrawFramebuffer = GL_DRAW_FRAMEBUFFER
};
enum class CubeFace
{
Front,
Back,
Top,
Bottom,
Left,
Right
};
struct Specification
{
GLsizei width = 0;
GLsizei height = 0;
GLsizei samples = 0;
bool cubeMap = false;
DepthStencilType depthStencilType = DepthStencilType::Depth24Stencil8;
gsl::span<const Tex::InternalFormat> colorAttachmentFormats;
bool operator==(const Specification& other) const;
};
struct Attachments
{
SPtr<Texture> depthStencilAttachment;
std::vector<SPtr<Texture>> colorAttachments;
};
Attachments generateAttachments(const Specification& specification);
}
namespace std
{
template<>
struct hash<Fb::Specification>
{
size_t operator()(const Fb::Specification& specification) const;
};
}
class Framebuffer : public GraphicsResource
{
public:
Framebuffer();
Framebuffer(const Framebuffer& other) = delete;
Framebuffer(Framebuffer&& other);
~Framebuffer();
Framebuffer& operator=(const Framebuffer& other) = delete;
Framebuffer& operator=(Framebuffer&& other);
private:
void move(Framebuffer&& other);
void release();
public:
using SpecificationType = Fb::Specification;
static SPtr<Framebuffer> create(const Fb::Specification& specification);
static const char* labelSuffix();
static void blit(Framebuffer& source, Framebuffer& destination, GLenum readBuffer, GLenum drawBuffer, GLbitfield mask, GLenum filter);
static void bindDefault(Fb::Target target = Fb::Target::Framebuffer);
void bind(Fb::Target target = Fb::Target::Framebuffer);
bool isBound(Fb::Target target = Fb::Target::Framebuffer) const;
const Fb::Attachments& getAttachments() const
{
return attachments;
}
const SPtr<Texture>& getDepthStencilAttachment() const;
SPtr<Texture> getColorAttachment(int index) const;
void setAttachments(Fb::Attachments newAttachments);
bool getViewport(Viewport& viewport) const;
bool isCubeMap() const;
void setActiveFace(Fb::CubeFace face);
private:
const SPtr<Texture>* getFirstValidAttachment() const;
Fb::Attachments attachments;
};
| {
"alphanum_fraction": 0.6984428409,
"avg_line_length": 22.1260504202,
"ext": "h",
"hexsha": "fb48ddaf9a3810252df957a26429542158156e72",
"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": "955f36bc95b6829bf1a1a89b430df7816c065ac0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "aaronmjacobs/Swap",
"max_forks_repo_path": "Source/Graphics/Framebuffer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0",
"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": "aaronmjacobs/Swap",
"max_issues_repo_path": "Source/Graphics/Framebuffer.h",
"max_line_length": 137,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "955f36bc95b6829bf1a1a89b430df7816c065ac0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "aaronmjacobs/Swap",
"max_stars_repo_path": "Source/Graphics/Framebuffer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 603,
"size": 2633
} |
#pragma once
#include <gsl/gsl_math.h>
double brent(gsl_function *F, double x_lo, double x_hi, int *status1, int *status2); | {
"alphanum_fraction": 0.75,
"avg_line_length": 31,
"ext": "h",
"hexsha": "0cfca3d5716769af1330eaae921c3d3f9a701791",
"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": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "eduardomgutierrez/RIAF_radproc",
"max_forks_repo_path": "src/lib/nrMath/brent.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12",
"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": "eduardomgutierrez/RIAF_radproc",
"max_issues_repo_path": "src/lib/nrMath/brent.h",
"max_line_length": 84,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "eduardomgutierrez/RIAF_radproc",
"max_stars_repo_path": "src/lib/nrMath/brent.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z",
"num_tokens": 39,
"size": 124
} |
#ifndef __BaseStar_h__
#define __BaseStar_h__
#include <gsl/gsl_roots.h>
#include <gsl/gsl_sf_erf.h>
#include "constants.h"
#include "typedefs.h"
#include "profiling.h"
#include "utils.h"
#include "vector3d.h"
#include "Options.h"
#include "Log.h"
#include "Errors.h"
class BaseStar {
public:
BaseStar();
BaseStar(const unsigned long int p_RandomSeed,
const double p_MZAMS,
const double p_Metallicity,
const KickParameters p_KickParameters,
const double p_RotationalVelocity = -1.0);
virtual ~BaseStar() {}
// object identifiers - all classes have these
OBJECT_ID ObjectId() const { return m_ObjectId; }
OBJECT_TYPE ObjectType() const { return m_ObjectType; }
STELLAR_TYPE InitialStellarType() const { return m_InitialStellarType; }
STELLAR_TYPE StellarType() const { return m_StellarType; }
STELLAR_TYPE StellarTypePrev() const { return m_StellarTypePrev; }
// getters - alphabetically
double Age() const { return m_Age; }
double AngularMomentum() const { return CalculateGyrationRadius() * m_Radius * RSOL_TO_AU * m_Radius * RSOL_TO_AU * m_Omega; }
double BindingEnergy_Fixed() const { return m_BindingEnergies.fixed; }
double BindingEnergy_Nanjing() const { return m_BindingEnergies.nanjing; }
double BindingEnergy_Loveridge() const { return m_BindingEnergies.loveridge; }
double BindingEnergy_LoveridgeWinds() const { return m_BindingEnergies.loveridgeWinds; }
double BindingEnergy_Kruckow() const { return m_BindingEnergies.kruckow; }
bool CHonMS() const { return m_CHE; }
double COCoreMass() const { return m_COCoreMass; }
double CoreMass() const { return m_CoreMass; }
int DominantMassLossRate() const { return static_cast<int>(m_DominantMassLossRate); }
double Dt() const { return m_Dt; }
double DtPrev() const { return m_DtPrev; }
ERROR Error() const { return m_Error; }
bool ExperiencedCCSN() const { return (m_SupernovaDetails.events.past & SN_EVENT::CCSN) == SN_EVENT::CCSN; }
bool ExperiencedECSN() const { return (m_SupernovaDetails.events.past & SN_EVENT::ECSN) == SN_EVENT::ECSN; }
bool ExperiencedPISN() const { return (m_SupernovaDetails.events.past & SN_EVENT::PISN) == SN_EVENT::PISN; }
bool ExperiencedPPISN() const { return (m_SupernovaDetails.events.past & SN_EVENT::PPISN) == SN_EVENT::PPISN; }
SN_EVENT ExperiencedSN_Type() const { return utils::SNEventType(m_SupernovaDetails.events.past); }
bool ExperiencedUSSN() const { return (m_SupernovaDetails.events.past & SN_EVENT::USSN) == SN_EVENT::USSN; }
double HeCoreMass() const { return m_HeCoreMass; }
bool IsCCSN() const { return (m_SupernovaDetails.events.current & SN_EVENT::CCSN) == SN_EVENT::CCSN; }
virtual bool IsDegenerate() const { return false; } // default is not degenerate - White Dwarfs, NS and BH are degenerate
bool IsECSN() const { return (m_SupernovaDetails.events.current & SN_EVENT::ECSN) == SN_EVENT::ECSN; }
virtual bool IsMassRatioUnstable(const double p_AccretorMass, const bool p_AccretorIsDegenerate) const { return false; } // default is stable
bool IsOneOf(const STELLAR_TYPE_LIST p_List) const;
bool IsPISN() const { return (m_SupernovaDetails.events.current & SN_EVENT::PISN) == SN_EVENT::PISN; }
bool IsPPISN() const { return (m_SupernovaDetails.events.current & SN_EVENT::PPISN) == SN_EVENT::PPISN; }
bool IsUSSN() const { return (m_SupernovaDetails.events.current & SN_EVENT::USSN) == SN_EVENT::USSN; }
double Lambda_Dewi() const { return m_Lambdas.dewi; }
double Lambda_Fixed() const { return m_Lambdas.fixed; }
double Lambda_Kruckow() const { return m_Lambdas.kruckow; }
double Lambda_KruckowBottom() const { return m_Lambdas.kruckowBottom; }
double Lambda_KruckowMiddle() const { return m_Lambdas.kruckowMiddle; }
double Lambda_KruckowTop() const { return m_Lambdas.kruckowTop; }
double Lambda_Loveridge() const { return m_Lambdas.loveridge; }
double Lambda_LoveridgeWinds() const { return m_Lambdas.loveridgeWinds; }
double Lambda_Nanjing() const { return m_Lambdas.nanjing; }
bool LBV_Phase_Flag() const { return m_LBVphaseFlag; }
double Luminosity() const { return m_Luminosity; }
double Mass() const { return m_Mass; }
double Mass0() const { return m_Mass0; }
double MassPrev() const { return m_MassPrev; }
STYPE_VECTOR MassTransferDonorHistory() const { return m_MassTransferDonorHistory; }
std::string MassTransferDonorHistoryString() const;
double Mdot() const { return m_Mdot; }
double Metallicity() const { return m_Metallicity; }
double MZAMS() const { return m_MZAMS; }
double Omega() const { return m_Omega; }
double OmegaCHE() const { return m_OmegaCHE; }
double OmegaBreak() const { return CalculateOmegaBreak(); }
double OmegaPrev() const { return m_OmegaPrev; }
double OmegaZAMS() const { return m_OmegaZAMS; }
COMPAS_VARIABLE PropertyValue(const T_ANY_PROPERTY p_Property) const;
double Pulsar_MagneticField() const { return m_PulsarDetails.magneticField; }
double Pulsar_SpinPeriod() const { return m_PulsarDetails.spinPeriod; }
double Pulsar_SpinFrequency() const { return m_PulsarDetails.spinFrequency; }
double Pulsar_SpinDownRate() const { return m_PulsarDetails.spinDownRate; }
double Radius() const { return m_Radius; }
double RadiusPrev() const { return m_RadiusPrev; }
unsigned long int RandomSeed() const { return m_RandomSeed; }
double RZAMS() const { return m_RZAMS; }
double SN_CoreMassAtCOFormation() const { return m_SupernovaDetails.coreMassAtCOFormation; }
double SN_COCoreMassAtCOFormation() const { return m_SupernovaDetails.COCoreMassAtCOFormation; }
SupernovaDetailsT SN_Details() const { return m_SupernovaDetails; }
double SN_DrawnKickMagnitude() const { return m_SupernovaDetails.drawnKickMagnitude; }
double SN_EccentricAnomaly() const { return m_SupernovaDetails.eccentricAnomaly; }
double SN_FallbackFraction() const { return m_SupernovaDetails.fallbackFraction; }
double SN_HeCoreMassAtCOFormation() const { return m_SupernovaDetails.HeCoreMassAtCOFormation; }
bool SN_IsHydrogenPoor() const { return m_SupernovaDetails.isHydrogenPoor; }
double SN_KickMagnitude() const { return m_SupernovaDetails.kickMagnitude; }
double SN_MeanAnomaly() const { return m_SupernovaDetails.meanAnomaly; }
double SN_Phi() const { return m_SupernovaDetails.phi; }
double SN_TotalMassAtCOFormation() const { return m_SupernovaDetails.totalMassAtCOFormation; }
double SN_TrueAnomaly() const { return m_SupernovaDetails.trueAnomaly; }
double SN_Theta() const { return m_SupernovaDetails.theta; }
SN_EVENT SN_Type() const { return utils::SNEventType(m_SupernovaDetails.events.current); }
double SN_KickMagnitudeRandom() const { return m_SupernovaDetails.kickMagnitudeRandom; }
double Speed() const { return m_ComponentVelocity.Magnitude(); }
COMPAS_VARIABLE StellarPropertyValue(const T_ANY_PROPERTY p_Property) const;
double Tau() const { return m_Tau; }
double Temperature() const { return m_Temperature; }
double Time() const { return m_Time; }
double Timescale(TIMESCALE p_Timescale) const { return m_Timescales[static_cast<int>(p_Timescale)]; }
double XExponent() const { return m_XExponent; }
// setters
void SetInitialType(STELLAR_TYPE p_InitialType) { m_InitialStellarType = p_InitialType; } // JR Could do some sanity checks here
void SetOmega(double p_vRot) { if (p_vRot >= 0.0) m_Omega = p_vRot; }; // Do nothing if sanity check fails (JR: I don't really like this, but I think unavoidable - at least for now)
void SetSNCurrentEvent(SN_EVENT p_SNEvent) { m_SupernovaDetails.events.current |= p_SNEvent; } // Set supernova primary event/state for current timestep
void SetSNPastEvent(const SN_EVENT p_SNEvent) { m_SupernovaDetails.events.past |= p_SNEvent; } // Set supernova primary event/state for any past timestep
void UpdateComponentVelocity(const Vector3d p_newVelocity);
void UpdateMassTransferDonorHistory();
// member functions - alphabetically
void ApplyMassTransferRejuvenationFactor() { m_Age *= CalculateMassTransferRejuvenationFactor(); } // Apply age rejuvenation factor
void CalculateBindingEnergies(const double p_CoreMass, const double p_EnvMass, const double p_Radius);
double CalculateDynamicalTimescale() const { return CalculateDynamicalTimescale_Static(m_Mass, m_Radius); } // Use class member variables
double CalculateEddyTurnoverTimescale();
virtual void CalculateGBParams(const double p_Mass, DBL_VECTOR &p_GBParams) { } // Default is NO-OP
virtual void CalculateGBParams() { CalculateGBParams(m_Mass0, m_GBParams); } // Use class member variables
virtual double CalculateGyrationRadius() const { return 0.0; } // Default is 0.0
void CalculateLambdas() { CalculateLambdas(m_Mass - m_CoreMass); } // Use class member variables
void CalculateLambdas(const double p_EnvMass);
virtual DBL_DBL CalculateMassAcceptanceRate(const double p_DonorMassRate,
const double p_AccretorMassRate = 0.0);
double CalculateMassLossValues(const bool p_UpdateMDot = false, const bool p_UpdateMDt = false); // JR: todo: better name?
virtual double CalculateMomentOfInertia(const double p_RemnantRadius = 0.0) const { return 0.0; } // Use inheritance hierarchy
virtual double CalculateMomentOfInertiaAU(const double p_RemnantRadius = 0.0) const { return 0.0; } // Use inheritance hierarchy
double CalculateNuclearTimescale() const { return CalculateNuclearTimescale_Static(m_Mass, m_Luminosity); } // Use class member variables
double CalculateOmegaCHE(const double p_MZAMS, const double p_Metallicity) const;
double CalculateRadialChange() const { return (utils::Compare(m_RadiusPrev,0)<=0)? 0 : std::abs(m_Radius - m_RadiusPrev) / m_RadiusPrev; } // Return fractional radial change (if previous radius is negative or zero, return 0 to avoid NaN
double CalculateRadialExpansionTimescale() const { return CalculateRadialExpansionTimescale_Static(m_StellarType, m_StellarTypePrev, m_Radius, m_RadiusPrev, m_DtPrev); } // Use class member variables
void CalculateSNAnomalies(const double p_Eccentricity);
double CalculateSNKickMagnitude(const double p_RemnantMass, const double p_EjectaMass, const STELLAR_TYPE p_StellarType);
double CalculateThermalMassAcceptanceRate(const double p_Radius) const;
double CalculateThermalMassAcceptanceRate() const { return CalculateThermalMassAcceptanceRate(m_Radius); }
virtual double CalculateThermalMassLossRate() const { return m_Mass / CalculateThermalTimescale(); } // Use class member variables - and inheritance hierarchy
virtual double CalculateThermalTimescale(const double p_Radius) const; // Use inheritance hierarchy
virtual double CalculateThermalTimescale() const { return CalculateThermalTimescale(m_Radius); } // Use inheritance hierarchy
double CalculateTimestep();
virtual double CalculateZeta(ZETA_PRESCRIPTION p_ZetaPrescription) { return 0.0; } // Use inheritance hierarchy
void ClearCurrentSNEvent() { m_SupernovaDetails.events.current = SN_EVENT::NONE; } // Clear supernova event/state for current timestep
virtual ENVELOPE DetermineEnvelopeType() const { return ENVELOPE::REMNANT; } // Default is REMNANT - but should never be called
void IncrementOmega(const double p_OmegaDelta) { m_Omega += p_OmegaDelta; } // Apply delta to current m_Omega
void ResolveAccretion(const double p_AccretionMass) { m_Mass = std::max(0.0, m_Mass + p_AccretionMass); } // Handles donation and accretion - won't let mass go negative
virtual STELLAR_TYPE ResolveEnvelopeLoss(bool p_NoCheck = false) { return m_StellarType; }
virtual void ResolveMassLoss();
virtual STELLAR_TYPE ResolveRemnantAfterEnvelopeLoss() { return m_StellarType; }
void SetStellarTypePrev(const STELLAR_TYPE p_StellarTypePrev) { m_StellarTypePrev = p_StellarTypePrev; }
void StashSupernovaDetails(const STELLAR_TYPE p_StellarType) { LOGGING->StashSSESupernovaDetails(this, p_StellarType); }
virtual void UpdateAgeAfterMassLoss() { } // Default is NO-OP
STELLAR_TYPE UpdateAttributesAndAgeOneTimestep(const double p_DeltaMass,
const double p_DeltaMass0,
const double p_DeltaTime,
const bool p_ForceRecalculate);
virtual void UpdateInitialMass() { } // Default is NO-OP
virtual void UpdateMagneticFieldAndSpin(const bool p_CommonEnvelope,
const bool p_RecyclesNS,
const double p_Stepsize,
const double p_MassGainPerTimeStep,
const double p_Epsilon) { } // Default is NO-OP
// printing functions
bool PrintDetailedOutput(const int p_Id) const { return OPTIONS->DetailedOutput() ? LOGGING->LogSSEDetailedOutput(this, p_Id) : true; } // Write record to SSE Detailed Output log file
bool PrintSupernovaDetails() const { return LOGGING->LogSSESupernovaDetails(this); } // Write record to SSE Supernovae log file
bool PrintStashedSupernovaDetails() { return LOGGING->LogStashedSSESupernovaDetails(this); } // Write record to SSE Supernovae log file
bool PrintSwitchLog() const { return OPTIONS->SwitchLog() ? LOGGING->LogSSESwitchLog(this) : true; } // Write record to SSE Switchlog log file
bool PrintSystemParameters() const { return LOGGING->LogSSESystemParameters(this); } // Write record to SSE System Parameters file
protected:
OBJECT_ID m_ObjectId; // Instantiated object's unique object id
OBJECT_TYPE m_ObjectType; // Instantiated object's object type
STELLAR_TYPE m_InitialStellarType; // Stellar type at birth, defined in Hurley et al. 2000
STELLAR_TYPE m_StellarType; // Stellar type defined in Hurley et al. 2000
ERROR m_Error; // Records most recent error encountered for this star
// member variables - alphabetical in groups
bool m_CHE; // CHE flag - true if the star spent entire MS as a CH star; false if evolved CH->MS
// Stellar variables
unsigned long int m_RandomSeed; // Seeds the random number generator for this star
// Zero Age Main Sequence
double m_LZAMS; // ZAMS Luminosity
double m_MZAMS; // ZAMS Mass
double m_OmegaZAMS; // ZAMS Angular Frequency
double m_OmegaCHE; // Minimum angular frequency at which CHE will occur (calculated at ZAMS)
double m_RZAMS; // ZAMS Radius
double m_TZAMS; // ZAMS Temperature
// Effective Zero Age Main Sequence
double m_LZAMS0; // Effective ZAMS Luminosity
double m_RZAMS0; // Effective ZAMS Radius
double m_TZAMS0; // Effective ZAMS Temperature
// Current timestep variables
double m_Age; // Current effective age (changes with mass loss/gain)(myrs)
double m_COCoreMass; // Current CO core mass (Msol)
double m_CoreMass; // Current core mass (Msol)
double m_CoreRadius; // Current core radius (Rsol) JR: todo: I don't think this is used anywhere...
double m_Dt; // Current timestep (myrs)
double m_HeCoreMass; // Current He core mass (Msol)
bool m_LBVphaseFlag; // Flag to know if the star satisfied the conditions, at any point in its evolution, to be considered a Luminous Blue Variable (LBV)
double m_Luminosity; // Current luminosity (Lsol)
double m_Mass; // Current mass (Msol)
double m_Mass0; // Current effective initial mass (Msol) JR: todo: fix this one day - it is not always initial mass
double m_MinimumLuminosityOnPhase; // JR: Only required for CHeB stars, but only needs to be calculated once per star
double m_Mdot; // Current mass loss rate (Msol per ?)
MASS_LOSS_TYPE m_DominantMassLossRate; // Current dominant mass loss rate
double m_Mu; // Current small envelope parameter mu
double m_Omega; // Current angular frequency (yr-1)
double m_Radius; // Current radius (Rsol)
double m_Tau; // Relative time
double m_Temperature; // Current temperature (Tsol)
double m_Time; // Current physical time the star has been evolved(myrs)
// Previous timestep variables
double m_DtPrev; // Previous timestep
double m_MassPrev; // Previous mass (Msol)
double m_OmegaPrev; // Previous angular frequency (yr-1)
double m_RadiusPrev; // Previous radius (Rsol)
STELLAR_TYPE m_StellarTypePrev; // Stellar type at previous timestep
// Metallicity variables
double m_LogMetallicityRho; // logMetallicityXi + 1.0 - called rho in Hurley et al 2000
double m_LogMetallicitySigma; // log10(Metallicity) - called sigma in Hurley et al 2000
double m_LogMetallicityXi; // log10(Metallicity / Zsol) - called xi in Hurley et al 2000
double m_Metallicity; // Metallicity
// Metallicity dependent constants
double m_Alpha1; // alpha1 in Hurly et al. 2000, just after eq 49
double m_Alpha3; // alpha4 in Hurley et al. 2000, just after eq 56
double m_Alpha4; // alpha4 in Hurley et al. 2000, just after eq 57
double m_XExponent; // exponent to which R depends on M - 'x' in Hurley et al. 2000, eq 47
// constants only calculated once
double m_BaryonicMassOfMaximumNeutronStarMass; // baryonic mass of MaximumNeutronStarMass
// JR:
// I initially implemented the following vectors as unordered_maps. The code worked
// quite well, except for one small problem - access times (presumably due to hashing)
// were prohibitive when accessed hundreds of thousands, and in some cases, millions,
// of times as we evolve the star. So I used vectors instead - the code is not as
// elegant, but performance is better by an order of magnitude
// Timescales, Giant Branch parameters, mass cutoffs
DBL_VECTOR m_GBParams; // Giant Branch Parameters
DBL_VECTOR m_MassCutoffs; // Mass cutoffs
DBL_VECTOR m_Timescales; // Timescales
// Luminosity, Radius, a(n) and b(n) coefficients
DBL_VECTOR m_AnCoefficients; // a(n) coefficients
DBL_VECTOR m_BnCoefficients; // b(n) coefficients
DBL_VECTOR m_LCoefficients; // Luminosity coefficients
DBL_VECTOR m_RCoefficients; // Radius coefficients
// Luminosity, Radius and Gamma constants
// JR:
// These are calculated in CalculateAnCoefficients()
// Calculating the a(n) coefficients requires one of the R constants, and the L, R and Gamma
// constants are calculated using the a(n) coefficients, so it seemed logical to calculate
// them all in the same function
DBL_VECTOR m_GammaConstants; // Gamma constants
DBL_VECTOR m_LConstants; // Luminosity constants
DBL_VECTOR m_RConstants; // Radius constants
// Binding energies, Lambdas and Zetas
BindingEnergiesT m_BindingEnergies; // Binding enery values
LambdasT m_Lambdas; // Lambda values
// Stellar details squirrelled away...
SupernovaDetailsT m_SupernovaDetails; // Supernova attributes
PulsarDetailsT m_PulsarDetails; // Pulsar attributes
// Star vector velocity
Vector3d m_ComponentVelocity; // Isolated star velocity vector (binary's center-of-mass velocity for bound binary)
// Star mass transfer history
STYPE_VECTOR m_MassTransferDonorHistory; // List of MT donor stellar types - mostly relevent for binary stars
// member functions - alphabetically
void AgeOneTimestepPreamble(const double p_DeltaTime);
double ApplyBlackHoleKicks(const double p_vK, const double p_FallbackFraction, const double p_BlackHoleMass);
double CalculateAlpha1() const;
double CalculateAlpha3() const;
double CalculateAlpha4() const;
void CalculateAnCoefficients(DBL_VECTOR &p_AnCoefficients,
DBL_VECTOR &p_LConstants,
DBL_VECTOR &p_RConstants,
DBL_VECTOR &p_GammaConstants);
virtual void CalculateAndSetPulsarParameters() { } // NO-OP for most stellar types
double CalculateBindingEnergy(const double p_CoreMass, const double p_EnvMass, const double p_Radius, const double p_Lambda) const;
void CalculateBnCoefficients(DBL_VECTOR &p_BnCoefficients);
virtual double CalculateCOCoreMassAtPhaseEnd() const { return m_COCoreMass; } // Default is NO-OP
virtual double CalculateCOCoreMassOnPhase() const { return m_COCoreMass; } // Default is NO-OP
virtual double CalculateCoreMassAtPhaseEnd() const { return m_CoreMass; } // Default is NO-OP
static double CalculateCoreMassGivenLuminosity_Static(const double p_Luminosity, const DBL_VECTOR &p_GBParams);
virtual double CalculateCoreMassOnPhase() const { return m_CoreMass; } // Default is NO-OP
static double CalculateDynamicalTimescale_Static(const double p_Mass, const double p_Radius);
virtual double CalculateEddingtonCriticalRate() const { return 2.08E-3 / 1.7 * m_Radius * MYR_TO_YEAR; } // Hurley+, 2002, Eq. (67); should never be called...
double CalculateGBRadiusXExponent() const;
virtual double CalculateHeCoreMassAtPhaseEnd() const { return m_HeCoreMass; } // Default is NO-OP
virtual double CalculateHeCoreMassOnPhase() const { return m_HeCoreMass; } // Default is NO-OP
static double CalculateHeRateConstant_Static() { return HE_RATE_CONSTANT; } // Only >= CHeB stars need AHe, but no drama if other stars calculate (retrieve it) - it's only a constant (we could just use the constant inline...)
static double CalculateHHeRateConstant_Static() { return HHE_RATE_CONSTANT; } // Only TPAGB stars need AHHe, but no drama if other stars calculate (retrieve it) - it's only a constant (we could just use the constant inline...)
static double CalculateInitialEnvelopeMass_Static(const double p_Mass);
virtual double CalculateLambdaDewi() const { SHOW_WARN(ERROR::NO_LAMBDA_DEWI, "Default used: 1.0"); return 1.0; } // Not supported: show error
double CalculateLambdaKruckow(const double p_Radius, const double p_Alpha) const;
double CalculateLambdaLoveridgeEnergyFormalism(const double p_EnvMass, const double p_IsMassLoss = false) const;
virtual double CalculateLambdaNanjing() const { SHOW_WARN(ERROR::NO_LAMBDA_NANJING, "Default used: 1.0"); return 1.0; } // Not supported: show error
void CalculateLCoefficients(const double p_LogMetallicityXi, DBL_VECTOR &p_LCoefficients);
double CalculateLifetimeToBAGB(const double p_tHeI, const double p_tHe) const;
double CalculateLifetimeToBGB(const double p_Mass) const;
double CalculateLogBindingEnergyLoveridge(bool p_IsMassLoss) const;
double CalculateLuminosityAtBAGB(double p_Mass) const;
virtual double CalculateLuminosityAtPhaseEnd() const { return m_Luminosity; } // Default is NO-OP
double CalculateLuminosityAtZAMS(const double p_MZAMS);
double CalculateLuminosityGivenCoreMass(const double p_CoreMass) const;
virtual double CalculateLuminosityOnPhase() const { return m_Luminosity; } // Default is NO-OP
void CalculateMassCutoffs(const double p_Metallicity, const double p_LogMetallicityXi, DBL_VECTOR &p_MassCutoffs);
static double CalculateMassLoss_Static(const double p_Mass, const double p_Mdot, const double p_Dt);
double CalculateMassLossRate();
virtual double CalculateMassLossRateHurley();
double CalculateMassLossRateKudritzkiReimers() const;
double CalculateMassLossRateLBV(const LBV_PRESCRIPTION p_LBV_prescription);
double CalculateMassLossRateLBVHurley(const double p_HD_limit_fac) const;
double CalculateMassLossRateLBVBelczynski() const;
double CalculateMassLossRateNieuwenhuijzenDeJager() const;
double CalculateMassLossRateOB(const double p_Teff);
double CalculateMassLossRateVassiliadisWood() const;
virtual double CalculateMassLossRateVink();
double CalculateMassLossRateWolfRayetZDependent(const double p_Mu) const;
double CalculateMassLossRateWolfRayet3() const; // JR: Never called - do we need it?
double CalculateMassLossRateWolfRayet(const double p_Mu) const;
virtual double CalculateMassTransferRejuvenationFactor() const;
double CalculateMaximumCoreMass(double p_Mass) const;
static double CalculateNuclearTimescale_Static(const double p_Mass, const double p_Luminosity);
double CalculateOmegaBreak() const;
static double CalculateOStarRotationalVelocityAnalyticCDF_Static(const double p_Ve);
static double CalculateOStarRotationalVelocityAnalyticCDFInverse_Static(double p_Ve, void *p_Params);
static double CalculateOStarRotationalVelocity_Static(const double p_Xmin, const double p_Xmax);
double CalculatePerturbationB(const double p_Mass) const;
double CalculatePerturbationC(double p_Mass) const;
virtual double CalculatePerturbationMu() const { return m_Mu; } // Default is NO-OP
virtual double CalculatePerturbationMuAtPhaseEnd() const { return CalculatePerturbationMuOnPhase(); } // Same as on phase
virtual double CalculatePerturbationMuOnPhase() const { return CalculatePerturbationMu(); }
double CalculatePerturbationQ(const double p_Radius, const double p_Rc) const;
double CalculatePerturbationR(const double p_Mu, const double p_Mass, const double p_Radius, const double p_Rc) const;
double CalculatePerturbationS(const double p_Mu, const double p_Mass) const;
static double CalculateRadialExpansionTimescale_Static(const STELLAR_TYPE p_StellarType,
const STELLAR_TYPE p_StellarTypePrev,
const double p_Radius,
const double p_RadiusPrev,
const double p_DtPrev);
virtual double CalculateRadialExtentConvectiveEnvelope() const { return m_Radius; } // default for stars with no convective envelope
virtual double CalculateRadiusAtPhaseEnd() const { return m_Radius; } // Default is NO-OP
double CalculateRadiusAtZAMS(const double p_MZAMS) const;
virtual double CalculateRadiusOnPhase() const { return m_Radius; } // Default is NO-OP
virtual std::tuple <double, STELLAR_TYPE> CalculateRadiusAndStellarTypeOnPhase() const { return std::make_tuple(CalculateRadiusOnPhase(), m_StellarType); }
void CalculateRCoefficients(const double p_LogMetallicityXi, DBL_VECTOR &p_RCoefficients);
double CalculateRotationalVelocity(double p_MZAMS) const;
virtual double CalculateTauOnPhase() const { return m_Tau; } // Default is NO-OP
virtual double CalculateTauAtPhaseEnd() const { return m_Tau; } // Default is NO-OP
virtual double CalculateTemperatureAtPhaseEnd() const { return CalculateTemperatureAtPhaseEnd(m_Luminosity, m_Radius); }
virtual double CalculateTemperatureAtPhaseEnd(const double p_Luminosity, const double p_Radius) const { return CalculateTemperatureOnPhase(p_Luminosity, p_Radius); } // Same as on phase
double CalculateTemperatureKelvinOnPhase(const double p_Luminosity, const double p_Radius) const;
virtual double CalculateTemperatureOnPhase() const { return CalculateTemperatureOnPhase(m_Luminosity, m_Radius); }
virtual double CalculateTemperatureOnPhase(const double p_Luminosity, const double p_Radius) const { return CalculateTemperatureOnPhase_Static(p_Luminosity, p_Radius); }
static double CalculateTemperatureOnPhase_Static(const double p_Luminosity, const double p_Radius);
virtual void CalculateTimescales() { CalculateTimescales(m_Mass0, m_Timescales); } // Use class member variables
virtual void CalculateTimescales(const double p_Mass, DBL_VECTOR &p_Timescales) { } // Default is NO-OP
double CalculateZadiabaticHurley2002(const double p_CoreMass) const;
double CalculateZadiabaticSPH(const double p_CoreMass) const;
double CalculateZadiabatic(ZETA_PRESCRIPTION p_ZetaPrescription);
double CalculateZAMSAngularFrequency(const double p_MZAMS, const double p_RZAMS) const;
virtual double ChooseTimestep(const double p_Time) const { return m_Dt; }
double DrawKickMagnitudeBrayEldridge(const double p_EjectaMass,
const double p_RemnantMass,
const double p_Alpha,
const double p_Beta) const;
double DrawKickMagnitudeDistributionFlat(const double p_MaxVK, const double p_Rand) const;
double DrawKickMagnitudeDistributionMaxwell(const double p_Sigma, const double p_Rand) const;
double DrawRemnantKickMuller(const double p_COCoreMass) const;
double DrawRemnantKickMullerMandel(const double p_COCoreMass,
const double p_Rand,
const double p_RemnantMass) const;
double DrawSNKickMagnitude(const double p_Sigma,
const double p_COCoreMass,
const double p_Rand,
const double p_EjectaMass,
const double p_RemnantMass) const;
virtual void EvolveOneTimestepPreamble() { }; // Default is NO-OP
STELLAR_TYPE EvolveOnPhase();
virtual STELLAR_TYPE EvolveToNextPhase() { return m_StellarType; }
virtual bool IsEndOfPhase() const { return false; }
virtual bool IsSupernova() const { return false; }
double LimitTimestep(const double p_Dt);
/*
* Perturb Luminosity and Radius
*
* See Hurley et al. 2000, section 6.3
*
* The default is no perturbation - this function does nothing and is called
* only if the stellar class doesn't define its own perturbation function.
* See the stellar class perturbation functions for perturbation details specific
* to the stellar class.
*
* Perturbation is disabled by default when DEBUG is enabled - except when
* DEBUG_PERTURB is defined (see below). The stellar class perturbation
* functions are defined away if DEBUG is defined - so this generic Star
* function is called (and does nothing).
*
* If DEBUG_PERTURB is defined then perturbation is not disabled while debbuging.
* To enable perturbation while DEBUG is enabled, define DEBUG_PERTURB.
*/
virtual void PerturbLuminosityAndRadius() { } // NO-OP
virtual void PerturbLuminosityAndRadiusAtPhaseEnd() { PerturbLuminosityAndRadiusOnPhase(); } // Same as on phase
virtual void PerturbLuminosityAndRadiusOnPhase() { PerturbLuminosityAndRadius(); }
STELLAR_TYPE ResolveEndOfPhase();
virtual void ResolveHeliumFlash() { }
virtual STELLAR_TYPE ResolveSkippedPhase() { return EvolveToNextPhase(); } // Default is evolve to next phase
virtual STELLAR_TYPE ResolveSupernova() { return m_StellarType; } // Default is NO-OP
virtual void SetSNHydrogenContent() { m_SupernovaDetails.isHydrogenPoor = false; } // Default is false
bool ShouldBeMasslessRemnant() const { return (m_Mass <= 0.0 || m_StellarType==STELLAR_TYPE::MASSLESS_REMNANT); }
virtual bool ShouldEvolveOnPhase() const { return true; }
virtual bool ShouldSkipPhase() const { return false; } // Default is false
void UpdateAttributesAndAgeOneTimestepPreamble(const double p_DeltaMass, const double p_DeltaMass0, const double p_DeltaTime);
};
#endif // __BaseStar_h__
| {
"alphanum_fraction": 0.4705525443,
"avg_line_length": 89.4104882459,
"ext": "h",
"hexsha": "af8f3ad437651c145c2a2a593be01747405a9e6f",
"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": "c97632e0a5abddd066f8a01931bf9f70729b4e05",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiekeVanSon/COMPAS",
"max_forks_repo_path": "src/BaseStar.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c97632e0a5abddd066f8a01931bf9f70729b4e05",
"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": "LiekeVanSon/COMPAS",
"max_issues_repo_path": "src/BaseStar.h",
"max_line_length": 345,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c97632e0a5abddd066f8a01931bf9f70729b4e05",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiekeVanSon/COMPAS",
"max_stars_repo_path": "src/BaseStar.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8555,
"size": 49444
} |
#include <config.h>
#include <math.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_sort_vector.h>
static int compute_rank(gsl_vector *v);
#define BASE_LONG_DOUBLE
#include "templates_on.h"
#include "covariance_source.c"
#include "templates_off.h"
#undef BASE_LONG_DOUBLE
#define BASE_DOUBLE
#include "templates_on.h"
#include "covariance_source.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "covariance_source.c"
#include "templates_off.h"
#undef BASE_FLOAT
#define BASE_ULONG
#include "templates_on.h"
#include "covariance_source.c"
#include "templates_off.h"
#undef BASE_ULONG
#define BASE_LONG
#include "templates_on.h"
#include "covariance_source.c"
#include "templates_off.h"
#undef BASE_LONG
#define BASE_UINT
#include "templates_on.h"
#include "covariance_source.c"
#include "templates_off.h"
#undef BASE_UINT
#define BASE_INT
#include "templates_on.h"
#include "covariance_source.c"
#include "templates_off.h"
#undef BASE_INT
#define BASE_USHORT
#include "templates_on.h"
#include "covariance_source.c"
#include "templates_off.h"
#undef BASE_USHORT
#define BASE_SHORT
#include "templates_on.h"
#include "covariance_source.c"
#include "templates_off.h"
#undef BASE_SHORT
#define BASE_UCHAR
#include "templates_on.h"
#include "covariance_source.c"
#include "templates_off.h"
#undef BASE_UCHAR
#define BASE_CHAR
#include "templates_on.h"
#include "covariance_source.c"
#include "templates_off.h"
#undef BASE_CHAR
/*
compute_rank()
Compute rank of a sorted vector
Inputs: v - sorted data vector on input; rank vector on output
Notes: ranks are always computed in double precision
*/
static int
compute_rank(gsl_vector *v)
{
const size_t n = v->size;
size_t i = 0;
while (i < n - 1)
{
double vi = gsl_vector_get(v, i);
if (vi == gsl_vector_get(v, i + 1))
{
size_t j = i + 2;
size_t k;
double rank = 0.0;
/* we have detected a tie, find number of equal elements */
while (j < n && vi == gsl_vector_get(v, j))
++j;
/* compute rank */
for (k = i; k < j; ++k)
rank += k + 1.0;
/* divide by number of ties */
rank /= (double) (j - i);
for (k = i; k < j; ++k)
gsl_vector_set(v, k, rank);
i = j;
}
else
{
/* no tie - set rank to natural ordered position */
gsl_vector_set(v, i, i + 1.0);
++i;
}
}
if (i == n - 1)
gsl_vector_set(v, n - 1, (double) n);
return GSL_SUCCESS;
} /* compute_rank() */
| {
"alphanum_fraction": 0.6549137284,
"avg_line_length": 20.6666666667,
"ext": "c",
"hexsha": "78803c9eabf7ce3fe8937939648f78c5fe331023",
"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/statistics/covariance.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/statistics/covariance.c",
"max_line_length": 69,
"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/statistics/covariance.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": 686,
"size": 2666
} |
/*
* Copyright (c) 2010-2018 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
*
* @precisions normal z -> s d c
*
*/
#include <math.h>
#include <stdlib.h>
#include <core_blas.h>
#include <cblas.h>
#include "dplasma.h"
#include "dplasmatypes.h"
#include "dplasma/lib/dplasmaaux.h"
#include "parsec/private_mempool.h"
#include "dplasma/lib/zhetrf.h"
#include "dplasma/lib/ztrmdm.h"
/*
* dplasma_zhetrf_New()
*/
parsec_taskpool_t*
dplasma_zhetrf_New( parsec_tiled_matrix_dc_t *A, int *INFO)
{
int ldwork, lwork, ib;
parsec_taskpool_t *parsec_zhetrf = NULL;
parsec_memory_pool_t *pool_0, *pool_1;
ib = A->mb;
/* ldwork and lwork are necessary for the macros zhetrf_pool_0_SIZE and zhetrf_pool_1_SIZE */
ldwork = (A->nb+1)*ib;
lwork = (A->mb+1)*A->nb + ib*ib;
pool_0 = (parsec_memory_pool_t*)malloc(sizeof(parsec_memory_pool_t));
parsec_private_memory_init( pool_0, zhetrf_pool_0_SIZE );
pool_1 = (parsec_memory_pool_t*)malloc(sizeof(parsec_memory_pool_t));
parsec_private_memory_init( pool_1, zhetrf_pool_1_SIZE );
parsec_zhetrf = (parsec_taskpool_t *)parsec_zhetrf_new(PlasmaLower, A, (parsec_data_collection_t *)A, ib, pool_1, pool_0, INFO);
dplasma_add2arena_tile(((parsec_zhetrf_taskpool_t*)parsec_zhetrf)->arenas[PARSEC_zhetrf_DEFAULT_ARENA],
A->mb*A->nb*sizeof(parsec_complex64_t),
PARSEC_ARENA_ALIGNMENT_SSE,
parsec_datatype_double_complex_t, A->mb);
return parsec_zhetrf;
}
void
dplasma_zhetrf_Destruct( parsec_taskpool_t *tp )
{
parsec_zhetrf_taskpool_t *obut = (parsec_zhetrf_taskpool_t *)tp;
parsec_matrix_del2arena( obut->arenas[PARSEC_zhetrf_DEFAULT_ARENA] );
parsec_taskpool_free(tp);
}
/*
* dplasma_ztrmdm_New()
*/
parsec_taskpool_t*
dplasma_ztrmdm_New( parsec_tiled_matrix_dc_t *A)
{
parsec_taskpool_t *parsec_ztrmdm = NULL;
parsec_ztrmdm = (parsec_taskpool_t *)parsec_ztrmdm_new(A);
dplasma_add2arena_tile(((parsec_ztrmdm_taskpool_t*)parsec_ztrmdm)->arenas[PARSEC_ztrmdm_DEFAULT_ARENA],
A->mb*A->nb*sizeof(parsec_complex64_t),
PARSEC_ARENA_ALIGNMENT_SSE,
parsec_datatype_double_complex_t, A->mb);
return parsec_ztrmdm;
}
void
dplasma_ztrmdm_Destruct( parsec_taskpool_t *tp )
{
parsec_ztrmdm_taskpool_t *obut = (parsec_ztrmdm_taskpool_t *)tp;
parsec_matrix_del2arena( obut->arenas[PARSEC_ztrmdm_DEFAULT_ARENA] );
parsec_taskpool_free(tp);
}
/*
* Blocking Interface
*/
int dplasma_zhetrf(parsec_context_t *parsec, parsec_tiled_matrix_dc_t *A)
{
parsec_taskpool_t *parsec_zhetrf/*, *parsec_ztrmdm*/;
int info = 0, ginfo = 0;
parsec_zhetrf = dplasma_zhetrf_New(A, &info);
parsec_context_add_taskpool(parsec, (parsec_taskpool_t *)parsec_zhetrf);
dplasma_wait_until_completion(parsec);
dplasma_zhetrf_Destruct(parsec_zhetrf);
/*
parsec_ztrmdm = dplasma_ztrmdm_New(A);
parsec_context_add_taskpool(parsec, (parsec_taskpool_t *)parsec_ztrmdm);
dplasma_wait_until_completion(parsec);
dplasma_ztrmdm_Destruct(parsec_ztrmdm);
*/
/* This covers both cases when we have not compiled with MPI, or we don't need to do the reduce */
ginfo = info;
#if defined(PARSEC_HAVE_MPI)
/* If we don't need to reduce, don't do it, this way we don't require MPI to be initialized */
if( A->super.nodes > 1 )
MPI_Allreduce( &info, &ginfo, 1, MPI_INT, MPI_MAX, *(MPI_Comm*)dplasma_pcomm);
#endif
return ginfo;
}
| {
"alphanum_fraction": 0.7011431682,
"avg_line_length": 29.6290322581,
"ext": "c",
"hexsha": "fdb1d43e2a987b5eb161960a9057d3c283e16504",
"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/lib/zhetrf_wrapper.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/lib/zhetrf_wrapper.c",
"max_line_length": 132,
"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/lib/zhetrf_wrapper.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": 1139,
"size": 3674
} |
/* err/test_errnos.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 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 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 <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_test.h>
#define CHECK(x) errors[n].number = x ; errors[n].name = #x ; n++ ;
#define MAX_ERRS 64
int verbose = 0 ;
int
main (void)
{
int i, j, n = 0 ;
struct {
int number;
const char * name;
} errors[MAX_ERRS] ;
CHECK(GSL_SUCCESS);
CHECK(GSL_FAILURE);
CHECK(GSL_CONTINUE);
CHECK(GSL_EDOM);
CHECK(GSL_ERANGE);
CHECK(GSL_EFAULT);
CHECK(GSL_EINVAL);
CHECK(GSL_EFAILED);
CHECK(GSL_EFACTOR);
CHECK(GSL_ESANITY);
CHECK(GSL_ENOMEM);
CHECK(GSL_EBADFUNC);
CHECK(GSL_ERUNAWAY);
CHECK(GSL_EMAXITER);
CHECK(GSL_EZERODIV);
CHECK(GSL_EBADTOL);
CHECK(GSL_ETOL);
CHECK(GSL_EUNDRFLW);
CHECK(GSL_EOVRFLW);
CHECK(GSL_ELOSS);
CHECK(GSL_EROUND);
CHECK(GSL_EBADLEN);
CHECK(GSL_ENOTSQR);
CHECK(GSL_ESING);
CHECK(GSL_EDIVERGE);
CHECK(GSL_EUNSUP);
CHECK(GSL_EUNIMPL);
CHECK(GSL_ECACHE);
CHECK(GSL_ETABLE);
CHECK(GSL_ENOPROG);
CHECK(GSL_ENOPROGJ);
CHECK(GSL_ETOLF);
CHECK(GSL_ETOLX);
CHECK(GSL_ETOLG);
CHECK(GSL_EOF);
for (i = 0 ; i < n ; i++)
{
if (verbose) printf ("%s = %d\n", errors[i].name, errors[i].number) ;
}
for (i = 0; i < n; i++)
{
int status = 0;
for (j = 0; j < n; j++)
{
if (j != i)
status |= (errors[i].number == errors[j].number);
}
gsl_test (status, "%s is distinct from other error values",
errors[i].name);
}
for (i = 0; i < n; i++)
{
int status = 0;
int e1 = errors[i].number ;
for (j = 0; j < n; j++)
{
if (j != i)
{
int e2 = errors[j].number;
status |= (gsl_strerror(e1) == gsl_strerror(e2)) ;
}
}
gsl_test (status, "%s has a distinct error message",
errors[i].name);
}
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.6365705615,
"avg_line_length": 22.5299145299,
"ext": "c",
"hexsha": "9e2741d26daa70d287b2f504a89fb344b2986153",
"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/err/test.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/err/test.c",
"max_line_length": 75,
"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/err/test.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": 832,
"size": 2636
} |
/*
Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file 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 NNTYPES_H
#include <vector>
#include <set>
#include <string>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <netcdf>
#ifndef __NVCC__
#include <tuple>
#include <json/json.h>
#endif
#include <sys/time.h>
#include <cmath>
class NNDataSetBase;
class NNLayer;
class NNNetwork;
class NNWeight;
// Activates step by step CPU validation
#define VALIDATION
#ifdef VALIDATION
extern "C"
{
#include <cblas.h>
}
#endif
static const float NN_VERSION = 0.81f;
static const float MIN_ERROR = 1.0e-12f;
static const float MIN_ACTIVATION = 0.000001f;
static const float MAX_ACTIVATION = 0.999999f;
static const float MAX_VALUE = 999999999999999.0f;
template <typename T> struct GpuBuffer;
enum
{
DefaultBatch = 512
};
enum TrainingMode
{
SGD = 0,
Momentum = 1,
AdaGrad = 2,
Nesterov = 3,
RMSProp = 4,
AdaDelta = 5,
};
ostream& operator<< (ostream& out, const TrainingMode& e);
enum ErrorFunction
{
L1,
L2,
CrossEntropy,
ScaledMarginalCrossEntropy,
};
ostream& operator<< (ostream& out, const ErrorFunction& e);
enum Activation {
Sigmoid,
Tanh,
RectifiedLinear,
Linear,
ParametricRectifiedLinear,
SoftPlus,
SoftSign,
SoftMax,
ReluMax,
LinearMax,
};
ostream& operator<< (ostream& out, const Activation& a);
enum WeightInitialization
{
Xavier,
CaffeXavier,
Gaussian,
Uniform,
UnitBall,
Constant
};
ostream& operator<< (ostream& out, const WeightInitialization& w);
enum PoolingFunction {
None,
Max,
Average,
Stochastic,
LocalContrastNormalization,
LocalResponseNormalization,
GlobalTemporal,
};
ostream& operator<< (ostream& out, const PoolingFunction& p);
#include "kernels.h"
#include "GpuSort.h"
#include "NNEnum.h"
#include "NNWeight.h"
#include "NNLayer.h"
#include "NNNetwork.h"
int MPI_Bcast_string(string& s);
struct NNDataSetDimensions
{
uint32_t _dimensions;
uint32_t _width;
uint32_t _height;
uint32_t _length;
};
struct NNDataSetBase {
string _name; // Dataset name
NNDataSetEnums::DataType _dataType; // Dataset type (see above enum)
uint32_t _attributes; // Dataset characteristics (see NNDataSetEnum::Attributes in NNEnum.h)
uint32_t _examples; // Number of examples
uint32_t _dimensions; // Dimensionality of data set
uint32_t _width; // Dataset x dimension
uint32_t _height; // Dataset y dimension
uint32_t _length; // Dataset z dimension
uint32_t _stride; // Stride between examples
NNDataSetEnums::Sharding _sharding; // Sharding of dataset for parallel execution
uint32_t _minX; // Beginning of local X sharding for model parallel execution
uint32_t _maxX; // End of local X sharding for model parallel execution
uint64_t _sparseDataSize; // Total sparse datapoints
uint32_t _maxSparseDatapoints; // Maximum observed sparse datapoints per example
NNFloat _sparseDensity; // Overall sparse density (0.0 - 1.0)
vector<uint64_t> _vSparseStart; // Vector of sparse datapoint starts per example
GpuBuffer<uint64_t>* _pbSparseStart; // GPU copy of _vSparseStart
vector<uint64_t> _vSparseEnd; // Vector of sparse datapoint ends per example
GpuBuffer<uint64_t>* _pbSparseEnd; // GPU copy of _vSparseEnd
vector<uint32_t> _vSparseIndex; // Vector of sparse indices
GpuBuffer<uint32_t>* _pbSparseIndex; // GPU copy of _vSparseIndex
GpuBuffer<NNFloat>* _pbDenoisingRandom; // Denoising randoms
// Transposed sparse lookup for sparse backpropagation
vector<uint64_t> _vSparseDatapointCount;
vector<uint32_t> _vSparseTransposedStart;
uint32_t _sparseTransposedIndices;
GpuBuffer<uint32_t>* _pbSparseTransposedStart;
GpuBuffer<uint32_t>* _pbSparseTransposedEnd;
GpuBuffer<uint32_t>* _pbSparseTransposedIndex;
// States
bool _bDenoising;
bool _bDirty;
uint32_t _batch;
NNDataSetBase();
NNDataSetDimensions GetDimensions();
uint32_t GetExamples() { return _examples; };
virtual bool SaveNetCDF(const string& fname) = 0;
virtual bool WriteNetCDF(netCDF::NcFile& nfc, const string& fname, const uint32_t n) = 0;
virtual ~NNDataSetBase() = 0;
virtual void RefreshState(uint32_t batch) = 0;
virtual bool Shard(NNDataSetEnums::Sharding sharding) = 0;
virtual bool UnShard() = 0;
virtual vector<tuple<uint64_t, uint64_t> > getMemoryUsage() = 0;
virtual bool CalculateSparseDatapointCounts() = 0;
virtual bool GenerateSparseTransposedMatrix(uint32_t batch, NNLayer* pLayer) = 0;
virtual bool CalculateSparseTransposedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer) = 0;
virtual bool CalculateSparseTransposedDenoisedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer) = 0;
virtual bool CalculateSparseTransposedWeightGradient(NNFloat alpha, NNFloat beta, uint32_t m, uint32_t n, NNFloat* pDelta, NNFloat* pWeightGradient) = 0;
virtual bool SetDenoising(bool flag) = 0;
virtual bool GenerateDenoisingData() = 0;
virtual bool LoadInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual bool LoadSparseInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual bool LoadSparseDenoisedInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual bool CalculateSparseZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta = (NNFloat)0.0) = 0;
virtual bool CalculateSparseDenoisedZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta = (NNFloat)0.0) = 0;
virtual float CalculateL1Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateL2Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateMultinomialCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual float CalculateMultinomialScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit) = 0;
virtual bool CalculateL1OutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0;
virtual bool CalculateCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0;
virtual bool CalculateScaledMarginalCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0;
virtual bool CalculateOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta) = 0;
};
ostream& operator<< (ostream& out, NNDataSetEnums::Attributes& a);
ostream& operator<< (ostream& out, NNDataSetEnums::Kind& k);
ostream& operator<< (ostream& out, NNDataSetEnums::DataType& t);
ostream& operator<< (ostream& out, NNDataSetEnums::Sharding& s);
template<typename T> class NNDataSet : public NNDataSetBase {
public:
friend class NNetwork;
friend class NNLayer;
friend vector<NNDataSetBase*> LoadNetCDF(const string& fname);
friend bool SaveNetCDF(const string& fname, vector<NNDataSetBase*> vDataSet);
private:
vector<T> _vData;
GpuBuffer<T>* _pbData;
vector<T> _vSparseData;
GpuBuffer<T>* _pbSparseData;
GpuBuffer<T>* _pbSparseTransposedData;
// Force constructor private
NNDataSet(const string& fname, uint32_t n);
bool Rename(const string& name);
bool SaveNetCDF(const string& fname);
bool WriteNetCDF(netCDF::NcFile& nfc, const string& fname, const uint32_t n);
void RefreshState(uint32_t batch) {}
bool Shard(NNDataSetEnums::Sharding sharding);
bool UnShard();
vector<tuple<uint64_t, uint64_t> > getMemoryUsage();
bool CalculateSparseDatapointCounts();
bool GenerateSparseTransposedMatrix(uint32_t batch, NNLayer* pLayer);
bool CalculateSparseTransposedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer);
bool CalculateSparseTransposedDenoisedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer);
bool CalculateSparseTransposedWeightGradient(NNFloat alpha, NNFloat beta, uint32_t m, uint32_t n, NNFloat* pDelta, NNFloat* pWeightGradient);
bool SetDenoising(bool flag);
bool GenerateDenoisingData();
bool LoadInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
bool LoadSparseInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
bool LoadSparseDenoisedInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
bool CalculateSparseZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta);
bool CalculateSparseDenoisedZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta);
float CalculateL1Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateL2Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateMultinomialCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
float CalculateMultinomialScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit);
bool CalculateL1OutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta);
bool CalculateCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta);
bool CalculateScaledMarginalCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta);
bool CalculateOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta);
public:
~NNDataSet();
void Shuffle();
T GetDataPoint(uint32_t n, uint32_t x, uint32_t y = 0, uint32_t z = 0);
bool SetDataPoint(T v, uint32_t n, uint32_t x, uint32_t y = 0, uint32_t z = 0);
uint32_t GetSparseDataPoints(uint32_t n);
uint32_t GetSparseIndex(uint32_t n, uint32_t i);
bool SetSparseIndex(uint32_t n, uint32_t i, uint32_t v);
T GetSparseDataPoint(uint32_t n, uint32_t i);
bool SetSparseDataPoint(uint32_t n, uint32_t i, T v);
};
template<typename T> bool NNDataSet<T>::LoadInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
kLoadInputUnit(position, batch, stride, pUnit, _pbData->_pDevData);
return true;
}
template<typename T> bool NNDataSet<T>::LoadSparseInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
if (_attributes & NNDataSetEnums::Boolean)
kLoadSparseInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData);
else
kLoadSparseAnalogInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData);
return true;
}
template<typename T> bool NNDataSet<T>::LoadSparseDenoisedInputUnit(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
if (_attributes & NNDataSetEnums::Boolean)
kLoadSparseDenoisedInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbDenoisingRandom->_pDevData);
else
kLoadSparseAnalogDenoisedInputUnit(position, batch, stride, pUnit, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData);
return true;
}
template<typename T> bool NNDataSet<T>::CalculateSparseZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta)
{
if (_attributes & NNDataSetEnums::Boolean)
kCalculateSparseZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, pUnit, beta);
else
kCalculateSparseAnalogZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, pUnit, beta);
return true;
}
template<typename T> bool NNDataSet<T>::CalculateSparseDenoisedZ(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pWeight, NNFloat* pUnit, NNFloat beta)
{
if (_attributes & NNDataSetEnums::Boolean)
kCalculateSparseDenoisedZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbDenoisingRandom->_pDevData, pUnit, beta);
else
kCalculateSparseAnalogDenoisedZ(position, batch, stride, pWeight, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData, pUnit, beta);
return true;
}
template<typename T> bool NNDataSet<T>::CalculateSparseTransposedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer)
{
// Rebuild sparse data table if dataset changed
if (_bDirty || (batch != _batch))
{
GenerateSparseTransposedMatrix(batch, pLayer);
}
// Initialize transposed sparse offsets
_pbSparseTransposedEnd->Copy(_pbSparseTransposedStart->_pDevData);
// Call appropriate matrix generation kernel
if (_attributes & NNDataSetEnums::Boolean)
kCalculateSparseTransposedMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData);
else
kCalculateSparseTransposedAnalogMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, _pbSparseTransposedData->_pDevData);
return true;
}
template<typename T> bool NNDataSet<T>::CalculateSparseTransposedDenoisedMatrix(uint32_t position, uint32_t batch, NNLayer* pLayer)
{
// Rebuild sparse data table if dataset changed
if (_bDirty || (batch != _batch))
{
GenerateSparseTransposedMatrix(batch, pLayer);
}
// Initialize transposed sparse offsets
_pbSparseTransposedEnd->Copy(_pbSparseTransposedStart->_pDevData);
// Call appropriate matrix generation kernel
if (_attributes & NNDataSetEnums::Boolean)
kCalculateSparseTransposedDenoisedMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbDenoisingRandom->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData);
else
kCalculateSparseTransposedAnalogDenoisedMatrix(position, batch, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, _pbDenoisingRandom->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, _pbSparseTransposedData->_pDevData);
#if 0
vector<uint32_t> vSparseTransposedStart(53120);
vector<uint32_t> vSparseTransposedEnd(53120);
_pbSparseTransposedStart->Download(&vSparseTransposedStart[0]);
_pbSparseTransposedEnd->Download(&vSparseTransposedEnd[0]);
for (uint32_t i = 0; i < 53120; i++)
printf("%6u %9u %9u %9u %9u\n", i, vSparseTransposedStart[i], vSparseTransposedEnd[i], vSparseTransposedEnd[i] - vSparseTransposedStart[i], (uint32_t)_vSparseDatapointCount[i]);
exit(-1);
#endif
return true;
}
template<typename T> bool NNDataSet<T>::CalculateSparseTransposedWeightGradient(NNFloat alpha, NNFloat beta, uint32_t m, uint32_t n, NNFloat* pDelta, NNFloat* pWeightGradient)
{
if (_attributes & NNDataSetEnums::Boolean)
kCalculateSparseTransposedWeightGradient(alpha, beta, m, n, _pbSparseTransposedStart->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, pDelta, pWeightGradient);
else
kCalculateSparseTransposedAnalogWeightGradient(alpha, beta, m, n, _pbSparseTransposedStart->_pDevData, _pbSparseTransposedEnd->_pDevData, _pbSparseTransposedIndex->_pDevData, _pbSparseTransposedData->_pDevData, pDelta, pWeightGradient);
return true;
}
template<typename T> float NNDataSet<T>::CalculateL1Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Boolean)
return kCalculateSparseL1Error(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
bSparseIgnoreZero);
else
return kCalculateSparseAnalogL1Error(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
_pbSparseData->_pDevData,
bSparseIgnoreZero);
}
else
return kCalculateL1Error(position, batch, stride, pUnit, _pbData->_pDevData);
}
template<typename T> float NNDataSet<T>::CalculateL2Error(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Boolean)
return kCalculateSparseL2Error(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
bSparseIgnoreZero);
else
return kCalculateSparseAnalogL2Error(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
_pbSparseData->_pDevData,
bSparseIgnoreZero);
}
else
return kCalculateL2Error(position, batch, stride, pUnit, _pbData->_pDevData);
}
template<typename T> float NNDataSet<T>::CalculateCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
return kCalculateSparseCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
bSparseIgnoreZero);
}
else
return kCalculateCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData);
}
template<typename T> float NNDataSet<T>::CalculateScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
return kCalculateSparseScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
bSparseIgnoreZero);
}
else
return kCalculateScaledMarginalCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData);
}
template<typename T> float NNDataSet<T>::CalculateMultinomialCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
if (_attributes & NNDataSetEnums::Sparse)
{
if (_attributes & NNDataSetEnums::Boolean)
{
return kCalculateSparseMultinomialCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData);
}
else
return kCalculateSparseAnalogMultinomialCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
_pbSparseData->_pDevData);
}
else
return kCalculateMultinomialCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData);
}
template<typename T> float NNDataSet<T>::CalculateMultinomialScaledMarginalCrossEntropyError(uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit)
{
if (_attributes & NNDataSetEnums::Sparse)
{
if (_attributes & NNDataSetEnums::Boolean)
return kCalculateSparseMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData);
else
return kCalculateSparseAnalogMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit,
_pbSparseStart->_pDevData,
_pbSparseEnd->_pDevData,
_pbSparseIndex->_pDevData,
_pbSparseData->_pDevData);
}
else
return kCalculateMultinomialScaledMarginalCrossEntropyError(position, batch, stride, pUnit, _pbData->_pDevData);
}
template<typename T> bool NNDataSet<T>::CalculateL1OutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)
{
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
kCalculateSparseL1OutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, bSparseIgnoreZero);
}
else
kCalculateL1OutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData);
return true;
}
template<typename T> bool NNDataSet<T>::CalculateCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)
{
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
kCalculateSparseCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, bSparseIgnoreZero);
}
else
kCalculateCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData);
return true;
}
template<typename T> bool NNDataSet<T>::CalculateScaledMarginalCrossEntropyOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)
{
if (_attributes & NNDataSetEnums::Sparse)
{
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
kCalculateSparseScaledMarginalCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, bSparseIgnoreZero);
}
else
{
kCalculateScaledMarginalCrossEntropyOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData);
}
return true;
}
template<typename T> bool NNDataSet<T>::CalculateOutputDelta(Activation activation, uint32_t position, uint32_t batch, uint32_t stride, NNFloat* pUnit, NNFloat* pDelta)
{
if (_attributes & NNDataSetEnums::Sparse) {
bool bSparseIgnoreZero = _attributes & NNDataSetEnums::SparseIgnoreZero;
if (_attributes & NNDataSetEnums::Boolean)
{
kCalculateSparseOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, bSparseIgnoreZero);
}
else
{
kCalculateSparseAnalogOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbSparseStart->_pDevData, _pbSparseEnd->_pDevData, _pbSparseIndex->_pDevData, _pbSparseData->_pDevData, bSparseIgnoreZero);
}
}
else
{
kCalculateOutputDelta(activation, position, batch, stride, pUnit, pDelta, _pbData->_pDevData);
}
return true;
}
vector<NNDataSetBase*> LoadNetCDF(const string& fname);
bool SaveNetCDF(const string& fname, vector<NNDataSetBase*> vDataset);
vector<NNDataSetBase*> LoadImageData(const string& fname);
vector<NNDataSetBase*> LoadCSVData(const string& fname);
vector<NNDataSetBase*> LoadJSONData(const string& fname);
vector<NNDataSetBase*> LoadAudioData(const string& name);
#define NNTYPES_H
#endif
| {
"alphanum_fraction": 0.7123252201,
"avg_line_length": 47.3450087566,
"ext": "h",
"hexsha": "15e76a8dc2f3ec3293121384755a2dfee029bc99",
"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": "7d57d23f4971e2c95fd9933d1c71a1c67ab2d63a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "just4jc/amazon-dsstne",
"max_forks_repo_path": "src/amazon/dsstne/engine/NNTypes.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7d57d23f4971e2c95fd9933d1c71a1c67ab2d63a",
"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": "just4jc/amazon-dsstne",
"max_issues_repo_path": "src/amazon/dsstne/engine/NNTypes.h",
"max_line_length": 318,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7d57d23f4971e2c95fd9933d1c71a1c67ab2d63a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "just4jc/amazon-dsstne",
"max_stars_repo_path": "src/amazon/dsstne/engine/NNTypes.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7016,
"size": 27034
} |
/* block/gsl_block_char.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 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 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.
*/
#ifndef __GSL_BLOCK_CHAR_H__
#define __GSL_BLOCK_CHAR_H__
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
struct gsl_block_char_struct
{
size_t size;
char *data;
};
typedef struct gsl_block_char_struct gsl_block_char;
GSL_EXPORT gsl_block_char *gsl_block_char_alloc (const size_t n);
GSL_EXPORT gsl_block_char *gsl_block_char_calloc (const size_t n);
GSL_EXPORT void gsl_block_char_free (gsl_block_char * b);
GSL_EXPORT int gsl_block_char_fread (FILE * stream, gsl_block_char * b);
GSL_EXPORT int gsl_block_char_fwrite (FILE * stream, const gsl_block_char * b);
GSL_EXPORT int gsl_block_char_fscanf (FILE * stream, gsl_block_char * b);
GSL_EXPORT int gsl_block_char_fprintf (FILE * stream, const gsl_block_char * b, const char *format);
GSL_EXPORT int gsl_block_char_raw_fread (FILE * stream, char * b, const size_t n, const size_t stride);
GSL_EXPORT int gsl_block_char_raw_fwrite (FILE * stream, const char * b, const size_t n, const size_t stride);
GSL_EXPORT int gsl_block_char_raw_fscanf (FILE * stream, char * b, const size_t n, const size_t stride);
GSL_EXPORT int gsl_block_char_raw_fprintf (FILE * stream, const char * b, const size_t n, const size_t stride, const char *format);
GSL_EXPORT size_t gsl_block_char_size (const gsl_block_char * b);
GSL_EXPORT char * gsl_block_char_data (const gsl_block_char * b);
__END_DECLS
#endif /* __GSL_BLOCK_CHAR_H__ */
| {
"alphanum_fraction": 0.772208639,
"avg_line_length": 36.6268656716,
"ext": "h",
"hexsha": "d197bea88cd6efe81c95ca6f61dd13565a6da2cf",
"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": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_block_char.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"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": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_block_char.h",
"max_line_length": 131,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_block_char.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 641,
"size": 2454
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <float.h>
#include "optimization.h"
/*****************************************************************************/
/* vector routines */
double vec_dot_prod(const double *v1, const double *v2, const int N)
{
int i;
double nn = 0;
for (i=0;i<N;i++)
{
nn += v1[i] * v2[i];
}
return nn;
}
double vec_norm(const double *v1, const int N)
{
return sqrt(vec_dot_prod(v1, v1, N));
}
/*****************************************************************************/
/* Wolfe conditions */
int check_armijo(double new_misfit, double old_misfit,
double dir_deriv, double step_len)
{
/* returns 1 if Armijo condition satisfied, 0 otherwise */
if (new_misfit <= old_misfit + WOLFE_C1 * step_len * dir_deriv)
{
/* step length okay */
return 1;
}
return 0;
}
int check_curvature(double dir_deriv_old, double dir_deriv_new)
{
/* returns 1 if curvature satisfied, 0 otherwise */
if (dir_deriv_new >= WOLFE_C2 * dir_deriv_old)
{
return 1;
}
return 0;
}
int check_strong_curvature(double dir_deriv_old, double dir_deriv_new)
{
/* returns 1 if strong curvature satisfied, 0 otherwise */
if (dir_deriv_new >= WOLFE_C2 * dir_deriv_old &&
dir_deriv_new <= -WOLFE_C2 * dir_deriv_old)
{
return 1;
}
return 0;
}
/*****************************************************************************/
double initial_step_length(search_dir sd, double alpha_old, double dir_deriv_old, double dir_deriv_new)
{
/* calculate initial step length for a line search step */
/* inputs: */
/* sd: search direction, CG, STEEPEST, or LBFGS */
/* alpha_old: previous (accepted) step length */
/* dir_deriv_old: directional derivative at previous step */
/* (dot product of previous gradient and search direction) */
/* dir_deriv_new: directional derivative at current step */
/* (dot product of current gradient and search direction) */
if (sd == CG || sd == STEEPEST)
{
/* see Nocedal & Wright 2006, p. 59 */
return alpha_old * (dir_deriv_old / dir_deriv_new);
}
/* quasi-Newton methods are well scaled use steplength of 1.0 for L-BFGS */
return 1.0;
}
/*****************************************************************************/
/* steepest descent direction */
void steepest_descent_direction(const double *grad, double *p, const int N)
{
int i;
for (i=0;i<N;i++)
{
p[i] = -grad[i];
}
}
/*****************************************************************************/
/* conjugate gradient direction */
void conjugate_grad_direction(double *grad_old, double *grad_new, double *p_old, double *p_new, int N)
{
/*
Determine a search direction by the conjugate gradient method
Uses PR-FR conjugate gradient method to calculate a conjugate direection,
see Nocedal & Wright 2006, p. 123.
All vectors should be double precision of length N.
grad_old: previous gradient
grad_new: current gradient
p_old: previous search direction
p_new: new search direction (output, must be allocated already)
*/
/* calculate beta values for both PR and FR methods */
double beta_lower = 0;
double beta_upper_FR = 0;
double beta_upper_PR = 0;
int i;
for (i=0;i<N;i++)
{
beta_lower += grad_old[i] * grad_old[i];
beta_upper_FR += grad_new[i] * grad_new[i];
beta_upper_PR += grad_new[i] * (grad_new[i] - grad_old[i]);
}
double beta_FR = beta_upper_FR / beta_lower;
double beta_PR = beta_upper_PR / beta_lower;
/* select beta based on criteria given in Nocedal and Wright 2006 */
double beta = 0;
if (beta_PR < -beta_FR)
{
beta = -beta_FR;
}
else if (fabs(beta_PR) <= beta_FR)
{
beta = beta_PR;
}
else if (beta_PR > beta_FR)
{
beta = beta_FR;
}
/* calculate new search direction */
for (i=0;i<N;i++)
{
p_new[i] = -grad_new[i] + beta * p_old[i];
}
}
/*****************************************************************************/
/* L-BFGS direction */
void LBFGS_direction(double *grad_new, double *grad_old, double *model_new, double *model_old, double *p_new, int N, int m, int k)
{
/* call with the last parameter negative to clean up local variables */
int ii, jj;
static double *s = NULL;
static double *y = NULL;
static double *q = NULL;
static double *aa = NULL;
static double *rho = NULL;
static int *ind = NULL;
double *r = p_new;
/* allocate memory */
/* note: opt_allocate is the same as malloc, but checks to make sure */
/* memory allocate was successful */
if (!s)
{
s = opt_allocate(sizeof(*s) * N * m);
}
if (!y)
{
y = opt_allocate(sizeof(*y) * N * m);
}
if (!q)
{
q = opt_allocate(sizeof(*q) * N);
}
if (!aa)
{
aa = opt_allocate(sizeof(*aa) * m);
}
if (!rho)
{
rho = opt_allocate(sizeof(*rho) * m);
}
if (!ind)
{
ind = opt_allocate(sizeof(*ind) * m);
for (ii=0;ii<m;ii++)
{
ind[ii] = ii * N;
}
}
/* j is the min of k and m */
int j = (k < m) ? k : m;
/* position to write new y and s vectors */
int pos = ((k-1) % m) * N;
/* write new y and s vectors */
for (ii=0;ii<N;ii++)
{
y[ii+pos] = grad_new[ii] - grad_old[ii];
s[ii+pos] = model_new[ii] - model_old[ii];
}
/* calculate rho */
rho[pos / N] = 1.0 / vec_dot_prod(y+pos, s+pos, N);
/* calculate gamma */
double gamma = vec_dot_prod(s+pos, y+pos, N) / vec_dot_prod(y+pos, y+pos, N);
if (k<m)
{
/* shift ind vector so ind[0] is still the index
of the oldest element */
int first_ele = ind[0];
for (ii=0;ii<m-1;ii++)
{
ind[ii] = ind[ii+1];
}
ind[m-1] = first_ele;
}
/* assign initial q value */
for (jj=0;jj<N;jj++)
{
q[jj] = grad_new[jj];
}
/*begin backwards loop */
for (ii=j-1;ii>=0;ii--)
{
aa[ii] = rho[ind[ii] / N] * vec_dot_prod(s+ind[ii], q, N);
for (jj=0;jj<N;jj++)
{
q[jj] = q[jj] - aa[ii] * (y+ind[ii])[jj];
}
}
/* assign r */
for (jj=0;jj<N;jj++)
{
r[jj] = gamma * q[jj];
}
/* begin forwards loop */
double beta;
for (ii=0;ii<j;ii++)
{
beta = rho[ind[ii] / N] * vec_dot_prod(y+ind[ii], r, N);
for (jj=0;jj<N;jj++)
{
r[jj] = r[jj] + (s+ind[ii])[jj] * (aa[ii] - beta);
}
}
/* negate r */
for (jj=0;jj<N;jj++)
{
r[jj] = -r[jj];
}
}
/*****************************************************************************/
#include <lapacke.h>
void newton_direction(const double *gradient, const double *hessian, const int N, double *p_new)
{
/********************************************************/
/* not implemented yet - use steepest descent for now */
//fprintf(stderr,"Newton direction not implemented yet\n");
//fprintf(stderr,"Reverting to steepest descent\n");
//steepest_descent_direction(gradient, p_new, N);
/********************************************************/
/* make a temp copy of the gradient*/
double *temp_g = opt_allocate(sizeof(*temp_g) * N);
double *temp_h = opt_allocate(sizeof(*temp_h) * N * N);
memcpy(temp_g, gradient, sizeof(*temp_h) * N );
/* need to check if Hessian is PD and modify if not */
/* Note that this repeated performs a Cholesky factorization on */
/* the Hessian and will be expensive if N is large */
/* In those cases, a modified Cholesky factorization (see Nocedal */
/* and Wright 2006, pp. 52-54) may be a better approach */
double beta = sqrt(DBL_EPSILON);
int pd = hessian_modification(hessian, temp_h, N, beta);
/* if we found a pd Hessian approximation, solve system for p */
/* otherwise, return steepest descent direction */
if (pd != 1)
{
fprintf(stderr,"Could not find a positive definite "
"Hessian approximation\n");
fprintf(stderr,"Returning steepest descent direction\n");
}
else
{
/* solve system for p: Hp = -g */
int nrhs = 1;
int lda = N;
int ldb = N;
LAPACKE_dpotrs(LAPACK_COL_MAJOR, 'L', N, nrhs, temp_h, lda, temp_g, ldb);
}
/* negate gradient or solution to system */
int i;
for (i = 0;i<N;i++)
p_new[i] = -temp_g[i];
free(temp_h);
free(temp_g);
}
#define HESSMOD_MAX_IT 100
int hessian_modification(const double *hessian, double *upper_factor, int N, double beta)
{
/* beta may need to be adjusted based on the scaling of the problem */
/* find minimum diagonal element of the hessian */
int i;
double min_diag = hessian[0];
for (i=0;i<N;i++)
{
double diag = hessian[i*(N+1)];
min_diag = (diag < min_diag) ? diag : min_diag;
}
/* find initial tau */
double tau;
if (min_diag > 0)
{
/* if it is already pd, min_diag will be positive */
tau = 0.0;
}
else
{
tau = - min_diag + beta;
}
/* add multiples of the identity until hessian is positive definite */
int k;
int pd;
int lda = N;
for (k=0;k<HESSMOD_MAX_IT;k++)
{
/* copy hessian and add identity multiple */
/* upper_factor will change every loop because of the dpotrf call */
memcpy(upper_factor, hessian, sizeof(*hessian) * N *N);
for (i=0;i<N;i++)
{
upper_factor[i * (N+1)] = hessian[i * (N+1)] + tau;
}
/* try cholesky factorization */
pd = LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', N, upper_factor, lda);
if (pd == 0)
{
/* positive definite */
return 1;
}
/* increment tau */
tau = 2.0 * tau > beta ? 2.0 * tau : beta;
}
/* return 0 if not positive definite */
return 0;
}
/*****************************************************************************/
/* function for performing line search */
void line_search(double *x_in,
double *x_out,
const int N,
optimization_parameters *opt_par,
void *aux
)
{
double (*misfit)(const double *, const int, void *) = opt_par->objective;
void (*grad)(const double *, double *, int, void *) = opt_par->grad;
void (*hess)(const double *, double *, int, void *) = opt_par->hess;
int success = 0;
int i,j;
/* note: opt_allocate is the same as malloc, but checks to make sure */
/* memory allocate was successful */
double *gradient = opt_allocate(sizeof(*gradient) * N);
double *grad_old = opt_allocate(sizeof(*grad_old) * N);
double *p = opt_allocate(sizeof(*p) * N);
double *p_old = opt_allocate(sizeof(*p_old) * N);
double *x_old = opt_allocate(sizeof(*x_old) * N);
double *x_trial = opt_allocate(sizeof(*x_trial) * N);
double *hessian = NULL;
if (opt_par->sd == NEWTON)
hessian = opt_allocate(sizeof(*hessian) * N * N);
/* initial alpha_old and dir_deriv_old to keep the compiler from complaining, */
/* but these initialization values will never be used */
double alpha_old = 1;
double alpha_new;
double dir_deriv_old = 1;
double dir_deriv_new;
/* copy x_in to x_old */
for (i=0;i<N;i++)
{
x_out[i] = x_in[i];
}
/* evaluate function and gradient at initial point */
double f_old = misfit(x_out, N, aux);
grad(x_out, gradient, N, aux);
/* check grad norm for exit condition */
if (vec_norm(gradient, N) < opt_par->stopping_tolerance)
{
success = 1;
free(p);
free(gradient);
return;
}
int m = opt_par->LBFGS_mem;
/* start main loop */
search_dir sd;
int max_it = opt_par->max_iterations;
for (j=0;j<max_it;j++)
{
printf("Starting line search, iteration %d\n",j);
if (j == 0 && opt_par->sd != NEWTON)
{
/* first iteration - use steepest descent */
/* get steepest descent direction */
steepest_descent_direction(gradient, p, N);
sd = STEEPEST;
dir_deriv_new = vec_dot_prod(gradient, p, N);
alpha_new = opt_par->initial_step_length;
}
else
{
if (opt_par->sd == LBFGS)
{
LBFGS_direction(gradient, grad_old, x_out, x_old, p, N, m, j);
sd = LBFGS;
dir_deriv_new = vec_dot_prod(gradient, p, N);
}
else if (opt_par->sd == CG)
{
conjugate_grad_direction(grad_old, gradient, p_old, p, N);
sd = CG;
dir_deriv_new = vec_dot_prod(gradient, p, N);
}
else if (opt_par->sd == NEWTON)
{
/* compute hessian */
hess(x_out, hessian, N, aux);
newton_direction(gradient, hessian, N, p);
sd = NEWTON;
dir_deriv_new = vec_dot_prod(gradient, p, N);
}
if (opt_par->sd == STEEPEST || (opt_par->angle_restart_allowed && check_angle_restart(gradient, p, N)))
{
steepest_descent_direction(gradient, p, N);
sd = STEEPEST;
dir_deriv_new = vec_dot_prod(gradient, p, N);
}
alpha_new = initial_step_length(sd, alpha_old, dir_deriv_old, dir_deriv_new);
}
if (opt_par->bracket_only || j==0)
{
alpha_new = ls_bracket(x_out, p, N, opt_par, alpha_new, aux);
}
else
{
alpha_new = back_track(x_out, p, N, opt_par, alpha_new, aux);
}
for (i=0;i<N;i++)
{
p_old[i] = p[i];
grad_old[i] = gradient[i];
x_old[i] = x_out[i];
}
if (!opt_par->backtrack_only && !opt_par->bracket_only && j!=0)
{
/* update model */
for (i=0;i<N;i++)
{
x_trial[i] = x_out[i] + alpha_new * p[i];
}
/* evaluate gradient at new point */
grad(x_trial, gradient, N, aux);
/* check (strong) curvature */
double ppi = vec_dot_prod(gradient, p, N);
if (!check_strong_curvature(dir_deriv_new, ppi))
{
//alpha_new = initial_step_length(sd, alpha_old, dir_deriv_old, dir_deriv_new);
alpha_new = ls_bracket(x_out, p, N, opt_par, alpha_new, aux);
}
}
alpha_old = alpha_new;
dir_deriv_old = dir_deriv_new;
/* calculate new x value */
for (i=0; i<N; i++)
{
x_out[i] = x_out[i] + alpha_new * p[i];
}
/* evaluate gradient at new point */
grad(x_out, gradient, N, aux);
/* check grad norm for exit condition */
if (vec_norm(gradient, N) < opt_par->stopping_tolerance)
{
success = 1;
break;
}
}
printf("No. iterations: %d\n",j);
free(p);
free(p_old);
free(gradient);
free(grad_old);
free(x_trial);
free(x_old);
if (hessian)
free(hessian);
if (!success)
{
fprintf(stderr,"Error: line search failed to find a solution\n");
fprintf(stderr,"Point returned is not stationary\n");
}
}
/*****************************************************************************/
double ls_zoom(const double *x,
const double *p,
const int N,
optimization_parameters *opt_par,
double a_lo,
double a_hi,
void *aux
)
{
double (*misfit)(const double *, const int, void *) = opt_par->objective;
void (*grad)(const double *, double *, int, void *) = opt_par->grad;
int success = 0;
double bb_star = 0.0;
double mf;
double *gradient = opt_allocate(sizeof(*gradient) * N);
double *x_update = opt_allocate(sizeof(*x_update) * N);
/* calculate initial misfit and gradient */
mf = misfit(x, N, aux);
grad(x, gradient, N, aux);
double phi0 = mf;
double phi_prime0 = vec_dot_prod(gradient, p, N);
double phi_aj;
double phi_prime_aj;
double phi_a_lo;
double mean_step;
double tol = 0;
/* start iterations */
double a_j;
int i, j;
for (i=0;i<opt_par->bracket_zoom_iterations;i++)
{
printf("Bracket successful, starting zoom, iteration %d\n",i);
printf("a_lo, a_hi: %f, %f\n", a_lo, a_hi);
fflush(stdout);
/* check if a_lo and a_hi are too close together */
mean_step = 0.5 * (a_lo + a_hi);
if (fabs(a_lo - a_hi) / mean_step < 0.01)
{
bb_star = mean_step;
success = 1;
break;
}
if (mean_step < 1e-6) /* <-- this should really depend on the scaling of the problem */
{
success = 0;
break;
}
a_j = ls_cubic_interpolation(x, p, N, opt_par, a_lo, a_hi, aux);
//a_j = (a_lo + a_hi) / 2.0;
tol = mean_step * 0.01; /* one percent of the mean step */
//fprintf(stderr, "Trial step: %f\n",a_j);
if (fabs(a_j - a_lo) < tol || fabs(a_j - a_hi) < tol)
{
/* too close to boundary of interval */
//fprintf(stderr,"ls_zoom: too close to boundary\n");
//success = 0;
//break;
a_j = mean_step;
}
if (isnan(a_j) || isinf(a_j))
{
fprintf(stderr,"nan/inf value\n");
success = 0;
break;
}
/* evaluate function at a_lo (don't need dir. derivative) */
for (j=0;j<N;j++)
{
x_update[j] = x[j] + a_lo * p[j];
}
phi_a_lo = misfit(x_update, N, aux);
/* evaluate function at a_j. directional derivative will be */
/* calculated later if needed */
for (j=0;j<N;j++)
{
x_update[j] = x[j] + a_j * p[j];
}
phi_aj = misfit(x_update, N, aux);
printf("Trial step length %E misfit: %E\n", a_j, phi_aj);
if (phi_aj > phi0 + WOLFE_C1 * a_j * phi_prime0
|| phi_aj >= phi_a_lo)
{
/* trial step length violates Armijo or */
/* trial step evaluate to a function value greater than a_lo */
/* need to reduce step length */
a_hi = a_j;
}
else
{
/* trial step length satisfies Armijo and function value is */
/* less than a_lo */
/* check curvature */
grad(x_update, gradient, N, aux);
phi_prime_aj = vec_dot_prod(gradient, p, N);
printf("Trial step length %E dir deriv: %E\n", a_j, phi_prime_aj);
if (fabs(phi_prime_aj) <= -WOLFE_C2 * phi_prime0)
{
/* trial step length satisfies strong curvature condition */
/* accept trial step length */
bb_star = a_j;
success = 1;
break;
}
if (phi_prime_aj * (a_hi - a_lo) >= 0)
{
a_hi = a_lo;
}
/* satisfies Armijo, but not curvature */
/* increase step length */
a_lo = a_j;
}
}
free(x_update);
free(gradient);
if (!success)
{
fprintf(stderr,"Line search zoom failed to return an "
"appropriate step length\n");
//exit(-90);
return -1;
}
return bb_star;
}
/*****************************************************************************/
double ls_cubic_interpolation(const double *x,
const double *p,
const int N,
optimization_parameters *opt_par,
const double bound1,
const double bound2,
void *aux
)
{
/* calculates a new trial step length from cubic interpolation */
/* interpolation is based on two function values and the */
/* corresponding directional derivatives */
/* */
/* This interpolation requires two function evaluations and */
/* two gradient evaluations. If the function or gradient is */
/* expensive to evaluate, there are probably better ways to */
/* calculate an appropriate step length */
/* */
/* see Nocedal and Wright 2006, equation 3.59 */
/* */
/* inputs: */
/* x: current point in parameter space */
/* p: search direction */
/* N: number of dimensions */
/* misfit: function that takes point and returns objective */
/* function value. x and N as defined above */
/* grad: function that takes point and returns gradient */
/* value (returned as parameter) */
/* bound1, bound2: bounds of step length search */
/* */
/* new trial step length is returned */
double (*misfit)(const double *, const int, void *) = opt_par->objective;
void (*grad)(const double *, double *, int, void *) = opt_par->grad;
double *gradient = opt_allocate(sizeof(*gradient) * N);
double *x_update = opt_allocate(sizeof(*x_update) * N);
double f1, f2, g1, g2;
int i;
/* evaluate objective function and directional derivative at bound1 */
for (i=0;i<N;i++)
{
x_update[i] = x[i] + bound1 * p[i];
}
f1 = misfit(x_update, N, aux);
grad(x_update, gradient, N, aux);
g1 = vec_dot_prod(gradient, p, N);
printf("misfit at %E: %E\n", bound1, f1);
printf("dir deriv at %E: %E\n", bound1, g1);
/* evaluate objective function and directional derivative at bound2 */
for (i=0;i<N;i++)
{
x_update[i] = x[i] + bound2 * p[i];
}
f2 = misfit(x_update, N, aux);
grad(x_update, gradient, N, aux);
g2 = vec_dot_prod(gradient, p, N);
printf("misfit at %E: %E\n", bound2, f2);
printf("dir deriv at %E: %E\n", bound2, g2);
/*calculate cubic approximateion */
double d1 = g1 + g2 - 3 * ((f1 - f2)/(bound1 - bound2));
/* note that both bound1 and bound2 should always be positive */
/* they should never be equal */
/* d2_sign is sign(bound2 - bound1) */
double d2_sign = bound2 > bound1 ? 1.0 : -1.0;
if ((bound2 - bound1) > 0)
d2_sign = 1.0;
else if ((bound2 - bound1) < 0)
d2_sign = -1.0;
else
d2_sign = 0.0;
double d2 = d2_sign * sqrt(d1 * d1 - g1 * g2);
double a_new = bound2 - (bound2 - bound1) * ((g2 + d2 - d1)/(g2 - g1 + 2 * d2));
/* the minimum is always either at a_new as calculated above orj */
/* at one of the end points. Check those here. */
//a_new = (a_new < bound1) ? a_new : bound1;
//a_new = (a_new < bound2) ? a_new : bound2;
free(x_update);
free(gradient);
return a_new;
}
/*****************************************************************************/
double ls_bracket(const double *x,
const double *p,
const int N,
optimization_parameters *opt_par,
double alpha0,
void *aux
)
{
double (*misfit)(const double *, const int, void *) = opt_par->objective;
void (*grad)(const double *, double *, int, void *) = opt_par->grad;
int success = 0;
double b_star;
int steplength_max = 50;
double beta_max = 5e30;
double beta0 = 0;
double beta1 = alpha0; /* initial step length */
double *gradient = opt_allocate(sizeof(*gradient) * N);
double *x_update = opt_allocate(sizeof(*x_update) * N);
double p0; /* phi(0) */
double pp0; /* phi'(0) */
/* evaluate objective and dir. derivative at initial point */
p0 = misfit(x, N, aux);
grad(x, gradient, N, aux);
pp0 = vec_dot_prod(gradient, p, N);
double pi; /* phi(i) */
double ppi; /* phi'(i) */
double pi_1 = p0; /* phi(i-1) */
//double ppi_1 = pp0; /* phi'(i-1) */
double b_i = beta1; /* beta_i */
double b_i_1 = beta0; /* beta_{i-1} */
int i, j;
for (i=0;i<steplength_max;i++)
{
printf("Starting bracketing, iteration %d\n",i);
printf("Bracket bounds: %E, %E\n",b_i_1, b_i);
fflush(stdout);
/* calculate objective and derivative values at b_i */
for (j=0;j<N;j++)
{
x_update[j] = x[j] + b_i * p[j];
}
pi = misfit(x_update, N, aux);
if ((pi > p0 + WOLFE_C1 * b_i * pp0) || (pi >= pi_1 && i>0))
{
b_star = ls_zoom(x, p, N, opt_par, b_i_1, b_i, aux);
if (b_star < 0)
{
/* ls_zoom failed - try bigger steps */
b_i = 2 * alpha0;
b_i_1 = alpha0;
continue;
}
success = 1;
break;
}
grad(x_update, gradient, N, aux);
ppi = vec_dot_prod(gradient, p, N);
if (fabs(ppi) <= -WOLFE_C2 * pp0)
{
b_star = b_i;
success = 1;
break;
}
if (ppi >= 0.0)
{
b_star = ls_zoom(x, p, N, opt_par, b_i, b_i_1, aux);
if (b_star < 0)
{
/* ls_zoom failed - try bigger steps */
b_i = 2 * alpha0;
b_i_1 = alpha0;
continue;
}
success = 1;
break;
}
/* update b_i and b_i_1 */
b_i_1 = b_i;
b_i = 2 * b_i;
if (b_i > beta_max)
{
fprintf(stderr,"Error: ls_bracket: max step length reached\n");
success = 0;
break;
}
}
free(x_update);
free(gradient);
if (!success)
{
fprintf(stderr,"Line search bracket failed to return an "
"appropriate step length\n");
exit(-90);
}
printf("Step length successfully selected. Step length: %E\n",b_star);
fflush(stdout);
return b_star;
}
/*****************************************************************************/
int check_angle_restart(double *grad, double *p, int N)
{
int restart = 0;
double angle_tol_deg = 95.0;
double angle_tol_rad = angle_tol_deg * (M_PI / 180.0);
double grad_norm = vec_norm(grad, N);
double p_norm = vec_norm(p, N);
double pg = vec_dot_prod(p, grad, N);
double ang = pg / (p_norm * grad_norm);
if(ang > cos(angle_tol_rad))
{
restart = 1;
}
return restart;
}
/*****************************************************************************/
double back_track_quad(double phi0, double phip0, double phi_a0, double a0)
{
/* see Nodedal and Wright, p. 58 (equation 3.57 and 3.58) */
double a1;
double num = phip0 * a0 * a0;
double den = phi_a0 - phi0 - phip0 * a0;
a1 = -0.5 * (num / den);
return a1;
}
double back_track_cubic(double phi0,
double phip0,
double phi_a0,
double phi_a1,
double a0,
double a1)
{
/* see Nocedal and Wright 2006, p. 58 */
double a, b, a2;
double a02 = a0 * a0; /* a0 squared */
double a12 = a1 * a1; /* a1 squared */
double a03 = a02 * a0; /* a0 cubed */
double a13 = a12 * a1; /* a1 cubed */
double v1 = phi_a1 - phi0 - phip0 * a1;
double v2 = phi_a0 - phi0 - phip0 * a0;
double norm = 1.0 / (a02 * a12 * (a1 - a0));
a = norm * (a02 * v1 - a12 * v2);
b = norm * (-a03 * v1 + a13 * v2);
a2 = (-b + sqrt(b * b - 3 * a * phip0)) / (3 * a);
return a2;
}
/*****************************************************************************/
double back_track(double *x,
double *p,
int N,
optimization_parameters *opt_par,
double alpha,
void *aux
)
{
static double a[2]; /* holds a set of step lengths that can be used for bracketing */
a[0] = 0;
a[1] = 0;
double (*misfit)(const double *, const int, void *) = opt_par->objective;
void (*grad)(const double *, double *, int, void *) = opt_par->grad;
int i;
double phi0, phip0;
double a0, a1, a2;
double phi_a0, phi_a1, phi_a2;
double *gradient = opt_allocate(sizeof(*gradient) * N);
double *x_update = opt_allocate(sizeof(*x_update) * N);
/* evaluate initial misfit and directional derivative */
phi0 = misfit(x, N, aux);
grad(x, gradient, N, aux);
phip0 = vec_dot_prod(gradient, p, N);
/* try a0*/
a0 = alpha;
a[1] = a0;
for (i=0;i<N;i++)
{
x_update[i] = x[i] + a0 * p[i];
}
phi_a0 = misfit(x_update, N, aux);
/* check Armijo condition */
if (phi_a0 <= phi0 + WOLFE_C1 * a0 * phip0)
{
/* condition satisfied */
free(x_update);
free(gradient);
return a0;
}
/* try quadratic approximation */
a1 = back_track_quad(phi0, phip0, phi_a0, a0);
a[0] = a1;
for (i=0;i<N;i++)
{
x_update[i] = x[i] + a1 * p[i];
}
phi_a1 = misfit(x_update, N, aux);
/* check Armijo condition */
if (phi_a1 <= phi0 + WOLFE_C1 * a1 * phip0)
{
/* condition satisfied */
free(x_update);
free(gradient);
return a1;
}
/* move into cubic approximations */
int cubic_max = 10; /* <----------May need to adjust max number of iterations */
int j;
for (j=0;j<cubic_max;j++)
{
a2 = back_track_cubic(phi0, phip0, phi_a0, phi_a1, a0, a1);
/* make sure a2 is not too close to a1 */
if (fabs(a2 - a1) / a1 < 0.01) /* <--------- May need to adjust the factor of 0.01 here */
a2 = 0.5 * a1;
/* make sure a2 is not too much smaller than a1 */
if (a2 < (0.01 * a1)) /* <-------- May need to adjust the factor of 0.01 here */
a2 = 0.5 * a1;
a[1] = a[0];
a[0] = a2;
for (i=0;i<N;i++)
{
x_update[i] = x[i] + a2 * p[i];
}
phi_a2 = misfit(x_update, N, aux);
/* check Armijo condition */
if (phi_a2 <= phi0 + WOLFE_C1 * a2 * phip0)
{
/* condition satisfied */
break;
}
/* keep only the two newest values */
a0 = a1;
phi_a0 = phi_a1;
a1 = a2;
phi_a1 = phi_a2;
}
if (j >= cubic_max)
{
fprintf(stderr,"Backtrack failed to return an "
"appropriate step length\n");
//exit(1);
}
free(x_update);
free(gradient);
return a2;
}
/*****************************************************************************/
double max3(double x1, double x2, double x3)
{
double mm = (x1 > x2) ? x1 : x2;
mm = (mm > x3) ? mm : x3;
return mm;
}
void modified_chol(double *A, int N)
{
/* make temp copy of A */
double *temp = opt_allocate(sizeof(*temp) * N * N);
double *c = opt_allocate(sizeof(*c) * N * N);
double *d = opt_allocate(sizeof(*d) * N);
memcpy(temp, A, sizeof(*temp) * N *N);
int i, j, s;
double sum = 0;
double beta = 1.0;
double delta = 1.0e-3;
double theta = 0.0;
for (j = 0; j < N; j++)
{
for (s=0;s<j;s++)
{
sum = d[s] * A[j+s*N] * A[j+s*N];
}
c[j+j*N] = temp[j+j*N] - sum;
A[j+j*N] = 1.0;
//d[j] = c[j+j*N];
d[j] = max3(fabs(c[j+j*N]),pow(theta / beta,2.0),delta);
theta = DBL_MIN;
for (i = j+1; i<N;i++)
{
for (s=0;s<j;s++)
{
sum = d[s] * A[i+s*N] * A[j+s*N];
}
c[i+j*N] = temp[j+i*N] -sum;
theta = theta > c[i+j*N] ? theta : c[i+j*N];
A[i+j*N] = c[i+j*N] / d[j];
}
}
for (j=0;j<N;j++)
{
for (i=j;i<N;i++)
{
A[i+j*N] = A[i+j*N] * sqrt(d[j]);
}
}
//printf("Diag:\n");
//for (i=0;i<N;i++)
// printf("%f\n",d[i]);
free(d);
free(c);
free(temp);
}
void* opt_allocate(long nbytes)
{
void *ptr = malloc(nbytes);
if (!ptr)
{
fprintf(stderr, "Error: optimization.c : memory allocation failure\n");
exit (1);
}
return ptr;
} | {
"alphanum_fraction": 0.4806441261,
"avg_line_length": 26.3279569892,
"ext": "c",
"hexsha": "ad6d42c3d79f9d615bfcb14994d1c2a777192c4c",
"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": "5fbb42590dec4187314eb1bd21ea8d24c207209b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dt-jackson/FWI",
"max_forks_repo_path": "src/optimization.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5fbb42590dec4187314eb1bd21ea8d24c207209b",
"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": "dt-jackson/FWI",
"max_issues_repo_path": "src/optimization.c",
"max_line_length": 130,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5fbb42590dec4187314eb1bd21ea8d24c207209b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dt-jackson/FWI",
"max_stars_repo_path": "src/optimization.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8908,
"size": 34279
} |
// -*- C++ -*-
//
// michael a.g. aïvázis <michael.aivazis@para-sim.com>
//
// (c) 2013-2020 parasim inc
// (c) 2010-2020 california institute of technology
// all rights reserved
//
// code guard
#if !defined(altar_bayesian_COV_h)
#define altar_bayesian_COV_h
// externals
#include <gsl/gsl_rng.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
// place everything in the local namespace
namespace altar {
namespace bayesian {
// forward declarations
class COV;
class CoolingStep;
} // of namespace bayesian
} // of namespace altar
// declaration
class altar::bayesian::COV
{
// types
public:
typedef CoolingStep state_t;
typedef gsl_rng rng_t;
typedef gsl_vector vector_t;
typedef gsl_matrix matrix_t;
// accessors
public:
inline auto cov() const;
inline auto beta() const;
// interface
public:
virtual double dbeta_brent(vector_t * llk, double llkMedian, vector_t * w);
virtual double dbeta_grid(vector_t * llk, double llkMedian, vector_t * w);
// meta-methods
public:
virtual ~COV();
inline COV(rng_t * rng, double tolerance=.001, size_t maxIterations=1000, double target=1.0);
// data
private:
const double _betaMin;
const double _betaMax;
rng_t * _rng;
double _tolerance;
size_t _maxIterations;
double _target;
double _beta, _cov;
// disallow
private:
COV(const COV &) = delete;
const COV & operator=(const COV &) = delete;
};
// get the inline definitions
#define altar_bayesian_COV_icc
#include "COV.icc"
#undef altar_bayesian_COV_icc
# endif
// end of file
| {
"alphanum_fraction": 0.6789895256,
"avg_line_length": 20.2875,
"ext": "h",
"hexsha": "8a02ce585fa65550e367610953765cafed0f3103",
"lang": "C",
"max_forks_count": 20,
"max_forks_repo_forks_event_max_datetime": "2022-02-10T07:10:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-26T18:40:41.000Z",
"max_forks_repo_head_hexsha": "3f13e04640331702387f1eb696acfc21a94f26f7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "AlTarFramework/altar",
"max_forks_repo_path": "altar/lib/libaltar/bayesian/COV.h",
"max_issues_count": 13,
"max_issues_repo_head_hexsha": "3f13e04640331702387f1eb696acfc21a94f26f7",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T06:48:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-11-20T15:55:50.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "AlTarFramework/altar",
"max_issues_repo_path": "altar/lib/libaltar/bayesian/COV.h",
"max_line_length": 97,
"max_stars_count": 32,
"max_stars_repo_head_hexsha": "3f13e04640331702387f1eb696acfc21a94f26f7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "AlTarFramework/altar",
"max_stars_repo_path": "altar/lib/libaltar/bayesian/COV.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-15T23:48:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-04-24T05:32:27.000Z",
"num_tokens": 456,
"size": 1623
} |
#include <gsl/gsl_complex.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_blas.h>
/* Level 1 */
int mgsl_blas_caxpy(gsl_complex_float *alpha, gsl_vector_complex_float *x, gsl_vector_complex_float *y)
{
return gsl_blas_caxpy(*alpha, x, y);
}
int mgsl_blas_zaxpy(gsl_complex *alpha, gsl_vector_complex *x, gsl_vector_complex *y)
{
return gsl_blas_zaxpy(*alpha, x, y);
}
void mgsl_blas_cscal(gsl_complex_float *alpha, gsl_vector_complex_float *x)
{
gsl_blas_cscal(*alpha, x);
}
void mgsl_blas_zscal(gsl_complex *alpha, gsl_vector_complex *x)
{
gsl_blas_zscal(*alpha, x);
}
/* Level 2 */
int mgsl_blas_cgemv(CBLAS_TRANSPOSE_t TransA, gsl_complex_float *alpha, gsl_matrix_complex_float *A, gsl_vector_complex_float *x, gsl_complex_float *beta, gsl_vector_complex_float *y)
{
return gsl_blas_cgemv(TransA, *alpha, A, x, *beta, y);
}
int mgsl_blas_zgemv(CBLAS_TRANSPOSE_t TransA, gsl_complex *alpha, gsl_matrix_complex *A, gsl_vector_complex *x, gsl_complex *beta, gsl_vector_complex *y)
{
return gsl_blas_zgemv(TransA, *alpha, A, x, *beta, y);
}
int mgsl_blas_chemv(CBLAS_UPLO_t Uplo, gsl_complex_float *alpha, gsl_matrix_complex_float *A, gsl_vector_complex_float *x, gsl_complex_float *beta, gsl_vector_complex_float *y)
{
return gsl_blas_chemv(Uplo, *alpha, A, x, *beta, y);
}
int mgsl_blas_zhemv(CBLAS_UPLO_t Uplo, gsl_complex *alpha, gsl_matrix_complex *A, gsl_vector_complex *x, gsl_complex *beta, gsl_vector_complex *y)
{
return gsl_blas_zhemv(Uplo, *alpha, A, x, *beta, y);
}
int mgsl_blas_cgeru(gsl_complex_float *alpha, gsl_vector_complex_float *x, gsl_vector_complex_float *y, gsl_matrix_complex_float *A)
{
return gsl_blas_cgeru(*alpha, x, y, A);
}
int mgsl_blas_zgeru(gsl_complex *alpha, gsl_vector_complex *x, gsl_vector_complex *y, gsl_matrix_complex *A)
{
return gsl_blas_zgeru(*alpha, x, y, A);
}
int mgsl_blas_cgerc(gsl_complex_float *alpha, gsl_vector_complex_float *x, gsl_vector_complex_float *y, gsl_matrix_complex_float *A)
{
return gsl_blas_cgerc(*alpha, x, y, A);
}
int mgsl_blas_zgerc(gsl_complex *alpha, gsl_vector_complex *x, gsl_vector_complex *y, gsl_matrix_complex *A)
{
return gsl_blas_zgerc(*alpha, x, y, A);
}
int mgsl_blas_cher2(CBLAS_UPLO_t Uplo, gsl_complex_float *alpha, gsl_vector_complex_float *x, gsl_vector_complex_float *y, gsl_matrix_complex_float *A)
{
return gsl_blas_cher2(Uplo, *alpha, x, y, A);
}
int mgsl_blas_zher2(CBLAS_UPLO_t Uplo, gsl_complex *alpha, gsl_vector_complex *x, gsl_vector_complex *y, gsl_matrix_complex *A)
{
return gsl_blas_zher2(Uplo, *alpha, x, y, A);
}
int mgsl_blas_cgemm(CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, gsl_complex_float *alpha, gsl_matrix_complex_float *A, gsl_matrix_complex_float *B, gsl_complex_float *beta, gsl_matrix_complex_float *C)
{
return gsl_blas_cgemm(TransA, TransB, *alpha, A, B, *beta, C);
}
int mgsl_blas_zgemm(CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB, gsl_complex *alpha, gsl_matrix_complex *A, gsl_matrix_complex *B, gsl_complex *beta, gsl_matrix_complex *C)
{
return gsl_blas_zgemm(TransA, TransB, *alpha, A, B, *beta, C);
}
int mgsl_blas_csymm(CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, gsl_complex_float *alpha, gsl_matrix_complex_float *A, gsl_matrix_complex_float *B, gsl_complex_float *beta, gsl_matrix_complex_float *C)
{
return gsl_blas_csymm(Side, Uplo, *alpha, A, B, *beta, C);
}
int mgsl_blas_zsymm(CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, gsl_complex *alpha, gsl_matrix_complex *A, gsl_matrix_complex *B, gsl_complex *beta, gsl_matrix_complex *C)
{
return gsl_blas_zsymm(Side, Uplo, *alpha, A, B, *beta, C);
}
int mgsl_blas_chemm(CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, gsl_complex_float *alpha, gsl_matrix_complex_float *A, gsl_matrix_complex_float *B, gsl_complex_float *beta, gsl_matrix_complex_float *C)
{
return gsl_blas_chemm(Side, Uplo, *alpha, A, B, *beta, C);
}
int mgsl_blas_zhemm(CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, gsl_complex *alpha, gsl_matrix_complex *A, gsl_matrix_complex *B, gsl_complex *beta, gsl_matrix_complex *C)
{
return gsl_blas_zhemm(Side, Uplo, *alpha, A, B, *beta, C);
}
int mgsl_blas_ctrmm(CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, gsl_complex_float *alpha, gsl_matrix_complex_float *A, gsl_matrix_complex_float *B)
{
return gsl_blas_ctrmm(Side, Uplo, TransA, Diag, *alpha, A, B);
}
int mgsl_blas_ztrmm(CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, gsl_complex *alpha, gsl_matrix_complex *A, gsl_matrix_complex *B)
{
return gsl_blas_ztrmm(Side, Uplo, TransA, Diag, *alpha, A, B);
}
int mgsl_blas_ctrsm(CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, gsl_complex_float *alpha, gsl_matrix_complex_float *A, gsl_matrix_complex_float *B)
{
return gsl_blas_ctrsm(Side, Uplo, TransA, Diag, *alpha, A, B);
}
int mgsl_blas_ztrsm(CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag, gsl_complex *alpha, gsl_matrix_complex *A, gsl_matrix_complex *B)
{
return gsl_blas_ztrsm(Side, Uplo, TransA, Diag, *alpha, A, B);
}
int mgsl_blas_csyrk(CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, gsl_complex_float *alpha, gsl_matrix_complex_float *A, gsl_complex_float *beta, gsl_matrix_complex_float *C)
{
return gsl_blas_csyrk(Uplo, TransA, *alpha, A, *beta, C);
}
int mgsl_blas_zsyrk(CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, gsl_complex *alpha, gsl_matrix_complex *A, gsl_complex *beta, gsl_matrix_complex *C)
{
return gsl_blas_zsyrk(Uplo, TransA, *alpha, A, *beta, C);
}
int mgsl_blas_csyr2k(CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, gsl_complex_float *alpha, gsl_matrix_complex_float *A, gsl_matrix_complex_float *B, gsl_complex_float *beta, gsl_matrix_complex_float *C)
{
return gsl_blas_csyr2k(Uplo, TransA, *alpha, A, B, *beta, C);
}
int mgsl_blas_zsyr2k(CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, gsl_complex *alpha, gsl_matrix_complex *A, gsl_matrix_complex *B, gsl_complex *beta, gsl_matrix_complex *C)
{
return gsl_blas_zsyr2k(Uplo, TransA, *alpha, A, B, *beta, C);
}
int mgsl_blas_cher2k(CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, gsl_complex_float *alpha, gsl_matrix_complex_float *A, gsl_matrix_complex_float *B, float beta, gsl_matrix_complex_float *C)
{
return gsl_blas_cher2k(Uplo, TransA, *alpha, A, B, beta, C);
}
int mgsl_blas_zher2k(CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA, gsl_complex *alpha, gsl_matrix_complex *A, gsl_matrix_complex *B, double beta, gsl_matrix_complex *C)
{
return gsl_blas_zher2k(Uplo, TransA, *alpha, A, B, beta, C);
}
| {
"alphanum_fraction": 0.7841187271,
"avg_line_length": 41.8974358974,
"ext": "c",
"hexsha": "a4e150eacef8d1674636aec0bd04d6a3cfeb8de7",
"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": "2c77f2d14da6cdef3a3cfb383ed3557f61438718",
"max_forks_repo_licenses": [
"Artistic-2.0"
],
"max_forks_repo_name": "frithnanth/raku-Math-Libgsl-BLAS",
"max_forks_repo_path": "src/blas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2c77f2d14da6cdef3a3cfb383ed3557f61438718",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Artistic-2.0"
],
"max_issues_repo_name": "frithnanth/raku-Math-Libgsl-BLAS",
"max_issues_repo_path": "src/blas.c",
"max_line_length": 209,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2c77f2d14da6cdef3a3cfb383ed3557f61438718",
"max_stars_repo_licenses": [
"Artistic-2.0"
],
"max_stars_repo_name": "frithnanth/raku-Math-Libgsl-BLAS",
"max_stars_repo_path": "src/blas.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2181,
"size": 6536
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <pthread.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include "LSAbundance.h"
static int verbose = FALSE;
static int nLines = 9;
static char *usage[] = {"LSAbundance - \n",
"Required parameters:\n",
" -a abundance data\n",
" -in filename parameter file \n",
"Optional:\n",
" -b integer length of sample file to ignore\n",
" -s integer sampling frequency\n",
" -seed long seed random number generator\n",
" -v verbose\n"};
void updateExpectations(double* adExpect, int nMax, double dMDash, double dV, double dNu, int nS, t_Data *ptData)
{
int i = 0;
for(i = 1; i <= nMax; i++){
int nA = i;
double dLog = 0.0, dP = 0.0;
if(nA < MAX_QUAD){
dLog = logLikelihoodQuad(nA, dMDash, dV, dNu);
}
else{
dLog = logLikelihoodRampal(nA, dMDash, dV, dNu);
}
dP = exp(dLog);
adExpect[i - 1]+= dP*nS;
}
}
int main(int argc, char* argv[]){
t_Params tParams;
t_LSParams* atLSParams;
int i = 0, nSamples = 0, nMax = 0;
t_Data tData;
double* adExpect = NULL;
gsl_set_error_handler_off();
getCommandLineParams(&tParams, argc, argv);
/*allocate memory for samples*/
atLSParams = (t_LSParams *) malloc(MAX_SAMPLES*sizeof(t_LSParams));
if(!atLSParams)
goto memoryError;
/*read in Monte-Carlo samples*/
readSamples(&tParams, atLSParams, &nSamples);
readAbundanceData(tParams.szAbundFile, &tData);
nMax = tData.aanAbund[tData.nNA - 1][0];
nMax = floor(pow(2.0,ceil(log((double) nMax)/log(2.0)) + 2.0) + 1.0e-7);
adExpect = (double *) malloc(sizeof(double)*nMax);
for(i = 0; i < nMax; i++){
adExpect[i] = 0.0;
}
for(i = 0; i < nSamples; i++){
updateExpectations(adExpect, nMax,
atLSParams[i].dMDash,
atLSParams[i].dV,
atLSParams[i].dNu,
atLSParams[i].nS,
&tData);
}
for(i = 1; i <= nMax; i++){
printf("%d %f\n",i,adExpect[i - 1]/((double) nSamples));
}
free(adExpect);
exit(EXIT_SUCCESS);
memoryError:
fprintf(stderr, "Failed to allocate memory in main aborting ...\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
int intCompare(const void *pvA, const void *pvB)
{
int* pnA = (int *) pvA, *pnB = (int *) pvB;
if(*pnA < *pnB)
return +1;
else if(*pnA == *pnB){
return 0;
}
else{
return -1;
}
}
int doubleCompare(const void *pvA, const void *pvB)
{
double* pnA = (double *) pvA, *pnB = (double *) pvB;
if(*pnA < *pnB)
return +1;
else if(*pnA == *pnB){
return 0;
}
else{
return -1;
}
}
void writeUsage(FILE* ofp)
{
int i = 0;
char *line;
for(i = 0; i < nLines; i++){
line = usage[i];
fputs(line,ofp);
}
}
char *extractParameter(int argc, char **argv, char *param,int when)
{
int i = 0;
while((i < argc) && (strcmp(param,argv[i]))){
i++;
}
if(i < argc - 1){
return(argv[i + 1]);
}
if((i == argc - 1) && (when == OPTION)){
return "";
}
if(when == ALWAYS){
fprintf(stdout,"Can't find asked option %s\n",param);
}
return (char *) NULL;
}
void getCommandLineParams(t_Params *ptParams,int argc,char *argv[])
{
char *szTemp = NULL;
char *cError = NULL;
/*get parameter file name*/
ptParams->szInputFile = extractParameter(argc,argv, INPUT_FILE,ALWAYS);
if(ptParams->szInputFile == NULL)
goto error;
/*get abundance file name*/
ptParams->szAbundFile = extractParameter(argc,argv, ABUND_FILE,ALWAYS);
if(ptParams->szAbundFile == NULL)
goto error;
/*get long seed*/
szTemp = extractParameter(argc,argv,SEED,OPTION);
if(szTemp != NULL){
ptParams->lSeed = strtol(szTemp,&cError,10);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->lSeed = 0;
}
/*get burn*/
szTemp = extractParameter(argc, argv, BURN, OPTION);
if(szTemp != NULL){
ptParams->nBurn = strtol(szTemp,&cError,10);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->nBurn = DEF_BURN;
}
/*get long seed*/
szTemp = extractParameter(argc, argv, SAMPLE, OPTION);
if(szTemp != NULL){
ptParams->nSample = strtol(szTemp,&cError,10);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->nSample = DEF_SAMPLE;
}
/*verbosity*/
szTemp = extractParameter(argc, argv, VERBOSE, OPTION);
if(szTemp != NULL){
verbose = TRUE;
}
return;
error:
writeUsage(stdout);
exit(EXIT_FAILURE);
}
void readSamples(t_Params *ptParams, t_LSParams *atLSParams, int *pnSamples)
{
int nSamples = 0;
char *szInputFile = ptParams->szInputFile;
char szLine[MAX_LINE_LENGTH];
FILE *ifp = NULL;
ifp = fopen(szInputFile, "r");
if(ifp){
while(fgets(szLine, MAX_LINE_LENGTH, ifp)){
char *szTok = NULL, *szBrk = NULL, *pcError = NULL;
int nTime = 0;
/*remove trailing new line*/
szBrk = strpbrk(szLine, "\n"); (*szBrk) = '\0';
szTok = strtok(szLine, DELIM);
nTime = strtol(szTok, &pcError, 10);
if(*pcError != '\0') goto fileFormatError;
if(nTime > ptParams->nBurn && nTime % ptParams->nSample == 0){
szTok = strtok(NULL,DELIM);
atLSParams[nSamples].dMDash = strtod(szTok, &pcError);
if(*pcError != '\0') goto fileFormatError;
szTok = strtok(NULL,DELIM);
atLSParams[nSamples].dV = strtod(szTok, &pcError);
if(*pcError != '\0') goto fileFormatError;
szTok = strtok(NULL,DELIM);
atLSParams[nSamples].dNu = strtod(szTok, &pcError);
if(*pcError != '\0') goto fileFormatError;
szTok = strtok(NULL,DELIM);
atLSParams[nSamples].nS = strtol(szTok, &pcError, 10);
if(*pcError != '\0') goto fileFormatError;
nSamples++;
}
}
fclose(ifp);
}
else{
fprintf(stderr, "Failed to open file %s aborting\n", szInputFile);
fflush(stderr);
exit(EXIT_FAILURE);
}
(*pnSamples) = nSamples;
return;
fileFormatError:
fprintf(stderr, "Incorrectly formatted input file aborting\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
double f1(double x, void *pvParams)
{
t_LSParams *ptLSParams = (t_LSParams *) pvParams;
double dMDash = ptLSParams->dMDash, dV = ptLSParams->dV, dNu = ptLSParams->dNu;
int n = ptLSParams->n;
double t = ((x - dMDash)*(x - dMDash))/dV;
double dExp = x*((double) n) - exp(x);
double dF = pow(1.0 + t/dNu, -0.5*(dNu + 1.0));
return exp(dExp)*dF;
}
double f1Log(double x, void *pvParams)
{
t_LNParams *ptLNParams = (t_LNParams *) pvParams;
double dMDash = ptLNParams->dMDash, dV = ptLNParams->dV;
int n = ptLNParams->n;
double dTemp = (x - dMDash);
double dExp = x*((double) n) - exp(x) - 0.5*((dTemp*dTemp)/dV);
double dRet = exp(dExp);
return dRet;
}
double derivExponent(double x, void *pvParams)
{
t_LNParams *ptLNParams = (t_LNParams *) pvParams;
double dMDash = ptLNParams->dMDash, dV = ptLNParams->dV, n = ptLNParams->n;
double dTemp = (x - dMDash)/dV, dRet = 0.0;
dRet = ((double) n) - exp(x) - dTemp;
return dRet;
}
double logStirlingsGamma(double dZ)
{
return 0.5*log(2.0*M_PI) + (dZ - 0.5)*log(dZ) - dZ;
}
double logLikelihoodQuad(int n, double dMDash, double dV, double dNu)
{
gsl_integration_workspace *ptGSLWS =
gsl_integration_workspace_alloc(1000);
double dLogFac1 = 0.0, dLogFacN = 0.0;
double dN = (double) n, dResult = 0.0, dError = 0.0, dPrecision = 0.0;
gsl_function tGSLF;
t_LSParams tLSParams;
double dEst = dMDash + ((double)n)*dV, dA = 0.0, dB = 0.0;
tLSParams.n = n; tLSParams.dMDash = dMDash; tLSParams.dV = dV; tLSParams.dNu = dNu;
tGSLF.function = &f1;
tGSLF.params = (void *) &tLSParams;
if(dNu < MAX_MU_GAMMA){
dLogFac1 = gsl_sf_lngamma(0.5*(dNu + 1.0)) - gsl_sf_lngamma(0.5*dNu) - 0.5*log(M_PI*dNu);
}
else{
dLogFac1 = 0.5*dNu*(log(0.5*(dNu + 1.0)) - log(0.5*dNu)) -0.5*log(2.0*M_PI) - 0.5;
}
if(n < 50){
dLogFacN = gsl_sf_fact(n);
dLogFacN = log(dLogFacN);
}
else if(n < 100){
dLogFacN = gsl_sf_lngamma(dN + 1.0);
}
else{
dLogFacN = logStirlingsGamma(dN + 1.0);
}
dA = -100.0; dB = 100.0;
if(n < 10){
dPrecision = HI_PRECISION;
}
else{
dPrecision = LO_PRECISION;
}
gsl_integration_qag(&tGSLF, dA, dB, dPrecision, 0.0, 1000, GSL_INTEG_GAUSS61, ptGSLWS, &dResult, &dError);
//printf("%f %f\n", dResult, dError);
gsl_integration_workspace_free(ptGSLWS);
return log(dResult) - dLogFacN + dLogFac1 - 0.5*log(dV);
}
int solveF(double x_lo, double x_hi, double (*f)(double, void*),
void* params, double tol, double *xsolve)
{
int status, iter = 0, max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
double r = 0;
gsl_function F;
t_LNParams *ptLNParams = (t_LNParams *) params;
F.function = f;
F.params = params;
//printf("%f %f %d %f %f\n",ptLNParams->dMDash, ptLNParams->dV, ptLNParams->n, x_lo, x_hi);
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc (T);
gsl_root_fsolver_set (s, &F, x_lo, x_hi);
do{
iter++;
status = gsl_root_fsolver_iterate (s);
r = gsl_root_fsolver_root (s);
x_lo = gsl_root_fsolver_x_lower (s);
x_hi = gsl_root_fsolver_x_upper (s);
status = gsl_root_test_interval (x_lo, x_hi, 0, tol);
}
while (status == GSL_CONTINUE && iter < max_iter);
(*xsolve) = gsl_root_fsolver_root (s);
gsl_root_fsolver_free (s);
return status;
}
double logLikelihoodLNQuad(int n, double dMDash, double dV)
{
gsl_integration_workspace *ptGSLWS =
gsl_integration_workspace_alloc(1000);
double dLogFac1 = 0.0, dLogFacN = 0.0;
double dResult = 0.0, dError = 0.0, dPrecision = 0.0;
gsl_function tGSLF;
t_LNParams tLNParams;
double dEst = dMDash + ((double)n)*dV, dA = 0.0, dB = 0.0;
tLNParams.n = n; tLNParams.dMDash = dMDash; tLNParams.dV = dV;
tGSLF.function = &f1Log;
tGSLF.params = (void *) &tLNParams;
dLogFac1 = log(2.0*M_PI*dV);
if(n < 50){
dLogFacN = gsl_sf_fact(n);
dLogFacN = log(dLogFacN);
}
else{
dLogFacN = gsl_sf_lngamma(((double) n) + 1.0);
}
if(dEst > dV){
double dMax = 0.0;
double dUpper = (((double) n) + (dMDash/dV) - 1.0)/(1.0 + 1.0/dV);
double dVar = 0.0;
if(fabs(dUpper) > 1.0e-7){
solveF(0.0, dUpper, derivExponent, (void *) &tLNParams, 1.0e-5, &dMax);
}
dVar = sqrt(1.0/((1.0/dV) + exp(dMax)));
dA = dMax - V_MULT*dVar; dB = dMax + V_MULT*dVar;
}
else{
double dMax = 0.0;
double dLower = dEst - dV;
double dUpper = (((double) n) + (dMDash/dV) - 1.0)/(1.0 + 1.0/dV);
double dVar = 0.0;
if(fabs(dUpper - dLower) > 1.0e-7){
solveF(dLower, dUpper, derivExponent, (void *) &tLNParams, 1.0e-5, &dMax);
}
else{
dMax = 0.5*(dLower + dUpper);
}
dVar = sqrt(1.0/((1.0/dV) + exp(dMax)));
dA = dMax - V_MULT*dVar; dB = dMax + V_MULT*dVar;
}
if(n < 10){
dPrecision = HI_PRECISION;
}
else{
dPrecision = LO_PRECISION;
}
gsl_integration_qag(&tGSLF, dA, dB, dPrecision, 0.0, 1000, GSL_INTEG_GAUSS61, ptGSLWS, &dResult, &dError);
gsl_integration_workspace_free(ptGSLWS);
return log(dResult) - dLogFacN -0.5*dLogFac1;
}
double logLikelihoodLNRampal(int n, double dMDash, double dV)
{
double dN = (double) n;
double dLogLik = 0.0, dTemp = gsl_pow_int(log(dN) - dMDash,2), dTemp3 = gsl_pow_int(log(dN) - dMDash,3);
dLogLik = -0.5*log(2.0*M_PI*dV) - log(dN) - (dTemp/(2.0*dV));
dLogLik += log(1.0 + 1.0/(2.0*dN*dV)*(dTemp/dV + log(dN) - dMDash - 1.0)
+ 1.0/(6.0*dN*dN*dV*dV*dV)*(3.0*dV*dV - (3.0*dV - 2.0*dV*dV)*(dMDash - log(dN))
- 3.0*dV*dTemp + dTemp3));
return dLogLik;
}
double logLikelihoodRampal(int n, double dMDash, double dV, double dNu)
{
double dGamma = 0.5*(dNu + 1.0), dN = (double) n, dRN = 1.0/dN, dRSV = 1.0/(sqrt(dV)*sqrt(dNu));
double dZ = (log(dN) - dMDash)*dRSV;
double dDZDX = dRN*dRSV, dDZDX2 = -dRN*dRN*dRSV;
double dF = (1.0 + dZ*dZ);
double dA = 0.0, dB = 0.0, dTemp = 0.0;
double dLogFac1 = 0.0;
if(dNu < MAX_MU_GAMMA){
dLogFac1 = gsl_sf_lngamma(0.5*(dNu + 1.0)) - gsl_sf_lngamma(0.5*dNu) - 0.5*log(M_PI*dNu);
}
else{
dLogFac1 = 0.5*dNu*(log(0.5*(dNu + 1.0)) - log(0.5*dNu)) -0.5*log(2.0*M_PI) - 0.5;
}
dA = 4.0*dZ*dZ*dDZDX*dDZDX*dGamma*(dGamma + 1.0);
dA /= dF*dF;
dB = -2.0*dGamma*(dDZDX*dDZDX + dZ*dDZDX2);
dB /= dF;
dTemp = dRN + dA + dB;
return -dGamma*log(dF) + log(dTemp) + dLogFac1 - 0.5*log(dV);
}
void readAbundanceData(const char *szFile, t_Data *ptData)
{
int **aanAbund = NULL;
int i = 0, nNA = 0, nA = 0, nC = 0;
int nL = 0, nJ = 0;
char szLine[MAX_LINE_LENGTH];
FILE* ifp = NULL;
ifp = fopen(szFile, "r");
if(ifp){
char* szTok = NULL;
char* pcError = NULL;
fgets(szLine, MAX_LINE_LENGTH, ifp);
szTok = strtok(szLine, DELIM2);
nNA = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
aanAbund = (int **) malloc(nNA*sizeof(int*));
for(i = 0; i < nNA; i++){
aanAbund[i] = (int *) malloc(sizeof(int)*2);
fgets(szLine, MAX_LINE_LENGTH, ifp);
szTok = strtok(szLine, DELIM2);
nA = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
szTok = strtok(NULL, DELIM2);
nC = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
nL += nC;
nJ += nC*nA;
aanAbund[i][0] = nA;
aanAbund[i][1] = nC;
}
}
else{
fprintf(stderr, "Failed to open abundance data file %s aborting\n", szFile);
fflush(stderr);
exit(EXIT_FAILURE);
}
ptData->nJ = nJ;
ptData->nL = nL;
ptData->aanAbund = aanAbund;
ptData->nNA = nNA;
return;
formatError:
fprintf(stderr, "Incorrectly formatted abundance data file\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
| {
"alphanum_fraction": 0.6007367526,
"avg_line_length": 23.7243697479,
"ext": "c",
"hexsha": "14bae4124d495fb83d6369136e157fee70a071dd",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "chrisquince/DiversityEstimates",
"max_forks_repo_path": "LSAbundance/LSAbundance.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "chrisquince/DiversityEstimates",
"max_issues_repo_path": "LSAbundance/LSAbundance.c",
"max_line_length": 113,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "chrisquince/DiversityEstimates",
"max_stars_repo_path": "LSAbundance/LSAbundance.c",
"max_stars_repo_stars_event_max_datetime": "2019-03-19T13:22:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-18T17:56:16.000Z",
"num_tokens": 5156,
"size": 14116
} |
/*
* -----------------------------------------------------------------
* ODE Solver Library --- ode_lib.c
* Version: 1.6180
* Date: Jan 4, 2011
* -----------------------------------------------------------------
* Programmer: Americo Barbosa da Cunha Junior
* americo.cunhajr@gmail.com
* -----------------------------------------------------------------
* Copyright (c) 2010 by Americo Barbosa da Cunha Junior
*
* 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.
*
* A copy of the GNU General Public License is available in
* LICENSE.txt or http://www.gnu.org/licenses/.
* -----------------------------------------------------------------
* This is the implementation file of a library
* with ODE solution tools.
* -----------------------------------------------------------------
*/
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <nvector/nvector_serial.h>
#include <cvode/cvode_dense.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "../include/ode_lib.h"
/*
*------------------------------------------------------------
* uround
*
* This function computes the machine unit roundoff
* defined as the smallest u such that 1.0 + u > 1.0
*
* Output:
* uround - machine unit roundoff
*
* last update: May 20, 2009
*------------------------------------------------------------
*/
double uround(void)
{
double u = 1.0;
double comp = 0.0;
while(comp != 1.0)
{
u *= 0.5;
comp = 1.0 + u;
}
return 2.0*u;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* wnorm
*
* This function computes v1 and v2 vector weight norm
* defined as
* wnorm = sqrt( (1/n)*(sum (v1[i]*v2[i])^2) )
*
* Input:
* n - vectors dimension
* v - vector 1
* v - vector 2
*
* Output:
* wnorm - weight norm
*
* last update: May 20, 2009
*------------------------------------------------------------
*/
double wnorm(int n,double *v1,double *v2)
{
int i;
double wnorm = 0.0;
for ( i = 0; i < n; i++ )
wnorm += v1[i]*v1[i]*v2[i]*v2[i];
return sqrt( wnorm / (double)n );
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* ewset
*
* This function creates a error weight vector
* defined as ewv[i] = rtol*abs(v[i]) + atol
*
* Input:
* n - vector dimension
* v - vector
* atol - absolute tolerance
* rtol - relative tolerance
*
* Output:
* ewv - error weight vector
*
* last update: May 22, 2009
*------------------------------------------------------------
*/
void ewtset(int n,double *v,double atol,double rtol,double *ewt)
{
int i;
for ( i = 0; i < n; i++ )
ewt[i] = rtol*fabs(v[i]) + atol;
return;
}
/*------------------------------------------------------------*/
/*------------------------------------------------------------
* jacobian
*
* This function computes the jacobian matrix of ydot = f(y,t)
* defiend as Jij = dfi/dyj
*
* Input:
* n - vector dimension
* f_data - pointer to external data
* Fy - reaction mapping
* y - composition vector
* t - time step
* atol - absolute tolerance
* rtol - relative tolerance
*
* Output:
* J - jacobian matrix
* success or error
*
* last update: Oct 7, 2009
------------------------------------------------------------*/
int jacobian(CVRhsFn f,void *f_data,gsl_vector *Fy,gsl_vector *y,
double t,double atol,double rtol,gsl_matrix *J)
{
unsigned int i, j, N1, N2;
double roundoff, min_inc_mult;
double fnorm, minInc, inc, inc_inv, yjsaved, srur;
double *yd_data = NULL;
double *Fyd_data = NULL;
N_Vector yd = NULL;
N_Vector Fyd = NULL;
gsl_vector *ewt = NULL;
min_inc_mult = 1.0e3;
/* vectors dimensions */
N1 = y->size;
N2 = Fy->size;
/* error weight vector */
ewt = gsl_vector_calloc(N1);
/* computing the unit roundoff */
roundoff = uround();
/* memory allocation and startup of yd and Fyd */
yd = N_VNew_Serial(N1);
Fyd = N_VNew_Serial(N2);
if ( yd == NULL || Fyd == NULL )
return GSL_ENOMEM;
/* obtaining yd and Fyd compoments */
yd_data = NV_DATA_S(yd);
Fyd_data = NV_DATA_S(Fyd);
/* setting yd equal y vector */
for ( i = 0; i < N1; i++ )
yd_data[i] = y->data[i];
/* setting Fyd equal the null vector */
for ( i = 0; i < N2; i++ )
Fyd_data[i] = 0.0;
/* defing error weight vector */
ewtset(N1,y->data,atol,rtol,ewt->data);
/* computing weight norm */
fnorm = wnorm(N2,Fy->data,ewt->data);
/* square root of the machine roundoff */
srur = sqrt(roundoff);
/* computing disturbance parameter */
minInc = (fnorm != 0.0) ?
(min_inc_mult*fabs(t)*roundoff*((double)N1)*fnorm) : 1.0;
for ( j = 0; j < N1; j++ )
{
/* saving y[j] value */
yjsaved = yd_data[j];
/* disturbance */
inc = GSL_MAX(srur*fabs(yjsaved),minInc/ewt->data[j]);
/* disturbing y */
yd_data[j] += inc;
/* computing Fy disturbed */
f(t,yd,Fyd,f_data);
/* restoring yd[j] original value */
yd_data[j] = yjsaved;
/* computing the step */
inc_inv = 1.0/inc;
/* computing jacobian matrix column j */
for ( i = 0; i < N2; i++ )
J->data[i*J->tda+j] = inc_inv*(Fyd_data[i] - Fy->data[i]);
}
/* releasing allocated memory */
N_VDestroy_Serial(yd);
N_VDestroy_Serial(Fyd);
gsl_vector_free(ewt);
yd = NULL;
Fyd = NULL;
yd_data = NULL;
Fyd_data = NULL;
ewt = NULL;
return GSL_SUCCESS;
}
/*------------------------------------------------------------*/
/*------------------------------------------------------------
* gradient
*
* This function computes the gradient matrix of R(phi)
* defiend as: Aij = d R_i/d phi_j
*
* Input:
* f - right hand side function
* f_data - pointer to external data
* t0 - initial time
* delta_t - time step
* atol - absolute tolerance
* rtol - relative tolerance
* phi - composition vector
* Rphi - reac tion mapping
*
* Output:
* A - gradient matrix
* success or error
*
* last update: Feb 19, 2010
------------------------------------------------------------*/
int gradient(CVRhsFn f,void *f_data,void *cvode_mem,double t0,double delta_t,
double atol,double rtol,gsl_vector *phi,gsl_vector *Rphi,gsl_matrix *A)
{
unsigned int i, j, flag;
double inc, inc_inv, phijsaved, srur;
gsl_vector *Rphid = NULL;
/* memory allocation for Rphid */
Rphid = gsl_vector_calloc(Rphi->size);
/* square root of 1.0e6 times the machine roundoff */
srur = sqrt(1.0e6*DBL_EPSILON);
for ( j = 0; j < phi->size; j++ )
{
/* saving phi_j value */
phijsaved = phi->data[j];
/* disturbance */
inc = phijsaved*srur + srur;
/* disturbing phi_j */
phi->data[j] += inc;
/* computing R(phi) disturbed */
flag = odesolver_reinit(f,f_data,t0,atol,rtol,phi,cvode_mem);
if ( flag != GSL_SUCCESS )
return flag;
flag = odesolver(cvode_mem,delta_t,Rphid);
if ( flag != GSL_SUCCESS )
return flag;
/* restoring phi_j original value */
phi->data[j] = phijsaved;
/* computing the step */
inc_inv = 1.0/inc;
/* computing gradient matrix column j */
for ( i = 0; i < Rphi->size; i++ )
A->data[i*A->tda+j] = inc_inv*(Rphid->data[i] - Rphi->data[i]);
}
/* releasing allocated memory */
gsl_vector_free(Rphid);
Rphid = NULL;
return GSL_SUCCESS;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* linear_approx
*
* This function computes the linear approximation
* for a vector function F(x) near the point x0.
*
* F(x) = F(x0) + DF(x0)*(x-x0) + O(|x-x0|^2)
*
* Input:
* x - vector x
* x0 - vector x0
* Fx0 - function at x0
* DFx0 - jacobian matrix at x0
*
* Output:
* Fx - linear approximation for F(x)
*
* last update: Jun 9, 2009
*------------------------------------------------------------
*/
void linear_approx(gsl_vector *x,gsl_vector *x0,
gsl_vector *Fx0,gsl_matrix *DFx0,gsl_vector *Fx)
{
gsl_vector *aux = NULL;
/* memory allocation */
aux = gsl_vector_alloc(x0->size);
/* aux := x */
gsl_vector_memcpy(aux,x);
/* aux := x - x0 */
gsl_vector_sub(aux,x0);
/* Fx := F(x0) */
gsl_vector_memcpy(Fx,Fx0);
/* Fx := F(x0) + DF(x0)*(x-x0) */
gsl_blas_dgemv(CblasNoTrans,1.0,DFx0,aux,1.0,Fx);
/* releasing allocated memory */
gsl_vector_free(aux);
aux = NULL;
return;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* odesolver_init
*
* This function initiates the ODE solver workspace.
*
* Input:
* f - right hand side function
* f_data - right hand side function data
* t0 - initial time
* mxsteps - max # of solver iterations
* atol - absolute tolerance
* rtol - relative tolerance
* x - initial condition
* cvode_mem - ODE solver workspace
*
* Output:
* success or error
*
* last update: Jan 4, 2011
*------------------------------------------------------------
*/
int odesolver_init(CVRhsFn f,void *f_data,double t0,int mxsteps,
double atol,double rtol,gsl_vector *x,void *cvode_mem)
{
int maxnef = 100;
int flag = CV_SUCCESS;
N_Vector y0 = NULL;
/* memory allocation and startup of y0 */
y0 = N_VMake_Serial(x->size,x->data);
if ( y0 == NULL )
return GSL_ENOMEM;
/* memory allocation for CVODE */
flag = CVodeMalloc(cvode_mem,f,t0,y0,CV_SS,rtol,&atol);
if( flag != CV_SUCCESS )
return GSL_ENOMEM;
/* setting user data for right hand side function */
flag = CVodeSetFdata(cvode_mem,f_data);
if( flag != CV_SUCCESS )
return flag;
/* setting max # of steps to be taken by the solver */
flag = CVodeSetMaxNumSteps(cvode_mem,mxsteps);
if( flag != CV_SUCCESS )
return flag;
/* setting max # of error test failures permitted */
flag = CVodeSetMaxErrTestFails(cvode_mem,maxnef);
if( flag != CV_SUCCESS )
return flag;
/* setting dense linear solver */
flag = CVDense(cvode_mem,x->size);
if( flag != CV_SUCCESS )
return flag;
/* releasing allocated memory */
N_VDestroy_Serial(y0);
y0 = NULL;
return GSL_SUCCESS;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* odesolver_reinit
*
* This function reinitiates the ODE solver workspace.
*
* Input:
* f - right hand side function
* f_data - right hand side function data
* t0 - initial time
* atol - absolute tolerance
* rtol - relative tolerance
* x - initial condition
* cvode_mem - ODE solver workspace
*
* Output:
* success or error
*
* last update: Oct 31, 2009
*------------------------------------------------------------
*/
int odesolver_reinit(CVRhsFn f,void *f_data,double t0,
double atol,double rtol,gsl_vector *x,void *cvode_mem)
{
int flag = CV_SUCCESS;
N_Vector y0 = NULL;
/* memory allocation and startup of y0 */
y0 = N_VMake_Serial(x->size,x->data);
if ( y0 == NULL )
return GSL_ENOMEM;
/* restarting CVODE workspace */
flag = CVodeReInit(cvode_mem,f,t0,y0,CV_SS,rtol,&atol);
if( flag != CV_SUCCESS )
return flag;
/* setting user data for right hand side function */
flag = CVodeSetFdata(cvode_mem,f_data);
if( flag != CV_SUCCESS )
return flag;
/* releasing allocated memory */
N_VDestroy_Serial(y0);
y0 = NULL;
return GSL_SUCCESS;
}
/*------------------------------------------------------------*/
/*
*------------------------------------------------------------
* odesolver
*
* This function performs the direct integration of the
* governing equations.
*
* Input:
* cvode_mem - ODE solver workspace
* tf - final time
* Fx - solution vector
*
* Output:
* success or error
*
* last update: Oct 31, 2009
*------------------------------------------------------------
*/
int odesolver(void *cvode_mem,double tf,gsl_vector *Fx)
{
double t;
int flag = CV_SUCCESS;
N_Vector y = NULL;
/* memory allocation and startup of y */
y = N_VMake_Serial(Fx->size,Fx->data);
if ( y == NULL )
return GSL_ENOMEM;
/* calling CVode solver */
flag = CVode(cvode_mem,tf,y,&t,CV_NORMAL);
if( flag != CV_SUCCESS )
return flag;
/* releasing allocated memory */
N_VDestroy_Serial(y);
y = NULL;
return GSL_SUCCESS;
}
/*------------------------------------------------------------*/
| {
"alphanum_fraction": 0.5010828761,
"avg_line_length": 24.3873239437,
"ext": "c",
"hexsha": "d1aaa7a82107ad637395a3966dc3600f8f28c03f",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z",
"max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "americocunhajr/CRFlowLib",
"max_forks_repo_path": "CRFlowLib-1.0/src/ode_lib.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"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": "americocunhajr/CRFlowLib",
"max_issues_repo_path": "CRFlowLib-1.0/src/ode_lib.c",
"max_line_length": 77,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "americocunhajr/CRFlowLib",
"max_stars_repo_path": "CRFlowLib-1.0/src/ode_lib.c",
"max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z",
"num_tokens": 3690,
"size": 13852
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_
#define SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_
#include "./tensor_math.h"
#include <cfloat>
#include "singa/core/common.h"
#include <math.h>
#ifdef USE_CBLAS
#include <cblas.h>
#endif
namespace singa {
template <>
void Abs<float, lang::Cpp>(const size_t num, const Block *in, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = fabs(inPtr[i]);
}
}
template <>
void Add<float, lang::Cpp>(const size_t num, const Block *in, const float x,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = inPtr[i] + x;
}
}
template <>
void Add<float, lang::Cpp>(const size_t num, const Block *in1, const Block *in2,
Block *out, Context *ctx) {
// CHECK_EQ(ctx->stream, nullptr);
float *outPtr = static_cast<float *>(out->mutable_data());
const float *in1Ptr = static_cast<const float *>(in1->data());
const float *in2Ptr = static_cast<const float *>(in2->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = in1Ptr[i] + in2Ptr[i];
}
}
template <>
void Clamp<float, lang::Cpp>(const size_t num, const float low,
const float high, const Block *in, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
if (inPtr[i] > high) {
outPtr[i] = high;
} else if (inPtr[i] < low) {
outPtr[i] = low;
} else {
outPtr[i] = inPtr[i];
}
}
}
template <>
void Div<float, lang::Cpp>(const size_t num, const Block *in1, const Block *in2,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *in1Ptr = static_cast<const float *>(in1->data());
const float *in2Ptr = static_cast<const float *>(in2->data());
for (size_t i = 0; i < num; i++) {
CHECK_NE(in2Ptr[i], 0.f);
outPtr[i] = in1Ptr[i] / in2Ptr[i];
}
}
template <>
void Div<float, lang::Cpp>(const size_t num, const float x, const Block *in,
Block *out, Context *ctx) {
const float *inPtr = static_cast<const float *>(in->data());
float *outPtr = static_cast<float *>(out->mutable_data());
for (size_t i = 0; i < num; i++) {
CHECK_NE(inPtr[i], 0.f);
outPtr[i] = x / inPtr[i];
}
}
template <>
void EltwiseMult<float, lang::Cpp>(const size_t num, const Block *in,
const float x, Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = inPtr[i] * x;
}
}
template <>
void EltwiseMult<float, lang::Cpp>(const size_t num, const Block *in1,
const Block *in2, Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *in1Ptr = static_cast<const float *>(in1->data());
const float *in2Ptr = static_cast<const float *>(in2->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = in1Ptr[i] * in2Ptr[i];
}
}
template <>
void Exp<float, lang::Cpp>(const size_t num, const Block *in, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = exp(inPtr[i]);
}
}
template <>
void GE<float, lang::Cpp>(const size_t num, const Block *in, const float x,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = (inPtr[i] >= x) ? 1.f : 0.f;
}
}
template <>
void GE<float, lang::Cpp>(const size_t num, const Block *in1, const Block *in2,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr1 = static_cast<const float *>(in1->data());
const float *inPtr2 = static_cast<const float *>(in2->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = (inPtr1[i] >= inPtr2[i]) ? 1.f : 0.f;
}
}
template <>
void GT<float, lang::Cpp>(const size_t num, const Block *in, const float x,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = (inPtr[i] > x) ? 1.f : 0.f;
}
}
template <>
void GT<float, lang::Cpp>(const size_t num, const Block *in1, const Block *in2,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr1 = static_cast<const float *>(in1->data());
const float *inPtr2 = static_cast<const float *>(in2->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = (inPtr1[i] > inPtr2[i]) ? 1.f : 0.f;
}
}
template <>
void LE<float, lang::Cpp>(const size_t num, const Block *in, const float x,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = (inPtr[i] <= x) ? 1.f : 0.f;
}
}
template <>
void LE<float, lang::Cpp>(const size_t num, const Block *in1, const Block *in2,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr1 = static_cast<const float *>(in1->data());
const float *inPtr2 = static_cast<const float *>(in2->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = (inPtr1[i] <= inPtr2[i]) ? 1.f : 0.f;
}
}
template <>
void Log<float, lang::Cpp>(const size_t num, const Block *in, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
CHECK_GT(inPtr[i], 0.f);
outPtr[i] = log(inPtr[i]);
}
}
template <>
void LT<float, lang::Cpp>(const size_t num, const Block *in, const float x,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = (inPtr[i] < x) ? 1.f : 0.f;
}
}
template <>
void LT<float, lang::Cpp>(const size_t num, const Block *in1, const Block *in2,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr1 = static_cast<const float *>(in1->data());
const float *inPtr2 = static_cast<const float *>(in2->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = (inPtr1[i] < inPtr2[i]) ? 1.f : 0.f;
}
}
template <>
void Pow<float, lang::Cpp>(const size_t num, const Block *in, const float x,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = pow(inPtr[i], x);
}
}
template <>
void Pow<float, lang::Cpp>(const size_t num, const Block *in1, const Block *in2,
Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *in1Ptr = static_cast<const float *>(in1->data());
const float *in2Ptr = static_cast<const float *>(in2->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = pow(in1Ptr[i], in2Ptr[i]);
}
}
template <>
void ReLU<float, lang::Cpp>(const size_t num, const Block *in, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = (inPtr[i] >= 0.f) ? inPtr[i] : 0.f;
}
}
template <>
void Set<float, lang::Cpp>(const size_t num, const float x, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
for (size_t i = 0; i < num; i++) outPtr[i] = x;
}
template <>
void Set<int, lang::Cpp>(const size_t num, const int x, Block *out,
Context *ctx) {
int *outPtr = static_cast<int *>(out->mutable_data());
for (size_t i = 0; i < num; i++) outPtr[i] = x;
}
template <>
void Sigmoid<float, lang::Cpp>(const size_t num, const Block *in, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = 1.f / (1.f + exp(-inPtr[i]));
}
}
template <>
void Sign<float, lang::Cpp>(const size_t num, const Block *in, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = (inPtr[i] > 0) - (inPtr[i] < 0);
}
}
template <>
void Sqrt<float, lang::Cpp>(const size_t num, const Block *in, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
CHECK_GE(inPtr[i], 0.f);
outPtr[i] = sqrt(inPtr[i]);
}
}
/*
template <>
void Square<float, lang::Cpp>(const size_t num, const Block *in, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = inPtr[i] * inPtr[i];
}
}
*/
template <>
void Sub<float, lang::Cpp>(const size_t num, const Block *in1, const Block *in2,
Block *out, Context *ctx) {
// CHECK_EQ(ctx->stream, nullptr);
float *outPtr = static_cast<float *>(out->mutable_data());
const float *in1Ptr = static_cast<const float *>(in1->data());
const float *in2Ptr = static_cast<const float *>(in2->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = in1Ptr[i] - in2Ptr[i];
}
}
// sum all elements of input into out
// TODO(wangwei) optimize using omp
template <>
void Sum<float, lang::Cpp>(const size_t num, const Block *in, float *out,
Context *ctx) {
float s = 0.f;
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
s += inPtr[i];
}
*out = s;
}
template <>
void Tanh<float, lang::Cpp>(const size_t num, const Block *in, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = tanh(inPtr[i]);
}
}
// ===============Random operations==========================================
template <>
void Bernoulli<float, lang::Cpp>(const size_t num, const float p, Block *out,
Context *ctx) {
std::bernoulli_distribution distribution(p);
float *outPtr = static_cast<float *>(out->mutable_data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = distribution(ctx->random_generator) ? 1.0f : 0.0f;
}
}
template <>
void Gaussian<float, lang::Cpp>(const size_t num, const float mean,
const float std, Block *out, Context *ctx) {
std::normal_distribution<float> distribution(mean, std);
float *outPtr = static_cast<float *>(out->mutable_data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = static_cast<float>(distribution(ctx->random_generator));
}
}
template <>
void Uniform<float, lang::Cpp>(const size_t num, const float low,
const float high, Block *out, Context *ctx) {
std::uniform_real_distribution<float> distribution(low, high);
float *outPtr = static_cast<float *>(out->mutable_data());
for (size_t i = 0; i < num; i++) {
outPtr[i] = static_cast<float>(distribution(ctx->random_generator));
}
}
// ====================Blas operations======================================
template <>
void DGMM<float, lang::Cpp>(const bool side_right, const size_t nrow,
const size_t ncol, const Block *M, const Block *v,
Block *out, Context *ctx) {
const float *MPtr = static_cast<const float *>(M->data());
const float *vPtr = static_cast<const float *>(v->data());
float *outPtr = static_cast<float *>(out->mutable_data());
if (side_right) {
for (size_t r = 0; r < nrow; r++) {
size_t offset = r * ncol;
for (size_t c = 0; c < ncol; c++) {
outPtr[offset + c] = MPtr[offset + c] * vPtr[c];
}
}
} else {
for (size_t r = 0; r < nrow; r++) {
size_t offset = r * ncol;
for (size_t c = 0; c < ncol; c++) {
outPtr[offset + c] = MPtr[offset + c] * vPtr[r];
}
}
}
}
#ifdef USE_CBLAS
template <>
void Amax<float, lang::Cpp>(const size_t num, const Block *in, size_t *out,
Context *ctx) {
const float *inPtr = static_cast<const float *>(in->data());
*out = cblas_isamax(num, inPtr, 1);
}
template <>
void Asum<float, lang::Cpp>(const size_t num, const Block *in, float *out,
Context *ctx) {
const float *inPtr = static_cast<const float *>(in->data());
*out = cblas_sasum(num, inPtr, 1);
}
template <>
void Axpy<float, lang::Cpp>(const size_t num, const float alpha,
const Block *in, Block *out, Context *ctx) {
const float *inPtr = static_cast<const float *>(in->data());
float *outPtr = static_cast<float *>(out->mutable_data());
cblas_saxpy(num, alpha, inPtr, 1, outPtr, 1);
}
template <>
void Dot<float, lang::Cpp>(const size_t num, const Block *in1, const Block *in2,
float *out, Context *ctx) {
const float *in1Ptr = static_cast<const float *>(in1->data());
const float *in2Ptr = static_cast<const float *>(in2->data());
*out = cblas_sdot(num, in1Ptr, 1, in2Ptr, 1);
}
template <>
void Scale<float, lang::Cpp>(const size_t num, const float x, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
cblas_sscal(num, x, outPtr, 1);
}
template <>
void Nrm2<float, lang::Cpp>(const size_t num, const Block *in, float *out,
Context *ctx) {
const float *inPtr = static_cast<const float *>(in->data());
*out = cblas_snrm2(num, inPtr, 1);
}
template <>
void GEMV<float, lang::Cpp>(bool trans, const size_t m, const size_t n,
const float alpha, const Block *A, const Block *v,
const float beta, Block *out, Context *ctx) {
const float *APtr = static_cast<const float *>(A->data());
const float *vPtr = static_cast<const float *>(v->data());
float *outPtr = static_cast<float *>(out->mutable_data());
if (!trans) {
cblas_sgemv(CblasRowMajor, CblasNoTrans, m, n, alpha, APtr, n, vPtr, 1,
beta, outPtr, 1);
} else {
cblas_sgemv(CblasRowMajor, CblasTrans, n, m, alpha, APtr, m, vPtr, 1, beta,
outPtr, 1);
}
}
template <>
void GEMM<float, lang::Cpp>(const bool transA, const bool transB,
const size_t nrowA, const size_t ncolB,
const size_t ncolA, const float alpha,
const Block *A, const Block *B, const float beta,
Block *C, Context *ctx) {
auto transa = transA ? CblasTrans : CblasNoTrans;
auto transb = transB ? CblasTrans : CblasNoTrans;
auto lda = transA ? nrowA : ncolA;
auto ldb = transB ? ncolA : ncolB;
auto ldc = ncolB;
const float *APtr = static_cast<const float *>(A->data());
const float *BPtr = static_cast<const float *>(B->data());
float *CPtr = static_cast<float *>(C->mutable_data());
cblas_sgemm(CblasRowMajor, transa, transb, nrowA, ncolB, ncolA, alpha, APtr,
lda, BPtr, ldb, beta, CPtr, ldc);
}
#else
template <>
void Amax<float, lang::Cpp>(const size_t num, const Block *in, size_t *out,
Context *ctx) {
size_t maxPos = 0;
float maxVal = 0;
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
if (i == 0) {
maxVal = inPtr[i];
} else if (inPtr[i] > maxVal) {
maxVal = inPtr[i];
maxPos = i;
}
}
*out = maxPos;
}
template <>
void Amin<float, lang::Cpp>(const size_t num, const Block *in, size_t *out,
Context *ctx) {
size_t minPos = 0;
float minVal = 0;
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
if (i == 0) {
minVal = inPtr[i];
} else if (inPtr[i] > minVal) {
minVal = inPtr[i];
minPos = i;
}
}
*out = minPos;
}
template <>
void Asum<float, lang::Cpp>(const size_t num, const Block *in, float *out,
Context *ctx) {
float sum = 0;
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
sum += fabs(inPtr[i]);
}
}
template <>
void Axpy<float, lang::Cpp>(const size_t num, const float alpha,
const Block *in, Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t i = 0; i < num; i++) {
outPtr[i] += alpha * inPtr[i];
}
}
template <>
void Scale<float, lang::Cpp>(const size_t num, const float x, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
for (size_t i = 0; i < num; i++) {
outPtr[i] *= x;
}
}
template <>
void Dot<float, lang::Cpp>(const size_t num, const Block *in1, const Block *in2,
float *out, Context *ctx) {
float sum = 0;
const float *in1Ptr = static_cast<const float *>(in1->data());
const float *in2Ptr = static_cast<const float *>(in2->data());
for (size_t i = 0; i < num; i++) {
sum += in1Ptr[i] * in2Ptr[i];
}
}
template <>
void GEMV<float, lang::Cpp>(bool trans, const size_t m, const size_t n,
const float alpha, const Block *A, const Block *v,
const float beta, Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *APtr = static_cast<const float *>(A->data());
const float *vPtr = static_cast<const float *>(v->data());
for (size_t r = 0; r < m; r++) {
float sum = 0;
for (size_t c = 0; c < n; c++) {
size_t idx = trans ? c * m + r : r * n + c;
sum += APtr[idx] * vPtr[c];
}
outPtr[r] = alpha * sum + beta * outPtr[r];
}
}
#endif // USE_CBLAS
template <>
void ComputeCrossEntropy<float, lang::Cpp>(bool int_target,
const size_t batchsize,
const size_t dim, const Block *p,
const Block *t, Block *loss,
Context *ctx) {
const float *pPtr = static_cast<const float *>(p->data());
const int *tPtr = static_cast<const int *>(t->data());
float *lossPtr = static_cast<float *>(loss->mutable_data());
if (int_target) {
for (size_t i = 0; i < batchsize; i++) {
int truth_idx = tPtr[i];
CHECK_GE(truth_idx, 0);
float prob_of_truth = pPtr[i * dim + truth_idx];
lossPtr[i] = -std::log((std::max)(prob_of_truth, FLT_MIN));
}
} else {
for (size_t i = 0;i < batchsize; i++) {
float sum = 0.f;
for (size_t j = 0; j < dim; j++) {
sum += tPtr[i * dim + j];
}
float loss = 0.f;
for (size_t j = 0, offset = i * dim; j < dim; j++, offset++) {
loss -= tPtr[offset] / sum * std::log((std::max)(pPtr[offset], FLT_MIN));
}
lossPtr[i] = loss;
}
}
}
template <>
void SoftmaxCrossEntropyBwd<float, lang::Cpp>(bool int_target,
const size_t batchsize,
const size_t dim, const Block *p,
const Block *t, Block *grad,
Context *ctx) {
CHECK_EQ(p, grad) << "Use the same pointer to optimize performance";
// const float* pPtr = static_cast<const float*>(p->data());
const int *tPtr = static_cast<const int *>(t->data());
float *gradPtr = static_cast<float *>(grad->mutable_data());
if (int_target) {
for (size_t i = 0; i < batchsize; i++) {
int truth_idx = static_cast<int>(tPtr[i]);
CHECK_GE(truth_idx, 0);
gradPtr[i * dim + truth_idx] -= 1.0;
}
} else {
for (size_t i = 0; i < batchsize; i++) {
float sum = 0.f;
for (size_t j = 0; j < dim; j++) {
sum += tPtr[i * dim + j];
}
for (size_t j = 0, offset = i * dim; j < dim; j++, offset++) {
gradPtr[offset] -= tPtr[offset] / sum;
}
}
}
}
template <>
void RowMax<float, lang::Cpp>(const size_t nrow, const size_t ncol,
const Block *in, Block *out, Context *ctx) {
const float *inPtr = static_cast<const float *>(in->data());
float *outPtr = static_cast<float *>(out->mutable_data());
for (size_t r = 0; r < nrow; r++) {
int offset = (int)(r * ncol);
float maxval = inPtr[offset];
for (size_t c = 1; c < ncol; c++)
maxval = (std::max)(maxval, inPtr[offset + c]);
outPtr[r] = maxval;
}
}
// =========Matrix operations ================================================
/*
template <>
void AddCol<float, lang::Cpp>(const size_t nrow, const size_t ncol,
const Block *A, const Block *v, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *APtr = static_cast<const float *>(A->data());
const float *vPtr = static_cast<const float *>(v->data());
for (size_t r = 0; r < nrow; r++) {
size_t offset = r * ncol;
for (size_t c = 0; c < ncol; c++) {
outPtr[offset + c] = APtr[offset + c] + vPtr[r];
}
}
}
template <>
void AddRow<float, lang::Cpp>(const size_t nrow, const size_t ncol,
const Block *A, const Block *v, Block *out,
Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *APtr = static_cast<const float *>(A->data());
const float *vPtr = static_cast<const float *>(v->data());
for (size_t r = 0; r < nrow; r++) {
size_t offset = r * ncol;
for (size_t c = 0; c < ncol; c++) {
outPtr[offset + c] = APtr[offset + c] + vPtr[c];
}
}
}
template <>
void Outer<float, lang::Cpp>(const size_t m, const size_t n, const Block *in1,
const Block *in2, Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *in1Ptr = static_cast<const float *>(in1->data());
const float *in2Ptr = static_cast<const float *>(in2->data());
for (size_t r = 0; r < m; r++) {
size_t offset = r * n;
for (size_t c = 0; c < n; c++) {
outPtr[offset + c] = in1Ptr[r] * in2Ptr[c];
}
}
}
template <>
void Softmax<float, lang::Cpp>(const size_t nrow, const size_t ncol,
const Block *in, Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
float *bPtr = new float[ncol];
for (size_t r = 0; r < nrow; r++) {
size_t offset = r * ncol;
float denom = 0.f;
for (size_t c = 0; c < ncol; c++) {
bPtr[c] = exp(inPtr[offset + c]);
denom += bPtr[c];
}
for (size_t c = 0; c < ncol; c++) {
size_t idx = offset + c;
outPtr[idx] = bPtr[c] / denom;
}
}
delete bPtr;
}
template <>
void SumColumns<float, lang::Cpp>(const size_t nrow, const size_t ncol,
const Block *in, Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t c = 0; c < ncol; c++) {
outPtr[c] = 0.f;
}
for (size_t r = 0; r < nrow; r++) {
size_t offset = r * ncol;
for (size_t c = 0; c < ncol; c++) {
outPtr[c] += inPtr[offset + c];
}
}
}
template <>
void SumRows<float, lang::Cpp>(const size_t nrow, const size_t ncol,
const Block *in, Block *out, Context *ctx) {
float *outPtr = static_cast<float *>(out->mutable_data());
const float *inPtr = static_cast<const float *>(in->data());
for (size_t r = 0; r < nrow; r++) {
size_t offset = r * ncol;
outPtr[r] = 0.f;
for (size_t c = 0; c < ncol; c++) {
outPtr[r] += inPtr[offset + c];
}
}
}
*/
} // namespace singa
#endif // SINGA_CORE_TENSOR_TENSOR_MATH_CPP_H_
| {
"alphanum_fraction": 0.5664781297,
"avg_line_length": 35.7894736842,
"ext": "h",
"hexsha": "4f510edbce1785e0dc5b280a3e38ddba6da54484",
"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": "b4ea650efb79584261e88e4ea8dd7b97fef7a758",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "TsinghuaDatabaseGroup/incubator-singa",
"max_forks_repo_path": "src/core/tensor/tensor_math_cpp.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b4ea650efb79584261e88e4ea8dd7b97fef7a758",
"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": "TsinghuaDatabaseGroup/incubator-singa",
"max_issues_repo_path": "src/core/tensor/tensor_math_cpp.h",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e5c438c3410c714df3a9cdf4fd760676e5eeb721",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "pavan87/Machine-learning",
"max_stars_repo_path": "src/core/tensor/tensor_math_cpp.h",
"max_stars_repo_stars_event_max_datetime": "2020-08-04T23:28:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-04T23:28:33.000Z",
"num_tokens": 7639,
"size": 26520
} |
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "allvars.h"
#include "proto.h"
#ifdef OUTPUTLINEOFSIGHT
#ifdef OUTPUTLINEOFSIGHT_SPECTRUM
#define PIXELS 512 /* number of bins along line of sight */
#else
#define PIXELS 1
#endif
#define N_LOS 10 /* number of lines of sight selected */
static double H_a, Wmax;
struct line_of_sight
{
int xaxis, yaxis, zaxis;
double Xpos, Ypos; /* relative position of line-of-sight on face of box */
double BoxSize, Wmax, Time;
/* total gas density */
double Rho[PIXELS];
double Vpec[PIXELS];
double Temp[PIXELS];
double Metallicity[PIXELS];
/* neutral hydrogen */
double RhoHI[PIXELS];
double NHI[PIXELS];
double VpecHI[PIXELS];
double TempHI[PIXELS];
double TauHI[PIXELS];
/* HeII quantities */
double RhoHeII[PIXELS];
double NHeII[PIXELS];
double VpecHeII[PIXELS];
double TempHeII[PIXELS];
double TauHeII[PIXELS];
}
*Los, *LosGlobal;
struct line_of_sight_particles
{
MyFloat Pos[3];
MyFloat Hsml;
MyFloat Vz;
MyFloat Utherm;
MyFloat Mass;
MyFloat Metallicity;
}
*particles;
void lineofsight_output(void)
{
char buf[500];
int n, s, next;
double ti;
next = find_next_lineofsighttime(All.Ti_nextlineofsight);
ti = All.TimeBegin * exp(next * All.Timebase_interval);
if(ThisTask == 0)
{
printf("Line of sight output! ThisTask=%d Time=%g NextTime=%g\n", ThisTask, All.Time, ti);
fflush(stdout);
}
H_a = hubble_function(All.Time);
Wmax = All.Time * H_a * All.BoxSize;
if(ThisTask == 0)
{
sprintf(buf, "%s/los", All.OutputDir);
mkdir(buf, 02755);
}
Los = mymalloc(sizeof(struct line_of_sight));
LosGlobal = mymalloc(sizeof(struct line_of_sight));
for(n = 0, s = 0; n < N_LOS; n++)
{
if(s + 3 >= RNDTABLE)
{
set_random_numbers();
s = 0;
}
Los->zaxis = (int) (3.0 * get_random_number(s++));
switch (Los->zaxis)
{
case 2:
Los->xaxis = 0;
Los->yaxis = 1;
break;
case 0:
Los->xaxis = 1;
Los->yaxis = 2;
break;
case 1:
Los->xaxis = 2;
Los->yaxis = 0;
break;
}
Los->Xpos = All.BoxSize * get_random_number(s++);
Los->Ypos = All.BoxSize * get_random_number(s++);
#ifdef OUTPUTLINEOFSIGHT_SPECTRUM
add_along_lines_of_sight();
sum_over_processors_and_normalize();
absorb_along_lines_of_sight();
output_lines_of_sight(n);
#endif
#ifdef OUTPUTLINEOFSIGHT_PARTICLES
find_particles_and_save_them(n);
#endif
}
myfree(LosGlobal);
myfree(Los);
}
void find_particles_and_save_them(int num)
{
int n, k, count_local, *countlist, counttot, rep;
double a3inv;
MyFloat dx, dy, r2;
char fname[1000];
MPI_Status status;
FILE *fd = 0;
countlist = mymalloc(sizeof(int) * NTask);
particles = mymalloc(sizeof(struct line_of_sight_particles) * N_gas);
a3inv = 1.0 / (All.Time * All.Time * All.Time);
for(n = 0, count_local = 0; n < N_gas; n++)
{
if(P[n].Type == 0)
{
dx = los_periodic(P[n].Pos[Los->xaxis] - Los->Xpos);
dy = los_periodic(P[n].Pos[Los->yaxis] - Los->Ypos);
r2 = dx * dx + dy * dy;
if(r2 < PPP[n].Hsml * PPP[n].Hsml)
{
for(k = 0; k < 3; k++)
particles[count_local].Pos[k] = P[n].Pos[k];
particles[count_local].Hsml = PPP[n].Hsml;
particles[count_local].Vz = P[n].Vel[Los->zaxis];
particles[count_local].Utherm = SphP[n].Entropy / GAMMA_MINUS1 * pow(SphP[n].d.Density *
a3inv, GAMMA_MINUS1);
particles[count_local].Mass = P[n].Mass;
particles[count_local].Metallicity = P[n].Metallicity;
count_local++;
}
}
}
MPI_Gather(&count_local, 1, MPI_INT, countlist, 1, MPI_INT, 0, MPI_COMM_WORLD);
if(ThisTask == 0)
{
sprintf(fname, "%s/los/part_los_z%05.3f_%03d.dat", All.OutputDir, 1 / All.Time - 1, num);
if(!(fd = fopen(fname, "w")))
{
printf("can't open file `%s`\n", fname);
endrun(112);
}
fwrite(&count_local, sizeof(int), 1, fd); /* will be overwritten later */
fwrite(&LosGlobal->xaxis, sizeof(int), 1, fd);
fwrite(&LosGlobal->yaxis, sizeof(int), 1, fd);
fwrite(&LosGlobal->zaxis, sizeof(int), 1, fd);
fwrite(&LosGlobal->Xpos, sizeof(double), 1, fd);
fwrite(&LosGlobal->Ypos, sizeof(double), 1, fd);
fwrite(&LosGlobal->BoxSize, sizeof(double), 1, fd);
fwrite(&LosGlobal->Wmax, sizeof(double), 1, fd);
fwrite(&LosGlobal->Time, sizeof(double), 1, fd);
}
for(rep = 0, counttot = 0; rep < NTask; rep++)
{
if(ThisTask != 0 && rep == ThisTask && count_local > 0)
MPI_Ssend(particles, sizeof(struct line_of_sight_particles) * count_local, MPI_BYTE, 0,
TAG_PDATA, MPI_COMM_WORLD);
if(ThisTask == 0)
{
if(rep > 0 && countlist[rep] > 0)
MPI_Recv(particles, sizeof(struct line_of_sight_particles) * countlist[rep],
MPI_BYTE, rep, TAG_PDATA, MPI_COMM_WORLD, &status);
fwrite(particles, sizeof(struct line_of_sight_particles), countlist[rep], fd);
counttot += countlist[rep];
}
}
if(ThisTask == 0)
{
fclose(fd);
if(!(fd = fopen(fname, "r+")))
{
printf("can't open file `%s'\n", fname);
endrun(113);
}
fseek(fd, 0, SEEK_CUR);
fwrite(&counttot, sizeof(int), 1, fd);
fclose(fd);
}
myfree(particles);
myfree(countlist);
}
void add_along_lines_of_sight(void)
{
int n, bin, i, iz0, iz1, iz;
double dx, dy, dz, r, r2, ne, nh0, nHeII, utherm, temp, meanWeight;
double u, wk, weight, a3inv, h3inv;
double z0, z1, dmax1, dmax2;
for(i = 0; i < PIXELS; i++)
{
Los->Rho[i] = 0;
Los->Vpec[i] = 0;
Los->Temp[i] = 0;
Los->Metallicity[i] = 0;
Los->RhoHI[i] = 0;
Los->NHI[i] = 0;
Los->VpecHI[i] = 0;
Los->TempHI[i] = 0;
Los->TauHI[i] = 0;
Los->RhoHeII[i] = 0;
Los->NHeII[i] = 0;
Los->VpecHeII[i] = 0;
Los->TempHeII[i] = 0;
Los->TauHeII[i] = 0;
}
a3inv = 1.0 / (All.Time * All.Time * All.Time);
for(n = 0; n < N_gas; n++)
{
if(P[n].Type == 0)
{
dx = los_periodic(P[n].Pos[Los->xaxis] - Los->Xpos);
dy = los_periodic(P[n].Pos[Los->yaxis] - Los->Ypos);
r2 = dx * dx + dy * dy;
if(r2 < PPP[n].Hsml * PPP[n].Hsml)
{
z0 = (P[n].Pos[Los->zaxis] - PPP[n].Hsml) / All.BoxSize * PIXELS;
z1 = (P[n].Pos[Los->zaxis] + PPP[n].Hsml) / All.BoxSize * PIXELS;
iz0 = (int) z0;
iz1 = (int) z1;
if(z0 < 0)
iz0 -= 1;
for(iz = iz0; iz <= iz1; iz++)
{
dz = los_periodic((iz + 0.5) / PIXELS * All.BoxSize - P[n].Pos[Los->zaxis]);
r = sqrt(r2 + dz * dz);
if(PPP[n].Hsml > All.BoxSize)
{
printf("Here:%d n=%d %g\n", ThisTask, n, PPP[n].Hsml);
endrun(89);
}
if(r < PPP[n].Hsml)
{
u = r / PPP[n].Hsml;
h3inv = 1.0 / (PPP[n].Hsml * PPP[n].Hsml * PPP[n].Hsml);
if(u < 0.5)
wk = h3inv * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u);
else
wk = h3inv * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u);
bin = iz;
while(bin >= PIXELS)
bin -= PIXELS;
while(bin < 0)
bin += PIXELS;
ne = SphP[n].Ne;
utherm = DMAX(All.MinEgySpec,
SphP[n].Entropy / GAMMA_MINUS1 * pow(SphP[n].d.Density *
a3inv, GAMMA_MINUS1));
AbundanceRatios(utherm, SphP[n].d.Density * a3inv, &ne, &nh0, &nHeII);
meanWeight = 4.0 / (3 * HYDROGEN_MASSFRAC + 1 + 4 * HYDROGEN_MASSFRAC * ne);
temp = meanWeight * PROTONMASS / BOLTZMANN * GAMMA_MINUS1 * utherm
* All.UnitEnergy_in_cgs / All.UnitMass_in_g;
/* do total gas */
weight = P[n].Mass * wk;
Los->Rho[bin] += weight;
Los->Metallicity[bin] += P[n].Metallicity * weight;
Los->Temp[bin] += temp * weight;
Los->Vpec[bin] += P[n].Vel[Los->zaxis] * weight;
/* do neutral hydrogen */
weight = nh0 * HYDROGEN_MASSFRAC * P[n].Mass * wk;
Los->RhoHI[bin] += weight;
Los->TempHI[bin] += temp * weight;
Los->VpecHI[bin] += P[n].Vel[Los->zaxis] * weight;
/* do HeII */
weight = 4 * nHeII * HYDROGEN_MASSFRAC * P[n].Mass * wk;
Los->RhoHeII[bin] += weight;
Los->TempHeII[bin] += temp * weight;
Los->VpecHeII[bin] += P[n].Vel[Los->zaxis] * weight;
}
}
}
}
}
}
void sum_over_processors_and_normalize(void)
{
int bin;
MPI_Reduce(Los->Rho, LosGlobal->Rho, PIXELS, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(Los->Metallicity, LosGlobal->Metallicity, PIXELS, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(Los->Temp, LosGlobal->Temp, PIXELS, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(Los->Vpec, LosGlobal->Vpec, PIXELS, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(Los->RhoHI, LosGlobal->RhoHI, PIXELS, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(Los->TempHI, LosGlobal->TempHI, PIXELS, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(Los->VpecHI, LosGlobal->VpecHI, PIXELS, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(Los->RhoHeII, LosGlobal->RhoHeII, PIXELS, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(Los->TempHeII, LosGlobal->TempHeII, PIXELS, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(Los->VpecHeII, LosGlobal->VpecHeII, PIXELS, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if(ThisTask == 0)
{
/* normalize results by the weights */
for(bin = 0; bin < PIXELS; bin++)
{
/* total gas density */
LosGlobal->Metallicity[bin] /= LosGlobal->Rho[bin];
LosGlobal->Temp[bin] /= LosGlobal->Rho[bin];
LosGlobal->Vpec[bin] /= (All.Time * LosGlobal->Rho[bin]);
/* neutral hydrogen quantities */
LosGlobal->VpecHI[bin] /= LosGlobal->RhoHI[bin];
LosGlobal->TempHI[bin] /= LosGlobal->RhoHI[bin];
LosGlobal->NHI[bin] = LosGlobal->RhoHI[bin] * (All.UnitMass_in_g / PROTONMASS);
/* HeII quantities */
LosGlobal->VpecHeII[bin] /= (All.Time * LosGlobal->RhoHeII[bin]);
LosGlobal->TempHeII[bin] /= LosGlobal->RhoHeII[bin];
LosGlobal->NHeII[bin] = LosGlobal->RhoHeII[bin] * (All.UnitMass_in_g / (4 * PROTONMASS));
}
}
}
void absorb_along_lines_of_sight(void)
{
double dz, dv, b, fac, fac_HeII;
int bin, k;
if(ThisTask == 0)
{
dz = All.BoxSize / PIXELS;
for(bin = 0; bin < PIXELS; bin++)
{
LosGlobal->TauHI[bin] = 0;
LosGlobal->TauHeII[bin] = 0;
for(k = 0; k < PIXELS; k++)
{
dv = (k - bin);
while(dv < -PIXELS / 2)
dv += PIXELS;
while(dv > PIXELS / 2)
dv -= PIXELS;
dv = (dv * Wmax / PIXELS + LosGlobal->VpecHI[k]) * All.UnitVelocity_in_cm_per_s;
b = sqrt(2 * BOLTZMANN * LosGlobal->TempHI[k] / PROTONMASS);
LosGlobal->TauHI[bin] += LosGlobal->NHI[k] * exp(-dv * dv / (b * b)) / b * dz;
/* now HeII */
dv = (k - bin);
while(dv < -PIXELS / 2)
dv += PIXELS;
while(dv > PIXELS / 2)
dv -= PIXELS;
dv = (dv * Wmax / PIXELS + LosGlobal->VpecHeII[k]) * All.UnitVelocity_in_cm_per_s;
b = sqrt(2 * BOLTZMANN * LosGlobal->TempHeII[k] / (4 * PROTONMASS));
LosGlobal->TauHeII[bin] += LosGlobal->NHeII[k] * exp(-dv * dv / (b * b)) / b * dz;
}
}
/* multiply with correct prefactors */
/* to get things into cgs units */
fac = 1 / pow(All.UnitLength_in_cm, 2);
fac *= All.HubbleParam * All.HubbleParam;
fac *= OSCILLATOR_STRENGTH * M_PI * LYMAN_ALPHA * sqrt(3 * THOMPSON / (8 * M_PI)); /* Ly-alpha cross section */
fac *= C / (All.Time * All.Time) / sqrt(M_PI);
/* Note: For HeII, the oscillator strength is equal to that of HI,
and the Lyman-alpha wavelength is 4 times shorter */
fac_HeII = fac * (OSCILLATOR_STRENGTH_HeII / OSCILLATOR_STRENGTH) * (LYMAN_ALPHA_HeII / LYMAN_ALPHA);
for(bin = 0; bin < PIXELS; bin++)
{
LosGlobal->TauHI[bin] *= fac;
LosGlobal->TauHeII[bin] *= fac_HeII;
}
LosGlobal->BoxSize = All.BoxSize;
LosGlobal->Wmax = Wmax;
LosGlobal->Time = All.Time;
}
}
void output_lines_of_sight(int num)
{
FILE *fd;
int dummy;
char fname[400];
sprintf(fname, "%s/los/spec_los_z%05.3f_%03d.dat", All.OutputDir, 1 / All.Time - 1, num);
if(!(fd = fopen(fname, "w")))
{
printf("can't open file `%s`\n", fname);
exit(1);
}
dummy = PIXELS;
fwrite(&dummy, sizeof(int), 1, fd);
fwrite(&LosGlobal->BoxSize, sizeof(double), 1, fd);
fwrite(&LosGlobal->Wmax, sizeof(double), 1, fd);
fwrite(&LosGlobal->Time, sizeof(double), 1, fd);
fwrite(&LosGlobal->Xpos, sizeof(double), 1, fd);
fwrite(&LosGlobal->Ypos, sizeof(double), 1, fd);
fwrite(&LosGlobal->xaxis, sizeof(int), 1, fd);
fwrite(&LosGlobal->yaxis, sizeof(int), 1, fd);
fwrite(&LosGlobal->zaxis, sizeof(int), 1, fd);
fwrite(LosGlobal->TauHI, sizeof(double), PIXELS, fd);
fwrite(LosGlobal->TempHI, sizeof(double), PIXELS, fd);
fwrite(LosGlobal->VpecHI, sizeof(double), PIXELS, fd);
fwrite(LosGlobal->NHI, sizeof(double), PIXELS, fd);
fwrite(LosGlobal->TauHeII, sizeof(double), PIXELS, fd);
fwrite(LosGlobal->TempHeII, sizeof(double), PIXELS, fd);
fwrite(LosGlobal->VpecHeII, sizeof(double), PIXELS, fd);
fwrite(LosGlobal->NHeII, sizeof(double), PIXELS, fd);
fwrite(LosGlobal->Rho, sizeof(double), PIXELS, fd);
fwrite(LosGlobal->Vpec, sizeof(double), PIXELS, fd);
fwrite(LosGlobal->Temp, sizeof(double), PIXELS, fd);
fwrite(LosGlobal->Metallicity, sizeof(double), PIXELS, fd);
fclose(fd);
}
int find_next_lineofsighttime(int time0)
{
double a1, a2, df1, df2, u1, u2;
double logTimeBegin, logTimeMax;
int i1, i2, im, time1;
logTimeBegin = log(All.TimeBegin);
logTimeMax = log(All.TimeMax);
a1 = logTimeBegin + time0 * All.Timebase_interval;
u1 = (a1 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;
i1 = (int) u1;
if(i1 >= DRIFT_TABLE_LENGTH)
i1 = DRIFT_TABLE_LENGTH - 1;
if(i1 <= 1)
df1 = u1 * GravKickTable[0];
else
df1 = GravKickTable[i1 - 1] + (GravKickTable[i1] - GravKickTable[i1 - 1]) * (u1 - i1);
df2 = df1 + All.BoxSize / (C / All.UnitVelocity_in_cm_per_s);
i2 = DRIFT_TABLE_LENGTH - 1;
while(i2 - i1 > 0)
{
im = (i1 - 1 + i2) / 2;
if(GravKickTable[im] > df2)
i2 = im;
else
i1 = im + 1;
}
u2 = (df2 - GravKickTable[i2 - 1]) / (GravKickTable[i2] - GravKickTable[i2 - 1]) + i2;
a2 = u2 * (logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH + logTimeBegin;
time1 = (int) ((a2 - logTimeBegin) / All.Timebase_interval + 0.5);
return time1;
}
double los_periodic(double x)
{
if(x >= 0.5 * All.BoxSize)
x -= All.BoxSize;
if(x < -0.5 * All.BoxSize)
x += All.BoxSize;
return x;
}
#endif
| {
"alphanum_fraction": 0.6036655212,
"avg_line_length": 25.5879310345,
"ext": "c",
"hexsha": "81ff394ca7821f190f4a450df42dec6f41391bde",
"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": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "egpbos/egp",
"max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/lineofsight.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"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": "egpbos/egp",
"max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/lineofsight.c",
"max_line_length": 117,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "egpbos/egp",
"max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/lineofsight.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5129,
"size": 14841
} |
/* fracbm-fpt-mc (2019)
* Authors: Benjamin Walter, Kay Wiese
* Header File */
// LIBRARIES
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include <unistd.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf.h>
#include <fftw3.h>
#include <lapacke.h>
#include <cblas.h>
// MACROS
#define IJ2K(a,b) (a+b*(b+1)/2) // Converts matrix indices
#define ARRAY_REALLOC_FACTOR 2.0 // Factor for realloc
#define MIN(a,b) ( (a < b) ? (a) : (b))
#define MAX(a,b) ( (a > b) ? (a) : (b))
#define ABS(a) ((a > 0) ? (a): (-a) )
#define ALLOC(p,n) (p)=malloc( (n) * sizeof(*(p))); if( (p) == NULL){printf("Allocation of '%s' failed. Terminate. \n", #p); exit(2); }
#define FFT_ALLOC(p,n) (p)=fftw_malloc( (n) * sizeof(*(p))); if( (p) == NULL){printf("Allocation of '%s' failed. Terminate. \n", #p); exit(2); }
#define REALLOC(p,n) (p)=realloc( (p) , (n) * sizeof(*(p))); if( (p) == NULL){printf("Allocation of '%s' failed. Terminate. \n", #p); exit(2); }
// STRUCT
// Complex numbers
typedef struct complex_z
{
double r;
double i;
} complex_z;
typedef struct bridge_process // This is the bridge process spanned by two midpoints. In its center, a midpoint will be generated
{
double right_time; // Time of right endpoint
double right_value; // Height of right endpoint
double left_time; // Time of left endpoint
double left_value; // Height of left endpoint
int generation; // Generation
double threshold; // They know where the upper threshold is
double critical_strip; // And the critical strip;
int centre_critical; // 1 - Center is in critical strip -> Sub-divide; 0 - Off the critical strip -> Stop
int crossing_threshold; // 1 - The connection of both endpoints crosses the threshold
struct bridge_process * left_sub_bridge;
struct bridge_process * right_sub_bridge;
struct bridge_process * parental_bridge;
struct bridge_process * root_bridge;
struct bridge_process * previous_root;
struct bridge_process ** pointer_stack; // Only root node has this. List of all bridges attached to the root. Free every pointer in this list.
int stack_top;
} bridge_process;
typedef struct triag_matrix
{
/* This struct stores a sequence of points X_1, X_2, ... and their inverse correlation matrix. It can be dynamically managed as points are added. Convention for triagonal matrix: column major form and 'upper' triagonal form.*/
long size; // This is the size of the matrix itself, that is 0, 1, ..., size - 1 are array indices for both vectors 'trajectory_x' and 'trajectory_t', and 0, 1, ..., size*(size+1)/2 - 1 are indices for upper triagonal matrix. Note that size=N, meanwhile fracbm has N+1 entries. So size is the number of 'free' points, the first one being fixed.
long array_length; // This is the length of the array. If size gets to large, realloc. If size == array_length, this array is full.
double * inv_corr_matrix; // ( size * ( size + 1) / 2) entries in symmetric inverse correlation matrix of all points already known
double * trajectory_x; // All points of the trajectory already known. Length = size + 1 (X_0 = 0 doesn't count, and is neglected in inverse correlation matrix (null mode)).
double * trajectory_t; // And the corresponding time points. Length = size + 1
double hurst_parameter;
} triag_matrix;
// FUNCTIONS
void initialise( fftw_complex** , fftw_complex** , fftw_complex** , fftw_complex** , double** , complex_z** , long N, gsl_rng**, const gsl_rng_type**, int);
void initialise_trajectory ( double**, long);
void initialise_inverse_correlation_matrix(double***, long );
double erfcinv(double);
void write_correlation_exponents(double*, long, double, double);
void write_correlation(fftw_complex*, double*, long);
void write_inverse_correlation_matrix(double **, long, double);
void generate_random_vector(complex_z*, fftw_complex*, fftw_complex*,long, double);
void set_to_zero(double*, long);
void integrate_noise(double*, fftw_complex*, double, double, long, double, int*, double);
void find_fpt(double*, double*, double, long, double, double**, double, int);
void fpt_to_zvar(double, double, double);
void initialise_critical_bridge(bridge_process**, double, double, double, double, double, double, bridge_process*);
void split_and_search_bridge(bridge_process*, int*, double*, double);
bridge_process* check_this_bridge(bridge_process*, double*, double);
bridge_process* split_bridge(bridge_process*);
double generate_random_conditional_midpoint(double, double, double, double);
double crossing_time_of_bridge(bridge_process*);
double time_time_correlation(double, double, double);
void enlarge_QI(void);
void print_QI(void);
void print_bridge(bridge_process*);
void copy_QI(double**, int, double, double*, double );
void free_tree(bridge_process**);
void free_bridge(bridge_process**);
// GLOBAL VARIABLES
extern int max_generation;
extern double *gamma_N_vec;
extern double *g_vec;
extern double lin_drift, frac_drift; // Additional linear and fractional drift constants: Z_t = X_t + lin_drift * t + frac_drift * t^(2*hurst). FPT is searched for Z_t.
extern double *xfracbm; // The fBM trajectory with *no* drift is 'xfracbm'. The process with drift is labelled 'fracbm'.
// GSL RNG
extern const gsl_rng_type *T;
extern gsl_rng *r;
extern int seed;
extern triag_matrix *QI; //malloc somewhere
| {
"alphanum_fraction": 0.7325341824,
"avg_line_length": 48.9816513761,
"ext": "h",
"hexsha": "4713fbfeb7ef8c29f019251e0253fc2a49990e55",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-03-05T00:52:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-05T00:52:18.000Z",
"max_forks_repo_head_hexsha": "0097a81e415abf28eeca0fd5c7c2165a6ae8cba5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "benjamin-w/fracbm-fpt-mc",
"max_forks_repo_path": "fbm_header.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0097a81e415abf28eeca0fd5c7c2165a6ae8cba5",
"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": "benjamin-w/fracbm-fpt-mc",
"max_issues_repo_path": "fbm_header.h",
"max_line_length": 345,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "0097a81e415abf28eeca0fd5c7c2165a6ae8cba5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "benjamin-w/fracbm-fpt-mc",
"max_stars_repo_path": "fbm_header.h",
"max_stars_repo_stars_event_max_datetime": "2021-03-05T00:52:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-22T08:46:24.000Z",
"num_tokens": 1387,
"size": 5339
} |
/*
* SpanDSP - a series of DSP components for telephony
*
* makecss.c - Create the composite source signal (CSS) for G.168 testing.
*
* Written by Steve Underwood <steveu@coppice.org>
*
* Copyright (C) 2003 Steve Underwood
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2, as
* published by the Free Software Foundation.
*
* 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.
*/
/*! \page makecss_page CSS construction for G.168 testing
\section makecss_page_sec_1 What does it do?
???.
\section makecss_page_sec_2 How does it work?
???.
*/
#if defined(HAVE_CONFIG_H)
#include "config.h"
#endif
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
#include <fcntl.h>
#include <sndfile.h>
#if defined(HAVE_FFTW3_H)
#include <fftw3.h>
#else
#include <fftw.h>
#endif
#include "spandsp.h"
#include "spandsp/g168models.h"
#if !defined(NULL)
#define NULL (void *) 0
#endif
#define FAST_SAMPLE_RATE 44100.0
#define C1_VOICED_SAMPLES 2144 /* 48.62ms at 44100 samples/second => 2144.142 */
#define C1_NOISE_SAMPLES 8820 /* 200ms at 44100 samples/second => 8820.0 */
#define C1_SILENCE_SAMPLES 4471 /* 101.38ms at 44100 samples/second => 4470.858 */
#define C3_VOICED_SAMPLES 3206 /* 72.69ms at 44100 samples/second => 3205.629 */
#define C3_NOISE_SAMPLES 8820 /* 200ms at 44100 samples/second => 8820.0 */
#define C3_SILENCE_SAMPLES 5614 /* 127.31ms at 44100 samples/second => 5614.371 */
static double scaling(double f, double start, double end, double start_gain, double end_gain)
{
double scale;
scale = start_gain + (f - start)*(end_gain - start_gain)/(end - start);
return scale;
}
/*- End of function --------------------------------------------------------*/
static double peak(const int16_t amp[], int len)
{
int16_t peak;
int i;
peak = 0;
for (i = 0; i < len; i++)
{
if (abs(amp[i]) > peak)
peak = abs(amp[i]);
}
return peak/32767.0;
}
/*- End of function --------------------------------------------------------*/
static double rms(const int16_t amp[], int len)
{
double ms;
int i;
ms = 0.0;
for (i = 0; i < len; i++)
ms += amp[i]*amp[i];
return sqrt(ms/len)/32767.0;
}
/*- End of function --------------------------------------------------------*/
static double rms_to_dbm0(double rms)
{
return 20.0*log10(rms) + DBM0_MAX_POWER;
}
/*- End of function --------------------------------------------------------*/
static double rms_to_db(double rms)
{
return 20.0*log10(rms);
}
/*- End of function --------------------------------------------------------*/
int main(int argc, char *argv[])
{
#if defined(HAVE_FFTW3_H)
double in[8192][2];
double out[8192][2];
#else
fftw_complex in[8192];
fftw_complex out[8192];
#endif
fftw_plan p;
int16_t voiced_sound[8192];
int16_t noise_sound[8830];
int16_t silence_sound[8192];
int i;
int voiced_length;
int randy;
double f;
double pk;
double ms;
double scale;
SNDFILE *filehandle;
SF_INFO info;
awgn_state_t *noise_source;
memset(&info, 0, sizeof(info));
info.frames = 0;
info.samplerate = FAST_SAMPLE_RATE;
info.channels = 1;
info.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
info.sections = 1;
info.seekable = 1;
if ((filehandle = sf_open("sound_c1.wav", SFM_WRITE, &info)) == NULL)
{
fprintf(stderr, " Failed to open result file\n");
exit(2);
}
printf("Generate C1\n");
/* The sequence is
48.62ms of voiced sound from table C.1 of G.168
200.0ms of pseudo-noise
101.38ms of silence
The above is then repeated phase inverted.
The voice comes straight from C.1, repeated enough times to
fill out the 48.62ms period - i.e. 16 copies of the sequence.
The pseudo noise section is random numbers filtered by the spectral
pattern in Figure C.2 */
/* The set of C1 voice samples is ready for use in the output file. */
voiced_length = sizeof(css_c1)/sizeof(css_c1[0]);
for (i = 0; i < voiced_length; i++)
voiced_sound[i] = css_c1[i];
pk = peak(voiced_sound, voiced_length);
ms = rms(voiced_sound, voiced_length);
printf("Voiced level = %.2fdB, crest factor = %.2fdB\n", rms_to_dbm0(ms), rms_to_db(pk/ms));
#if defined(HAVE_FFTW3_H)
p = fftw_plan_dft_1d(8192, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);
#else
p = fftw_create_plan(8192, FFTW_BACKWARD, FFTW_ESTIMATE);
#endif
for (i = 0; i < 8192; i++)
{
#if defined(HAVE_FFTW3_H)
in[i][0] = 0.0;
in[i][1] = 0.0;
#else
in[i].re = 0.0;
in[i].im = 0.0;
#endif
}
for (i = 1; i <= 3715; i++)
{
f = FAST_SAMPLE_RATE*i/8192.0;
#if 1
if (f < 50.0)
scale = -60.0;
else if (f < 100.0)
scale = scaling(f, 50.0, 100.0, -25.8, -12.8);
else if (f < 200.0)
scale = scaling(f, 100.0, 200.0, -12.8, 17.4);
else if (f < 215.0)
scale = scaling(f, 200.0, 215.0, 17.4, 17.8);
else if (f < 500.0)
scale = scaling(f, 215.0, 500.0, 17.8, 12.2);
else if (f < 1000.0)
scale = scaling(f, 500.0, 1000.0, 12.2, 7.2);
else if (f < 2850.0)
scale = scaling(f, 1000.0, 2850.0, 7.2, 0.0);
else if (f < 3600.0)
scale = scaling(f, 2850.0, 3600.0, 0.0, -2.0);
else if (f < 3660.0)
scale = scaling(f, 3600.0, 3660.0, -2.0, -20.0);
else if (f < 3680.0)
scale = scaling(f, 3600.0, 3680.0, -20.0, -30.0);
else
scale = -60.0;
#else
scale = 0.0;
#endif
randy = ((rand() >> 10) & 0x1) ? 1.0 : -1.0;
#if defined(HAVE_FFTW3_H)
in[i][0] = randy*pow(10.0, scale/20.0)*35.0;
in[8192 - i][0] = -in[i][0];
#else
in[i].re = randy*pow(10.0, scale/20.0)*35.0;
in[8192 - i].re = -in[i].re;
#endif
}
#if defined(HAVE_FFTW3_H)
fftw_execute(p);
#else
fftw_one(p, in, out);
#endif
for (i = 0; i < 8192; i++)
{
#if defined(HAVE_FFTW3_H)
noise_sound[i] = out[i][1];
#else
noise_sound[i] = out[i].im;
#endif
}
pk = peak(noise_sound, 8192);
ms = rms(noise_sound, 8192);
printf("Filtered noise level = %.2fdB, crest factor = %.2fdB\n", rms_to_dbm0(ms), rms_to_db(pk/ms));
for (i = 0; i < 8192; i++)
silence_sound[i] = 0.0;
for (i = 0; i < 16; i++)
sf_writef_short(filehandle, voiced_sound, voiced_length);
printf("%d samples of voice\n", 16*voiced_length);
sf_writef_short(filehandle, noise_sound, 8192);
sf_writef_short(filehandle, noise_sound, C1_NOISE_SAMPLES - 8192);
printf("%d samples of noise\n", C1_NOISE_SAMPLES);
sf_writef_short(filehandle, silence_sound, C1_SILENCE_SAMPLES);
printf("%d samples of silence\n", C1_SILENCE_SAMPLES);
/* Now phase invert the C1 set of samples. */
voiced_length = sizeof(css_c1)/sizeof(css_c1[0]);
for (i = 0; i < voiced_length; i++)
voiced_sound[i] = -css_c1[i];
for (i = 0; i < 8192; i++)
noise_sound[i] = -noise_sound[i];
for (i = 0; i < 16; i++)
sf_writef_short(filehandle, voiced_sound, voiced_length);
printf("%d samples of voice\n", 16*voiced_length);
sf_writef_short(filehandle, noise_sound, 8192);
sf_writef_short(filehandle, noise_sound, C1_NOISE_SAMPLES - 8192);
printf("%d samples of noise\n", C1_NOISE_SAMPLES);
sf_writef_short(filehandle, silence_sound, C1_SILENCE_SAMPLES);
printf("%d samples of silence\n", C1_SILENCE_SAMPLES);
if (sf_close(filehandle))
{
fprintf(stderr, " Cannot close speech file '%s'\n", "sound_c1.wav");
exit(2);
}
memset(&info, 0, sizeof(info));
info.frames = 0;
info.samplerate = FAST_SAMPLE_RATE;
info.channels = 1;
info.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
info.sections = 1;
info.seekable = 1;
if ((filehandle = sf_open("sound_c3.wav", SFM_WRITE, &info)) == NULL)
{
fprintf(stderr, " Failed to open result file\n");
exit(2);
}
printf("Generate C3\n");
/* The sequence is
72.69ms of voiced sound from table C.3 of G.168
200.0ms of pseudo-noise
127.31ms of silence
The above is then repeated phase inverted.
The voice comes straight from C.3, repeated enough times to
fill out the 72.69ms period - i.e. 14 copies of the sequence.
The pseudo noise section is AWGN filtered by the spectral
pattern in Figure C.2. Since AWGN has the quality of being its
own Fourier transform, we can use an approach like the one above
for the C1 signal, using AWGN samples instead of randomly alternating
ones and zeros. */
/* Take the supplied set of C3 voice samples. */
voiced_length = (sizeof(css_c3)/sizeof(css_c3[0]));
for (i = 0; i < voiced_length; i++)
voiced_sound[i] = css_c3[i];
pk = peak(voiced_sound, voiced_length);
ms = rms(voiced_sound, voiced_length);
printf("Voiced level = %.2fdB, crest factor = %.2fdB\n", rms_to_dbm0(ms), rms_to_db(pk/ms));
noise_source = awgn_init_dbm0(NULL, 7162534, rms_to_dbm0(ms));
for (i = 0; i < 8192; i++)
noise_sound[i] = awgn(noise_source);
pk = peak(noise_sound, 8192);
ms = rms(noise_sound, 8192);
printf("Unfiltered noise level = %.2fdB, crest factor = %.2fdB\n", rms_to_dbm0(ms), rms_to_db(pk/ms));
/* Now filter them */
#if defined(HAVE_FFTW3_H)
p = fftw_plan_dft_1d(8192, in, out, FFTW_BACKWARD, FFTW_ESTIMATE);
#else
p = fftw_create_plan(8192, FFTW_BACKWARD, FFTW_ESTIMATE);
#endif
for (i = 0; i < 8192; i++)
{
#if defined(HAVE_FFTW3_H)
in[i][0] = 0.0;
in[i][1] = 0.0;
#else
in[i].re = 0.0;
in[i].im = 0.0;
#endif
}
for (i = 1; i <= 3715; i++)
{
f = FAST_SAMPLE_RATE*i/8192.0;
#if 1
if (f < 50.0)
scale = -60.0;
else if (f < 100.0)
scale = scaling(f, 50.0, 100.0, -25.8, -12.8);
else if (f < 200.0)
scale = scaling(f, 100.0, 200.0, -12.8, 17.4);
else if (f < 215.0)
scale = scaling(f, 200.0, 215.0, 17.4, 17.8);
else if (f < 500.0)
scale = scaling(f, 215.0, 500.0, 17.8, 12.2);
else if (f < 1000.0)
scale = scaling(f, 500.0, 1000.0, 12.2, 7.2);
else if (f < 2850.0)
scale = scaling(f, 1000.0, 2850.0, 7.2, 0.0);
else if (f < 3600.0)
scale = scaling(f, 2850.0, 3600.0, 0.0, -2.0);
else if (f < 3660.0)
scale = scaling(f, 3600.0, 3660.0, -2.0, -20.0);
else if (f < 3680.0)
scale = scaling(f, 3600.0, 3680.0, -20.0, -30.0);
else
scale = -60.0;
#else
scale = 0.0;
#endif
#if defined(HAVE_FFTW3_H)
in[i][0] = noise_sound[i]*pow(10.0, scale/20.0)*0.0106;
in[8192 - i][0] = -in[i][0];
#else
in[i].re = noise_sound[i]*pow(10.0, scale/20.0)*0.0106;
in[8192 - i].re = -in[i].re;
#endif
}
#if defined(HAVE_FFTW3_H)
fftw_execute(p);
#else
fftw_one(p, in, out);
#endif
for (i = 0; i < 8192; i++)
{
#if defined(HAVE_FFTW3_H)
noise_sound[i] = out[i][1];
#else
noise_sound[i] = out[i].im;
#endif
}
pk = peak(noise_sound, 8192);
ms = rms(noise_sound, 8192);
printf("Filtered noise level = %.2fdB, crest factor = %.2fdB\n", rms_to_dbm0(ms), rms_to_db(pk/ms));
for (i = 0; i < 14; i++)
sf_writef_short(filehandle, voiced_sound, voiced_length);
printf("%d samples of voice\n", 14*voiced_length);
sf_writef_short(filehandle, noise_sound, 8192);
sf_writef_short(filehandle, noise_sound, C3_NOISE_SAMPLES - 8192);
printf("%d samples of noise\n", C3_NOISE_SAMPLES);
sf_writef_short(filehandle, silence_sound, C3_SILENCE_SAMPLES);
printf("%d samples of silence\n", C3_SILENCE_SAMPLES);
/* Now phase invert the C3 set of samples. */
voiced_length = (sizeof(css_c3)/sizeof(css_c3[0]));
for (i = 0; i < voiced_length; i++)
voiced_sound[i] = -css_c3[i];
for (i = 0; i < 8192; i++)
noise_sound[i] = -noise_sound[i];
for (i = 0; i < 14; i++)
sf_writef_short(filehandle, voiced_sound, voiced_length);
printf("%d samples of voice\n", 14*voiced_length);
sf_writef_short(filehandle, noise_sound, 8192);
sf_writef_short(filehandle, noise_sound, C3_NOISE_SAMPLES - 8192);
printf("%d samples of noise\n", C3_NOISE_SAMPLES);
sf_writef_short(filehandle, silence_sound, C3_SILENCE_SAMPLES);
printf("%d samples of silence\n", C3_SILENCE_SAMPLES);
if (sf_close(filehandle))
{
fprintf(stderr, " Cannot close speech file '%s'\n", "sound_c3.wav");
exit(2);
}
fftw_destroy_plan(p);
return 0;
}
/*- End of function --------------------------------------------------------*/
/*- End of file ------------------------------------------------------------*/
| {
"alphanum_fraction": 0.5845183991,
"avg_line_length": 31.7255813953,
"ext": "c",
"hexsha": "0cb065783d3b39dbe3a2ac7979391c6daf016f8e",
"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": "c2bba464eaddc9ec70604a8614d84c5334461e8e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zengfanmao/mpds",
"max_forks_repo_path": "VideoServer/libs/spandsp/tests/make_g168_css.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c2bba464eaddc9ec70604a8614d84c5334461e8e",
"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": "zengfanmao/mpds",
"max_issues_repo_path": "VideoServer/libs/spandsp/tests/make_g168_css.c",
"max_line_length": 106,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c2bba464eaddc9ec70604a8614d84c5334461e8e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zengfanmao/mpds",
"max_stars_repo_path": "VideoServer/libs/spandsp/tests/make_g168_css.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4373,
"size": 13642
} |
#pragma once
#include "IntervalGrad.h"
#ifndef _NOGSL
#include <gsl/gsl_vector.h>
#else
#include "CustomSolver.h"
#endif
#include "BooleanNodes.h"
#include "BooleanDAG.h"
#include "NodeVisitor.h"
#include "VarStore.h"
#include <map>
#include "FloatSupport.h"
#include <iostream>
using namespace std;
#define FINE_GRAIN_RANGES 1
class RangeDiff: NodeVisitor
{
FloatManager& floats;
BooleanDAG& bdag;
map<string, int> floatCtrls; // Maps float ctrl names to indices with grad vectors
int nctrls; // number of float ctrls
gsl_vector* ctrls; // ctrl values
vector<IntervalGrad*> ranges; // Keeps track of ranges for each node
vector<DistanceGrad*> distances; // Keeps track of distance metric for boolean nodes
map<int, int> inputValues; // Maps node id to values set by the SAT solver
double error = 0.0;
gsl_vector* errorGrad;
int DEFAULT_INP = -1;
int assertCtr;
bool foundFailure;
static constexpr float ASSERT_PENALTY = 1.0;
public:
int failedAssert;
RangeDiff(BooleanDAG& bdag_p, FloatManager& _floats, const map<string, int>& floatCtrls_p);
~RangeDiff(void);
virtual void visit( SRC_node& node );
virtual void visit( DST_node& node );
virtual void visit( CTRL_node& node );
virtual void visit( PLUS_node& node );
virtual void visit( TIMES_node& node );
virtual void visit( ARRACC_node& node );
virtual void visit( DIV_node& node );
virtual void visit( MOD_node& node );
virtual void visit( NEG_node& node );
virtual void visit( CONST_node& node );
virtual void visit( LT_node& node );
virtual void visit( EQ_node& node );
virtual void visit( AND_node& node );
virtual void visit( OR_node& node );
virtual void visit( NOT_node& node );
virtual void visit( ARRASS_node& node );
virtual void visit( UFUN_node& node );
virtual void visit( TUPLE_R_node& node );
virtual void visit( ASSERT_node& node );
double run(const gsl_vector* ctrls_p, map<int, int>& inputValues_p, gsl_vector* errorGrad_p);
void setrange(bool_node& bn, IntervalGrad* r) {
ranges[bn.id] = r;
}
IntervalGrad* r(bool_node& bn) {
IntervalGrad* interval = ranges[bn.id];
if (interval == NULL) {
gsl_vector* l = gsl_vector_alloc(nctrls);
gsl_vector* h = gsl_vector_alloc(nctrls);
interval = new IntervalGrad(0, 0, l, h);
setrange(bn, interval);
}
return interval;
}
IntervalGrad* r(bool_node* bn) {
return r(*bn);
}
void setdistance(bool_node& bn, DistanceGrad* d) {
distances[bn.id] = d;
}
DistanceGrad* d(bool_node& bn) {
DistanceGrad* dist = distances[bn.id];
if (dist == NULL) {
gsl_vector* g = gsl_vector_alloc(nctrls);
dist = new DistanceGrad(0, g);
setdistance(bn, dist);
}
return dist;
}
DistanceGrad* d(bool_node* bn) {
return d(*bn);
}
void print() {
for (int i = 0; i < bdag.size(); i++) {
cout << bdag[i]->lprint() << " ";
if (bdag[i]->getOtype() == OutType::FLOAT) {
cout << r(bdag[i])->print() << endl;
} else {
cout << d(bdag[i])->print() << endl;
}
}
}
void printFull() {
for (int i = 0; i < bdag.size(); i++) {
cout << bdag[i]->lprint() << endl;
if (bdag[i]->getOtype() == OutType::FLOAT) {
cout << r(bdag[i])->printFull() << endl;
} else {
cout << d(bdag[i])->printFull() << endl;
}
}
}
bool isFloat(bool_node& bn) {
return (bn.getOtype() == OutType::FLOAT);
}
bool isFloat(bool_node* bn) {
return (bn->getOtype() == OutType::FLOAT);
}
int getInputValue(bool_node& bn) {
if (inputValues.find(bn.id) != inputValues.end()) {
int val = inputValues[bn.id];
Assert(val == 0 || val == 1, "NYI: Integer values");
return val;
} else {
return DEFAULT_INP;
}
}
int getInputValue(bool_node* bn) {
return getInputValue(*bn);
}
void computeError(double dist, int expected, gsl_vector* dg, bool_node& node, bool relax = false);
};
| {
"alphanum_fraction": 0.6627665107,
"avg_line_length": 25.3026315789,
"ext": "h",
"hexsha": "294485f8d31758bf9b378256786856904aad298e",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-12-06T01:45:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-04T20:47:51.000Z",
"max_forks_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_forks_repo_licenses": [
"X11"
],
"max_forks_repo_name": "natebragg/sketch-backend",
"max_forks_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/RangeDiff.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-04T04:02:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-03-01T16:53:05.000Z",
"max_issues_repo_licenses": [
"X11"
],
"max_issues_repo_name": "natebragg/sketch-backend",
"max_issues_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/RangeDiff.h",
"max_line_length": 99,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "6ecbb6f724149d50d290997fef5e2e1e92ab3d9e",
"max_stars_repo_licenses": [
"X11"
],
"max_stars_repo_name": "natebragg/sketch-backend",
"max_stars_repo_path": "src/SketchSolver/NumericalSynthesis/SymbolicEvaluators/RangeDiff.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T00:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-20T14:54:11.000Z",
"num_tokens": 1137,
"size": 3846
} |
/*
* C version of Diffusive Nested Sampling (DNest4) by Brendon J. Brewer
*
* Yan-Rong Li, liyanrong@mail.ihep.ac.cn
* Jun 30, 2016
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#include <float.h>
#include <mpi.h>
#include <sys/stat.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "dnest.h"
#include "dnestvars.h"
/*
* dnest
* call this function to do sampling
* ========================================================
* arguments:
* argc: number of command-line options (mandatory)
* argv: command-line options (mandatory)
* fptrset: function set pointers required (mandatory)
* num_params: number of parameters (mandatory)
* param_range: parameter ranges (mandatory)
* prior_type: prior types (optional)
* prior_info: prior informations (optional)
* sample_dir: output directory for sampling (mandatory)
* optfile: option files (optional)
* opts: options struct. if optfile is empty, use this struct (optional)
* args: any other arguments transferred to cdnest. (optional)
* useful when referring to external variables or calling external functions (optional)
* ========================================================
* optional arguments can be set to "NULL"
*/
double dnest(int argc, char** argv, DNestFptrSet *fptrset, int num_params,
double *param_range, int *prior_type, double *prior_info,
char *sample_dir, char *optfile, DNestOptions *opts, void *args)
{
int optid;
MPI_Comm_rank(MPI_COMM_WORLD, &dnest_thistask);
MPI_Comm_size(MPI_COMM_WORLD, &dnest_totaltask);
if(dnest_thistask == dnest_root)
{
printf("#=======================================================\n");
printf("# Starting CDNest.\n");
printf("# Use %d cores.\n", dnest_totaltask);
}
dnest_check_fptrset(fptrset);
// cope with argv
if(dnest_thistask == dnest_root )
{
dnest_post_temp = 1.0;
dnest_flag_restart = 0;
dnest_flag_postprc = 0;
dnest_flag_sample_info = 0;
dnest_flag_limits = 0;
strcpy(file_save_restart, "restart_dnest.txt");
strcpy(dnest_sample_postfix, "\0");
strcpy(dnest_sample_tag, "\0");
opterr = 0;
optind = 0;
while( (optid = getopt(argc, argv, "r:s:pt:clx:g:")) != -1)
{
switch(optid)
{
case 'r':
dnest_flag_restart = 1;
strcpy(file_restart, optarg);
printf("# Dnest restarts.\n");
break;
case 's':
strcpy(file_save_restart, optarg);
printf("# Dnest sets restart file %s.\n", file_save_restart);
break;
case 'p':
dnest_flag_postprc = 1;
dnest_post_temp = 1.0;
printf("# Dnest does postprocess.\n");
break;
case 't':
dnest_post_temp = atof(optarg);
printf("# Dnest sets a temperature %f.\n", dnest_post_temp);
if(dnest_post_temp == 0.0)
{
printf("# Dnest incorrect option -t %s.\n", optarg);
exit(0);
}
if(dnest_post_temp < 1.0)
{
printf("# Dnest temperature should >= 1.0\n");
exit(0);
}
break;
case 'c':
dnest_flag_sample_info = 1;
printf("# Dnest recalculates sample information.\n");
break;
case 'l':
dnest_flag_limits = 1;
printf("# Dnest level-dependent sampling.\n");
break;
case 'x':
strcpy(dnest_sample_postfix, optarg);
printf("# Dnest sets sample postfix %s.\n", dnest_sample_postfix);
break;
case 'g':
strcpy(dnest_sample_tag, optarg);
printf("# Dnest sets sample tag %s.\n", dnest_sample_tag);
break;
case '?':
printf("# Dnest incorrect option -%c %s.\n", optopt, optarg);
exit(0);
break;
default:
break;
}
}
}
MPI_Bcast(&dnest_flag_restart, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);
MPI_Bcast(&dnest_flag_postprc, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);
MPI_Bcast(&dnest_flag_sample_info, 1, MPI_INT,dnest_root, MPI_COMM_WORLD);
MPI_Bcast(&dnest_post_temp, 1, MPI_DOUBLE, dnest_root, MPI_COMM_WORLD);
MPI_Bcast(&dnest_flag_limits, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);
setup(argc, argv, fptrset, num_params, param_range, prior_type, prior_info, sample_dir, optfile, opts, args);
if(dnest_flag_postprc == 1)
{
dnest_postprocess(dnest_post_temp, optfile, opts);
MPI_Barrier(MPI_COMM_WORLD);
finalise();
return post_logz;
}
if(dnest_flag_sample_info == 1)
{
dnest_postprocess(dnest_post_temp, optfile, opts);
finalise();
return post_logz;
}
if(dnest_flag_restart==1)
dnest_restart();
initialize_output_file();
dnest_run();
close_output_file();
dnest_postprocess(dnest_post_temp, optfile, opts);
finalise();
return post_logz;
}
// postprocess, calculate evidence, generate posterior sample.
void dnest_postprocess(double temperature,char *optfile, DNestOptions *opts)
{
if(dnest_thistask == dnest_root)
{
options_load(optfile, opts);
postprocess(temperature);
}
MPI_Bcast(&post_logz, 1, MPI_DOUBLE, dnest_root, MPI_COMM_WORLD);
}
void dnest_run()
{
int i, j, k, size_all_above_incr;
Level *pl, *levels_orig;
int *buf_size_above, *buf_displs;
double *plimits;
// used to gather levels' information
if(dnest_thistask == dnest_root)
{
buf_size_above = malloc(dnest_totaltask * sizeof(int));
buf_displs = malloc(dnest_totaltask * sizeof(int));
}
if(dnest_thistask == dnest_root)
{
printf("#=======================================================\n");
printf("# Starting diffusive nested sampling.\n");
}
MPI_Barrier(MPI_COMM_WORLD);
while(true)
{
//check for termination
if(options.max_num_saves !=0 &&
count_saves != 0 && (count_saves%options.max_num_saves == 0))
break;
dnest_mcmc_run();
MPI_Barrier(MPI_COMM_WORLD);
//gather levels
MPI_Gather(levels, size_levels*sizeof(Level), MPI_BYTE,
copies_of_levels, size_levels*sizeof(Level), MPI_BYTE, dnest_root, MPI_COMM_WORLD);
//gather limits
if(dnest_flag_limits == 1)
{
MPI_Gather(limits, size_levels*particle_offset_double*2, MPI_DOUBLE,
copies_of_limits, size_levels*particle_offset_double*2, MPI_DOUBLE, dnest_root, MPI_COMM_WORLD );
}
//gather size_above
MPI_Gather(&size_above, 1, MPI_INT, buf_size_above, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);
// task 0 responsible for updating levels
if(dnest_thistask == dnest_root)
{
size_all_above_incr = 0;
for(i = 0; i<dnest_totaltask; i++)
{
size_all_above_incr += buf_size_above[i];
buf_size_above[i] *= sizeof(LikelihoodType);
}
// store new points following the end of all_above array.
buf_displs[0] = size_all_above * sizeof(LikelihoodType);
for(i=1; i<dnest_totaltask; i++)
{
buf_displs[i] = buf_displs[i-1] + buf_size_above[i-1];
}
//update size_all_above
size_all_above += size_all_above_incr;
if(size_all_above > options.new_level_interval*2)
{
printf("# Error, all above overflow.\n");
exit(0);
}
}
// gather above into all_above, stored in task 0, note that its size is different among tasks
MPI_Gatherv(above, size_above * sizeof(LikelihoodType), MPI_BYTE,
all_above, buf_size_above, buf_displs, MPI_BYTE, dnest_root, MPI_COMM_WORLD);
// reset size_above for each task
size_above = 0;
count_mcmc_steps += options.thread_steps * dnest_totaltask;
if(dnest_thistask == dnest_root)
{
//backup levels_combine
levels_orig = malloc(size_levels_combine * sizeof(Level));
memcpy(levels_orig, levels_combine, size_levels_combine*sizeof(Level));
//scan over all copies of levels
pl = copies_of_levels;
for(i=0; i< dnest_totaltask; i++)
{
for(j=0; j<size_levels_combine; j++)
{
levels_combine[j].accepts += (pl[j].accepts - levels_orig[j].accepts);
levels_combine[j].tries += (pl[j].tries - levels_orig[j].tries);
levels_combine[j].visits += (pl[j].visits - levels_orig[j].visits);
levels_combine[j].exceeds += (pl[j].exceeds - levels_orig[j].exceeds);
//printf("%d %d\n", thistask, (pl[j].accepts - levels_orig[j].accepts) );;
}
pl += size_levels_combine;
}
free(levels_orig);
// scan over all copies of limits
if(dnest_flag_limits == 1)
{
plimits = copies_of_limits;
for(i=0; i< dnest_totaltask; i++)
{
for(j=0; j < size_levels; j++)
{
for(k=0; k<particle_offset_double; k++)
{
limits[j * particle_offset_double *2 + k*2 ] = fmin(limits[j * particle_offset_double *2 + k*2 ],
plimits[j * particle_offset_double *2 + k*2]);
limits[j * particle_offset_double *2 + k*2 +1 ] = fmax(limits[j * particle_offset_double *2 + k*2 +1 ],
plimits[j * particle_offset_double *2 + k*2 + 1]);
}
}
plimits += size_levels * particle_offset_double * 2;
}
// limits of smaller levels should be larger than those of higher levels
for(j=size_levels-2; j >= 0; j--)
for(k=0; k<particle_offset_double; k++)
{
limits[ j * particle_offset_double *2 + k*2 ] = fmin( limits[ j * particle_offset_double *2 + k*2 ],
limits[ (j+1) * particle_offset_double *2 + k*2 ] );
limits[ j * particle_offset_double *2 + k*2 + 1] = fmax( limits[ j * particle_offset_double *2 + k*2 +1 ],
limits[ (j+1) * particle_offset_double *2 + k*2 + 1 ] );
}
}
do_bookkeeping();
size_levels = size_levels_combine;
memcpy(levels, levels_combine, size_levels * sizeof(Level));
}
//broadcast levels
MPI_Bcast(&size_levels, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);
//MPI_Bcast(&count_saves, 1, MPI_INT, root, MPI_COMM_WORLD);
MPI_Bcast(levels, size_levels * sizeof(Level), MPI_BYTE, dnest_root, MPI_COMM_WORLD);
if(dnest_flag_limits == 1)
MPI_Bcast(limits, size_levels * particle_offset_double *2, MPI_DOUBLE, dnest_root, MPI_COMM_WORLD);
if(count_mcmc_steps >= (count_saves + 1)*options.save_interval)
{
save_particle();
if(dnest_thistask == dnest_root )
{
// save levels, limits, sync samples when running a number of steps
if( count_saves % num_saves == 0 )
{
save_levels();
if(dnest_flag_limits == 1)
save_limits();
fflush(fsample_info);
fsync(fileno(fsample_info));
fflush(fsample);
fsync(fileno(fsample));
printf("# Save levels, limits, and sync samples at N= %d.\n", count_saves);
}
}
if( count_saves % num_saves_restart == 0 )
{
dnest_save_restart();
}
}
}
//dnest_save_restart();
if(dnest_thistask == dnest_root)
{
//save levels
save_levels();
if(dnest_flag_limits == 1)
save_limits();
/* output state of sampler */
FILE *fp;
fp = fopen(options.sampler_state_file, "w");
fprintf(fp, "%d %d\n", size_levels, count_saves);
fclose(fp);
free(buf_size_above);
free(buf_displs);
}
}
void do_bookkeeping()
{
int i;
//bool created_level = false;
if(!enough_levels(levels_combine, size_levels_combine) && size_all_above >= options.new_level_interval)
{
// in descending order
qsort(all_above, size_all_above, sizeof(LikelihoodType), dnest_cmp);
int index = (int)( (1.0/compression) * size_all_above);
Level level_tmp = {all_above[index], 0.0, 0, 0, 0, 0};
levels_combine[size_levels_combine] = level_tmp;
size_levels_combine++;
printf("# Creating level %d with log likelihood = %e.\n",
size_levels_combine-1, levels_combine[size_levels_combine-1].log_likelihood.value);
// clear out the last index records
for(i=index; i<size_all_above; i++)
{
all_above[i].value = 0.0;
all_above[i].tiebreaker = 0.0;
}
size_all_above = index;
if(enough_levels(levels_combine, size_levels_combine))
{
renormalise_visits();
options.max_num_levels = size_levels_combine;
printf("# Done creating levles.\n");
}
else
{
kill_lagging_particles();
}
//created_level = true;
}
recalculate_log_X();
/* if(created_level)
save_levels();
if(count_mcmc_steps >= (count_saves + 1)*options.save_interval)
{
//save_particle();
if(!created_level)
save_levels();
}*/
}
void recalculate_log_X()
{
int i;
levels_combine[0].log_X = 0.0;
for(i=1; i<size_levels_combine; i++)
{
levels_combine[i].log_X = levels_combine[i-1].log_X
+ log( (double)( (levels_combine[i-1].exceeds + 1.0/compression * regularisation)
/(levels_combine[i-1].visits + regularisation) ) );
}
}
void renormalise_visits()
{
size_t i;
for(i=0; i<size_levels_combine; i++)
{
if(levels_combine[i].tries >= regularisation)
{
levels_combine[i].accepts = ((double)(levels_combine[i].accepts+1) / (double)(levels_combine[i].tries+1)) * regularisation;
levels_combine[i].tries = regularisation;
}
if(levels_combine[i].visits >= regularisation)
{
levels_combine[i].exceeds = ( (double) (levels_combine[i].exceeds+1) / (double)(levels_combine[i].visits + 1) ) * regularisation;
levels_combine[i].visits = regularisation;
}
}
}
void kill_lagging_particles()
{
static unsigned int deletions = 0;
bool *good;
good = (bool *)malloc(options.num_particles * sizeof(bool));
double max_log_push = -DBL_MAX;
double kill_probability = 0.0;
unsigned int num_bad = 0;
size_t i;
for(i=0; i<options.num_particles; i++)good[i] = true;
for(i=0; i<options.num_particles; i++)
{
if( log_push(level_assignments[i]) > max_log_push)
max_log_push = log_push(level_assignments[i]);
kill_probability = pow(1.0 - 1.0/(1.0 + exp(-log_push(level_assignments[i]) - 4.0)), 3);
if(gsl_rng_uniform(dnest_gsl_r) <= kill_probability)
{
good[i] = false;
++num_bad;
}
}
if(num_bad < options.num_particles)
{
for(i=0; i< options.num_particles; i++)
{
if(!good[i])
{
int i_copy;
do
{
i_copy = gsl_rng_uniform_int(dnest_gsl_r, options.num_particles);
}while(!good[i_copy] || gsl_rng_uniform(dnest_gsl_r) >= exp(log_push(level_assignments[i_copy]) - max_log_push));
memcpy(particles+i*particle_offset_size, particles + i_copy*particle_offset_size, dnest_size_of_modeltype);
log_likelihoods[i] = log_likelihoods[i_copy];
level_assignments[i] = level_assignments[i_copy];
kill_action(i, i_copy);
deletions++;
printf("# Replacing lagging particle.\n");
printf("# This has happened %d times.\n", deletions);
}
}
}
else
printf("# Warning: all particles lagging!.\n");
free(good);
}
/* save levels */
void save_levels()
{
if(!save_to_disk)
return;
int i;
FILE *fp;
fp = fopen(options.levels_file, "w");
fprintf(fp, "# log_X, log_likelihood, tiebreaker, accepts, tries, exceeds, visits\n");
for(i=0; i<size_levels_combine; i++)
{
fprintf(fp, "%14.12g %14.12g %f %llu %llu %llu %llu\n", levels_combine[i].log_X, levels_combine[i].log_likelihood.value,
levels_combine[i].log_likelihood.tiebreaker, levels_combine[i].accepts,
levels_combine[i].tries, levels[i].exceeds, levels_combine[i].visits);
}
fclose(fp);
/* update state of sampler */
fp = fopen(options.sampler_state_file, "w");
fprintf(fp, "%d %d\n", size_levels, count_saves);
fclose(fp);
}
void save_limits()
{
int i, j;
FILE *fp;
fp = fopen(options.limits_file, "w");
for(i=0; i<size_levels_combine; i++)
{
fprintf(fp, "%d ", i);
for(j=0; j<particle_offset_double; j++)
fprintf(fp, "%f %f ", limits[i*2*particle_offset_double+j*2], limits[i*2*particle_offset_double+j*2+1]);
fprintf(fp, "\n");
}
fclose(fp);
}
/* save particle */
void save_particle()
{
count_saves++;
if(!save_to_disk)
return;
int whichparticle, whichtask;
void *particle_message;
if(dnest_thistask == dnest_root)
{
if(count_saves%1 == 0)
printf("#[%.1f%%] Saving particle to disk. N= %d.\n", 100.0*count_saves/options.max_num_saves, count_saves);
whichtask = gsl_rng_uniform_int(dnest_gsl_r,dnest_totaltask);
}
MPI_Bcast(&whichtask, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);
if(whichtask != dnest_root)
{
if(dnest_thistask == whichtask)
{
int size_message = dnest_size_of_modeltype + 2*sizeof(int) + 2*sizeof(double);
particle_message = (void *)malloc(size_message);
whichparticle = gsl_rng_uniform_int(dnest_gsl_r,options.num_particles);
memcpy(particle_message, particles + whichparticle * particle_offset_size, dnest_size_of_modeltype);
memcpy(particle_message + dnest_size_of_modeltype, &log_likelihoods[whichparticle].value, 2*sizeof(double));
memcpy(particle_message + dnest_size_of_modeltype + 2*sizeof(double), &level_assignments[whichparticle], sizeof(int));
memcpy(particle_message + dnest_size_of_modeltype + 2*sizeof(double) + sizeof(int), &whichparticle, sizeof(int));
MPI_Send(particle_message, size_message, MPI_BYTE, dnest_root, 1, MPI_COMM_WORLD);
//printf("%f %f\n", log_likelihoods[whichparticle].value, log_likelihoods[whichparticle].tiebreaker);
free(particle_message);
}
if(dnest_thistask == dnest_root)
{
MPI_Status status;
int size_message = dnest_size_of_modeltype + 2*sizeof(int) + 2*sizeof(double);
int whichlevel;
LikelihoodType logl;
particle_message = (void *)malloc(size_message);
MPI_Recv(particle_message, size_message, MPI_BYTE, whichtask, 1, MPI_COMM_WORLD, &status);
memcpy(&logl, particle_message + dnest_size_of_modeltype, 2*sizeof(double) );
memcpy(&whichlevel, particle_message + dnest_size_of_modeltype + 2*sizeof(double), sizeof(int) );
memcpy(&whichparticle, particle_message + dnest_size_of_modeltype + 2*sizeof(double) + sizeof(int), sizeof(int) );
//printf("%f %f\n", logl.value, logl.tiebreaker);
print_particle(fsample, particle_message);
fprintf(fsample_info, "%d %e %f %d\n", whichlevel,
logl.value,
logl.tiebreaker,
whichtask * options.num_particles + whichparticle);
free(particle_message);
}
}
else
{
if(dnest_thistask == dnest_root)
{
whichparticle = gsl_rng_uniform_int(dnest_gsl_r,options.num_particles);
print_particle(fsample, particles + whichparticle * particle_offset_size);
fprintf(fsample_info, "%d %e %f %d\n", level_assignments[whichparticle],
log_likelihoods[whichparticle].value,
log_likelihoods[whichparticle].tiebreaker,
whichtask * options.num_particles + whichparticle);
}
}
}
void dnest_mcmc_run()
{
unsigned int which;
unsigned int i;
for(i = 0; i<options.thread_steps; i++)
{
/* randomly select out one particle to update */
which = gsl_rng_uniform_int(dnest_gsl_r, options.num_particles);
dnest_which_particle_update = which;
//if(count_mcmc_steps >= 10000)printf("FFFF\n");
//printf("%d\n", which);
//printf("%f %f %f\n", particles[which].param[0], particles[which].param[1], particles[which].param[2]);
//printf("level:%d\n", level_assignments[which]);
//printf("%e\n", log_likelihoods[which].value);
if(gsl_rng_uniform(dnest_gsl_r) <= 0.5)
{
update_particle(which);
update_level_assignment(which);
}
else
{
update_level_assignment(which);
update_particle(which);
}
if( !enough_levels(levels, size_levels) && levels[size_levels-1].log_likelihood.value <= log_likelihoods[which].value)
{
above[size_above] = log_likelihoods[which];
size_above++;
}
}
}
void update_particle(unsigned int which)
{
void *particle = particles+ which*particle_offset_size;
LikelihoodType *logl = &(log_likelihoods[which]);
Level *level = &(levels[level_assignments[which]]);
void *proposal = (void *)malloc(dnest_size_of_modeltype);
LikelihoodType logl_proposal;
double log_H;
memcpy(proposal, particle, dnest_size_of_modeltype);
dnest_which_level_update = level_assignments[which];
log_H = perturb(proposal);
logl_proposal.value = log_likelihoods_cal(proposal);
logl_proposal.tiebreaker = (*logl).tiebreaker + gsl_rng_uniform(dnest_gsl_r);
dnest_wrap(&logl_proposal.tiebreaker, 0.0, 1.0);
if(log_H > 0.0)
log_H = 0.0;
dnest_perturb_accept[which] = 0;
if( gsl_rng_uniform(dnest_gsl_r) <= exp(log_H) && level->log_likelihood.value <= logl_proposal.value)
{
memcpy(particle, proposal, dnest_size_of_modeltype);
memcpy(logl, &logl_proposal, sizeof(LikelihoodType));
level->accepts++;
dnest_perturb_accept[which] = 1;
accept_action();
account_unaccepts[which] = 0; /* reset the number of unaccepted perturb */
}
else
{
account_unaccepts[which] += 1; /* number of unaccepted perturb */
}
level->tries++;
unsigned int current_level = level_assignments[which];
for(; current_level < size_levels-1; ++current_level)
{
levels[current_level].visits++;
if(levels[current_level+1].log_likelihood.value <= log_likelihoods[which].value)
levels[current_level].exceeds++;
else
break; // exit the loop if it does not satify higher levels
}
free(proposal);
}
void update_level_assignment(unsigned int which)
{
int i;
int proposal = level_assignments[which]
+ (int)( pow(10.0, 2*gsl_rng_uniform(dnest_gsl_r))*gsl_ran_ugaussian(dnest_gsl_r));
if(proposal == level_assignments[which])
proposal = ((gsl_rng_uniform(dnest_gsl_r) < 0.5)?(proposal-1):(proposal+1));
proposal=mod_int(proposal, size_levels);
double log_A = -levels[proposal].log_X + levels[level_assignments[which]].log_X;
log_A += log_push(proposal) - log_push(level_assignments[which]);
// enforce uniform exploration if levels are enough
if(enough_levels(levels, size_levels))
log_A += options.beta*log( (double)(levels[level_assignments[which]].tries +1)/ (levels[proposal].tries +1) );
if(log_A > 0.0)
log_A = 0.0;
if( gsl_rng_uniform(dnest_gsl_r) <= exp(log_A) && levels[proposal].log_likelihood.value <= log_likelihoods[which].value)
{
level_assignments[which] = proposal;
// update the limits of the level
if(dnest_flag_limits == 1)
{
double *particle = (double *) (particles+ which*particle_offset_size);
for(i=0; i<particle_offset_double; i++)
{
limits[proposal * 2 * particle_offset_double + i*2] =
fmin(limits[proposal * 2* particle_offset_double + i*2], particle[i]);
limits[proposal * 2 * particle_offset_double + i*2+1] =
fmax(limits[proposal * 2 * particle_offset_double + i*2+1], particle[i]);
}
}
}
}
double log_push(unsigned int which_level)
{
if(which_level > size_levels)
{
printf("level overflow %d %d.\n", which_level, size_levels);
exit(0);
}
if(enough_levels(levels, size_levels))
return 0.0;
int i = which_level - (size_levels - 1);
return ((double)i)/options.lam;
}
bool enough_levels(Level *l, int size_l)
{
int i;
if(options.max_num_levels == 0)
{
if(size_l >= LEVEL_NUM_MAX)
return true;
if(size_l < 10)
return false;
int num_levels_to_check = 20;
if(size_l > 80)
num_levels_to_check = (int)(sqrt(20) * sqrt(0.25*size_l));
int k = size_l - 1, kc = 0;
double tot = 0.0;
double max = -DBL_MAX;
double diff;
for(i= 0; i<num_levels_to_check; i++)
{
diff = l[k].log_likelihood.value - l[k-1].log_likelihood.value;
tot += diff;
if(diff > max)
max = diff;
k--;
kc++;
if( k < 1 )
break;
}
if(tot/kc < options.max_ptol && max < options.max_ptol*1.1)
return true;
else
return false;
}
return (size_l >= options.max_num_levels);
}
void initialize_output_file()
{
if(dnest_thistask != dnest_root)
return;
if(dnest_flag_restart !=1)
fsample = fopen(options.sample_file, "w");
else
fsample = fopen(options.sample_file, "a");
if(fsample==NULL)
{
fprintf(stderr, "# Cannot open file sample.txt.\n");
exit(0);
}
if(dnest_flag_restart != 1)
fprintf(fsample, "# \n");
if(dnest_flag_restart != 1)
fsample_info = fopen(options.sample_info_file, "w");
else
fsample_info = fopen(options.sample_info_file, "a");
if(fsample_info==NULL)
{
fprintf(stderr, "# Cannot open file %s.\n", options.sample_info_file);
exit(0);
}
if(dnest_flag_restart != 1)
fprintf(fsample_info, "# level assignment, log likelihood, tiebreaker, ID.\n");
}
void close_output_file()
{
if(dnest_thistask != dnest_root )
return;
fclose(fsample);
fclose(fsample_info);
}
void setup(int argc, char** argv, DNestFptrSet *fptrset, int num_params,
double *param_range, int *prior_type, double *prior_info,
char *sample_dir, char *optfile, DNestOptions *opts, void *args)
{
int i, j;
// root task.
dnest_root = 0;
if(dnest_thistask == dnest_root)
{
dnest_check_directory(sample_dir);
}
MPI_Barrier(MPI_COMM_WORLD);
// setup function pointers
from_prior = fptrset->from_prior;
log_likelihoods_cal = fptrset->log_likelihoods_cal;
log_likelihoods_cal_initial = fptrset->log_likelihoods_cal_initial;
log_likelihoods_cal_restart = fptrset->log_likelihoods_cal_restart;
perturb = fptrset->perturb;
print_particle = fptrset->print_particle;
read_particle = fptrset->read_particle;
restart_action = fptrset->restart_action;
accept_action = fptrset->accept_action;
kill_action = fptrset->kill_action;
strcpy(options_file, optfile);
strcpy(dnest_sample_dir, sample_dir);
// random number generator
dnest_gsl_T = (gsl_rng_type *) gsl_rng_default;
dnest_gsl_r = gsl_rng_alloc (dnest_gsl_T);
#ifndef Debug
gsl_rng_set(dnest_gsl_r, time(NULL) + dnest_thistask);
#else
gsl_rng_set(dnest_gsl_r, 9999 + dnest_thistask);
printf("# debugging, task %d dnest random seed %d\n", dnest_thistask, 9999 + dnest_thistask);
#endif
dnest_num_params = num_params;
dnest_size_of_modeltype = dnest_num_params * sizeof(double);
if(param_range != NULL)
{
dnest_param_range = malloc(num_params*2*sizeof(double));
memcpy(dnest_param_range, param_range, num_params*2*sizeof(double));
}
if(prior_type != NULL)
{
dnest_prior_type = malloc(num_params*sizeof(int));
memcpy(dnest_prior_type, prior_type, num_params*sizeof(int));
}
if(prior_info != NULL)
{
dnest_prior_info = malloc(num_params*2*sizeof(double));
memcpy(dnest_prior_info, prior_info, num_params*2*sizeof(double));
}
if(args != NULL)
{
dnest_args = args;
}
// read options
if(dnest_thistask == dnest_root)
options_load(optfile, opts);
MPI_Bcast(&options, sizeof(DNestOptions), MPI_BYTE, dnest_root, MPI_COMM_WORLD);
//dnest_post_temp = 1.0;
compression = exp(1.0);
regularisation = options.new_level_interval*sqrt(options.lam);
save_to_disk = true;
// particles
particle_offset_size = dnest_size_of_modeltype/sizeof(void);
particle_offset_double = dnest_size_of_modeltype/sizeof(double);
particles = (void *)malloc(options.num_particles*dnest_size_of_modeltype);
// initialise sampler
if(dnest_thistask == dnest_root)
all_above = (LikelihoodType *)malloc(2*options.new_level_interval * sizeof(LikelihoodType));
above = (LikelihoodType *)malloc(2*options.new_level_interval * sizeof(LikelihoodType));
log_likelihoods = (LikelihoodType *)malloc(2*options.num_particles * sizeof(LikelihoodType));
level_assignments = (unsigned int*)malloc(options.num_particles * sizeof(unsigned int));
account_unaccepts = (unsigned int *)malloc(options.num_particles * sizeof(unsigned int));
for(i=0; i<options.num_particles; i++)
{
account_unaccepts[i] = 0;
}
if(options.max_num_levels != 0)
{
levels = (Level *)malloc(options.max_num_levels * sizeof(Level));
if(dnest_thistask == dnest_root)
{
levels_combine = (Level *)malloc(options.max_num_levels * sizeof(Level));
copies_of_levels = (Level *)malloc(dnest_totaltask * options.max_num_levels * sizeof(Level));
}
if(dnest_flag_limits == 1)
{
limits = malloc(options.max_num_levels * particle_offset_double * 2 * sizeof(double));
if(limits == NULL)
{
printf("Cannot allocate memory for limits.\n"
"This usually happens when both the numbers of parameters and levels are extremely large.\n"
"Please do not switch on '-l' option in argv passed to dnest.\n");
exit(EXIT_FAILURE);
}
for(i=0; i<options.max_num_levels; i++)
{
for(j=0; j<particle_offset_double; j++)
{
limits[i*2*particle_offset_double+ j*2] = DBL_MAX;
limits[i*2*particle_offset_double + j*2 + 1] = -DBL_MAX;
}
}
if(dnest_thistask == dnest_root)
{
copies_of_limits = malloc( dnest_totaltask * options.max_num_levels * particle_offset_double * 2 * sizeof(double));
if(copies_of_limits == NULL)
{
printf("Cannot allocate memory for limits.\n"
"This usually happens when both the numbers of parameters and levels are extremely large.\n"
"Please do not switch on '-l' option in argv passed to dnest.\n");
exit(EXIT_FAILURE);
}
}
}
}
else
{
levels = (Level *)malloc(LEVEL_NUM_MAX * sizeof(Level));
if(dnest_thistask == dnest_root)
{
levels_combine = (Level *)malloc(LEVEL_NUM_MAX * sizeof(Level));
copies_of_levels = (Level *)malloc(dnest_totaltask * LEVEL_NUM_MAX * sizeof(Level));
}
if(dnest_flag_limits == 1)
{
limits = malloc(LEVEL_NUM_MAX * particle_offset_double * 2 * sizeof(double));
if(limits == NULL)
{
printf("Cannot allocate memory for limits.\n"
"This usually happens when both the numbers of parameters and levels are extremely large.\n"
"Please do not switch on '-l' option in argv passed to dnest.\n");
exit(EXIT_FAILURE);
}
for(i=0; i<LEVEL_NUM_MAX; i++)
{
for(j=0; j<particle_offset_double; j++)
{
limits[i*2*particle_offset_double + j*2] = DBL_MAX;
limits[i*2*particle_offset_double + j*2 + 1] = -DBL_MAX;
}
}
if(dnest_thistask == dnest_root)
{
copies_of_limits = malloc(dnest_totaltask * LEVEL_NUM_MAX * particle_offset_double * 2 * sizeof(double));
if(copies_of_limits == NULL)
{
printf("Cannot allocate memory for limits.\n"
"This usually happens when both the numbers of parameters and levels are extremely large.\n"
"Please do not switch on '-l' option in argv passed to dnest.\n");
exit(EXIT_FAILURE);
}
}
}
}
dnest_perturb_accept = malloc(options.num_particles * sizeof(int));
for(i=0; i<options.num_particles; i++)
{
dnest_perturb_accept[i] = 0;
}
count_mcmc_steps = 0;
count_saves = 0;
num_saves = (int)fmax(0.02*options.max_num_saves, 1.0);
num_saves_restart = (int)fmax(0.2 * options.max_num_saves, 1.0);
// first level
size_levels = 0;
size_above = 0;
size_all_above = 0;
LikelihoodType like_tmp = {-DBL_MAX, gsl_rng_uniform(dnest_gsl_r)};
Level level_tmp = {like_tmp, 0.0, 0, 0, 0, 0};
levels[size_levels] = level_tmp;
size_levels++;
if(dnest_thistask == dnest_root)
{
size_levels_combine = 0;
levels_combine[size_levels_combine] = level_tmp;
size_levels_combine++;
}
for(i=0; i<options.num_particles; i++)
{
dnest_which_particle_update = i;
dnest_which_level_update = 0;
from_prior(particles+i*particle_offset_size);
log_likelihoods[i].value = log_likelihoods_cal_initial(particles+i*particle_offset_size);
log_likelihoods[i].tiebreaker = dnest_rand();
level_assignments[i] = 0;
}
/*ModelType proposal;
printf("%f %f %f \n", particles[0].param[0], particles[0].param[1], particles[0].param[2] );
proposal = particles[0];
printf("%f %f %f \n", proposal.param[0], proposal.param[1], proposal.param[2] );*/
}
void finalise()
{
free(particles);
free(above);
free(log_likelihoods);
free(level_assignments);
free(levels);
free(account_unaccepts);
if(dnest_flag_limits == 1)
free(limits);
if(dnest_thistask == dnest_root)
{
free(all_above);
free(levels_combine);
free(copies_of_levels);
if(dnest_flag_limits == 1)
free(copies_of_limits);
}
gsl_rng_free(dnest_gsl_r);
free(dnest_perturb_accept);
if(dnest_param_range != NULL)
{
free(dnest_param_range);
}
if(dnest_prior_type != NULL)
{
free(dnest_prior_type);
}
if(dnest_prior_info != NULL)
{
free(dnest_prior_info);
}
if(dnest_thistask == dnest_root)
{
printf("# Finalizing CDNest.\n");
printf("#=======================================================\n");
}
}
int dnest_search_pardict(DNestPARDICT *pardict, int num_pardict, char *tag)
{
int i;
for(i=0; i<num_pardict; i++)
{
if(strcmp(pardict[i].tag, tag) == 0)
{
return i;
}
}
fprintf(stderr, "# cdnest no match of tag %s.\n", tag);
return num_pardict+1;
}
void options_load(char *optfile, DNestOptions *opts)
{
if(strlen(optfile) > 0)
{
DNestPARDICT *pardict;
int num_pardict;
pardict = malloc(10 * sizeof(DNestPARDICT));
enum TYPE {INT, DOUBLE, STRING};
FILE *fp;
char str[BUF_MAX_LENGTH], buf1[BUF_MAX_LENGTH], buf2[BUF_MAX_LENGTH], buf3[BUF_MAX_LENGTH];
int i, j, nt, idx;
nt = 0;
strcpy(pardict[nt].tag, "NumberParticles");
pardict[nt].addr = &options.num_particles;
pardict[nt].isset = 0;
pardict[nt++].id = INT;
strcpy(pardict[nt].tag, "NewLevelIntervalFactor");
pardict[nt].addr = &options.new_level_interval_factor;
pardict[nt].isset = 0;
pardict[nt++].id = DOUBLE;
strcpy(pardict[nt].tag, "SaveIntervalFactor");
pardict[nt].addr = &options.save_interval_factor;
pardict[nt].isset = 0;
pardict[nt++].id = DOUBLE;
strcpy(pardict[nt].tag, "ThreadStepsFactor");
pardict[nt].addr = &options.thread_steps_factor;
pardict[nt].isset = 0;
pardict[nt++].id = DOUBLE;
strcpy(pardict[nt].tag, "MaxNumberLevels");
pardict[nt].addr = &options.max_num_levels;
pardict[nt].isset = 0;
pardict[nt++].id = INT;
strcpy(pardict[nt].tag, "BacktrackingLength");
pardict[nt].addr = &options.lam;
pardict[nt].isset = 0;
pardict[nt++].id = DOUBLE;
strcpy(pardict[nt].tag, "StrengthEqualPush");
pardict[nt].addr = &options.beta;
pardict[nt].isset = 0;
pardict[nt++].id = DOUBLE;
strcpy(pardict[nt].tag, "MaxNumberSaves");
pardict[nt].addr = &options.max_num_saves;
pardict[nt].isset = 0;
pardict[nt++].id = INT;
strcpy(pardict[nt].tag, "PTol");
pardict[nt].addr = &options.max_ptol;
pardict[nt].isset = 0;
pardict[nt++].id = DOUBLE;
num_pardict = nt;
/* default values */
options.new_level_interval_factor = 2;
options.save_interval_factor = options.new_level_interval_factor;
options.thread_steps_factor = 10;
options.num_particles = 1;
options.max_num_levels = 0;
options.lam = 10.0;
options.beta = 100.0;
options.max_ptol = 0.1;
options.max_num_saves = 10000;
fp = fopen(options_file, "r");
if(fp == NULL)
{
fprintf(stderr, "# ERROR: Cannot open options file %s.\n", options_file);
exit(0);
}
while(!feof(fp))
{
sprintf(str,"empty");
fgets(str, 200, fp);
if(sscanf(str, "%s%s%s", buf1, buf2, buf3)<2)
continue;
if(buf1[0]=='%' || buf1[0] == '#')
continue;
for(i=0, j=-1; i<nt; i++)
if(strcmp(buf1, pardict[i].tag) == 0 && pardict[i].isset == 0)
{
j = i;
pardict[i].isset = 1;
//printf("%s %s\n", buf1, buf2);
break;
}
if(j >=0)
{
switch(pardict[j].id)
{
case DOUBLE:
*((double *) pardict[j].addr) = atof(buf2);
break;
case STRING:
strcpy(pardict[j].addr, buf2);
break;
case INT:
*((unsigned int *)pardict[j].addr) = (unsigned int) atof(buf2);
break;
}
}
else
{
fprintf(stderr, "# Error in file %s: Tag '%s' is not allowed or multiple defined.\n",
options_file, buf1);
exit(0);
}
}
fclose(fp);
/* check options */
idx = dnest_search_pardict(pardict, num_pardict, "SaveIntervalFactor");
if(pardict[idx].isset == 0) /* if not set */
{
options.save_interval_factor = options.new_level_interval_factor;
}
free(pardict);
}
else
{
options.new_level_interval_factor = opts->new_level_interval_factor;
options.save_interval_factor = opts->save_interval_factor;
options.thread_steps_factor = opts->thread_steps_factor;
options.num_particles = opts->num_particles;
options.max_num_levels = opts->max_num_levels;
options.lam = opts->lam;
options.beta = opts->beta;
options.max_ptol = opts->max_ptol;
options.max_num_saves = opts->max_num_saves;
}
options.thread_steps = dnest_num_params * options.thread_steps_factor * options.num_particles;
options.new_level_interval = dnest_totaltask * options.thread_steps * options.new_level_interval_factor;
options.save_interval = dnest_totaltask * options.thread_steps * options.save_interval_factor;
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.sample_file);
strcpy(options.sample_file, dnest_sample_dir);
strcat(options.sample_file,"/sample");
strcat(options.sample_file, dnest_sample_tag);
strcat(options.sample_file, ".txt");
strcat(options.sample_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.sample_info_file);
strcpy(options.sample_info_file, dnest_sample_dir);
strcat(options.sample_info_file,"/sample_info");
strcat(options.sample_info_file, dnest_sample_tag);
strcat(options.sample_info_file, ".txt");
strcat(options.sample_info_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.levels_file);
strcpy(options.levels_file, dnest_sample_dir);
strcat(options.levels_file,"/levels");
strcat(options.levels_file, dnest_sample_tag);
strcat(options.levels_file, ".txt");
strcat(options.levels_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.sampler_state_file);
strcpy(options.sampler_state_file, dnest_sample_dir);
strcat(options.sampler_state_file,"/sampler_state");
strcat(options.sampler_state_file, dnest_sample_tag);
strcat(options.sampler_state_file, ".txt");
strcat(options.sampler_state_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.posterior_sample_file);
strcpy(options.posterior_sample_file, dnest_sample_dir);
strcat(options.posterior_sample_file,"/posterior_sample");
strcat(options.posterior_sample_file, dnest_sample_tag);
strcat(options.posterior_sample_file, ".txt");
strcat(options.posterior_sample_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.posterior_sample_info_file);
strcpy(options.posterior_sample_info_file, dnest_sample_dir);
strcat(options.posterior_sample_info_file,"/posterior_sample_info");
strcat(options.posterior_sample_info_file, dnest_sample_tag);
strcat(options.posterior_sample_info_file, ".txt");
strcat(options.posterior_sample_info_file, dnest_sample_postfix);
//fgets(buf, BUF_MAX_LENGTH, fp);
//sscanf(buf, "%s", options.limits_file);
strcpy(options.limits_file, dnest_sample_dir);
strcat(options.limits_file,"/limits");
strcat(options.limits_file, dnest_sample_tag);
strcat(options.limits_file, ".txt");
strcat(options.limits_file, dnest_sample_postfix);
// check options.
if(options.new_level_interval < dnest_totaltask * options.thread_steps)
{
printf("# incorrect options:\n");
printf("# new level interval should be equal to or larger than");
printf(" totaltask * thread step.\n");
exit(0);
}
char fname[STR_MAX_LENGTH];
strcpy(fname, dnest_sample_dir);
strcat(fname, "/DNEST_OPTIONS");
FILE *fp = fopen(fname, "w");
if(fp == NULL)
{
fprintf(stderr, "# ERROR: Cannot write file %s.\n", fname);
exit(0);
}
fprintf(fp, "NumberParticles %d # Number of particles\n", options.num_particles);
fprintf(fp, "NewLevelIntervalFactor %.2f # New level interval factor\n", options.new_level_interval_factor);
fprintf(fp, "SaveIntervalFactor %.2f # Save interval factor\n", options.save_interval_factor);
fprintf(fp, "ThreadStepsFactor %.2f # ThreadSteps factor\n", options.thread_steps_factor);
fprintf(fp, "MaxNumberLevels %d # Maximum number of levels\n", options.max_num_levels);
fprintf(fp, "BacktrackingLength %.1f # Backtracking scale length\n", options.lam);
fprintf(fp, "StrengthEqualPush %.1f # Strength of effect to force histogram to equal push\n", options.beta);
fprintf(fp, "MaxNumberSaves %d # Maximum number of saves\n", options.max_num_saves);
fprintf(fp, "PTol %.1e # Likelihood tolerance in loge\n", options.max_ptol);
fprintf(fp, "ThreadSteps %d #\n", options.thread_steps);
fprintf(fp, "SaveInterval %d #\n", options.save_interval);
fprintf(fp, "NewLevelInterval %d #\n", options.new_level_interval);
fprintf(fp, "SampleFile %s #\n", options.sample_file);
fprintf(fp, "SampleInfoFile %s #\n", options.sample_info_file);
fprintf(fp, "SamplerStateFile %s #\n", options.sampler_state_file);
fprintf(fp, "PosteriorSampleFile %s #\n", options.posterior_sample_file);
fprintf(fp, "PosteriorSampleInfoFile %s #\n", options.posterior_sample_info_file);
fprintf(fp, "LevelsFile %s #\n", options.levels_file);
if(dnest_flag_limits == 1)
fprintf(fp, "LimitsFile %s #\n", options.limits_file);
fprintf(fp, "NumberCores %d # Number of cores\n", dnest_totaltask);
fprintf(fp, "NumberParameters %d # Number of parameters\n", dnest_num_params);
fclose(fp);
}
double mod(double y, double x)
{
if(x > 0.0)
{
return (y/x - floor(y/x))*x;
}
else if(x == 0.0)
{
return 0.0;
}
else
{
printf("Warning in mod(double, double) %e\n", x);
exit(0);
}
}
inline void dnest_wrap(double *x, double min, double max)
{
*x = mod(*x - min, max - min) + min;
}
inline void wrap_limit(double *x, double min, double max)
{
*x = fmax(fmin(*x, max), min);
}
inline int mod_int(int y, int x)
{
if(y >= 0)
return y - (y/x)*x;
else
return (x-1) - mod_int(-y-1, x);
}
inline double dnest_randh()
{
return pow(10.0, 1.5 - 3.0*fabs(gsl_ran_tdist(dnest_gsl_r, 2))) * gsl_ran_ugaussian(dnest_gsl_r);
}
inline double dnest_rand()
{
return gsl_rng_uniform(dnest_gsl_r);
}
inline int dnest_rand_int(int size)
{
return gsl_rng_uniform_int(dnest_gsl_r, size);
}
inline double dnest_randn()
{
return gsl_ran_ugaussian(dnest_gsl_r);
}
int dnest_cmp(const void *pa, const void *pb)
{
LikelihoodType *a = (LikelihoodType *)pa;
LikelihoodType *b = (LikelihoodType *)pb;
// in decesending order
if(a->value > b->value)
return false;
if( a->value == b->value && a->tiebreaker > b->tiebreaker)
return false;
return true;
}
inline int dnest_get_size_levels()
{
return size_levels;
}
inline int dnest_get_which_level_update()
{
return dnest_which_level_update;
}
inline int dnest_get_which_particle_update()
{
return dnest_which_particle_update;
}
inline unsigned int dnest_get_which_num_saves()
{
return num_saves;
}
unsigned int dnest_get_count_saves()
{
return count_saves;
}
inline unsigned long long int dnest_get_count_mcmc_steps()
{
return count_mcmc_steps;
}
inline void dnest_get_posterior_sample_file(char *fname)
{
strcpy(fname, options.posterior_sample_file);
return;
}
inline void dnest_get_limit(int ilevel, int jparam, double *limit1, double *limit2)
{
*limit1 = limits[ilevel*dnest_num_params*2 + jparam * 2 + 0];
*limit2 = limits[ilevel*dnest_num_params*2 + jparam * 2 + 1];
return;
}
/*
* version check
*
* 1: greater
* 0: equal
* -1: lower
*/
int dnest_check_version(char *version_str)
{
int major, minor, patch;
sscanf(version_str, "%d.%d.%d", &major, &minor, &patch);
if(major > DNEST_MAJOR_VERSION)
return 1;
if(major < DNEST_MAJOR_VERSION)
return -1;
if(minor > DNEST_MINOR_VERSION)
return 1;
if(minor < DNEST_MINOR_VERSION)
return -1;
if(patch > DNEST_PATCH_VERSION)
return 1;
if(patch > DNEST_PATCH_VERSION)
return -1;
return 0;
}
void dnest_check_fptrset(DNestFptrSet *fptrset)
{
if(fptrset->from_prior == NULL)
{
printf("\"from_prior\" function is not defined at task %d.\
\nSet to the default function in dnest.\n", dnest_thistask);
fptrset->from_prior = dnest_from_prior;
}
if(fptrset->print_particle == NULL)
{
printf("\"print_particle\" function is not defined at task %d. \
\nSet to be default function in dnest.\n", dnest_thistask);
fptrset->print_particle = dnest_print_particle;
}
if(fptrset->read_particle == NULL)
{
printf("\"read_particle\" function is not defined at task %d. \
\nSet to be default function in dnest.\n", dnest_thistask);
fptrset->read_particle = dnest_read_particle;
}
if(fptrset->log_likelihoods_cal == NULL)
{
printf("\"log_likelihoods_cal\" function is not defined at task %d.\n", dnest_thistask);
exit(0);
}
if(fptrset->log_likelihoods_cal_initial == NULL)
{
printf("\"log_likelihoods_cal_initial\" function is not defined at task %d. \
\nSet to the same as \"log_likelihoods_cal\" function.\n", dnest_thistask);
fptrset->log_likelihoods_cal_initial = fptrset->log_likelihoods_cal;
}
if(fptrset->log_likelihoods_cal_restart == NULL)
{
printf("\"log_likelihoods_cal_restart\" function is not defined at task %d. \
\nSet to the same as \"log_likelihoods_cal\" function.\n", dnest_thistask);
fptrset->log_likelihoods_cal_restart = fptrset->log_likelihoods_cal;
}
if(fptrset->perturb == NULL)
{
printf("\"perturb\" function is not defined at task %d.\
\nSet to the default function in dnest.\n", dnest_thistask);
fptrset->perturb = dnest_perturb;
}
if(fptrset->restart_action == NULL)
{
printf("\"restart_action\" function is not defined at task %d.\
\nSet to the default function in dnest.\n", dnest_thistask);
fptrset->restart_action = dnest_restart_action;
}
if(fptrset->accept_action == NULL)
{
printf("\"accept_action\" function is not defined at task %d.\
\nSet to the default function in dnest.\n", dnest_thistask);
fptrset->accept_action = dnest_accept_action;
}
if(fptrset->kill_action == NULL)
{
printf("\"kill_action\" function is not defined at task %d.\
\nSet to the default function in dnest.\n", dnest_thistask);
fptrset->kill_action = dnest_kill_action;
}
return;
}
DNestFptrSet * dnest_malloc_fptrset()
{
DNestFptrSet * fptrset;
fptrset = (DNestFptrSet *)malloc(sizeof(DNestFptrSet));
fptrset->from_prior = NULL;
fptrset->log_likelihoods_cal = NULL;
fptrset->log_likelihoods_cal_initial = NULL;
fptrset->log_likelihoods_cal_restart = NULL;
fptrset->perturb = NULL;
fptrset->print_particle = NULL;
fptrset->read_particle = NULL;
fptrset->restart_action = NULL;
fptrset->accept_action = NULL;
fptrset->kill_action = NULL;
return fptrset;
}
inline void dnest_free_fptrset(DNestFptrSet * fptrset)
{
free(fptrset);
return;
}
void dnest_check_directory(char *sample_dir)
{
/* check if sample_dir exists
* if not, create it;
* if exists, check if it is a directory;
* if not, throw an error.*/
struct stat st;
int status;
status = stat(sample_dir, &st);
if(status != 0)
{
printf("================================\n"
"Directory %s not exist! create it.\n", sample_dir);
status = mkdir(sample_dir, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if(status!=0)
{
printf("Cannot create %s\n"
"================================\n", sample_dir);
}
}
else
{
if(!S_ISDIR(st.st_mode))
{
printf("================================\n"
"%s is not a direcotry!\n"
"================================\n", sample_dir);
exit(-1);
}
}
return;
}
/*!
* Save sampler state for later restart.
*/
void dnest_save_restart()
{
FILE *fp;
int i, j;
void *particles_all;
LikelihoodType *log_likelihoods_all;
unsigned int *level_assignments_all;
char str[200];
if(dnest_thistask == dnest_root)
{
sprintf(str, "%s_%d", file_save_restart, count_saves);
fp = fopen(str, "wb");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s. \n", file_save_restart);
exit(0);
}
particles_all = (void *)malloc( options.num_particles * dnest_totaltask * dnest_size_of_modeltype );
log_likelihoods_all = (LikelihoodType *)malloc(dnest_totaltask * options.num_particles * sizeof(LikelihoodType));
level_assignments_all = (unsigned int*)malloc(dnest_totaltask * options.num_particles * sizeof(unsigned int));
}
MPI_Gather(particles, options.num_particles * dnest_size_of_modeltype, MPI_BYTE,
particles_all, options.num_particles * dnest_size_of_modeltype, MPI_BYTE, dnest_root, MPI_COMM_WORLD);
MPI_Gather(level_assignments, options.num_particles * sizeof(unsigned int), MPI_BYTE,
level_assignments_all, options.num_particles * sizeof(unsigned int), MPI_BYTE, dnest_root, MPI_COMM_WORLD);
MPI_Gather(log_likelihoods, options.num_particles * sizeof(LikelihoodType), MPI_BYTE,
log_likelihoods_all, options.num_particles * sizeof(LikelihoodType), MPI_BYTE, dnest_root, MPI_COMM_WORLD);
if(dnest_thistask == dnest_root )
{
printf("# Save restart data to file %s.\n", str);
//fprintf(fp, "%d %d\n", count_saves, count_mcmc_steps);
//fprintf(fp, "%d\n", size_levels_combine);
fwrite(&count_saves, sizeof(int), 1, fp);
fwrite(&count_mcmc_steps, sizeof(int), 1, fp);
fwrite(&size_levels_combine, sizeof(int), 1, fp);
for(i=0; i<size_levels_combine; i++)
{
//fprintf(fp, "%14.12g %14.12g %f %llu %llu %llu %llu\n", levels_combine[i].log_X, levels_combine[i].log_likelihood.value,
// levels_combine[i].log_likelihood.tiebreaker, levels_combine[i].accepts,
// levels_combine[i].tries, levels[i].exceeds, levels_combine[i].visits);
fwrite(&levels_combine[i], sizeof(Level), 1, fp);
}
for(j=0; j<dnest_totaltask; j++)
{
for(i=0; i<options.num_particles; i++)
{
//fprintf(fp, "%d %e %f\n", level_assignments_all[j*options.num_particles + i],
// log_likelihoods_all[j*options.num_particles + i].value,
// log_likelihoods_all[j*options.num_particles + i].tiebreaker);
fwrite(&level_assignments_all[j*options.num_particles + i], sizeof(int), 1, fp);
fwrite(&log_likelihoods_all[j*options.num_particles + i], sizeof(LikelihoodType), 1, fp);
}
}
if(dnest_flag_limits == 1)
{
for(i=0; i<size_levels_combine; i++)
{
//fprintf(fp, "%d ", i);
for(j=0; j<particle_offset_double; j++)
{
//fprintf(fp, "%f %f ", limits[i*2*particle_offset_double+j*2], limits[i*2*particle_offset_double+j*2+1]);
fwrite(&limits[i*2*particle_offset_double+j*2], sizeof(double), 2, fp);
}
//fprintf(fp, "\n");
}
}
for(j=0; j<dnest_totaltask; j++)
{
for(i=0; i<options.num_particles; i++)
{
//print_particle(fp, particles_all + (j * options.num_particles + i) * particle_offset_size);
fwrite(particles_all + (j * options.num_particles + i) * particle_offset_size, dnest_size_of_modeltype, 1, fp);
}
}
fclose(fp);
free(particles_all);
free(log_likelihoods_all);
free(level_assignments_all);
}
restart_action(0);
}
void dnest_restart()
{
FILE *fp;
int i, j;
void *particles_all;
unsigned int *level_assignments_all;
LikelihoodType *log_likelihoods_all;
void *particle;
if(dnest_thistask == dnest_root)
{
fp = fopen(file_restart, "rb");
if(fp == NULL)
{
fprintf(stderr, "# Error: Cannot open file %s. \n", file_restart);
exit(0);
}
printf("# Reading %s\n", file_restart);
particles_all = (void *)malloc( options.num_particles * dnest_totaltask * dnest_size_of_modeltype );
log_likelihoods_all = (LikelihoodType *)malloc(dnest_totaltask * options.num_particles * sizeof(LikelihoodType));
level_assignments_all = (unsigned int*)malloc(dnest_totaltask * options.num_particles * sizeof(unsigned int));
fread(&count_saves, sizeof(int), 1, fp);
fread(&count_mcmc_steps, sizeof(int), 1, fp);
fread(&size_levels_combine, sizeof(int), 1, fp);
/* consider that the newly input max_num_levels may be different from the saved size of levels */
if(options.max_num_levels != 0)
{
if(size_levels_combine > options.max_num_levels)
{
printf("# input max_num_levels %d smaller than the one in restart data %d.\n", options.max_num_levels, size_levels_combine);
size_levels = options.max_num_levels;
}
else
{
size_levels = size_levels_combine;
}
}
else /* not input max_num_levels, directly use the saved size of levels */
{
if(size_levels_combine > LEVEL_NUM_MAX)
{
printf("# the saved size of levels %d exceeds LEVEL_NUM_MAX %d. \n", size_levels_combine, LEVEL_NUM_MAX);
exit(EXIT_FAILURE);
}
else
{
size_levels = size_levels_combine;
}
}
// read levels
for(i=0; i<size_levels_combine; i++)
{
if(i<size_levels) // not read all the levels
fread(&levels_combine[i], sizeof(Level), 1, fp);
else
fseek(fp, sizeof(Level), SEEK_CUR); /* offset the file point */
}
memcpy(levels, levels_combine, size_levels * sizeof(Level));
// read level assignment
for(j=0; j<dnest_totaltask; j++)
{
for(i=0; i<options.num_particles; i++)
{
fread(&level_assignments_all[j*options.num_particles + i], sizeof(int), 1, fp);
fread(&log_likelihoods_all[j*options.num_particles + i], sizeof(LikelihoodType), 1, fp);
/* reset the level assignment that exceeds the present maximum level */
if(level_assignments_all[j*options.num_particles + i] > size_levels -1)
{
level_assignments_all[j*options.num_particles + i] = size_levels - 1;
}
}
}
// read limits
if(dnest_flag_limits == 1)
{
for(i=0; i<size_levels_combine; i++)
{
if(i < size_levels)
{
for(j=0; j<particle_offset_double; j++)
{
fread(&limits[i*2*particle_offset_double+j*2], sizeof(double), 2, fp);
}
}
else
{
fseek(fp, sizeof(double) * 2 * particle_offset_double, SEEK_CUR); /* offset the file point */
}
}
}
// read particles
for(j=0; j<dnest_totaltask; j++)
{
for(i=0; i<options.num_particles; i++)
{
particle = (particles_all + (j * options.num_particles + i) * dnest_size_of_modeltype);
fread(particle, dnest_size_of_modeltype, 1, fp);
}
}
fclose(fp);
}
MPI_Bcast(&count_saves, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);
MPI_Bcast(&count_mcmc_steps, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);
MPI_Bcast(&size_levels, 1, MPI_INT, dnest_root, MPI_COMM_WORLD);
MPI_Bcast(levels, size_levels * sizeof(Level), MPI_BYTE, dnest_root, MPI_COMM_WORLD);
if(count_saves > options.max_num_saves)
{
if(dnest_thistask == dnest_root)
{
printf("# Number of samples already larger than the input number, exit!\n");
}
MPI_Barrier(MPI_COMM_WORLD);
exit(0);
}
size_levels_combine = size_levels; /* reset szie_levels_combine */
num_saves = (int)fmax(0.02*(options.max_num_saves-count_saves), 1.0); /* reset num_saves */
num_saves_restart = (int)fmax(0.2 * (options.max_num_saves-count_saves), 1.0); /* reset num_saves_restart */
if(dnest_flag_limits == 1)
MPI_Bcast(limits, size_levels * particle_offset_double * 2, MPI_DOUBLE, dnest_root, MPI_COMM_WORLD);
MPI_Scatter(level_assignments_all, options.num_particles * sizeof(unsigned int), MPI_BYTE,
level_assignments, options.num_particles * sizeof(unsigned int), MPI_BYTE, dnest_root, MPI_COMM_WORLD);
MPI_Scatter(log_likelihoods_all, options.num_particles * sizeof(LikelihoodType), MPI_BYTE,
log_likelihoods, options.num_particles * sizeof(LikelihoodType), MPI_BYTE, dnest_root, MPI_COMM_WORLD);
MPI_Scatter(particles_all, options.num_particles * dnest_size_of_modeltype, MPI_BYTE,
particles, options.num_particles * dnest_size_of_modeltype, MPI_BYTE, dnest_root, MPI_COMM_WORLD);
restart_action(1);
for(i=0; i<options.num_particles; i++)
{
dnest_which_particle_update = i;
dnest_which_level_update = level_assignments[i];
//printf("%d %d %f\n", thistask, i, log_likelihoods[i].value);
log_likelihoods[i].value = log_likelihoods_cal_restart(particles+i*particle_offset_size);
//printf("%d %d %f\n", thistask, i, log_likelihoods[i].value);
//due to randomness, the original level assignment may be incorrect. re-asign the level
while(log_likelihoods[i].value < levels[level_assignments[i]].log_likelihood.value)
{
printf("# level assignment decrease %d %f %f %d.\n", i, log_likelihoods[i].value,
levels[level_assignments[i]].log_likelihood.value, level_assignments[i]);
level_assignments[i]--;
}
}
if(dnest_thistask == dnest_root)
{
free(particles_all);
free(log_likelihoods_all);
free(level_assignments_all);
}
return;
}
void dnest_from_prior(void *model)
{
int i;
double *pm = (double *)model;
for(i=0; i<dnest_num_params; i++)
{
if(dnest_prior_type[i] == GAUSSIAN )
{
pm[i] = dnest_randn() * dnest_prior_info[i*2+1] + dnest_prior_info[i*2+0];
dnest_wrap(&pm[i], dnest_param_range[i*2+0], dnest_param_range[i*2+1]);
}
else if(dnest_prior_type[i] == LOG)
{
pm[i] = log(dnest_param_range[i*2+0]) + dnest_rand()*(log(dnest_param_range[i*2+1]) - log(dnest_param_range[i*2+0]));
pm[i] = exp(pm[i]);
}
else
{
pm[i] = dnest_param_range[i*2+0] + dnest_rand()*(dnest_param_range[i*2+1] - dnest_param_range[i*2+0]);
}
}
}
double dnest_perturb(void *model)
{
double *pm = (double *)model;
double logH = 0.0, width;
int which;
which = dnest_rand_int(dnest_num_params);
width = ( dnest_param_range[which*2+1] - dnest_param_range[which*2+0] );
if(dnest_prior_type[which] == UNIFORM)
{
pm[which] += dnest_randh() * width;
dnest_wrap(&(pm[which]), dnest_param_range[which*2+0], dnest_param_range[which*2+1]);
}
else if(dnest_prior_type[which] == LOG)
{
logH -= (-log(pm[which]));
pm[which] += dnest_randh() * width;
dnest_wrap(&(pm[which]), dnest_param_range[which*2+0], dnest_param_range[which*2+1]);
logH += (-log(pm[which]));
}
else
{
logH -= (-0.5*pow((pm[which] - dnest_prior_info[which*2+0])/dnest_prior_info[which*2+1], 2.0) );
pm[which] += dnest_randh() * width;
dnest_wrap(&pm[which], dnest_param_range[which*2+0], dnest_param_range[which*2+1]);
logH += (-0.5*pow((pm[which] - dnest_prior_info[which*2+0])/dnest_prior_info[which*2+1], 2.0) );
}
return logH;
}
inline void dnest_print_particle(FILE *fp, const void *model)
{
int i;
double *pm = (double *)model;
for(i=0; i<dnest_num_params; i++)
{
fprintf(fp, "%e ", pm[i] );
}
fprintf(fp, "\n");
return;
}
void dnest_read_particle(FILE *fp, void *model)
{
int j;
double *psample = (double *)model;
for(j=0; j < dnest_num_params; j++)
{
if(fscanf(fp, "%lf", psample+j) < 1)
{
printf("%f\n", *psample);
fprintf(stderr, "#Error: Cannot read file %s.\n", options.sample_file);
exit(0);
}
}
return;
}
inline void dnest_restart_action(int iflag)
{
return;
}
inline void dnest_accept_action()
{
return;
}
inline void dnest_kill_action(int i, int i_copy)
{
return;
} | {
"alphanum_fraction": 0.6487144527,
"avg_line_length": 29.8777885548,
"ext": "c",
"hexsha": "06c24b3da622218366a3b15222e9111a0c3f7eed",
"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": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LiyrAstroph/DNest_C",
"max_forks_repo_path": "src/dnest.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e",
"max_issues_repo_issues_event_max_datetime": "2021-01-06T02:04:19.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-14T10:04:48.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "LiyrAstroph/DNest_C",
"max_issues_repo_path": "src/dnest.c",
"max_line_length": 135,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "afb6b869ce1c4ebd76662b20310f1d9d3db4e26e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LiyrAstroph/CDNest",
"max_stars_repo_path": "src/dnest.c",
"max_stars_repo_stars_event_max_datetime": "2020-10-16T12:14:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-11T03:34:45.000Z",
"num_tokens": 16972,
"size": 61608
} |
#ifndef BIO_BAYESIAN_HIERARCHICAL_CLUSTERING_H_
#define BIO_BAYESIAN_HIERARCHICAL_CLUSTERING_H_
#include "bio/defs.h"
#include <boost/graph/adjacency_list.hpp>
#include <boost/io/ios_state.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/operation.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/storage.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <set>
#include <list>
#include <limits>
#include <iterator>
#include <algorithm>
#include <iostream>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_exp.h>
#include <gsl/gsl_sf_log.h>
#include <gsl/gsl_math.h>
BIO_NS_START
/** @file
See http://www.gatsby.ucl.ac.uk/~heller/bhc.pdf for the motivation for these algorithms.
*/
/** Aggregates a data set with its associated score. */
template <class DataIt, class Score>
struct Cluster
{
typedef std::set<DataIt> data_set_t;
data_set_t data_set;
Score score;
};
/** A Normal-Wishart prior.
Each datum should be an iterator that points to a sequence of reals.
I am not convinced this is implemented correctly...
*/
struct NormalWishartPrior
{
typedef double real_t;
typedef boost::numeric::ublas::vector<real_t> vector_t;
typedef boost::numeric::ublas::matrix<real_t> matrix_t;
matrix_t s;
vector_t m;
real_t r;
real_t v;
unsigned get_num_dims() const { return s.size1(); }
NormalWishartPrior(unsigned num_dimensions = 0)
: s(num_dimensions, num_dimensions)
, m(num_dimensions)
{
}
template <class DataIt>
real_t
operator()(
DataIt data_begin,
DataIt data_end) const
{
using namespace boost::numeric::ublas;
//if we have no data
if (data_end == data_begin)
{
return real_t(1);
}
//calculate the number of data points
unsigned n = 0; //std::count_if(data_begin, data_end, true);
for (DataIt di = data_begin;
data_end != di;
++di)
{
++n;
}
//put the data set in a matrix
matrix_t x(get_num_dims(), n);
unsigned i = 0;
for (DataIt di = data_begin;
data_end != di;
++di, ++i)
{
for (unsigned j = 0;
get_num_dims() != j;
++j)
{
x(j,i) = (**di)[j];
}
}
//calculate the sum of the data in each dimension
vector_t x_sum(get_num_dims());
for (unsigned j = 0;
get_num_dims() != j;
++j)
{
x_sum(j) = 0;
for (unsigned i = 0;
n != i;
++i)
{
x_sum(j) += x(j, i);
}
}
//calculate s_dash - the first term is s
matrix_t s_dash(s);
{
//add X.XT to s_dash
s_dash += prod(x, trans(x));
//add m.mT term to s_dash
s_dash += (r * n / (n + r)) * outer_prod(m, m);
//add x_sum.x_sumT term to s_dash
s_dash += (1.0 / (n + r)) * outer_prod(x_sum, x_sum);
//subtract m.x_sum term from s_dash
s_dash -= (r / (n + r)) * (outer_prod(m, x_sum) + outer_prod(x_sum, m));
}
//std::cout << s << std::endl;
//std::cout << s_dash << std::endl;
//std::cout << prod(x, trans(x)) << std::endl;
//calculate the determinants
const real_t s_det = get_determinant(s);
const real_t s_dash_det = get_determinant(s_dash);
//v_dash
const real_t v_dash = v + n;
//the number of dimensions
const real_t k = get_num_dims();
//the number of data points
const real_t N = n;
//the natural logarithm of the result
real_t ln_p_D_given_H1 = 0.0;
ln_p_D_given_H1 -= N * k / 2 * gsl_sf_log(2 * M_PI);
ln_p_D_given_H1 += k / 2 * gsl_sf_log(r / (N + r));
ln_p_D_given_H1 += v / 2 * gsl_sf_log(fabs(s_det));
ln_p_D_given_H1 -= v_dash / 2 * gsl_sf_log(fabs(s_dash_det));
ln_p_D_given_H1 += v_dash * k / 2 * gsl_sf_log(2);
ln_p_D_given_H1 -= v * k / 2 * gsl_sf_log(2);
//add/subtract the pi terms
for (unsigned d = 0; k != d; ++d)
{
ln_p_D_given_H1 +=
gsl_sf_lngamma((v_dash + 1 - d) / 2)
- gsl_sf_lngamma((v + 1 - d) / 2);
}
return gsl_sf_exp(ln_p_D_given_H1);
}
template <class M>
static real_t
get_determinant(const M & m)
{
BOOST_ASSERT(m.size1() == m.size2());
matrix_t lu(m);
//permutation_matrix<unsigned> p(m.size());
lu_factorize(lu);
real_t result = 0;
for (unsigned j = 0;
lu.size1() != j;
++j)
{
result += lu(j,j);
}
return result;
}
};
/** A Bernoulli - Beta prior.
Each datum should be an iterator that points to a sequence of bools (or convertible types).
*/
struct BernoulliBetaPrior
{
typedef double real_t;
typedef std::vector<real_t> param_vec_t;
param_vec_t alpha;
param_vec_t beta;
BernoulliBetaPrior(unsigned num_dimensions = 0)
: alpha(num_dimensions)
, beta(num_dimensions)
{
}
template <class DataIt>
real_t
operator()(
DataIt data_begin,
DataIt data_end)
{
if (data_end == data_begin)
{
return real_t(1);
}
assert(alpha.size() == beta.size());
assert((*data_begin)->size() == alpha.size());
//the log of p(D|H1)
double ln_p_D_H1 = 0.0;
unsigned n = 0;
for (DataIt i = data_begin; data_end != i; ++i)
{
++n;
}
//for each dimension
for (size_t d = 0; alpha.size() != d; ++d)
{
//work out m_d
unsigned m_d = 0;
for (DataIt i = data_begin; data_end != i; ++i)
{
assert((*i)->size() == alpha.size());
if ((**i)[d])
{
++m_d;
}
}
ln_p_D_H1 +=
gsl_sf_lngamma(alpha[d] + beta[d])
+ gsl_sf_lngamma(alpha[d] + m_d)
+ gsl_sf_lngamma(beta[d] + n - m_d)
- gsl_sf_lngamma(alpha[d])
- gsl_sf_lngamma(beta[d])
- gsl_sf_lngamma(alpha[d] + beta[d] + n);
}
return gsl_sf_exp(ln_p_D_H1);
}
};
/** A Multinomial Dirichlet prior.
Each datum should be an iterator that points to a sequence of bools (or convertible types).
*/
struct MultinomialDirichletPrior
{
typedef double real_t;
typedef std::vector<real_t> param_vec_t;
param_vec_t alpha;
MultinomialDirichletPrior(unsigned num_dimensions = 0)
: alpha(num_dimensions)
{
}
template <class DataIt>
real_t
operator()(
DataIt data_begin,
DataIt data_end)
{
if (data_end == data_begin)
{
return real_t(1);
}
assert((*data_begin)->size() == alpha.size());
//the log of p(D|H1) ie log of the result
double ln_p_D_H1 = 0.0;
//TODO - not implemented
return gsl_sf_exp(ln_p_D_H1);
}
};
/** The score of a cluster based on a prior model and the score of the two clusters
it is composed of. */
struct BayesianClusterScore
{
typedef double real_t;
real_t p_Dk_given_H1k;
real_t p_Dk_given_Tk;
BayesianClusterScore(real_t p_Dk_given_H1k = 1, real_t p_Dk_given_Tk = 1)
: p_Dk_given_H1k(p_Dk_given_H1k)
, p_Dk_given_Tk(p_Dk_given_Tk)
{
}
bool operator<(const BayesianClusterScore & rhs) const
{
if (real_t(0) == p_Dk_given_Tk)
{
return false;
}
if (real_t(0) == rhs.p_Dk_given_Tk)
{
return false;
}
return operator()() < rhs();
}
real_t operator()() const
{
return p_Dk_given_H1k / p_Dk_given_Tk;
}
};
BIO_NS_END
std::ostream &
operator<<(std::ostream & os, const BIO_NS::BayesianClusterScore & score)
{
boost::io::ios_all_saver ias(os);
os.precision(3);
os << score.p_Dk_given_H1k << "/" << score.p_Dk_given_Tk << "=" << score();
return os;
}
BIO_NS_START
/** Scores clusters according to http://www.gatsby.ucl.ac.uk/~heller/bhcnew.pdf */
template <class Model>
struct BayesianClusterScorer
{
typedef double real_t;
typedef Model model_t;
model_t & model;
BayesianClusterScorer(model_t & model)
: model(model)
{
}
typedef BayesianClusterScore score_t;
static score_t min_score() { return score_t(-1, 1); }
template <class Cluster>
score_t
operator()(
const Cluster & cluster) const
{
const real_t marginal_likelihood = model(cluster.data_set.begin(), cluster.data_set.end());
return score_t(marginal_likelihood, marginal_likelihood);
}
/** Returns the score of the data set resulting from merging the two data sets. */
template <class Cluster>
score_t
operator()(
const Cluster & cluster_1,
const Cluster & cluster_2) const
{
//merge the two data sets
typename Cluster::data_set_t merged_data_set;
set_union(
cluster_1.data_set.begin(),
cluster_1.data_set.end(),
cluster_2.data_set.begin(),
cluster_2.data_set.end(),
std::inserter(merged_data_set, merged_data_set.begin()));
score_t result;
const real_t pi_k = 0.5; //?????
result.p_Dk_given_H1k =
pi_k * model(merged_data_set.begin(), merged_data_set.end());
result.p_Dk_given_Tk =
result.p_Dk_given_H1k
+ (1 - pi_k) * cluster_1.score.p_Dk_given_Tk * cluster_2.score.p_Dk_given_Tk;
return result;
}
};
/** Defines some types for given data types and scorers. */
template <class DataIt, class Scorer>
struct ClusterTraits
{
typedef DataIt data_it;
typedef Scorer scorer_t;
typedef typename data_it::value_type data_t;
typedef std::set<data_it> data_set_t;
typedef Cluster<data_it, typename scorer_t::score_t> cluster_t;
typedef typename cluster_t::data_set_t::iterator cluster_data_it;
typedef std::list<cluster_t> cluster_list_t;
typedef typename cluster_list_t::iterator cluster_it;
};
/** Clusters the data points according to pairs' scores. */
template <class DataIt, class Scorer, class Output>
void
cluster(
DataIt data_begin,
DataIt data_end,
Scorer & scorer,
Output & output)
{
using namespace boost;
using namespace std;
typedef ClusterTraits<DataIt, Scorer> traits_t;
//initialise the list of clusters with one entry for every data point
typename traits_t::cluster_list_t cluster_list;
for (DataIt d = data_begin;
data_end != d;
++d)
{
typename traits_t::cluster_t cluster;
cluster.data_set.insert(d);
cluster.score = scorer(cluster);
output(cluster_list.insert(cluster_list.begin(), cluster));
}
//while we have at least 2 clusters to merge
while (1 < cluster_list.size())
{
//look for the best pair of clusters to merge in the hierarchy
typename std::pair<typename traits_t::cluster_it, typename traits_t::cluster_it> best_clusters =
make_pair(cluster_list.end(), cluster_list.end());
typename Scorer::score_t best_score = Scorer::min_score();
//for each pair of clusters, c1 and c2
for (typename traits_t::cluster_it c1 = cluster_list.begin();
cluster_list.end() != c1;
++c1)
{
typename traits_t::cluster_it c2 = c1;
++c2;
for ( ;
cluster_list.end() != c2;
++c2)
{
//score the pair of clusters
const typename Scorer::score_t score = scorer(*c1, *c2);
//is it the best score so far?
if (best_score < score)
{
//update best
best_score = score;
best_clusters.first = c1;
best_clusters.second = c2;
}
}
}
assert(best_clusters.first != best_clusters.second);
assert(cluster_list.end() != best_clusters.first);
assert(cluster_list.end() != best_clusters.second);
//create and add the merged cluster
typename traits_t::cluster_t merged_cluster;
merged_cluster.score = best_score;
set_union(
best_clusters.first->data_set.begin(),
best_clusters.first->data_set.end(),
best_clusters.second->data_set.begin(),
best_clusters.second->data_set.end(),
inserter(merged_cluster.data_set, merged_cluster.data_set.begin()));
//let the output know
output(
best_clusters.first,
best_clusters.second,
cluster_list.insert(cluster_list.begin(), merged_cluster));
//remove the old data sets and add the merged one
cluster_list.erase(best_clusters.first);
cluster_list.erase(best_clusters.second);
}
}
struct LoggingClusterer
{
std::ostream & os;
LoggingClusterer(std::ostream & os) : os(os)
{
}
template <class ClusterIt>
void
operator()(
const ClusterIt & cluster)
{
using namespace std;
os << "Initial cluster: ";
for (typename ClusterIt::value_type::data_set_t::const_iterator d = cluster->data_set.begin();
cluster->data_set.end() != d;
++d)
{
os << **d << ",";
}
os << " score:" << cluster->score << endl;
}
template <class ClusterIt>
void
operator()(
ClusterIt cluster_1,
ClusterIt cluster_2,
ClusterIt merged_cluster)
{
using namespace std;
//print what we are doing
cout << "Clustering: ";
for (typename ClusterIt::value_type::data_set_t::const_iterator d = cluster_1->data_set.begin();
cluster_1->data_set.end() != d;
++d)
{
os << **d << ",";
}
cout << " with ";
for (typename ClusterIt::value_type::data_set_t::const_iterator d = cluster_2->data_set.begin();
cluster_2->data_set.end() != d;
++d)
{
os << **d << ",";
}
os << " score:" << merged_cluster->score << endl;
}
};
template <class DataIt, class Scorer>
struct TreeBuildingClusterer
{
typedef DataIt data_it;
typedef Scorer scorer_t;
typedef ClusterTraits<data_it, scorer_t> traits_t;
typedef std::pair<bool, typename traits_t::data_it> vertex_property;
typedef boost::adjacency_list<
boost::listS,
boost::vecS,
boost::directedS,
vertex_property,
typename Scorer::score_t> tree_t;
typedef typename boost::graph_traits<tree_t>::vertex_iterator tree_vertex_it;
typedef typename boost::graph_traits<tree_t>::vertex_descriptor tree_vertex;
tree_t tree;
/** A map from clusters to tree nodes. */
typedef std::map<typename traits_t::cluster_t *, tree_vertex> cluster_vertex_map_t;
cluster_vertex_map_t cluster_vertex_map;
LoggingClusterer logger;
bool logging_on;
TreeBuildingClusterer(bool logging_on = false) : logger(std::cout), logging_on(logging_on)
{
}
void
reset()
{
cluster_vertex_map.clear();
tree.clear();
}
void
operator()(
typename traits_t::cluster_it cluster)
{
using namespace std;
using namespace boost;
if (logging_on)
{
logger(cluster);
}
cluster_vertex_map[&*cluster] = add_vertex(make_pair(true, *cluster->data_set.begin()), tree);
}
void
operator()(
typename traits_t::cluster_it cluster_1,
typename traits_t::cluster_it cluster_2,
typename traits_t::cluster_it merged_cluster)
{
using namespace std;
using namespace boost;
if (logging_on)
{
logger(cluster_1, cluster_2, merged_cluster);
}
//find the vertex descriptors for cluster_1 and cluster_2
assert(cluster_vertex_map.end() != cluster_vertex_map.find(&*cluster_1));
assert(cluster_vertex_map.end() != cluster_vertex_map.find(&*cluster_2));
cluster_vertex_map[&*merged_cluster] = add_vertex(make_pair(false, typename traits_t::data_it()), tree);
add_edge(cluster_vertex_map[&*merged_cluster], cluster_vertex_map[&*cluster_1], tree);
add_edge(cluster_vertex_map[&*merged_cluster], cluster_vertex_map[&*cluster_2], tree);
}
};
BIO_NS_END
#endif //BIO_BAYESIAN_HIERARCHICAL_CLUSTERING_H_
| {
"alphanum_fraction": 0.5822204157,
"avg_line_length": 26.3333333333,
"ext": "h",
"hexsha": "c9d0e2136e7cdf52e51d0f7101281cf17ef154c0",
"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": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JohnReid/biopsy",
"max_forks_repo_path": "C++/include/bio/bayesian_hierarchical_clustering.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"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": "JohnReid/biopsy",
"max_issues_repo_path": "C++/include/bio/bayesian_hierarchical_clustering.h",
"max_line_length": 112,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JohnReid/biopsy",
"max_stars_repo_path": "C++/include/bio/bayesian_hierarchical_clustering.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4253,
"size": 17222
} |
/* specfunc/bessel_Y0.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "gsl_sf_trig.h"
#include "gsl_sf_bessel.h"
#include "error.h"
#include "bessel.h"
#include "bessel_amp_phase.h"
#include "cheb_eval.c"
/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/
/* based on SLATEC besy0, 1980 version, w. fullerton */
/* chebyshev expansions
series for by0 on the interval 0. to 1.60000d+01
with weighted error 1.20e-17
log weighted error 16.92
significant figures required 16.15
decimal places required 17.48
*/
static double by0_data[13] = {
-0.011277839392865573,
-0.128345237560420350,
-0.104378847997942490,
0.023662749183969695,
-0.002090391647700486,
0.000103975453939057,
-0.000003369747162423,
0.000000077293842676,
-0.000000001324976772,
0.000000000017648232,
-0.000000000000188105,
0.000000000000001641,
-0.000000000000000011
};
static cheb_series by0_cs = {
by0_data,
12,
-1, 1,
8
};
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int gsl_sf_bessel_Y0_e(const double x, gsl_sf_result * result)
{
const double two_over_pi = 2.0/M_PI;
const double xmax = 1.0/GSL_DBL_EPSILON;
/* CHECK_POINTER(result) */
if (x <= 0.0) {
DOMAIN_ERROR(result);
}
else if(x < 4.0) {
gsl_sf_result J0;
gsl_sf_result c;
int stat_J0 = gsl_sf_bessel_J0_e(x, &J0);
cheb_eval_e(&by0_cs, 0.125*x*x-1.0, &c);
result->val = two_over_pi*(-M_LN2 + log(x))*J0.val + 0.375 + c.val;
result->err = 2.0 * GSL_DBL_EPSILON * fabs(result->val) + c.err;
return stat_J0;
}
else if(x < xmax) {
/* Leading behaviour of phase is x, which is exact,
* so the error is bounded.
*/
const double z = 32.0/(x*x) - 1.0;
gsl_sf_result c1;
gsl_sf_result c2;
gsl_sf_result sp;
const int stat_c1 = cheb_eval_e(&_gsl_sf_bessel_amp_phase_bm0_cs, z, &c1);
const int stat_c2 = cheb_eval_e(&_gsl_sf_bessel_amp_phase_bth0_cs, z, &c2);
const int stat_sp = gsl_sf_bessel_sin_pi4_e(x, c2.val/x, &sp);
const double sqrtx = sqrt(x);
const double ampl = (0.75 + c1.val) / sqrtx;
result->val = ampl * sp.val;
result->err = fabs(sp.val) * c1.err/sqrtx + fabs(ampl) * sp.err;
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_3(stat_sp, stat_c1, stat_c2);
}
else {
UNDERFLOW_ERROR(result);
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_bessel_Y0(const double x)
{
EVAL_RESULT(gsl_sf_bessel_Y0_e(x, &result));
}
| {
"alphanum_fraction": 0.6551226551,
"avg_line_length": 28.1707317073,
"ext": "c",
"hexsha": "9f29aadf156d6b0ed13ea2370f722300e0bfc622",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_Y0.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/specfunc/bessel_Y0.c",
"max_line_length": 79,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_Y0.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": 1147,
"size": 3465
} |
/**
* @file tde.h
* @brief Time delay estimation
* @author Kenichi Kumatani
*/
#ifndef TDE_H
#define TDE_H
#include <stdio.h>
#include <assert.h>
#include <float.h>
#include <gsl/gsl_block.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_fft_real.h>
#include <gsl/gsl_fft_complex.h>
#include <common/refcount.h>
#include "common/jexception.h"
#include "stream/stream.h"
#include "feature/feature.h"
#include "modulated/modulated.h"
#include "btk.h"
// ----- definition for class `CCTDE' -----
//
/**
@class find the time difference which provides the maximum correlation between tow signals.
@usage
1. constrct sample feature objects :
samp1 =
samp2 =
2. construct this object and feed the sample features into it:
*/
class CCTDE : public VectorFeatureStream {
public:
/**
@brief
@param
@param
@param
@param
*/
CCTDE( SampleFeaturePtr& samp1, SampleFeaturePtr& samp2, int fftLen=512, unsigned nHeldMaxCC=1, int freqLowerLimit=-1, int freqUpperLimit=-1, const String& nm= "CCTDE" );
~CCTDE();
virtual const gsl_vector* next(int frame_no = -5 );
virtual const gsl_vector* nextX( unsigned chanX = 0, int frame_no = -5);
virtual void reset();
void allsamples( int fftLen = -1 );
void set_target_frequency_range( int freqLowerLimit, int freqUpperLimit ){
freq_lower_limit_ = freqLowerLimit;
freq_upper_limit_ = freqUpperLimit;
}
const unsigned *sample_delays() const { return sample_delays_; }
const double *cc_values() const {return cc_values_; }
#ifdef ENABLE_LEGACY_BTK_API
void setTargetFrequencyRange( int freqLowerLimit, int freqUpperLimit ){ set_target_frequency_range(freqLowerLimit, freqUpperLimit); }
const unsigned *getSampleDelays(){ return sample_delays(); }
const double *getCCValues(){ return cc_values(); }
#endif
private:
const gsl_vector* detect_cc_peaks_( double **samples, size_t stride );
typedef list<SampleFeaturePtr> ChannelList_;
typedef ChannelList_::iterator ChannelIterator_;
ChannelList_ channelL_; // must be 2.
unsigned *sample_delays_; // sample delays
double *cc_values_; // cross-correlation (CC) values
unsigned nHeldMaxCC_; // how many CC values are held
unsigned fftLen_;
int samplerate_;
gsl_vector *window_;
int freq_lower_limit_;
int freq_upper_limit_;
vector<unsigned > _frameCounter;
};
typedef Inherit<CCTDE, VectorFeatureStreamPtr> CCTDEPtr;
#endif
| {
"alphanum_fraction": 0.7231437599,
"avg_line_length": 28.4494382022,
"ext": "h",
"hexsha": "9b4761dd877f362f9068b8b12ccf660439e0b3bc",
"lang": "C",
"max_forks_count": 68,
"max_forks_repo_forks_event_max_datetime": "2021-11-17T09:33:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-01-08T06:33:30.000Z",
"max_forks_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "musiclvme/distant_speech_recognition",
"max_forks_repo_path": "btk20_src/tde/tde.h",
"max_issues_count": 25,
"max_issues_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_issues_repo_issues_event_max_datetime": "2021-07-28T22:01:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-12-03T04:33:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "musiclvme/distant_speech_recognition",
"max_issues_repo_path": "btk20_src/tde/tde.h",
"max_line_length": 172,
"max_stars_count": 136,
"max_stars_repo_head_hexsha": "60f867383488ac45c2fa3a5433736fdf00dd4f1d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "musiclvme/distant_speech_recognition",
"max_stars_repo_path": "btk20_src/tde/tde.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-27T15:07:42.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-06T06:35:44.000Z",
"num_tokens": 684,
"size": 2532
} |
#ifndef LOGSPLINEPDF
#define LOGSPLINEPDF
#include <gsl/gsl_rng.h>
#include "splinetable.h"
#ifdef __cplusplus
extern "C" {
#endif
void logsplinepdf_n_sample(double *result, int results, int burnin,
double *coords, int dim, struct splinetable *table, int derivatives,
double (* proposal)(void*), double (* proposal_pdf)(double, double, void*),
void *proposal_info, const gsl_rng *rng);
void splinepdf_n_sample(double *result, int results, int burnin,
double *coords, int dim, struct splinetable *table, int derivatives,
double (* proposal)(void*), double (* proposal_pdf)(double, double, void*),
void *proposal_info, const gsl_rng *rng);
#ifdef __cplusplus
}
#endif
#endif
| {
"alphanum_fraction": 0.7272727273,
"avg_line_length": 26.0740740741,
"ext": "h",
"hexsha": "bcef366ce4cb67f641b56fa54c69c10b597d39ad",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-03-30T16:44:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-07-17T09:20:29.000Z",
"max_forks_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "hschwane/offline_production",
"max_forks_repo_path": "photospline/public/photospline/splinepdf.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e",
"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": "hschwane/offline_production",
"max_issues_repo_path": "photospline/public/photospline/splinepdf.h",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e14a6493782f613b8bbe64217559765d5213dc1e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "hschwane/offline_production",
"max_stars_repo_path": "photospline/public/photospline/splinepdf.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-24T22:00:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-24T22:00:01.000Z",
"num_tokens": 183,
"size": 704
} |
/*
* Adapted from bits and pieces in https://code.google.com/p/eq-polar-alignment/
* Could not find copyright statement from there, but license seems to be GPLv3...
*
* Copyright 2014, Kalle Vahlman, zuh@iki.fi
* Licensed under the GNU GPL v3
*
*/
#include <stdio.h>
#include <time.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multiroots.h>
#include <astrometry/anwcs.h>
#include <astrometry/sip.h>
#include <astrometry/sip_qfits.h>
struct coord
{
double ra;
double dec;
double x;
double y;
};
struct state
{
anwcs_t* h_wcs;
anwcs_t* v_wcs;
double pixel_scale;
struct coord ncp;
struct coord polaris;
struct coord lambda;
struct coord axis;
};
double julian_date()
{
time_t now = time(NULL);
struct tm *t = localtime(&now);
int day = t->tm_mday;
int month = t->tm_mon+1;
int year = 1900 + t->tm_year;
return 367*year-7*(year+(month+9)/12)/4-3*((year+(month-9)/7)/100+1)/4+275*month/9+day+1721029;
}
int calculate_ncp (double julian, struct coord *c)
{
double t, zeta, theta;
if (c == NULL)
return 0;
t = (julian-2451545)/36525;
zeta = (2306.2181*t+0.30188*t*t+0.017998*t*t*t)/3600;
theta = (2004.3109*t-0.42665*t*t-0.041833*t*t*t)/3600;
c->dec = 90 - theta;
c->ra = -zeta;
return 1;
}
int solve_field(struct state *ps, const char *dir, const char *in, const char *out)
{
char run[512];
// TODO: Run the solving with code rather than system()
#define SOLVE "solve-field -B none -M none -S none -R none -U none -N none " \
"--no-plots --temp-dir %s --dir %s --out %s " \
"--downsample 2 --ra %.4f --dec %.4f --radius 10 %s"
sprintf(run, SOLVE, dir, dir, out, ps->ncp.ra, ps->ncp.dec, in);
printf("%s\n", run);
return system(run);
}
int fvec(const gsl_vector *x, void *params, gsl_vector *f)
{
struct state *s = (struct state *)params;
double ra, dec, xp, yp;
double xi = gsl_vector_get(x, 0);
double yi = gsl_vector_get(x, 1);
anwcs_pixelxy2radec(s->h_wcs, xi, yi, &ra, &dec);
anwcs_radec2pixelxy(s->v_wcs, ra, dec, &xp, &yp);
xp = xp - xi;
yp = yp - yi;
gsl_vector_set(f, 0, xp);
gsl_vector_set(f, 1, yp);
return GSL_SUCCESS;
}
int solve_axis(struct state *ps)
{
int s;
size_t iter=0;
const size_t n=2;
gsl_multiroot_fsolver *solver;
gsl_multiroot_function f = { &fvec, n, ps};
gsl_vector *x = gsl_vector_alloc(n);
gsl_vector_set(x, 0, ps->polaris.x);
gsl_vector_set(x, 1, ps->polaris.y);
solver = gsl_multiroot_fsolver_alloc(gsl_multiroot_fsolver_hybrids, 2);
gsl_multiroot_fsolver_set(solver, &f, x);
do {
iter++;
s = gsl_multiroot_fsolver_iterate(solver);
if (s) break;
s = gsl_multiroot_test_residual(solver->f,1e-7);
} while (s == GSL_CONTINUE && iter < 1000);
ps->axis.x = gsl_vector_get(solver->x, 0);
ps->axis.y = gsl_vector_get(solver->x, 1);
gsl_multiroot_fsolver_free(solver);
gsl_vector_free(x);
return s;
}
#define MAX(a, b) a < b ? b : a
int plot(struct state *ps, char *in, char *out)
{
char convert[2048];
double arcmin = 60/ps->pixel_scale;
double cropwidth = MAX(400, 120 * arcmin);
double cropheight = MAX(400, 120 * arcmin);
double cropx = ps->ncp.x - cropwidth/2;
double cropy = ps->ncp.y - cropheight/2;
int fontsize = ps->pixel_scale < 24 ? 16 : 8;
#define CONVERT "convert -fill none " \
"-pointsize %d " \
"-font Courier -stroke cyan " \
"-draw 'point %.0f,%.0f' " \
"-draw 'circle %.0f,%.0f %.0f,%.0f' " \
"-draw 'circle %.0f,%.0f %.0f,%.0f' " \
"-draw 'circle %.0f,%.0f %.0f,%.0f' " \
"-draw 'circle %.0f,%.0f %.0f,%.0f' " \
"-draw 'circle %.0f,%.0f %.0f,%.0f' " \
"-draw \"text %.0f,%.0f '%s'\" " \
"-draw \"text %.0f,%.0f '%s'\" " \
"-draw \"text %.0f,%.0f '%s'\" " \
"-draw \"text %.0f,%.0f '%s'\" " \
"-draw \"text %.0f,%.0f '%s'\" " \
"-stroke red " \
"-draw 'line %.0f,%.0f %.0f,%.0f' " \
"-draw 'line %.0f,%.0f %.0f,%.0f' " \
"-draw 'circle %.0f,%.0f %.0f,%.0f' " \
"-draw 'circle %.0f,%.0f %.0f,%.0f' " \
"-stroke white " \
"-draw 'line %.0f,%.0f %.0f,%.0f' " \
"-draw 'line %.0f,%.0f %.0f,%.0f' " \
"-font Symbol -fill white " \
"-draw \"text %.0f,%.0f '%s'\" " \
"-fill none " \
"-stroke orange " \
"-draw 'line %.0f,%.0f %.0f,%.0f' " \
"-draw 'line %.0f,%.0f %.0f,%.0f' " \
"-font Symbol -fill orange " \
"-draw \"text %.0f,%.0f '%s'\" " \
"-fill none " \
"-font Courier -stroke white -fill white " \
"-draw \"text %.0f,%.0f 'Current pixel offset from NCP: %.0f, %.0f'\" " \
"-draw \"text %.0f,%.0f '%s %s %s %s'\" " \
"-crop '%.0fx%.0f+%.0f+%.0f' " \
"%s %s"
sprintf(convert, CONVERT, fontsize,
// Target circles
ps->ncp.x, ps->ncp.y,
ps->ncp.x, ps->ncp.y, ps->ncp.x+2*arcmin, ps->ncp.y,
ps->ncp.x, ps->ncp.y, ps->ncp.x+5*arcmin, ps->ncp.y,
ps->ncp.x, ps->ncp.y, ps->ncp.x+10*arcmin, ps->ncp.y,
ps->ncp.x, ps->ncp.y, ps->ncp.x+20*arcmin, ps->ncp.y,
ps->ncp.x, ps->ncp.y, ps->ncp.x+40*arcmin, ps->ncp.y,
ps->ncp.x-2*arcmin+2, ps->ncp.y, ps->pixel_scale < 24 ? "2\\'" : "",
ps->ncp.x-5*arcmin+2, ps->ncp.y, ps->pixel_scale < 24 ? "5\\'" : "",
ps->ncp.x-10*arcmin+2, ps->ncp.y, ps->pixel_scale < 24 ? "10\\'" : "",
ps->ncp.x-20*arcmin+2, ps->ncp.y, "20\\'",
ps->ncp.x-40*arcmin+2, ps->ncp.y, "40\\'",
// Current axis
ps->axis.x-5*arcmin, ps->axis.y-5*arcmin, ps->axis.x+5*arcmin, ps->axis.y+5*arcmin,
ps->axis.x-5*arcmin, ps->axis.y+5*arcmin, ps->axis.x+5*arcmin, ps->axis.y-5*arcmin,
ps->axis.x, ps->axis.y, ps->axis.x+2*arcmin, ps->axis.y,
ps->axis.x, ps->axis.y, ps->axis.x+5*arcmin, ps->axis.y,
// Polaris
ps->polaris.x, ps->polaris.y-1*arcmin,
ps->polaris.x, ps->polaris.y+1*arcmin,
ps->polaris.x-1*arcmin, ps->polaris.y,
ps->polaris.x+1*arcmin, ps->polaris.y,
ps->polaris.x+1*arcmin, ps->polaris.y-1*arcmin, "a",
// λ UMi
ps->lambda.x, ps->lambda.y-1*arcmin,
ps->lambda.x, ps->lambda.y+1*arcmin,
ps->lambda.x-1*arcmin, ps->lambda.y,
ps->lambda.x+1*arcmin, ps->lambda.y,
ps->lambda.x+1*arcmin, ps->lambda.y-1*arcmin, "l",
// Offset report
cropx + 16, cropy + 32, ps->ncp.x-ps->axis.x, ps->ncp.y-ps->axis.y,
cropx + 16, cropy + 64,
(ps->ncp.x == ps->axis.x && ps->ncp.y == ps->axis.y)
? "Well done, perfect alignment!"
: "Adjust mount alignment to",
(ps->ncp.x == ps->axis.x && ps->ncp.y == ps->axis.y)
? ""
: ps->ncp.x < ps->axis.x ? "left" : "right",
(ps->ncp.x == ps->axis.x && ps->ncp.y == ps->axis.y) ? "" : "and",
(ps->ncp.x == ps->axis.x && ps->ncp.y == ps->axis.y)
? ""
: ps->ncp.y < ps->axis.y ? "up" : "down",
// Crop
cropwidth, cropheight, cropx, cropy,
in, out);
printf("%s\n", convert);
return system(convert);
}
int main (int argc, char **argv)
{
char dir[20] = "/tmp/polar-XXXXXX";
char h_dst[30];
char v_dst[30];
sip_t *sip;
struct state ps = { NULL, NULL, 0,
{ 0, 0, 0, 0 }, // NCP
{ 37.9529, 89.2642, 0, 0 }, // Polaris
{ 259.2367, 89.0378, 0, 0 }, // λ UMi
{ 0, 0, 0, 0 } // axis
};
if (argc < 3) {
printf("E: Not enough parameters!\n");
printf("Usage: %s <horizontal image> <vertical image> [output]\n", argv[0]);
return -1;
}
if (mkdtemp(dir) == NULL) {
printf("E: Could not create working directory!\n");
return -1;
}
// Calculate current ra,dec position of North Celestial Pole
calculate_ncp(julian_date(), &ps.ncp);
// Solve horizontal and vertical images of Polaris and Lambda UMi
sprintf(h_dst, "%s/h.wcs", dir);
sprintf(v_dst, "%s/v.wcs", dir);
solve_field(&ps, dir, argv[1], "h.wcs");
solve_field(&ps, dir, argv[2], "v.wcs");
// Pick pixel coordinates from horizontal image
ps.h_wcs = anwcs_open(h_dst, 0);
anwcs_radec2pixelxy(ps.h_wcs, ps.polaris.ra, ps.polaris.dec, &ps.polaris.x, &ps.polaris.y);
anwcs_radec2pixelxy(ps.h_wcs, ps.lambda.ra, ps.lambda.dec, &ps.lambda.x, &ps.lambda.y);
anwcs_radec2pixelxy(ps.h_wcs, ps.ncp.ra, ps.ncp.dec, &ps.ncp.x, &ps.ncp.y);
// Solve rotational axis in pixel coordinates of the horizontal image
ps.v_wcs = anwcs_open(v_dst, 0);
solve_axis(&ps);
anwcs_pixelxy2radec(ps.h_wcs, ps.axis.x, ps.axis.y, &ps.axis.ra, &ps.axis.dec);
anwcs_free(ps.v_wcs);
// Grab pixel scale from horizontal image
sip = anwcs_get_sip(ps.h_wcs);
ps.pixel_scale = sip_pixel_scale(sip);
anwcs_free(ps.h_wcs);
// Print what we found
printf("Pixel scale: %.4f\n", ps.pixel_scale);
printf("Polaris: %+9.4f ra, %+9.4f dec (%4.0f, %4.0f)\n",
ps.lambda.ra, ps.lambda.dec, ps.lambda.x, ps.lambda.y);
printf("λ UMi : %+9.4f ra, %+9.4f dec (%4.0f, %4.0f)\n",
ps.polaris.ra, ps.polaris.dec, ps.polaris.x, ps.polaris.y);
printf("NCP : %+9.4f ra, %+9.4f dec (%4.0f, %4.0f)\n",
ps.ncp.ra, ps.ncp.dec, ps.ncp.x, ps.ncp.y);
printf("Axis : %+9.4f ra, %+9.4f dec (%4.0f, %4.0f)\n",
ps.axis.ra, ps.axis.dec, ps.axis.x, ps.axis.y);
printf("Offset : %4.0f x, %4.0f y\n",
ps.ncp.x-ps.axis.x, ps.ncp.y-ps.axis.y);
// Plot a chart of the polar alignment, if user asks for it
if (argc == 4)
plot(&ps, argv[1], argv[3]);
return 0;
}
| {
"alphanum_fraction": 0.54617737,
"avg_line_length": 33.9446366782,
"ext": "c",
"hexsha": "5515141bfd3b70832de14c563a95e653416ce473",
"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": "61bf261c7921d289e0bb9addb0a22b219e895503",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "zuh/starflow",
"max_forks_repo_path": "polar-plot/polar-plot.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "61bf261c7921d289e0bb9addb0a22b219e895503",
"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": "zuh/starflow",
"max_issues_repo_path": "polar-plot/polar-plot.c",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "61bf261c7921d289e0bb9addb0a22b219e895503",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "zuh/starflow",
"max_stars_repo_path": "polar-plot/polar-plot.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3537,
"size": 9810
} |
/* histogram/test2d.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 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 <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_machine.h>
#include <gsl/gsl_histogram2d.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#define M 107
#define N 239
#define M1 17
#define N1 23
#define MR 10
#define NR 5
void
test2d (void)
{
double xr[MR + 1] =
{ 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 };
double yr[NR + 1] = { 90.0, 91.0, 92.0, 93.0, 94.0, 95.0 };
gsl_histogram2d *h, *h1, *g, *hr;
size_t i, j, k;
gsl_ieee_env_setup ();
h = gsl_histogram2d_calloc (M, N);
h1 = gsl_histogram2d_calloc (M, N);
g = gsl_histogram2d_calloc (M, N);
gsl_test (h->xrange == 0,
"gsl_histogram2d_calloc returns valid xrange pointer");
gsl_test (h->yrange == 0,
"gsl_histogram2d_calloc returns valid yrange pointer");
gsl_test (h->bin == 0, "gsl_histogram2d_calloc returns valid bin pointer");
gsl_test (h->nx != M, "gsl_histogram2d_calloc returns valid nx");
gsl_test (h->ny != N, "gsl_histogram2d_calloc returns valid ny");
hr = gsl_histogram2d_calloc_range (MR, NR, xr, yr);
gsl_test (hr->xrange == 0,
"gsl_histogram2d_calloc_range returns valid xrange pointer");
gsl_test (hr->yrange == 0,
"gsl_histogram2d_calloc_range returns valid yrange pointer");
gsl_test (hr->bin == 0,
"gsl_histogram2d_calloc_range returns valid bin pointer");
gsl_test (hr->nx != MR, "gsl_histogram2d_calloc_range returns valid nx");
gsl_test (hr->ny != NR, "gsl_histogram2d_calloc_range returns valid ny");
{
int status = 0;
for (i = 0; i <= MR; i++)
{
if (hr->xrange[i] != xr[i])
{
status = 1;
}
};
gsl_test (status,
"gsl_histogram2d_calloc_range creates xrange");
}
{
int status = 0;
for (i = 0; i <= NR; i++)
{
if (hr->yrange[i] != yr[i])
{
status = 1;
}
};
gsl_test (status,
"gsl_histogram2d_calloc_range creates yrange");
}
for (i = 0; i <= MR; i++)
{
hr->xrange[i] = 0.0;
}
for (i = 0; i <= NR; i++)
{
hr->yrange[i] = 0.0;
}
{
int status = gsl_histogram2d_set_ranges (hr, xr, MR + 1, yr, NR + 1);
for (i = 0; i <= MR; i++)
{
if (hr->xrange[i] != xr[i])
{
status = 1;
}
};
gsl_test (status, "gsl_histogram2d_set_ranges sets xrange");
}
{
int status = 0;
for (i = 0; i <= NR; i++)
{
if (hr->yrange[i] != yr[i])
{
status = 1;
}
};
gsl_test (status, "gsl_histogram2d_set_ranges sets yrange");
}
k = 0;
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
k++;
gsl_histogram2d_accumulate (h, (double) i, (double) j, (double) k);
};
}
{
int status = 0;
k = 0;
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
k++;
if (h->bin[i * N + j] != (double) k)
{
status = 1;
}
}
}
gsl_test (status,
"gsl_histogram2d_accumulate writes into array");
}
{
int status = 0;
k = 0;
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
k++;
if (gsl_histogram2d_get (h, i, j) != (double) k)
status = 1;
};
}
gsl_test (status, "gsl_histogram2d_get reads from array");
}
for (i = 0; i <= M; i++)
{
h1->xrange[i] = 100.0 + i;
}
for (i = 0; i <= N; i++)
{
h1->yrange[i] = 900.0 + i * i;
}
gsl_histogram2d_memcpy (h1, h);
{
int status = 0;
for (i = 0; i <= M; i++)
{
if (h1->xrange[i] != h->xrange[i])
status = 1;
};
gsl_test (status, "gsl_histogram2d_memcpy copies bin xranges");
}
{
int status = 0;
for (i = 0; i <= N; i++)
{
if (h1->yrange[i] != h->yrange[i])
status = 1;
};
gsl_test (status, "gsl_histogram2d_memcpy copies bin yranges");
}
{
int status = 0;
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
if (gsl_histogram2d_get (h1, i, j) !=
gsl_histogram2d_get (h, i, j))
status = 1;
}
}
gsl_test (status, "gsl_histogram2d_memcpy copies bin values");
}
gsl_histogram2d_free (h1);
h1 = gsl_histogram2d_clone (h);
{
int status = 0;
for (i = 0; i <= M; i++)
{
if (h1->xrange[i] != h->xrange[i])
status = 1;
};
gsl_test (status, "gsl_histogram2d_clone copies bin xranges");
}
{
int status = 0;
for (i = 0; i <= N; i++)
{
if (h1->yrange[i] != h->yrange[i])
status = 1;
};
gsl_test (status, "gsl_histogram2d_clone copies bin yranges");
}
{
int status = 0;
for (i = 0; i < M; i++)
{
for (j = 0; j < N; j++)
{
if (gsl_histogram2d_get (h1, i, j) !=
gsl_histogram2d_get (h, i, j))
status = 1;
}
}
gsl_test (status, "gsl_histogram2d_clone copies bin values");
}
gsl_histogram2d_reset (h);
{
int status = 0;
for (i = 0; i < M * N; i++)
{
if (h->bin[i] != 0)
status = 1;
}
gsl_test (status, "gsl_histogram2d_reset zeros array");
}
gsl_histogram2d_free (h);
h = gsl_histogram2d_calloc (M1, N1);
{
int status = 0;
for (i = 0; i < M1; i++)
{
for (j = 0; j < N1; j++)
{
gsl_histogram2d_increment (h, (double) i, (double) j);
for (k = 0; k <= i * N1 + j; k++)
{
if (h->bin[k] != 1)
{
status = 1;
}
}
for (k = i * N1 + j + 1; k < M1 * N1; k++)
{
if (h->bin[k] != 0)
{
status = 1;
}
}
}
}
gsl_test (status, "gsl_histogram2d_increment increases bin value");
}
gsl_histogram2d_free (h);
h = gsl_histogram2d_calloc (M, N);
{
int status = 0;
for (i = 0; i < M; i++)
{
double x0 = 0, x1 = 0;
gsl_histogram2d_get_xrange (h, i, &x0, &x1);
if (x0 != i || x1 != i + 1)
{
status = 1;
}
}
gsl_test (status,
"gsl_histogram2d_get_xlowerlimit and xupperlimit");
}
{
int status = 0;
for (i = 0; i < N; i++)
{
double y0 = 0, y1 = 0;
gsl_histogram2d_get_yrange (h, i, &y0, &y1);
if (y0 != i || y1 != i + 1)
{
status = 1;
}
}
gsl_test (status,
"gsl_histogram2d_get_ylowerlimit and yupperlimit");
}
{
int status = 0;
if (gsl_histogram2d_xmax (h) != M)
status = 1;
gsl_test (status, "gsl_histogram2d_xmax");
}
{
int status = 0;
if (gsl_histogram2d_xmin (h) != 0)
status = 1;
gsl_test (status, "gsl_histogram2d_xmin");
}
{
int status = 0;
if (gsl_histogram2d_nx (h) != M)
status = 1;
gsl_test (status, "gsl_histogram2d_nx");
}
{
int status = 0;
if (gsl_histogram2d_ymax (h) != N)
status = 1;
gsl_test (status, "gsl_histogram2d_ymax");
}
{
int status = 0;
if (gsl_histogram2d_ymin (h) != 0)
status = 1;
gsl_test (status, "gsl_histogram2d_ymin");
}
{
int status = 0;
if (gsl_histogram2d_ny (h) != N)
status = 1;
gsl_test (status, "gsl_histogram2d_ny");
}
h->bin[3 * N + 2] = 123456.0;
h->bin[4 * N + 3] = -654321;
{
double max = gsl_histogram2d_max_val (h);
gsl_test (max != 123456.0, "gsl_histogram2d_max_val finds maximum value");
}
{
double min = gsl_histogram2d_min_val (h);
gsl_test (min != -654321.0,
"gsl_histogram2d_min_val finds minimum value");
}
{
size_t imax, jmax;
gsl_histogram2d_max_bin (h, &imax, &jmax);
gsl_test (imax != 3
|| jmax != 2,
"gsl_histogram2d_max_bin finds maximum value bin");
}
{
size_t imin, jmin;
gsl_histogram2d_min_bin (h, &imin, &jmin);
gsl_test (imin != 4
|| jmin != 3, "gsl_histogram2d_min_bin find minimum value bin");
}
for (i = 0; i < M * N; i++)
{
h->bin[i] = i + 27;
g->bin[i] = (i + 27) * (i + 1);
}
{
double sum = gsl_histogram2d_sum (h);
gsl_test (sum != N * M * 27 + ((N * M - 1) * N * M) / 2,
"gsl_histogram2d_sum sums all bin values");
}
{
/* first test... */
const double xpos = 0.6;
const double ypos = 0.85;
double xmean;
double ymean;
size_t xbin;
size_t ybin;
gsl_histogram2d *h3 = gsl_histogram2d_alloc (M, N);
gsl_histogram2d_set_ranges_uniform (h3, 0, 1, 0, 1);
gsl_histogram2d_increment (h3, xpos, ypos);
gsl_histogram2d_find (h3, xpos, ypos, &xbin, &ybin);
xmean = gsl_histogram2d_xmean (h3);
ymean = gsl_histogram2d_ymean (h3);
{
double expected_xmean = (h3->xrange[xbin] + h3->xrange[xbin + 1]) / 2.0;
double expected_ymean = (h3->yrange[ybin] + h3->yrange[ybin + 1]) / 2.0;
gsl_test_abs (xmean, expected_xmean, 100.0 * GSL_DBL_EPSILON,
"gsl_histogram2d_xmean");
gsl_test_abs (ymean, expected_ymean, 100.0 * GSL_DBL_EPSILON,
"gsl_histogram2d_ymean");
};
gsl_histogram2d_free (h3);
}
{
/* test it with bivariate normal distribution */
const double xmean = 0.7;
const double ymean = 0.7;
const double xsigma = 0.1;
const double ysigma = 0.1;
const double correl = 0.5;
const double norm =
10.0 / M_PI / xsigma / ysigma / sqrt (1.0 - correl * correl);
size_t xbin;
size_t ybin;
gsl_histogram2d *h3 = gsl_histogram2d_alloc (M, N);
gsl_histogram2d_set_ranges_uniform (h3, 0, 1, 0, 1);
/* initialize with 2d gauss pdf in two directions */
for (xbin = 0; xbin < M; xbin++)
{
double xi =
((h3->xrange[xbin] + h3->xrange[xbin + 1]) / 2.0 - xmean) / xsigma;
for (ybin = 0; ybin < N; ybin++)
{
double yi =
((h3->yrange[ybin] + h3->yrange[ybin + 1]) / 2.0 -
ymean) / ysigma;
double prob =
norm * exp (-(xi * xi - 2.0 * correl * xi * yi + yi * yi) /
2.0 / (1 - correl * correl));
h3->bin[xbin * N + ybin] = prob;
}
}
{
double xs = gsl_histogram2d_xsigma (h3);
double ys = gsl_histogram2d_ysigma (h3);
/* evaluate results and compare with parameters */
gsl_test_abs (gsl_histogram2d_xmean (h3), xmean, 2.0/M,
"gsl_histogram2d_xmean histogram mean(x)");
gsl_test_abs (gsl_histogram2d_ymean (h3), ymean, 2.0/N,
"gsl_histogram2d_ymean histogram mean(y)");
gsl_test_abs (xs, xsigma, 2.0/M,
"gsl_histogram2d_xsigma histogram stdev(x)");
gsl_test_abs (ys, ysigma, 2.0/N,
"gsl_histogram2d_ysigma histogram stdev(y)");
gsl_test_abs (gsl_histogram2d_cov (h3) / xs / ys, correl,
2.0/((M < N) ? M : N),
"gsl_histogram2d_cov histogram covariance");
}
gsl_histogram2d_free (h3);
}
gsl_histogram2d_memcpy (h1, g);
gsl_histogram2d_add (h1, h);
{
int status = 0;
for (i = 0; i < M * N; i++)
{
if (h1->bin[i] != g->bin[i] + h->bin[i])
status = 1;
}
gsl_test (status, "gsl_histogram2d_add histogram addition");
}
gsl_histogram2d_memcpy (h1, g);
gsl_histogram2d_sub (h1, h);
{
int status = 0;
for (i = 0; i < M * N; i++)
{
if (h1->bin[i] != g->bin[i] - h->bin[i])
status = 1;
}
gsl_test (status, "gsl_histogram2d_sub histogram subtraction");
}
gsl_histogram2d_memcpy (h1, g);
gsl_histogram2d_mul (h1, h);
{
int status = 0;
for (i = 0; i < M * N; i++)
{
if (h1->bin[i] != g->bin[i] * h->bin[i])
status = 1;
}
gsl_test (status, "gsl_histogram2d_mul histogram multiplication");
}
gsl_histogram2d_memcpy (h1, g);
gsl_histogram2d_div (h1, h);
{
int status = 0;
for (i = 0; i < M * N; i++)
{
if (h1->bin[i] != g->bin[i] / h->bin[i])
status = 1;
}
gsl_test (status, "gsl_histogram2d_div histogram division");
}
gsl_histogram2d_memcpy (h1, g);
gsl_histogram2d_scale (h1, 0.5);
{
int status = 0;
for (i = 0; i < M * N; i++)
{
if (h1->bin[i] != 0.5 * g->bin[i])
status = 1;
}
gsl_test (status, "gsl_histogram2d_scale histogram scaling");
}
gsl_histogram2d_memcpy (h1, g);
gsl_histogram2d_shift (h1, 0.25);
{
int status = 0;
for (i = 0; i < M * N; i++)
{
if (h1->bin[i] != 0.25 + g->bin[i])
status = 1;
}
gsl_test (status, "gsl_histogram2d_shift histogram shift");
}
gsl_histogram2d_free (h); /* free whatever is in h */
h = gsl_histogram2d_calloc_uniform (M1, N1, 0.0, 5.0, 0.0, 5.0);
gsl_test (h->xrange == 0,
"gsl_histogram2d_calloc_uniform returns valid range pointer");
gsl_test (h->yrange == 0,
"gsl_histogram2d_calloc_uniform returns valid range pointer");
gsl_test (h->bin == 0,
"gsl_histogram2d_calloc_uniform returns valid bin pointer");
gsl_test (h->nx != M1, "gsl_histogram2d_calloc_uniform returns valid nx");
gsl_test (h->ny != N1, "gsl_histogram2d_calloc_uniform returns valid ny");
gsl_histogram2d_accumulate (h, 0.0, 3.01, 1.0);
gsl_histogram2d_accumulate (h, 0.1, 2.01, 2.0);
gsl_histogram2d_accumulate (h, 0.2, 1.01, 3.0);
gsl_histogram2d_accumulate (h, 0.3, 0.01, 4.0);
{
size_t i1, i2, i3, i4;
size_t j1, j2, j3, j4;
double expected;
int status;
status = gsl_histogram2d_find (h, 0.0, 3.01, &i1, &j1);
status = gsl_histogram2d_find (h, 0.1, 2.01, &i2, &j2);
status = gsl_histogram2d_find (h, 0.2, 1.01, &i3, &j3);
status = gsl_histogram2d_find (h, 0.3, 0.01, &i4, &j4);
for (i = 0; i < M1; i++)
{
for (j = 0; j < N1; j++)
{
if (i == i1 && j == j1)
{
expected = 1.0;
}
else if (i == i2 && j == j2)
{
expected = 2.0;
}
else if (i == i3 && j == j3)
{
expected = 3.0;
}
else if (i == i4 && j == j4)
{
expected = 4.0;
}
else
{
expected = 0.0;
}
if (h->bin[i * N1 + j] != expected)
{
status = 1;
}
}
}
gsl_test (status, "gsl_histogram2d_find returns index");
}
{
FILE *f = fopen ("test.txt", "w");
gsl_histogram2d_fprintf (f, h, "%.19e", "%.19e");
fclose (f);
}
{
FILE *f = fopen ("test.txt", "r");
gsl_histogram2d *hh = gsl_histogram2d_calloc (M1, N1);
int status = 0;
gsl_histogram2d_fscanf (f, hh);
for (i = 0; i <= M1; i++)
{
if (h->xrange[i] != hh->xrange[i])
{
printf ("xrange[%d] : %g orig vs %g\n",
(int) i, h->xrange[i], hh->xrange[i]);
status = 1;
}
}
for (j = 0; j <= N1; j++)
{
if (h->yrange[j] != hh->yrange[j])
{
printf ("yrange[%d] : %g orig vs %g\n",
(int) j, h->yrange[j], hh->yrange[j]);
status = 1;
}
}
for (i = 0; i < M1 * N1; i++)
{
if (h->bin[i] != hh->bin[i])
{
printf ("bin[%d] : %g orig vs %g\n",
(int) i, h->bin[i], hh->bin[i]);
status = 1;
}
}
gsl_test (status, "gsl_histogram2d_fprintf and fscanf");
gsl_histogram2d_free (hh);
fclose (f);
}
{
FILE *f = fopen ("test.dat", "wb");
gsl_histogram2d_fwrite (f, h);
fclose (f);
}
{
FILE *f = fopen ("test.dat", "rb");
gsl_histogram2d *hh = gsl_histogram2d_calloc (M1, N1);
int status = 0;
gsl_histogram2d_fread (f, hh);
for (i = 0; i <= M1; i++)
{
if (h->xrange[i] != hh->xrange[i])
{
printf ("xrange[%d] : %g orig vs %g\n",
(int) i, h->xrange[i], hh->xrange[i]);
status = 1;
}
}
for (j = 0; j <= N1; j++)
{
if (h->yrange[j] != hh->yrange[j])
{
printf ("yrange[%d] : %g orig vs %g\n",
(int) j, h->yrange[j], hh->yrange[j]);
status = 1;
}
}
for (i = 0; i < M1 * N1; i++)
{
if (h->bin[i] != hh->bin[i])
{
printf ("bin[%d] : %g orig vs %g\n",
(int) i, h->bin[i], hh->bin[i]);
status = 1;
}
}
gsl_test (status, "gsl_histogram2d_fwrite and fread");
gsl_histogram2d_free (hh);
fclose (f);
}
gsl_histogram2d_free (h);
gsl_histogram2d_free (h1);
gsl_histogram2d_free (g);
gsl_histogram2d_free (hr);
}
| {
"alphanum_fraction": 0.4972931591,
"avg_line_length": 24.2533156499,
"ext": "c",
"hexsha": "36daf6a6d39c001012d2a16f2e6ce320e1575e9b",
"lang": "C",
"max_forks_count": 224,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z",
"max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "utdsimmons/ohpc",
"max_forks_repo_path": "tests/libs/gsl/tests/histogram/test2d.c",
"max_issues_count": 1096,
"max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "utdsimmons/ohpc",
"max_issues_repo_path": "tests/libs/gsl/tests/histogram/test2d.c",
"max_line_length": 81,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/histogram/test2d.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z",
"num_tokens": 6058,
"size": 18287
} |
#pragma once
#ifndef __CONSTANTS_H__
#define __CONSTANTS_H__
/***************************************************
*************** Auto-Generated File ***************
***************************************************/
#include <cstring>
#include <string>
#include <gsl/gsl_math.h>
#include "../../Utils/BinarySearch.h"
constexpr const int numConstants = 4;
constexpr const char* constants[numConstants] = {
"e", "gamma", "pi", "vphi"
};
constexpr const double constantValues[numConstants] = {
M_E, M_EULER, M_PI, 1.618033988749895
};
const std::string shortConstants[numConstants] = {
"e", "γ", "π", "ϕ"
};
constexpr const char * constantLongValues[numConstants] = {
"2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932",
"0.5772156649015328606065120900824024310421593359399235988057672348848677267776646709369470632917467495146314472498",
"3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328",
"1.61803398874989484820458683436563811772030917980576286213544862270526046281890244970720720418939113748475408807538"
};
constexpr const int longestConstantName = 5;
constexpr const int shortestConstantName = 1;
/*
Returns index of the constant in the constants array.
Uses binary search under the hood to search for the index.
Parameters
----------
name: The name of the constant
Returns
-------
The index or -1 if the provided name is not a constant.
*/
CONSTEXPR_BINARY_SEARCH(getConstantIndex, constants, numConstants)
/*
Returns the value of the constant at the provided index.
Parameters
----------
index: the index of the constant name
Returns
-------
If the index is valid, it will return the number of arguments.
If the index is not valid, the function will return 0.
Note: a return value of -1 means that it accepts a variable number of parameters.
*/
static double getConstantValue(const std::string& name){
int index = getConstantIndex(name.c_str());
if (index != -1){
return constantValues[index];
}
return GSL_NAN;
}
constexpr double getConstantValue(int index){
if (index >= 0 && index < numConstants){
return constantValues[index];
}
return GSL_NAN;
}
#endif // __CONSTANTS_H__
| {
"alphanum_fraction": 0.7168989547,
"avg_line_length": 28.7,
"ext": "h",
"hexsha": "3018a0b4dfc190ad727590f0627fab6110d4fc58",
"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/VariableExpressions/Constants.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/VariableExpressions/Constants.h",
"max_line_length": 120,
"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/VariableExpressions/Constants.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 575,
"size": 2296
} |
#pragma once
#include "rev/gl/Context.h"
#include "rev/gl/Resource.h"
#include "rev/gl/Uniform.h"
#include <array>
#include <gsl/gsl_assert>
#include <string>
namespace rev {
template <GLenum shaderType>
GLuint createShader()
{
return glCreateShader(shaderType);
}
namespace detail {
template <void (*propertyGetter)(GLuint, GLenum, GLint*),
void (*logGetter)(GLuint, GLsizei, GLsizei*, GLchar*)>
std::string extractLog(GLuint objectId)
{
GLint logLength;
propertyGetter(objectId, GL_INFO_LOG_LENGTH, &logLength);
std::string log;
log.resize(logLength);
GLint fetchedLength;
logGetter(objectId, logLength, &fetchedLength, log.data());
log.resize(fetchedLength);
return log;
}
} // namespace detail
template <GLenum shaderType>
class Shader : public Resource<createShader<shaderType>, gl::deleteShader> {
public:
void setSource(const std::string_view& source)
{
setSource(std::array<std::string_view, 1>{ source });
}
template <size_t arrayLength>
void setSource(const std::array<std::string_view, arrayLength>& source)
{
std::array<const char*, arrayLength> pointers;
std::array<GLint, arrayLength> lengths;
for (size_t i = 0; i < arrayLength; i++) {
pointers[i] = source[i].data();
lengths[i] = static_cast<GLint>(source[i].size());
Expects(source[i].size() <= std::numeric_limits<GLint>::max());
}
glShaderSource(this->getId(), arrayLength, pointers.data(), lengths.data());
}
void compile() { glCompileShader(this->getId()); }
bool getCompileStatus()
{
GLint status;
glGetShaderiv(this->getId(), GL_COMPILE_STATUS, &status);
return (status == GL_TRUE);
}
std::string getCompileLog()
{
return detail::extractLog<gl::getShaderiv, gl::getShaderInfoLog>(this->getId());
}
};
using VertexShader = Shader<GL_VERTEX_SHADER>;
using FragmentShader = Shader<GL_FRAGMENT_SHADER>;
class ProgramResource : public Resource<gl::createProgram, gl::deleteProgram> {
public:
template <GLenum shaderType>
void attachShader(const Shader<shaderType>& shader)
{
glAttachShader(getId(), shader.getId());
}
void link() { glLinkProgram(getId()); }
bool getLinkStatus()
{
GLint status;
glGetProgramiv(getId(), GL_LINK_STATUS, &status);
return (status == GL_TRUE);
}
std::string getLinkLog()
{
return detail::extractLog<gl::getProgramiv, gl::getProgramInfoLog>(getId());
}
template <typename VertexSourceType, typename FragmentSourceType>
void buildWithSource(
const VertexSourceType& vertexSource, const FragmentSourceType& fragmentSource)
{
VertexShader vShader;
vShader.setSource(vertexSource);
vShader.compile();
if (!vShader.getCompileStatus()) {
throw vShader.getCompileLog();
}
FragmentShader fShader;
fShader.setSource(fragmentSource);
fShader.compile();
if (!fShader.getCompileStatus()) {
throw fShader.getCompileLog();
}
attachShader(vShader);
attachShader(fShader);
link();
if (!getLinkStatus()) {
throw getLinkLog();
}
}
template <typename VariableType>
Uniform<VariableType> getUniform(const char* name)
{
GLint location = glGetUniformLocation(getId(), name);
return Uniform<VariableType>(location);
}
};
using ProgramContext = ResourceContext<ProgramResource, gl::useProgram>;
} // namespace rev
| {
"alphanum_fraction": 0.6386165577,
"avg_line_length": 26.6086956522,
"ext": "h",
"hexsha": "c486cfe962e21740e6a8e75576b215e7b7462891",
"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": "d8abdf0a0016e309942932c9af9df1f8a2b02448",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "eyebrowsoffire/rev",
"max_forks_repo_path": "engine/include/rev/gl/ProgramResource.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448",
"max_issues_repo_issues_event_max_datetime": "2019-01-27T16:52:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-01-27T16:52:41.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "eyebrowsoffire/rev",
"max_issues_repo_path": "engine/include/rev/gl/ProgramResource.h",
"max_line_length": 88,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "d8abdf0a0016e309942932c9af9df1f8a2b02448",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "eyebrowsoffire/rev",
"max_stars_repo_path": "engine/include/rev/gl/ProgramResource.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 830,
"size": 3672
} |
#include <iostream>
#include <math.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_wavelet2d.h>
#include <cgi/mosaic/Mosaic.hpp>
void normalizeBySum(double* data, int n)
{
int sum = 0;
for(int i=0; i<n; ++i)
sum += data[i];
for(int i=0; i<n; ++i)
data[i] /= sum;
}
int
main (int argc, char **argv)
{
const int n = 1024;
if(argc < 2)
{
std::cout << "ERROR" << std::endl;
return 1;
}
cgi::Mosaic m;
if(cgi::NoError != m.open(argv[1]))
{
std::cout << "Failed to open" << std::endl;
return 2;
}
m.setTileSize(cgi::core::Size2d<int>(n,n));
double* data = new double [n * n];
if(cgi::NoError != m.getTile<double>(0, 0, data))
{
std::cout << "getTile failed" << std::endl;
return 3;
}
gsl_wavelet *w;
gsl_wavelet_workspace *work;
w = gsl_wavelet_alloc (gsl_wavelet_daubechies, 4);
work = gsl_wavelet_workspace_alloc (n);
if(GSL_SUCCESS != gsl_wavelet2d_transform_forward (w, data, n, n, n, work))
{
std::cout << "Transform failed" << std::endl;
return 4;
}
/////////////////////////////////////////
cgi::Mosaic moDwt;
moDwt.create("dwt.tif", "GTiff", cgi::core::Size2d<int>(n,n), 1, cgi::Depth64F);
moDwt.setTileSize(cgi::core::Size2d<int>(n,n));
moDwt.putTile<double>(data, 0, 0);
moDwt.close();
/////////////////////////////////////////
// normalization
normalizeBySum(data, n);
/////////////////////////////////////////
// do the inverse and reconstruct the image
if(GSL_SUCCESS != gsl_wavelet2d_transform_inverse (w, data, n, n, n, work))
{
std::cout << "Transform failed" << std::endl;
return 5;
}
/////////////////////////////////////////
// convert the reconstructed image to unsigned short
unsigned short* recData = new unsigned short [n * n];
int i;
for(i=0; i<(n*n); ++i)
{
recData[i] = static_cast<unsigned short>(std::max(std::min(data[i], 65535.0), 0.0));
}
cgi::Mosaic moRec;
moRec.create("rec.tif", "GTiff", cgi::core::Size2d<int>(n,n), 1, cgi::Depth16U);
moRec.setTileSize(cgi::core::Size2d<int>(n,n));
moRec.putTile<unsigned short>(recData, 0, 0);
moRec.close();
/////////////////////////////////////////
gsl_wavelet_free (w);
gsl_wavelet_workspace_free (work);
delete [] recData;
delete [] data;
return 0;
}
| {
"alphanum_fraction": 0.5441487114,
"avg_line_length": 22.7596153846,
"ext": "c",
"hexsha": "2f1a9ca889a5f242e23ca1189a9a9b809baea598",
"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": "a1ae04c13a2209dee013284358d2d987bb0fb4fc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "klaricmn/snippets",
"max_forks_repo_path": "gsl_wavelet/dwt2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a1ae04c13a2209dee013284358d2d987bb0fb4fc",
"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": "klaricmn/snippets",
"max_issues_repo_path": "gsl_wavelet/dwt2.c",
"max_line_length": 90,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a1ae04c13a2209dee013284358d2d987bb0fb4fc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "klaricmn/snippets",
"max_stars_repo_path": "gsl_wavelet/dwt2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 740,
"size": 2367
} |
#ifndef _CALCLAMBDA_CHISQ_DIST
#define _CALCLAMBDA_CHISQ_DIST
#include <gsl/gsl_blas.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#define MIN_EIGENVAL 1E-6
#define SIGINT_DEFAULT 0.001
struct chisq_dist {
int mode;
double *covmat;
double *c;
double *slope;
double *pivotmag;
double *refmag;
double *refmagerr;
double *magerr;
double *color;
double *col_err_ratio;
double *lupcorr;
int ncalc;
int ngal;
int nz;
int ncol;
double sigint;
// long do_chisq;
//long nophotoerr;
};
int chisq_dist(int mode, int do_chisq, int nophotoerr, int ncalc, int ncol, double *covmat, double *c, double *slope, double *pivotmag, double *refmag, double *refmagerr, double *magerr, double *color, double *lupcorr, double *dist, double sigint);
int check_and_fix_covmat(gsl_matrix *covmat);
#endif
| {
"alphanum_fraction": 0.7026406429,
"avg_line_length": 21.243902439,
"ext": "h",
"hexsha": "6da71568726c679d7fe7112eed79f37b1c829d5d",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2020-11-14T07:41:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-01-26T01:38:41.000Z",
"max_forks_repo_head_hexsha": "23fb66c7369de784c67ce6c41ada2f1f51a84acb",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "erykoff/redmapper",
"max_forks_repo_path": "redmapper/chisq_dist/chisq_dist.h",
"max_issues_count": 42,
"max_issues_repo_head_hexsha": "23fb66c7369de784c67ce6c41ada2f1f51a84acb",
"max_issues_repo_issues_event_max_datetime": "2022-01-31T20:47:51.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-07-27T20:48:20.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "erykoff/redmapper",
"max_issues_repo_path": "redmapper/chisq_dist/chisq_dist.h",
"max_line_length": 248,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "23fb66c7369de784c67ce6c41ada2f1f51a84acb",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "erykoff/redmapper",
"max_stars_repo_path": "redmapper/chisq_dist/chisq_dist.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-03T15:17:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-03-06T07:51:02.000Z",
"num_tokens": 275,
"size": 871
} |
/**
*
* @file core_dgeqp3_pivot.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mark Gates
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:49 2014
*
**/
#include <math.h>
#include <cblas.h>
#include "common.h"
#define A(m,n) BLKADDR( A, double, m, n )
/***************************************************************************//**
*
* @ingroup CORE_double
*
* CORE_dgeqp3_pivot finds next pivot, pvt, based on maximum column norm.
* It applies the swap to the matrices A, F, and vectors jpvt, norms1, norms2.
* If info != 0, it returns immediately, doing no work.
*
*******************************************************************************
*
* @param[in,out] A
* On entry, descriptor for m by n matrix A.
* On exit, column k of jj-th block column is swapped with column pvt.
*
* @param[in,out] F
* On entry, n by nb matrix F.
* On exit, row k is swapped with row pvt - jj*nb.
* Currently, F is stored column-wise, not tile-wise.
*
* @param[in] ldf
* Leading dimension of F. ldf >= max(1,A.n).
*
* @param[in] jj
* Index of current block column, 0 <= jj < A.nt.
*
* @param[in] k
* Index of current column within block column, 0 <= k < A.nb.
*
* @param[in,out] jpvt
* Permutation vector, dimension n.
* On exit, swaps entries jpvt[k+jj*nb] and jpvt[pvt].
*
* @param[in,out] norms1
* On entry, vector of partial column norms, dimension n.
* On exit, sets norms1[pvt] = norms1[k+jj*nb].
*
* @param[in,out] norms2
* On entry, vector of original column norms, dimension n.
* On exit, sets norms2[pvt] = norms2[k+jj*nb].
*
* @param[in] info
* Error code from dgeqp3_update; zero if no error.
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dgeqp3_pivot = PCORE_dgeqp3_pivot
#define CORE_dgeqp3_pivot PCORE_dgeqp3_pivot
#endif
void CORE_dgeqp3_pivot( PLASMA_desc A, double *F, int ldf,
int jj, int k, int *jpvt,
double *norms1, double *norms2, int *info )
{
double *Aij, *Aip;
int pvt, ii, pp, p, mb, lda, tmp, jk;
/* since pivot depends on all the norm updates, check info here
* to detect errors from dgeqp3_updates. */
if ( *info != 0 )
return;
/* jk and pvt are indices in global matrix */
jk = jj*A.nb + k;
pvt = jk + cblas_idamax( A.n - jk, &norms1[jk], 1 );
if ( pvt != jk ) {
tmp = jpvt[jk];
jpvt[jk] = jpvt[pvt];
jpvt[pvt] = tmp;
norms1[pvt] = norms1[jk]; /* don't need to save norms[pvt] */
norms2[pvt] = norms2[jk];
cblas_dswap( A.nb, &F[k], ldf, &F[pvt-jj*A.nb], ldf ); /* rows k and pvt */
pp = pvt / A.nb; /* tile containing pvt */
p = pvt % A.nb; /* index within pp tile */
for( ii = 0; ii < A.mt; ++ii ) {
mb = min( A.mb, A.m - ii*A.mb );
lda = BLKLDD( A, ii );
Aij = A(ii,jj);
Aip = A(ii,pp);
cblas_dswap( mb, &Aij[k*lda], 1, &Aip[p*lda], 1 ); /* cols k and pvt */
}
}
}
| {
"alphanum_fraction": 0.5381316998,
"avg_line_length": 31.3942307692,
"ext": "c",
"hexsha": "25eb63c644e81963f8db7f1acf6e69cd8e289782",
"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_dgeqp3_pivot.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_dgeqp3_pivot.c",
"max_line_length": 84,
"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_dgeqp3_pivot.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1004,
"size": 3265
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.