Search is not available for this dataset
text string | meta dict |
|---|---|
/* cdf/inverse_normal.c
*
* Copyright (C) 2002 Przemyslaw Sliwa and Jason H. Stover.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* Computes the inverse normal cumulative distribution function
* according to the algorithm shown in
*
* Wichura, M.J. (1988).
* Algorithm AS 241: The Percentage Points of the Normal Distribution.
* Applied Statistics, 37, 477-484.
*/
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cdf.h>
#include "rat_eval.h"
static double
small (double q)
{
const double a[8] = { 3.387132872796366608, 133.14166789178437745,
1971.5909503065514427, 13731.693765509461125,
45921.953931549871457, 67265.770927008700853,
33430.575583588128105, 2509.0809287301226727
};
const double b[8] = { 1.0, 42.313330701600911252,
687.1870074920579083, 5394.1960214247511077,
21213.794301586595867, 39307.89580009271061,
28729.085735721942674, 5226.495278852854561
};
double r = 0.180625 - q * q;
double x = q * rat_eval (a, 8, b, 8, r);
return x;
}
static double
intermediate (double r)
{
const double a[] = { 1.42343711074968357734, 4.6303378461565452959,
5.7694972214606914055, 3.64784832476320460504,
1.27045825245236838258, 0.24178072517745061177,
0.0227238449892691845833, 7.7454501427834140764e-4
};
const double b[] = { 1.0, 2.05319162663775882187,
1.6763848301838038494, 0.68976733498510000455,
0.14810397642748007459, 0.0151986665636164571966,
5.475938084995344946e-4, 1.05075007164441684324e-9
};
double x = rat_eval (a, 8, b, 8, (r - 1.6));
return x;
}
static double
tail (double r)
{
const double a[] = { 6.6579046435011037772, 5.4637849111641143699,
1.7848265399172913358, 0.29656057182850489123,
0.026532189526576123093, 0.0012426609473880784386,
2.71155556874348757815e-5, 2.01033439929228813265e-7
};
const double b[] = { 1.0, 0.59983220655588793769,
0.13692988092273580531, 0.0148753612908506148525,
7.868691311456132591e-4, 1.8463183175100546818e-5,
1.4215117583164458887e-7, 2.04426310338993978564e-15
};
double x = rat_eval (a, 8, b, 8, (r - 5.0));
return x;
}
double
gsl_cdf_ugaussian_Pinv (const double P)
{
double r, x, pp;
double dP = P - 0.5;
if (P == 1.0)
{
return GSL_POSINF;
}
else if (P == 0.0)
{
return GSL_NEGINF;
}
if (fabs (dP) <= 0.425)
{
x = small (dP);
return x;
}
pp = (P < 0.5) ? P : 1.0 - P;
r = sqrt (-log (pp));
if (r <= 5.0)
{
x = intermediate (r);
}
else
{
x = tail (r);
}
if (P < 0.5)
{
return -x;
}
else
{
return x;
}
}
double
gsl_cdf_ugaussian_Qinv (const double Q)
{
double r, x, pp;
double dQ = Q - 0.5;
if (Q == 1.0)
{
return GSL_NEGINF;
}
else if (Q == 0.0)
{
return GSL_POSINF;
}
if (fabs (dQ) <= 0.425)
{
x = small (dQ);
return -x;
}
pp = (Q < 0.5) ? Q : 1.0 - Q;
r = sqrt (-log (pp));
if (r <= 5.0)
{
x = intermediate (r);
}
else
{
x = tail (r);
}
if (Q < 0.5)
{
return x;
}
else
{
return -x;
}
}
double
gsl_cdf_gaussian_Pinv (const double P, const double sigma)
{
return sigma * gsl_cdf_ugaussian_Pinv (P);
}
double
gsl_cdf_gaussian_Qinv (const double Q, const double sigma)
{
return sigma * gsl_cdf_ugaussian_Qinv (Q);
}
| {
"alphanum_fraction": 0.6426150121,
"avg_line_length": 20.3448275862,
"ext": "c",
"hexsha": "5376b757fccbbd5bc3b7e7dc1910d96766e21cbf",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "skair39/structured",
"max_forks_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/cdf/gaussinv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "skair39/structured",
"max_issues_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/cdf/gaussinv.c",
"max_line_length": 77,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "parasol-ppl/PPL_utils",
"max_stars_repo_path": "folding_libs/gsl-1.14/cdf/gaussinv.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z",
"num_tokens": 1510,
"size": 4130
} |
#pragma once
#include <cassert>
#include <exception>
#include <functional>
#include <set>
#include <map>
#include <nod/nod.hpp>
#include <gsl-lite/gsl-lite.hpp>
#include "mutils/time/profiler.h"
#include "threadpool/threadpool.h"
#include "nodegraph/model/node.h"
#include "nodegraph/model/pin.h"
namespace NodeGraph
{
// A collection of nodes that can be computed
class Graph
{
public:
Graph();
virtual ~Graph();
virtual void Clear();
// Use this method to create nodes and add them to the m_graph
template <typename T, typename... Args>
T* CreateNode(Args&&... args)
{
PreModify();
auto pNode = new T(*this, std::forward<Args>(args)...);
nodes.insert(pNode);
m_displayNodes.insert(pNode);
m_mapIdToNode[pNode->GetId()] = pNode;
PostModify();
return pNode;
}
void DestroyNode(Node* pNode);
bool IsType(Node& node, ctti::type_id_t type) const;
template <class T>
std::set<T*> Find(ctti::type_id_t type) const
{
std::set<T*> found;
for (auto& pNode : nodes)
{
if (IsType(*pNode, type))
{
found.insert(static_cast<T*>(pNode));
}
}
return found;
}
template <class T>
std::set<T*> Find(const std::vector<ctti::type_id_t>& nodeTypes) const
{
std::set<T*> found;
for (auto& t : nodeTypes)
{
auto f = Find<T>(t);
found.insert(f.begin(), f.end());
}
return found;
}
void Visit(Node& node, PinDir dir, ParameterType type, std::function<bool(Node&)> fn);
// Get the list of pins that could be on the UI
virtual std::vector<Pin*> GetControlSurface() const;
virtual void Compute(const std::set<Node*>& nodes, int64_t numTicks);
const std::set<Node*>& GetNodes() const
{
return nodes;
}
const std::set<Node*>& GetDisplayNodes() const
{
return m_displayNodes;
}
void SetDisplayNodes(const std::set<Node*>& nodes)
{
m_displayNodes = nodes;
}
const std::set<Node*>& GetOutputNodes() const
{
return m_outputNodes;
}
void SetOutputNodes(const std::set<Node*>& nodes)
{
m_outputNodes = nodes;
}
void PreModify()
{
if (m_modifyTracker == 0)
{
sigBeginModify(this);
}
m_modifyTracker++;
}
void PostModify()
{
assert(m_modifyTracker > 0);
m_modifyTracker--;
if (m_modifyTracker == 0)
{
sigEndModify(this);
}
}
void SetName(const std::string& name);
std::string Name() const;
// Called to notify that this graph is about to be destroyed
void NotifyDestroy(Graph* pGraph);
const std::map<uint64_t, Node*>& GetNodesById() const
{
return m_mapIdToNode;
}
// Signals
nod::signal<void(Graph*)> sigBeginModify;
nod::signal<void(Graph*)> sigEndModify;
nod::signal<void(Graph*)> sigDestroy;
protected:
uint32_t m_modifyTracker = 0;
std::map<uint64_t, Node*> m_mapIdToNode;
std::set<Node*> nodes;
std::set<Node*> m_displayNodes;
std::set<Node*> m_outputNodes;
uint64_t currentGeneration = 1;
std::string m_strName;
}; // Graph
} // namespace NodeGraph
| {
"alphanum_fraction": 0.5848493886,
"avg_line_length": 21.4935897436,
"ext": "h",
"hexsha": "65e79936f304de72e8874bb19ce33918fbf72ef6",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-06-24T09:03:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-12-08T18:43:17.000Z",
"max_forks_repo_head_hexsha": "207686ac742c9e5792f4f00d5c5d594ff0a4d0df",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "cmaughan/nodegraph",
"max_forks_repo_path": "include/nodegraph/model/graph.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "207686ac742c9e5792f4f00d5c5d594ff0a4d0df",
"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": "cmaughan/nodegraph",
"max_issues_repo_path": "include/nodegraph/model/graph.h",
"max_line_length": 90,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "2eb4994c5bbf73cc9d41199fc8a309de6d1b46c9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Rezonality/nodegraph",
"max_stars_repo_path": "include/nodegraph/model/graph.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-24T02:43:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-17T20:59:33.000Z",
"num_tokens": 845,
"size": 3353
} |
static char help[] = "Assemble a Mat sparsely.\n";
#include <petsc.h>
int main(int argc,char **args) {
PetscErrorCode ierr;
Mat A;
int i1[3] = {0, 1, 2},
j1[3] = {0, 1, 2},
i2 = 3,
j2[3] = {1, 2, 3},
i3 = 1,
j3 = 3;
double aA1[9] = { 1.0, 2.0, 3.0,
2.0, 1.0, -2.0,
-1.0, 1.0, 1.0},
aA2[3] = { 1.0, 1.0, -1.0},
aA3 = -3.0;
PetscInitialize(&argc,&args,NULL,help);
ierr = MatCreate(PETSC_COMM_WORLD,&A); CHKERRQ(ierr);
ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,4,4); CHKERRQ(ierr);
ierr = MatSetFromOptions(A); CHKERRQ(ierr);
ierr = MatSetUp(A); CHKERRQ(ierr);
ierr = MatSetValues(A,3,i1,3,j1,aA1,INSERT_VALUES); CHKERRQ(ierr);
ierr = MatSetValues(A,1,&i2,3,j2,aA2,INSERT_VALUES); CHKERRQ(ierr);
ierr = MatSetValue(A,i3,j3,aA3,INSERT_VALUES); CHKERRQ(ierr);
ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
MatDestroy(&A);
return PetscFinalize();
}
| {
"alphanum_fraction": 0.5780669145,
"avg_line_length": 29.8888888889,
"ext": "c",
"hexsha": "a0362cffa0209a4ef96a8cc9da15a6f01a372d66",
"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": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mapengfei-nwpu/p4pdes",
"max_forks_repo_path": "c/ch2/sparsemat.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"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": "mapengfei-nwpu/p4pdes",
"max_issues_repo_path": "c/ch2/sparsemat.c",
"max_line_length": 69,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mapengfei-nwpu/p4pdes",
"max_stars_repo_path": "c/ch2/sparsemat.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 410,
"size": 1076
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gbpLib.h>
#include <gbpMath.h>
#include <gbpCosmo_core.h>
#include <gbpCosmo_NFW_etc.h>
#include <gsl/gsl_sf_expint.h>
// Cole and Lacey (1996) V_c(r) profile
double V_circ_NFW(double r, double M_vir, double z, int mode, cosmo_info **cosmo) {
double c_vir;
double R_vir;
double V2_c_characteristic;
double g_c;
double r_o;
double x;
double r_val = 0.;
set_NFW_params(M_vir, z, mode, cosmo, &c_vir, &R_vir);
r_o = R_vir / c_vir;
x = r / r_o;
if(x > 0.) {
V2_c_characteristic = G_NEWTON * M_vir / R_vir;
g_c = 1. / (log(1. + c_vir) - c_vir / (1. + c_vir));
r_val = sqrt(V2_c_characteristic * g_c * (log(1. + x) - x / (1. + x)) * c_vir / x);
}
return (r_val);
}
| {
"alphanum_fraction": 0.5842293907,
"avg_line_length": 27,
"ext": "c",
"hexsha": "3e0af8534e9c735f4c6a5ca5765e4cf1eb56eef2",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/V_circ_NFW.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/V_circ_NFW.c",
"max_line_length": 105,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/V_circ_NFW.c",
"max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z",
"num_tokens": 301,
"size": 837
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_vector.h>
#include "MeshAttributes.h"
#include "mathfunctions.h"
#include "oneTimeStep.h"
extern const double g;
void oneTimeStep2D (double time, double dt)
{
// store H, Qx, Qy
gsl_vector *gzeta = gsl_vector_alloc(3*NumEl);
gsl_vector *gQx = gsl_vector_alloc(3*NumEl);
gsl_vector *gQy = gsl_vector_alloc(3*NumEl);
int j = 0;
for (int i=0; i < NumEl; ++i) {
for (int k=0; k < 3; ++k){
gsl_vector_set(gzeta,j,zeta[index(i,k,3)]);
gsl_vector_set(gQx,j, Qx[index(i,k,3)]);
gsl_vector_set(gQy,j, Qy[index(i,k,3)]);
++j;
}
}
/************ print out zeta, Qx and Qy for debugging ********************/
#ifdef DEBUG
printf("Initial values:\n zeta \n");
gsl_vector_fprintf(stdout,gzeta,"%e");
printf("\n Qx \n");
gsl_vector_fprintf(stdout,gQx,"%e");
printf("\n Qy \n");
gsl_vector_fprintf(stdout,gQy,"%e");
printf("\n");
#endif
/***************************************************************************/
// Calculate the wet-dry status of the elements
// wetDryStatus2D();
// Intermediate RK step
compute2DL(time);
gsl_vector *gRHSZeta = gsl_vector_alloc(3*NumEl);
gsl_vector *gRHSQx = gsl_vector_alloc(3*NumEl);
gsl_vector *gRHSQy = gsl_vector_alloc(3*NumEl);
j = 0;
for (int i=0; i < NumEl; ++i) {
for (int k=0; k < 3; ++k){
gsl_vector_set(gRHSZeta,j,RHSZeta[index(i,k,3)]);
gsl_vector_set(gRHSQx,j,RHSQx[index(i,k,3)]);
gsl_vector_set(gRHSQy,j,RHSQy[index(i,k,3)]);
++j;
}
}
/************ print out RHSZeta, RHSQx and RHSQy for debugging ********************/
#ifdef DEBUG
printf("After first computeL:\n RHSZeta \n");
gsl_vector_fprintf(stdout,gRHSZeta,"%e");
printf("\n RHSQx \n");
gsl_vector_fprintf(stdout,gRHSQx,"%e");
printf("\n RHSQy \n");
gsl_vector_fprintf(stdout,gRHSQy,"%e");
printf("\n");
#endif
/***************************************************************************/
// w_1 = w + dt*L;
gsl_vector *gzeta_1 = gsl_vector_alloc(3*NumEl);
gsl_vector *gQx_1 = gsl_vector_alloc(3*NumEl);
gsl_vector *gQy_1 = gsl_vector_alloc(3*NumEl);
for (int i=0; i<3*NumEl; ++i)
{
gsl_vector_set(gzeta_1,i,gsl_vector_get(gzeta,i));
gsl_vector_set(gQx_1,i,gsl_vector_get(gQx,i));
gsl_vector_set(gQy_1,i,gsl_vector_get(gQy,i));
}
gsl_vector_scale(gRHSZeta,dt);
gsl_vector_scale(gRHSQx,dt);
gsl_vector_scale(gRHSQy,dt);
gsl_vector_add(gzeta_1,gRHSZeta);
gsl_vector_add(gQx_1, gRHSQx);
gsl_vector_add(gQy_1, gRHSQy);
/************ print out zeta, Qx and Qy for debugging ********************/
#ifdef DEBUG
printf("After first computeL:\n Zeta \n");
gsl_vector_fprintf(stdout,gzeta_1,"%e");
printf("\n Qx \n");
gsl_vector_fprintf(stdout,gQx_1,"%e");
printf("\n Qy \n");
gsl_vector_fprintf(stdout,gQy_1,"%e");
printf("\n");
#endif
/***************************************************************************/
j = 0;
for (int i=0; i<NumEl; ++i){
for (int k =0; k < 3; ++k){
zeta[index(i,k,3)] = gsl_vector_get(gzeta_1,j);
Qx[index(i,k,3)] = gsl_vector_get(gQx_1,j);
Qy[index(i,k,3)] = gsl_vector_get(gQy_1,j);
++j;
}
}
/* printf("zeta\n");
for (int i=0; i < NumEl; ++i)
{
for (int k =0; k <3; ++k)
{
printf("%1.15f\t",junc->zeta[index(i,k,3)]);
}
printf("\n");
}
printf("Qx\n");
for (int i=0; i < NumEl; ++i)
{
for (int k =0; k <3; ++k)
{
printf("%1.15f\t",junc->Qx[index(i,k,3)]);
}
printf("\n");
}
printf("Qy\n");
for (int i=0; i < NumEl; ++i)
{
for (int k =0; k <3; ++k)
{
printf("%1.15f\t",junc->Qy[index(i,k,3)]);
}
printf("\n");
}
*/
// Apply minmod slope limiter on w_1
SlopeLimiter();
// Apply the positive-depth operator on w_1
// PDop2D();
j = 0;
for (int i=0; i<NumEl; ++i)
{
for(int k=0; k <3; ++k)
{
gsl_vector_set(gzeta_1,j,zeta[index(i,k,3)]);
gsl_vector_set(gQx_1,j,Qx[index(i,k,3)]);
gsl_vector_set(gQy_1,j,Qy[index(i,k,3)]);
++j;
}
}
/************ print out zeta, Qx and Qy for debugging ********************/
#ifdef DEBUG
printf("After first slope limiting:\n zeta \n");
gsl_vector_fprintf(stdout,gzeta_1,"%e");
printf("\n Qx \n");
gsl_vector_fprintf(stdout,gQx_1,"%e");
printf("\n Qy \n");
gsl_vector_fprintf(stdout,gQy_1,"%e");
printf("\n");
#endif
/***************************************************************************/
// w_1 = w_1 + w;
gsl_vector_add(gzeta_1,gzeta);
gsl_vector_add(gQx_1,gQx);
gsl_vector_add(gQy_1,gQy);
// Calcualte the wet-dry status of the elements again
// wetDryStatus2D();
// Compute w
compute2DL(time);
j = 0;
for (int i=0; i < NumEl; ++i) {
for (int k=0; k < 3; ++k){
gsl_vector_set(gRHSZeta,j,RHSZeta[index(i,k,3)]);
gsl_vector_set(gRHSQx,j,RHSQx[index(i,k,3)]);
gsl_vector_set(gRHSQy,j,RHSQy[index(i,k,3)]);
++j;
}
}
/************ print out zeta, Qx and Qy for debugging ********************/
#ifdef DEBUG
printf("After second computeL:\n RHSZeta \n");
gsl_vector_fprintf(stdout,gRHSZeta,"%e");
printf("\n RHSQx \n");
gsl_vector_fprintf(stdout,gRHSQx,"%e");
printf("\n RHSQy \n");
gsl_vector_fprintf(stdout,gRHSQy,"%e");
printf("\n");
#endif
/***************************************************************************/
gsl_vector_scale(gzeta_1,0.5);
gsl_vector_scale(gQx_1,0.5);
gsl_vector_scale(gQy_1,0.5);
gsl_vector_scale(gRHSZeta,dt/2);
gsl_vector_scale(gRHSQx,dt/2);
gsl_vector_scale(gRHSQy,dt/2);
gsl_vector_add(gzeta_1,gRHSZeta);
gsl_vector_add(gQx_1,gRHSQx);
gsl_vector_add(gQy_1,gRHSQy);
j = 0;
for (int i=0; i<NumEl; ++i){
for (int k =0; k < 3; ++k){
zeta[index(i,k,3)] = gsl_vector_get(gzeta_1,j);
Qx[index(i,k,3)] = gsl_vector_get(gQx_1,j);
Qy[index(i,k,3)] = gsl_vector_get(gQy_1,j);
++j;
}
}
// Apply minmod slope limiter to w
SlopeLimiter();
// Apply the positive depth operator on w
// PDop2D();
gsl_vector_free(gzeta);
gsl_vector_free(gQx);
gsl_vector_free(gQy);
gsl_vector_free(gzeta_1);
gsl_vector_free(gQx_1);
gsl_vector_free(gQy_1);
gsl_vector_free(gRHSZeta);
gsl_vector_free(gRHSQx);
gsl_vector_free(gRHSQy);
}
void time_evolution(double FinalTime)
{
// output the file with x y and z information for the elements
boundary_conditions();
double time = 0;
double dt = 1e-7;
int Nstep = 0;
int fileNumber = 1;
// write out initial conditions
FILE* Initfile1;
FILE* Initfile2;
FILE* Initfile3;
// FILE* Initfile4;
char flname1[100];
char flname2[100];
char flname3[100];
// char flname4[100];
sprintf(flname1, "000_zeta.dat");
sprintf(flname2, "000_Qx.dat");
sprintf(flname3, "000_Qy.dat");
// sprintf(flname4, "000_Qdotn.dat");
Initfile1 = fopen(flname1, "w");
Initfile2 = fopen(flname2, "w");
Initfile3 = fopen(flname3, "w");
// Initfile4 = fopen(flname4, "w");
/* fprintf(Initfile1, "H at time 0\n");
fprintf(Initfile2, "Qx at time 0 \n");
fprintf(Initfile3, "Qy at time 0 \n");
fprintf(Initfile4, "Qdotn at time 0 \n");
*/
int k;
for (int j=0; j<NumEl; ++j)
{
for(k=0; k<3; ++k)
{
double zeta_val = zeta[index(j,k,3)];
double zval = (z[EltoVert[j*3+k]]+z[EltoVert[j*3+((k+1)%3)]])/2;
double H = zeta_val + zval;
double Qx_val = Qx[index(j,k,3)];
double Qy_val = Qy[index(j,k,3)];
// double Qdotn = Qx_val*normvecx[index(j,k,3)] + Qy_val*normvecy[index(j,k,3)];
fprintf(Initfile1, "%1.15f\t\t",zeta_val);
fprintf(Initfile2, "%1.15f\t\t",Qx_val);
fprintf(Initfile3, "%1.15f\t\t",Qy_val);
// fprintf(Initfile4, "%1.15f\t\t",Qdotn);
}
fprintf(Initfile1, "\n");
fprintf(Initfile2, "\n");
fprintf(Initfile3, "\n");
// fprintf(Initfile4, "\n");
}
fclose(Initfile1);
fclose(Initfile2);
fclose(Initfile3);
// fclose(Initfile4);
//wetDryStatus2D();
while (time<FinalTime)
{
time = time + dt;
printf("dt = %e\n", dt);
printf("time = %e\n", time);
oneTimeStep2D(time,dt);
boundary_conditions();
/********* Output data every twentienth step *************/
Nstep = Nstep + 1;
int NstepinSec = floor(1./dt);
if (time == FinalTime)
// if (Nstep%500 == 0 || time == FinalTime)
// if ((Nstep%(10*NstepinSec) == 0) || time == FinalTime)
{
FILE* file3;
FILE* file4;
FILE* file5;
// FILE* file6;
char filename1[100];
char filename2[100];
char filename3[100];
// char filename4[100];
/* sprintf(filename1, "Zeta%d", NumEl);
sprintf(filename2, "Qx%d", NumEl);
sprintf(filename3, "Qy%d", NumEl);
*/
sprintf(filename1, "%3.3d_H.dat", fileNumber);
sprintf(filename2, "%3.3d_Qx.dat", fileNumber);
sprintf(filename3, "%3.3d_Qy.dat", fileNumber);
// sprintf(filename1, "%3.3d_H.dat", fileNumber);
// sprintf(filename2, "%3.3d_Qx.dat", fileNumber);
// sprintf(filename3, "%3.3d_Qy.dat", fileNumber);
// sprintf(filename4, "%3.3d_Q.n.dat", fileNumber);
file3 = fopen(filename1, "w");
file4 = fopen(filename2, "w");
file5 = fopen(filename3, "w");
// file6 = fopen(filename4, "w");
//fprintf(file3, "H at time %e\n", time);
//fprintf(file4, "Qx at time %e \n", time);
//fprintf(file5, "Qy at time %e \n", time);
// fprintf(file6, "Qdotn at time %e \n", time);
int k;
for (int j=0; j<NumEl; ++j)
{
for(k=0; k<3; ++k)
{
double zeta_val = zeta[index(j,k,3)];
double Qx_val = Qx[index(j,k,3)];
double Qy_val = Qy[index(j,k,3)];
double zval = (z[EltoVert[j*3+k]]+z[EltoVert[j*3+((k+1)%3)]])/2;
double hval = zeta_val + zval;
// double Qdotn = Qx_val*normvecx[index(j,k,3)] + Qy_val*normvecy[index(j,k,3)];
fprintf(file3, "%1.15f\t\t",zeta_val);
fprintf(file4, "%1.15f\t\t",Qx_val);
fprintf(file5, "%1.15f\t\t",Qy_val);
// fprintf(file6, "%1.15f\t\t",Qdotn);
}
fprintf(file3, "\n");
fprintf(file4, "\n");
fprintf(file5, "\n");
// fprintf(file6, "\n");
}
fclose(file3);
fclose(file4);
fclose(file5);
// fclose(file6);
++fileNumber;
}
/**************** Set next time step ****************/
// set next time step
// printf("max_lambda = %e\n", max_lambda);
// printf("minEdgLength = %e\n", minEdgLength);
dt = 0.1*minEdgLength/max_lambda;
if ((time + dt) > FinalTime)
dt = FinalTime - time;
}
}
| {
"alphanum_fraction": 0.5901574803,
"avg_line_length": 25.0864197531,
"ext": "c",
"hexsha": "0cce59f174c3818e109ea325cb114e75a883a9bb",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-04-03T20:59:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-18T02:50:05.000Z",
"max_forks_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "evalseth/DG-RAIN",
"max_forks_repo_path": "2DCode/time_evolution.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c",
"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": "evalseth/DG-RAIN",
"max_issues_repo_path": "2DCode/time_evolution.c",
"max_line_length": 85,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f4765de2050adedfbe57ea25437c54de1f05ca9c",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "evalseth/DG-RAIN",
"max_stars_repo_path": "2DCode/time_evolution.c",
"max_stars_repo_stars_event_max_datetime": "2021-10-05T12:23:11.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-10-05T12:23:11.000Z",
"num_tokens": 3677,
"size": 10160
} |
static char help[] = "This code implements the distribution federate of the T-D power flow use-case. A global convergence for the federation is implemented in this use-case. The The distribution federate obtains the upstream distribution substation voltage from transmission federate, solves power flow, and sends the updated injection into transmission. This code does not use HELICS iterative API\n\n";
#include <petsc.h>
#include <ValueFederate.h>
#include <opendss.h>
#include <complex.h>
typedef struct {
helics_federate vfed;
helics_publication pub;
helics_subscription sub;
helics_time_t currenttime;
helics_iteration_status currenttimeiter;
char pub_topic[PETSC_MAX_PATH_LEN];
} UserData;
helics_status CreateDistributionFederate(helics_federate *distfed,char* pub_topic)
{
helics_federate_info_t fedinfo;
helics_status status;
const char* fedinitstring="--federates=1";
helics_federate vfed;
char fedname[PETSC_MAX_PATH_LEN];
PetscErrorCode ierr;
/* Create Federate Info object that describes the federate properties */
fedinfo = helicsFederateInfoCreate();
ierr = PetscStrcpy(fedname,"Distribution Federate ");CHKERRQ(ierr);
ierr = PetscStrcat(fedname,pub_topic);CHKERRQ(ierr);
/* Set Federate name */
status = helicsFederateInfoSetFederateName(fedinfo,fedname);
/* Set core type from string */
status = helicsFederateInfoSetCoreTypeFromString(fedinfo,"zmq");
/* Federate init string */
status = helicsFederateInfoSetCoreInitString(fedinfo,fedinitstring);
/* Set the message interval (timedelta) for federate. Note that
HELICS minimum message time interval is 1 ns and by default
it uses a time delta of 1 second. What is provided to the
setTimedelta routine is a multiplier for the default timedelta.
*/
/* Set one second message interval */
status = helicsFederateInfoSetTimeDelta(fedinfo,1.0);
status = helicsFederateInfoSetLoggingLevel(fedinfo,1);
status = helicsFederateInfoSetMaxIterations(fedinfo,100);
/* Create value federate */
vfed = helicsCreateValueFederate(fedinfo);
*distfed = vfed;
return status;
}
int main(int argc,char **argv)
{
PetscErrorCode ierr;
const char* helicsversion;
UserData user;
helics_status status;
PetscBool flg;
char netfile[PETSC_MAX_PATH_LEN],dcommand[PETSC_MAX_PATH_LEN];
char sub_topic[PETSC_MAX_PATH_LEN];
double complex *Stotal;
PetscInt iter=0;
PetscScalar Vm,Va;
PetscScalar Pg,Qg,Pgprv,Qgprv;
PetscInt pflowT_conv=0,pflowD_conv=0,global_conv=0;
char pubstr[PETSC_MAX_PATH_LEN],substr[PETSC_MAX_PATH_LEN];
PetscInt strlen;
PetscReal tol=1E-6,mis;
PetscInitialize(&argc,&argv,NULL,help);
helicsversion = helicsGetVersion();
printf("D FED: Helics version = %s\n",helicsversion);
/* Get network data file from command line */
ierr = PetscOptionsGetString(NULL,NULL,"-netfile",netfile,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
ierr = PetscSNPrintf(dcommand,PETSC_MAX_PATH_LEN-1,"Redirect ");CHKERRQ(ierr);
ierr = PetscStrcat(dcommand,netfile);CHKERRQ(ierr);
/* Load the D file */
ierr = OpenDSSRunCommand(dcommand);CHKERRQ(ierr);
flg = PETSC_FALSE;
/* Get the distribution topic for publication stream */
ierr = PetscOptionsGetString(NULL,NULL,"-dtopic",user.pub_topic,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
if(!flg) {
SETERRQ(PETSC_COMM_SELF,0,"Need to specify the publication name, option -dtopic <topic_name>.\n This is same as the distribution feeder file name without the extension");
}
/* Create distribution federate */
status = CreateDistributionFederate(&user.vfed,user.pub_topic);
printf("Created D FEDERATE %s\n",user.pub_topic);
/* Register the publication */
user.pub = helicsFederateRegisterGlobalPublication(user.vfed,user.pub_topic,"string","");
printf("D FEDERATE %s: Publication registered\n",user.pub_topic);
/* Subscribe to transmission federate's publication */
ierr = PetscStrcpy(sub_topic,"Trans/");
ierr = PetscStrcat(sub_topic,user.pub_topic);
user.sub = helicsFederateRegisterSubscription(user.vfed,sub_topic,"string","");
printf("D FEDERATE %s: Subscription registered\n",user.pub_topic);
status = helicsFederateEnterInitializationMode(user.vfed);
printf("D FEDERATE %s: Entered initialization mode\n",user.pub_topic);
user.currenttime = 0.0;
user.currenttimeiter = iterating;
PetscInt solve;
/* Solve power flow */
// printf("D FEDERATE %s running power flow\n",user.pub_topic);
ierr = OpenDSSSolutionGetSolve(&solve);CHKERRQ(ierr);
/* Send power injection to transmission */
/* Get the net injection at the boundary bus */
ierr = OpenDSSCircuitGetTotalPower(&Stotal);CHKERRQ(ierr);
Pgprv = -creal(Stotal[0])/1000.0; /* Conversion to MW */
Qgprv = -cimag(Stotal[0])/1000.0;
ierr = PetscSNPrintf(pubstr,PETSC_MAX_PATH_LEN-1,"%18.16f,%18.16f,%d",Pgprv,Qgprv,pflowD_conv);CHKERRQ(ierr);
status = helicsPublicationPublishString(user.pub,pubstr);
// printf("D FEDERATE %s sent Pg = %4.3f, Qg = %4.3f, conv = %d from T FEDERATE\n",user.pub_topic,Pgprv,Qgprv,pflowD_conv);
status = helicsFederateEnterExecutionMode(user.vfed);
printf("D FEDERATE %s: Entered execution mode\n",user.pub_topic);
while(user.currenttimeiter == iterating) {
iter++;
status = helicsSubscriptionGetString(user.sub,substr,PETSC_MAX_PATH_LEN-1,&strlen);
sscanf(substr,"%lf,%lf,%d",&Vm,&Va,&pflowT_conv);
// printf("D FEDERATE %s received Vm = %4.3f, Va = %4.3f, conv = %d from T FEDERATE\n",user.pub_topic,Vm,Va,pflowT_conv);
global_conv = pflowT_conv & pflowD_conv;
if(global_conv) {
helicsFederateRequestTimeIterative(user.vfed,user.currenttime,no_iteration,&user.currenttime,&user.currenttimeiter);
} else {
/* Set source bus voltage */
ierr = OpenDSSVsourcesSetPU(Vm);CHKERRQ(ierr);
ierr = OpenDSSVsourcesSetAngleDeg(Va);CHKERRQ(ierr);
/* 2. Solve power flow */
// printf("D FEDERATE %s running power flow\n",user.pub_topic);
ierr = OpenDSSSolutionGetSolve(&solve);CHKERRQ(ierr);
/* Send power injection to transmission */
/* Get the net injection at the boundary bus */
ierr = OpenDSSCircuitGetTotalPower(&Stotal);CHKERRQ(ierr);
Pg = -creal(Stotal[0])/1000.0; /* Conversion to MW */
Qg = -cimag(Stotal[0])/1000.0;
mis = PetscSqrtScalar((Pg-Pgprv)/100*(Pg-Pgprv)/100 + (Qg-Qgprv)/100*(Qg-Qgprv)/100); /* Divide by 100 for conversion to pu */
if(mis < tol) {
pflowD_conv = 1;
} else {
pflowD_conv = 0;
Pgprv = Pg;
Qgprv = Qg;
}
ierr = PetscSNPrintf(pubstr,PETSC_MAX_PATH_LEN-1,"%18.16f,%18.16f,%d",Pg,Qg,pflowD_conv);CHKERRQ(ierr);
status = helicsPublicationPublishString(user.pub,pubstr);
// printf("D FEDERATE %s sent Pg = %4.3f, Qg = %4.3f, conv = %d to T FEDERATE\n",user.pub_topic,Pg,Qg,pflowD_conv);
fflush(NULL);
/*3. Publish Pg, Qg, and convergence status to transmission */
status = helicsFederateRequestTimeIterative(user.vfed,user.currenttime,force_iteration,&user.currenttime,&user.currenttimeiter);
printf("Iteration %d: D Federate %s mis = %g,converged = %d\n",iter,user.pub_topic,mis,pflowD_conv);
}
}
status = helicsFederateEnterExecutionModeComplete(user.vfed);
status = helicsFederateFinalize(user.vfed);
PetscFinalize();
return 0;
}
| {
"alphanum_fraction": 0.7171378802,
"avg_line_length": 38.2717948718,
"ext": "c",
"hexsha": "344b5a684604c3a31851f9b020ec6e6b8e39284c",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-09-23T19:30:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-08-01T21:49:40.000Z",
"max_forks_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "GMLC-TDC/Use-Cases",
"max_forks_repo_path": "ANL-TD-Iterative-Pflow/pflow-helics-dist.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "GMLC-TDC/Use-Cases",
"max_issues_repo_path": "ANL-TD-Iterative-Pflow/pflow-helics-dist.c",
"max_line_length": 404,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "14d687fe04af731c1ee466e05acfd5813095660a",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "GMLC-TDC/Use-Cases",
"max_stars_repo_path": "ANL-TD-Iterative-Pflow/pflow-helics-dist.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-04T07:27:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-04T07:27:34.000Z",
"num_tokens": 2117,
"size": 7463
} |
#include <stdio.h>
#include <stdlib.h>
#include <cblas.h>
#include <math.h>
#include <string.h>
#include "../inc/knnring.h"
#include "mpi.h"
// Application Entry Point
/*
* X is this node's points from which distances will be calculated
* n is the number of points in X and each incoming-outcoming block
* d is the number of dimensions of each point
* k is the number of minimum points to calculate
*/
knnresult distrAllkNN(double * X, int n, int d, int k){
// Timers
double start = MPI_Wtime();
double end;
// Get processes number and process id
int p, id;
MPI_Comm_rank(MPI_COMM_WORLD, &id); // Task ID
MPI_Comm_size(MPI_COMM_WORLD, &p); // # tasks
// Find IDs of previous and next node in ring
int prev, nxt;
if(id == 0)
prev = p - 1;
else
prev = id - 1;
if(id == p-1)
nxt = 0;
else
nxt = id + 1;
// MPI variables used for async communication
MPI_Request reqSend, reqReceive;
//MPI_Status status;
// Y matrix for receiving points
double* Y = calloc(n*d, sizeof(double));
// Temporary Y matrix, used for trading in nodes with even ids so that we don't overwrite Y before sending it while receiving
double* tempY = calloc(n*d, sizeof(double));
// Start pre-fetching and sending data asynchronously
MPI_Isend(X, n*d, MPI_DOUBLE, nxt, 2, MPI_COMM_WORLD, &reqSend);
MPI_Irecv(tempY, n*d, MPI_DOUBLE, prev, 2, MPI_COMM_WORLD, &reqReceive);
// This is the id that corresponds to the node that initially had the current block of points Y
// It's used to reconstruct the ids array we receive so we don't have to also send ids
int blockID = id;
// Generate ids matrix
int* ids = calloc(n, sizeof(int));
for(int i = 0; i < n; i++){
// The first node gets points [0, n], second [n+1, 2n] etc. Node 0 gets the last n points
if(id != 0)
ids[i] = (id - 1) * n + i;
else
ids[i] = (p-1) * n + i;
}
// First calculate using the original dataset, then move on to sending/receiving blocks from others
knnresult results = kNN(X, X, n, n, d, k);
// IDs in the knnresult structure are relative. They start from 0 and go up to n-1. We need to map them to the actual ids generated above
for(int i = 0; i < n * k; i++)
results.nidx[i] = ids[results.nidx[i]];
// Temporary results struct, used for calculations in incoming block
knnresult newResults;
// Pointers and temporary arrays used for merging results.
int ptrResults = 0;
int ptrNewResults = 0;
double* tempResDis = calloc(n * k, sizeof(double));
int* tempResIDs = calloc(n * k, sizeof(int));
// Variables to hold minimum and maximum reduction
double mindis, maxdis, tempmindis, tempmaxdis;
// Trade blocks p-1 times in the ring
for(int i = 0; i < p-1; i++){
// Wait for sending/receiving to complete before proceeding
MPI_Wait(&reqSend, MPI_STATUS_IGNORE);
MPI_Wait(&reqReceive, MPI_STATUS_IGNORE);
// Write the received points into Y so we can start pre-fetching the next ones in tempY
memcpy(Y, tempY, n * d * sizeof(double));
// Last time we go in data doesn't need to be prefetched
if(i < p-2){
// Start pre-fetching
MPI_Isend(Y, n*d, MPI_DOUBLE, nxt, 2, MPI_COMM_WORLD, &reqSend);
MPI_Irecv(tempY, n*d, MPI_DOUBLE, prev, 2, MPI_COMM_WORLD, &reqReceive);
}
// Reconstruct ids array of received block of points based on the node and the number of blocks already traded
blockID--;
if(blockID < 0)
blockID = p-1;
for(int j = 0; j < n; j++){
if(blockID != 0)
ids[j] = (blockID - 1) * n + j;
else
ids[j] = (p-1) * n + j;
}
// Run calculations on received points
newResults = kNN(Y, X, n, n, d, k);
// Again map ids as done initially
for(int l = 0; l < n * k; l++)
newResults.nidx[l] = ids[newResults.nidx[l]];
// Copy points and ids array of current results to temporary arrays to safely alter the results struct bellow
memcpy(tempResDis, results.ndist, n * k * sizeof(double));
memcpy(tempResIDs, results.nidx, n * k * sizeof(int));
// Merge results and newResults arrays in a merge-sort fashion
// Iterate for each query point
for(int r = 0; r < n; r++){
ptrResults = 0;
ptrNewResults = 0;
// Iterate for each neighbor
for(int j = 0; j < k; j++){
// If the point in older results is closer than the new one, add it, else add the other one and increment the appropriate array pointer
if(tempResDis[r*k + ptrResults] < newResults.ndist[r*k + ptrNewResults]){
results.ndist[r*k + j] = tempResDis[r*k + ptrResults];
results.nidx[r*k + j] = tempResIDs[r*k + ptrResults];
ptrResults++;
}else{
results.ndist[r*k + j] = newResults.ndist[r*k + ptrNewResults];
results.nidx[r*k + j] = newResults.nidx[r*k + ptrNewResults];
ptrNewResults++;
}
}
}
}
// Find overall minimum and maximum distances of knn neighbors - excluding initial 0s
mindis = results.ndist[1];
maxdis = results.ndist[k-1];
// Locally reduce minimum and maximum
for(int i = 0; i < n; i++){
if(results.ndist[k*i] < mindis)
mindis = results.ndist[k*i + 1];
if(results.ndist[k*i + k - 1] > maxdis)
maxdis = results.ndist[k*i + k - 1];
}
MPI_Reduce(&mindis, &tempmindis, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD);
MPI_Reduce(&maxdis, &tempmaxdis, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
end = MPI_Wtime();
printf("Execution time for node %d: %f s\n", id, end-start);
if(id == 0){
if(mindis < tempmindis)
tempmindis = mindis;
if(maxdis > tempmaxdis)
tempmaxdis = maxdis;
printf("Minimum distance is %f, maximum is %f\n", tempmindis, tempmaxdis);
printf("Note: this message is printed twice because the tester runs two tests: one for column major and one for row major in this order.\n");
}
return results;
}
// Application Entry Point
knnresult kNN(double * X, double * Y, int n, int m, int d, int k)
{
// Calculate distances matrix D - D is row-major and nxm
double* tempD = calculateD(X, Y, n, m, d, k);
double* D = calloc(m*n, sizeof(double));
// Transpose D to mxn
//cblas_dimatcopy(CblasRowMajor, CblasTrans, n, m, 1.0, D, m, n);
double* identityMat = calloc(n*n, sizeof(double));
for(int f=0; f<n; f++)
identityMat[f*n + f] = 1;
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, m, n, n, 1, tempD, m, identityMat, n, 0, D, n);
// Free memory
free(identityMat);
free(tempD);
// Create results struct
knnresult results;
results.k = k;
results.m = m;
results.ndist = calloc(m*k, sizeof(double));
results.nidx = calloc(m*k, sizeof(int));
// Create ids array for the X array
int* ids = calloc(n, sizeof(int));
// K-Select using quickselect to find k smallest distances for each point of Y
for(int j = 0; j < m; j++){
// Re-set ids vector before executing quickselect each time
for(int i = 0; i < n; i++)
ids[i] = i;
// Call quickselect on the row of D to sort it up to its k-th element
kselect(D + j * n, ids, n, k);
// Quicksort the results
quickSort(D + j * n, ids, 0, n-1);
// Write results (point id and distance)
for(int l = 0; l < k; l++){
results.ndist[j * k + l] = D[j * n + l];
results.nidx[j * k + l] = ids[l];
}
}
// Free memory and return results
free(ids);
return results;
}
// Function used to calculate D = sqrt(sum(X.^2,2) -2* X*Y.' + sum(Y.^2,2).');
double* calculateD(double * X, double * Y, int n, int m, int d, int k){
// Temporary variable
double temp = 0;
// Distance matrix for results
double* D = calloc(n*m, sizeof(double));
// Euclidean norm vectors
double* normX = calloc(n, sizeof(double));
double* normY = calloc(m, sizeof(double));
// Matrice to store -2*X*Y'
double* XY = calloc(n*m, sizeof(double));
// Calculate -2*XY (https://software.intel.com/en-us/mkl-tutorial-c-multiplying-matrices-using-dgemm)
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n, m, d, -2, X, d, Y, d, 0, XY, m);
// Calculate sum(X.^2,2), sum(Y.^2,2)
for(int i = 0; i < n; i++){
temp = cblas_dnrm2(d, X+i*d, 1);
normX[i] = temp * temp;
}
for(int i = 0; i < m; i++){
temp = cblas_dnrm2(d, Y+i*d, 1);
normY[i] = temp * temp;
}
// XY = sum(X.^2,2) -2* X*Y.'
for (int i=0; i<n; i++)
for(int j=0; j<m; j++)
XY[i*m+j] += normX[i] + normY[j];
// D = sqrt(sum(X.^2,2) -2* X*Y.' + sum(Y.^2,2).');
for(int i = 0; i < n*m; i++)
D[i] = sqrt(fabs(XY[i]));
// Free memory
free(normX);
free(normY);
free(XY);
return D;
}
// A utility function to swap two elements
void swap_double(double *a, double *b){
double t = *a;
*a = *b;
*b = t;
}
// A utility function to swap two elements
void swap_int(int *a, int *b){
int t = *a;
*a = *b;
*b = t;
}
// QuickSort Partition function. low and high are the range of indexes in arr where partition should work
int partition (double arr[], int *ids, int low, int high){
// Select a pivot and initialize flag to position of smallest element before pivot
double pivot = arr[high];
int i = (low - 1);
// Go through the array examining each element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than the pivot, increment i and swap it out with the one currently pointed by i
if (arr[j] < pivot)
{
i++;
// Swap distances and corresponding point ids
swap_double(&arr[i], &arr[j]);
swap_int(&ids[i], &ids[j]);
}
}
// Finally place pivot in its correct position in the array and return the position as the middle point
swap_double(&arr[i + 1], &arr[high]);
swap_int(&ids[i + 1], &ids[high]);
return (i + 1);
}
// Returns the median using the QuickSelect algorithm
double kselect(double arr[], int *ids, int length, int k){
return quickSelect(arr, ids, length, k);
}
// Returns the idx-th element of arr when arr is sorted. idx is the index (starting from 1) of the point we want to find when the array is sorted.
double quickSelect(double arr[], int *ids, int length, int idx){
// Check to end recursion
if (length == 1){
return arr[0];
}
// Select last array element as pivot
double pivot = arr[length - 1];
// Get index of pivot after we partition the array
int pivotIndex = partition(arr, ids, 0, length - 1);
// Create the higher and lower arrays that occur after partitioning in QuickSort fashion
int lowerLength = pivotIndex;
pivotIndex++;
int higherLength = (length - (lowerLength + 1));
// At this point pivotIndex, lowerLength and higherLength all start from 1 not 0
// Variable to store result of following recursive calls
double result = 0;
// This means that the point we're looking (median in our case) is in the lower partition
if (idx <= lowerLength){
result = quickSelect(arr, ids, lowerLength, idx);
}
// This means that idx-th element is our pivot point
else if(idx == pivotIndex){
result = pivot;
}
// This means that the median is in the higher partition
else{
result = quickSelect(arr + pivotIndex, ids + pivotIndex, higherLength, idx - pivotIndex);
}
// Return result
return result;
}
// Simple quicksort implementation that also sorts the ids array according to the way the main array was sorted
void quickSort(double arr[], int *ids, int low, int high)
{
if (low < high)
{
// idx is the partition point
int idx = partition(arr, ids, low, high);
// Divide and conquer
quickSort(arr, ids, low, idx - 1);
quickSort(arr, ids, idx + 1, high);
}
}
| {
"alphanum_fraction": 0.6410811747,
"avg_line_length": 29.2227848101,
"ext": "c",
"hexsha": "90aab1cc60cc0eeaf433128de26de45019aa01e6",
"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": "b426495643705e5616dd526327ba23934d6d1285",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CedArctic/knn_mpi",
"max_forks_repo_path": "src/knnring_mpi_async.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b426495643705e5616dd526327ba23934d6d1285",
"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": "CedArctic/knn_mpi",
"max_issues_repo_path": "src/knnring_mpi_async.c",
"max_line_length": 146,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b426495643705e5616dd526327ba23934d6d1285",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CedArctic/knn_mpi",
"max_stars_repo_path": "src/knnring_mpi_async.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3454,
"size": 11543
} |
/*
* 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 framesys_300a49a6_c103_4a1f_8166_358e823a432b_h
#define framesys_300a49a6_c103_4a1f_8166_358e823a432b_h
#include <gslib/type.h>
#include <ariel/sysop.h>
#include <ariel/config.h>
#include <ariel/rendersys.h>
__ariel_begin__
enum frame_strategy
{
fs_busy_loop,
fs_lazy_passive,
};
struct app_config;
struct app_env;
class framesys;
struct frame_event;
class frame_listener;
class rose;
enum frame_event_id
{
feid_invalid,
feid_draw,
feid_timer,
feid_paint,
feid_mouse_down,
feid_mouse_up,
feid_mouse_move,
feid_key_down,
feid_key_up,
feid_char,
feid_show,
feid_create,
feid_close,
feid_resize,
feid_halt,
feid_resume,
feid_custom,
};
struct __gs_novtable frame_event abstract
{
virtual uint get_id() const = 0;
virtual uint get_event_size() const = 0;
};
struct frame_draw_event:
public frame_event
{
public:
virtual uint get_id() const override { return feid_draw; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_close_event:
public frame_event
{
public:
virtual uint get_id() const override { return feid_close; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_halt_event:
public frame_event
{
public:
virtual uint get_id() const override { return feid_halt; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_resume_event:
public frame_event
{
public:
virtual uint get_id() const override { return feid_resume; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_paint_event:
public frame_event
{
rect boundary;
public:
virtual uint get_id() const override { return feid_paint; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_timer_event:
public frame_event
{
uint timerid;
public:
virtual uint get_id() const override { return feid_timer; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_show_event:
public frame_event
{
bool show;
public:
virtual uint get_id() const override { return feid_show; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_resize_event:
public frame_event
{
rect boundary;
public:
virtual uint get_id() const override { return feid_resize; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_mouse_down_event:
public frame_event
{
uint modifier;
unikey key;
point position;
public:
virtual uint get_id() const override { return feid_mouse_down; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_mouse_up_event:
public frame_event
{
uint modifier;
unikey key;
point position;
public:
virtual uint get_id() const override { return feid_mouse_up; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_mouse_move_event:
public frame_event
{
uint modifier;
point position;
public:
virtual uint get_id() const override { return feid_mouse_move; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_key_down_event:
public frame_event
{
uint modifier;
unikey key;
public:
virtual uint get_id() const override { return feid_key_down; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_key_up_event:
public frame_event
{
uint modifier;
unikey key;
public:
virtual uint get_id() const override { return feid_key_up; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_char_event:
public frame_event
{
uint modifier;
uint charactor;
public:
virtual uint get_id() const override { return feid_char; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
struct frame_create_event:
public frame_event
{
system_driver* driver;
rect boundary;
public:
virtual uint get_id() const override { return feid_create; }
virtual uint get_event_size() const override { return sizeof(*this); }
};
template<frame_event_id _feid>
struct frame_event_table;
#define register_frame_event(feid, fevt) \
template<> \
struct frame_event_table<feid> { \
typedef fevt type; \
};
register_frame_event(feid_draw, frame_draw_event);
register_frame_event(feid_timer, frame_timer_event);
register_frame_event(feid_paint, frame_paint_event);
register_frame_event(feid_mouse_down, frame_mouse_down_event);
register_frame_event(feid_mouse_up, frame_mouse_up_event);
register_frame_event(feid_mouse_move, frame_mouse_move_event);
register_frame_event(feid_key_down, frame_key_down_event);
register_frame_event(feid_key_up, frame_key_up_event);
register_frame_event(feid_char, frame_char_event);
register_frame_event(feid_show, frame_show_event);
register_frame_event(feid_create, frame_create_event);
register_frame_event(feid_close, frame_close_event);
register_frame_event(feid_resize, frame_resize_event);
register_frame_event(feid_halt, frame_halt_event);
register_frame_event(feid_resume, frame_resume_event);
#undef register_frame_event
class __gs_novtable frame_listener abstract
{
public:
virtual ~frame_listener() {}
virtual void on_frame_start() = 0;
virtual void on_frame_end() = 0;
virtual bool on_frame_event(const frame_event& event) = 0;
};
class frame_dispatcher:
public system_notify
{
public:
virtual void on_show(bool b) override;
virtual void on_create(system_driver* ptr, const rect& rc) override;
virtual void on_close() override;
virtual void on_resize(const rect& rc) override;
virtual void on_paint(const rect& rc) override;
virtual void on_halt() override;
virtual void on_resume() override;
virtual bool on_mouse_down(uint um, unikey uk, const point& pt) override;
virtual bool on_mouse_up(uint um, unikey uk, const point& pt) override;
virtual bool on_mouse_move(uint um, const point& pt) override;
virtual bool on_key_down(uint um, unikey uk) override;
virtual bool on_key_up(uint um, unikey uk) override;
virtual bool on_char(uint um, uint ch) override;
virtual void on_timer(uint tid) override;
protected:
frame_listener* _listener;
public:
frame_dispatcher() { _listener = 0; }
void set_listener(frame_listener* listenter) { _listener = listenter; }
void do_draw();
void on_frame_start();
void on_frame_end();
};
struct frame_configs
{
uint handles;
int width;
int height;
/* more to come.. */
};
class framesys:
public system_driver
{
public:
friend class frame_dispatcher;
typedef void (framesys::*fn_empty_frame)();
public:
void set_frame_strategy(frame_strategy stt);
void set_notify(system_notify* notify) { _notify = notify; }
void set_frame_listener(frame_listener* lis) { _dispatcher.set_listener(lis); }
system_notify* get_notify() const { return _notify; }
rendersys* get_rendersys() const { return _rendersys; }
rose* get_rose() const { return _rose; }
const frame_configs& get_configs() const { return _configs; }
void initialize(const rect& rc);
void refresh();
public:
virtual ~framesys();
virtual void initialize(const system_context& ctx) override;
virtual void setup() override;
virtual void close() override;
virtual void set_timer(uint tid, int t) override;
virtual void kill_timer(uint tid) override;
virtual void update() override;
virtual void emit(int msgid, void* msg, int size) override;
virtual void set_ime(point pt, const font& ft) override;
virtual void set_cursor(cursor_type curty) override;
private:
framesys();
public:
static int run();
static framesys* get_framesys()
{
static framesys inst;
return &inst;
}
#if defined(WIN32) || defined(_WINDOWS)
static void set_default_config(app_config& cfg);
static void on_app_initialized(const app_env& env);
static void on_app_windowed(HWND);
#endif
protected:
void idle()
{
assert(_empty_frame_proc);
(this->*_empty_frame_proc)();
}
void empty_frame_lazy();
void empty_frame_busy();
protected:
frame_strategy _strategy;
frame_configs _configs;
frame_dispatcher _dispatcher;
system_notify* _notify;
rendersys* _rendersys;
rose* _rose;
fn_empty_frame _empty_frame_proc;
};
__ariel_end__
#endif
| {
"alphanum_fraction": 0.6859582543,
"avg_line_length": 28.4864864865,
"ext": "h",
"hexsha": "2d32eade1bd0343fa2d91d59571d97ecef622cae",
"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/framesys.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/framesys.h",
"max_line_length": 84,
"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/framesys.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": 2351,
"size": 10540
} |
// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
// reserved. See files LICENSE and NOTICE for details.
//
// This file is part of CEED, a collection of benchmarks, miniapps, software
// libraries and APIs for efficient high-order finite element and spectral
// element discretizations for exascale applications. For more information and
// source code availability see http://github.com/ceed.
//
// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,
// a collaborative effort of two U.S. Department of Energy organizations (Office
// of Science and the National Nuclear Security Administration) responsible for
// the planning and preparation of a capable exascale ecosystem, including
// software, applications, hardware, advanced system engineering and early
// testbed platforms, in support of the nation's exascale computing imperative.
#ifndef setupsphere_h
#define setupsphere_h
#include <ceed.h>
#include <petsc.h>
#include <petscdmplex.h>
#include <petscfe.h>
#include <stdbool.h>
#include <string.h>
#include "qfunctions/bps/bp1sphere.h"
#include "qfunctions/bps/bp2sphere.h"
#include "qfunctions/bps/bp3sphere.h"
#include "qfunctions/bps/bp4sphere.h"
#include "qfunctions/bps/common.h"
#if PETSC_VERSION_LT(3,14,0)
# define DMPlexGetClosureIndices(a,b,c,d,e,f,g,h,i) DMPlexGetClosureIndices(a,b,c,d,f,g,i)
# define DMPlexRestoreClosureIndices(a,b,c,d,e,f,g,h,i) DMPlexRestoreClosureIndices(a,b,c,d,f,g,i)
#endif
#if PETSC_VERSION_LT(3,14,0)
# define DMPlexCreateSphereMesh(a,b,c,d,e) DMPlexCreateSphereMesh(a,b,c,e)
#endif
// -----------------------------------------------------------------------------
// PETSc Operator Structs
// -----------------------------------------------------------------------------
// Data for PETSc
typedef struct UserO_ *UserO;
struct UserO_ {
MPI_Comm comm;
DM dm;
Vec Xloc, Yloc, diag;
CeedVector xceed, yceed;
CeedOperator op;
Ceed ceed;
};
// Data for PETSc Interp/Restrict operators
typedef struct UserIR_ *UserIR;
struct UserIR_ {
MPI_Comm comm;
DM dmc, dmf;
Vec Xloc, Yloc, mult;
CeedVector ceedvecc, ceedvecf;
CeedOperator op;
Ceed ceed;
};
// -----------------------------------------------------------------------------
// libCEED Data Struct
// -----------------------------------------------------------------------------
// libCEED data struct for level
typedef struct CeedData_ *CeedData;
struct CeedData_ {
Ceed ceed;
CeedBasis basisx, basisu, basisctof;
CeedElemRestriction Erestrictx, Erestrictu, Erestrictui, Erestrictqdi;
CeedQFunction qf_apply;
CeedOperator op_apply, op_restrict, op_interp;
CeedVector qdata, xceed, yceed;
};
// -----------------------------------------------------------------------------
// Command Line Options
// -----------------------------------------------------------------------------
// Coarsening options
typedef enum {
COARSEN_UNIFORM = 0, COARSEN_LOGARITHMIC = 1
} coarsenType;
static const char *const coarsenTypes [] = {"uniform","logarithmic",
"coarsenType","COARSEN",0
};
// -----------------------------------------------------------------------------
// BP Option Data
// -----------------------------------------------------------------------------
// BP options
typedef enum {
CEED_BP1 = 0, CEED_BP2 = 1, CEED_BP3 = 2,
CEED_BP4 = 3, CEED_BP5 = 4, CEED_BP6 = 5
} bpType;
static const char *const bpTypes[] = {"bp1","bp2","bp3","bp4","bp5","bp6",
"bpType","CEED_BP",0
};
// BP specific data
typedef struct {
CeedInt ncompu, qdatasize, qextra;
CeedQFunctionUser setupgeo, setuprhs, apply, error;
const char *setupgeofname, *setuprhsfname, *applyfname, *errorfname;
CeedEvalMode inmode, outmode;
CeedQuadMode qmode;
PetscBool enforce_bc;
PetscErrorCode (*bcs_func)(PetscInt, PetscReal, const PetscReal *,
PetscInt, PetscScalar *, void *);
} bpData;
static bpData bpOptions[6] = {
[CEED_BP1] = {
.ncompu = 1,
.qdatasize = 1,
.qextra = 1,
.setupgeo = SetupMassGeo,
.setuprhs = SetupMassRhs,
.apply = Mass,
.error = Error,
.setupgeofname = SetupMassGeo_loc,
.setuprhsfname = SetupMassRhs_loc,
.applyfname = Mass_loc,
.errorfname = Error_loc,
.inmode = CEED_EVAL_INTERP,
.outmode = CEED_EVAL_INTERP,
.qmode = CEED_GAUSS
},
[CEED_BP2] = {
.ncompu = 3,
.qdatasize = 1,
.qextra = 1,
.setupgeo = SetupMassGeo,
.setuprhs = SetupMassRhs3,
.apply = Mass3,
.error = Error3,
.setupgeofname = SetupMassGeo_loc,
.setuprhsfname = SetupMassRhs3_loc,
.applyfname = Mass3_loc,
.errorfname = Error3_loc,
.inmode = CEED_EVAL_INTERP,
.outmode = CEED_EVAL_INTERP,
.qmode = CEED_GAUSS
},
[CEED_BP3] = {
.ncompu = 1,
.qdatasize = 4,
.qextra = 1,
.setupgeo = SetupDiffGeo,
.setuprhs = SetupDiffRhs,
.apply = Diff,
.error = Error,
.setupgeofname = SetupDiffGeo_loc,
.setuprhsfname = SetupDiffRhs_loc,
.applyfname = Diff_loc,
.errorfname = Error_loc,
.inmode = CEED_EVAL_GRAD,
.outmode = CEED_EVAL_GRAD,
.qmode = CEED_GAUSS
},
[CEED_BP4] = {
.ncompu = 3,
.qdatasize = 4,
.qextra = 1,
.setupgeo = SetupDiffGeo,
.setuprhs = SetupDiffRhs3,
.apply = Diff3,
.error = Error3,
.setupgeofname = SetupDiffGeo_loc,
.setuprhsfname = SetupDiffRhs3_loc,
.applyfname = Diff_loc,
.errorfname = Error3_loc,
.inmode = CEED_EVAL_GRAD,
.outmode = CEED_EVAL_GRAD,
.qmode = CEED_GAUSS
},
[CEED_BP5] = {
.ncompu = 1,
.qdatasize = 4,
.qextra = 0,
.setupgeo = SetupDiffGeo,
.setuprhs = SetupDiffRhs,
.apply = Diff,
.error = Error,
.setupgeofname = SetupDiffGeo_loc,
.setuprhsfname = SetupDiffRhs_loc,
.applyfname = Diff_loc,
.errorfname = Error_loc,
.inmode = CEED_EVAL_GRAD,
.outmode = CEED_EVAL_GRAD,
.qmode = CEED_GAUSS_LOBATTO
},
[CEED_BP6] = {
.ncompu = 3,
.qdatasize = 4,
.qextra = 0,
.setupgeo = SetupDiffGeo,
.setuprhs = SetupDiffRhs3,
.apply = Diff3,
.error = Error3,
.setupgeofname = SetupDiffGeo_loc,
.setuprhsfname = SetupDiffRhs3_loc,
.applyfname = Diff_loc,
.errorfname = Error3_loc,
.inmode = CEED_EVAL_GRAD,
.outmode = CEED_EVAL_GRAD,
.qmode = CEED_GAUSS_LOBATTO
}
};
// -----------------------------------------------------------------------------
// PETSc sphere auxiliary functions
// -----------------------------------------------------------------------------
// Utility function taken from petsc/src/dm/impls/plex/examples/tutorials/ex7.c
static PetscErrorCode ProjectToUnitSphere(DM dm) {
Vec coordinates;
PetscScalar *coords;
PetscInt Nv, v, dim, d;
PetscErrorCode ierr;
PetscFunctionBeginUser;
ierr = DMGetCoordinatesLocal(dm, &coordinates); CHKERRQ(ierr);
ierr = VecGetLocalSize(coordinates, &Nv); CHKERRQ(ierr);
ierr = VecGetBlockSize(coordinates, &dim); CHKERRQ(ierr);
Nv /= dim;
ierr = VecGetArray(coordinates, &coords); CHKERRQ(ierr);
for (v = 0; v < Nv; ++v) {
PetscReal r = 0.0;
for (d = 0; d < dim; ++d) r += PetscSqr(PetscRealPart(coords[v*dim+d]));
r = PetscSqrtReal(r);
for (d = 0; d < dim; ++d) coords[v*dim+d] /= r;
}
ierr = VecRestoreArray(coordinates, &coords); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// -----------------------------------------------------------------------------
// PETSc FE Boilerplate
// -----------------------------------------------------------------------------
// Create FE by degree
static int PetscFECreateByDegree(DM dm, PetscInt dim, PetscInt Nc,
PetscBool isSimplex, const char prefix[],
PetscInt order, PetscFE *fem) {
PetscQuadrature q, fq;
DM K;
PetscSpace P;
PetscDualSpace Q;
PetscInt quadPointsPerEdge;
PetscBool tensor = isSimplex ? PETSC_FALSE : PETSC_TRUE;
PetscErrorCode ierr;
PetscFunctionBeginUser;
/* Create space */
ierr = PetscSpaceCreate(PetscObjectComm((PetscObject) dm), &P); CHKERRQ(ierr);
ierr = PetscObjectSetOptionsPrefix((PetscObject) P, prefix); CHKERRQ(ierr);
ierr = PetscSpacePolynomialSetTensor(P, tensor); CHKERRQ(ierr);
ierr = PetscSpaceSetFromOptions(P); CHKERRQ(ierr);
ierr = PetscSpaceSetNumComponents(P, Nc); CHKERRQ(ierr);
ierr = PetscSpaceSetNumVariables(P, dim); CHKERRQ(ierr);
ierr = PetscSpaceSetDegree(P, order, order); CHKERRQ(ierr);
ierr = PetscSpaceSetUp(P); CHKERRQ(ierr);
ierr = PetscSpacePolynomialGetTensor(P, &tensor); CHKERRQ(ierr);
/* Create dual space */
ierr = PetscDualSpaceCreate(PetscObjectComm((PetscObject) dm), &Q);
CHKERRQ(ierr);
ierr = PetscDualSpaceSetType(Q,PETSCDUALSPACELAGRANGE); CHKERRQ(ierr);
ierr = PetscObjectSetOptionsPrefix((PetscObject) Q, prefix); CHKERRQ(ierr);
ierr = PetscDualSpaceCreateReferenceCell(Q, dim, isSimplex, &K); CHKERRQ(ierr);
ierr = PetscDualSpaceSetDM(Q, K); CHKERRQ(ierr);
ierr = DMDestroy(&K); CHKERRQ(ierr);
ierr = PetscDualSpaceSetNumComponents(Q, Nc); CHKERRQ(ierr);
ierr = PetscDualSpaceSetOrder(Q, order); CHKERRQ(ierr);
ierr = PetscDualSpaceLagrangeSetTensor(Q, tensor); CHKERRQ(ierr);
ierr = PetscDualSpaceSetFromOptions(Q); CHKERRQ(ierr);
ierr = PetscDualSpaceSetUp(Q); CHKERRQ(ierr);
/* Create element */
ierr = PetscFECreate(PetscObjectComm((PetscObject) dm), fem); CHKERRQ(ierr);
ierr = PetscObjectSetOptionsPrefix((PetscObject) *fem, prefix); CHKERRQ(ierr);
ierr = PetscFESetFromOptions(*fem); CHKERRQ(ierr);
ierr = PetscFESetBasisSpace(*fem, P); CHKERRQ(ierr);
ierr = PetscFESetDualSpace(*fem, Q); CHKERRQ(ierr);
ierr = PetscFESetNumComponents(*fem, Nc); CHKERRQ(ierr);
ierr = PetscFESetUp(*fem); CHKERRQ(ierr);
ierr = PetscSpaceDestroy(&P); CHKERRQ(ierr);
ierr = PetscDualSpaceDestroy(&Q); CHKERRQ(ierr);
/* Create quadrature */
quadPointsPerEdge = PetscMax(order + 1,1);
if (isSimplex) {
ierr = PetscDTStroudConicalQuadrature(dim, 1, quadPointsPerEdge, -1.0, 1.0,
&q); CHKERRQ(ierr);
ierr = PetscDTStroudConicalQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,
&fq); CHKERRQ(ierr);
} else {
ierr = PetscDTGaussTensorQuadrature(dim, 1, quadPointsPerEdge, -1.0, 1.0,
&q); CHKERRQ(ierr);
ierr = PetscDTGaussTensorQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,
&fq); CHKERRQ(ierr);
}
ierr = PetscFESetQuadrature(*fem, q); CHKERRQ(ierr);
ierr = PetscFESetFaceQuadrature(*fem, fq); CHKERRQ(ierr);
ierr = PetscQuadratureDestroy(&q); CHKERRQ(ierr);
ierr = PetscQuadratureDestroy(&fq); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// -----------------------------------------------------------------------------
// PETSc Setup for Level
// -----------------------------------------------------------------------------
// This function sets up a DM for a given degree
static int SetupDMByDegree(DM dm, PetscInt degree, PetscInt ncompu,
PetscInt dim) {
PetscInt ierr;
PetscFE fe;
PetscFunctionBeginUser;
// Setup FE
ierr = PetscFECreateByDegree(dm, dim, ncompu, PETSC_FALSE, NULL, degree, &fe);
CHKERRQ(ierr);
ierr = DMAddField(dm, NULL, (PetscObject)fe); CHKERRQ(ierr);
// Setup DM
ierr = DMCreateDS(dm); CHKERRQ(ierr);
ierr = DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL);
CHKERRQ(ierr);
ierr = PetscFEDestroy(&fe); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// -----------------------------------------------------------------------------
// libCEED Setup for Level
// -----------------------------------------------------------------------------
// Destroy libCEED operator objects
static PetscErrorCode CeedDataDestroy(CeedInt i, CeedData data) {
PetscInt ierr;
CeedVectorDestroy(&data->qdata);
CeedVectorDestroy(&data->xceed);
CeedVectorDestroy(&data->yceed);
CeedBasisDestroy(&data->basisx);
CeedBasisDestroy(&data->basisu);
CeedElemRestrictionDestroy(&data->Erestrictu);
CeedElemRestrictionDestroy(&data->Erestrictx);
CeedElemRestrictionDestroy(&data->Erestrictui);
CeedElemRestrictionDestroy(&data->Erestrictqdi);
CeedQFunctionDestroy(&data->qf_apply);
CeedOperatorDestroy(&data->op_apply);
if (i > 0) {
CeedOperatorDestroy(&data->op_interp);
CeedBasisDestroy(&data->basisctof);
CeedOperatorDestroy(&data->op_restrict);
}
ierr = PetscFree(data); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// Get CEED restriction data from DMPlex
static int CreateRestrictionPlex(Ceed ceed, CeedInt P, CeedInt ncomp,
CeedElemRestriction *Erestrict, DM dm) {
PetscInt ierr;
PetscInt c, cStart, cEnd, nelem, nnodes, *erestrict, eoffset;
PetscSection section;
Vec Uloc;
PetscFunctionBegin;
// Get Nelem
ierr = DMGetSection(dm, §ion); CHKERRQ(ierr);
ierr = DMPlexGetHeightStratum(dm, 0, &cStart,& cEnd); CHKERRQ(ierr);
nelem = cEnd - cStart;
// Get indices
ierr = PetscMalloc1(nelem*P*P, &erestrict); CHKERRQ(ierr);
for (c=cStart, eoffset = 0; c<cEnd; c++) {
PetscInt numindices, *indices, i;
ierr = DMPlexGetClosureIndices(dm, section, section, c, PETSC_TRUE,
&numindices, &indices, NULL, NULL);
CHKERRQ(ierr);
for (i=0; i<numindices; i+=ncomp) {
for (PetscInt j=0; j<ncomp; j++) {
if (indices[i+j] != indices[i] + copysign(j, indices[i]))
SETERRQ1(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,
"Cell %D closure indices not interlaced", c);
}
// NO BC on closed surfaces
PetscInt loc = indices[i];
erestrict[eoffset++] = loc;
}
ierr = DMPlexRestoreClosureIndices(dm, section, section, c, PETSC_TRUE,
&numindices, &indices, NULL, NULL);
CHKERRQ(ierr);
}
// Setup CEED restriction
ierr = DMGetLocalVector(dm, &Uloc); CHKERRQ(ierr);
ierr = VecGetLocalSize(Uloc, &nnodes); CHKERRQ(ierr);
ierr = DMRestoreLocalVector(dm, &Uloc); CHKERRQ(ierr);
CeedElemRestrictionCreate(ceed, nelem, P*P, ncomp, 1, nnodes, CEED_MEM_HOST,
CEED_COPY_VALUES, erestrict, Erestrict);
ierr = PetscFree(erestrict); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// Set up libCEED for a given degree
static int SetupLibceedByDegree(DM dm, Ceed ceed, CeedInt degree,
CeedInt topodim, CeedInt qextra,
PetscInt ncompx, PetscInt ncompu,
PetscInt gsize, PetscInt xlsize,
bpType bpChoice, CeedData data,
PetscBool setup_rhs, CeedVector rhsceed,
CeedVector *target) {
int ierr;
DM dmcoord;
Vec coords;
const PetscScalar *coordArray;
CeedBasis basisx, basisu;
CeedElemRestriction Erestrictx, Erestrictu, Erestrictui, Erestrictqdi;
CeedQFunction qf_setupgeo, qf_apply;
CeedOperator op_setupgeo, op_apply;
CeedVector xcoord, qdata, xceed, yceed;
CeedInt P, Q, cStart, cEnd, nelem, qdatasize = bpOptions[bpChoice].qdatasize;
CeedScalar R = 1, // radius of the sphere
l = 1.0/PetscSqrtReal(3.0); // half edge of the inscribed cube
// CEED bases
P = degree + 1;
Q = P + qextra;
CeedBasisCreateTensorH1Lagrange(ceed, topodim, ncompu, P, Q,
bpOptions[bpChoice].qmode, &basisu);
CeedBasisCreateTensorH1Lagrange(ceed, topodim, ncompx, 2, Q,
bpOptions[bpChoice].qmode, &basisx);
// CEED restrictions
ierr = DMGetCoordinateDM(dm, &dmcoord); CHKERRQ(ierr);
ierr = DMPlexSetClosurePermutationTensor(dmcoord, PETSC_DETERMINE, NULL);
CHKERRQ(ierr);
ierr = CreateRestrictionPlex(ceed, 2, ncompx, &Erestrictx, dmcoord);
CHKERRQ(ierr);
ierr = CreateRestrictionPlex(ceed, P, ncompu, &Erestrictu, dm); CHKERRQ(ierr);
ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd); CHKERRQ(ierr);
nelem = cEnd - cStart;
CeedElemRestrictionCreateStrided(ceed, nelem, Q*Q, ncompu, ncompu*nelem*Q*Q,
CEED_STRIDES_BACKEND, &Erestrictui);
CeedElemRestrictionCreateStrided(ceed, nelem, Q*Q, qdatasize,
qdatasize*nelem*Q*Q,
CEED_STRIDES_BACKEND, &Erestrictqdi);
// Element coordinates
ierr = DMGetCoordinatesLocal(dm, &coords); CHKERRQ(ierr);
ierr = VecGetArrayRead(coords, &coordArray); CHKERRQ(ierr);
CeedElemRestrictionCreateVector(Erestrictx, &xcoord, NULL);
CeedVectorSetArray(xcoord, CEED_MEM_HOST, CEED_COPY_VALUES,
(PetscScalar *)coordArray);
ierr = VecRestoreArrayRead(coords, &coordArray);
// Create the persistent vectors that will be needed in setup and apply
CeedInt nqpts;
CeedBasisGetNumQuadraturePoints(basisu, &nqpts);
CeedVectorCreate(ceed, qdatasize*nelem*nqpts, &qdata);
CeedVectorCreate(ceed, xlsize, &xceed);
CeedVectorCreate(ceed, xlsize, &yceed);
// Create the Q-function that builds the operator (i.e. computes its
// quadrature data) and set its context data
CeedQFunctionCreateInterior(ceed, 1, bpOptions[bpChoice].setupgeo,
bpOptions[bpChoice].setupgeofname, &qf_setupgeo);
CeedQFunctionAddInput(qf_setupgeo, "x", ncompx, CEED_EVAL_INTERP);
CeedQFunctionAddInput(qf_setupgeo, "dx", ncompx*topodim, CEED_EVAL_GRAD);
CeedQFunctionAddInput(qf_setupgeo, "weight", 1, CEED_EVAL_WEIGHT);
CeedQFunctionAddOutput(qf_setupgeo, "qdata", qdatasize, CEED_EVAL_NONE);
// Set up PDE operator
CeedInt inscale = bpOptions[bpChoice].inmode==CEED_EVAL_GRAD ? topodim : 1;
CeedInt outscale = bpOptions[bpChoice].outmode==CEED_EVAL_GRAD ? topodim : 1;
CeedQFunctionCreateInterior(ceed, 1, bpOptions[bpChoice].apply,
bpOptions[bpChoice].applyfname, &qf_apply);
CeedQFunctionAddInput(qf_apply, "u", ncompu*inscale,
bpOptions[bpChoice].inmode);
CeedQFunctionAddInput(qf_apply, "qdata", qdatasize, CEED_EVAL_NONE);
CeedQFunctionAddOutput(qf_apply, "v", ncompu*outscale,
bpOptions[bpChoice].outmode);
// Create the operator that builds the quadrature data for the operator
CeedOperatorCreate(ceed, qf_setupgeo, NULL, NULL, &op_setupgeo);
CeedOperatorSetField(op_setupgeo, "x", Erestrictx, basisx,
CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_setupgeo, "dx", Erestrictx, basisx,
CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_setupgeo, "weight", CEED_ELEMRESTRICTION_NONE, basisx,
CEED_VECTOR_NONE);
CeedOperatorSetField(op_setupgeo, "qdata", Erestrictqdi,
CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);
// Create the mass or diff operator
CeedOperatorCreate(ceed, qf_apply, NULL, NULL, &op_apply);
CeedOperatorSetField(op_apply, "u", Erestrictu, basisu, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_apply, "qdata", Erestrictqdi, CEED_BASIS_COLLOCATED,
qdata);
CeedOperatorSetField(op_apply, "v", Erestrictu, basisu, CEED_VECTOR_ACTIVE);
// Setup qdata
CeedOperatorApply(op_setupgeo, xcoord, qdata, CEED_REQUEST_IMMEDIATE);
// Set up RHS if needed
if (setup_rhs) {
CeedQFunction qf_setuprhs;
CeedOperator op_setuprhs;
CeedVectorCreate(ceed, nelem*nqpts*ncompu, target);
// Create the q-function that sets up the RHS and true solution
CeedQFunctionCreateInterior(ceed, 1, bpOptions[bpChoice].setuprhs,
bpOptions[bpChoice].setuprhsfname, &qf_setuprhs);
CeedQFunctionAddInput(qf_setuprhs, "x", ncompx, CEED_EVAL_INTERP);
CeedQFunctionAddInput(qf_setuprhs, "qdata", qdatasize, CEED_EVAL_NONE);
CeedQFunctionAddOutput(qf_setuprhs, "true_soln", ncompu, CEED_EVAL_NONE);
CeedQFunctionAddOutput(qf_setuprhs, "rhs", ncompu, CEED_EVAL_INTERP);
// Create the operator that builds the RHS and true solution
CeedOperatorCreate(ceed, qf_setuprhs, NULL, NULL, &op_setuprhs);
CeedOperatorSetField(op_setuprhs, "x", Erestrictx, basisx, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_setuprhs, "qdata", Erestrictqdi, CEED_BASIS_COLLOCATED,
qdata);
CeedOperatorSetField(op_setuprhs, "true_soln", Erestrictui,
CEED_BASIS_COLLOCATED,
*target);
CeedOperatorSetField(op_setuprhs, "rhs", Erestrictu, basisu,
CEED_VECTOR_ACTIVE);
// Set up the libCEED context
CeedQFunctionContext rhsSetup;
CeedQFunctionContextCreate(ceed, &rhsSetup);
CeedScalar rhsSetupData[2] = {R, l};
CeedQFunctionContextSetData(rhsSetup, CEED_MEM_HOST, CEED_COPY_VALUES,
sizeof rhsSetupData, &rhsSetupData);
CeedQFunctionSetContext(qf_setuprhs, rhsSetup);
CeedQFunctionContextDestroy(&rhsSetup);
// Setup RHS and target
CeedOperatorApply(op_setuprhs, xcoord, rhsceed, CEED_REQUEST_IMMEDIATE);
CeedVectorTakeArray(rhsceed, CEED_MEM_HOST, NULL);
// Cleanup
CeedQFunctionDestroy(&qf_setuprhs);
CeedOperatorDestroy(&op_setuprhs);
}
// Cleanup
CeedQFunctionDestroy(&qf_setupgeo);
CeedOperatorDestroy(&op_setupgeo);
CeedVectorDestroy(&xcoord);
// Save libCEED data required for level
data->basisx = basisx; data->basisu = basisu;
data->Erestrictx = Erestrictx;
data->Erestrictu = Erestrictu;
data->Erestrictui = Erestrictui;
data->Erestrictqdi = Erestrictqdi;
data->qf_apply = qf_apply;
data->op_apply = op_apply;
data->qdata = qdata;
data->xceed = xceed;
data->yceed = yceed;
PetscFunctionReturn(0);
}
#ifdef multigrid
// Setup libCEED level transfer operator objects
static PetscErrorCode CeedLevelTransferSetup(Ceed ceed, CeedInt numlevels,
CeedInt ncompu, bpType bpChoice, CeedData *data, CeedInt *leveldegrees,
CeedQFunction qf_restrict, CeedQFunction qf_prolong) {
// Return early if numlevels=1
if (numlevels==1)
PetscFunctionReturn(0);
// Set up each level
for (CeedInt i=1; i<numlevels; i++) {
// P coarse and P fine
CeedInt Pc = leveldegrees[i-1] + 1;
CeedInt Pf = leveldegrees[i] + 1;
// Restriction - Fine to corse
CeedBasis basisctof;
CeedOperator op_restrict;
// Basis
CeedBasisCreateTensorH1Lagrange(ceed, 3, ncompu, Pc, Pf,
CEED_GAUSS_LOBATTO, &basisctof);
// Create the restriction operator
CeedOperatorCreate(ceed, qf_restrict, NULL, NULL, &op_restrict);
CeedOperatorSetField(op_restrict, "input", data[i]->Erestrictu,
CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_restrict, "output", data[i-1]->Erestrictu,
basisctof, CEED_VECTOR_ACTIVE);
// Save libCEED data required for level
data[i]->basisctof = basisctof;
data[i]->op_restrict = op_restrict;
// Interpolation - Corse to fine
CeedOperator op_interp;
// Create the prolongation operator
CeedOperatorCreate(ceed, qf_prolong, NULL, NULL, &op_interp);
CeedOperatorSetField(op_interp, "uin", data[i-1]->Erestrictu,
basisctof, CEED_VECTOR_ACTIVE);
CeedOperatorSetField(op_interp, "uout", data[i]->Erestrictu,
CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);
// Save libCEED data required for level
data[i]->op_interp = op_interp;
}
PetscFunctionReturn(0);
}
#endif
// -----------------------------------------------------------------------------
// Mat Shell Functions
// -----------------------------------------------------------------------------
#ifdef multigrid
// This function returns the computed diagonal of the operator
static PetscErrorCode MatGetDiag(Mat A, Vec D) {
PetscErrorCode ierr;
UserO user;
PetscFunctionBeginUser;
ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);
ierr = VecCopy(user->diag, D); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#endif
// This function uses libCEED to compute the action of the Laplacian with
// Dirichlet boundary conditions
static PetscErrorCode MatMult_Ceed(Mat A, Vec X, Vec Y) {
PetscErrorCode ierr;
UserO user;
PetscScalar *x, *y;
PetscFunctionBeginUser;
ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);
// Global-to-local
ierr = DMGlobalToLocalBegin(user->dm, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(user->dm, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);
// Setup CEED vectors
ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);
ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);
CeedVectorSetArray(user->xceed, CEED_MEM_HOST, CEED_USE_POINTER, x);
CeedVectorSetArray(user->yceed, CEED_MEM_HOST, CEED_USE_POINTER, y);
// Apply CEED operator
CeedOperatorApply(user->op, user->xceed, user->yceed, CEED_REQUEST_IMMEDIATE);
// Restore PETSc vectors
CeedVectorTakeArray(user->xceed, CEED_MEM_HOST, NULL);
CeedVectorTakeArray(user->yceed, CEED_MEM_HOST, NULL);
ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);
CHKERRQ(ierr);
ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);
// Local-to-global
ierr = VecZeroEntries(Y); CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(user->dm, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(user->dm, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#ifdef multigrid
// This function uses libCEED to compute the action of the interp operator
static PetscErrorCode MatMult_Interp(Mat A, Vec X, Vec Y) {
PetscErrorCode ierr;
UserIR user;
PetscScalar *x, *y;
PetscFunctionBeginUser;
ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);
// Global-to-local
ierr = VecZeroEntries(user->Xloc); CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(user->dmc, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(user->dmc, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);
// Setup CEED vectors
ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);
ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);
CeedVectorSetArray(user->ceedvecc, CEED_MEM_HOST, CEED_USE_POINTER, x);
CeedVectorSetArray(user->ceedvecf, CEED_MEM_HOST, CEED_USE_POINTER, y);
// Apply CEED operator
CeedOperatorApply(user->op, user->ceedvecc, user->ceedvecf,
CEED_REQUEST_IMMEDIATE);
// Restore PETSc vectors
CeedVectorTakeArray(user->ceedvecc, CEED_MEM_HOST, NULL);
CeedVectorTakeArray(user->ceedvecf, CEED_MEM_HOST, NULL);
ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);
CHKERRQ(ierr);
ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);
// Multiplicity
ierr = VecPointwiseMult(user->Yloc, user->Yloc, user->mult);
// Local-to-global
ierr = VecZeroEntries(Y); CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(user->dmf, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(user->dmf, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
PetscFunctionReturn(0);
}
// This function uses libCEED to compute the action of the restriction operator
static PetscErrorCode MatMult_Restrict(Mat A, Vec X, Vec Y) {
PetscErrorCode ierr;
UserIR user;
PetscScalar *x, *y;
PetscFunctionBeginUser;
ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);
// Global-to-local
ierr = VecZeroEntries(user->Xloc); CHKERRQ(ierr);
ierr = DMGlobalToLocalBegin(user->dmf, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = DMGlobalToLocalEnd(user->dmf, X, INSERT_VALUES, user->Xloc);
CHKERRQ(ierr);
ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);
// Multiplicity
ierr = VecPointwiseMult(user->Xloc, user->Xloc, user->mult); CHKERRQ(ierr);
// Setup CEED vectors
ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);
ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);
CeedVectorSetArray(user->ceedvecf, CEED_MEM_HOST, CEED_USE_POINTER, x);
CeedVectorSetArray(user->ceedvecc, CEED_MEM_HOST, CEED_USE_POINTER, y);
// Apply CEED operator
CeedOperatorApply(user->op, user->ceedvecf, user->ceedvecc,
CEED_REQUEST_IMMEDIATE);
// Restore PETSc vectors
CeedVectorTakeArray(user->ceedvecf, CEED_MEM_HOST, NULL);
CeedVectorTakeArray(user->ceedvecc, CEED_MEM_HOST, NULL);
ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);
CHKERRQ(ierr);
ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);
// Local-to-global
ierr = VecZeroEntries(Y); CHKERRQ(ierr);
ierr = DMLocalToGlobalBegin(user->dmc, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
ierr = DMLocalToGlobalEnd(user->dmc, user->Yloc, ADD_VALUES, Y);
CHKERRQ(ierr);
PetscFunctionReturn(0);
}
#endif
// This function calculates the error in the final solution
static PetscErrorCode ComputeErrorMax(UserO user, CeedOperator op_error,
Vec X, CeedVector target,
PetscReal *maxerror) {
PetscErrorCode ierr;
PetscScalar *x;
CeedVector collocated_error;
CeedInt length;
PetscFunctionBeginUser;
CeedVectorGetLength(target, &length);
CeedVectorCreate(user->ceed, length, &collocated_error);
// Global-to-local
ierr = DMGlobalToLocal(user->dm, X, INSERT_VALUES, user->Xloc); CHKERRQ(ierr);
// Setup CEED vector
ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);
CeedVectorSetArray(user->xceed, CEED_MEM_HOST, CEED_USE_POINTER, x);
// Apply CEED operator
CeedOperatorApply(op_error, user->xceed, collocated_error,
CEED_REQUEST_IMMEDIATE);
// Restore PETSc vector
VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);
// Reduce max error
*maxerror = 0;
const CeedScalar *e;
CeedVectorGetArrayRead(collocated_error, CEED_MEM_HOST, &e);
for (CeedInt i=0; i<length; i++) {
*maxerror = PetscMax(*maxerror, PetscAbsScalar(e[i]));
}
CeedVectorRestoreArrayRead(collocated_error, &e);
ierr = MPI_Allreduce(MPI_IN_PLACE, maxerror,
1, MPIU_REAL, MPIU_MAX, user->comm); CHKERRQ(ierr);
// Cleanup
CeedVectorDestroy(&collocated_error);
PetscFunctionReturn(0);
}
#endif // setupsphere_h
| {
"alphanum_fraction": 0.6511718623,
"avg_line_length": 36.4922894425,
"ext": "h",
"hexsha": "6820308f54bfe2632f345b3bc7de48ad63fa19f7",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-03-30T23:13:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-30T23:13:18.000Z",
"max_forks_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "barker29/libCEED",
"max_forks_repo_path": "examples/petsc/setupsphere.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514",
"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": "barker29/libCEED",
"max_issues_repo_path": "examples/petsc/setupsphere.h",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "barker29/libCEED",
"max_stars_repo_path": "examples/petsc/setupsphere.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 8646,
"size": 30763
} |
#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_rotg (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
float a = -1.5f;
float b = -1.5f;
float c;
float s;
float r_expected = -2.12132034356f;
float z_expected = 1.41421356237f;
float c_expected = 0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 166)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 167)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 168)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 169)");
};
{
float a = -1.5f;
float b = -1.0f;
float c;
float s;
float r_expected = -1.80277563773f;
float z_expected = 0.554700196225f;
float c_expected = 0.832050294338f;
float s_expected = 0.554700196225f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 170)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 171)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 172)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 173)");
};
{
float a = -1.5f;
float b = -0.1f;
float c;
float s;
float r_expected = -1.50332963784f;
float z_expected = 0.0665190105238f;
float c_expected = 0.997785157857f;
float s_expected = 0.0665190105238f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 174)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 175)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 176)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 177)");
};
{
float a = -1.5f;
float b = 0.0f;
float c;
float s;
float r_expected = -1.5f;
float z_expected = -0.0f;
float c_expected = 1.0f;
float s_expected = -0.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 178)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 179)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 180)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 181)");
};
{
float a = -1.5f;
float b = 0.1f;
float c;
float s;
float r_expected = -1.50332963784f;
float z_expected = -0.0665190105238f;
float c_expected = 0.997785157857f;
float s_expected = -0.0665190105238f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 182)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 183)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 184)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 185)");
};
{
float a = -1.5f;
float b = 1.0f;
float c;
float s;
float r_expected = -1.80277563773f;
float z_expected = -0.554700196225f;
float c_expected = 0.832050294338f;
float s_expected = -0.554700196225f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 186)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 187)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 188)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 189)");
};
{
float a = -1.5f;
float b = 1.5f;
float c;
float s;
float r_expected = 2.12132034356f;
float z_expected = -1.41421356237f;
float c_expected = -0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 190)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 191)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 192)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 193)");
};
{
float a = -1.0f;
float b = -1.5f;
float c;
float s;
float r_expected = -1.80277563773f;
float z_expected = 1.80277563773f;
float c_expected = 0.554700196225f;
float s_expected = 0.832050294338f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 194)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 195)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 196)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 197)");
};
{
float a = -1.0f;
float b = -1.0f;
float c;
float s;
float r_expected = -1.41421356237f;
float z_expected = 1.41421356237f;
float c_expected = 0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 198)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 199)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 200)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 201)");
};
{
float a = -1.0f;
float b = -0.1f;
float c;
float s;
float r_expected = -1.00498756211f;
float z_expected = 0.099503719021f;
float c_expected = 0.99503719021f;
float s_expected = 0.099503719021f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 202)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 203)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 204)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 205)");
};
{
float a = -1.0f;
float b = 0.0f;
float c;
float s;
float r_expected = -1.0f;
float z_expected = -0.0f;
float c_expected = 1.0f;
float s_expected = -0.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 206)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 207)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 208)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 209)");
};
{
float a = -1.0f;
float b = 0.1f;
float c;
float s;
float r_expected = -1.00498756211f;
float z_expected = -0.099503719021f;
float c_expected = 0.99503719021f;
float s_expected = -0.099503719021f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 210)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 211)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 212)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 213)");
};
{
float a = -1.0f;
float b = 1.0f;
float c;
float s;
float r_expected = 1.41421356237f;
float z_expected = -1.41421356237f;
float c_expected = -0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 214)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 215)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 216)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 217)");
};
{
float a = -1.0f;
float b = 1.5f;
float c;
float s;
float r_expected = 1.80277563773f;
float z_expected = -1.80277563773f;
float c_expected = -0.554700196225f;
float s_expected = 0.832050294338f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 218)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 219)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 220)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 221)");
};
{
float a = -0.1f;
float b = -1.5f;
float c;
float s;
float r_expected = -1.50332963784f;
float z_expected = 15.0332963784f;
float c_expected = 0.0665190105238f;
float s_expected = 0.997785157857f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 222)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 223)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 224)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 225)");
};
{
float a = -0.1f;
float b = -1.0f;
float c;
float s;
float r_expected = -1.00498756211f;
float z_expected = 10.0498756211f;
float c_expected = 0.099503719021f;
float s_expected = 0.99503719021f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 226)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 227)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 228)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 229)");
};
{
float a = -0.1f;
float b = -0.1f;
float c;
float s;
float r_expected = -0.141421356237f;
float z_expected = 1.41421356237f;
float c_expected = 0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 230)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 231)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 232)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 233)");
};
{
float a = -0.1f;
float b = 0.0f;
float c;
float s;
float r_expected = -0.1f;
float z_expected = -0.0f;
float c_expected = 1.0f;
float s_expected = -0.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 234)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 235)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 236)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 237)");
};
{
float a = -0.1f;
float b = 0.1f;
float c;
float s;
float r_expected = 0.141421356237f;
float z_expected = -1.41421356237f;
float c_expected = -0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 238)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 239)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 240)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 241)");
};
{
float a = -0.1f;
float b = 1.0f;
float c;
float s;
float r_expected = 1.00498756211f;
float z_expected = -10.0498756211f;
float c_expected = -0.099503719021f;
float s_expected = 0.99503719021f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 242)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 243)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 244)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 245)");
};
{
float a = -0.1f;
float b = 1.5f;
float c;
float s;
float r_expected = 1.50332963784f;
float z_expected = -15.0332963784f;
float c_expected = -0.0665190105238f;
float s_expected = 0.997785157857f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 246)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 247)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 248)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 249)");
};
{
float a = 0.0f;
float b = -1.5f;
float c;
float s;
float r_expected = -1.5f;
float z_expected = 1.0f;
float c_expected = -0.0f;
float s_expected = 1.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 250)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 251)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 252)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 253)");
};
{
float a = 0.0f;
float b = -1.0f;
float c;
float s;
float r_expected = -1.0f;
float z_expected = 1.0f;
float c_expected = -0.0f;
float s_expected = 1.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 254)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 255)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 256)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 257)");
};
{
float a = 0.0f;
float b = -0.1f;
float c;
float s;
float r_expected = -0.1f;
float z_expected = 1.0f;
float c_expected = -0.0f;
float s_expected = 1.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 258)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 259)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 260)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 261)");
};
{
float a = 0.0f;
float b = 0.0f;
float c;
float s;
float r_expected = 0.0f;
float z_expected = 0.0f;
float c_expected = 1.0f;
float s_expected = 0.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 262)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 263)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 264)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 265)");
};
{
float a = 0.0f;
float b = 0.1f;
float c;
float s;
float r_expected = 0.1f;
float z_expected = 1.0f;
float c_expected = 0.0f;
float s_expected = 1.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 266)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 267)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 268)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 269)");
};
{
float a = 0.0f;
float b = 1.0f;
float c;
float s;
float r_expected = 1.0f;
float z_expected = 1.0f;
float c_expected = 0.0f;
float s_expected = 1.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 270)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 271)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 272)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 273)");
};
{
float a = 0.0f;
float b = 1.5f;
float c;
float s;
float r_expected = 1.5f;
float z_expected = 1.0f;
float c_expected = 0.0f;
float s_expected = 1.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 274)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 275)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 276)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 277)");
};
{
float a = 0.1f;
float b = -1.5f;
float c;
float s;
float r_expected = -1.50332963784f;
float z_expected = -15.0332963784f;
float c_expected = -0.0665190105238f;
float s_expected = 0.997785157857f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 278)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 279)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 280)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 281)");
};
{
float a = 0.1f;
float b = -1.0f;
float c;
float s;
float r_expected = -1.00498756211f;
float z_expected = -10.0498756211f;
float c_expected = -0.099503719021f;
float s_expected = 0.99503719021f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 282)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 283)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 284)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 285)");
};
{
float a = 0.1f;
float b = -0.1f;
float c;
float s;
float r_expected = -0.141421356237f;
float z_expected = -1.41421356237f;
float c_expected = -0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 286)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 287)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 288)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 289)");
};
{
float a = 0.1f;
float b = 0.0f;
float c;
float s;
float r_expected = 0.1f;
float z_expected = 0.0f;
float c_expected = 1.0f;
float s_expected = 0.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 290)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 291)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 292)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 293)");
};
{
float a = 0.1f;
float b = 0.1f;
float c;
float s;
float r_expected = 0.141421356237f;
float z_expected = 1.41421356237f;
float c_expected = 0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 294)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 295)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 296)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 297)");
};
{
float a = 0.1f;
float b = 1.0f;
float c;
float s;
float r_expected = 1.00498756211f;
float z_expected = 10.0498756211f;
float c_expected = 0.099503719021f;
float s_expected = 0.99503719021f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 298)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 299)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 300)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 301)");
};
{
float a = 0.1f;
float b = 1.5f;
float c;
float s;
float r_expected = 1.50332963784f;
float z_expected = 15.0332963784f;
float c_expected = 0.0665190105238f;
float s_expected = 0.997785157857f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 302)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 303)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 304)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 305)");
};
{
float a = 1.0f;
float b = -1.5f;
float c;
float s;
float r_expected = -1.80277563773f;
float z_expected = -1.80277563773f;
float c_expected = -0.554700196225f;
float s_expected = 0.832050294338f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 306)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 307)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 308)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 309)");
};
{
float a = 1.0f;
float b = -1.0f;
float c;
float s;
float r_expected = -1.41421356237f;
float z_expected = -1.41421356237f;
float c_expected = -0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 310)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 311)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 312)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 313)");
};
{
float a = 1.0f;
float b = -0.1f;
float c;
float s;
float r_expected = 1.00498756211f;
float z_expected = -0.099503719021f;
float c_expected = 0.99503719021f;
float s_expected = -0.099503719021f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 314)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 315)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 316)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 317)");
};
{
float a = 1.0f;
float b = 0.0f;
float c;
float s;
float r_expected = 1.0f;
float z_expected = 0.0f;
float c_expected = 1.0f;
float s_expected = 0.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 318)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 319)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 320)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 321)");
};
{
float a = 1.0f;
float b = 0.1f;
float c;
float s;
float r_expected = 1.00498756211f;
float z_expected = 0.099503719021f;
float c_expected = 0.99503719021f;
float s_expected = 0.099503719021f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 322)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 323)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 324)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 325)");
};
{
float a = 1.0f;
float b = 1.0f;
float c;
float s;
float r_expected = 1.41421356237f;
float z_expected = 1.41421356237f;
float c_expected = 0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 326)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 327)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 328)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 329)");
};
{
float a = 1.0f;
float b = 1.5f;
float c;
float s;
float r_expected = 1.80277563773f;
float z_expected = 1.80277563773f;
float c_expected = 0.554700196225f;
float s_expected = 0.832050294338f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 330)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 331)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 332)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 333)");
};
{
float a = 1.5f;
float b = -1.5f;
float c;
float s;
float r_expected = -2.12132034356f;
float z_expected = -1.41421356237f;
float c_expected = -0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 334)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 335)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 336)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 337)");
};
{
float a = 1.5f;
float b = -1.0f;
float c;
float s;
float r_expected = 1.80277563773f;
float z_expected = -0.554700196225f;
float c_expected = 0.832050294338f;
float s_expected = -0.554700196225f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 338)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 339)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 340)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 341)");
};
{
float a = 1.5f;
float b = -0.1f;
float c;
float s;
float r_expected = 1.50332963784f;
float z_expected = -0.0665190105238f;
float c_expected = 0.997785157857f;
float s_expected = -0.0665190105238f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 342)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 343)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 344)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 345)");
};
{
float a = 1.5f;
float b = 0.0f;
float c;
float s;
float r_expected = 1.5f;
float z_expected = 0.0f;
float c_expected = 1.0f;
float s_expected = 0.0f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 346)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 347)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 348)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 349)");
};
{
float a = 1.5f;
float b = 0.1f;
float c;
float s;
float r_expected = 1.50332963784f;
float z_expected = 0.0665190105238f;
float c_expected = 0.997785157857f;
float s_expected = 0.0665190105238f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 350)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 351)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 352)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 353)");
};
{
float a = 1.5f;
float b = 1.0f;
float c;
float s;
float r_expected = 1.80277563773f;
float z_expected = 0.554700196225f;
float c_expected = 0.832050294338f;
float s_expected = 0.554700196225f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 354)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 355)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 356)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 357)");
};
{
float a = 1.5f;
float b = 1.5f;
float c;
float s;
float r_expected = 2.12132034356f;
float z_expected = 1.41421356237f;
float c_expected = 0.707106781187f;
float s_expected = 0.707106781187f;
cblas_srotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, flteps, "srotg(case 358)");
gsl_test_rel(b, z_expected, flteps, "srotg(case 359)");
gsl_test_rel(c, c_expected, flteps, "srotg(case 360)");
gsl_test_rel(s, s_expected, flteps, "srotg(case 361)");
};
{
double a = -1.5;
double b = -1.5;
double c;
double s;
double r_expected = -2.12132034356;
double z_expected = 1.41421356237;
double c_expected = 0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 362)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 363)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 364)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 365)");
};
{
double a = -1.5;
double b = -1;
double c;
double s;
double r_expected = -1.80277563773;
double z_expected = 0.554700196225;
double c_expected = 0.832050294338;
double s_expected = 0.554700196225;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 366)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 367)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 368)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 369)");
};
{
double a = -1.5;
double b = -0.1;
double c;
double s;
double r_expected = -1.50332963784;
double z_expected = 0.0665190105238;
double c_expected = 0.997785157857;
double s_expected = 0.0665190105238;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 370)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 371)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 372)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 373)");
};
{
double a = -1.5;
double b = 0;
double c;
double s;
double r_expected = -1.5;
double z_expected = -0;
double c_expected = 1;
double s_expected = -0;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 374)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 375)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 376)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 377)");
};
{
double a = -1.5;
double b = 0.1;
double c;
double s;
double r_expected = -1.50332963784;
double z_expected = -0.0665190105238;
double c_expected = 0.997785157857;
double s_expected = -0.0665190105238;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 378)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 379)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 380)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 381)");
};
{
double a = -1.5;
double b = 1;
double c;
double s;
double r_expected = -1.80277563773;
double z_expected = -0.554700196225;
double c_expected = 0.832050294338;
double s_expected = -0.554700196225;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 382)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 383)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 384)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 385)");
};
{
double a = -1.5;
double b = 1.5;
double c;
double s;
double r_expected = 2.12132034356;
double z_expected = -1.41421356237;
double c_expected = -0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 386)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 387)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 388)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 389)");
};
{
double a = -1;
double b = -1.5;
double c;
double s;
double r_expected = -1.80277563773;
double z_expected = 1.80277563773;
double c_expected = 0.554700196225;
double s_expected = 0.832050294338;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 390)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 391)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 392)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 393)");
};
{
double a = -1;
double b = -1;
double c;
double s;
double r_expected = -1.41421356237;
double z_expected = 1.41421356237;
double c_expected = 0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 394)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 395)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 396)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 397)");
};
{
double a = -1;
double b = -0.1;
double c;
double s;
double r_expected = -1.00498756211;
double z_expected = 0.099503719021;
double c_expected = 0.99503719021;
double s_expected = 0.099503719021;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 398)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 399)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 400)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 401)");
};
{
double a = -1;
double b = 0;
double c;
double s;
double r_expected = -1;
double z_expected = -0;
double c_expected = 1;
double s_expected = -0;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 402)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 403)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 404)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 405)");
};
{
double a = -1;
double b = 0.1;
double c;
double s;
double r_expected = -1.00498756211;
double z_expected = -0.099503719021;
double c_expected = 0.99503719021;
double s_expected = -0.099503719021;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 406)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 407)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 408)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 409)");
};
{
double a = -1;
double b = 1;
double c;
double s;
double r_expected = 1.41421356237;
double z_expected = -1.41421356237;
double c_expected = -0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 410)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 411)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 412)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 413)");
};
{
double a = -1;
double b = 1.5;
double c;
double s;
double r_expected = 1.80277563773;
double z_expected = -1.80277563773;
double c_expected = -0.554700196225;
double s_expected = 0.832050294338;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 414)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 415)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 416)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 417)");
};
{
double a = -0.1;
double b = -1.5;
double c;
double s;
double r_expected = -1.50332963784;
double z_expected = 15.0332963784;
double c_expected = 0.0665190105238;
double s_expected = 0.997785157857;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 418)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 419)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 420)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 421)");
};
{
double a = -0.1;
double b = -1;
double c;
double s;
double r_expected = -1.00498756211;
double z_expected = 10.0498756211;
double c_expected = 0.099503719021;
double s_expected = 0.99503719021;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 422)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 423)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 424)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 425)");
};
{
double a = -0.1;
double b = -0.1;
double c;
double s;
double r_expected = -0.141421356237;
double z_expected = 1.41421356237;
double c_expected = 0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 426)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 427)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 428)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 429)");
};
{
double a = -0.1;
double b = 0;
double c;
double s;
double r_expected = -0.1;
double z_expected = -0;
double c_expected = 1;
double s_expected = -0;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 430)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 431)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 432)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 433)");
};
{
double a = -0.1;
double b = 0.1;
double c;
double s;
double r_expected = 0.141421356237;
double z_expected = -1.41421356237;
double c_expected = -0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 434)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 435)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 436)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 437)");
};
{
double a = -0.1;
double b = 1;
double c;
double s;
double r_expected = 1.00498756211;
double z_expected = -10.0498756211;
double c_expected = -0.099503719021;
double s_expected = 0.99503719021;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 438)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 439)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 440)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 441)");
};
{
double a = -0.1;
double b = 1.5;
double c;
double s;
double r_expected = 1.50332963784;
double z_expected = -15.0332963784;
double c_expected = -0.0665190105238;
double s_expected = 0.997785157857;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 442)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 443)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 444)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 445)");
};
{
double a = 0;
double b = -1.5;
double c;
double s;
double r_expected = -1.5;
double z_expected = 1;
double c_expected = -0;
double s_expected = 1;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 446)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 447)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 448)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 449)");
};
{
double a = 0;
double b = -1;
double c;
double s;
double r_expected = -1;
double z_expected = 1;
double c_expected = -0;
double s_expected = 1;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 450)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 451)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 452)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 453)");
};
{
double a = 0;
double b = -0.1;
double c;
double s;
double r_expected = -0.1;
double z_expected = 1;
double c_expected = -0;
double s_expected = 1;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 454)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 455)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 456)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 457)");
};
{
double a = 0;
double b = 0;
double c;
double s;
double r_expected = 0;
double z_expected = 0;
double c_expected = 1;
double s_expected = 0;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 458)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 459)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 460)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 461)");
};
{
double a = 0;
double b = 0.1;
double c;
double s;
double r_expected = 0.1;
double z_expected = 1;
double c_expected = 0;
double s_expected = 1;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 462)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 463)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 464)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 465)");
};
{
double a = 0;
double b = 1;
double c;
double s;
double r_expected = 1;
double z_expected = 1;
double c_expected = 0;
double s_expected = 1;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 466)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 467)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 468)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 469)");
};
{
double a = 0;
double b = 1.5;
double c;
double s;
double r_expected = 1.5;
double z_expected = 1;
double c_expected = 0;
double s_expected = 1;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 470)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 471)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 472)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 473)");
};
{
double a = 0.1;
double b = -1.5;
double c;
double s;
double r_expected = -1.50332963784;
double z_expected = -15.0332963784;
double c_expected = -0.0665190105238;
double s_expected = 0.997785157857;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 474)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 475)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 476)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 477)");
};
{
double a = 0.1;
double b = -1;
double c;
double s;
double r_expected = -1.00498756211;
double z_expected = -10.0498756211;
double c_expected = -0.099503719021;
double s_expected = 0.99503719021;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 478)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 479)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 480)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 481)");
};
{
double a = 0.1;
double b = -0.1;
double c;
double s;
double r_expected = -0.141421356237;
double z_expected = -1.41421356237;
double c_expected = -0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 482)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 483)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 484)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 485)");
};
{
double a = 0.1;
double b = 0;
double c;
double s;
double r_expected = 0.1;
double z_expected = 0;
double c_expected = 1;
double s_expected = 0;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 486)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 487)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 488)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 489)");
};
{
double a = 0.1;
double b = 0.1;
double c;
double s;
double r_expected = 0.141421356237;
double z_expected = 1.41421356237;
double c_expected = 0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 490)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 491)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 492)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 493)");
};
{
double a = 0.1;
double b = 1;
double c;
double s;
double r_expected = 1.00498756211;
double z_expected = 10.0498756211;
double c_expected = 0.099503719021;
double s_expected = 0.99503719021;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 494)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 495)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 496)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 497)");
};
{
double a = 0.1;
double b = 1.5;
double c;
double s;
double r_expected = 1.50332963784;
double z_expected = 15.0332963784;
double c_expected = 0.0665190105238;
double s_expected = 0.997785157857;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 498)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 499)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 500)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 501)");
};
{
double a = 1;
double b = -1.5;
double c;
double s;
double r_expected = -1.80277563773;
double z_expected = -1.80277563773;
double c_expected = -0.554700196225;
double s_expected = 0.832050294338;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 502)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 503)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 504)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 505)");
};
{
double a = 1;
double b = -1;
double c;
double s;
double r_expected = -1.41421356237;
double z_expected = -1.41421356237;
double c_expected = -0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 506)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 507)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 508)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 509)");
};
{
double a = 1;
double b = -0.1;
double c;
double s;
double r_expected = 1.00498756211;
double z_expected = -0.099503719021;
double c_expected = 0.99503719021;
double s_expected = -0.099503719021;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 510)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 511)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 512)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 513)");
};
{
double a = 1;
double b = 0;
double c;
double s;
double r_expected = 1;
double z_expected = 0;
double c_expected = 1;
double s_expected = 0;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 514)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 515)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 516)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 517)");
};
{
double a = 1;
double b = 0.1;
double c;
double s;
double r_expected = 1.00498756211;
double z_expected = 0.099503719021;
double c_expected = 0.99503719021;
double s_expected = 0.099503719021;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 518)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 519)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 520)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 521)");
};
{
double a = 1;
double b = 1;
double c;
double s;
double r_expected = 1.41421356237;
double z_expected = 1.41421356237;
double c_expected = 0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 522)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 523)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 524)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 525)");
};
{
double a = 1;
double b = 1.5;
double c;
double s;
double r_expected = 1.80277563773;
double z_expected = 1.80277563773;
double c_expected = 0.554700196225;
double s_expected = 0.832050294338;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 526)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 527)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 528)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 529)");
};
{
double a = 1.5;
double b = -1.5;
double c;
double s;
double r_expected = -2.12132034356;
double z_expected = -1.41421356237;
double c_expected = -0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 530)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 531)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 532)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 533)");
};
{
double a = 1.5;
double b = -1;
double c;
double s;
double r_expected = 1.80277563773;
double z_expected = -0.554700196225;
double c_expected = 0.832050294338;
double s_expected = -0.554700196225;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 534)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 535)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 536)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 537)");
};
{
double a = 1.5;
double b = -0.1;
double c;
double s;
double r_expected = 1.50332963784;
double z_expected = -0.0665190105238;
double c_expected = 0.997785157857;
double s_expected = -0.0665190105238;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 538)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 539)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 540)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 541)");
};
{
double a = 1.5;
double b = 0;
double c;
double s;
double r_expected = 1.5;
double z_expected = 0;
double c_expected = 1;
double s_expected = 0;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 542)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 543)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 544)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 545)");
};
{
double a = 1.5;
double b = 0.1;
double c;
double s;
double r_expected = 1.50332963784;
double z_expected = 0.0665190105238;
double c_expected = 0.997785157857;
double s_expected = 0.0665190105238;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 546)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 547)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 548)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 549)");
};
{
double a = 1.5;
double b = 1;
double c;
double s;
double r_expected = 1.80277563773;
double z_expected = 0.554700196225;
double c_expected = 0.832050294338;
double s_expected = 0.554700196225;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 550)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 551)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 552)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 553)");
};
{
double a = 1.5;
double b = 1.5;
double c;
double s;
double r_expected = 2.12132034356;
double z_expected = 1.41421356237;
double c_expected = 0.707106781187;
double s_expected = 0.707106781187;
cblas_drotg(&a, &b, &c, &s);
gsl_test_rel(a, r_expected, dbleps, "drotg(case 554)");
gsl_test_rel(b, z_expected, dbleps, "drotg(case 555)");
gsl_test_rel(c, c_expected, dbleps, "drotg(case 556)");
gsl_test_rel(s, s_expected, dbleps, "drotg(case 557)");
};
}
| {
"alphanum_fraction": 0.6433367498,
"avg_line_length": 28.4904648391,
"ext": "c",
"hexsha": "a5a84d3cd25c5f315218e9854eb2f178c6d7ec76",
"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_rotg.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_rotg.c",
"max_line_length": 58,
"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_rotg.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": 17942,
"size": 47807
} |
/* TwoAdvSelfSims.c
Simulation calculating fixation probability of second beneficial allele, given existing
ben allele at initial frequency p. For use in the study "Linkage and the limits to natural
selection in partially selfing populations".
Simulation uses routines found with the GNU Scientific Library (GSL)
(http://www.gnu.org/software/gsl/)
Since GSL is distributed under the GNU General Public License
(http://www.gnu.org/copyleft/gpl.html), you must download it
separately from this file.
This program can be compiled with e.g. GCC using a command like:
gcc TwoAdvSelfSims -lm -lgsl -lgslcblas -I/usr/local/include -L/usr/local/lib TwoAdvSelfSims.c
Then run by executing:
./TwoAdvSelfSims N self rec ha sa hb sb p reps
Where:
- N is the population size
- self is the rate of self-fertilisation
- rec is recombination rate
- ha, hb is dominance at the original, introduced beneficial allele
- sa, sb is selection coefficient of the original, introduced beneficial allele
- p is the initial frequency of the first beneficial allele (when the second is introduced)
- reps is how many times the second allele should FIX before simulation stops
(the number of actual runs is greater due to stochastic loss of second allele)
Note that haplotypes are defined as:
x1 = ab
x2 = Ab
x3 = aB
x4 = AB
Genotypes defined as:
g11 = g1 = ab/ab
g12 = g2 = Ab/ab
g13 = g3 = aB/ab
g14 = g4 = AB/ab
g22 = g5 = Ab/Ab
g23 = g6 = Ab/aB
g24 = g7 = Ab/AB
g33 = g8 = aB/aB
g34 = g9 = aB/AB
g44 = g10 = AB/AB
Output files are the parameters;
followed by number of times each haplotype fixed;
followed by average total generations elapsed in each case;
Then total number of simulations ran;
Then fixation prob of allele, both unscaled and scaled to unlinked case,
along with 95% CI intervals for the latter case;
then number of allele fixations.
Note that 'fixation' DIFFERS depending on the inputs of sa, sb.
If sa >= sb (interference case) then 'fixation' counts as fixation of second allele on any genetic background.
If sa < sb (replacement case) then 'fixation' only considers fixation of second allele with neutral haplotype
(I.e. where the 'less fit' neutral allele at locus A fixes, instead of selected allele).
*/
/* Preprocessor statements */
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stddef.h>
#include <string.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
/* Function prototypes */
void geninit(double *geninit, double FIS, const gsl_rng *r);
void selection(double *geninit);
void reproduction(double *geninit);
unsigned int hcheck(double *geninit, double *haps, unsigned int *hf, unsigned int stype);
/* Global variable declaration */
unsigned int N = 0; /* Pop size */
double rec = 0; /* Recombination rate */
double self = 0; /* Rate of self-fertilisation */
double ha = 0; /* Dominance of site A */
double sa = 0; /* Fitness of site A */
double hb = 0; /* Dominance of site B */
double sb = 0; /* Fitness of site B */
double pee = 0; /* Freq of initial sweep */
/* Main program */
int main(int argc, char *argv[]){
unsigned int i; /* A counter */
unsigned int reps; /* Length of simulation (no. of introductions of neutral site) */
unsigned int stype = 0; /* What type of sim (replacement or hitch-hiking)? */
unsigned int nsfix = 0; /* sims where target type fixed */
unsigned int nstot = 0; /* total sims ran */
unsigned int gens = 0; /* Number gens elapsed */
unsigned int isfin = 0; /* Is sim finished? */
unsigned int hf = 0; /* The hap that fixed */
double pf = 0; /* Overall fix prob */
double FIS = 0; /* Wright's FIS */
double StdFix = 0; /* Standard Fixation prob if unlinked */
double citop = 0;
double cibot = 0;
double nsfix2 = 0;
double nstot2 = 0;
char selfchar[10];
char recchar[15];
char hchar[10];
char pchar[10];
char fname[64];
FILE *ofp_tr;
/* GSL random number definitions */
const gsl_rng_type * T;
gsl_rng * r;
/* This reads in data from command line. */
if(argc != 10){
fprintf(stderr,"Invalid number of input values.\n");
exit(1);
}
N = strtod(argv[1],NULL);
self = strtod(argv[2],NULL);
rec = strtod(argv[3],NULL);
ha = strtod(argv[4],NULL);
sa = strtod(argv[5],NULL);
hb = strtod(argv[6],NULL);
sb = strtod(argv[7],NULL);
pee = strtod(argv[8],NULL);
reps = strtod(argv[9],NULL);
if(sa >= sb){
stype = 0;
}else if(sa < sb){
stype = 1;
}
FIS = self/(2.0-self);
/* Arrays definition and memory assignment */
double *genotype = calloc(10,sizeof(double)); /* Genotype frequencies */
unsigned int *gensamp = calloc(10,sizeof(unsigned int)); /* New population samples */
double *haps = calloc(4,sizeof(double)); /* Haplotypes */
unsigned int *pfix = calloc(4,sizeof(unsigned int)); /* Haplotypes that fix */
unsigned int *tfix = calloc(4,sizeof(unsigned int)); /* time that haps fix */
/* create a generator chosen by the
environment variable GSL_RNG_TYPE */
gsl_rng_env_setup();
if (!getenv("GSL_RNG_SEED")) gsl_rng_default_seed = time(0);
T = gsl_rng_default;
r = gsl_rng_alloc(T);
nsfix = 0;
nstot = 0;
while(nsfix < reps){
nstot++;
/* Initialising genotypes */
geninit(genotype,FIS,r);
gens = 0;
isfin = 0;
hf = 0;
while(isfin == 0){
/* Selection routine */
selection(genotype);
/* Reproduction routine */
reproduction(genotype);
/* Sampling based on new frequencies */
gsl_ran_multinomial(r,10,N,genotype,gensamp);
for(i = 0; i < 10; i++){
*(genotype + i) = (*(gensamp + i))/(1.0*N);
}
gens++;
isfin = hcheck(genotype, haps, &hf, stype);
}
if(isfin == 1){
(*(pfix + hf))++;
(*(tfix + hf)) += gens;
if(stype == 0){
nsfix += (*(haps + 2) + *(haps + 3));
}else if(stype == 1){
nsfix += (*(haps + 2));
}
}
} /* End of simulation */
pf = nsfix/(1.0*nstot);
StdFix = 2*sb*((hb+FIS-hb*FIS)/(1+FIS)); /* Fix prob of new allele if unlinked */
nstot2 = nstot + 3.84;
nsfix2 = (1.0/(nstot2))*(nsfix + (3.84/2.0));
citop = nsfix2 + 1.96*sqrt((1.0/(nstot2))*nsfix2*(1.0-nsfix2));
cibot = nsfix2 - 1.96*sqrt((1.0/(nstot2))*nsfix2*(1.0-nsfix2));
citop = citop/(1.0*StdFix);
cibot = cibot/(1.0*StdFix);
/* Printing solutions to file */
/* First, converting values to strings */
sprintf(selfchar, "%0.2lf",self);
sprintf(recchar, "%0.7lf",rec);
sprintf(hchar, "%0.3lf",ha);
sprintf(pchar, "%0.5lf",pee);
strcpy(fname,"sim_self");
strcat(fname,selfchar);
strcat(fname,"rec");
strcat(fname,recchar);
strcat(fname,"h");
strcat(fname,hchar);
strcat(fname,"p");
strcat(fname,pchar);
strcat(fname,".sim");
ofp_tr = fopen(fname,"a+");
fprintf(ofp_tr,"%d %lf %lf %lf %lf %lf %lf %lf ",N,self,rec,ha,sa,hb,sb,pee);
for(i = 0; i < 4; i++){
fprintf(ofp_tr,"%d ",*(pfix + i));
}
for(i = 0; i < 4; i++){
fprintf(ofp_tr,"%lf ",((*(tfix + i)))/(1.0*(*(pfix + i))));
}
fprintf(ofp_tr,"%d %lf %lf %lf %lf %d\n",nstot,pf,pf/(1.0*StdFix),citop,cibot,reps);
fclose(ofp_tr);
/* Freeing memory and wrapping up */
gsl_rng_free(r);
free(tfix);
free(pfix);
free(haps);
free(gensamp);
free(genotype);
return 0;
}
/* Initialising genotypes */
void geninit(double *geninit, double FIS, const gsl_rng *r){
unsigned int htype = 0; /* Type of het assignment */
double *ptype = calloc(3,sizeof(double));
unsigned int *ctype = calloc(3,sizeof(double));
/* Routine to determine initial background of second mutant, given first is at frequency p. */
*(ptype + 0) = (1-pee)*(1-pee) + FIS*pee*(1-pee);
*(ptype + 1) = 2*pee*(1-pee)*(1-FIS);
*(ptype + 2) = pee*pee + FIS*pee*(1-pee);
/* First initialise baseline freqs */
*(geninit + 0) = *(ptype + 0);
*(geninit + 1) = *(ptype + 1);
*(geninit + 2) = 0;
*(geninit + 3) = 0;
*(geninit + 4) = *(ptype + 2);
*(geninit + 5) = 0;
*(geninit + 6) = 0;
*(geninit + 7) = 0;
*(geninit + 8) = 0;
*(geninit + 9) = 0;
/* Then decide where to add new mutant */
gsl_ran_multinomial(r,3,1,ptype,ctype);
if(*(ctype + 0) == 1){
*(geninit + 0) -= 1/(1.0*N);
*(geninit + 2) += 1/(1.0*N);
}else if(*(ctype + 1) == 1){
*(geninit + 1) -= 1/(1.0*N);
htype = gsl_ran_bernoulli(r,0.5);
if(htype == 0){
*(geninit + 5) += 1/(1.0*N);
}else if(htype == 1){
*(geninit + 3) += 1/(1.0*N);
}
}else if(*(ctype + 2) == 1){
*(geninit + 4) -= 1/(1.0*N);
*(geninit + 6) += 1/(1.0*N);
}
free(ctype);
free(ptype);
} /* End of gen initiation routine */
/* Selection routine */
void selection(double *geninit){
/* Fitness of each genotype */
double W11, W12, W13, W14, W22, W23, W24, W33, W34, W44;
double Wmean; /* Mean fitness */
W11 = 1;
W12 = 1 + ha*sa;
W13 = 1 + hb*sb;
W14 = 1 + ha*sa + hb*sb;
W22 = 1 + sa;
W23 = 1 + ha*sa + hb*sb;
W24 = 1 + sa + hb*sb;
W33 = 1 + sb;
W34 = 1 + ha*sa + sb;
W44 = 1 + sa + sb;
/* Mean fitness calculation */
Wmean = ((*(geninit + 0))*W11) + ((*(geninit + 1))*W12) + ((*(geninit + 2))*W13) + ((*(geninit + 3))*W14) + ((*(geninit + 4))*W22) + ((*(geninit + 5))*W23) + ((*(geninit + 6))*W24) + ((*(geninit + 7))*W33) + ((*(geninit + 8))*W34) + ((*(geninit + 9))*W44);
/* Changing frequencies by selection */
*(geninit + 0) = ((*(geninit + 0))*W11)/Wmean;
*(geninit + 1) = ((*(geninit + 1))*W12)/Wmean;
*(geninit + 2) = ((*(geninit + 2))*W13)/Wmean;
*(geninit + 3) = ((*(geninit + 3))*W14)/Wmean;
*(geninit + 4) = ((*(geninit + 4))*W22)/Wmean;
*(geninit + 5) = ((*(geninit + 5))*W23)/Wmean;
*(geninit + 6) = ((*(geninit + 6))*W24)/Wmean;
*(geninit + 7) = ((*(geninit + 7))*W33)/Wmean;
*(geninit + 8) = ((*(geninit + 8))*W34)/Wmean;
*(geninit + 9) = ((*(geninit + 9))*W44)/Wmean;
} /* End of selection routine */
/* Reproduction routine */
void reproduction(double *geninit){
/* Fed-in genotype frequencies (for ease of programming) */
double g11s, g12s, g13s, g14s, g22s, g23s, g24s, g33s, g34s, g44s;
/* Haplotypes */
double x1, x2, x3, x4;
/* Initial definition of genotypes */
g11s = *(geninit + 0);
g12s = *(geninit + 1);
g13s = *(geninit + 2);
g14s = *(geninit + 3);
g22s = *(geninit + 4);
g23s = *(geninit + 5);
g24s = *(geninit + 6);
g33s = *(geninit + 7);
g34s = *(geninit + 8);
g44s = *(geninit + 9);
/* Baseline change in haplotype frequencies */
x1 = g11s + (g12s + g13s + g14s)/2.0 - ((g14s - g23s)*rec)/2.0;
x2 = g22s + (g12s + g23s + g24s)/2.0 + ((g14s - g23s)*rec)/2.0;
x3 = g33s + (g13s + g23s + g34s)/2.0 + ((g14s - g23s)*rec)/2.0;
x4 = g44s + (g14s + g24s + g34s)/2.0 - ((g14s - g23s)*rec)/2.0;
/* Change in SEXUAL frequencies (both outcrossing and selfing) */
*(geninit + 0) = (g11s + (g12s + g13s + g14s*pow((1 - rec),2) + g23s*pow(rec,2))/4.0)*self + (1 - self)*pow(x1,2);
*(geninit + 4) = (g22s + (g12s + g24s + g23s*pow((1 - rec),2) + g14s*pow(rec,2))/4.0)*self + (1 - self)*pow(x2,2);
*(geninit + 7) = (g33s + (g13s + g34s + g23s*pow((1 - rec),2) + g14s*pow(rec,2))/4.0)*self + (1 - self)*pow(x3,2);
*(geninit + 9) = (g44s + (g24s + g34s + g14s*pow((1 - rec),2) + g23s*pow(rec,2))/4.0)*self + (1 - self)*pow(x4,2);
*(geninit + 1) = ((g12s + (g14s + g23s)*(1 - rec)*rec)*self)/2.0 + 2.0*(1 - self)*x1*x2;
*(geninit + 2) = ((g13s + (g14s + g23s)*(1 - rec)*rec)*self)/2.0 + 2.0*(1 - self)*x1*x3;
*(geninit + 3) = ((g14s*pow((1 - rec),2) + g23s*pow(rec,2))*self)/2.0 + 2.0*(1 - self)*x1*x4;
*(geninit + 5) = ((g23s*pow((1 - rec),2) + g14s*pow(rec,2))*self)/2.0 + 2.0*(1 - self)*x2*x3;
*(geninit + 6) = ((g24s + (g14s + g23s)*(1 - rec)*rec)*self)/2.0 + 2.0*(1 - self)*x2*x4;
*(geninit + 8) = ((g34s + (g14s + g23s)*(1 - rec)*rec)*self)/2.0 + 2.0*(1 - self)*x3*x4;
} /* End of reproduction routine */
/* Has any allele fixed or not? */
unsigned int hcheck(double *geninit, double *haps, unsigned int *hf, unsigned int stype){
/* Fed-in genotype frequencies (for ease of programming) */
double g11s, g12s, g13s, g14s, g22s, g23s, g24s, g33s, g34s, g44s;
unsigned int retval = 0;
/* Initial definition of genotypes */
g11s = *(geninit + 0);
g12s = *(geninit + 1);
g13s = *(geninit + 2);
g14s = *(geninit + 3);
g22s = *(geninit + 4);
g23s = *(geninit + 5);
g24s = *(geninit + 6);
g33s = *(geninit + 7);
g34s = *(geninit + 8);
g44s = *(geninit + 9);
/* Calculation of haplotypes */
*(haps + 0) = g11s + (g12s + g13s + g14s)/2.0;
*(haps + 1) = g22s + (g12s + g23s + g24s)/2.0;
*(haps + 2) = g33s + (g13s + g23s + g34s)/2.0;
*(haps + 3) = g44s + (g14s + g24s + g34s)/2.0;
/* printf("Haps are %lf %lf %lf %lf\n",*(haps + 0),*(haps + 1),*(haps + 2),*(haps + 3));*/
if(*(haps + 0) == 1){
retval = 1;
*hf = 0;
}
else if(*(haps + 1) == 1){
retval = 1;
*hf = 1;
}
else if(*(haps + 2) == 1){
retval = 1;
*hf = 2;
}
else if(*(haps + 3) == 1){
retval = 1;
*hf = 3;
}else if(stype == 1){
if( (*(haps + 2) + *(haps + 3) ) == 0 ){
retval = 2;
*hf = 0;
}
}
return retval;
} /* End of hap check routine */
/* End of program */
| {
"alphanum_fraction": 0.5954867729,
"avg_line_length": 31.6072289157,
"ext": "c",
"hexsha": "58ed7233be4ed49ebeea5acae795ffc76b29980b",
"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": "afb4d3aeba05bad8ae1440213d998d1d4e5a4daf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MattHartfield/TwoAdvSelfSims",
"max_forks_repo_path": "TwoAdvSelfSims.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "afb4d3aeba05bad8ae1440213d998d1d4e5a4daf",
"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": "MattHartfield/TwoAdvSelfSims",
"max_issues_repo_path": "TwoAdvSelfSims.c",
"max_line_length": 257,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "afb4d3aeba05bad8ae1440213d998d1d4e5a4daf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MattHartfield/TwoAdvSelfSims",
"max_stars_repo_path": "TwoAdvSelfSims.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4812,
"size": 13117
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_chebyshev.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_multifit_nlin.h>
#include <gsl/gsl_multifit_nlinear.h>
#include <gsl/gsl_blas_types.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_randist.h>
double funcExp(double x, void *p)
{
(void)(p); //avoid unused parameter warning
return exp(pow(x, 2));
}
double funcAbs(double x, void *p)
{
(void)(p); //avoid unused parameter warning
return fabs(x + pow(x, 3));
}
double funcSign(double x, void *p)
{
(void)(p); //avoid unused parameter warning
if (x == 0) return 0.0;
else if (x < 0) return -1.0;
return 1.0;
}
void calculateExp()
{
const int stepsCount = 1000;
FILE* outputR1 = fopen("cheb_exp_r1.txt", "w");
FILE* outputR2 = fopen("cheb_exp_r2.txt", "w");
FILE* outputR4 = fopen("cheb_exp_r4.txt", "w");
FILE* outputR8 = fopen("cheb_exp_r8.txt", "w");
FILE* outputR16 = fopen("cheb_exp_r16.txt", "w");
FILE* outputR25 = fopen("cheb_exp_r25.txt", "w");
FILE* outputR40 = fopen("cheb_exp_r40.txt", "w");
gsl_cheb_series* cs = gsl_cheb_alloc(40);
gsl_function function;
function.function = funcExp;
function.params = 0;
gsl_cheb_init(cs, &function, -1.0, 1.0);
for (int i = -stepsCount; i <= stepsCount; i++)
{
double x = (double)i / (double)stepsCount;
double r1 = GSL_FN_EVAL(&function, x);
double r2 = gsl_cheb_eval_n(cs, 2, x);
double r4 = gsl_cheb_eval_n(cs, 4, x);
double r8 = gsl_cheb_eval_n(cs, 8, x);
double r16 = gsl_cheb_eval_n(cs, 16, x);
double r25 = gsl_cheb_eval_n(cs, 25, x);
double r40 = gsl_cheb_eval_n(cs, 40, x);
fprintf (outputR1,"%g %g\n", x, r1);
fprintf (outputR2,"%g %g\n", x, r2);
fprintf (outputR4,"%g %g\n", x, r4);
fprintf (outputR8,"%g %g\n", x, r8);
fprintf (outputR16,"%g %g\n", x, r16);
fprintf (outputR25,"%g %g\n", x, r25);
fprintf (outputR40,"%g %g\n", x, r40);
}
gsl_cheb_free(cs);
}
void calculateAbs()
{
const int stepsCount = 1000;
FILE* outputR1 = fopen("cheb_abs_r1.txt", "w");
FILE* outputR2 = fopen("cheb_abs_r2.txt", "w");
FILE* outputR4 = fopen("cheb_abs_r4.txt", "w");
FILE* outputR8 = fopen("cheb_abs_r8.txt", "w");
FILE* outputR16 = fopen("cheb_abs_r16.txt", "w");
FILE* outputR25 = fopen("cheb_abs_r25.txt", "w");
FILE* outputR40 = fopen("cheb_abs_r40.txt", "w");
gsl_cheb_series* cs = gsl_cheb_alloc(40);
gsl_function function;
function.function = funcAbs;
function.params = 0;
gsl_cheb_init(cs, &function, -1.0, 1.0);
for (int i = -stepsCount; i <= stepsCount; i++)
{
double x = (double)i / (double)stepsCount;
double r1 = GSL_FN_EVAL(&function, x);
double r2 = gsl_cheb_eval_n(cs, 2, x);
double r4 = gsl_cheb_eval_n(cs, 4, x);
double r8 = gsl_cheb_eval_n(cs, 8, x);
double r16 = gsl_cheb_eval_n(cs, 16, x);
double r25 = gsl_cheb_eval_n(cs, 25, x);
double r40 = gsl_cheb_eval_n(cs, 40, x);
fprintf (outputR1,"%g %g\n", x, r1);
fprintf (outputR2,"%g %g\n", x, r2);
fprintf (outputR4,"%g %g\n", x, r4);
fprintf (outputR8,"%g %g\n", x, r8);
fprintf (outputR16,"%g %g\n", x, r16);
fprintf (outputR25,"%g %g\n", x, r25);
fprintf (outputR40,"%g %g\n", x, r40);
}
gsl_cheb_free(cs);
}
void calculateSign()
{
const int stepsCount = 1000;
FILE* outputR1 = fopen("cheb_sign_r1.txt", "w");
FILE* outputR2 = fopen("cheb_sign_r2.txt", "w");
FILE* outputR4 = fopen("cheb_sign_r4.txt", "w");
FILE* outputR8 = fopen("cheb_sign_r8.txt", "w");
FILE* outputR16 = fopen("cheb_sign_r16.txt", "w");
FILE* outputR25 = fopen("cheb_sign_r25.txt", "w");
FILE* outputR40 = fopen("cheb_sign_r40.txt", "w");
gsl_cheb_series* cs = gsl_cheb_alloc(40);
gsl_function function;
function.function = funcSign;
function.params = 0;
gsl_cheb_init(cs, &function, -1.0, 1.0);
for (int i = -stepsCount; i <= stepsCount; i++)
{
double x = (double)i / (double)stepsCount;
double r1 = GSL_FN_EVAL(&function, x);
double r2 = gsl_cheb_eval_n(cs, 2, x);
double r4 = gsl_cheb_eval_n(cs, 4, x);
double r8 = gsl_cheb_eval_n(cs, 8, x);
double r16 = gsl_cheb_eval_n(cs, 16, x);
double r25 = gsl_cheb_eval_n(cs, 25, x);
double r40 = gsl_cheb_eval_n(cs, 40, x);
fprintf (outputR1,"%g %g\n", x, r1);
fprintf (outputR2,"%g %g\n", x, r2);
fprintf (outputR4,"%g %g\n", x, r4);
fprintf (outputR8,"%g %g\n", x, r8);
fprintf (outputR16,"%g %g\n", x, r16);
fprintf (outputR25,"%g %g\n", x, r25);
fprintf (outputR40,"%g %g\n", x, r40);
}
gsl_cheb_free(cs);
}
void fitLinear()
{
const int stepsCount = 1000;
double xArray[stepsCount * 2];
double yArray[stepsCount * 2];
FILE* outputOriginal = fopen("linear_original.txt", "w");
FILE* outputFit = fopen("linear_fit.txt", "w");
FILE* outputCheb = fopen("linear_cheb.txt", "w");
for (int i = -stepsCount; i <= stepsCount; i++)
{
double x = (double)i / (double)stepsCount;
double y = pow(0.5, pow(x, 2) + 2 * x);
xArray[i + stepsCount] = x;
yArray[i + stepsCount] = y;
fprintf (outputOriginal,"%g %g\n", x, y);
}
double c0 = 0;
double c1 = 0;
double cov00 = 0;
double cov01 = 0;
double cov11 = 0;
double sumsq = 0;
gsl_fit_linear(xArray, 1, yArray, 1, stepsCount * 2, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);
//------
for (int i = -stepsCount; i <= stepsCount; i++)
{
double x = (double)i / (double)stepsCount;
double y = c0 + c1 * x;
xArray[i + stepsCount] = x;
yArray[i + stepsCount] = y;
fprintf (outputFit,"%g %g\n", x, y);
}
printf("c0: %f --- c1: %f\n", c0, c1);
}
double funcCheb(double x, void *p)
{
(void)(p); //avoid unused parameter warning
return pow(0.5, pow(x, 2) + 2 * x);
}
void fitCheb()
{
const int stepsCount = 1000;
FILE* outputR4 = fopen("cheb_fit_r4.txt", "w");
FILE* outputR40 = fopen("cheb_fit_r40.txt", "w");
gsl_cheb_series* cs = gsl_cheb_alloc(40);
gsl_function function;
function.function = funcCheb;
function.params = 0;
gsl_cheb_init(cs, &function, -1.0, 1.0);
for (int i = -stepsCount; i <= stepsCount; i++)
{
double x = (double)i / (double)stepsCount;
double r4 = gsl_cheb_eval_n(cs, 4, x);
double r40 = gsl_cheb_eval_n(cs, 40, x);
fprintf (outputR4,"%g %g\n", x, r4);
fprintf (outputR40,"%g %g\n", x, r40);
}
gsl_cheb_free(cs);
}
int main (int argc, char* argv[])
{
calculateExp();
calculateSign();
calculateAbs();
fitLinear();
fitCheb();
return 0;
}
/*
plot "cheb_exp_r1.txt" with lines, \
"cheb_exp_r2.txt" with lines, \
"cheb_exp_r4.txt" with lines, \
"cheb_exp_r8.txt" with lines, \
"cheb_exp_r16.txt" with lines, \
"cheb_exp_r25.txt" with lines, \
"cheb_exp_r40.txt" with lines
plot "cheb_abs_r1.txt" with lines, \
"cheb_abs_r2.txt" with lines, \
"cheb_abs_r4.txt" with lines, \
"cheb_abs_r8.txt" with lines, \
"cheb_abs_r16.txt" with lines, \
"cheb_abs_r25.txt" with lines, \
"cheb_abs_r40.txt" with lines
plot "cheb_sign_r1.txt" with lines, \
"cheb_sign_r2.txt" with lines, \
"cheb_sign_r4.txt" with lines, \
"cheb_sign_r8.txt" with lines, \
"cheb_sign_r16.txt" with lines, \
"cheb_sign_r25.txt" with lines, \
"cheb_sign_r40.txt" with lines
================
plot "linear_original.txt" with lines title 'Original', \
"linear_fit.txt" with lines title 'Linear least sqr fit', \
"cheb_fit_r4.txt" with lines title 'Chebyshev approx R4'
*/ | {
"alphanum_fraction": 0.5929703822,
"avg_line_length": 28.8546099291,
"ext": "c",
"hexsha": "5b7a811a2223040c2969c867ca47e79959901ed5",
"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": "5fca38f9856cb17e129007eb3ad50112520af16e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "komilll/mownit_linux",
"max_forks_repo_path": "zad3/aproksymacja.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e",
"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": "komilll/mownit_linux",
"max_issues_repo_path": "zad3/aproksymacja.c",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5fca38f9856cb17e129007eb3ad50112520af16e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "komilll/mownit_linux",
"max_stars_repo_path": "zad3/aproksymacja.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2733,
"size": 8137
} |
//cmc_topol.c --
// this uses stateSpace generated previously to
// create the topology matrix and the move type matrix
//defined by the markov chain
//this was only for testing purposes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include "AFS.h"
#include "adkGSL.h"
#include "cs.h"
#include "time.h"
#include "adkCSparse.h"
#include "AFS_pthreads.c"
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
#define NTHREADS 4
int n1, n2;
const char *filename;
afsStateSpace *stateSpace;
void getParameters(int argc,const char **argv);
void usage();
int main(int argc, const char * argv[]){
int i,N,tmpS,win,t;
int rc;
void *v;
int nnz;
matrixThreadObject_sparse *tObj[NTHREADS];
pthread_t threads[NTHREADS];
getParameters(argc,argv);
stateSpace = afsStateSpaceImportFromFile(filename);
//afsStateSpaceRemoveAbsorbing(stateSpace);
N = stateSpace->nstates;
//Multithreaded construction of original transition matrix
// printf("initializing original transition matrix using %d threads....\n",NTHREADS);
//setup threads
tmpS=0;
win =(int) ceil( (((float)stateSpace->nstates) / NTHREADS) );
// printf("nstates: %d winSize: %d\n",stateSpace->nstates,win);
for(t=0;t<NTHREADS;t++){
tObj[t] = malloc(sizeof( matrixThreadObject_sparse));
tObj[t]->nnz = 0;
tObj[t]->dim1 = malloc(sizeof(int) * stateSpace->nstates * 3);
tObj[t]->dim2 = malloc(sizeof(int) * stateSpace->nstates * 3);
tObj[t]->moveType = malloc(sizeof(int) * stateSpace->nstates * 3);
tObj[t]->topol = malloc(sizeof(double) * stateSpace->nstates * 3);
tObj[t]->start = tmpS;
tObj[t]->stop = MIN(tmpS+win,stateSpace->nstates);
tObj[t]->im_params = malloc(sizeof(im_lik_params));
tObj[t]->im_params->stateSpace = stateSpace;
// printf("start: %d stop: %d\n",tmpS,tmpS+win);
rc = pthread_create(&threads[t], NULL, threadDoRows_sparse, (void *)tObj[t]);
tmpS += win;
}
// printf("threads alloced....\n");
//harvest jobs
nnz=0;
for(t=0;t<NTHREADS;t++){
rc = pthread_join(threads[t], &v);
tObj[t] = ((matrixThreadObject_sparse *)v);
nnz += tObj[t]->nnz;
}
//now combine outputs for nnz, dim1, and dim2
printf("nnz: %d\n",nnz);
for(t=0;t<NTHREADS;t++){
for(i=0;i<tObj[t]->nnz;i++){
printf("%lf\t%d\t%d\t%d\n",tObj[t]->topol[i],tObj[t]->moveType[i],tObj[t]->dim1[i],tObj[t]->dim2[i]);
}
}
//currentParams->nnz -= 1;
////////// Multithreading done!
// dim1 = malloc(sizeof(int) * N * 10);
// dim2 = malloc(sizeof(int) * N * 10);
// moveA = malloc(sizeof(int) * N * 10);
// topA = malloc(sizeof(double) * N * 10);
// for(i=0;i< (N*10);i++){
// moveA[i]=0;
// topA[i]=0;
// }
// nnz = coalMarkovChainTopologyMatrix_sparse(stateSpace,topA, moveA, dim1, dim2);
// printf("nnz: %d\n",nnz);
// for(i=0;i<nnz;i++){
// printf("%f\t%d\t%d\t%d\n",topA[i],moveA[i],dim1[i],dim2[i]);
// }
return(0);
}
void getParameters(int argc, const char **argv){
// int args;
// int i;
if( argc <= 1){
usage();
}
filename = argv[1];
}
void usage(){
fprintf(stderr,"usage: cmc_topol stateSpaceFile\n");
// fprintf(stderr,"parameters: \n");
exit(1);
}
| {
"alphanum_fraction": 0.6473567585,
"avg_line_length": 26.7711864407,
"ext": "c",
"hexsha": "21dae6583a117f81119946bc1ed771f8d2f4942b",
"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": "e1643d7489106d5e040329bd0b7db75d80ce21d6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kern-lab/im_clam",
"max_forks_repo_path": "cmc_topol.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec",
"max_issues_repo_issues_event_max_datetime": "2018-04-08T17:04:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-17T09:15:17.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dortegadelv/IMaDNA",
"max_issues_repo_path": "cmc_topol.c",
"max_line_length": 104,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "e55ad3d0114f2e1491989fb6a00a37f8e2e4cfec",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dortegadelv/IMaDNA",
"max_stars_repo_path": "cmc_topol.c",
"max_stars_repo_stars_event_max_datetime": "2020-04-17T17:22:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-07-22T13:06:07.000Z",
"num_tokens": 1036,
"size": 3159
} |
/* Copyright 2013 Perttu Luukko
* This file is part of libeemd.
* libeemd 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.
* libeemd 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 libeemd. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _EEMD_H_
#define _EEMD_H_
#ifndef EEMD_DEBUG
#define EEMD_DEBUG 0
#endif
#if EEMD_DEBUG == 0
#ifndef NDEBUG
#define NDEBUG
#endif
#endif
#include <assert.h>
#include <limits.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
#include <gsl/gsl_statistics_double.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_poly.h>
#ifdef _OPENMP
#include <omp.h>
#endif
// Possible error codes returned by functions eemd, ceemdan and
// emd_evaluate_spline
typedef enum {
EMD_SUCCESS = 0,
// Errors from invalid parameters
EMD_INVALID_ENSEMBLE_SIZE = 1,
EMD_INVALID_NOISE_STRENGTH = 2,
EMD_NOISE_ADDED_TO_EMD = 3,
EMD_NO_NOISE_ADDED_TO_EEMD = 4,
EMD_NO_CONVERGENCE_POSSIBLE = 5,
EMD_NOT_ENOUGH_POINTS_FOR_SPLINE = 6,
EMD_INVALID_SPLINE_POINTS = 7,
// Other errors
EMD_GSL_ERROR = 8
} libeemd_error_code;
// Helper functions to print an error message if an error occured
void emd_report_if_error(libeemd_error_code err);
void emd_report_to_file_if_error(FILE* file, libeemd_error_code err);
// Main EEMD decomposition routine as described in:
// Z. Wu and N. Huang,
// Ensemble Empirical Mode Decomposition: A Noise-Assisted Data Analysis
// Method, Advances in Adaptive Data Analysis,
// Vol. 1, No. 1 (2009) 1–41
//
// Parameters 'input' and 'N' denote the input data and its length,
// respectively. Output from the routine is written to array 'output', which
// needs to be able to store at least N*M doubles, where M is the number of
// Intrinsic Mode Functions (IMFs) to compute. If M is set to zero, a value of
// M = emd_num_imfs(N) will be used, which corresponds to a maximal number of
// IMFs. Note that the final residual is also counted as an IMF in this
// respect, so you most likely want at least num_imfs=2. The following
// parameters are the ensemble size and the relative noise standard deviation,
// respectively. These are followed by the parameters for the stopping
// criterion. The stopping parameter can be defined by a S-number (see the
// article for details) or a fixed number of siftings. If both are specified,
// the sifting ends when either criterion is fulfilled. The final parameter is
// the seed given to the random number generator. A value of zero denotes a
// RNG-specific default value.
libeemd_error_code eemd(double const* restrict input, size_t N,
double* restrict output, size_t M,
unsigned int ensemble_size, double noise_strength, unsigned int
S_number, unsigned int num_siftings, unsigned long int rng_seed);
// A complete variant of EEMD as described in:
// M. Torres et al,
// A Complete Ensemble Empirical Mode Decomposition with Adaptive Noise
// IEEE Int. Conf. on Acoust., Speech and Signal Proc. ICASSP-11,
// (2011) 4144-4147
//
// Parameters are identical to routine eemd
libeemd_error_code ceemdan(double const* restrict input, size_t N,
double* restrict output, size_t M,
unsigned int ensemble_size, double noise_strength, unsigned int
S_number, unsigned int num_siftings, unsigned long int rng_seed);
// A method for finding the local minima and maxima from input data specified
// with parameters x and N. The memory for storing the coordinates of the
// extrema and their number are passed as the rest of the parameters. The
// arrays for the coordinates must be at least size N. The method also counts
// the number of zero crossings in the data, and saves the results into the
// pointer given as num_zero_crossings_ptr.
void emd_find_extrema(double const* restrict x, size_t N,
double* restrict maxx, double* restrict maxy, size_t* num_max_ptr,
double* restrict minx, double* restrict miny, size_t* num_min_ptr,
size_t* num_zero_crossings_ptr);
// Return the number of IMFs that can be extracted from input data of length N,
// including the final residual.
size_t emd_num_imfs(size_t N);
// This routine evaluates a cubic spline with nodes defined by the arrays x and
// y, each of length N. The spline is evaluated using the not-a-node end point
// conditions (same as Matlab). The y values of the spline curve will be
// evaluated at integer points from 0 to x[N-1], and these y values will be
// written to the array spline_y. The endpoint x[N-1] is assumed to be an
// integer, and the x values are assumed to be in ascending order, with x[0]
// equal to 0. The workspace required is 5*N-10 doubles, except that N==2
// requires no extra memory. For N<=3 the routine falls back to polynomial
// interpolation, same as Matlab.
//
// This routine is mainly exported so that it can be tested separately to
// produce identical results to the Matlab routine 'spline'.
libeemd_error_code emd_evaluate_spline(double const* restrict x, double const* restrict y,
size_t N, double* restrict spline_y, double* spline_workspace);
#endif // _EEMD_H_
| {
"alphanum_fraction": 0.7612101567,
"avg_line_length": 40.8308823529,
"ext": "h",
"hexsha": "303b9bfc6bbcd23bdb601ce2d4fca467a1c4205f",
"lang": "C",
"max_forks_count": 58,
"max_forks_repo_forks_event_max_datetime": "2022-03-15T09:13:00.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-12-14T00:15:22.000Z",
"max_forks_repo_head_hexsha": "a87114a689a1566e9aa03d85bcf6dc7325b47633",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "tenomoto/ncl",
"max_forks_repo_path": "ni/src/lib/nfp/eemd.h",
"max_issues_count": 156,
"max_issues_repo_head_hexsha": "a87114a689a1566e9aa03d85bcf6dc7325b47633",
"max_issues_repo_issues_event_max_datetime": "2022-03-30T07:02:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-09-22T09:56:48.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "tenomoto/ncl",
"max_issues_repo_path": "ni/src/lib/nfp/eemd.h",
"max_line_length": 90,
"max_stars_count": 210,
"max_stars_repo_head_hexsha": "a87114a689a1566e9aa03d85bcf6dc7325b47633",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "tenomoto/ncl",
"max_stars_repo_path": "ni/src/lib/nfp/eemd.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T19:15:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-11-24T09:05:08.000Z",
"num_tokens": 1440,
"size": 5553
} |
#ifndef __calcAinvb__
#define __calcAinvb__
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_multiroots.h>
#define GSL 2
int GSLtag;
void least_gsl_error_handler( const char * reason,
const char * file,
int line,
int gsl_errno)
{
fprintf(stderr,"%s:%d: %s (gsl_error %d)\n", file, line, reason,gsl_errno);
GSLtag=1;
}
#define ZERO (1e-10)
double VarY;
int calcAinvb1(double *x_data, double *A_data, double *b_data, int nx, int ndata)
{
/*
b= A x --> x= Ainv b
b in R^{ndata x 1}
A in R^{ndata x nx} (ndata>nx)
x in R^{nx x 1}
*/
int i;
if(ndata<=0){
x_data[0]=1;
for(i=1;i<nx;i++) x_data[i]=1./nx;
}
else{
gsl_matrix *A =gsl_matrix_alloc(ndata,nx);
gsl_vector *b =gsl_vector_alloc(ndata);
gsl_matrix *V = gsl_matrix_alloc (nx,nx);
gsl_vector *S = gsl_vector_alloc (nx);
gsl_vector *work = gsl_vector_alloc(nx);
gsl_vector *x = gsl_vector_alloc(nx);
A->data=A_data;
b->data=b_data;
x->data=x_data;
gsl_set_error_handler( &least_gsl_error_handler );GSLtag=0;
#if GSL == 1
gsl_linalg_SV_decomp_jacobi (A, V, S); //higer accuracy than Golub-Reinsh
#elif GSL == 2
gsl_linalg_SV_decomp (A, V, S, work); //Golub-Reinsh
#elif GSL == 3
{//faster
gsl_matrix *X;
X = gsl_matrix_alloc (nx,nx);
gsl_linalg_SV_decomp_mod (A, X, V, S, work);
gsl_matrix_free(X);
}
#endif
VarY=0;
if(GSLtag==1){
fprintf(stderr,"\nError:EigenValue=");
for(i=0;i<nx;i++) fprintf(stderr,"%e ",S->data[i]); fprintf(stderr,"\n");
for(i=0;i<nx;i++) x_data[i]=1./nx;
}
else{
int i,j,l;
double *Si=(double*)malloc(sizeof(double)*nx);
double *Ai=(double*)malloc(sizeof(double)*nx*ndata);
for(i=0;i<nx;i++) if(S->data[i]>1e-10) Si[i]=1./S->data[i]; else Si[i]=0;
for(i=0;i<nx;i++){
for(j=0;j<ndata;j++){
double *Ai_ij=&Ai[i*ndata+j];
Ai_ij[0]=0;
for(l=0;l<nx;l++) Ai_ij[0]+=V->data[i*nx+l]*Si[l]*A->data[j*nx+l];
}
}
// for(i=0;i<nx;i++) x->data[i]=0;
x->data[0]=0;for(j=0;j<nx;j++) x->data[0]+=Ai[j]*b->data[j];
// int check=0;
// if(check){
// gsl_linalg_SV_solve(A,V,S,b,x);
// double xi;
// for(i=0;i<nx;i++){
// xi=0;
// for(j=0;j<nx;j++) xi+= Ai[i*ndata+j]*b->data[j];
// fprintf(stderr,"x[%d]=%g =?= %g\n",i,xi,x->data[i]);
// }
// fprintf(stderr,"p:");
// for(i=0;i<nx;i++){
// fprintf(stderr,"\n p(i%d,*):",i);
// for(j=0;j<nx;j++){
// fprintf(stderr,"%+.3f ",Ai[i*nx+j]);
// }
// }
// fprintf(stderr,"\n:");
// fprintf(stderr,"check\n");
// }
free(Si);
free(Ai);
}
gsl_vector_free(S);
gsl_vector_free(work);
gsl_vector_free(x);
gsl_matrix_free(V);
gsl_matrix_free(A);
gsl_vector_free(b);
}
return 0;
}
int calc_Ainvb(double *x_data, double *A_data, double *b_data, int nx, int ndata,int nxmarume)
{
/*
b= A x --> x= Ainv b
b in R^{ndata x 1}
A in R^{ndata x nx} (ndata>nx)
x in R^{nx x 1}
*/
int i;
if(ndata<=0){
x_data[0]=1;
for(i=1;i<nx;i++) x_data[i]=1./nx;
}
else{
gsl_matrix *A =gsl_matrix_alloc(ndata,nx);
gsl_vector *b =gsl_vector_alloc(ndata);
//A->data=A_data;
// b->data=b_data;
{
int n=ndata*nx;
for(i=0;i<n;i++){
A->data[i]=A_data[i];
}
for(i=0;i<ndata;i++) b->data[i]=b_data[i];
}
gsl_matrix *V = gsl_matrix_alloc (nx,nx);
gsl_vector *S = gsl_vector_alloc (nx);
gsl_vector *work = gsl_vector_alloc(nx);
gsl_vector *x = gsl_vector_alloc(nx);
gsl_set_error_handler( &least_gsl_error_handler );GSLtag=0;
#if GSL == 1
gsl_linalg_SV_decomp_jacobi (A, V, S); //higer accuracy than Golub-Reinsh
#elif GSL == 2
gsl_linalg_SV_decomp (A, V, S, work); //Golub-Reinsh
#elif GSL == 3
{//faster
gsl_matrix *X;
X = gsl_matrix_alloc (nx,nx);
gsl_linalg_SV_decomp_mod (A, X, V, S, work);
gsl_matrix_free(X);
}
#endif
VarY=0;
if(GSLtag==1){
fprintf(stderr,"\nError:EigenValue=");for(i=0;i<nx;i++) fprintf(stderr,"%e ",S->data[i]); fprintf(stderr,"\n");
for(i=0;i<nx;i++) x_data[i]=1./nx;
}
else{
if(nxmarume>=0){//Principal Component Analysis
for(i=0;i<nxmarume;i++) VarY+=S->data[i];
for(i=nxmarume;i<nx;i++) S->data[i]=0;
gsl_linalg_SV_solve(A,V,S,b,x);
for(i=0;i<nx;i++) x_data[i]=gsl_vector_get(x,i);
}
else{//Minor Component Analysis
int ii=0;
int im=-nxmarume;
for(i=nx-1;i>=0;i--){
if(S->data[i]>1e-20){
ii++;
VarY+=S->data[i];
if(ii>=im) break;
}
}
int j;
double M0=-V->data[i];
for(j=1;j<nx;j++){
x_data[j-1]=V->data[j*nx+i]/M0;
}
}
}
gsl_vector_free(S);
gsl_vector_free(work);
gsl_vector_free(x);
gsl_matrix_free(V);
gsl_matrix_free(A);
gsl_vector_free(b);
}
// fprintf(stderr,"OK");
return 0;
}
void calc_AtinvbMCA(double *M, double *At_data, double *b_data, int nx, int ndata,int nxmarume)
{
/* b= A M --> M= Ainv b
b in R^{ndata x 1}
A=At in R^{ndata x nx}
M in R^{nx x 1}
*/
int nx1=nx+1,i,j,jnx1;
gsl_matrix *A =gsl_matrix_alloc(ndata,nx1);
for(j=0;j<ndata;j++){
jnx1=j*nx1;
A->data[jnx1]=b_data[j];
for(i=0;i<nx;i++){
A->data[jnx1+i+1]=At_data[i*ndata+j];
}
}
calc_Ainvb(M, (double *)(A->data), b_data, nx1, ndata, -nxmarume);
gsl_matrix_free(A);
}
void calc_Atinvb(double *M, double *At_data, double *b_data, int nx, int ndata,int nxmarume)
{
/* b= A M --> M= Ainv b
b in R^{ndata x 1}
A=At in R^{ndata x nx}
M in R^{nx x 1}
*/
gsl_matrix *At =gsl_matrix_alloc(nx,ndata);
gsl_matrix *A =gsl_matrix_alloc(ndata,nx);
At->data=At_data;
gsl_matrix_transpose_memcpy(A, At);
calc_Ainvb(M, (double *)(A->data), b_data, nx, ndata, nxmarume);
gsl_matrix_free(A);
gsl_matrix_free(At);
}
#endif // __calcAinvb__
| {
"alphanum_fraction": 0.573872212,
"avg_line_length": 25.9260869565,
"ext": "c",
"hexsha": "206521f02b374d1e890d655844de378875889ce5",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-12-01T00:54:18.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-12-01T00:54:18.000Z",
"max_forks_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136",
"max_forks_repo_licenses": [
"CECILL-B"
],
"max_forks_repo_name": "Kurogi-Lab/CAN2",
"max_forks_repo_path": "1021/mspc/calcAinvb.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CECILL-B"
],
"max_issues_repo_name": "Kurogi-Lab/CAN2",
"max_issues_repo_path": "1021/mspc/calcAinvb.c",
"max_line_length": 117,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "abd029895f2ff9d1c8debdb3825b0d4b9314d136",
"max_stars_repo_licenses": [
"CECILL-B"
],
"max_stars_repo_name": "Kurogi-Lab/CAN2",
"max_stars_repo_path": "1021/mspc/calcAinvb.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2149,
"size": 5963
} |
#include <gsl/gsl_cdf.h>
#include <stdio.h>
int main()
{
double bottom_tail = gsl_cdf_gaussian_P(-1.96,1);
printf("Area between +-1.96: %g\n",1-2*bottom_tail);
return 0;
}
| {
"alphanum_fraction": 0.6685393258,
"avg_line_length": 14.8333333333,
"ext": "c",
"hexsha": "d8d50e891d303b9bc724f7aaf78624907999f03a",
"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": "9fbc7d117b9aee98d748669646dd200c25a4122f",
"max_forks_repo_licenses": [
"WTFPL"
],
"max_forks_repo_name": "jieyaren/hello-world",
"max_forks_repo_path": "cpp/gl_erf.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "9fbc7d117b9aee98d748669646dd200c25a4122f",
"max_issues_repo_issues_event_max_datetime": "2019-05-15T10:56:31.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-05-15T10:55:59.000Z",
"max_issues_repo_licenses": [
"WTFPL"
],
"max_issues_repo_name": "jieyaren/hello-world",
"max_issues_repo_path": "cpp/gl_erf.c",
"max_line_length": 53,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "9fbc7d117b9aee98d748669646dd200c25a4122f",
"max_stars_repo_licenses": [
"WTFPL"
],
"max_stars_repo_name": "jieyaren/hello-world",
"max_stars_repo_path": "cpp/gl_erf.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-18T11:34:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-12T09:20:21.000Z",
"num_tokens": 61,
"size": 178
} |
/*
* 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 pool_81b70dbf_d70f_42d7_8770_678651c585c4_h
#define pool_81b70dbf_d70f_42d7_8770_678651c585c4_h
#include <assert.h>
#include <memory.h>
#include <stdlib.h>
#include <gslib/type.h>
__gslib_begin__
template<class _construct>
class factory
{
public:
typedef _construct mycon;
typedef factory<mycon> myref;
public:
factory(void* ptr = nullptr) { _generated = (mycon*)ptr; }
const mycon* get_ptr() const { return _generated; }
mycon* get_ptr() { return _generated; }
mycon* emerge()
{
if(!_generated)
_generated = new mycon;
assert(_generated);
return _generated;
}
void destroy()
{
if(!_generated)
return;
delete _generated;
_generated = nullptr;
}
protected:
mycon* _generated;
};
class vessel
{
protected:
void* _buf;
int _cap;
int _cur;
public:
vessel()
{
_buf = nullptr;
_cap = 0;
_cur = 0;
}
~vessel()
{
destroy();
}
void destroy()
{
if(_buf) {
free(_buf);
_buf = nullptr;
}
_cap = _cur = 0;
}
int get_cap() const
{
return _cap;
}
int get_cur() const
{
return _cur;
}
void* get_ptr() const
{
return _buf;
}
int get_rest() const
{
return _cap - _cur;
}
void flex(int size)
{
_buf = realloc(_buf, size);
_cap = size;
}
void expand(int size)
{
flex(get_cap() + size);
}
void fit()
{
_buf = realloc(_buf, _cur);
_cap = _cur;
}
void occupy(int size)
{
_cur += size;
assert(_cur <= get_cap());
}
void set_cur(int size)
{
_cur = size;
assert(_cur <= get_cap());
}
int curaddr(int ofs = 0) const
{
return (int)_buf + _cur + ofs;
}
void store(const void* buf, int size)
{
if(_cur + size > get_cap())
expand(get_cap() > size ? get_cap() : size);
assert(get_cap() >= _cur + size);
memcpy_s((void*)curaddr(), get_rest(), buf, size);
occupy(size);
}
void attach(void* buf, int size)
{
flex(0);
_buf = buf;
_cap = size;
_cur = size;
}
void attach(vessel* vsl)
{
assert(vsl);
attach(vsl->get_ptr(), vsl->get_cap());
_cur = vsl->get_cur();
vsl->detach();
}
void detach()
{
_buf = nullptr;
_cap = 0;
_cur = 0;
}
template<class tpl>
tpl& current(int ofs = 0)
{
return *((tpl*)((int)_buf + _cur + ofs));
}
template<class tpl>
tpl& front(int ofs = 0)
{
return *((tpl*)((int)_buf + ofs));
}
};
__gslib_end__
#endif | {
"alphanum_fraction": 0.5496040987,
"avg_line_length": 23.8555555556,
"ext": "h",
"hexsha": "57c7c89a0b66d6b2dfccf70429e33058e0e77174",
"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/pool.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/pool.h",
"max_line_length": 82,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/gslib/pool.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": 1072,
"size": 4294
} |
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv.h>
#include <GL/glut.h>
#define SLICE 360
int *jac;
int rhs (double t, const double y[], double f[], void *params_ptr);
//int jacobian (double t, const double y[], double *dfdy, double dfdt[], void *params_ptr);
void draw_differential_eq_plot(void);
void draw_lattice(void);
typedef struct _xy_plot xy_plot;
struct _xy_plot
{
double x;
double y;
};
xy_plot plot_res[1001];
void display(void)
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glColor3f(1, 0, 0);
glBegin(GL_LINE_LOOP);
glVertex3f(100.0, 0.0, 0.0);
glVertex3f(-100.0, 0.0, 0.0);
glEnd();
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex3f(0.0, 100.0, 0.0);
glVertex3f(0.0, -100.0, 0.0);
glEnd();
draw_differential_eq_plot();
draw_lattice();
glutSwapBuffers();
}
void reshape(int w, int h)
{
GLfloat n_range = 100.0f;
if(h == 0)
h = 1;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
#if 0
if(w <= h)
glOrtho(-n_range, n_range, -n_range * h / w, n_range * h / w, -n_range, n_range);
else
glOrtho(-n_range * w / h, n_range * w / h, -n_range, n_range, -n_range, n_range);
#endif
glOrtho(-10, 10, -0.5, 0.5, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int calc_vertices_num(void)
{
double tmin = 0.0, tmax = 10.0, delta_t = 0.01;
return (tmax - tmin) / delta_t;
}
void calc_differential_eq(void)
{
int dimension = 2; /* number of differential equations */
double eps_abs = 1.e-8; /* absolute error requested */
double eps_rel = 1.e-10; /* relative error requested */
const gsl_odeiv_step_type *type_ptr = gsl_odeiv_step_rkf45;
gsl_odeiv_step *step_ptr = gsl_odeiv_step_alloc (type_ptr, dimension);
gsl_odeiv_control *control_ptr = gsl_odeiv_control_y_new (eps_abs, eps_rel);
gsl_odeiv_evolve *evolve_ptr = gsl_odeiv_evolve_alloc (dimension);
gsl_odeiv_system my_system; /* structure with the rhs function, etc. */
double mu = 10; /* parameter for the diffeq */
double y[2]; /* current solution vector */
double t, t_next; /* current and next independent variable */
double tmin, tmax, delta_t; /* range of t and step size for output */
double h = 1e-6; /* starting step size for ode solver */
int cnt = 0;
int vertex_num = calc_vertices_num();
#if 0
double res_x[vertex_num + 1] = {0};
double res_y[vertex_num + 1] = {0};
double *res_x = (double *)malloc(sizeof(double) * (vertex_num + 1));
double *res_y = (double *)malloc(sizeof(double) * (vertex_num + 1));
#endif
my_system.function = rhs; /* the right-hand-side functions dy[i]/dt */
my_system.jacobian = NULL;
my_system.dimension = dimension; /* number of diffeq's */
my_system.params = NULL;
tmin = 0.; /* starting t value */
tmax = 10.; /* final t value */
delta_t = 0.01;
y[0] = 0.16; /* initial x value */
y[1] = 0.; /* initial v value */
t = tmin; /* initialize t */
printf ("%.5e %.5e %.5e\n", t, y[0], y[1]); /* initial values */
for (t_next = tmin + delta_t; t_next <= tmax; t_next += delta_t)
{
while (t < t_next) /* evolve from t to t_next */
{
gsl_odeiv_evolve_apply (evolve_ptr, control_ptr, step_ptr,
&my_system, &t, t_next, &h, y);
}
plot_res[cnt].x = t;
plot_res[cnt].y = y[0];
printf ("%.5e %.5e %.5e\n", t, plot_res[cnt].x, plot_res[cnt].y); /* print at t=t_next */
cnt++;
}
gsl_odeiv_evolve_free (evolve_ptr);
gsl_odeiv_control_free (control_ptr);
gsl_odeiv_step_free (step_ptr);
}
void draw_lattice(void)
{
int i;
glColor3f(1, 1, 0);
glBegin(GL_LINES);
for (i = 1; i <= 10; i++)
{
glVertex2f(i, -0.01);
glVertex2f(i, 0.01);
}
glEnd();
}
void draw_differential_eq_plot(void)
{
float t = -100.0, step = 0.01;
float x = 0, x2 = 0, y2, cx, cy;
float tmp;
int cache = 0;
int i;
glBegin(GL_LINES);
//for(; ; t += step)
for (i = 0; i < 1000; i++)
{
x2 = plot_res[i].x;
y2 = plot_res[i].y;
if(cache)
{
glVertex2f(cx, cy); // 이전값
glVertex2f(x2, y2); // 현재값
}
cache = 1;
cx = x2;
cy = y2;
printf("t = %f, y2 = %f\n", x2, y2);
}
glEnd();
}
int main (int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE);
glutInitWindowSize(800, 800);
glutInitWindowPosition(0, 0);
glutCreateWindow("Digital Signal Processing");
calc_differential_eq();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
/*************************** rhs ****************************/
/*
x' = v ==> dy[0]/dt = f[0] = y[1]
v' = -x + \mu v (1-x^2) ==> dy[1]/dt = f[1] = -y[0] + mu*y[1]*(1-y[0]*y[0])
x''(t) + x'(t) + x(t) = 0
x''(t) = -x'(t) - x(t)
x' = v ===> dy[0]/dt = f[0] = y[1]
v' = -v - x ===> dy[1]/dt = f[1] = -y[1] - y[0]
*/
// https://www.wolframalpha.com/input/?i=y%27%27+%2B+y%27+%2B+y+%3D+0%2C+y%280%29+%3D+1%2C+y%27%280%29+%3D+0, y(0) = 1
// https://www.wolframalpha.com/input/?i=%28sqrt%283%29+*+sin%28sqrt%283%29+%2F+2%29+%2B+3+*+cos%28sqrt%283%29+%2F+2%29%29+%2F+%283+*+sqrt%28e%29%29, y(1)
// (sqrt(3) * sin(sqrt(3) / 2) + 3 * cos(sqrt(3) / 2)) / (3 * sqrt(e)), y(1) = 0.6597001...
int
rhs (double t, const double y[], double f[], void *params_ptr)
{
/*
f[0] = y[1];
f[1] = -y[0] + mu * y[1] * (1. - y[0] * y[0]);
*/
// 10 * y'' + 10 * y' + 90 * y = 0
// y'' + y' + 9 * y = 0
// y'' = - y' - 9 * y
// 파이썬의 dsolve가 자체적으로 표준형을 만들어주는 반면
// GSL의 경우 성능은 더 좋지만 이와 같은 작업을 사용자에게 위임하고 있음
f[0] = y[1];
f[1] = -y[1] - 9 * y[0];
return GSL_SUCCESS; /* GSL_SUCCESS defined in gsl/errno.h as 0 */
}
/*************************** Jacobian ****************************/
/*
*/
#if 0
int
jacobian (double t, const double y[], double *dfdy,
double dfdt[], void *params_ptr)
{
/* get parameter(s) from params_ptr; here, just a double */
double mu = *(double *) params_ptr;
gsl_matrix_view dfdy_mat = gsl_matrix_view_array (dfdy, 2, 2);
gsl_matrix *m_ptr = &dfdy_mat.matrix; /* m_ptr points to the matrix */
/* fill the Jacobian matrix as shown */
gsl_matrix_set (m_ptr, 0, 0, 0.0); /* df[0]/dy[0] = 0 */
gsl_matrix_set (m_ptr, 0, 1, 1.0); /* df[0]/dy[1] = 1 */
gsl_matrix_set (m_ptr, 1, 0, -2.0 * mu * y[0] * y[1] - 1.0); /* df[1]/dy[0] */
gsl_matrix_set (m_ptr, 1, 1, -mu * (y[0] * y[0] - 1.0)); /* df[1]/dy[1] */
/* set explicit t dependence of f[i] */
dfdt[0] = 0.0;
dfdt[1] = 0.0;
return GSL_SUCCESS; /* GSL_SUCCESS defined in gsl/errno.h as 0 */
}
#endif
| {
"alphanum_fraction": 0.5720971044,
"avg_line_length": 24.8654545455,
"ext": "c",
"hexsha": "6fccc436c5e21a8ff8f650398441749dd77e3e56",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-03-19T01:22:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-19T01:22:06.000Z",
"max_forks_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_forks_repo_path": "ch5/src/main/second_ode_plot.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"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": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_issues_repo_path": "ch5/src/main/second_ode_plot.c",
"max_line_length": 154,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_stars_repo_path": "ch5/src/main/second_ode_plot.c",
"max_stars_repo_stars_event_max_datetime": "2021-10-22T00:39:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-10-22T00:39:04.000Z",
"num_tokens": 2505,
"size": 6838
} |
#ifndef VKST_RENDERER_H
#define VKST_RENDERER_H
#include <plat/filesystem.h>
#include <wsi/window.h>
#include <vk/result.h>
#include <gsl.h>
#include <filesystem>
#include <vector>
// Holds all of the data for a surface. This includes the swapchain,
// renderpass, and framebuffers.
// Surfaces must be resized when the window is resized.
class surface {
public:
std::size_t num_images() const noexcept { return _color_images.size(); }
VkRenderPass render_pass() const noexcept { return _render_pass; }
VkFramebuffer framebuffer(std::size_t index) const noexcept {
return _framebuffers[index];
}
VkSampleCountFlagBits samples() const noexcept { return _samples; }
VkViewport& viewport() noexcept { return _viewport; }
VkViewport const& viewport() const noexcept { return _viewport; }
VkRect2D& scissor() noexcept { return _scissor; }
VkRect2D const& scissor() const noexcept { return _scissor; }
surface() noexcept {}
surface(surface const&) = delete;
surface(surface&& other) noexcept;
surface& operator=(surface const&) = delete;
surface& operator=(surface&& rhs) noexcept;
~surface() noexcept = default;
private:
VkSurfaceKHR _surface{VK_NULL_HANDLE};
VkSurfaceFormatKHR _color_format{};
VkFormat _depth_format{};
VkSampleCountFlagBits _samples{};
VkPresentModeKHR _present_mode{};
VkSemaphore _image_available{VK_NULL_HANDLE};
VkSemaphore _render_finished{VK_NULL_HANDLE};
VkRenderPass _render_pass{VK_NULL_HANDLE};
VkSurfaceCapabilitiesKHR _capabilities{};
VkExtent2D _extent{};
VkViewport _viewport{};
VkRect2D _scissor{};
VkSwapchainKHR _swapchain{VK_NULL_HANDLE};
constexpr static uint32_t MAX_IMAGES = 4;
std::vector<VkImage> _color_images{};
std::vector<VkImageView> _color_image_views{};
VkImage _depth_image{VK_NULL_HANDLE};
VkDeviceMemory _depth_image_memory{VK_NULL_HANDLE};
VkImageView _depth_image_view{VK_NULL_HANDLE};
VkImage _color_target{VK_NULL_HANDLE};
VkDeviceMemory _color_target_memory{VK_NULL_HANDLE};
VkImageView _color_target_view{VK_NULL_HANDLE};
VkImage _depth_target{VK_NULL_HANDLE};
VkDeviceMemory _depth_target_memory{VK_NULL_HANDLE};
VkImageView _depth_target_view{VK_NULL_HANDLE};
std::vector<VkFramebuffer> _framebuffers{};
friend class renderer;
}; // class surface
// Convenience class to hold both the VkShaderModule for a shader as well as
// any error message from compiling the shader.
class shader {
public:
enum class types : uint8_t {
vertex = 0,
fragment = 1,
}; // enum class types
operator VkShaderModule() const noexcept { return _module; }
std::string const& error_message() const noexcept { return _error_message; }
shader() noexcept {}
shader(shader const&) = delete;
shader(shader&& other) noexcept;
shader& operator=(shader const&) = delete;
shader& operator=(shader&& rhs) noexcept;
~shader() noexcept = default;
private:
VkShaderModule _module{VK_NULL_HANDLE};
std::string _error_message{};
friend class renderer;
}; // class shader
enum class renderer_result {
success = 0,
no_device = 1,
initialization_failed = 2,
surface_not_supported = 3,
no_memory_type = 4,
}; // class renderer_result
class renderer_result_category_impl : public std::error_category {
public:
virtual char const* name() const noexcept override {
return "renderer_result";
}
virtual std::string message(int ev) const override;
}; // class renderer_result_category_impl
std::error_category const& renderer_result_category();
inline std::error_code make_error_code(renderer_result e) noexcept {
return {static_cast<int>(e), renderer_result_category()};
}
enum class renderer_options : uint8_t {
none = 0,
use_integrated_gpu = (1 << 1),
}; // renderer_options
// Holds all of the data for rendering. Also provides methods for creating
// surfaces, shaders, pipelines, and command buffers, as well as submitting
// command buffers for execution on the device.
class renderer {
public:
// Create a new renderer. If ec is true, then an error occurred during
// creation and the renderer object is in an invalid state.
static renderer create(gsl::czstring application_name, renderer_options opts,
PFN_vkDebugReportCallbackEXT debug_report_callback,
uint32_t push_constant_size,
std::error_code& ec) noexcept;
// Create a new surface. If ec is true, then an error occurred during
// creation and the surface object is in an invalid state.
surface create_surface(wsi::window const& window,
std::error_code& ec) noexcept;
// Resize a surface. Must be called when the window that was passed for
// surface creation is resized. This is not automatically done to allow
// the render loop to determine when to perform the resize. If ec is true,
// then an error occurred during the resize.
void resize(surface& s, wsi::extent2d const& extent,
std::error_code& ec) noexcept;
// Acquire the next ready image in the swapchain for rendering to. This
// must be called and the returned index passed to submit_present. If
// ec is true, then an error occurred and the returned index is invalid.
uint32_t acquire_next_image(surface& s, std::error_code& ec) noexcept;
// Submit a set of command buffers for execution and then present the
// previously acquired swapchain image. image_index must come from an
// immediately preceding call to acquire_next_image. fence can be
// VK_NULL_HANDLE which indicates no fence should be signaled when the
// command buffers can be reused. If ec is true, then an error occurred
// during either the submit or present.
void submit_present(gsl::span<VkCommandBuffer> buffers, surface& s,
uint32_t image_index, VkFence fence,
std::error_code& ec) noexcept;
void destroy(surface& s) noexcept;
private:
void release(surface& s) noexcept;
public:
// Allocate a set of command buffers. If ec is true, then an error occurred
// and the vector is invalid.
std::vector<VkCommandBuffer>
allocate_command_buffers(uint32_t count, std::error_code& ec) noexcept;
// Submit a set of command buffers. onetime indicates that the submit should
// use the onetime fence and wait for the submit to complete before
// continuing. If ec is true, then an error occurred.
void submit(gsl::span<VkCommandBuffer> command_buffers, bool onetime,
std::error_code& ec) noexcept;
void free(std::vector<VkCommandBuffer>& command_buffers) noexcept;
// Create a new shader from the given source code. path is expected to hold
// GLSL source code which will be compiled before creating the shader. If ec
// is true, then an error occurred and the shader is valid such that
// shader::error_message can be called to get any compilation errors.
shader create_shader(plat::filesystem::path const& path, shader::types type,
std::error_code& ec) noexcept;
void destroy(shader& s) noexcept;
// Create a new pipeline layout. If ec is true, then an error occurred and
// the pipeline layout object is invalid.
VkPipelineLayout create_pipeline_layout(
gsl::span<VkDescriptorSetLayout> descriptor_set_layouts,
gsl::span<VkPushConstantRange> push_constant_ranges,
std::error_code& ec) noexcept;
void destroy(VkPipelineLayout layout) noexcept;
// Create a new set of pipelines. A single pipeline can also be created.
// If ec is true, then an error occurred and the vector of pipelines is
// invalid.
std::vector<VkPipeline>
create_pipelines(gsl::span<VkGraphicsPipelineCreateInfo> cinfos,
std::error_code& ec) noexcept;
void destroy(gsl::span<VkPipeline> pipes) noexcept;
// Create a new fence. If ec is true, then an error occurred and the fence
// is invalid.
VkFence create_fence(bool signaled, std::error_code& ec) noexcept;
// Wait for a set of fences to be signaled. If wait_all is true, then all
// fences must be signaled before the call will return, if wait_all is
// false, then a single fence will cause the call to return. timeout
// specifies how long to wait, 0 returns immediately, and UINT64_MAX will
// wait indefinitely. If ec is true, and error occurred while waiting.
void wait(gsl::span<VkFence> fences, bool wait_all, uint64_t timeout,
std::error_code& ec) noexcept;
// Reset a set of fences from the signaled state to unsignaled. If ec is
// true then an error occured.
void reset(gsl::span<VkFence> fences, std::error_code& ec) noexcept;
void destroy(VkFence fence) noexcept;
constexpr renderer() noexcept {};
renderer(renderer const&) = delete;
renderer(renderer&& other) noexcept;
renderer& operator=(renderer const&) = delete;
renderer& operator=(renderer&& rhs) noexcept;
~renderer() noexcept;
private:
VkInstance _instance{VK_NULL_HANDLE};
VkDebugReportCallbackEXT _callback{VK_NULL_HANDLE};
VkPhysicalDevice _physical{VK_NULL_HANDLE};
VkDevice _device{VK_NULL_HANDLE};
uint32_t _graphics_queue_family_index{UINT32_MAX};
VkQueue _graphics_queue{VK_NULL_HANDLE};
VkCommandPool _graphics_command_pool{VK_NULL_HANDLE};
VkFence _graphics_onetime_fence{VK_NULL_HANDLE};
}; // class renderer
inline constexpr auto operator|(renderer_options a,
renderer_options b) noexcept {
using U = std::underlying_type_t<renderer_options>;
return static_cast<renderer_options>(static_cast<U>(a) | static_cast<U>(b));
}
inline constexpr auto operator&(renderer_options a,
renderer_options b) noexcept {
using U = std::underlying_type_t<renderer_options>;
return static_cast<renderer_options>(static_cast<U>(a) & static_cast<U>(b));
}
#endif // VKST_RENDERER_H
| {
"alphanum_fraction": 0.7359430605,
"avg_line_length": 36.56133829,
"ext": "h",
"hexsha": "621b47c89059a0b2021aa751fefba4b409f1cf49",
"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/renderer.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/renderer.h",
"max_line_length": 79,
"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/renderer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2314,
"size": 9835
} |
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <glob.h>
#include <unistd.h>
#include <dirent.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 <gsl/gsl_permutation.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#include "mclib_3d.h"
#include <omp.h>
#include "mpi.h"
#define PROP_DIM1 1
#define PROP_DIM2 8
#define PROP_DIM3 8
#define COORD_DIM1 2
#define R_DIM_2D 9120
#define THETA_DIM_2D 2000
//define constants
const double A_RAD=7.56e-15, C_LIGHT=2.99792458e10, PL_CONST=6.6260755e-27;
const double K_B=1.380658e-16, M_P=1.6726231e-24, THOMP_X_SECT=6.65246e-25, M_EL=9.1093879e-28 ;
int getOrigNumProcesses(int *counted_cont_procs, int **proc_array, char dir[200], int angle_rank, int angle_procs, int last_frame, int dim_switch, int riken_switch)
{
int i=0, j=0, val=0, original_num_procs=-1, rand_num=0;
int frame2=0, framestart=0, scatt_framestart=0, ph_num=0;
double time=0;
char mc_chkpt_files[200]="", restrt=""; //define new variable that wont write over the restrt variable in the main part of the code, when its put into the readCheckpoint function
struct photon *phPtr=NULL; //pointer to array of photons
//DIR * dirp;
//struct dirent * entry;
//struct stat st = {0};
glob_t files;
//if (angle_rank==0)
{
//find number of mc_checkpt files there are
//loop through them and find out which prior processes didnt finish and keep track of which ones didnt
snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s", dir,"mc_chkpt_*" );
val=glob(mc_chkpt_files, 0, NULL,&files );
printf("TEST: %s\n", mc_chkpt_files);
//look @ a file by choosing rand int between 0 and files.gl_pathc and if the file exists open and read it to get the actual value for the old number of angle_procs
srand(angle_rank);
//printf("NUM_FILES: %d\n",files.gl_pathc);
rand_num=rand() % files.gl_pathc;
snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", rand_num,".dat" );
printf("TEST: %s\n", mc_chkpt_files);
if ( access( mc_chkpt_files, F_OK ) == -1 )
{
while(( access( mc_chkpt_files, F_OK ) == -1 ) )
{
rand_num=rand() % files.gl_pathc;
snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", rand_num,".dat" );
//printf("TEST: %s\n", mc_chkpt_files);
}
}
readCheckpoint(dir, &phPtr, &frame2, &framestart, &scatt_framestart, &ph_num, &restrt, &time, rand_num, &original_num_procs, dim_switch, riken_switch);
//original_num_procs= 70;
}
int count_procs[original_num_procs], count=0;
int cont_procs[original_num_procs];
//create array of files including any checkpoint file which may not have been created yet b/c old process was still in 1st frame of scattering
for (j=0;j<original_num_procs;j++)
{
count_procs[j]=j;
cont_procs[j]=-1; //set to impossible value for previous mpi process rank that needs to be con't
}
int limit= (angle_rank != angle_procs-1) ? (angle_rank+1)*original_num_procs/angle_procs : original_num_procs;
//char mc_chkpt_files[200]="";
printf("Angle ID: %d, start_num: %d, limit: %d\n", angle_rank, (angle_rank*original_num_procs/angle_procs), limit);
count=0;
for (j=floor(angle_rank*original_num_procs/angle_procs);j<limit;j++)
{
snprintf(mc_chkpt_files, sizeof(mc_chkpt_files), "%s%s%d%s", dir,"mc_chkpt_", j,".dat" );
//printf("TEST: %s\n", mc_chkpt_files);
if ( access( mc_chkpt_files, F_OK ) != -1 )
{
readCheckpoint(dir, &phPtr, &frame2, &framestart, &scatt_framestart, &ph_num, &restrt, &time, count_procs[j], &i, dim_switch, riken_switch);
free(phPtr);
phPtr=NULL;
if ((framestart<=frame2) && (scatt_framestart<=last_frame)) //add another condition here
{
cont_procs[count]=j;
printf("ACCEPTED: %s\n", mc_chkpt_files);
count++;
}
}
else
{
cont_procs[count]=j;
printf("ACCEPTED: %s\n", mc_chkpt_files);
count++;
}
}
(*proc_array)=malloc (count * sizeof (int )); //allocate space to pointer to hold the old process angle_id's
count=0;
for (i=0;i<original_num_procs;i++)
{
if (cont_procs[i]!=-1)
{
(*proc_array)[count]=cont_procs[i];
count++;
}
}
//save number of old processes this process counted need to be restarted
*counted_cont_procs=count;
globfree(& files);
return original_num_procs;
}
void printPhotons(struct photon *ph, int num_ph, int frame,int frame_inj, char dir[200], int angle_rank )
{
//function to save the photons' positions and 4 momentum
int i=0;
char mc_file_p0[200]="", mc_file_p1[200]="",mc_file_p2[200]="", mc_file_p3[200]="";
char mc_file_r0[200]="", mc_file_r1[200]="", mc_file_r2[200]="", mc_file_ns[200]="", mc_file_pw[200]="";
FILE *fPtr=NULL, *fPtr1=NULL,*fPtr2=NULL,*fPtr3=NULL,*fPtr4=NULL,*fPtr5=NULL,*fPtr6=NULL,*fPtr7=NULL,*fPtr8=NULL;
//make strings for proper files
snprintf(mc_file_p0,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P0_", angle_rank, ".dat" );
snprintf(mc_file_p1,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P1_", angle_rank, ".dat" );
snprintf(mc_file_p2,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P2_", angle_rank, ".dat" );
snprintf(mc_file_p3,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_P3_", angle_rank, ".dat" );
snprintf(mc_file_r0,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_R0_", angle_rank, ".dat" );
snprintf(mc_file_r1,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_R1_", angle_rank, ".dat" );
snprintf(mc_file_r2,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_R2_", angle_rank, ".dat" );
snprintf(mc_file_ns,sizeof(mc_file_p0),"%s%s%d%s%d%s",dir,"mcdata_", frame,"_NS_", angle_rank, ".dat" ); //for number of scatterings each photon went through
if (frame==frame_inj) //if the frame is the same one that the photons were injected in, save the photon weights
{
snprintf(mc_file_pw,sizeof(mc_file_p0),"%s%s%d%s",dir,"mcdata_PW_", angle_rank, ".dat" );
}
//save the energy
fPtr=fopen(mc_file_p0, "a");
fPtr1=fopen(mc_file_p1, "a");
fPtr2=fopen(mc_file_p2, "a");
fPtr3=fopen(mc_file_p3, "a");
fPtr4=fopen(mc_file_r0, "a");
fPtr5=fopen(mc_file_r1, "a");
fPtr6=fopen(mc_file_r2, "a");
fPtr7=fopen(mc_file_ns, "a");
if (frame==frame_inj)
{
fPtr8=fopen(mc_file_pw, "a");
}
//printf("Writing P0\n");
for (i=0;i<num_ph;i++)
{
fprintf(fPtr,"%0.13e\t", (ph+i)->p0);
//printf("%d: %0.13e \n", i, (ph+i)->p0);
fprintf(fPtr1,"%0.13e\t", (ph+i)->p1);
//printf("%d: %0.13e \n", i, (ph+i)->p1);
fprintf(fPtr2,"%0.13e\t", (ph+i)->p2);
//printf("%d: %0.13e \n", i, (ph+i)->p2);
fprintf(fPtr3,"%0.13e\t", (ph+i)->p3);
//printf("%d: %0.13e \n", i, (ph+i)->p3);
fprintf(fPtr4,"%0.13e\t", (ph+i)->r0);
//printf("%d: %0.13e \n", i, (ph+i)->r0);
fprintf(fPtr5,"%0.13e\t", (ph+i)->r1);
//printf("%d: %0.13e \n", i, (ph+i)->r1);
fprintf(fPtr6,"%0.13e\t", (ph+i)->r2);
//printf("%d: %0.13e \n", i, (ph+i)->r2);
//fprintf(fPtr7,"%0.13e\t", *(ph_num_scatt+i));
fprintf(fPtr7,"%e\t", (ph+i)->num_scatt);
//printf("%d: %0.13e \n", i, (ph+i)->num_scatt);
if (frame==frame_inj)
{
fprintf(fPtr8,"%e\t", (ph+i)->weight);
}
}
fclose(fPtr);
fclose(fPtr1);
fclose(fPtr2);
fclose(fPtr3);
fclose(fPtr4);
fclose(fPtr5);
fclose(fPtr6);
fclose(fPtr7);
if (frame==frame_inj)
{
fclose(fPtr8);
}
//printf("%s\n%s\n%s\n", mc_file_p0, mc_file_r0, mc_file_ns);
}
void saveCheckpoint(char dir[200], int frame, int frame2, int scatt_frame, int ph_num,double time_now, struct photon *ph, int last_frame, int angle_rank,int angle_size )
{
//function to save data necessary to restart simulation if it ends
//need to save all photon data
FILE *fPtr=NULL;
char checkptfile[200]="";
char command[200]="";
char restart;
int i=0;
//for openMPI have some type of problem with saving the checkpoint file for the frame in which photons have been injected and scattered in, can try to delete old mc_checkpoint file
//and creating a new one in that case?
snprintf(checkptfile,sizeof(checkptfile),"%s%s%d%s",dir,"mc_chkpt_", angle_rank,".dat" );
if ((scatt_frame!=last_frame) && (scatt_frame != frame))
{
fPtr=fopen(checkptfile, "wb");
//printf("%s\n", checkptfile);
if (fPtr==NULL)
{
printf("Cannot open %s to save checkpoint\n", checkptfile);
}
fwrite(&angle_size, sizeof(int), 1, fPtr);
restart='c';
fwrite(&restart, sizeof(char), 1, fPtr);
//printf("Rank: %d wrote restart %c\n", angle_rank, restart);
fflush(stdout);
fwrite(&frame, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote frame\n", angle_rank);
fflush(stdout);
fwrite(&frame2, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote frame2\n", angle_rank);
fflush(stdout);
fwrite(&scatt_frame, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote scatt_frame\n", angle_rank);
fflush(stdout);
fwrite(&time_now, sizeof(double), 1, fPtr);
//printf("Rank: %d wrote time_now\n", angle_rank);
fflush(stdout);
fwrite(&ph_num, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote ph_num\n", angle_rank);
fflush(stdout);
for(i=0;i<ph_num;i++)
{
fwrite((ph+i), sizeof(struct photon ), 1, fPtr);
//fwrite((ph), sizeof(struct photon )*ph_num, ph_num, fPtr);
}
//printf("Rank: %d wrote photons\n", angle_rank);
fflush(stdout);
}
else if (scatt_frame == frame)
{
snprintf(command, sizeof(command), "%s%s","exec rm ",checkptfile);
system(command);
fPtr=fopen(checkptfile, "wb");
//printf("%s\n", checkptfile);
fflush(stdout);
if (fPtr==NULL)
{
printf("Cannot open %s to save checkpoint\n", checkptfile);
}
fwrite(&angle_size, sizeof(int), 1, fPtr);
restart='c';
fwrite(&restart, sizeof(char), 1, fPtr);
//printf("Rank: %d wrote restart %c\n", angle_rank, restart);
fflush(stdout);
fwrite(&frame, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote frame\n", angle_rank);
fflush(stdout);
fwrite(&frame2, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote frame2\n", angle_rank);
fflush(stdout);
fwrite(&scatt_frame, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote scatt_frame\n", angle_rank);
fflush(stdout);
fwrite(&time_now, sizeof(double), 1, fPtr);
//printf("Rank: %d wrote time_now\n", angle_rank);
fflush(stdout);
fwrite(&ph_num, sizeof(int), 1, fPtr);
//printf("Rank: %d wrote ph_num\n", angle_rank);
fflush(stdout);
for(i=0;i<ph_num;i++)
{
//fwrite((ph), sizeof(struct photon )*ph_num, ph_num, fPtr);
fwrite((ph+i), sizeof(struct photon ), 1, fPtr);
}
//printf("Rank: %d wrote photons\n", angle_rank);
fflush(stdout);
}
else
{
fPtr=fopen(checkptfile, "wb");
//printf("%s\n", checkptfile);
if (fPtr==NULL)
{
printf("Cannot open %s to save checkpoint\n", checkptfile);
}
//just finished last iteration of scatt_frame
fwrite(&angle_size, sizeof(int), 1, fPtr);
restart='r';
fwrite(&restart, sizeof(char), 1, fPtr);
fwrite(&frame, sizeof(int), 1, fPtr);
fwrite(&frame2, sizeof(int), 1, fPtr);
}
fclose(fPtr);
}
void readCheckpoint(char dir[200], struct photon **ph, int *frame2, int *framestart, int *scatt_framestart, int *ph_num, char *restart, double *time, int angle_rank, int *angle_size , int dim_switch, int riken_switch )
{
//function to read in data from checkpoint file
FILE *fPtr=NULL;
char checkptfile[200]="";
int i=0;
//int frame, scatt_frame, ph_num, i=0;
struct photon *phHolder=NULL; //pointer to struct to hold data read in from checkpoint file
snprintf(checkptfile,sizeof(checkptfile),"%s%s%d%s",dir,"mc_chkpt_", angle_rank,".dat" );
printf("Checkpoint file: %s\n", checkptfile);
if (access( checkptfile, F_OK ) != -1) //if you can access the file, open and read it
{
fPtr=fopen(checkptfile, "rb");
{
fread(angle_size, sizeof(int), 1, fPtr); //uncomment once I run MCRAT for the sims that didnt save this originally
}
fread(restart, sizeof(char), 1, fPtr);
//printf("%c\n", *restart);
fread(framestart, sizeof(int), 1, fPtr);
//printf("%d\n", *framestart);
fread(frame2, sizeof(int), 1, fPtr);
if((*restart)=='c')
{
fread(scatt_framestart, sizeof(int), 1, fPtr);
if ((riken_switch==1) && (dim_switch==1) && ((*scatt_framestart)>=3000))
{
*scatt_framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1
}
else
{
*scatt_framestart+=1; //add one to start at the next frame after the simulation was interrrupted
}
//printf("%d\n", *scatt_framestart);
fread(time, sizeof(double), 1, fPtr);
//printf("%e\n", *time);
fread(ph_num, sizeof(int), 1, fPtr);
//printf("%d\n", *ph_num);
phHolder=malloc(sizeof(struct photon));
(*ph)=malloc(sizeof(struct photon)*(*ph_num)); //allocate memory to hold photon data
for (i=0;i<(*ph_num);i++)
{
fread(phHolder, sizeof(struct photon), 1, fPtr);
//printf("%e,%e,%e, %e,%e,%e, %e, %e\n",(ph)->p0, (ph)->p1, (ph)->p2, ph->p3, (ph)->r0, (ph)->r1, (ph)->r2, ph->num_scatt );
(*ph)[i].p0=phHolder->p0;
(*ph)[i].p1=phHolder->p1;
(*ph)[i].p2=phHolder->p2;
(*ph)[i].p3=phHolder->p3;
(*ph)[i].r0= phHolder->r0;
(*ph)[i].r1=phHolder->r1 ;
(*ph)[i].r2=phHolder->r2;
(*ph)[i].num_scatt=phHolder->num_scatt;
(*ph)[i].weight=phHolder->weight;
(*ph)[i].nearest_block_index= phHolder->nearest_block_index;
}
free(phHolder);
}
else
{
if ((riken_switch==1) && (dim_switch==1) && ((*framestart)>=3000))
{
*framestart+=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1
}
else
{
*framestart+=1; //if the checkpoint file saved and the program was inturrupted before the frame variable had just increased and before the scatt_frame iteration was saved, add one to the frame start
}
*scatt_framestart=(*framestart);
}
fclose(fPtr);
}
else //if not use default
{
//*framestart=(*framestart);
*scatt_framestart=(*framestart);
*restart='r';
}
}
void readMcPar(char file[200], double *fluid_domain_x, double *fluid_domain_y, double *fps, double *theta_jmin, double *theta_j, double *d_theta_j, double *inj_radius_small, double *inj_radius_large, int *frm0_small, int *frm0_large, int *last_frm, int *frm2_small,int *frm2_large , double *ph_weight_small,double *ph_weight_large,int *min_photons, int *max_photons, char *spect, char *restart, int *num_threads, int *dim_switch)
{
//function to read mc.par file
FILE *fptr=NULL;
char buf[100]="";
double theta_deg;
//open file
fptr=fopen(file,"r");
//read in frames per sec and other variables outlined in main()
fscanf(fptr, "%lf",fluid_domain_x);
//printf("%lf\n", *fluid_domain_x );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",fluid_domain_y);
//printf("%lf\n", *fluid_domain_y );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",fps);
//printf("%f\n", *fps );
fgets(buf, 100,fptr);
fscanf(fptr, "%d",frm0_small);
//printf("%d\n", *frm0_small );
fgets(buf, 100,fptr);
fscanf(fptr, "%d",frm0_large);
//printf("%d\n", *frm0_large );
fgets(buf, 100,fptr);
fscanf(fptr, "%d",last_frm);
//printf("%d\n", *last_frm );
fgets(buf, 100,fptr);
fscanf(fptr, "%d",frm2_small);
*frm2_small+=*frm0_small; //frame to go to is what is given in the file plus the starting frame
//printf("%d\n", *frm2_small );
fgets(buf, 100,fptr);
//fscanf(fptr, "%d",photon_num); remove photon num because we dont need this
//printf("%d\n", *photon_num );
fscanf(fptr, "%d",frm2_large);
*frm2_large+=*frm0_large; //frame to go to is what is given in the file plus the starting frame
//printf("%d\n", *frm2_large );
fgets(buf, 100,fptr);
//fgets(buf, 100,fptr);
fscanf(fptr, "%lf",inj_radius_small);
//printf("%lf\n", *inj_radius_small );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",inj_radius_large);
//printf("%lf\n", *inj_radius_large );
fgets(buf, 100,fptr);
//theta jmin
fscanf(fptr, "%lf",&theta_deg);
*theta_jmin=theta_deg;//*M_PI/180; leave as degrees to manipulate processes
//printf("%f\n", *theta_jmin );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",&theta_deg);
*theta_j=theta_deg;//*M_PI/180;
//printf("%f\n", *theta_j );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",d_theta_j);
//*theta_j=theta_deg;//*M_PI/180;
//printf("%f\n", *theta_j );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",ph_weight_small);
//printf("%f\n", *ph_weight_small );
fgets(buf, 100,fptr);
fscanf(fptr, "%lf",ph_weight_large);
fgets(buf, 100,fptr);
fscanf(fptr, "%d",min_photons);
fgets(buf, 100,fptr);
fscanf(fptr, "%d",max_photons);
fgets(buf, 100,fptr);
*spect=getc(fptr);
fgets(buf, 100,fptr);
//printf("%c\n",*spect);
*restart=getc(fptr);
fgets(buf, 100,fptr);
fscanf(fptr, "%d",num_threads);
//printf("%d\n",*num_threads);
fgets(buf, 100,fptr);
fscanf(fptr, "%d",dim_switch);
//printf("%d\n",*dim_switch);
//close file
fclose(fptr);
}
void readAndDecimate(char flash_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)
{
//function to read in data from FLASH file
hid_t file,dset, space;
herr_t status;
hsize_t dims[2]={0,0}; //hold dimension size for coordinate data set (mostly interested in dims[0])
double **vel_x_buffer=NULL, **vel_y_buffer=NULL, **dens_buffer=NULL, **pres_buffer=NULL, **coord_buffer=NULL, **block_sz_buffer=NULL;
double *velx_unprc=NULL, *vely_unprc=NULL, *dens_unprc=NULL, *pres_unprc=NULL, *x_unprc=NULL, *y_unprc=NULL, *r_unprc=NULL, *szx_unprc=NULL, *szy_unprc=NULL;
int i,j,count,x1_count, y1_count, r_count, **node_buffer=NULL, num_nodes=0, elem_factor=0;
double x1[8]={-7.0/16,-5.0/16,-3.0/16,-1.0/16,1.0/16,3.0/16,5.0/16,7.0/16};
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;
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)
}
file = H5Fopen (flash_file, H5F_ACC_RDONLY, H5P_DEFAULT);
//ret=H5Pclose(acc_tpl1);
fprintf(fPtr, ">> mc.py: Reading positional, density, pressure, and velocity information...\n");
fflush(fPtr);
//printf("Reading coord\n");
dset = H5Dopen (file, "coordinates", H5P_DEFAULT);
//get dimensions of array and save it
space = H5Dget_space (dset);
H5Sget_simple_extent_dims(space, dims, NULL); //save dimesnions in dims
/*
* Allocate array of pointers to rows. OPTIMIZE HERE: INITALIZE ALL THE BUFFERS AT ONCE IN 1 FOR LOOP
*/
coord_buffer = (double **) malloc (dims[0] * sizeof (double *));
coord_buffer[0] = (double *) malloc (dims[0] * dims[1] * sizeof (double));
block_sz_buffer= (double **) malloc (dims[0] * sizeof (double *));
block_sz_buffer[0] = (double *) malloc (dims[0] * COORD_DIM1 * sizeof (double));
node_buffer= (int **) malloc (dims[0] * sizeof (int *));
node_buffer[0] = (int *) malloc (dims[0] * sizeof (int));
vel_x_buffer= (double **) malloc (dims[0] * sizeof (double *));
vel_x_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));
vel_y_buffer= (double **) malloc (dims[0] * sizeof (double *));
vel_y_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));
dens_buffer= (double **) malloc (dims[0] * sizeof (double *));
dens_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));
pres_buffer= (double **) malloc (dims[0] * sizeof (double *));
pres_buffer[0]= (double *) malloc (dims[0] * PROP_DIM1 *PROP_DIM2*PROP_DIM3* sizeof (double));
/*
* Set the rest of the pointers to rows to the correct addresses.
*/
for (i=1; i<dims[0]; i++)
{
coord_buffer[i] = coord_buffer[0] + i * dims[1];
block_sz_buffer[i] = block_sz_buffer[0] + i * COORD_DIM1;
node_buffer[i] = node_buffer[0] + i ;
vel_x_buffer[i] = vel_x_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3;
vel_y_buffer[i] = vel_y_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3;
dens_buffer[i] = dens_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3;
pres_buffer[i] = pres_buffer[0] + i * PROP_DIM1*PROP_DIM2*PROP_DIM3;
}
//read data such that first column is x and second column is y
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,coord_buffer[0]);
//close dataset
status = H5Sclose (space);
status = H5Dclose (dset);
//printf("Reading block size\n");
dset = H5Dopen (file, "block size", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,block_sz_buffer[0]);
// first column of buffer is x and second column is y
status = H5Dclose (dset);
//printf("Reading node type\n");
dset = H5Dopen (file, "node type", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT,node_buffer[0]);
status = H5Dclose (dset);
//printf("Reading velx\n");
dset = H5Dopen (file, "velx", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,vel_x_buffer[0]);
status = H5Dclose (dset);
//printf("Reading vely\n");
dset = H5Dopen (file, "vely", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,vel_y_buffer[0]);
status = H5Dclose (dset);
//printf("Reading dens\n");
dset = H5Dopen (file, "dens", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,dens_buffer[0]);
status = H5Dclose (dset);
//printf("Reading pres\n");
dset = H5Dopen (file, "pres", H5P_DEFAULT);
//printf("Reading Dataset\n");
status = H5Dread (dset, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT,pres_buffer[0]);
status = H5Dclose (dset);
//H5Pclose(xfer_plist);
status = H5Fclose (file);
fprintf(fPtr,">> Selecting good node types (=1)\n");
//find out how many good nodes there are
for (i=0;i<dims[0];i++)
{
if (node_buffer[i][0]==1 ){
num_nodes++;
}
}
//allocate memory for arrays to hold unprocessed data
pres_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
dens_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
velx_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
vely_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
x_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
y_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
r_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
szx_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
szy_unprc=malloc (num_nodes* PROP_DIM1 *PROP_DIM2*PROP_DIM3 * sizeof (double ));
//find where the good values corresponding to the good gones (=1) and save them to the previously allocated pointers which are 1D arrays
//also create proper x and y arrays and block size arrays
//and then free up the buffer memory space
fprintf(fPtr,">> Creating and reshaping arrays\n");
count=0;
for (i=0;i<dims[0];i++)
{
if (node_buffer[i][0]==1 )
{
x1_count=0;
y1_count=0;
for (j=0;j<(PROP_DIM1*PROP_DIM2*PROP_DIM3);j++)
{
*(pres_unprc+count)=pres_buffer[i][j];
*(dens_unprc+count)=dens_buffer[i][j];
*(velx_unprc+count)=vel_x_buffer[i][j];
*(vely_unprc+count)=vel_y_buffer[i][j];
*(szx_unprc+count)=((block_sz_buffer[i][0])/8)*1e9; //divide by 8 for resolution, multiply by 1e9 to scale properly?
*(szy_unprc+count)=((block_sz_buffer[i][1])/8)*1e9;
if (j%8==0)
{
x1_count=0;
}
if ((j%8==0) && (j!=0))
{
y1_count++;
}
*(x_unprc+count)=(coord_buffer[i][0]+block_sz_buffer[i][0]*x1[x1_count])*1e9;
*(y_unprc+count)=(coord_buffer[i][1]+block_sz_buffer[i][1]*x1[y1_count])*1e9;
//printf("%d,%d,%d,%d\n",count,j,x1_count,y1_count);
x1_count++;
count++;
}
}
}
free (pres_buffer[0]); free (dens_buffer[0]);free (vel_x_buffer[0]);free (vel_y_buffer[0]); free(coord_buffer[0]);free(block_sz_buffer[0]);free(node_buffer[0]);
free (pres_buffer);free(dens_buffer);free(vel_x_buffer);free(vel_y_buffer);free(coord_buffer);free(block_sz_buffer);free(node_buffer);
//fill in radius array and find in how many places r > injection radius
elem_factor=1;
r_count=0;
while (r_count==0)
{
r_count=0;
elem_factor++;
for (i=0;i<count;i++)
{
*(r_unprc+i)=pow((pow(*(x_unprc+i),2)+pow(*(y_unprc+i),2)),0.5);
if (ph_inj_switch==0)
{
r_grid_innercorner = pow((*(x_unprc+i) - *(szx_unprc+i)/2.0) * ((*(x_unprc+i) - *(szx_unprc+i)/2.0))+(*(y_unprc+i) - *(szx_unprc+i)/2.0) * (*(y_unprc+i) - *(szx_unprc+i)/2.0),0.5);
r_grid_outercorner = pow((*(x_unprc+i) + *(szx_unprc+i)/2.0) * ((*(x_unprc+i) + *(szx_unprc+i)/2.0))+(*(y_unprc+i) + *(szx_unprc+i)/2.0) * (*(y_unprc+i) + *(szx_unprc+i)/2.0),0.5);
theta_grid_innercorner = acos( (*(y_unprc+i) - *(szx_unprc+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner
theta_grid_outercorner = acos( (*(y_unprc+i) + *(szx_unprc+i)/2.0) /r_grid_outercorner);
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 (*(r_unprc+i)> (0.95*r_inj) )
{
r_count++;
}
}
}
//fprintf(fPtr, "r_count: %d count: %d\n", r_count, 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<count;i++)
{
if (ph_inj_switch==0)
{
r_grid_innercorner = pow((*(x_unprc+i) - *(szx_unprc+i)/2.0) * ((*(x_unprc+i) - *(szx_unprc+i)/2.0))+(*(y_unprc+i) - *(szx_unprc+i)/2.0) * (*(y_unprc+i) - *(szx_unprc+i)/2.0),0.5);
r_grid_outercorner = pow((*(x_unprc+i) + *(szx_unprc+i)/2.0) * ((*(x_unprc+i) + *(szx_unprc+i)/2.0))+(*(y_unprc+i) + *(szx_unprc+i)/2.0) * (*(y_unprc+i) + *(szx_unprc+i)/2.0),0.5);
theta_grid_innercorner = acos( (*(y_unprc+i) - *(szx_unprc+i)/2.0) /r_grid_innercorner); //arccos of y/r for the bottom left corner
theta_grid_outercorner = acos( (*(y_unprc+i) + *(szx_unprc+i)/2.0) /r_grid_outercorner);
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_unprc+i);
(*velx)[j]=*(velx_unprc+i);
(*vely)[j]=*(vely_unprc+i);
(*dens)[j]=*(dens_unprc+i);
(*x)[j]=*(x_unprc+i);
(*y)[j]=*(y_unprc+i);
(*r)[j]=*(r_unprc+i);
(*szx)[j]=*(szx_unprc+i);
(*szy)[j]=*(szy_unprc+i);
(*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis
(*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c
(*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1));
(*temp)[j]=pow(3*(*(pres_unprc+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
j++;
}
}
else
{
if (*(r_unprc+i)> (0.95*r_inj) )
{
(*pres)[j]=*(pres_unprc+i);
(*velx)[j]=*(velx_unprc+i);
(*vely)[j]=*(vely_unprc+i);
(*dens)[j]=*(dens_unprc+i);
(*x)[j]=*(x_unprc+i);
(*y)[j]=*(y_unprc+i);
(*r)[j]=*(r_unprc+i);
(*szx)[j]=*(szx_unprc+i);
(*szy)[j]=*(szy_unprc+i);
(*theta)[j]=atan2( *(x_unprc+i) , *(y_unprc+i) );//theta in radians in relation to jet axis
(*gamma)[j]=pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1); //v is in units of c
(*dens_lab)[j]= (*(dens_unprc+i)) * (pow(pow(1.0-(pow(*(velx_unprc+i),2)+pow(*(vely_unprc+i),2)),0.5),-1));
(*temp)[j]=pow(3*(*(pres_unprc+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
j++;
}
}
}
*number=j;
//fprintf(fPtr, "number: %d\n", j);
free(pres_unprc); free(velx_unprc);free(vely_unprc);free(dens_unprc);free(x_unprc); free(y_unprc);free(r_unprc);free(szx_unprc);free(szy_unprc);
}
void photonInjection( struct photon **ph, int *ph_num, double r_inj, double ph_weight, int min_photons, int max_photons, char spect, int array_length, double fps, double theta_min, double theta_max,\
double *x, double *y, double *szx, double *szy, double *r, double *theta, double *temps, double *vx, double *vy, gsl_rng * rand, int riken_switch, FILE *fPtr)
{
int i=0, block_cnt=0, *ph_dens=NULL, ph_tot=0, j=0,k=0;
double ph_dens_calc=0.0, fr_dum=0.0, y_dum=0.0, yfr_dum=0.0, fr_max=0, bb_norm=0, position_phi, ph_weight_adjusted, rmin, rmax;
double com_v_phi, com_v_theta, *p_comv=NULL, *boost=NULL; //comoving phi, theta, comoving 4 momentum for a photon, and boost for photon(to go to lab frame)
double *l_boost=NULL; //pointer to hold array of lorentz boost, to lab frame, values
float num_dens_coeff;
if (spect=='w') //from MCRAT paper, w for wien spectrum
{
num_dens_coeff=8.44;
//printf("in wien spectrum\n");
}
else
{
num_dens_coeff=20.29; //this is for black body spectrum
//printf("in BB spectrum");
}
//find how many blocks are near the injection radius within the angles defined in mc.par, get temperatures and calculate number of photons to allocate memory for
//and then rcord which blocks have to have "x" amount of photons injected there
rmin=r_inj - 0.5*C_LIGHT/fps;
rmax=r_inj + 0.5*C_LIGHT/fps;
for(i=0;i<array_length;i++)
{
//look at all boxes in width delta r=c/fps and within angles we are interested in NEED TO IMPLEMENT
if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) )
{
block_cnt++;
}
}
//printf("Blocks: %d\n", block_cnt);
ph_dens=malloc(block_cnt * sizeof(int));
//calculate the photon density for each block and save it to the array
j=0;
ph_tot=0;
ph_weight_adjusted=ph_weight;
//printf("%d %d\n", max_photons, min_photons);
while ((ph_tot>max_photons) || (ph_tot<min_photons) )
{
j=0;
ph_tot=0;
//allocate memory to record density of photons for each block
//ph_dens=malloc(block_cnt * sizeof(int));
for (i=0;i<array_length;i++)
{
//printf("%d\n",i);
//printf("%e, %e, %e, %e, %e, %e\n", *(r+i),(r_inj - C_LIGHT/fps), (r_inj + C_LIGHT/fps), *(theta+i) , theta_max, theta_min);
if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >=theta_min) )
{
if (riken_switch==0)
{
//using FLASH
ph_dens_calc=(num_dens_coeff*2.0*M_PI*(*(x+i))*pow(*(temps+i),3.0)*pow(*(szx+i),2.0) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1) ; //a*T^3/(weight) dV, dV=2*PI*x*dx^2,
}
else
{
ph_dens_calc=(num_dens_coeff*2.0*M_PI*pow(*(r+i),2)*sin(*(theta+i))*pow(*(temps+i),3.0)*(*(szx+i))*(*(szy+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)),0.5),-1); //dV=2 *pi* r^2 Sin(theta) dr dtheta
}
(*(ph_dens+j))=gsl_ran_poisson(rand,ph_dens_calc) ; //choose from poission distribution with mean of ph_dens_calc
//printf("%d, %lf \n",*(ph_dens+j), ph_dens_calc);
//sum up all the densities to get total number of photons
ph_tot+=(*(ph_dens+j));
j++;
}
}
if (ph_tot>max_photons)
{
//if the number of photons is too big make ph_weight larger
ph_weight_adjusted*=10;
//free(ph_dens);
}
else if (ph_tot<min_photons)
{
ph_weight_adjusted*=0.5;
//free(ph_dens);
}
//printf("dens: %d, photons: %d\n", *(ph_dens+(j-1)), ph_tot);
}
//printf("%d\n", ph_tot);
//allocate memory for that many photons and also allocate memory to hold comoving 4 momentum of each photon and the velocity of the fluid
(*ph)=malloc (ph_tot * sizeof (struct photon ));
p_comv=malloc(4*sizeof(double));
boost=malloc(3*sizeof(double));
l_boost=malloc(4*sizeof(double));
//go through blocks and assign random energies/locations to proper number of photons
ph_tot=0;
k=0;
for (i=0;i<array_length;i++)
{
if ((*(r+i) >= rmin) && (*(r+i) < rmax ) && (*(theta+i)< theta_max) && (*(theta+i) >= theta_min) )
{
//*(temps+i)=0.76*(*(temps+i));
for(j=0;j<( *(ph_dens+k) ); j++ )
{
//have to get random frequency for the photon comoving frequency
y_dum=1; //initalize loop
yfr_dum=0;
while (y_dum>yfr_dum)
{
fr_dum=gsl_rng_uniform_pos(rand)*6.3e11*(*(temps+i)); //in Hz
//printf("%lf, %lf ",gsl_rng_uniform_pos(rand), (*(temps+i)));
y_dum=gsl_rng_uniform_pos(rand);
//printf("%lf ",fr_dum);
if (spect=='w')
{
yfr_dum=(1.0/(1.29e31))*pow((fr_dum/(*(temps+i))),3.0)/(exp((PL_CONST*fr_dum)/(K_B*(*(temps+i)) ))-1); //curve is normalized to maximum
}
else
{
fr_max=(5.88e10)*(*(temps+i));//(C_LIGHT*(*(temps+i)))/(0.29); //max frequency of bb
bb_norm=(PL_CONST*fr_max * pow((fr_max/C_LIGHT),2.0))/(exp(PL_CONST*fr_max/(K_B*(*(temps+i))))-1); //find value of bb at fr_max
yfr_dum=((1.0/bb_norm)*PL_CONST*fr_dum * pow((fr_dum/C_LIGHT),2.0))/(exp(PL_CONST*fr_dum/(K_B*(*(temps+i))))-1); //curve is normalized to vaue of bb @ max frequency
}
//printf("%lf, %lf,%lf,%e \n",(*(temps+i)),fr_dum, y_dum, yfr_dum);
}
//printf("%lf\n ",fr_dum);
position_phi=gsl_rng_uniform(rand)*2*M_PI;
com_v_phi=gsl_rng_uniform(rand)*2*M_PI;
com_v_theta=acos((gsl_rng_uniform(rand)*2)-1);
//printf("%lf, %lf, %lf\n", position_phi, com_v_phi, com_v_theta);
//populate 4 momentum comoving array
*(p_comv+0)=PL_CONST*fr_dum/C_LIGHT;
*(p_comv+1)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*cos(com_v_phi);
*(p_comv+2)=(PL_CONST*fr_dum/C_LIGHT)*sin(com_v_theta)*sin(com_v_phi);
*(p_comv+3)=(PL_CONST*fr_dum/C_LIGHT)*cos(com_v_theta);
//populate boost matrix, not sure why multiplying by -1, seems to give correct answer in old python code...
*(boost+0)=-1*(*(vx+i))*cos(position_phi);
*(boost+1)=-1*(*(vx+i))*sin(position_phi);
*(boost+2)=-1*(*(vy+i));
//printf("%lf, %lf, %lf\n", *(boost+0), *(boost+1), *(boost+2));
//boost to lab frame
lorentzBoost(boost, p_comv, l_boost, 'p', fPtr);
//printf("Assignemnt: %e, %e, %e, %e\n", *(l_boost+0), *(l_boost+1), *(l_boost+2),*(l_boost+3));
(*ph)[ph_tot].p0=(*(l_boost+0));
(*ph)[ph_tot].p1=(*(l_boost+1));
(*ph)[ph_tot].p2=(*(l_boost+2));
(*ph)[ph_tot].p3=(*(l_boost+3));
(*ph)[ph_tot].r0= (*(x+i))*cos(position_phi); //put photons @ center of box that they are supposed to be in with random phi
(*ph)[ph_tot].r1=(*(x+i))*sin(position_phi) ;
(*ph)[ph_tot].r2=(*(y+i)); //y coordinate in flash becomes z coordinate in MCRaT
(*ph)[ph_tot].num_scatt=0;
(*ph)[ph_tot].weight=ph_weight_adjusted;
(*ph)[ph_tot].nearest_block_index=0;
//printf("%d\n",ph_tot);
ph_tot++;
}
k++;
}
}
*ph_num=ph_tot; //save number of photons
//printf(" %d: %d\n", *(ph_dens+(k-1)), *ph_num);
free(ph_dens); free(p_comv);free(boost); free(l_boost);
}
void lorentzBoost(double *boost, double *p_ph, double *result, char object, FILE *fPtr)
{
//function to perform lorentz boost
//if doing boost for an electron last argument is 'e' and there wont be a check for zero norm
//if doing boost for a photon last argument is 'p' and there will be a check for zero norm
double beta=0, gamma=0, *boosted_p=NULL;
gsl_vector_view b=gsl_vector_view_array(boost, 3); //make boost pointer into vector
gsl_vector_view p=gsl_vector_view_array(p_ph, 4); //make boost pointer into vector
gsl_matrix *lambda1= gsl_matrix_calloc (4, 4); //create matrix thats 4x4 to do lorentz boost
gsl_vector *p_ph_prime =gsl_vector_calloc(4); //create vestor to hold lorentz boosted vector
/*
fprintf(fPtr,"Boost: %e, %e, %e, %e\n",gsl_blas_dnrm2(&b.vector), *(boost+0), *(boost+1), *(boost+2));
fflush(fPtr);
fprintf(fPtr,"4 Momentum to Boost: %e, %e, %e, %e\n",*(p_ph+0), *(p_ph+1), *(p_ph+2), *(p_ph+3));
fflush(fPtr);
*/
//if magnitude of fluid velocity is != 0 do lorentz boost otherwise dont need to do a boost
if (gsl_blas_dnrm2(&b.vector) > 0)
{
//fprintf(fPtr,"in If\n");
//fflush(fPtr);
beta=gsl_blas_dnrm2(&b.vector);
gamma=1.0/sqrt(1-pow(beta, 2.0));
//fprintf(fPtr,"Beta: %e\tGamma: %e\n",beta,gamma );
//fflush(fPtr);
//initalize matrix values
gsl_matrix_set(lambda1, 0,0, gamma);
gsl_matrix_set(lambda1, 0,1, -1*gsl_vector_get(&b.vector,0)*gamma);
gsl_matrix_set(lambda1, 0,2, -1*gsl_vector_get(&b.vector,1)*gamma);
gsl_matrix_set(lambda1, 0,3, -1*gsl_vector_get(&b.vector,2)*gamma);
gsl_matrix_set(lambda1, 1,1, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,0),2.0)/pow(beta,2.0) ) );
gsl_matrix_set(lambda1, 1,2, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,1)/pow(beta,2.0) ) ));
gsl_matrix_set(lambda1, 1,3, ((gamma-1)*(gsl_vector_get(&b.vector,0)* gsl_vector_get(&b.vector,2)/pow(beta,2.0) ) ));
gsl_matrix_set(lambda1, 2,2, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,1),2.0)/pow(beta,2.0) ) );
gsl_matrix_set(lambda1, 2,3, ((gamma-1)*(gsl_vector_get(&b.vector,1)* gsl_vector_get(&b.vector,2)/pow(beta,2.0)) ) );
gsl_matrix_set(lambda1, 3,3, 1+((gamma-1)*pow(gsl_vector_get(&b.vector,2),2.0)/pow(beta,2.0) ) );
gsl_matrix_set(lambda1, 1,0, gsl_matrix_get(lambda1,0,1));
gsl_matrix_set(lambda1, 2,0, gsl_matrix_get(lambda1,0,2));
gsl_matrix_set(lambda1, 3,0, gsl_matrix_get(lambda1,0,3));
gsl_matrix_set(lambda1, 2,1, gsl_matrix_get(lambda1,1,2));
gsl_matrix_set(lambda1, 3,1, gsl_matrix_get(lambda1,1,3));
gsl_matrix_set(lambda1, 3,2, gsl_matrix_get(lambda1,2,3));
gsl_blas_dgemv(CblasNoTrans, 1, lambda1, &p.vector, 0, p_ph_prime );
/*
fprintf(fPtr,"Lorentz Boost Matrix 0: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 0,0), gsl_matrix_get(lambda1, 0,1), gsl_matrix_get(lambda1, 0,2), gsl_matrix_get(lambda1, 0,3));
fflush(fPtr);
fprintf(fPtr,"Lorentz Boost Matrix 1: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 1,0), gsl_matrix_get(lambda1, 1,1), gsl_matrix_get(lambda1, 1,2), gsl_matrix_get(lambda1, 1,3));
fflush(fPtr);
fprintf(fPtr,"Lorentz Boost Matrix 2: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 2,0), gsl_matrix_get(lambda1, 2,1), gsl_matrix_get(lambda1, 2,2), gsl_matrix_get(lambda1, 2,3));
fflush(fPtr);
fprintf(fPtr,"Lorentz Boost Matrix 3: %e,%e, %e, %e\n", gsl_matrix_get(lambda1, 3,0), gsl_matrix_get(lambda1, 3,1), gsl_matrix_get(lambda1, 3,2), gsl_matrix_get(lambda1, 3,3));
fflush(fPtr);
fprintf(fPtr,"Before Check: %e %e %e %e\n ",gsl_vector_get(p_ph_prime, 0), gsl_vector_get(p_ph_prime, 1), gsl_vector_get(p_ph_prime, 2), gsl_vector_get(p_ph_prime, 3));
fflush(fPtr);
*/
//double check vector for 0 norm condition if photon
if (object == 'p')
{
//fprintf(fPtr,"In if\n");
boosted_p=zeroNorm(gsl_vector_ptr(p_ph_prime, 0));
}
else
{
boosted_p=gsl_vector_ptr(p_ph_prime, 0);
}
/*
fprintf(fPtr,"After Check: %e %e %e %e\n ", *(boosted_p+0),*(boosted_p+1),*(boosted_p+2),*(boosted_p+3) );
fflush(fPtr);
* */
}
else
{
/*
fprintf(fPtr,"in else");
fflush(fPtr);
* */
//double check vector for 0 norm condition
if (object=='p')
{
boosted_p=zeroNorm(p_ph);
}
else
{
//if 4 momentum isnt for photon and there is no boost to be done, we dont care about normality and just want back what was passed to lorentz boost
boosted_p=gsl_vector_ptr(&p.vector, 0);
}
}
//assign values to result
*(result+0)=*(boosted_p+0);
*(result+1)=*(boosted_p+1);
*(result+2)=*(boosted_p+2);
*(result+3)=*(boosted_p+3);
//free up memory
//free(boosted_p);
gsl_matrix_free (lambda1); gsl_vector_free(p_ph_prime);
}
double *zeroNorm(double *p_ph)
{
//ensures zero norm condition of photon 4 monetum is held
int i=0;
double normalizing_factor=0;
gsl_vector_view p=gsl_vector_view_array((p_ph+1), 3); //make last 3 elements of p_ph pointer into vector
if (*(p_ph+0) != gsl_blas_dnrm2(&p.vector ) )
{
normalizing_factor=(gsl_blas_dnrm2(&p.vector ));
//fprintf(fPtr,"in zero norm if\n");
//fflush(fPtr);
//go through and correct 4 momentum assuming the energy is correct
*(p_ph+1)= ((*(p_ph+1))/(normalizing_factor))*(*(p_ph+0));
*(p_ph+2)= ((*(p_ph+2))/(normalizing_factor))*(*(p_ph+0));
*(p_ph+3)= ((*(p_ph+3))/(normalizing_factor))*(*(p_ph+0));
}
/*
if (pow((*(p_ph+0)),2) != ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) )
{
printf("This isnt normalized in the function\nThe difference is: %e\n", pow((*(p_ph+0)),2) - ( pow((*(p_ph+1)),2)+pow((*(p_ph+2)),2)+pow((*(p_ph+3)),2) ) );
}
*/ //normalized within a factor of 10^-53
return p_ph;
}
int findNearestBlock(int array_num, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, int dim_switch_3d)
{
double dist=0, dist_min=1e15, block_dist=0;
int min_index=0, j=0;
dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved
block_dist=3e9;
while (dist_min==1e15) //if this is true, then the algorithm hasnt found blocks within the acceptable range given by block_dist
{
for(j=0;j<array_num;j++)
{
//if the distance between them is within 3e9, to restrict number of possible calculations, calulate the total distance between the box and photon
if ((dim_switch_3d==0) && (fabs(ph_x- (*(x+j)))<block_dist) && (fabs(ph_y- (*(y+j)))<block_dist))
{
dist= pow(pow(ph_x- (*(x+j)), 2.0) + pow(ph_y- (*(y+j)) , 2.0),0.5);
//fprintf(fPtr,"Dist calculated as: %e, index: %d\n", dist, j);
//printf("In outer if statement, OLD: %e, %d\n", dist_min, min_index);
if((dist<dist_min))
{
//fprintf(fPtr,"In innermost if statement, OLD: %e, %d\n", dist_min, min_index);
dist_min=dist; //save new minimum distance
min_index=j; //save index
//printf("New Min dist: %e, New min Index: %d, Array_Num: %d\n", dist_min, min_index, array_num);
}
}
else if ((dim_switch_3d==1) &&(fabs(ph_x- (*(x+j)))<block_dist) && (fabs(ph_y- (*(y+j)))<block_dist) && (fabs(ph_z- (*(z+j)))<block_dist))
{
dist= pow(pow(ph_x- (*(x+j)), 2.0) + pow(ph_y- (*(y+j)),2.0 ) + pow(ph_z- (*(z+j)) , 2.0),0.5);
if((dist<dist_min))
{
//printf("In innermost if statement, OLD: %e, %d\n", dist_min, min_index);
dist_min=dist; //save new minimum distance
min_index=j; //save index
//fprintf(fPtr,"New Min dist: %e, New min Index: %d, Array_Num: %e\n", dist_min, min_index, array_num);
}
}
}
block_dist*=10; //increase size of accepted distances for gris points, if dist_min==1e12 then the next time the acceptance range wil be larger
}
return min_index;
}
int findContainingBlock(int array_num, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, double *szx, double *szy, int dim_switch_3d, int riken_switch, FILE *fPtr)
{
int i=0, within_block_index=0;
bool is_in_block=0; //boolean to determine if the photon is outside of a grid
for (i=0;i<array_num;i++)
{
is_in_block=checkInBlock(i, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch);
if (is_in_block)
{
within_block_index=i;
//change for loop index once the block is found so the code doesnt search the rest of the grids to see if the photon is within those grids
i=array_num;
}
}
if (is_in_block==0)
{
fprintf(fPtr, "Couldn't find a block that the photon is in\n");
}
return within_block_index;
}
int checkInBlock(int block_index, double ph_x, double ph_y, double ph_z, double *x, double *y, double *z, double *szx, double *szy, int dim_switch_3d, int riken_switch)
{
bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block
double x0=0, x1=0, x2=0, sz_x0=0, sz_x1=0, sz_x2=0; //coordinate and sizes of grid block, in cartesian its x,y,z in spherical its r,theta,phi
int return_val=0;
if (dim_switch_3d==0)
{
if (riken_switch==1)
{
x0=pow(pow((*(x+block_index)),2.0)+pow((*(y+block_index)),2.0), 0.5);
x1=atan2((*(x+block_index)), (*(y+block_index)));
sz_x0=(*(szx+block_index));
sz_x1=(*(szy+block_index));
//pow(pow( ph_x, 2.0) + pow(ph_y, 2.0),0.5) atan2(ph_x, ph_y)
is_in_block= (fabs(pow(pow( ph_x, 2.0) + pow(ph_y, 2.0),0.5) - x0) <= sz_x0/2.0) && (fabs(atan2(ph_x, ph_y) - x1 ) <= sz_x1/2.0);
}
else
{
x0=(*(x+block_index));
x1=(*(y+block_index));
sz_x0=(*(szx+block_index));
sz_x1=(*(szy+block_index));
is_in_block= (fabs(ph_x-x0) <= sz_x0/2.0) && (fabs(ph_y-x1) <= sz_x1/2.0);
}
}
else
{
if (riken_switch==1)
{
x0=pow(pow((*(x+block_index)), 2.0) + pow((*(y+block_index)),2.0 ) + pow((*(z+block_index)) , 2.0),0.5);
x1=acos((*(z+block_index))/pow(pow((*(x+block_index)), 2.0) + pow((*(y+block_index)),2.0 ) + pow((*(z+block_index)) , 2.0),0.5));
x2=atan2((*(y+block_index)), (*(x+block_index)));
sz_x0=(*(szy+block_index));
sz_x1=(*(szx+block_index));
sz_x2=(*(szx+block_index));
is_in_block= (fabs(pow(pow( ph_x, 2.0) + pow(ph_y, 2.0)+pow(ph_z, 2.0),0.5) - x0) <= sz_x0/2.0) && (fabs(acos(ph_z/pow(pow(ph_x, 2.0) + pow(ph_y,2.0 ) + pow(ph_z , 2.0),0.5)) - x1 ) <= sz_x1/2.0) && (fabs(atan2(ph_y, ph_x) - x2 ) <= sz_x2/2.0);
}
}
if (is_in_block)
{
return_val=1;
}
else
{
return_val=0;
}
return return_val;
}
int findNearestPropertiesAndMinMFP( struct photon *ph, int num_ph, int array_num, double hydro_domain_x, double hydro_domain_y, double *time_step, double *x, double *y, double *z, double *szx, double *szy, double *velx, double *vely, double *velz, double *dens_lab,\
double *temp, double *n_dens_lab, double *n_vx, double *n_vy, double *n_vz, double *n_temp, gsl_rng * rand, int dim_switch_3d, int find_nearest_block_switch, int riken_switch, FILE *fPtr)
{
int i=0, min_index=0, ph_block_index=0;
double ph_x=0, ph_y=0, ph_phi=0, ph_z=0, ph_r=0;
double fl_v_x=0, fl_v_y=0, fl_v_z=0; //to hold the fluid velocity in MCRaT coordinates
double ph_v_norm=0, fl_v_norm=0;
double n_cosangle=0, n_dens_lab_tmp=0,n_vx_tmp=0, n_vy_tmp=0, n_vz_tmp=0, n_temp_tmp=0 ;
double rnd_tracker=0, n_dens_lab_min=0, n_vx_min=0, n_vy_min=0, n_vz_min=0, n_temp_min=0;
int num_thread=omp_get_num_threads();
bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block
int index=0;
double mfp=0,min_mfp=0, beta=0;
double *all_time_steps=NULL;
gsl_permutation *perm = gsl_permutation_alloc(num_ph); //to hold sorted indexes of smallest to largest time_steps
gsl_vector_view all_time_steps_vector;
//initialize gsl random number generator fo each thread
const gsl_rng_type *rng_t;
gsl_rng **rng;
gsl_rng_env_setup();
rng_t = gsl_rng_ranlxs0;
rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *));
rng[0]=rand;
//#pragma omp parallel for num_threads(nt)
for(i=1;i<num_thread;i++)
{
rng[i] = gsl_rng_alloc (rng_t);
gsl_rng_set(rng[i],gsl_rng_get(rand));
}
//go through each photon and find the blocks around it and then get the distances to all of those blocks and choose the one thats the shortest distance away
//can optimize here, exchange the for loops and change condition to compare to each of the photons is the radius of the block is .95 (or 1.05) times the min (max) photon radius
//or just parallelize this part here
all_time_steps=malloc(num_ph*sizeof(double));
min_mfp=1e12;
#pragma omp parallel for num_threads(num_thread) firstprivate( is_in_block, ph_block_index, ph_r, ph_x, ph_y, ph_z, ph_phi, min_index, n_dens_lab_tmp,n_vx_tmp, n_vy_tmp, n_vz_tmp, n_temp_tmp, fl_v_x, fl_v_y, fl_v_z, fl_v_norm, ph_v_norm, n_cosangle, mfp, beta, rnd_tracker) private(i) shared(min_mfp )
for (i=0;i<num_ph; i++)
{
//printf("%d, %e,%e\n", i, ((ph+i)->r0), ((ph+i)->r1));
if (find_nearest_block_switch==0)
{
ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault
}
else
{
ph_block_index=0; //if starting a new frame set index=0 to avoid this issue
}
if (dim_switch_3d==0)
{
ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate
ph_y=((ph+i)->r2);
ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0));
ph_r=pow(ph_x*ph_x + ph_y*ph_y, 0.5);
}
else
{
ph_x=((ph+i)->r0);
ph_y=((ph+i)->r1);
ph_z=((ph+i)->r2);
ph_r=pow(ph_x*ph_x + ph_y*ph_y+ph_z*ph_z, 0.5);
}
//if the location of the photon is less than the domain of the hydro simulation then do all of this, otherwise assing huge mfp value so no scattering occurs and the next frame is loaded
if ((ph_y<hydro_domain_y) && (ph_x<hydro_domain_x))
{
//printf("ph_x:%e, ph_y:%e\n", ph_x, ph_y);
is_in_block=checkInBlock(ph_block_index, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch);
if (find_nearest_block_switch==0 && is_in_block)
{
//keep the saved grid index
min_index=ph_block_index;
}
else
{
//find the new index of the block closest to the photon
//min_index=findNearestBlock(array_num, ph_x, ph_y, ph_z, x, y, z, dim_switch_3d); //stop doing this one b/c nearest grid could be one that the photon isnt actually in due to adaptive mesh
//find the new index of the block that the photon is actually in
min_index=findContainingBlock(array_num, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch, fPtr);
(ph+i)->nearest_block_index=min_index; //save the index
}
//fprintf(fPtr,"Outside\n");
//save values
(n_dens_lab_tmp)= (*(dens_lab+min_index));
(n_vx_tmp)= (*(velx+min_index));
(n_vy_tmp)= (*(vely+min_index));
(n_temp_tmp)= (*(temp+min_index));
if (dim_switch_3d==1)
{
(n_vz_tmp)= (*(velz+min_index));
}
if (dim_switch_3d==0)
{
fl_v_x=(*(velx+min_index))*cos(ph_phi);
fl_v_y=(*(velx+min_index))*sin(ph_phi);
fl_v_z=(*(vely+min_index));
}
else
{
fl_v_x=(*(velx+min_index));
fl_v_y=(*(vely+min_index));
fl_v_z=(*(velz+min_index));
}
fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5);
ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5);
//(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product
(n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined
if (dim_switch_3d==0)
{
beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)),0.5);
}
else
{
beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5);
}
//put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case
rnd_tracker=0;
rnd_tracker=gsl_rng_uniform_pos(rng[omp_get_thread_num()]);
//printf("Rnd_tracker: %e Thread number %d \n",rnd_tracker, omp_get_thread_num() );
mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOMP_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths
}
else
{
mfp=min_mfp;
//printf("In ELSE\n");
}
*(all_time_steps+i)=mfp/C_LIGHT;
}
//free rand number generator
for (i=1;i<num_thread;i++)
{
gsl_rng_free(rng[i]);
}
free(rng);
//save variables I need
all_time_steps_vector=gsl_vector_view_array(all_time_steps, num_ph); //makes a vector to use the time steps in another gsl function
gsl_sort_vector_index (perm, &all_time_steps_vector.vector); //sorts timesteps from smallest to largest and saves the indexes fo the smallest to largest elements in perm, the all_time_steps vector stays in the same order as before (ordered by photons)
//for (i=0;i<num_ph;i++)
//{
// *(sorted_indexes+i)= (int) perm->data[i]; //save sorted indexes to array to use outside of function
//}
(*time_step)=*(all_time_steps+( (int) perm->data[0] ));
index= (int) perm->data[0] ;//first element of sorted array, index of photon
min_index=(ph+index)->nearest_block_index; //index of FLASH element closest to photon that will scatter
*(n_dens_lab)= (*(dens_lab+min_index));
*(n_vx)= (*(velx+min_index));
*(n_vy)= (*(vely+min_index));
*(n_temp)= (*(temp+min_index));
if (dim_switch_3d==1)
{
*(n_vz)= (*(velz+min_index));
}
free (all_time_steps);
gsl_permutation_free(perm);
all_time_steps=NULL;
return index;
}
int interpolatePropertiesAndMinMFP( struct photon *ph, int num_ph, int array_num, double *time_step, double *x, double *y, double *z, double *szx, double *szy, double *velx, double *vely, double *velz, double *dens_lab,\
double *temp, double *n_dens_lab, double *n_vx, double *n_vy, double *n_vz, double *n_temp, gsl_rng * rand, int dim_switch_3d, int find_nearest_block_switch, int riken_switch, FILE *fPtr)
{
/*
* THIS FUNCTION IS WRITTEN JUST FOR 2D SIMS AS OF NOW
*/
int i=0, j=0, min_index=0, ph_block_index=0;
int left_block_index=0, right_block_index=0, bottom_block_index=0, top_block_index=0, all_adjacent_block_indexes[4];
double ph_x=0, ph_y=0, ph_phi=0, ph_z=0, dist=0, left_dist_min=0, right_dist_min=0, top_dist_min=0, bottom_dist_min=0, dv=0, v=0;
double fl_v_x=0, fl_v_y=0, fl_v_z=0; //to hold the fluid velocity in MCRaT coordinates
double r=0, theta=0;
double ph_v_norm=0, fl_v_norm=0;
double n_cosangle=0, n_dens_lab_tmp=0,n_vx_tmp=0, n_vy_tmp=0, n_vz_tmp=0, n_temp_tmp=0;
double rnd_tracker=0, n_dens_lab_min=0, n_vx_min=0, n_vy_min=0, n_vz_min=0, n_temp_min=0;
int num_thread=2;//omp_get_max_threads();
bool is_in_block=0; //boolean to determine if the photon is outside of its previously noted block
int index=0;
double mfp=0,min_mfp=0, beta=0;
//initialize gsl random number generator fo each thread
const gsl_rng_type *rng_t;
gsl_rng **rng;
gsl_rng_env_setup();
rng_t = gsl_rng_ranlxs0;
rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *));
rng[0]=rand;
//#pragma omp parallel for num_threads(nt)
for(i=1;i<num_thread;i++)
{
rng[i] = gsl_rng_alloc (rng_t);
gsl_rng_set(rng[i],gsl_rng_get(rand));
}
//go through each photon and find the blocks around it and then get the distances to all of those blocks and choose the one thats the shortest distance away
//can optimize here, exchange the for loops and change condition to compare to each of the photons is the radius of the block is .95 (or 1.05) times the min (max) photon radius
//or just parallelize this part here
min_mfp=1e12;
#pragma omp parallel for num_threads(num_thread) firstprivate( r, theta,dv, v, all_adjacent_block_indexes, j, left_block_index, right_block_index, top_block_index, bottom_block_index, is_in_block, ph_block_index, ph_x, ph_y, ph_z, ph_phi, min_index, n_dens_lab_tmp,n_vx_tmp, n_vy_tmp, n_vz_tmp, n_temp_tmp, fl_v_x, fl_v_y, fl_v_z, fl_v_norm, ph_v_norm, n_cosangle, mfp, beta, rnd_tracker) private(i) shared(min_mfp )
for (i=0;i<num_ph; i++)
{
//printf("%d, %e,%e\n", i, ((ph+i)->r0), ((ph+i)->r1));
if (find_nearest_block_switch==0)
{
ph_block_index=(ph+i)->nearest_block_index; //if starting a new frame the number of indexes can change and cause a seg fault
}
else
{
ph_block_index=0; //if starting a new frame set index=0 to avoid this issue
}
if (dim_switch_3d==0)
{
ph_x=pow(pow(((ph+i)->r0),2.0)+pow(((ph+i)->r1),2.0), 0.5); //convert back to FLASH x coordinate
ph_y=((ph+i)->r2);
ph_phi=atan2(((ph+i)->r1), ((ph+i)->r0));
}
else
{
ph_x=((ph+i)->r0);
ph_y=((ph+i)->r1);
ph_z=((ph+i)->r2);
}
//printf("ph_x:%e, ph_y:%e\n", ph_x, ph_y);
is_in_block=checkInBlock(ph_block_index, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch);
if (find_nearest_block_switch==0 && is_in_block)
{
//keep the saved grid index
min_index=ph_block_index;
}
else
{
//find the new index of the block closest to the photon
//min_index=findNearestBlock(array_num, ph_x, ph_y, ph_z, x, y, z, dim_switch_3d); //stop doing this one b/c nearest grid could be one that the photon isnt actually in due to adaptive mesh
//find the new index of the block that the photon is actually in
min_index=findContainingBlock(array_num, ph_x, ph_y, ph_z, x, y, z, szx, szy, dim_switch_3d, riken_switch, fPtr);
(ph+i)->nearest_block_index=min_index; //save the index
}
//look for the blocks surounding the block of interest and order them by the
left_dist_min=1e15;//set dist to impossible value to make sure at least first distance calulated is saved
right_dist_min=1e15;
top_dist_min=1e15;
bottom_dist_min=1e15;
for (j=0;j<array_num;j++)
{
if ((dim_switch_3d==0))
{
dist= pow(pow((*(x+min_index))- (*(x+j)), 2.0) + pow((*(y+min_index))- (*(y+j)) , 2.0),0.5);
}
else
{
dist= pow(pow((*(x+min_index))- (*(x+j)), 2.0) + pow((*(y+min_index))- (*(y+j)),2.0 ) + pow((*(z+min_index))- (*(z+j)) , 2.0),0.5);
}
if ((*(x+j))<(*(x+min_index)) && (dist < left_dist_min) )
{
left_block_index=j;
left_dist_min=dist;
}
else if ((*(x+j))>(*(x+min_index)) && (dist < right_dist_min))
{
right_block_index=j;
right_dist_min=dist;
}
if ((*(y+j))<(*(y+min_index)) && (dist < bottom_dist_min) )
{
bottom_block_index=j;
bottom_dist_min=dist;
}
else if ((*(y+j))>(*(y+min_index)) && (dist < top_dist_min) )
{
top_block_index=j;
top_dist_min=dist;
}
}
all_adjacent_block_indexes[0]=left_block_index;
all_adjacent_block_indexes[1]=right_block_index;
all_adjacent_block_indexes[2]=bottom_block_index;
all_adjacent_block_indexes[3]=top_block_index;
//do a weighted average of the 4 nearest grids based on volume
v=0;
(n_dens_lab_tmp)=0;
(n_vx_tmp)= 0;
(n_vy_tmp)= 0;
(n_temp_tmp)= 0;
(n_vz_tmp)= 0;
for (j=0;j<4;j++)
{
if (riken_switch==0)
{
//using FLASH
dv=2.0*M_PI*(*(x+all_adjacent_block_indexes[j]))*pow(*(szx+all_adjacent_block_indexes[j]),2.0) ;
}
else
{
r=pow(pow((*(x+all_adjacent_block_indexes[j])),2.0)+pow((*(y+all_adjacent_block_indexes[j])),2.0), 0.5);
theta=atan2((*(x+all_adjacent_block_indexes[j])), (*(y+all_adjacent_block_indexes[j])));
dv=2.0*M_PI*pow(r,2)*sin(theta)*(*(szx+all_adjacent_block_indexes[j]))*(*(szy+all_adjacent_block_indexes[j])) ;
}
v+=dv;
//save values
(n_dens_lab_tmp)+= (*(dens_lab+all_adjacent_block_indexes[j]))*dv;
(n_vx_tmp)+= (*(velx+all_adjacent_block_indexes[j]))*dv;
(n_vy_tmp)+= (*(vely+all_adjacent_block_indexes[j]))*dv;
(n_temp_tmp)+= (*(temp+all_adjacent_block_indexes[j]))*dv;
if (dim_switch_3d==1)
{
(n_vz_tmp)+= (*(velz+all_adjacent_block_indexes[j]))*dv;
}
}
//fprintf(fPtr,"Outside\n");
//save values
(n_dens_lab_tmp)/= v;
(n_vx_tmp)/= v;
(n_vy_tmp)/= v;
(n_temp_tmp)/= v;
if (dim_switch_3d==1)
{
(n_vz_tmp)/= v;
}
if (dim_switch_3d==0)
{
fl_v_x=n_vx_tmp*cos(ph_phi);
fl_v_y=n_vx_tmp*sin(ph_phi);
fl_v_z=n_vy_tmp;
}
else
{
fl_v_x=n_vx_tmp;
fl_v_y=n_vy_tmp;
fl_v_z=n_vz_tmp;
}
fl_v_norm=pow(pow(fl_v_x, 2.0)+pow(fl_v_y, 2.0)+pow(fl_v_z, 2.0), 0.5);
ph_v_norm=pow(pow(((ph+i)->p1), 2.0)+pow(((ph+i)->p2), 2.0)+pow(((ph+i)->p3), 2.0), 0.5);
//(*(n_cosangle+i))=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //find cosine of the angle between the photon and the fluid velocities via a dot product
(n_cosangle)=((fl_v_x* ((ph+i)->p1))+(fl_v_y* ((ph+i)->p2))+(fl_v_z* ((ph+i)->p3)))/(fl_v_norm*ph_v_norm ); //make 1 for cylindrical otherwise its undefined
if (dim_switch_3d==0)
{
beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)),0.5);
}
else
{
beta=pow((pow((n_vx_tmp),2)+pow((n_vy_tmp),2)+pow((n_vz_tmp),2)),0.5);
}
//put this in to double check that random number is between 0 and 1 (exclusive) because there was a problem with this for parallel case
rnd_tracker=0;
rnd_tracker=gsl_rng_uniform_pos(rng[omp_get_thread_num()]);
mfp=(-1)*(M_P/((n_dens_lab_tmp))/THOMP_X_SECT/(1.0-beta*((n_cosangle))))*log(rnd_tracker) ; //calulate the mfp and then multiply it by the ln of a random number to simulate distribution of mean free paths
#pragma omp critical
if ( mfp<min_mfp)
{
min_mfp=mfp;
n_dens_lab_min= n_dens_lab_tmp;
n_vx_min= n_vx_tmp;
n_vy_min= n_vy_tmp;
if (dim_switch_3d==1)
{
n_vz_min= n_vz_tmp;
}
n_temp_min= n_temp_tmp;
index=i;
//fprintf(fPtr, "Thread is %d. new min: %e for photon %d with block properties: %e, %e, %e Located at: %e, %e, Dist: %e\n", omp_get_thread_num(), mfp, index, n_vx_tmp, n_vy_tmp, n_temp_tmp, *(x+min_index), *(y+min_index), dist_min);
//fflush(fPtr);
#pragma omp flush(min_mfp)
}
}
//free rand number generator
for (i=1;i<num_thread;i++)
{
gsl_rng_free(rng[i]);
}
free(rng);
*(n_dens_lab)= n_dens_lab_min;
*(n_vx)= n_vx_min;
*(n_vy)= n_vy_min;
if (dim_switch_3d==1)
{
*(n_vz)= n_vz_min;
}
*(n_temp)= n_temp_min;
(*time_step)=min_mfp/C_LIGHT;
return index;
}
void updatePhotonPosition(struct photon *ph, int num_ph, double t, FILE *fPtr)
{
//move photons by speed of light
int i=0, num_thread=omp_get_num_threads();
double old_position=0, new_position=0, divide_p0=0;
#pragma omp parallel for num_threads(num_thread) firstprivate(old_position, new_position, divide_p0)
for (i=0;i<num_ph;i++)
{
old_position= pow( pow(ph->r0,2)+pow(ph->r1,2)+pow(ph->r2,2), 0.5 );
divide_p0=1.0/((ph+i)->p0);
((ph+i)->r0)+=((ph+i)->p1)*divide_p0*C_LIGHT*t; //update x position
((ph+i)->r1)+=((ph+i)->p2)*divide_p0*C_LIGHT*t;//update y
((ph+i)->r2)+=((ph+i)->p3)*divide_p0*C_LIGHT*t;//update z
new_position= pow( pow(ph->r0,2)+pow(ph->r1,2)+pow(ph->r2,2), 0.5 );
if ((new_position-old_position)/t > C_LIGHT)
{
fprintf(fPtr, "PHOTON NUMBER %d IS SUPERLUMINAL. ITS SPEED IS %e c.\n", i, ((new_position-old_position)/t)/C_LIGHT);
}
//printf("In update function: %e, %e, %e, %e, %e, %e, %e\n",((ph+i)->r0), ((ph+i)->r1), ((ph+i)->r2), t, ((ph+i)->p1)/((ph+i)->p0), ((ph+i)->p2)/((ph+i)->p0), ((ph+i)->p3)/((ph+i)->p0) );
}
//printf("In update function: %e, %e, %e, %e\n",t, ((ph)->p1)/((ph)->p0), ((ph)->p2)/((ph)->p0), ((ph)->p3)/((ph)->p0) );
}
void photonScatter(struct photon *ph, double flash_vx, double flash_vy, double flash_vz, double fluid_temp, gsl_rng * rand,int dim_switch_3d, FILE *fPtr)
{
//function to perform single photon scattering
double ph_phi=0;
double *ph_p=malloc(4*sizeof(double)); //pointer to hold only photon 4 momentum @ start
double *el_p_comov=malloc(4*sizeof(double));//pointer to hold the electron 4 momenta in comoving frame
double *ph_p_comov=malloc(4*sizeof(double));//pointer to hold the comoving photon 4 momenta
double *fluid_beta=malloc(3*sizeof(double));//pointer to hold fluid velocity vector
double *negative_fluid_beta=malloc(3*sizeof(double));//pointer to hold negative fluid velocity vector
ph_phi=atan2((ph->r1), ((ph->r0)));
/*
fprintf(fPtr,"ph_phi=%e\n", ph_phi);
fflush(fPtr);
*/
//convert flash coordinated into MCRaT coordinates
//printf("Getting fluid_beta\n");
if (dim_switch_3d==0)
{
(*(fluid_beta+0))=flash_vx*cos(ph_phi);
(*(fluid_beta+1))=flash_vx*sin(ph_phi);
(*(fluid_beta+2))=flash_vy;
}
else
{
(*(fluid_beta+0))=flash_vx;
(*(fluid_beta+1))=flash_vy;
(*(fluid_beta+2))=flash_vz;
}
/*
fprintf(fPtr,"FLASH v: %e, %e\n", flash_vx,flash_vy);
fflush(fPtr);
*/
//fill in photon 4 momentum
//printf("filling in 4 momentum in photonScatter\n");
*(ph_p+0)=(ph->p0);
*(ph_p+1)=(ph->p1);
*(ph_p+2)=(ph->p2);
*(ph_p+3)=(ph->p3);
/*
fprintf(fPtr,"Unscattered Photon in Lab frame: %e, %e, %e,%e, %e, %e, %e\n", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3), (ph->r0), (ph->r1), (ph->r2));
fflush(fPtr);
fprintf(fPtr,"Fluid Beta: %e, %e, %e\n", *(fluid_beta+0),*(fluid_beta+1), *(fluid_beta+2));
fflush(fPtr);
*/
//first we bring the photon to the fluid's comoving frame
lorentzBoost(fluid_beta, ph_p, ph_p_comov, 'p', fPtr);
/*
fprintf(fPtr,"Old: %e, %e, %e,%e\n", ph->p0, ph->p1, ph->p2, ph->p3);
fflush(fPtr);
fprintf(fPtr, "Before Scattering, In Comov_frame:\n");
fflush(fPtr);
fprintf(fPtr, "ph_comov: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));
fflush(fPtr);
*/
//second we generate a thermal electron at the correct temperature
singleElectron(el_p_comov, fluid_temp, ph_p_comov, rand, fPtr);
//fprintf(fPtr,"el_comov: %e, %e, %e,%e\n", *(el_p_comov+0), *(el_p_comov+1), *(el_p_comov+2), *(el_p_comov+3));
//fflush(fPtr);
//third we perform the scattering and save scattered photon 4 monetum in ph_p_comov @ end of function
singleComptonScatter(el_p_comov, ph_p_comov, rand, fPtr);
//fprintf(fPtr,"After Scattering, After Lorentz Boost to Comov frame: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));
//fflush(fPtr);
//fourth we bring the photon back to the lab frame
*(negative_fluid_beta+0)=-1*( *(fluid_beta+0));
*(negative_fluid_beta+1)=-1*( *(fluid_beta+1));
*(negative_fluid_beta+2)=-1*( *(fluid_beta+2));
lorentzBoost(negative_fluid_beta, ph_p_comov, ph_p, 'p', fPtr);
//fprintf(fPtr,"Scattered Photon in Lab frame: %e, %e, %e,%e\n", *(ph_p+0), *(ph_p+1), *(ph_p+2), *(ph_p+3));
fflush(fPtr);
if (((*(ph_p+0))*C_LIGHT/1.6e-9) > 1e4)
{
fprintf(fPtr,"Extremely High Photon Energy!!!!!!!!\n");
fflush(fPtr);
}
//fprintf(fPtr,"Old: %e, %e, %e,%e\n", ph->p0, ph->p1, ph->p2, ph->p3);
//fprintf(fPtr, "Old: %e, %e, %e,%e\n", *(ph_p_comov+0), *(ph_p_comov+1), *(ph_p_comov+2), *(ph_p_comov+3));
//assign the photon its new lab 4 momentum
(ph->p0)=(*(ph_p+0));
(ph->p1)=(*(ph_p+1));
(ph->p2)=(*(ph_p+2));
(ph->p3)=(*(ph_p+3));
//printf("Done assigning values to original struct\n");
free(el_p_comov);
free(ph_p_comov);
free(fluid_beta);
free(negative_fluid_beta);
free(ph_p);
ph_p=NULL;negative_fluid_beta=NULL;ph_p_comov=NULL; el_p_comov=NULL;
}
void singleElectron(double *el_p, double temp, double *ph_p, gsl_rng * rand, FILE *fPtr)
{
//generates an electron with random energy
double factor=0, gamma=0;
double y_dum=0, f_x_dum=0, x_dum=0, beta_x_dum=0, beta=0, phi=0, theta=0, ph_theta=0, ph_phi=0;
gsl_matrix *rot= gsl_matrix_calloc (3, 3); //create matrix thats 3x3 to do rotation
gsl_vector_view el_p_prime ; //create vector to hold rotated electron 4 momentum
gsl_vector *result=gsl_vector_alloc (3);
//fprintf(fPtr, "Temp in singleElectron: %e\n", temp);
if (temp>= 1e7)
{
//printf("In if\n");
factor=K_B*temp/(M_EL*pow(C_LIGHT,2.0));
y_dum=1; //initalize loop to get a random gamma from the distribution of electron velocities
f_x_dum=0;
while ((isnan(f_x_dum) !=0) || (y_dum>f_x_dum) )
{
x_dum=gsl_rng_uniform_pos(rand)*(1+100*factor);
beta_x_dum=pow(1-(pow(x_dum, -2.0)) ,0.5);
y_dum=gsl_rng_uniform(rand)/2.0;
f_x_dum=pow(x_dum,2)*(beta_x_dum/gsl_sf_bessel_Kn (2, 1.0/factor))*exp(-1*x_dum/factor); //not sure if this is right is giving small values of gamma -> beta=nan
//fprintf(fPtr,"Choosing a Gamma: xdum: %e, f_x_dum: %e, y_dum: %e\n", x_dum, f_x_dum, y_dum);
}
gamma=x_dum;
}
else
{
//printf("In else\n");
factor=pow(K_B*temp/M_EL,0.5);
//calculate a random gamma from 3 random velocities drawn from a gaussian distribution with std deviation of "factor"
gamma=pow( 1- (pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+ pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2)+pow(gsl_ran_gaussian(rand, factor)/C_LIGHT, 2) ) ,-0.5);
}
//fprintf(fPtr,"Chosen Gamma: %e\n",gamma);
beta=pow( 1- (1/pow( gamma,2.0 )) ,0.5);
//printf("Beta is: %e in singleElectron\n", beta);
phi=gsl_rng_uniform(rand)*2*M_PI;
y_dum=1; //initalize loop to get a random theta
f_x_dum=0;
while (y_dum>f_x_dum)
{
y_dum=gsl_rng_uniform(rand)*1.3;
x_dum=gsl_rng_uniform(rand)*M_PI;
f_x_dum=sin(x_dum)*(1-(beta*cos(x_dum)));
}
theta=x_dum;
//fprintf(fPtr,"Beta: %e\tPhi: %e\tTheta: %e\n",beta,phi, theta);
//fill in electron 4 momentum NOT SURE WHY THE ORDER IS AS SUCH SEEMS TO BE E/c, pz,py,px!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
*(el_p+0)=gamma*(M_EL)*(C_LIGHT);
*(el_p+1)=gamma*(M_EL)*(C_LIGHT)*beta*cos(theta);
*(el_p+2)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*sin(phi);
*(el_p+3)=gamma*(M_EL)*(C_LIGHT)*beta*sin(theta)*cos(phi);
//printf("Old: %e, %e, %e,%e\n", *(el_p+0), *(el_p+1), *(el_p+2), *(el_p+3));
el_p_prime=gsl_vector_view_array((el_p+1), 3);
//find angles of photon NOT SURE WHY WERE CHANGING REFERENCE FRAMES HERE???!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
ph_phi=atan2(*(ph_p+2), *(ph_p+3)); //Double Check
ph_theta=atan2(pow( pow(*(ph_p+2),2)+ pow(*(ph_p+3),2) , 0.5) , (*(ph_p+1)) );
//printf("Calculated Photon phi and theta in singleElectron:%e, %e\n", ph_phi, ph_theta);
//fill in rotation matrix to rotate around x axis to get rid of phi angle
gsl_matrix_set(rot, 1,1,1);
gsl_matrix_set(rot, 2,2,cos(ph_theta));
gsl_matrix_set(rot, 0,0,cos(ph_theta));
gsl_matrix_set(rot, 0,2,-sin(ph_theta));
gsl_matrix_set(rot, 2,0,sin(ph_theta));
gsl_blas_dgemv(CblasNoTrans, 1, rot, &el_p_prime.vector, 0, result);
/*
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2));
printf("Middle: %e, %e, %e,%e\n", *(el_p+0), gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2));
*/
gsl_matrix_set_all(rot,0);
gsl_matrix_set(rot, 0,0,1);
gsl_matrix_set(rot, 1,1,cos(-ph_phi));
gsl_matrix_set(rot, 2,2,cos(-ph_phi));
gsl_matrix_set(rot, 1,2,-sin(-ph_phi));
gsl_matrix_set(rot, 2,1,sin(-ph_phi));
gsl_blas_dgemv(CblasNoTrans, 1, rot, result, 0, &el_p_prime.vector);
/*
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot, 0,0), gsl_matrix_get(rot, 0,1), gsl_matrix_get(rot, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot, 1,0), gsl_matrix_get(rot, 1,1), gsl_matrix_get(rot, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot, 2,0), gsl_matrix_get(rot, 2,1), gsl_matrix_get(rot, 2,2));
printf("Final EL_P_vec: %e, %e, %e,%e\n", *(el_p+0), gsl_vector_get(&el_p_prime.vector,0), gsl_vector_get(&el_p_prime.vector,1), gsl_vector_get(&el_p_prime.vector,2));
*/
gsl_matrix_free (rot);gsl_vector_free(result);
}
void singleComptonScatter(double *el_comov, double *ph_comov, gsl_rng * rand, FILE *fPtr)
{
//This routine performs a Compton scattering between a photon and a moving electron.
int i=0;
double *el_v=malloc(3*sizeof(double));
double *negative_el_v=malloc(3*sizeof(double));
double *ph_p_prime=malloc(4*sizeof(double));//use this to keep track of how the ph 4 momentum changes with each rotation
double *el_p_prime=malloc(4*sizeof(double));
double phi0=0, phi1=0, phi=0, theta=0;
double y_dum, f_x_dum, x_dum;
gsl_matrix *rot0= gsl_matrix_calloc (3, 3); //create matricies thats 3x3 to do rotations
gsl_matrix *rot1= gsl_matrix_calloc (3, 3);
gsl_vector *result0=gsl_vector_alloc (3); //vectors to hold results of rotations
gsl_vector *result1=gsl_vector_alloc (3);
gsl_vector *result=gsl_vector_alloc (4);
gsl_vector *whole_ph_p=gsl_vector_alloc (4);
gsl_vector_view ph_p ; //create vector to hold comoving photon and electron 4 momentum
gsl_vector_view el_p ;
//fill in electron velocity array and photon 4 momentum
*(el_v+0)=(*(el_comov+1))/(*(el_comov+0));
*(el_v+1)=(*(el_comov+2))/(*(el_comov+0));
*(el_v+2)=(*(el_comov+3))/(*(el_comov+0));
//printf("el_v: %e, %e, %e\n", *(el_v+0), *(el_v+1), *(el_v+2));
//lorentz boost into frame where the electron is stationary
lorentzBoost(el_v, el_comov, el_p_prime, 'e', fPtr);
lorentzBoost(el_v, ph_comov, ph_p_prime, 'p', fPtr);
//printf("New ph_p in electron rest frame: %e, %e, %e,%e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));
ph_p=gsl_vector_view_array((ph_p_prime+1), 3);
el_p=gsl_vector_view_array(el_p_prime,4);
phi0=atan2(*(ph_p_prime+2), *(ph_p_prime+1) );
//printf("Photon Phi: %e\n", phi0);
//rotate the axes so that the photon incomes along the x-axis
gsl_matrix_set(rot0, 2,2,1);
gsl_matrix_set(rot0, 0,0,cos(-phi0));
gsl_matrix_set(rot0, 1,1,cos(-phi0));
gsl_matrix_set(rot0, 0,1,-sin(-phi0));
gsl_matrix_set(rot0, 1,0,sin(-phi0));
gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0);
/*
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2));
*/
//set values of ph_p_prime equal to the result and get new phi from result
*(ph_p_prime+1)=gsl_vector_get(result0,0);
*(ph_p_prime+2)=0;//gsl_vector_get(result,1); //just directly setting it to 0 now?
*(ph_p_prime+3)=gsl_vector_get(result0,2);
phi1=atan2(gsl_vector_get(result0,2), gsl_vector_get(result0,0));
/*
printf("rotation 1: %e, %e, %e\n", *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));
printf("Photon Phi: %e\n", phi1);
printf("make sure the vector view is good: %e, %e, %e,%e\n", *(ph_p_prime+0), gsl_vector_get(&ph_p.vector,0), gsl_vector_get(&ph_p.vector,1), gsl_vector_get(&ph_p.vector,2));
*/
//rotate around y to bring it all along x
gsl_matrix_set(rot1, 1,1,1);
gsl_matrix_set(rot1, 0,0,cos(-phi1));
gsl_matrix_set(rot1, 2,2,cos(-phi1));
gsl_matrix_set(rot1, 0,2,-sin(-phi1));
gsl_matrix_set(rot1, 2,0,sin(-phi1));
gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1);
/*
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2));
*/
//set values of ph_p_prime equal to the result and get new phi from result
*(ph_p_prime+1)=*(ph_p_prime+0);//why setting it to the energy?
*(ph_p_prime+2)=gsl_vector_get(result1,1);
*(ph_p_prime+3)=0; //just directly setting it to 0 now?
//printf("rotation 2: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));
//generate random theta and phi angles for scattering
phi=gsl_rng_uniform(rand)*2*M_PI;
//printf("Phi: %e\n", phi);
y_dum=1; //initalize loop to get a random theta
f_x_dum=0;
while (y_dum>f_x_dum)
{
y_dum=gsl_rng_uniform(rand)*1.09;
x_dum=gsl_rng_uniform(rand)*M_PI;
f_x_dum=sin(x_dum)*(1+pow(cos(x_dum),2));
}
theta=x_dum;
//printf("Theta: %e\n", theta);
//perform scattering and compute new 4-momenta of electron and photon
//scattered photon 4 momentum
gsl_vector_set(result, 0, (*(ph_p_prime+0))/(1+ (( (*(ph_p_prime+0))*(1-cos(theta)) )/(M_EL*C_LIGHT )) ) ); //DOUBLE CHECK HERE!!!!
gsl_vector_set(result, 1, gsl_vector_get(result,0)*cos(theta) );
gsl_vector_set(result, 2, gsl_vector_get(result,0)*sin(theta)*sin(phi) );
gsl_vector_set(result, 3, gsl_vector_get(result,0)*sin(theta)*cos(phi) );
//printf("%e\n", gsl_vector_get(result,0));
//calculate electron 4 momentum OPTIMIZE HERE: DONT USE A FOR LOOP HERE!!!! Done
//prescattered photon 4 momentum
gsl_vector_set(whole_ph_p, 0, (*(ph_p_prime+0)));
gsl_vector_set(whole_ph_p, 1, (*(ph_p_prime+1)));
gsl_vector_set(whole_ph_p, 2, (*(ph_p_prime+2)));
gsl_vector_set(whole_ph_p, 3, (*(ph_p_prime+3)));
/*
for (i=0;i<4;i++)
{
gsl_vector_set(whole_ph_p, i, (*(ph_p_prime+i)));
}
*/
gsl_vector_sub(whole_ph_p,result); //resut is saved into ph_p vector, unscattered-scattered 4 mometum of photon
gsl_vector_add(&el_p.vector ,whole_ph_p);
/*
printf("After scattering:\n");
printf("el_p: %e, %e, %e,%e\n", gsl_vector_get(&el_p.vector,0), gsl_vector_get(&el_p.vector,1), gsl_vector_get(&el_p.vector,2), gsl_vector_get(&el_p.vector,3));
printf("ph_p: %e, %e, %e,%e\n", gsl_vector_get(result,0), gsl_vector_get(result,1), gsl_vector_get(result,2), gsl_vector_get(result,3));
*/
//rotate back to comoving frame
*(ph_p_prime+0)=gsl_vector_get(result,0);
*(ph_p_prime+1)=gsl_vector_get(result,1); //set values of photon prime momentum from doing the scattering to use the vector view of it in dot product
*(ph_p_prime+2)=gsl_vector_get(result,2);
*(ph_p_prime+3)=gsl_vector_get(result,3);
gsl_matrix_set_all(rot1,0);
gsl_matrix_set(rot1, 1,1,1);
gsl_matrix_set(rot1, 0,0,cos(-phi1));
gsl_matrix_set(rot1, 2,2,cos(-phi1));
gsl_matrix_set(rot1, 0,2,sin(-phi1));
gsl_matrix_set(rot1, 2,0,-sin(-phi1));
gsl_blas_dgemv(CblasNoTrans, 1, rot1, &ph_p.vector, 0, result1);
/*
printf("Photon Phi: %e\n", phi1);
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot1, 0,0), gsl_matrix_get(rot1, 0,1), gsl_matrix_get(rot1, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot1, 1,0), gsl_matrix_get(rot1, 1,1), gsl_matrix_get(rot1, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot1, 2,0), gsl_matrix_get(rot1, 2,1), gsl_matrix_get(rot1, 2,2));
*/
//set values of ph_p_prime to result1 from undoing 2nd rotation
*(ph_p_prime+1)=gsl_vector_get(result1,0);
*(ph_p_prime+2)=gsl_vector_get(result1,1);
*(ph_p_prime+3)=gsl_vector_get(result1,2);
//printf("Undo rotation 2: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));
//ignore the electron, dont care about it, undo the first rotation
gsl_matrix_set_all(rot0,0);
gsl_matrix_set(rot0, 2,2,1);
gsl_matrix_set(rot0, 0,0,cos(-phi0));
gsl_matrix_set(rot0, 1,1,cos(-phi0));
gsl_matrix_set(rot0, 0,1,sin(-phi0));
gsl_matrix_set(rot0, 1,0,-sin(-phi0));
gsl_blas_dgemv(CblasNoTrans, 1, rot0, &ph_p.vector, 0, result0);
/*
printf("Photon Phi: %e\n", phi0);
printf("Rotation Matrix 0: %e,%e, %e\n", gsl_matrix_get(rot0, 0,0), gsl_matrix_get(rot0, 0,1), gsl_matrix_get(rot0, 0,2));
printf("Rotation Matrix 1: %e,%e, %e\n", gsl_matrix_get(rot0, 1,0), gsl_matrix_get(rot0, 1,1), gsl_matrix_get(rot0, 1,2));
printf("Rotation Matrix 2: %e,%e, %e\n", gsl_matrix_get(rot0, 2,0), gsl_matrix_get(rot0, 2,1), gsl_matrix_get(rot0, 2,2));
*/
*(ph_p_prime+1)=gsl_vector_get(result0,0);
*(ph_p_prime+2)=gsl_vector_get(result0,1);
*(ph_p_prime+3)=gsl_vector_get(result0,2);
//printf("Undo rotation 1: %e, %e, %e, %e\n", *(ph_p_prime+0), *(ph_p_prime+1), *(ph_p_prime+2), *(ph_p_prime+3));
//deboost photon to lab frame
*(negative_el_v+0)=(-1*(*(el_v+0)));
*(negative_el_v+1)=(-1*(*(el_v+1)));
*(negative_el_v+2)=(-1*(*(el_v+2)));
lorentzBoost(negative_el_v, ph_p_prime, ph_comov, 'p', fPtr);
//printf("Undo boost 1: %e, %e, %e, %e\n", *(ph_comov+0), *(ph_comov+1), *(ph_comov+2), *(ph_comov+3));
gsl_matrix_free(rot0); gsl_matrix_free(rot1);gsl_vector_free(result0);gsl_vector_free(result1);gsl_vector_free(result);
//gsl_rng_free (rand);
gsl_vector_free(whole_ph_p);free(ph_p_prime);free(el_p_prime);free(el_v); free(negative_el_v);
}
double averagePhotonEnergy(struct photon *ph, int num_ph)
{
//to calculate weighted photon energy
int i=0;
double e_sum=0, w_sum=0;
for (i=0;i<num_ph;i++)
{
e_sum+=(((ph+i)->p0)*((ph+i)->weight));
w_sum+=((ph+i)->weight);
}
return (e_sum*C_LIGHT)/w_sum;
}
void phScattStats(struct photon *ph, int ph_num, int *max, int *min, double *avg, double *r_avg )
{
int temp_max=0, temp_min=-1, i=0;
double sum=0, avg_r_sum=0;
for (i=0;i<ph_num;i++)
{
sum+=((ph+i)->num_scatt);
avg_r_sum+=pow(((ph+i)->r0)*((ph+i)->r0) + ((ph+i)->r1)*((ph+i)->r1) + ((ph+i)->r2)*((ph+i)->r2), 0.5);
if (((ph+i)->num_scatt) > temp_max )
{
temp_max=((ph+i)->num_scatt);
//printf("The new max is: %d\n", temp_max);
}
if ((i==0) || (((ph+i)->num_scatt)<temp_min))
{
temp_min=((ph+i)->num_scatt);
//printf("The new min is: %d\n", temp_min);
}
}
*avg=sum/ph_num;
*r_avg=avg_r_sum/ph_num;
*max=temp_max;
*min=temp_min;
}
void cylindricalPrep(double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array)
{
double gamma_infinity=100, t_comov=1*pow(10, 5), ddensity=3e-7;// the comoving temperature in Kelvin, and the comoving density in g/cm^2
int i=0;
double vel=pow(1-pow(gamma_infinity, -2.0) ,0.5), lab_dens=gamma_infinity*ddensity;
for (i=0; i<num_array;i++)
{
*(gamma+i)=gamma_infinity;
*(vx+i)=0;
*(vy+i)=vel;
*(dens+i)=ddensity;
*(dens_lab+i)=lab_dens;
*(pres+i)=(A_RAD*pow(t_comov, 4.0))/(3*pow(C_LIGHT, 2.0));
*(temp+i)=pow(3*(*(pres+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0); //just assign t_comov
}
}
void sphericalPrep(double *r, double *x, double *y, double *gamma, double *vx, double *vy, double *dens, double *dens_lab, double *pres, double *temp, int num_array, FILE *fPtr)
{
double gamma_infinity=100, lumi=1e52, r00=1e8;
double vel=0;
int i=0;
for (i=0;i<num_array;i++)
{
if ((*(r+i)) >= (r00*gamma_infinity))
{
*(gamma+i)=gamma_infinity;
*(pres+i)=(lumi*pow(r00, 2.0/3.0)*pow(*(r+i), -8.0/3.0) )/(12.0*M_PI*C_LIGHT*pow(gamma_infinity, 4.0/3.0)*pow(C_LIGHT, 2.0));
}
else
{
*(gamma+i)=(*(r+i))/r00;
*(pres+i)=(lumi*pow(r00, 2.0))/(12.0*M_PI*C_LIGHT*pow(C_LIGHT, 2.0)*pow(*(r+i), 4.0) );
}
vel=pow(1-(pow(*(gamma+i), -2.0)) ,0.5);
*(vx+i)=(vel*(*(x+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5);
*(vy+i)=(vel*(*(y+i)))/pow(pow(*(x+i), 2)+ pow(*(y+i), 2) ,0.5);
*(dens+i)=lumi/(4*M_PI*pow(*(r+i), 2.0)*pow(C_LIGHT, 3.0)*gamma_infinity*(*(gamma+i)));
*(dens_lab+i)=(*(dens+i))*(*(gamma+i));
*(temp+i)=pow(3*(*(pres+i))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
//fprintf(fPtr,"Gamma: %lf\nR: %lf\nPres: %e\nvel %lf\nX: %lf\nY %lf\nVx: %lf\nVy: %lf\nDens: %e\nLab_Dens: %e\nTemp: %lf\n", *(gamma+i), *(r+i), *(pres+i), vel, *(x+i), *(y+i), *(vx+i), *(vy+i), *(dens+i), *(dens_lab+i), *(temp+i));
}
}
void dirFileMerge(char dir[200], int start_frame, int last_frame, int numprocs, int angle_id, int dim_switch, int riken_switch, FILE *fPtr )
{
//function to merge files in mcdir produced by various threads
int i=0, j=0, k=0, num_files=8, num_thread=8; //omp_get_max_threads() number of files is number of types of mcdata files there are
int increment=1;
char filename_k[2000]="", file_no_thread_num[2000]="", cmd[2000]="", mcdata_type[200]="";
//printf("Merging files in %s\n", dir);
//#pragma omp parallel for num_threads(num_thread) firstprivate( filename_k, file_no_thread_num, cmd,mcdata_type,num_files, increment ) private(i,j,k)
// i < last frame because calculation before this function gives last_frame as the first frame of the next process set of frames to merge files for
for (i=start_frame;i<last_frame;i=i+increment)
{
fprintf(fPtr, "Merging files for frame: %d\n", i);
fflush(fPtr);
if ((riken_switch==1) && (dim_switch==1) && (i>=3000))
{
increment=10; //when the frame ==3000 for RIKEN 3D hydro files, increment file numbers by 10 instead of by 1
}
for (j=0;j<num_files;j=j+1)
{
switch (j)
{
case 0: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P0"); break;
case 1: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P1");break;
case 2: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P2"); break;
case 3: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "P3"); break;
case 4: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R0"); break;
case 5: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R1"); break;
case 6: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "R2"); break;
case 7: snprintf(mcdata_type,sizeof(mcdata_type), "%s", "NS"); break;
}
for (k=0;k<numprocs;k++)
{
snprintf(file_no_thread_num,sizeof(file_no_thread_num),"%s%s%d%s%s%s", dir,"mcdata_",i,"_", mcdata_type,".dat");
snprintf(filename_k,sizeof(filename_k),"%s%s%d%s%s%s%d%s", dir,"mcdata_",i,"_", mcdata_type ,"_",k, ".dat");
//check if both the file exists
if (( access( filename_k, F_OK ) != -1 ) )
{
//if they both do make command to cat the together always in the same order
//fprintf(fPtr, "Merging: %s\n", filename_k);
snprintf(cmd, sizeof(cmd), "%s%s %s%s", "cat ", filename_k, " >> ", file_no_thread_num);
system(cmd);
}
//remove file
snprintf(cmd, sizeof(cmd), "%s%s", "rm ", filename_k);
system(cmd);
}
}
}
if (angle_id==0)
{
//merge photon weight files
for (k=0;k<numprocs;k++)
{
snprintf(file_no_thread_num,sizeof(file_no_thread_num),"%s%s", dir,"mcdata_PW.dat");
snprintf(filename_k,sizeof(filename_k),"%s%s%d%s", dir,"mcdata_PW_",k,".dat");
if (( access( filename_k, F_OK ) != -1 ) )
{
//if they both do make command to cat the together always in the same order
snprintf(cmd, sizeof(cmd), "%s%s %s%s", "cat ", filename_k, " >> ", file_no_thread_num);
system(cmd);
}
//remove files
snprintf(cmd, sizeof(cmd), "%s%s", "rm ", filename_k);
system(cmd);
}
}
}
void modifyFlashName(char flash_file[200], char prefix[200], int frame, int dim_switch)
{
int lim1=0, lim2=0, lim3=0;
if (dim_switch==0)
{
//2D case
lim1=10;
lim2=100;
lim3=1000;
}
else
{
//3d case
lim1=100;
lim2=1000;
lim3=10000;
}
if (frame<lim1)
{
snprintf(flash_file,200, "%s%.3d%d",prefix,000,frame);
}
else if (frame<lim2)
{
snprintf(flash_file,200, "%s%.2d%d",prefix,00,frame);
}
else if (frame<lim3)
{
snprintf(flash_file,200, "%s%d%d",prefix,0,frame);
}
else
{
snprintf(flash_file,200, "%s%d",prefix,frame);
}
}
void readHydro2D(char hydro_prefix[200], int frame, 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, FILE *fPtr)
{
FILE *hydroPtr=NULL;
char hydrofile[200]="", file_num[200]="", full_file[200]="", file_end[200]="" ;
char buf[10]="";
int i=0, j=0, k=0, elem=0, elem_factor=0;
int all_index_buffer=0, r_min_index=0, r_max_index=0, theta_min_index=0, theta_max_index=0; //all_index_buffer contains phi_min, phi_max, theta_min, theta_max, r_min, r_max indexes to get from grid files
int r_index=0, theta_index=0;
float buffer=0;
float *dens_unprc=NULL,*vel_r_unprc=NULL, *vel_theta_unprc=NULL,*pres_unprc=NULL;
double ph_rmin=0, ph_rmax=0;
double r_in=1e10;
//double *r_edge=malloc(sizeof(double)*(R_DIM_2D+1));
//double *dr=malloc(sizeof(double)*(R_DIM_2D));
double *r_unprc=malloc(sizeof(double)*R_DIM_2D);
double *theta_unprc=malloc(sizeof(double)*THETA_DIM_2D);
if (ph_inj_switch==0)
{
ph_rmin=min_r;
ph_rmax=max_r;
}
snprintf(file_end,sizeof(file_end),"%s","small.data" );
//density
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 1,"-" );
modifyFlashName(file_num, hydrofile, frame,0);
fprintf(fPtr,">> Opening file %s\n", file_num);
fflush(fPtr);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&theta_min_index, sizeof(int)*1, 1,hydroPtr);
fread(&theta_max_index, sizeof(int)*1, 1,hydroPtr);
fread(&r_min_index, sizeof(int)*1, 1,hydroPtr);
fread(&r_max_index, sizeof(int)*1, 1,hydroPtr);
fclose(hydroPtr);
//fortran indexing starts @ 1, but C starts @ 0
r_min_index--;//=r_min_index-1;
r_max_index--;//=r_max_index-1;
theta_min_index--;//=theta_min_index-1;
theta_max_index--;//=theta_max_index-1;
elem=(r_max_index+1-r_min_index)*(theta_max_index+1-theta_min_index); //max index is max number of elements minus 1, there add one to get total number of elements
fprintf(fPtr,"Elem %d\n", elem);
fprintf(fPtr,"Limits %d, %d, %d, %d, %d, %d\n", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index);
fflush(fPtr);
//now with number of elements allocate data
dens_unprc=malloc(elem*sizeof(float));
vel_r_unprc=malloc(elem*sizeof(float));
vel_theta_unprc=malloc(elem*sizeof(float));
pres_unprc=malloc(elem*sizeof(float));
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
/*
for (i=0;i<elem;i++)
{
fread((dens_unprc+i), sizeof(float),1, hydroPtr); //read data
}
*/
fread(dens_unprc, sizeof(float),elem, hydroPtr);
fclose(hydroPtr);
//V_r
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 2,"-" );
modifyFlashName(file_num, hydrofile, frame,0);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(vel_r_unprc, sizeof(float),elem, hydroPtr); //data
fclose(hydroPtr);
//V_theta
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 3,"-" );
modifyFlashName(file_num, hydrofile, frame,0);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(vel_theta_unprc, sizeof(float), elem, hydroPtr); //data
fclose(hydroPtr);
//u04 is phi component but is all 0
//pres
snprintf(hydrofile,sizeof(hydrofile),"%s%s%d%s",hydro_prefix,"u0", 8,"-" );
modifyFlashName(file_num, hydrofile, frame,0);
snprintf(full_file, sizeof(full_file), "%s%s", file_num, file_end);
//fprintf(fPtr,">> Opening file %s\n", full_file);
//fflush(fPtr);
hydroPtr=fopen(full_file, "rb");
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran
//elem=(r_max_index-r_min_index)*(theta_max_index-theta_min_index);
//fprintf(fPtr,"Elem %d\n", elem);
//fprintf(fPtr,"Limits %d, %d, %d, %d, %d, %d\n", all_index_buffer, all_index_buffer, theta_min_index, theta_max_index, r_min_index, r_max_index);
//fflush(fPtr);
fread(pres_unprc, sizeof(float),elem, hydroPtr); //data
fclose(hydroPtr);
/*
for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)
{
for (k=0; k<(r_max_index+1-r_min_index); k++)
{
fprintf(fPtr,"Pres %d: %e\n", ( j*(r_max_index+1-r_min_index)+k ), *(pres_unprc+( j*(r_max_index+1-r_min_index)+k )));
//fprintf(fPtr,"Pres %d: %e\n", ( j*(r_max_index)+k ), *(pres_unprc+( j*(r_max_index)+k )));
fflush(fPtr);
}
}
exit(0);
*/
//R
snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x1.data" );
hydroPtr=fopen(hydrofile, "r");
//fprintf(fPtr,">> Opening file %s\n", hydrofile);
//fflush(fPtr);
i=0;
while (i<R_DIM_2D)
{
fscanf(hydroPtr, "%lf", (r_unprc+i)); //read value
fgets(buf, 3,hydroPtr); //read comma
/*
if (i<5)
{
//printf("Here\n");
fprintf(fPtr,"R %d: %e\n", i, *(r_unprc+i));
fflush(fPtr);
}
*/
i++;
}
fclose(hydroPtr);
//theta from y axis
snprintf(hydrofile,sizeof(hydrofile),"%s%s",hydro_prefix,"grid-x2.data" );
hydroPtr=fopen(hydrofile, "r");
//fprintf(fPtr,">> Opening file %s\n", hydrofile);
//fflush(fPtr);
i=0;
while (i<THETA_DIM_2D)
{
fscanf(hydroPtr, "%lf", (theta_unprc+i)); //read value
fgets(buf, 3,hydroPtr); //read comma
/*
if (i<5)
{
fprintf(fPtr,"Theta %d: %e\n", i, *(theta_unprc+i));
fflush(fPtr);
}
*/
i++;
}
fclose(hydroPtr);
//limit number of array elements
//fill in radius array and find in how many places r > injection radius
elem_factor=0;
elem=0;
while (elem==0)
{
elem_factor++;
elem=0;
for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)
{
for (k=0; k<(r_max_index+1-r_min_index); k++)
{
i=r_min_index+k; //look at indexes of r that are included in small hydro file
//if I have photons do selection differently than if injecting photons
if (ph_inj_switch==0)
{
//if calling this function when propagating photons, choose blocks based on where the photons are
if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (ph_rmax + elem_factor*C_LIGHT/fps) ))
{
// *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )
elem++;
}
}
else
{
//if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient
if (((r_inj - C_LIGHT/fps)<(*(r_unprc+i))) && (*(r_unprc+i) < (r_inj + C_LIGHT/fps) ))
{
// *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )
elem++;
}
}
}
}
}
fprintf(fPtr, "Number of post restricted Elems: %d %e\n", elem, r_inj);
fflush(fPtr);
(*pres)=malloc (elem * sizeof (double ));
(*velx)=malloc (elem * sizeof (double ));
(*vely)=malloc (elem * sizeof (double ));
(*dens)=malloc (elem * sizeof (double ));
(*x)=malloc (elem * sizeof (double ));
(*y)=malloc (elem * sizeof (double ));
(*r)=malloc (elem * sizeof (double ));
(*theta)=malloc (elem * sizeof (double ));
(*gamma)=malloc (elem * sizeof (double ));
(*dens_lab)=malloc (elem * sizeof (double ));
//szx becomes delta r szy becomes delta theta
(*szx)=malloc (elem * sizeof (double ));
(*szy)=malloc (elem * sizeof (double ));
(*temp)=malloc (elem * sizeof (double ));
elem=0;
for (j=0 ;j<(theta_max_index+1-theta_min_index); j++)
{
for (k=0; k<(r_max_index+1-r_min_index); k++)
{
r_index=r_min_index+k; //look at indexes of r that are included in small hydro file
theta_index=theta_min_index+j;
if (ph_inj_switch==0)
{
if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (ph_rmax + elem_factor*C_LIGHT/fps) ))
{
(*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k ));
(*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index));
(*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index));
(*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ));
(*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index));
(*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index));
(*r)[elem]=*(r_unprc+r_index);
(*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000);
(*szy)[elem]=(M_PI/2)/2000;
(*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis
(*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c
(*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1);
(*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
elem++;
}
}
else
{
if (((r_inj - C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (r_inj + C_LIGHT/fps) ))
{
(*pres)[elem]=*(pres_unprc+( j*(r_max_index+1-r_min_index)+k ));
(*velx)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index))+(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index));
(*vely)[elem]=(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )))*cos(*(theta_unprc+theta_index))-(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )))*sin(*(theta_unprc+theta_index));
(*dens)[elem]=*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ));
(*x)[elem]=(*(r_unprc+r_index))*sin(*(theta_unprc+theta_index));
(*y)[elem]=(*(r_unprc+r_index))*cos(*(theta_unprc+theta_index));
(*r)[elem]=*(r_unprc+r_index);
(*szx)[elem]=(*(r_unprc+r_index))*((M_PI/2)/2000);
(*szy)[elem]=(M_PI/2)/2000;
(*theta)[elem]=*(theta_unprc+theta_index);//theta in radians in relation to jet axis
(*gamma)[elem]=pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1); //v is in units of c
(*dens_lab)[elem]= (*(dens_unprc+( j*(r_max_index+1-r_min_index)+k ))) * pow(pow(1.0-(pow(*(vel_r_unprc+( j*(r_max_index+1-r_min_index)+k )),2)+pow(*(vel_theta_unprc+( j*(r_max_index+1-r_min_index)+k )),2)),0.5),-1);
(*temp)[elem]=pow(3*(*(pres_unprc+( j*(r_max_index+1-r_min_index)+k )))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);
elem++;
}
}
}
}
(*number)=elem;
//fprintf(fPtr, "Number of post restricted Elems: %d %e\n", elem, r_inj);
//fflush(fPtr);
free(pres_unprc); //works when not being freed?
//fprintf(fPtr, "pres Done\n\n");
//fflush(fPtr);
free(vel_r_unprc);
//fprintf(fPtr, "vel_r Done\n\n");
//fflush(fPtr);
free(vel_theta_unprc);
//fprintf(fPtr, "vel_theta Done\n\n");
//fflush(fPtr);
free(dens_unprc);
//fprintf(fPtr, "dens Done\n\n");
//fflush(fPtr);
free(r_unprc);
//fprintf(fPtr, "r Done\n\n");
//fflush(fPtr);
free(theta_unprc);
//fprintf(fPtr, "theta Done\n\n");
//fflush(fPtr);
pres_unprc=NULL;
vel_r_unprc=NULL;
vel_theta_unprc=NULL;
dens_unprc=NULL;
r_unprc=NULL;
theta_unprc=NULL;
//fprintf(fPtr, "ALL Done\n\n");
//fflush(fPtr);
}
| {
"alphanum_fraction": 0.5686085456,
"avg_line_length": 42.3784946237,
"ext": "c",
"hexsha": "f87fe86a92825d0dfff0034d8dd404538f22cc4d",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-11-20T09:12:08.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-09T16:11:50.000Z",
"max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "outflows/MCRaT",
"max_forks_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mclib.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": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mclib.c",
"max_line_length": 430,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "outflows/MCRaT",
"max_stars_repo_path": "OLDER_MCRaT_VERSIONS/HYBRID_PARALLEL/mclib.c",
"max_stars_repo_stars_event_max_datetime": "2021-04-05T14:51:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-20T08:37:35.000Z",
"num_tokens": 36050,
"size": 118236
} |
/*
**
** Lit:
** Y.Yu, S.T. Acton:
** Speckle reducing anisotropic diffusion.
** IEEE Trans Image Proc., Vol. 11, No. 11, Nov 2002
**
** G.Lohmann, MPI-CBS, 2008
*/
#include <viaio/Vlib.h>
#include <viaio/VImage.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_math.h>
#define SQR(x) ((x) * (x))
#define ABS(x) ((x) > 0 ? (x) : -(x))
/*
** repair border
*/
void
Border(VImage src)
{
int b=0,r,c,nrows,ncols;
double u;
nrows = VImageNRows(src);
ncols = VImageNColumns(src);
for (r=0; r<VImageNRows(src); r++) {
u = VGetPixel(src,b,r,1);
VSetPixel(src,b,r,0,u);
u = VGetPixel(src,b,r,ncols-2);
VSetPixel(src,b,r,ncols-1,u);
}
for (c=0; c<VImageNColumns(src); c++) {
u = VGetPixel(src,b,1,c);
VSetPixel(src,b,0,c,u);
u = VGetPixel(src,b,nrows-2,c);
VSetPixel(src,b,nrows-1,c,u);
}
}
VImage
VSRAD(VImage src,VImage dest,VShort numiter,VShort type,VFloat rho)
{
static VImage tmp1=NULL,tmp2=NULL,ctmp=NULL;
int nbands,nrows,ncols;
int b,r,c,iter;
double u,v,w,x,y;
double d,da,dd,dt,t,q,q0;
double cx,c0,c1,c2,c3;
double tiny=1.0e-6;
nbands = VImageNBands(src);
nrows = VImageNRows(src);
ncols = VImageNColumns(src);
if (tmp1 == NULL) {
tmp1 = VCreateImage(1,nrows,ncols,VFloatRepn);
tmp2 = VCreateImage(1,nrows,ncols,VFloatRepn);
ctmp = VCreateImage(1,nrows,ncols,VFloatRepn);
}
dt = 0.05;
dest = VCopyImage(src,dest,VAllBands);
for (b=0; b<nbands; b++) {
t = 0;
for (r=0; r<nrows; r++) {
for (c=0; c<ncols; c++) {
VPixel(tmp1,0,r,c,VFloat) = VGetPixel(src,b,r,c);
}
}
VFillImage(ctmp,VAllBands,0);
VFillImage(tmp2,VAllBands,0);
q0 = 1;
for (iter=0; iter < numiter; iter++) {
for (r=1; r<nrows-1; r++) {
for (c=1; c<ncols-1; c++) {
u = VPixel(tmp1,0,r,c,VFloat);
if (ABS(u) < tiny) continue;
v = VPixel(tmp1,0,r+1,c,VFloat);
w = VPixel(tmp1,0,r,c+1,VFloat);
x = VPixel(tmp1,0,r-1,c,VFloat);
y = VPixel(tmp1,0,r,c-1,VFloat);
da = (SQR(u-v) + SQR(u-w) + SQR(u-x) + SQR(u-y))/(u*u);
dd = (v+w+x+y - 4.0*u)/(u*u);
q = (0.5*da - 0.0625*dd) / (SQR(1.0 + 0.25*dd));
if (q > 0) {
q = sqrt(q);
u = (q*q - q0*q0) / ((q0*q0)*(1.0 + q0*q0));
}
else
u = 0;
cx = 0;
if (type == 0)
cx = 1.0 / (1.0 + u);
else
cx = exp(-u);
if (gsl_isnan(cx) || gsl_isinf(cx)) {
cx = 0;
VWarning(" cx, insnan, isinf");
}
VPixel(ctmp,0,r,c,VFloat) = cx;
}
}
Border(ctmp);
for (r=1; r<nrows-1; r++) {
for (c=1; c<ncols-1; c++) {
u = VPixel(tmp1,0,r,c,VFloat);
if (ABS(u) < tiny) continue;
v = VPixel(tmp1,0,r+1,c,VFloat);
w = VPixel(tmp1,0,r,c+1,VFloat);
x = VPixel(tmp1,0,r-1,c,VFloat);
y = VPixel(tmp1,0,r,c-1,VFloat);
c0 = VPixel(ctmp,0,r+1,c,VFloat);
c1 = VPixel(ctmp,0,r,c+1,VFloat);
c2 = VPixel(ctmp,0,r-1,c,VFloat);
c3 = VPixel(ctmp,0,r,c-1,VFloat);
/* ???
cx = VPixel(ctmp,0,r,c,VFloat);
d = c0*(v-u) + c1*(w-u) + cx*(x-u) + cx*(y-u);
*/
d = c0*(v-u) + c1*(w-u) + c2*(x-u) + c3*(y-u);
u = u + 0.25*dt * d;
if (gsl_isnan(u) || gsl_isinf(u)) {
u = 0;
VWarning(" insnan, isinf");
}
if (u > VPixelMaxValue (tmp2)) u = VPixelMaxValue (tmp2);
if (u < VPixelMinValue (tmp2)) u = VPixelMinValue (tmp2);
VPixel(tmp2,0,r,c,VFloat) = u;
}
}
q0 *= exp(-rho*t);
Border(tmp2);
tmp1 = VCopyImagePixels(tmp2,tmp1,VAllBands);
t += dt;
}
/*
** output
*/
for (r=1; r<nrows-1; r++) {
for (c=1; c<ncols-1; c++) {
v = VPixel(tmp2,0,r,c,VFloat);
if (gsl_isnan(v) || gsl_isinf(v)) {
v = 0;
VWarning(" insnan, isinf");
}
if (v > VPixelMaxValue (dest)) v = VPixelMaxValue (dest);
if (v < VPixelMinValue (dest)) v = VPixelMinValue (dest);
VSetPixel(dest,b,r,c,(VDouble) v);
}
}
}
/*
VDestroyImage(tmp1);
VDestroyImage(tmp2);
*/
return dest;
}
| {
"alphanum_fraction": 0.5302543838,
"avg_line_length": 20.0445544554,
"ext": "c",
"hexsha": "958e3f0fb113e84a6f7ef9266f576f89f5a7dd1d",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/prep/vsrad/SRAD.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/prep/vsrad/SRAD.c",
"max_line_length": 67,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/prep/vsrad/SRAD.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-18T10:55:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-10T16:33:42.000Z",
"num_tokens": 1637,
"size": 4049
} |
#include <stdio.h>
#include <stdlib.h>
#include <cblas.h>
#include "matrix.h"
void Matrix_Multiply(Matrix a, Matrix b, Matrix c) {
/* for dimentions:
* a[m*k],b[k*n],c[m*n]
* We use:
* RowMajor, NoTrans, NoTrans, m, n, k, 1, A, k, B, n, 0, C, n);
*/
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, a.rows, b.cols, a.cols,
1, a.values, a.cols, b.values, b.cols, 0, c.values, b.cols);
}
void Matrix_Print(Matrix m) {
printf("=====\n");
printf("rows: %lld, columns: %lld\n", m.rows, m.cols);
for (int i = 0; i < m.rows; i++) {
for (int j = 0; j < m.cols; j++) {
printf("%lf ", m.values[i * m.cols + j]);
}
printf("\n");
}
}
void Matrix_Add(Matrix a, Matrix b, Matrix c) {
for (int i = 0; i < a.rows * a.cols; i++) {
c.values[i] = a.values[i] + b.values[i];
}
}
void Matrix_Scale(Matrix a, double n) {
cblas_dscal(a.rows * a.cols, n, a.values, 1);
}
void Matrix_Test(void) {
double *A, *B, *C;
int m, n, k, i;
double alpha, beta;
m = 2000, k = 200, n = 1000;
printf(
" Initializing data for matrix multiplication C=A*B for matrix \n"
" A(%ix%i) and matrix B(%ix%i)\n",
m, k, k, n);
alpha = 1.0;
beta = 0.0;
A = (double *) malloc(m * k * sizeof(double));
B = (double *) malloc(k * n * sizeof(double));
C = (double *) malloc(m * n * sizeof(double));
if (A == NULL || B == NULL || C == NULL) {
printf("\n ERROR: Can't allocate memory for matrices. Aborting... \n\n");
free(A);
free(B);
free(C);
return;
}
printf(" Intializing matrix data \n");
for (i = 0; i < (m * k); i++) {
A[i] = (double) (i + 1);
}
for (i = 0; i < (k * n); i++) {
B[i] = (double) (-i - 1);
}
for (i = 0; i < (m * n); i++) {
C[i] = 0.0;
}
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, alpha, A, k,
B, n, beta, C, n);
printf("\n Computations completed.\n");
free(A);
free(B);
free(C);
} | {
"alphanum_fraction": 0.4872641509,
"avg_line_length": 26.5,
"ext": "c",
"hexsha": "fe558c164edc5f3e128f0692ab51607bcf22a622",
"lang": "C",
"max_forks_count": 34,
"max_forks_repo_forks_event_max_datetime": "2018-11-17T13:45:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-01-04T13:02:39.000Z",
"max_forks_repo_head_hexsha": "21480bd580a2620851ffd34f960d83e9f43fc4b5",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "rmikio/redis-ml",
"max_forks_repo_path": "src/matrix.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "21480bd580a2620851ffd34f960d83e9f43fc4b5",
"max_issues_repo_issues_event_max_datetime": "2019-02-11T00:25:55.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-02-04T01:13:36.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "rmikio/redis-ml",
"max_issues_repo_path": "src/matrix.c",
"max_line_length": 82,
"max_stars_count": 242,
"max_stars_repo_head_hexsha": "18578794d975511b6a20212e67c07e5114d25074",
"max_stars_repo_licenses": [
"Adobe-2006"
],
"max_stars_repo_name": "RedisLabsModules/redis-ml",
"max_stars_repo_path": "src/matrix.c",
"max_stars_repo_stars_event_max_datetime": "2019-02-19T22:18:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-11-01T20:52:16.000Z",
"num_tokens": 709,
"size": 2120
} |
/*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include "spc_FITScards.h"
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "spce_PET.h"
#include "inout_aper.h"
#include "trace_conf.h"
#include "aper_conf.h"
#include "disp_conf.h"
#include "drizzle_utils.h"
#include "crossdisp_utils.h"
#include "spc_cfg.h"
#include "inima_utils.h"
#include "spce_output.h"
#define AXE_IMAGE_PATH "AXE_IMAGE_PATH"
#define AXE_OUTPUT_PATH "AXE_OUTPUT_PATH"
#define AXE_CONFIG_PATH "AXE_CONFIG_PATH"
int
main (int argc, char *argv[])
{
char *opt;
char aper_file[MAXCHAR];
char aper_file_path[MAXCHAR];
char list_file[MAXCHAR];
char list_file_path[MAXCHAR];
char conf_file[MAXCHAR];
char conf_file_path[MAXCHAR];
char grism_file[MAXCHAR];
char grism_file_path[MAXCHAR];
char PET_file[MAXCHAR];
char PET_file_path[MAXCHAR];
char SEC_file[MAXCHAR];
char SEC_file_path[MAXCHAR];
char outputroot[MAXCHAR];
char outputroot_path[MAXCHAR];
char output_path[MAXCHAR];
aperture_conf *conf;
object **oblist;
observation *obs;
ap_pixel *pri_PET;
ap_pixel *sec_PET;
d_point pixel;
d_point refwave_pos;
d_point outref;
d_point minxy_PET;
px_point pixmax;
dispstruct *disp, *outdisp;
trace_func *trace;
gsl_matrix *drizzcoeffs;
//gsl_vector *lambdaref = gsl_vector_alloc(2);
FILE *in_file;
objectobs **allobjects;
int nobjects, nobjects2;
int boxwidth, boxheight,trlength;
double relx, rely, objwidth, orient;
//double min_px, min_py;
double drizzle_width;
double cdref, cdscale, cdcorr, cdmeanscale;
double sprefreso, spreso, spmeanreso, spcorr;
double sky_cps;
double exptime;
double *gaga;
int index, i, for_grism, in_index;
char label[MAXCHAR];
fitsfile *PET_ptr, *SEC_ptr, *DPP_ptr;
int f_status = 0;
int aperID, beamID, objindex;
FITScards *cards;
drzstamp_dim dimension;
drzprep *drzprep_stamps;
axe_inputs *input_list;
//int rectified = 0;
//int drizzled = 0;
int bckmode = 0;
int backpet = 1;
//int usemode = 0;
int quant_cont= 0;
int opt_extr = 0;
if ((argc < 3) || (opt = get_online_option ("help", argc, argv)))
{
fprintf (stdout,
"aXe_DRZPREP Version %s:\n"
" aXe task to produce a set of Drizzle PrePare (DPP) files\n"
" for a set of images given in an image list. A DPP-file is\n"
" a multi extension fits file with an pixel stamp image and a\n"
" contamination stamp image for each aperture in the\n"
" grism image. Uses the PET file to derive the pixel/contamination\n"
" values for the stamp images and the aperture files\n"
" (AF's) to define a common geometry for the individual objects,\n"
" which are usually located on several images/PET's. The task also\n"
" derives and stores keywords such that aXe_DRIZZLE can create\n"
" coadded images for all objects in the set of DPP-files.\n"
"\n"
" The image list is looked for in the current directory.\n"
" The images listed in the image list is looked for in\n"
" $AXE_IMAGE_PATH. The OAF/BAF- and PET-files computed from\n"
" those images is looked for in $AXE_OUTPUT_PATH\n"
" The DPP's are written to $AXE_OUTPUT_PATH\n"
"\n"
"Usage:\n"
" aXe_DRZPREP [image list filename] [aXe_config1,aXe_config2,..] [options]\n"
"\n"
"Options:\n"
" -bck - generating a background DPP from a background PET\n"
"\n",RELEASE);
exit (1);
}
fprintf (stdout, "aXe_DRZPREP: Starting...\n\n");
index = 0;
strcpy (list_file, argv[++index]);
strcpy (list_file_path, list_file);
strcpy (conf_file, argv[++index]);
// build the aXe inputs structure
input_list = get_axe_inputs(list_file_path, conf_file);
//print_axe_inputs(input_list);
/* Determine if we are using the special bck mode */
/* In this mode, file names are handled differently */
if ((opt = get_online_option("bck", argc, argv)))
bckmode = 1;
if ((opt = get_online_option("backpet", argc, argv)))
backpet = 1;
if ((opt = get_online_option("opt_extr", argc, argv)))
opt_extr = 1;
// give feedback onto the screen:
// report on input and output
// and also on specific parameter
fprintf (stdout, "aXe_DRZPREP: Input Image List: %s\n",
list_file_path);
fprintf (stdout, "aXe_DRZPREP: Configuration file names: %s\n",
conf_file);
if (opt_extr)
fprintf (stdout, "aXe_DRZPREP: Storing optimal weighting extentions.\n");
fprintf(stdout, "\n\n");
nobjects = 0;
nobjects2 = 0;
allobjects = malloc_objectobs();
fprintf (stdout, "aXe_DRZPREP: Checking input files ...");
for (in_index=0; in_index < input_list->nitems; in_index++)
{
// copy the config file name and the grism file
// name from the struct to loacal variables
strcpy(conf_file, input_list->axe_items[in_index].config_file);
strcpy(grism_file, input_list->axe_items[in_index].grism_file);
fprintf(stdout, "(%i): %s, %s\n", in_index, conf_file, grism_file);
// construct the full path to the current configuration fille
build_path (AXE_CONFIG_PATH, conf_file, conf_file_path);
for (i=0; i<= DRZMAX; i++)
{
for_grism = check_for_grism (conf_file_path,i);
if (!for_grism)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: Beam %c in configuration file %s has no grism dispersion and can not be drizzled.\n",
BEAM(i), conf_file_path);
}
conf = get_aperture_descriptor (conf_file_path);
// compose the full name to the grism image
build_path (AXE_IMAGE_PATH, grism_file, grism_file_path);
// check whether the grism file exists
in_file = fopen(grism_file_path, "r");
if (!in_file)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: File %s does not exist!\n", grism_file_path);
fclose (in_file);
get_extension_numbers(grism_file_path, conf,conf->optkey1,conf->optval1);
// find the full name to the PET file
if (bckmode)
{
/* Build object PET file name */
replace_file_extension (grism_file, PET_file, ".fits",
".BCK.PET.fits", conf->science_numext);
build_path (AXE_OUTPUT_PATH, PET_file, PET_file_path);
}
else
{
/* Build object PET file name */
replace_file_extension (grism_file, PET_file, ".fits",
".PET.fits", conf->science_numext);
build_path (AXE_OUTPUT_PATH, PET_file, PET_file_path);
}
// Open the OPET file for reading
fits_open_file (&PET_ptr, PET_file_path, READONLY, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: Could not open file: %s\n",
PET_file_path);
}
if (!bckmode)
// check whether there is quantitative contamination
quant_cont = check_quantitative_contamination(PET_ptr);
else
quant_cont=1;
// check whether optimal extraction can be done
if (opt_extr && !quant_cont)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: PET file: %s was assembled without quantitative contamination.\n",
"Optimal extraction is not possible.", PET_file_path);
// close the PET file
fits_close_file (PET_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: Could not" " close PET file: %s\n", PET_file_path);
}
if (bckmode && opt_extr)
{
/* Build object PET file name */
replace_file_extension (grism_file, PET_file, ".fits",
".PET.fits", conf->science_numext);
build_path (AXE_OUTPUT_PATH, PET_file, PET_file_path);
// Open the OPET file for reading
fits_open_file (&PET_ptr, PET_file_path, READONLY, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: Could not open file: %s\n",
PET_file_path);
}
// check whether there is quantitative contamination
quant_cont = check_quantitative_contamination(PET_ptr);
if (!quant_cont)
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: PET file: %s was assembled without quantitative contamination.\n",
"Optimal extraction is not possible.", PET_file_path);
// close the PET file
fits_close_file (PET_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: Could not" " close PET file: %s\n", PET_file_path);
}
}
}
fprintf (stdout, "Done.\n\n");
for (i=0; i < input_list->nitems; i++)
{
// copy the config file name and the grism file
// name from the struct to loacal variables
strcpy(conf_file, input_list->axe_items[i].config_file);
strcpy(grism_file, input_list->axe_items[i].grism_file);
build_path (AXE_CONFIG_PATH, conf_file, conf_file_path);
conf = get_aperture_descriptor (conf_file_path);
build_path (AXE_IMAGE_PATH, grism_file, grism_file_path);
get_extension_numbers(grism_file_path, conf,conf->optkey1,conf->optval1);
if (bckmode){
/* Build aperture file name */
replace_file_extension (grism_file, aper_file, ".fits",
".OAF", conf->science_numext);
build_path (AXE_OUTPUT_PATH, aper_file, aper_file_path);
}
else{
if (backpet)
replace_file_extension (grism_file, aper_file, ".fits",
".OAF", conf->science_numext);
else
replace_file_extension (grism_file, aper_file, ".fits",
".OAF", conf->science_numext);
build_path (AXE_OUTPUT_PATH, aper_file, aper_file_path);
}
fprintf(stdout,
"aXe_DRZPREP: Input image file list: %s\n", list_file_path);
fprintf(stdout,
"aXe_DRZPREP: Input grism image: %s\n", grism_file_path);
fprintf(stdout,
"aXe_DRZPREP: Input aperture file: %s\n", aper_file_path);
fprintf(stdout,
"aXe_DRZPREP: Input configuration file: %s\n", conf_file_path);
obs = load_dummy_observation ();
/* Loading the object list */
fprintf (stdout, "aXe_DRZPREP: Loading object aperture list ... ");
oblist = file_to_object_list_seq (aper_file_path, obs);
if (oblist != NULL) {
pixmax = get_npixels (grism_file_path, conf->science_numext);
fprintf (stdout,"%d objects loaded.\n\n",object_list_size(oblist));
nobjects2 = add_observation(grism_file_path, conf_file_path,
allobjects, nobjects2, oblist,
object_list_size(oblist), pixmax,
conf->science_numext);
free_oblist(oblist);
}
}
fprintf (stdout, "aXe_DRZPREP: %i objects in all observations.\n", nobjects2);
fprintf (stdout, "aXe_DRZPREP: Starting to compute the mean values...");
f_status = make_refpoints(conf_file_path, grism_file_path,
pixmax, allobjects, nobjects2);
fprintf (stdout, "Done.\n\n");
for (in_index=0; in_index < input_list->nitems; in_index++)
{
// copy the config file name and the grism file
// name from the struct to loacal variables
strcpy(conf_file, input_list->axe_items[in_index].config_file);
strcpy(grism_file, input_list->axe_items[in_index].grism_file);
build_path (AXE_CONFIG_PATH, conf_file, conf_file_path);
conf = get_aperture_descriptor (conf_file_path);
build_path (AXE_IMAGE_PATH, grism_file, grism_file_path);
//
// Start of working on one image
//
//
//
/* Determine where the various extensions are in the FITS file */
get_extension_numbers(grism_file_path, conf,conf->optkey1,conf->optval1);
sky_cps = (double)get_float_from_keyword(grism_file_path, conf->science_numext, "SKY_CPS");
if (isnan(sky_cps))
sky_cps = 0.0;
//
// try to get the descriptor 'sky_cps' from the 'sci'-extension
//
exptime = (double)get_float_from_keyword(grism_file_path, conf->science_numext, conf->exptimekey);
if (isnan(exptime))
exptime = (double)get_float_from_keyword(grism_file_path, 1, conf->exptimekey);
if (isnan(exptime))
exptime = 1.0;
if (bckmode)
{
/* Build aperture file name */
// replace_file_extension (grism_file, aper_file, ".fits",
// ".BAF", conf->science_numext);
replace_file_extension (grism_file, aper_file, ".fits",
".OAF", conf->science_numext);
build_path (AXE_OUTPUT_PATH, aper_file, aper_file_path);
/* Build object PET file name */
replace_file_extension (grism_file, PET_file, ".fits",
".BCK.PET.fits", conf->science_numext);
build_path (AXE_OUTPUT_PATH, PET_file, PET_file_path);
if (opt_extr)
{
/* Build second PET file name */
replace_file_extension (grism_file, SEC_file, ".fits",
".PET.fits", conf->science_numext);
build_path (AXE_OUTPUT_PATH, SEC_file, SEC_file_path);
}
}
else
{
/* Build aperture file name */
// replace_file_extension (grism_file, aper_file, ".fits",
// ".BAF", conf->science_numext);
replace_file_extension (grism_file, aper_file, ".fits",
".OAF", conf->science_numext);
build_path (AXE_OUTPUT_PATH, aper_file, aper_file_path);
/* Build object PET file name */
replace_file_extension (grism_file, PET_file, ".fits",
".PET.fits", conf->science_numext);
build_path (AXE_OUTPUT_PATH, PET_file, PET_file_path);
}
if ( (opt = get_online_option ("outputroot", argc, argv)) ){
strcpy (outputroot, opt);
}
else{
replace_file_extension (PET_file, outputroot, ".PET.fits", "",-1);
}
build_path (AXE_OUTPUT_PATH, outputroot, outputroot_path);
sprintf(output_path,"%s.DPP.fits",outputroot_path);
fprintf (stdout, "aXe_DRZPREP: Input PET file name: %s\n",
PET_file_path);
fprintf (stdout, "aXe_DRZPREP: Input Aperture file name: %s\n",
aper_file_path);
fprintf (stdout, "aXe_DRZPREP: Name of DPP file : %s\n",
output_path);
obs = load_dummy_observation ();
/* Loading the object list */
fprintf (stdout, "aXe_DRZPREP: Loading object aperture list...");
oblist = file_to_object_list_seq (aper_file_path, obs);
fprintf (stdout,"%d objects loaded.\n",object_list_size(oblist));
// Open the OPET file for reading
fits_open_file (&PET_ptr, PET_file_path, READONLY, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: Could not open file: %s\n",
PET_file_path);
}
if (!bckmode)
// check whether there is quantitative contamination
quant_cont = check_quantitative_contamination(PET_ptr);
else
quant_cont=1;
if (bckmode && opt_extr)
{
// Open the OPET file for reading
fits_open_file (&SEC_ptr, SEC_file_path, READONLY, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: Could not open file: %s\n",
SEC_file_path);
}
}
DPP_ptr = create_FITSimage_opened (output_path, 1);
/* Copy the header info from the grism image */
{
FITScards *cards;
if (bckmode && opt_extr)
cards = get_FITS_cards_opened (SEC_ptr);
else
cards = get_FITS_cards_opened (PET_ptr);
put_FITS_cards_opened(DPP_ptr,cards);
free_FITScards(cards);
}
i = 0;
if (oblist!=NULL)
{
while (1)
{
/* Get the PET for this object */
pri_PET = get_ALL_from_next_in_PET(PET_ptr, &aperID, &beamID);
if ((aperID==-1) && (beamID==-1)) break;
if (bckmode && opt_extr)
sec_PET = get_ALL_from_next_in_PET(SEC_ptr, &aperID, &beamID);
else
sec_PET = NULL;
if (beamID >= 0 && beamID <= DRZMAX){
// if (beamID == 0){
fprintf (stdout, "aXe_DRZPREP: BEAM_%d%c.", aperID, BEAM(beamID));
objindex = find_object_in_object_list(oblist,aperID);
sprintf (label, "%s.%d%c.ps/CPS", outputroot_path,
oblist[objindex]->ID, BEAM (oblist[objindex]->beams[beamID].ID));
pixel.x = oblist[objindex]->beams[beamID].refpoint.x - conf->refx;
pixel.y = oblist[objindex]->beams[beamID].refpoint.y - conf->refy;
disp = get_dispstruct_at_pos(conf_file_path, 1,
oblist[objindex]->beams[beamID].ID,pixel);
trace = oblist[objindex]->beams[beamID].spec_trace;
outref = get_mean_refpoint(allobjects, nobjects2, oblist[objindex]->ID,
&boxwidth, &boxheight, &relx, &rely, &objwidth,
&orient, &cdref, &cdscale, &cdmeanscale,
&sprefreso, &spreso, &spmeanreso, &trlength);
minxy_PET = get_minxy_from_PET(pri_PET);
relx = oblist[objindex]->beams[beamID].refpoint.x - minxy_PET.x;
rely = oblist[objindex]->beams[beamID].refpoint.y - minxy_PET.y;
//*************************************************
// patch to correct the reference point in case
// that the the trace descritpion
// does have a non negligeable first order term!
gaga = oblist[objindex]->beams[beamID].spec_trace->data;
rely = rely + gaga[1];
//**************************************************
outdisp = get_dispstruct_at_pos(conf_file_path, 1,
oblist[objindex]->beams[beamID].ID,outref);
cdcorr = cdscale / cdref;
spcorr = spreso / sprefreso;
// determine the trace length
// NOTE: putting in this line is wrong, but opens to make
// drizzle results as in aXe-1.7
//trlength = get_beam_trace_length(oblist[objindex]->beams[beamID]);
drizzcoeffs = get_drizzle_coeffs( disp, trace, boxwidth, boxheight,
trlength, relx, rely, conf, orient,
outdisp, cdcorr, sprefreso, spmeanreso);
drizzle_width = cdcorr * get_drizzle_width(oblist[objindex],beamID,trace);
objwidth = cdmeanscale / cdref * objwidth;
refwave_pos = get_refwave_position( disp, trace, pixel, conf);
refwave_pos.x = refwave_pos.x - minxy_PET.x;
refwave_pos.y = refwave_pos.y - minxy_PET.y;
trlength = gsl_matrix_get(drizzcoeffs, 0,10);
dimension = get_drzprep_dim(pri_PET, oblist[objindex]->beams[beamID].width,
boxwidth, boxheight);
{
px_point tmp_in;
px_point tmp_out;
d_point new_pos;
tmp_in.x = dimension.xsize;
tmp_in.y = dimension.ysize;
tmp_out.x = (int)trlength;
tmp_out.y = 2*(int)ceil(objwidth) + 10;
// gsl_matrix_fprintf (stdout, drizzcoeffs, "%f");
gsl_matrix_set(drizzcoeffs, 0,10,0.0);
new_pos = get_drz_position_free(refwave_pos, drizzcoeffs, tmp_in, tmp_out);
}
drzprep_stamps = stamp_img_drzprep(opt_extr, pri_PET, sec_PET,
oblist[objindex]->beams[beamID].width,
-1000000.0, quant_cont, dimension,
drizzcoeffs, exptime, sky_cps,
(double)conf->rdnoise, bckmode);
// store the count-extension
sprintf (label, "BEAM_%d%c",oblist[objindex]->ID,
BEAM (oblist[objindex]->beams[beamID].ID));
gsl_to_FITSimage_opened (drzprep_stamps->counts, DPP_ptr ,0,label);
cards = drzinfo_to_FITScards(oblist[objindex],beamID,
outref, conf, drizzcoeffs,
trlength, relx, rely,objwidth,
refwave_pos, sky_cps,
drizzle_width, cdref, spcorr);
put_FITS_cards_opened(DPP_ptr,cards);
// store the error-extension
sprintf (label, "ERR_%d%c",oblist[objindex]->ID,
BEAM (oblist[objindex]->beams[beamID].ID));
gsl_to_FITSimage_opened (drzprep_stamps->error, DPP_ptr ,0,label);
put_FITS_cards_opened(DPP_ptr,cards);
// store the contamination-extension
sprintf (label, "CONT_%d%c",oblist[objindex]->ID,
BEAM (oblist[objindex]->beams[beamID].ID));
gsl_to_FITSimage_opened (drzprep_stamps->cont, DPP_ptr ,0,label);
put_FITS_cards_opened(DPP_ptr,cards);
// if (opt_extr)
if (drzprep_stamps->model)
{
// store the model-extension
sprintf (label, "MOD_%d%c",oblist[objindex]->ID,
BEAM (oblist[objindex]->beams[beamID].ID));
gsl_to_FITSimage_opened (drzprep_stamps->model, DPP_ptr ,0,label);
put_FITS_cards_opened(DPP_ptr,cards);
}
if (drzprep_stamps->vari)
{
// store the variance extension
sprintf (label, "VAR_%d%c",oblist[objindex]->ID,
BEAM (oblist[objindex]->beams[beamID].ID));
gsl_to_FITSimage_opened (drzprep_stamps->vari, DPP_ptr ,0,label);
put_FITS_cards_opened(DPP_ptr,cards);
}
// release memory
free_drzprep(drzprep_stamps);
free_FITScards(cards);
free_dispstruct(disp);
free_dispstruct(outdisp);
gsl_matrix_free(drizzcoeffs);
fprintf (stdout, " Done.\n");
i++;
}
if (pri_PET!=NULL) free(pri_PET);
if (sec_PET!=NULL) free(sec_PET);
}
}
if (oblist!=NULL) free_oblist (oblist);
fits_close_file (DPP_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: Could not" " close DPP file: %s\n", output_path);
}
fits_close_file (PET_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: Could not" " close PET file: %s\n", PET_file_path);
}
if (bckmode && opt_extr)
{
fits_close_file (SEC_ptr, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"aXe_DRZPREP: Could not" " close PET file: %s\n", SEC_file_path);
}
}
fprintf (stdout, "aXe_DRZPREP: %s Done...\n\n", output_path);
//
// End of working on one image
//
//
//
}
free_axe_inputs(input_list);
free_objectobs(allobjects);
exit (0);
}
| {
"alphanum_fraction": 0.6588686832,
"avg_line_length": 31.6271676301,
"ext": "c",
"hexsha": "51dda34d596eb7ac1df96eb8a4431cc7a16deb51",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/aXe_DRZPREP.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/aXe_DRZPREP.c",
"max_line_length": 104,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/aXe_DRZPREP.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6456,
"size": 21886
} |
#pragma once
#include <string>
#include <gsl/gsl_complex.h>
#include "Expression.h"
#include "UnitConversionExpression/Units.h"
class BaseUnitExpression: public Expression {
UnitType type;
std::string abbr;
double val;
BaseUnitExpression(const std::string& unit, double val);
BaseUnitExpression(UnitType type, const std::string& unit, double val);
public:
static expression construct(const std::string& unit, double val = 1);
static expression construct(UnitType type, const std::string& unit, double val);
std::string repr() const override;
int id() const override;
EXPRESSION_OVERRIDES
friend expression operator*(const BaseUnitExpression& unit1, const BaseUnitExpression& unit2);
friend expression operator*(const BaseUnitExpression& unit1, const expression expr);
friend expression operator/(const BaseUnitExpression& unit1, const BaseUnitExpression& unit2);
friend expression operator/(const BaseUnitExpression& unit1, const expression expr);
friend expression operator^(const BaseUnitExpression& unit1, const expression expr);
friend expression convert(const BaseUnitExpression& from, const BaseUnitExpression& to);
};
class ConvertedUnitExpression: public Expression {
UnitType type;
std::string abbr;
double val;
ConvertedUnitExpression(UnitType type, const std::string& unit, double val);
public:
static expression construct(UnitType type, const std::string& unit, double val);
std::string repr() const override;
int id() const override;
EXPRESSION_OVERRIDES
};
| {
"alphanum_fraction": 0.7167070218,
"avg_line_length": 31.1698113208,
"ext": "h",
"hexsha": "c5950c56fe153962ba975f2f4bb589a8f88118c7",
"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/UnitExpression.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/UnitExpression.h",
"max_line_length": 102,
"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/UnitExpression.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 346,
"size": 1652
} |
#ifndef PARALLEL_PROCESSING_H_2FVRLMCH
#define PARALLEL_PROCESSING_H_2FVRLMCH
#include <chrono>
#include <gsl/gsl>
#include <iomanip>
#include <ios>
#include <iostream>
#include <sens_loc/util/console.h>
#include <sens_loc/util/progress_bar_observer.h>
#include <taskflow/taskflow.hpp>
#include <type_traits>
namespace sens_loc::apps {
/// Helper function that processes a range of files based on index.
/// The boolean function \c f is applied to each function. Error handling
/// and reporting is done if \c f returns \c false.
///
/// \tparam BoolFunction Apply this functor for each index.
/// \param start,end inclusive range of integers for the files
/// \param f functor that is applied for each index
template <typename BoolFunction>
bool parallel_indexed_file_processing(int start,
int end,
BoolFunction f) noexcept {
static_assert(std::is_nothrow_invocable_r_v<bool, BoolFunction, int>,
"Functor needs to be noexcept callable and return bool!");
try {
if (start > end)
std::swap(start, end);
int total_tasks = end - start + 1;
tf::Executor executor;
executor.make_observer<util::progress_bar_observer>(total_tasks);
tf::Taskflow tf;
bool batch_success = true;
int fails = 0;
tf.parallel_for(
start, end + 1, 1, [&batch_success, &fails, &f](int idx) {
const bool success = f(idx);
if (!success) {
auto s = synced();
fails++;
std::cerr << util::err{};
std::cerr << "Could not process index \""
<< rang::style::bold << idx << "\""
<< rang::style::reset << "!" << std::endl;
batch_success = false;
}
});
const auto before = std::chrono::steady_clock::now();
executor.run(tf).wait();
const auto after = std::chrono::steady_clock::now();
const auto dur_deci_seconds =
std::chrono::duration_cast<std::chrono::duration<long, std::centi>>(
after - before);
std::cout << std::endl;
Ensures(fails >= 0);
using namespace std::chrono;
{
auto s = synced();
std::cerr << util::info{};
std::cerr << "Processing " << rang::style::bold
<< std::abs(end - start) + 1 - fails << rang::style::reset
<< " images took " << rang::style::bold << std::fixed
<< std::setprecision(2)
<< (dur_deci_seconds.count() / 100.) << rang::style::reset
<< " seconds!\n";
}
if (fails > 0) {
auto s = synced();
std::cerr << util::warn{} << "Encountered " << rang::style::bold
<< fails << rang::style::reset << " problematic files!\n";
}
return batch_success;
} catch (...) {
auto s = synced();
std::cerr << util::err{} << "System error in batch processing!\n";
return false;
}
}
} // namespace sens_loc::apps
#endif /* end of include guard: PARALLEL_PROCESSING_H_2FVRLMCH */
| {
"alphanum_fraction": 0.530941704,
"avg_line_length": 34.84375,
"ext": "h",
"hexsha": "9d1a7f542a87b07250ad71359b9b0d5bacacfabc",
"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": "5c8338276565d846c07673e83f94f6841006872b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "JonasToth/depth-conversions",
"max_forks_repo_path": "src/apps/util/parallel_processing.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"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": "JonasToth/depth-conversions",
"max_issues_repo_path": "src/apps/util/parallel_processing.h",
"max_line_length": 80,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "JonasToth/depth-conversions",
"max_stars_repo_path": "src/apps/util/parallel_processing.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z",
"num_tokens": 743,
"size": 3345
} |
/*
Copyright [2017-2019] [IBM Corporation]
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 __MCAS_CLIENT_HANDLER_H__
#define __MCAS_CLIENT_HANDLER_H__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Weffc++"
#include "fabric_transport.h"
#include "mcas_client_config.h"
#include "protocol.h"
#include "protocol_ostream.h"
#include <api/fabric_itf.h>
#include <api/mcas_itf.h>
#include <common/exceptions.h>
#include <common/utils.h>
#include <common/byte_buffer.h>
#include <common/string_view.h>
#include <gsl/pointers>
#include <sys/mman.h>
#include <sys/uio.h>
#include <unistd.h>
#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <gnutls/crypto.h>
#include <boost/numeric/conversion/cast.hpp>
#include <map>
#include <set>
#include <tuple>
/* Enable this to introduce locks to prevent re-entry by multiple
threads. The client is not re-entrant because of the state machine
and multi-packet operations
*/
#define THREAD_SAFE_CLIENT
#define CAFILE "/etc/ssl/certs/ca-bundle.trust.crt"
#ifdef THREAD_SAFE_CLIENT
#define API_LOCK() std::lock_guard<std::mutex> g(_api_lock);
#else
#define API_LOCK()
#endif
namespace mcas
{
namespace client
{
struct TLS_transport
{
static unsigned debug_level();
static ssize_t gnutls_pull_func(gnutls_transport_ptr_t, void*, size_t);
static ssize_t gnutls_vec_push_func(gnutls_transport_ptr_t, const giovec_t * , int );
static int gnutls_pull_timeout_func(gnutls_transport_ptr_t, unsigned int);
};
struct async_buffer_set_t;
struct iob_free;
static const char *env_scbe = ::getenv("SHORT_CIRCUIT_BACKEND");
/* Adaptor point for other transports */
using Connection_base = mcas::client::Fabric_transport;
/**
* Client side connection handler
*
*/
class Connection_handler : public Connection_base {
using iob_ptr = std::unique_ptr<client::Fabric_transport::buffer_t, iob_free>;
using locate_element = protocol::Message_IO_response::locate_element;
public:
friend struct TLS_transport;
using memory_region_t = typename Transport::memory_region_t;
template <typename T>
using basic_string_view = common::basic_string_view<T>;
using byte = common::byte;
/**
* Constructor
*
* @param debug_level
* @param connection
* @param patience Time to wait (in seconds) for single fabric post to complete
* @param other Additional configuration string
*
* @return
*/
Connection_handler(const unsigned debug_level,
Connection_base::Transport *connection,
const unsigned patience,
const std::string other);
~Connection_handler();
private:
enum State {
INITIALIZE,
HANDSHAKE_SEND,
HANDSHAKE_GET_RESPONSE,
SHUTDOWN,
STOPPED,
READY,
};
State _state = State::INITIALIZE;
template <typename MT>
status_t invoke_ado_common(
const iob_ptr & iobs
, const MT *msg
, std::vector<component::IMCAS::ADO_response>& out_response
, unsigned int flags
);
public:
using pool_t = uint64_t;
void bootstrap()
{
set_state(INITIALIZE);
while (tick() > 0)
;
}
void shutdown()
{
set_state(SHUTDOWN);
while (tick() > 0) sleep(1);
}
pool_t open_pool(const std::string name,
const unsigned int flags,
const addr_t base);
pool_t create_pool(const std::string name,
const size_t size,
const unsigned int flags,
const uint64_t expected_obj_count,
const addr_t base);
status_t close_pool(const pool_t pool);
status_t delete_pool(const std::string &name);
status_t delete_pool(const pool_t pool);
status_t configure_pool(const component::IKVStore::pool_t pool, const std::string &json);
status_t put(const pool_t pool,
const std::string key,
const void * value,
const size_t value_len,
const unsigned int flags);
status_t put(const pool_t pool,
const void * key,
const size_t key_len,
const void * value,
const size_t value_len,
const unsigned int flags);
status_t put_direct(pool_t pool,
const void * key,
size_t key_len,
const void * value,
size_t value_len,
component::Registrar_memory_direct * rmd,
component::IKVStore::memory_handle_t handle,
unsigned int flags);
status_t async_put(const pool_t pool,
const void * key,
const size_t key_len,
const void * value,
size_t value_len,
component::IMCAS::async_handle_t &out_handle,
unsigned int flags);
status_t async_put_direct(const component::IMCAS::pool_t pool,
const void * key,
size_t key_len,
const void * value,
size_t value_len,
component::IMCAS::async_handle_t & out_handle,
component::Registrar_memory_direct * rmd,
component::IKVStore::memory_handle_t handle = component::IMCAS::MEMORY_HANDLE_NONE,
unsigned int flags = component::IMCAS::FLAGS_NONE);
status_t async_get_direct(const component::IMCAS::pool_t pool,
const void * key,
size_t key_len,
void * value,
size_t & value_len,
component::IMCAS::async_handle_t & out_handle,
component::Registrar_memory_direct * rmd,
component::IKVStore::memory_handle_t handle = component::IMCAS::MEMORY_HANDLE_NONE,
unsigned int flags = component::IMCAS::FLAGS_NONE);
status_t check_async_completion(component::IMCAS::async_handle_t &handle);
status_t get(const pool_t pool, const std::string &key, std::string &value);
status_t get(const pool_t pool, const std::string &key, void *&value, size_t &value_len);
status_t get_direct(const pool_t pool,
const void * key,
size_t key_len,
void * value,
size_t & out_value_len,
component::Registrar_memory_direct * rmd,
component::IKVStore::memory_handle_t handle = component::IKVStore::HANDLE_NONE);
status_t get_direct_offset(pool_t pool,
std::size_t offset,
std::size_t & length,
void * buffer,
component::Registrar_memory_direct *rmd,
component::IMCAS::memory_handle_t handle);
status_t async_get_direct_offset(pool_t pool,
std::size_t offset,
std::size_t & length,
void * buffer,
component::IMCAS::async_handle_t & out_handle,
component::Registrar_memory_direct *rmd,
component::IMCAS::memory_handle_t handle);
status_t put_direct_offset(pool_t pool,
std::size_t offset,
std::size_t & length,
const void * buffer,
component::Registrar_memory_direct *rmd,
component::IMCAS::memory_handle_t handle);
status_t async_put_direct_offset(pool_t pool,
std::size_t offset,
std::size_t & length,
const void * buffer,
component::IMCAS::async_handle_t & out_handle,
component::Registrar_memory_direct *rmd,
component::IMCAS::memory_handle_t handle);
status_t erase(const pool_t pool, const std::string &key);
status_t async_erase(const component::IMCAS::pool_t pool,
const std::string & key,
component::IMCAS::async_handle_t &out_handle);
uint64_t key_hash(const void *key, const size_t key_len);
uint64_t auth_id() const
{
/* temporary */
auto env = getenv("MCAS_AUTH_ID");
uint64_t auth_id;
if (env) {
auto id = std::strtoll(env, nullptr, 10);
auth_id = boost::numeric_cast<uint64_t>(id);
}
else {
auth_id = boost::numeric_cast<uint64_t>(getuid());
}
return auth_id;
}
size_t count(const pool_t pool);
status_t get_attribute(const component::IKVStore::pool_t pool,
const component::IKVStore::Attribute attr,
std::vector<uint64_t> & out_attr,
const std::string * key);
status_t get_statistics(component::IMCAS::Shard_stats &out_stats);
status_t find(const component::IKVStore::pool_t pool,
const std::string & key_expression,
const offset_t offset,
offset_t & out_matched_offset,
std::string & out_matched_key);
status_t invoke_ado(const component::IMCAS::pool_t pool,
basic_string_view<byte> key,
basic_string_view<byte> request,
const unsigned int flags,
std::vector<component::IMCAS::ADO_response> &out_response,
const size_t value_size);
status_t invoke_ado_async(const component::IMCAS::pool_t pool,
basic_string_view<byte> key,
basic_string_view<byte> request,
const component::IMCAS::ado_flags_t flags,
std::vector<component::IMCAS::ADO_response> &out_response,
component::IMCAS::async_handle_t & out_async_handle,
const size_t value_size);
status_t invoke_put_ado(const component::IMCAS::pool_t pool,
basic_string_view<byte> key,
basic_string_view<byte> request,
basic_string_view<byte> value,
size_t root_len,
const unsigned int flags,
std::vector<component::IMCAS::ADO_response> &out_response);
status_t invoke_put_ado_async(const component::IMCAS::pool_t pool,
const basic_string_view<byte> key,
const basic_string_view<byte> request,
const basic_string_view<byte> value,
const size_t root_len,
const component::IMCAS::ado_flags_t flags,
std::vector<component::IMCAS::ADO_response>& out_response,
component::IMCAS::async_handle_t& out_async_handle);
bool check_message_size(size_t size) const { return size > _max_message_size; }
status_t receive_and_process_ado_response(
const iob_ptr & iobr
, std::vector<component::IMCAS::ADO_response> & out_response
);
private:
/**
* FSM tick call
*
*/
int tick();
/**
* FSM state change
*
* @param s State to change to
*/
inline void set_state(State s)
{
if (2 < debug_level()) {
static const std::map<State, const char *> m{
{INITIALIZE, "INITIALIZE"},
{HANDSHAKE_SEND, "HANDSHAKE_SEND"},
{HANDSHAKE_GET_RESPONSE, "HANDSHAKE_GET_RESPONSE"},
{SHUTDOWN, "SHUTDOWN"},
{STOPPED, "STOPPED"},
{READY, "READY"},
};
PLOG("Client state %s -> %s", m.find(_state)->second, m.find(s)->second);
}
_state = s;
} /* we could add transition checking later */
void start_tls();
template <typename MT>
void msg_send_log(const MT *m, const void *context, const char *desc) { msg_send_log(1, m, context, desc); }
template <typename MT>
void msg_send_log(const unsigned level, const MT *msg, const void *context, const char *desc)
{
msg_log(level, msg, context, desc, "SEND");
}
template <typename MT>
void msg_log(const unsigned level_, const MT *msg_, const void *context_, const char *desc_, const char *direction_)
{
if ( level_ < debug_level() )
{
std::ostringstream m;
m << *msg_;
PLOG("%s (%p) (%s) %s", direction_, context_, desc_, m.str().c_str());
}
}
template <typename MT>
void msg_recv_log(const MT *m, const void *context, const char *desc) { msg_recv_log(1, m, context, desc); }
template <typename MT>
void msg_recv_log(const unsigned level, const MT *msg, const void *context, const char *desc)
{
msg_log(level, msg, context, desc, "RECV");
}
public:
template <typename MT>
gsl::not_null<const MT *>msg_recv(const buffer_t *iob, const char *desc)
{
/*
* First, cast the response buffer to Message (checking version).
* Second, cast the Message to a specific message type (checking message type).
*/
const auto *const msg = mcas::protocol::message_cast(iob->base());
const auto *const response_msg = msg->ptr_cast<MT>();
msg_recv_log(response_msg, iob, desc);
return response_msg;
}
template <typename MT>
void sync_inject_send(buffer_t *iob, const MT *msg, std::size_t size, const char *desc)
{
msg_send_log(msg, iob, desc);
Connection_base::sync_inject_send(iob, size);
}
template <typename MT>
void sync_inject_send(buffer_t *iob, const MT *msg, const char *desc)
{
sync_inject_send(iob, msg, msg->msg_len(), desc);
}
template <typename MT>
void sync_send(buffer_t *iob, const MT *msg, const char *desc)
{
msg_send_log(msg, iob, desc);
Connection_base::sync_send(iob);
}
void sync_inject_send(buffer_t *iob, std::size_t size)
{
Connection_base::sync_inject_send(iob, size);
}
private:
/* unused */
#if 0
void post_send(buffer_t *iob, const protocol::Message_IO_request *msg, buffer_external *iob_extra, const char *desc)
{
msg_send_log(msg, iob, desc);
Connection_base::post_send(iob, iob_extra);
}
#endif
template <typename MT>
void post_send(buffer_t *iob, const MT *msg, const char *desc)
{
msg_send_log(2, msg, iob, desc);
Connection_base::post_send(iob);
}
template <typename MT>
void post_send(const ::iovec *first, const ::iovec *last, void **descriptors, void *context, const MT *msg, const char *desc)
{
msg_send_log(msg, context, desc);
Connection_base::post_send(first, last, descriptors, context);
}
/**
* Put used when the value exceeds the size of the basic
* IO buffer (e.g., 2MB). This version of put will perform
* a two-stage exchange, advance notice and then value
*
* @param pool Pool identifier
* @param key Key
* @param key_len Key length
* @param value_len Value length
* @param flags ignored?
*
* @return
*/
std::tuple<uint64_t, uint64_t> put_locate(const pool_t pool,
const void * key,
const size_t key_len,
const size_t value_len,
const unsigned flags);
component::IMCAS::async_handle_t put_locate_async(pool_t pool,
const void * key,
size_t key_len,
const void * value,
size_t value_len,
component::Registrar_memory_direct *rmd,
void * desc,
unsigned flags);
std::tuple<uint64_t, uint64_t, std::size_t> get_locate(const pool_t pool,
const void * key,
const size_t key_len,
const unsigned flags);
component::IMCAS::async_handle_t get_locate_async(pool_t pool,
const void * key,
size_t key_len,
void * value,
size_t & value_len,
component::Registrar_memory_direct *rmd,
void * desc,
unsigned flags);
public:
iob_ptr make_iob_ptr(buffer_t::completion_t);
iob_ptr make_iob_ptr_recv();
iob_ptr make_iob_ptr_send();
iob_ptr make_iob_ptr_write();
iob_ptr make_iob_ptr_read();
private:
static void send_complete(void *, buffer_t *iob);
static void recv_complete(void *, buffer_t *iob);
static void write_complete(void *, buffer_t *iob);
static void read_complete(void *, buffer_t *iob);
std::tuple<uint64_t, std::vector<locate_element>> locate(pool_t pool, std::size_t offset, std::size_t size);
component::IMCAS::async_handle_t get_direct_offset_async(pool_t pool,
std::size_t offset,
void * buffer,
std::size_t & length,
component::Registrar_memory_direct *rmd,
void * desc);
component::IMCAS::async_handle_t put_direct_offset_async(pool_t pool,
std::size_t offset,
const void * buffer,
std::size_t & length,
component::Registrar_memory_direct *rmd,
void * desc);
private:
#ifdef THREAD_SAFE_CLIENT
std::mutex _api_lock;
#endif
bool _exit;
uint64_t _request_id;
public: /* for async "move_along" processing */
uint64_t request_id() { return ++_request_id; }
private:
size_t _max_message_size;
size_t _max_inject_size;
struct options_s {
bool short_circuit_backend;
unsigned tls : 1;
unsigned hmac : 1;
options_s()
: short_circuit_backend(env_scbe && env_scbe[0] == '1'), tls(0), hmac(0)
{}
};
options_s _options;
gnutls_certificate_credentials_t _xcred;
gnutls_priority_t _priority;
gnutls_session_t _session;
common::Byte_buffer _tls_buffer;
};
} // namespace client
} // namespace mcas
#pragma GCC diagnostic pop
#endif
| {
"alphanum_fraction": 0.4973570611,
"avg_line_length": 39.6195462478,
"ext": "h",
"hexsha": "d61e8b9c533109c8048140dd927848cdfe973f8e",
"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": "a6af06bc278993fb3ffe780f230d2396b2287c26",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "moshik1/mcas",
"max_forks_repo_path": "src/components/client/mcas-client/src/connection.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26",
"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": "moshik1/mcas",
"max_issues_repo_path": "src/components/client/mcas-client/src/connection.h",
"max_line_length": 127,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a6af06bc278993fb3ffe780f230d2396b2287c26",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "moshik1/mcas",
"max_stars_repo_path": "src/components/client/mcas-client/src/connection.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4285,
"size": 22702
} |
//===--- Sudoku/precompiled_basic.h ---===//
//
// Lists the standard system includes consumed by this library,
// or project specific include files that are used frequently, but
// are changed infrequently.
//
// - To be used as part of a precompiled header configuration for a project
// consuming this library.
// - Where frequent changes to the Sudoku library code are expected.
// - Not required when the library itself is added to a precompiled header.
//
//===----------------------------------------------------------------------===//
#pragma once
// STL containers
#include <array>
#include <bitset>
#include <vector>
// STL
#include <algorithm>
#include <iterator>
#include <limits>
#include <memory>
#include <stdexcept>
#include <utility>
// Libraries
#include <gsl/gsl>
| {
"alphanum_fraction": 0.6221142163,
"avg_line_length": 28.3793103448,
"ext": "h",
"hexsha": "6e1b4bac5b35812523cc2750435b1fe7a2a40118",
"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": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "FeodorFitsner/fwkSudoku",
"max_forks_repo_path": "Sudoku/Sudoku/precompiled_basic.h",
"max_issues_count": 38,
"max_issues_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"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": "FeodorFitsner/fwkSudoku",
"max_issues_repo_path": "Sudoku/Sudoku/precompiled_basic.h",
"max_line_length": 80,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "760aa5731efe089dc08e51898a37d42f3db5bb10",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "FeodorFitsner/fwkSudoku",
"max_stars_repo_path": "Sudoku/Sudoku/precompiled_basic.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": 156,
"size": 823
} |
/* ieee-utils/fp-unknown.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_errno.h>
int
gsl_ieee_set_mode (int precision, int rounding, int exception_mask)
{
GSL_ERROR (
"the IEEE interface for this platform is unsupported or could not be "
"determined at configure time\n", GSL_EUNSUP) ;
}
| {
"alphanum_fraction": 0.741252302,
"avg_line_length": 35.0322580645,
"ext": "c",
"hexsha": "6e4ac96aa75ba5df7a63fe7ee56ef38260b77d7a",
"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/ieee-utils/fp-unknown.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/ieee-utils/fp-unknown.c",
"max_line_length": 72,
"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/ieee-utils/fp-unknown.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": 277,
"size": 1086
} |
#ifndef EXECUTION_HANDLER_INCLUDE
#define EXECUTION_HANDLER_INCLUDE
#include <map>
#include <gsl/gsl>
#include "executionContent.h"
namespace execHelper {
namespace test {
namespace baseUtils {
class ExecutionHandler {
public:
void add(const std::string& key, ExecutionContent&& content) noexcept;
const ExecutionContent& at(const std::string& key) const noexcept;
private:
using ExecutionContentCollection = std::map<std::string, ExecutionContent>;
/**
* \brief Used for handling an execution iteration
*/
class ExecutionHandlerIterationRAII {
public:
explicit ExecutionHandlerIterationRAII(
gsl::not_null<ExecutionContentCollection*> outputs);
~ExecutionHandlerIterationRAII();
ExecutionHandlerIterationRAII(
const ExecutionHandlerIterationRAII& other) = default;
ExecutionHandlerIterationRAII(ExecutionHandlerIterationRAII&& other) =
default;
ExecutionHandlerIterationRAII&
operator=(const ExecutionHandlerIterationRAII& other) = default;
ExecutionHandlerIterationRAII&
operator=(ExecutionHandlerIterationRAII&& other) noexcept =
default; // NOLINT(misc-noexcept-move-constructor)
const ExecutionContent& at(const std::string& key) const noexcept;
private:
gsl::not_null<ExecutionContentCollection*> m_outputs;
};
ExecutionContentCollection m_outputs;
public:
ExecutionHandlerIterationRAII startIteration() noexcept;
};
} // namespace baseUtils
} // namespace test
} // namespace execHelper
#endif /* EXECUTION_HANDLER_INCLUDE */
| {
"alphanum_fraction": 0.7196090409,
"avg_line_length": 28.224137931,
"ext": "h",
"hexsha": "d5a1b09da561ffdfad0621d18b7f00aaa35bd5b2",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-07-03T11:11:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-07-03T11:11:19.000Z",
"max_forks_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "exec-helper/source",
"max_forks_repo_path": "test/base-utils/include/base-utils/executionHandler.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"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": "exec-helper/source",
"max_issues_repo_path": "test/base-utils/include/base-utils/executionHandler.h",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8869989a59b352f340406ae8859958bf343be776",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "exec-helper/source",
"max_stars_repo_path": "test/base-utils/include/base-utils/executionHandler.h",
"max_stars_repo_stars_event_max_datetime": "2020-01-28T13:24:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-01-28T13:24:30.000Z",
"num_tokens": 330,
"size": 1637
} |
/* integration/romberg.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.
*/
/* the code in this module performs Romberg integration */
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#define ROMBERG_PRINT_ROW(i, r) \
do { \
size_t jj; \
fprintf(stderr, "R[%zu] = ", i); \
for (jj = 0; jj <= i; ++jj) \
fprintf(stderr, "%.8e ", r[jj]); \
fprintf(stderr, "\n"); \
} while (0)
gsl_integration_romberg_workspace *
gsl_integration_romberg_alloc(const size_t n)
{
gsl_integration_romberg_workspace *w;
/* check inputs */
if (n < 1)
{
GSL_ERROR_VAL ("workspace size n must be at least 1", GSL_EDOM, 0);
}
w = calloc(1, sizeof(gsl_integration_romberg_workspace));
if (w == NULL)
{
GSL_ERROR_VAL ("unable to allocate workspace", GSL_ENOMEM, 0);
}
/* ceiling on n, since the number of points is 2^n + 1 */
w->n = GSL_MIN(n, 30);
w->work1 = malloc(w->n * sizeof(double));
if (w->work1 == NULL)
{
gsl_integration_romberg_free(w);
GSL_ERROR_VAL ("unable to allocate previous row", GSL_ENOMEM, 0);
}
w->work2 = malloc(w->n * sizeof(double));
if (w->work2 == NULL)
{
gsl_integration_romberg_free(w);
GSL_ERROR_VAL ("unable to allocate current row", GSL_ENOMEM, 0);
}
return w;
}
void
gsl_integration_romberg_free(gsl_integration_romberg_workspace * w)
{
if (w->work1)
free(w->work1);
if (w->work2)
free(w->work2);
free(w);
}
int
gsl_integration_romberg(const gsl_function * f, const double a, const double b,
const double epsabs, const double epsrel, double * result,
size_t * neval, gsl_integration_romberg_workspace * w)
{
if (epsabs < 0.0)
{
GSL_ERROR("epsabs must be non-negative", GSL_EDOM);
}
else if (epsrel < 0.0)
{
GSL_ERROR("epsrel must be non-negative", GSL_EDOM);
}
else
{
const size_t n = w->n;
double *Rp = &(w->work1[0]); /* previous row */
double *Rc = &(w->work2[0]); /* current row */
double *Rtmp;
double h = 0.5 * (b - a); /* step size */
size_t i;
/* R(0,0) */
Rp[0] = h * (GSL_FN_EVAL(f, a) + GSL_FN_EVAL(f, b));
*neval = 2;
/*ROMBERG_PRINT_ROW((size_t) 0, Rp);*/
for (i = 1; i < n; ++i)
{
size_t j;
double sum = 0.0;
double err;
double four_j; /* 4^j */
size_t two_i = 1 << i; /* 2^i */
for (j = 1; j < two_i; j += 2)
{
sum += GSL_FN_EVAL(f, a + j * h);
++(*neval);
}
/* R(i,0) */
Rc[0] = sum * h + 0.5 * Rp[0];
four_j = 4.0;
for (j = 1; j <= i; ++j)
{
Rc[j] = (four_j * Rc[j - 1] - Rp[j - 1]) / (four_j - 1.0);
four_j *= 4.0;
}
/*ROMBERG_PRINT_ROW(i, Rc);*/
/*
* compute difference between current and previous result and
* check for convergence
*/
err = fabs(Rc[i] - Rp[i - 1]);
if ((err < epsabs) || (err < epsrel * fabs(Rc[i])))
{
*result = Rc[i];
return GSL_SUCCESS;
}
/* swap Rp and Rc */
Rtmp = Rp;
Rp = Rc;
Rc = Rtmp;
h *= 0.5;
}
/* did not converge - return best guess */
*result = Rp[n - 1];
return GSL_EMAXITER;
}
}
| {
"alphanum_fraction": 0.5487347704,
"avg_line_length": 25.8666666667,
"ext": "c",
"hexsha": "581d087ef654d67751520abe6db8f403b41e5b32",
"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/integration/romberg.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/integration/romberg.c",
"max_line_length": 82,
"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/integration/romberg.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": 1222,
"size": 4268
} |
/*solver/integration.c
*
* Function for numerical integration
* using quadrature and Monte Carlo
* methods.
*
* Author: Benjamin Vatter.
* email: benjaminvatterj@gmail.com
* date: 15 August 2015
*/
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include "integration.h"
#include "dbg.h"
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_rng.h>
typedef struct {
int dims;
int depth;
double *lb;
double *ub;
double *real_x;
double epsabs;
double epsrel;
size_t limit;
gsl_integration_workspace * workspace;
double * abserr;
nquad_function *f;
} nquad_params;
void gsl_error (const char * reason, const char * file, int line, int gsl_errno)
{
gsl_stream_printf ("NQUAD ERROR", file, line, reason);
if (gsl_errno != GSL_EROUND) {
fflush (stderr);
fflush (stdout);
abort ();
} else {
log_warn("NQUAD ERROR: rounding error detected. This result might be unreliable.");
fflush (stderr);
return;
}
}
/*
SUbroutine for recursive multidimensional integration
*/
double nquad_f(double x, void * params)
{
nquad_params *in_pars = (nquad_params *) params;
double result;
double abserr;
int step = in_pars->depth;
// Add value
if (step>0) {
in_pars->real_x[step-1] = x;
}
if (in_pars->dims == in_pars->depth){
result = in_pars->f->function(in_pars->real_x, in_pars->dims, in_pars->f->params);
return result;
} else {
// Consistency
assert((step+1) <= in_pars->dims);
// increase depth
in_pars->depth += 1;
gsl_integration_workspace *w = gsl_integration_workspace_alloc(in_pars->limit);
gsl_function F = {.function = &nquad_f, .params = in_pars};
gsl_integration_qags(&F, in_pars->lb[step], in_pars->ub[step], in_pars->epsabs, in_pars->epsrel, in_pars->limit, w,&result, &abserr);
//gsl_integration_qag(&F, in_pars->lb[step], in_pars->ub[step], in_pars->epsabs, in_pars->epsrel, in_pars->limit, 2, w,&result, &abserr);
in_pars->abserr[step] = abserr;
gsl_integration_workspace_free(w);
in_pars->depth -= 1;
return result;
}
}
/*
An extension of gsl_integration_qags
to n dimensions. The first parameter is
the number or dimensions. the signature of
f must be
f(double *x, void * params)
Parameters:
n - dimensions
f - function and parameters
lb - lower bounds to integrals
ub - upper bounds to integrals
epsabs - desired absolute error in each integral (only in nested-quadrature)
epsrel - desired relative error in each integral (only in nested-quadrature)
limit - max number of iterations
result - on out contains result
abserr - on out contains estimated error
*/
void nquad(int n, nquad_function *f, double *lb, double *ub,
double epsabs, double epsrel, size_t limit, double * result, double *abserr)
{
assert(n>=1);
nquad_params *new_params = malloc(sizeof(nquad_params));
new_params->dims = n;
new_params->depth = 0;
new_params->lb = lb;
new_params->ub = ub;
new_params->epsabs = epsabs;
new_params->epsrel = epsrel;
new_params->limit = limit;
new_params->abserr = malloc(sizeof(double) * n);
new_params->f = f;
new_params->real_x = malloc(sizeof(double) * n);
// Set error handle
gsl_error_handler_t *old_handler = gsl_set_error_handler(&gsl_error);
// integrate
result[0] = nquad_f(0.0, new_params);
abserr[0] = 1.0;
int i;
double err = 0.0;
for (i = 0; i<n; i++){
err = (err < new_params->abserr[i])? new_params->abserr[i]: err;
}
*abserr = err;
// release real x
free(new_params->real_x);
free(new_params->abserr);
free(new_params);
// recover error handle
gsl_set_error_handler(old_handler);
}
/* Monte Carlo integration routine
* It has the same signature as the nquad function
* but it doesn't really use the epsrel value. It is
* done so to allow interchanging those two functions
* during runtime.
*
* This is based on the Monte Carlo plain routine found
* in GSL, written by Michael Booth
*/
void mcint(int n, nquad_function *f, double *lb, double *ub, double epsabs,
double epsrel, size_t limit, double *result, double *abserr)
{
double vol=1.0, m = 0, q = 0;
double *x = malloc(sizeof(double)*n);
size_t i, j;
const gsl_rng_type *T;
gsl_rng *r;
gsl_rng_env_setup ();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
/* Sanity check */
for(i=0; i<n; i++) {
if(lb[i] >= ub[i]) {
GSL_ERROR("Lower bound is higher than upper bound. Null feasible region.", GSL_EINVAL);
}
if(ub[i] - lb[i] > GSL_DBL_MAX) {
GSL_ERROR("Range of integration is too large, please rescale",
GSL_EINVAL);
}
vol *= ub[i] - lb[i];
}
j=0;
do
{
for (i=0; i < n; i++) {
x[i] = lb[i] + gsl_rng_uniform_pos(r) * (ub[i] - lb[i]);
}
double fval = (f->function)(x, n, f->params);
double d = fval - m;
m += d / (n + 1.0);
q += d * d * (n/(n +1.0));
if (j < 2){ *abserr = GSL_POSINF;}
else {
*abserr = vol * sqrt(q / (limit * (limit - 1.0)));
}
j++;
} while((*abserr > epsabs) && j < limit);
*result = vol * m;
if (*abserr > epsabs){
log_warn("Monte Carlo integration max evaluation %d was insufficient"
"to achieve the desired absolute error of %e", (int)limit, epsabs);
}
free(x);
gsl_rng_free (r);
}
| {
"alphanum_fraction": 0.6760617761,
"avg_line_length": 25.145631068,
"ext": "c",
"hexsha": "33b9c3174628f435eecf85663a579c41dd85de96",
"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": "0e38ce207ed835e7a3d49381966113809d394dc2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "benjaminvatterj/multidim_integration",
"max_forks_repo_path": "integration.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2",
"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": "benjaminvatterj/multidim_integration",
"max_issues_repo_path": "integration.c",
"max_line_length": 139,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0e38ce207ed835e7a3d49381966113809d394dc2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "benjaminvatterj/multidim_integration",
"max_stars_repo_path": "integration.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1553,
"size": 5180
} |
#include "GeneralFunctions.h"
#include <math.h>
#include <stdio.h>
#include <iostream>
#include <time.h>
//
#include <gsl/gsl_sf_exp.h>
#include <gsl/gsl_sf_log.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include "gsl/gsl_cdf.h"
#include "gsl/gsl_randist.h"
#include "gsl/gsl_rng.h"
int AcceleratedGibbs (int maxK,int bias, int N, int D, int K, char *C, int *R, double alpha, double s2B, double s2Y, gsl_matrix **Y, gsl_matrix *Z, int *nest, gsl_matrix *P, gsl_matrix *Pnon, gsl_matrix **lambda, gsl_matrix **lambdanon);
void SampleY (double missing, int N, int D, int K, char Cd, int Rd, double fd, double mud, double wd, double s2Y,double s2u, double s2theta, gsl_matrix *X, gsl_matrix *Z, gsl_matrix *Yd, gsl_matrix *Bd, gsl_vector *thetad, const gsl_rng *seed);
double Samples2Y (double missing, int N, int d, int K, char Cd, int Rd, double fd, double mud, double wd, double s2u, double s2theta, gsl_matrix *X, gsl_matrix *Z, gsl_matrix *Yd, gsl_matrix *Bd, gsl_vector *thetad, const gsl_rng *seed);
int IBPsampler_func (double missing, gsl_matrix *X, char *C, gsl_matrix *Z, gsl_matrix **B, gsl_vector **theta, int *R, double *f, double *mu, double *w, int maxR, int bias, int N, int D, int K, double alpha, double s2B, double *s2Y,double s2u, int maxK,int Nsim);
int initialize_func (int N, int D, int maxK, double missing, gsl_matrix *X, char *C, gsl_matrix **B, gsl_vector **theta, int *R, double *f, double *mu, double *w, double *s2Y); | {
"alphanum_fraction": 0.7206451613,
"avg_line_length": 70.4545454545,
"ext": "h",
"hexsha": "862df605f86a939bc39f2e8707b2690c7b2d6618",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-02-18T07:18:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-04T01:53:41.000Z",
"max_forks_repo_head_hexsha": "b219c650d0429ea71b953743730ae53cc122a61b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ferjorosa/test-glfm",
"max_forks_repo_path": "src/Ccode/wrapper_R/RcppGSLExample/src/InferenceFunctions.h",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "b219c650d0429ea71b953743730ae53cc122a61b",
"max_issues_repo_issues_event_max_datetime": "2019-10-11T01:54:01.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-18T13:22:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ferjorosa/test-glfm",
"max_issues_repo_path": "src/Ccode/wrapper_R/RcppGSLExample/src/InferenceFunctions.h",
"max_line_length": 265,
"max_stars_count": 45,
"max_stars_repo_head_hexsha": "b219c650d0429ea71b953743730ae53cc122a61b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ferjorosa/test-glfm",
"max_stars_repo_path": "src/Ccode/wrapper_R/RcppGSLExample/src/InferenceFunctions.h",
"max_stars_repo_stars_event_max_datetime": "2021-10-18T20:01:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-07T03:43:25.000Z",
"num_tokens": 516,
"size": 1550
} |
// BSD 3-Clause License
//
// Copyright (c) 2018, Gregory Meyer
// 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 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.
#ifndef SWEEP_UTIL_TYPES_H
#define SWEEP_UTIL_TYPES_H
#include <cstdint>
#include <gsl/gsl_util>
namespace sweep::util {
inline namespace types {
using u8 = std::uint8_t;
using u16 = std::uint16_t;
using u32 = std::uint32_t;
using u64 = std::uint64_t;
using i8 = std::int8_t;
using i16 = std::int16_t;
using i32 = std::int32_t;
using i64 = std::int64_t;
using usize = std::size_t;
using isize = std::ptrdiff_t;
using f32 = float;
using f64 = double;
inline namespace literals {
constexpr u8 operator""_u8(unsigned long long x) noexcept {
return gsl::narrow_cast<u8>(x);
}
constexpr u16 operator""_u16(unsigned long long x) noexcept {
return gsl::narrow_cast<u16>(x);
}
constexpr u32 operator""_u32(unsigned long long x) noexcept {
return gsl::narrow_cast<u32>(x);
}
constexpr u64 operator""_u64(unsigned long long x) noexcept {
return gsl::narrow_cast<u64>(x);
}
constexpr i8 operator""_i8(unsigned long long x) noexcept {
return gsl::narrow_cast<i8>(x);
}
constexpr i16 operator""_i16(unsigned long long x) noexcept {
return gsl::narrow_cast<i16>(x);
}
constexpr i32 operator""_i32(unsigned long long x) noexcept {
return gsl::narrow_cast<i32>(x);
}
constexpr i64 operator""_i64(unsigned long long x) noexcept {
return gsl::narrow_cast<i64>(x);
}
constexpr usize operator""_usize(unsigned long long x) noexcept {
return gsl::narrow_cast<usize>(x);
}
constexpr isize operator""_isize(unsigned long long x) noexcept {
return gsl::narrow_cast<isize>(x);
}
constexpr f32 operator""_f32(long double x) noexcept {
return gsl::narrow_cast<f32>(x);
}
constexpr f64 operator""_f64(long double x) noexcept {
return gsl::narrow_cast<f64>(x);
}
} // inline namespace literals
} // inline namespace types
} // namespace sweep::util
#endif
| {
"alphanum_fraction": 0.7391304348,
"avg_line_length": 29.3448275862,
"ext": "h",
"hexsha": "2e1d61fcd0c9af09d517a63b33339143eb140d1a",
"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": "396e9bc23d2fd836618f5f562b9e9fb361ca9f4d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Gregory-Meyer/minesweeper",
"max_forks_repo_path": "include/sweep/util/types.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "396e9bc23d2fd836618f5f562b9e9fb361ca9f4d",
"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": "Gregory-Meyer/minesweeper",
"max_issues_repo_path": "include/sweep/util/types.h",
"max_line_length": 71,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "396e9bc23d2fd836618f5f562b9e9fb361ca9f4d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Gregory-Meyer/minesweeper",
"max_stars_repo_path": "include/sweep/util/types.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 824,
"size": 3404
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#ifndef NOMPI
#include <mpi.h>
#endif
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include "allvars.h"
#include "proto.h"
/*! \file driftfac.c
* \brief compute loop-up tables for prefactors in cosmological integration
*/
static double logTimeBegin;
static double logTimeMax;
/*! This function computes look-up tables for factors needed in
* cosmological integrations. The (simple) integrations are carried out
* with the GSL library. Separate factors are computed for the "drift",
* and the gravitational and hydrodynamical "kicks". The lookup-table is
* used for reasons of speed.
*/
void init_drift_table(void)
{
#define WORKSIZE 100000
int i;
double result, abserr;
gsl_function F;
gsl_integration_workspace *workspace;
logTimeBegin = log(All.TimeBegin);
logTimeMax = log(All.TimeMax);
workspace = gsl_integration_workspace_alloc(WORKSIZE);
for(i = 0; i < DRIFT_TABLE_LENGTH; i++)
{
F.function = &drift_integ;
gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), 0,
1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);
DriftTable[i] = result;
F.function = &gravkick_integ;
gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), 0,
1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);
GravKickTable[i] = result;
F.function = &hydrokick_integ;
gsl_integration_qag(&F, exp(logTimeBegin), exp(logTimeBegin + ((logTimeMax - logTimeBegin) / DRIFT_TABLE_LENGTH) * (i + 1)), 0,
1.0e-8, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);
HydroKickTable[i] = result;
}
gsl_integration_workspace_free(workspace);
}
/*! This function integrates the cosmological prefactor for a drift step
* between time0 and time1. The value returned is * \f[ \int_{a_0}^{a_1}
* \frac{{\rm d}a}{H(a)} * \f]
*/
double get_drift_factor(int time0, int time1)
{
double a1, a2, df1, df2, u1, u2;
int i1, i2;
/* note: will only be called for cosmological integration */
a1 = logTimeBegin + time0 * All.Timebase_interval;
a2 = logTimeBegin + time1 * 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 * DriftTable[0];
else
df1 = DriftTable[i1 - 1] + (DriftTable[i1] - DriftTable[i1 - 1]) * (u1 - i1);
u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;
i2 = (int) u2;
if(i2 >= DRIFT_TABLE_LENGTH)
i2 = DRIFT_TABLE_LENGTH - 1;
if(i2 <= 1)
df2 = u2 * DriftTable[0];
else
df2 = DriftTable[i2 - 1] + (DriftTable[i2] - DriftTable[i2 - 1]) * (u2 - i2);
return df2 - df1;
}
/*! This function integrates the cosmological prefactor for a kick step of
* the gravitational force.
*/
double get_gravkick_factor(int time0, int time1)
{
double a1, a2, df1, df2, u1, u2;
int i1, i2;
/* note: will only be called for cosmological integration */
a1 = logTimeBegin + time0 * All.Timebase_interval;
a2 = logTimeBegin + time1 * 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);
u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;
i2 = (int) u2;
if(i2 >= DRIFT_TABLE_LENGTH)
i2 = DRIFT_TABLE_LENGTH - 1;
if(i2 <= 1)
df2 = u2 * GravKickTable[0];
else
df2 = GravKickTable[i2 - 1] + (GravKickTable[i2] - GravKickTable[i2 - 1]) * (u2 - i2);
return df2 - df1;
}
/*! This function integrates the cosmological prefactor for a kick step of
* the hydrodynamical force.
*/
double get_hydrokick_factor(int time0, int time1)
{
double a1, a2, df1, df2, u1, u2;
int i1, i2;
/* note: will only be called for cosmological integration */
a1 = logTimeBegin + time0 * All.Timebase_interval;
a2 = logTimeBegin + time1 * 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 * HydroKickTable[0];
else
df1 = HydroKickTable[i1 - 1] + (HydroKickTable[i1] - HydroKickTable[i1 - 1]) * (u1 - i1);
u2 = (a2 - logTimeBegin) / (logTimeMax - logTimeBegin) * DRIFT_TABLE_LENGTH;
i2 = (int) u2;
if(i2 >= DRIFT_TABLE_LENGTH)
i2 = DRIFT_TABLE_LENGTH - 1;
if(i2 <= 1)
df2 = u2 * HydroKickTable[0];
else
df2 = HydroKickTable[i2 - 1] + (HydroKickTable[i2] - HydroKickTable[i2 - 1]) * (u2 - i2);
return df2 - df1;
}
/*! Integration kernel for drift factor computation.
*/
double drift_integ(double a, void *param)
{
double h;
h = All.Omega0 / (a * a * a) + (1 - All.Omega0 - All.OmegaLambda) / (a * a) + All.OmegaLambda;
h = All.Hubble * sqrt(h);
return 1 / (h * a * a * a);
}
/*! Integration kernel for gravitational kick factor computation.
*/
double gravkick_integ(double a, void *param)
{
double h;
h = All.Omega0 / (a * a * a) + (1 - All.Omega0 - All.OmegaLambda) / (a * a) + All.OmegaLambda;
h = All.Hubble * sqrt(h);
return 1 / (h * a * a);
}
/*! Integration kernel for hydrodynamical kick factor computation.
*/
double hydrokick_integ(double a, void *param)
{
double h;
h = All.Omega0 / (a * a * a) + (1 - All.Omega0 - All.OmegaLambda) / (a * a) + All.OmegaLambda;
h = All.Hubble * sqrt(h);
return 1 / (h * pow(a, 3 * GAMMA_MINUS1) * a);
}
double growthfactor_integ(double a, void *param)
{
double s;
s = All.Omega0 + (1 - All.Omega0 - All.OmegaLambda) * a + All.OmegaLambda * a * a * a;
s = sqrt(s);
return pow(sqrt(a) / s, 3);
}
| {
"alphanum_fraction": 0.6564296272,
"avg_line_length": 26.8237885463,
"ext": "c",
"hexsha": "533cb797f87ba7ac8d7feadc1c0845fff839dc78",
"lang": "C",
"max_forks_count": 102,
"max_forks_repo_forks_event_max_datetime": "2022-02-09T13:29:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-22T10:00:29.000Z",
"max_forks_repo_head_hexsha": "3ac3b6b8f922643657279ddee5c8ab3fc0440d5e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "rieder/amuse",
"max_forks_repo_path": "src/amuse/community/gadget2/src/driftfac.c",
"max_issues_count": 690,
"max_issues_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T16:15:58.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-10-17T12:18:08.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "rknop/amuse",
"max_issues_repo_path": "src/amuse/community/gadget2/src/driftfac.c",
"max_line_length": 133,
"max_stars_count": 131,
"max_stars_repo_head_hexsha": "85d5bdcc29cfc87dc69d91c264101fafd6658aec",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "rknop/amuse",
"max_stars_repo_path": "src/amuse/community/gadget2/src/driftfac.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-01T12:11:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-06-04T09:06:57.000Z",
"num_tokens": 2052,
"size": 6089
} |
#ifndef SIGSCANNERMEMORYDATA_HHHHH
#define SIGSCANNERMEMORYDATA_HHHHH
#include <vector>
#include <gsl/span>
#include <string>
namespace MPSig {
class SigScannerMemoryData {
gsl::span<const char> m_refData;
public:
explicit SigScannerMemoryData(gsl::span<const char> data);
bool IsInRange(std::intptr_t addr) const;
char* Deref(std::intptr_t addrWithOffset) const;
std::pair<char*, bool> DerefTry(std::intptr_t addrWithOffset) const;
gsl::span<const char> Get() const;
std::intptr_t GetOffset() const;
};
}
#endif
| {
"alphanum_fraction": 0.6819727891,
"avg_line_length": 22.6153846154,
"ext": "h",
"hexsha": "ef846bc9b7561a6bd6b8adae976cca330e98b1be",
"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": "13f290ec593ddbeed3c59c7fba642c1704bfd529",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "KevinW1998/MultipassSigScanner",
"max_forks_repo_path": "src/SigScannerMemoryData.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529",
"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": "KevinW1998/MultipassSigScanner",
"max_issues_repo_path": "src/SigScannerMemoryData.h",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "KevinW1998/MultipassSigScanner",
"max_stars_repo_path": "src/SigScannerMemoryData.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 148,
"size": 588
} |
// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights
// reserved. See files LICENSE and NOTICE for details.
//
// This file is part of CEED, a collection of benchmarks, miniapps, software
// libraries and APIs for efficient high-order finite element and spectral
// element discretizations for exascale applications. For more information and
// source code availability see http://github.com/ceed.
//
// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,
// a collaborative effort of two U.S. Department of Energy organizations (Office
// of Science and the National Nuclear Security Administration) responsible for
// the planning and preparation of a capable exascale ecosystem, including
// software, applications, hardware, advanced system engineering and early
// testbed platforms, in support of the nation's exascale computing imperative.
#ifndef setup_h
#define setup_h
#include <ceed.h>
#include <petsc.h>
#include <petscdmplex.h>
#include <petscfe.h>
#include <petscksp.h>
#include <stdbool.h>
#include <string.h>
#if PETSC_VERSION_LT(3,14,0)
# define DMAddBoundary(a,b,c,d,e,f,g,h,i,j,k,l,m,n) DMAddBoundary(a,b,c,e,h,i,j,k,f,g,m)
#elif PETSC_VERSION_LT(3,16,0)
# define DMAddBoundary(a,b,c,d,e,f,g,h,i,j,k,l,m,n) DMAddBoundary(a,b,c,e,h,i,j,k,l,f,g,m)
#else
# define DMAddBoundary(a,b,c,d,e,f,g,h,i,j,k,l,m,n) DMAddBoundary(a,b,c,d,f,g,h,i,j,k,l,m,n)
#endif
#ifndef PHYSICS_STRUCT
#define PHYSICS_STRUCT
typedef struct Physics_private *Physics;
struct Physics_private {
CeedScalar nu; // Poisson's ratio
CeedScalar E; // Young's Modulus
};
#endif
// -----------------------------------------------------------------------------
// Command Line Options
// -----------------------------------------------------------------------------
// Problem options
typedef enum {
ELAS_LINEAR = 0, ELAS_SS_NH = 1, ELAS_FSInitial_NH1 = 2, ELAS_FSInitial_NH2 = 3,
ELAS_FSCurrent_NH1 = 4, ELAS_FSCurrent_NH2 = 5
} problemType;
static const char *const problemTypes[] = {"Linear",
"SS-NH",
"FSInitial-NH1",
"FSInitial-NH2",
"FSCurrent-NH1",
"FSCurrent-NH2",
"problemType","ELAS_",0
};
static const char *const problemTypesForDisp[] = {"Linear elasticity",
"Hyperelasticity small strain, Neo-Hookean",
"Hyperelasticity finite strain Initial config Neo-Hookean w/ dXref_dxinit, Grad(u) storage",
"Hyperelasticity finite strain Initial config Neo-Hookean w/ dXref_dxinit, Grad(u), C_inv, constant storage",
"Hyperelasticity finite strain Current config Neo-Hookean w/ dXref_dxinit, Grad(u) storage",
"Hyperelasticity finite strain Current config Neo-Hookean w/ dXref_dxcurr, tau, constant storage",
};
// Forcing function options
typedef enum {
FORCE_NONE = 0, FORCE_CONST = 1, FORCE_MMS = 2
} forcingType;
static const char *const forcing_types[] = {"none",
"constant",
"mms",
"forcingType","FORCE_",0
};
static const char *const forcing_types_for_disp[] = {"None",
"Constant",
"Manufactured solution"
};
// Multigrid options
typedef enum {
MULTIGRID_LOGARITHMIC = 0, MULTIGRID_UNIFORM = 1, MULTIGRID_NONE = 2
} multigridType;
static const char *const multigrid_types [] = {"logarithmic",
"uniform",
"none",
"multigridType","MULTIGRID",0
};
static const char *const multigrid_types_for_disp[] = {"P-multigrid, logarithmic coarsening",
"P-multigrind, uniform coarsening",
"No multigrid"
};
typedef PetscErrorCode BCFunc(PetscInt, PetscReal, const PetscReal *, PetscInt,
PetscScalar *, void *);
// Note: These variables should be updated if additional boundary conditions
// are added to boundary.c.
BCFunc BCMMS, BCZero, BCClamp;
// -----------------------------------------------------------------------------
// Structs
// -----------------------------------------------------------------------------
// Units
typedef struct Units_private *Units;
struct Units_private {
// Fundamental units
PetscScalar meter;
PetscScalar kilogram;
PetscScalar second;
// Derived unit
PetscScalar Pascal;
};
// Application context from user command line options
typedef struct AppCtx_private *AppCtx;
struct AppCtx_private {
char ceed_resource[PETSC_MAX_PATH_LEN]; // libCEED backend
char mesh_file[PETSC_MAX_PATH_LEN]; // exodusII mesh file
char output_dir[PETSC_MAX_PATH_LEN];
PetscBool test_mode;
PetscBool view_soln;
PetscBool view_final_soln;
problemType problem_choice;
forcingType forcing_choice;
multigridType multigrid_choice;
PetscScalar nu_smoother;
PetscInt degree;
PetscInt q_extra;
PetscInt num_levels;
PetscInt *level_degrees;
PetscInt num_increments; // Number of steps
PetscInt bc_clamp_count;
PetscInt bc_clamp_faces[16];
// [translation; 3] [rotation axis; 3] [rotation magnitude c_0, c_1]
// The rotations are (c_0 + c_1 s) \pi, where s = x · axis
PetscScalar bc_clamp_max[16][8];
PetscInt bc_traction_count;
PetscInt bc_traction_faces[16];
PetscScalar bc_traction_vector[16][3];
PetscScalar forcing_vector[3];
};
// Problem specific data
// *INDENT-OFF*
typedef struct {
CeedInt q_data_size;
CeedQFunctionUser setup_geo, apply, jacob, energy, diagnostic;
const char *setup_geo_loc, *apply_loc, *jacob_loc, *energy_loc,
*diagnostic_loc;
CeedQuadMode quad_mode;
} problemData;
// *INDENT-ON*
// Data specific to each problem option
extern problemData problem_options[6];
// Forcing function data
typedef struct {
CeedQFunctionUser setup_forcing;
const char *setup_forcing_loc;
} forcingData;
extern forcingData forcing_options[3];
// Data for PETSc Matshell
typedef struct UserMult_private *UserMult;
struct UserMult_private {
MPI_Comm comm;
DM dm;
Vec X_loc, Y_loc, neumann_bcs;
CeedVector x_ceed, y_ceed;
CeedOperator op;
CeedQFunction qf;
Ceed ceed;
PetscScalar load_increment;
CeedQFunctionContext ctx_phys, ctx_phys_smoother;
};
// Data for Jacobian setup routine
typedef struct FormJacobCtx_private *FormJacobCtx;
struct FormJacobCtx_private {
UserMult *jacob_ctx;
PetscInt num_levels;
SNES snes_coarse;
Mat *jacob_mat, jacob_mat_coarse;
Vec u_coarse;
};
// Data for PETSc Prolongation/Restriction Matshell
typedef struct UserMultProlongRestr_private *UserMultProlongRestr;
struct UserMultProlongRestr_private {
MPI_Comm comm;
DM dm_c, dm_f;
Vec loc_vec_c, loc_vec_f;
CeedVector ceed_vec_c, ceed_vec_f;
CeedOperator op_prolong, op_restrict;
Ceed ceed;
};
// libCEED data struct for level
typedef struct CeedData_private *CeedData;
struct CeedData_private {
Ceed ceed;
CeedBasis basis_x, basis_u, basis_c_to_f, basis_energy,
basis_diagnostic;
CeedElemRestriction elem_restr_x, elem_restr_u, elem_restr_qd_i,
elem_restr_gradu_i,
elem_restr_energy, elem_restr_diagnostic,
elem_restr_dXdx, elem_restr_tau,
elem_restr_C_inv, elem_restr_lam_log_J, elem_restr_qd_diagnostic_i;
CeedQFunction qf_apply, qf_jacob, qf_energy, qf_diagnostic;
CeedOperator op_apply, op_jacob, op_restrict, op_prolong, op_energy,
op_diagnostic;
CeedVector q_data, q_data_diagnostic, grad_u, x_ceed,
y_ceed, true_soln, dXdx, tau, C_inv, lam_log_J;
};
// Translate PetscMemType to CeedMemType
static inline CeedMemType MemTypeP2C(PetscMemType mem_type) {
return PetscMemTypeDevice(mem_type) ? CEED_MEM_DEVICE : CEED_MEM_HOST;
}
// -----------------------------------------------------------------------------
// Process command line options
// -----------------------------------------------------------------------------
// Process general command line options
PetscErrorCode ProcessCommandLineOptions(MPI_Comm comm, AppCtx app_ctx);
// Process physics options
PetscErrorCode ProcessPhysics(MPI_Comm comm, Physics phys, Units units);
// -----------------------------------------------------------------------------
// 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);
// -----------------------------------------------------------------------------
// libCEED Functions
// -----------------------------------------------------------------------------
// Destroy libCEED objects
PetscErrorCode CeedDataDestroy(CeedInt level, CeedData data);
// Utility function - essential BC dofs are encoded in closure indices as -(i+1)
PetscInt Involute(PetscInt i);
// Utility function to create local CEED restriction from DMPlex
PetscErrorCode CreateRestrictionFromPlex(Ceed ceed, DM dm, CeedInt P,
CeedInt height, DMLabel domain_label, CeedInt value,
CeedElemRestriction *elem_restr);
// Utility function to get Ceed Restriction for each domain
PetscErrorCode GetRestrictionForDomain(Ceed ceed, DM dm, CeedInt height,
DMLabel domain_label, PetscInt value, CeedInt P, CeedInt Q, CeedInt q_data_size,
CeedElemRestriction *elem_restr_q, CeedElemRestriction *elem_restr_x,
CeedElemRestriction *elem_restr_qd_i);
// Set up libCEED for a given degree
PetscErrorCode SetupLibceedFineLevel(DM dm, DM dm_energy, DM dm_diagnostic,
Ceed ceed, AppCtx app_ctx,
CeedQFunctionContext phys_ctx,
CeedData *data, PetscInt fine_level,
PetscInt num_comp_u, PetscInt U_g_size,
PetscInt u_loc_size, CeedVector force_ceed,
CeedVector neumann_ceed);
// Set up libCEED multigrid level for a given degree
PetscErrorCode SetupLibceedLevel(DM dm, Ceed ceed, AppCtx app_ctx,
CeedData *data, PetscInt level,
PetscInt num_comp_u, PetscInt U_g_size,
PetscInt u_loc_size, CeedVector fine_mult);
// Setup context data for Jacobian evaluation
PetscErrorCode SetupJacobianCtx(MPI_Comm comm, AppCtx app_ctx, DM dm, Vec V,
Vec V_loc, CeedData ceed_data, Ceed ceed,
CeedQFunctionContext ctx_phys,
CeedQFunctionContext ctx_phys_smoother,
UserMult jacobian_ctx);
// Setup context data for prolongation and restriction operators
PetscErrorCode SetupProlongRestrictCtx(MPI_Comm comm, AppCtx app_ctx, DM dm_c,
DM dm_f, Vec V_f, Vec V_loc_c, Vec V_loc_f,
CeedData ceed_data_c, CeedData ceed_data_f,
Ceed ceed,
UserMultProlongRestr prolong_restr_ctx);
// -----------------------------------------------------------------------------
// Jacobian setup
// -----------------------------------------------------------------------------
PetscErrorCode FormJacobian(SNES snes, Vec U, Mat J, Mat J_pre, void *ctx);
// -----------------------------------------------------------------------------
// Solution output
// -----------------------------------------------------------------------------
PetscErrorCode ViewSolution(MPI_Comm comm, AppCtx app_ctx, Vec U,
PetscInt increment,
PetscScalar load_increment);
PetscErrorCode ViewDiagnosticQuantities(MPI_Comm comm, DM dm_U,
UserMult user, AppCtx app_ctx, Vec U,
CeedElemRestriction elem_restr_diagnostic);
// -----------------------------------------------------------------------------
// libCEED Operators for MatShell
// -----------------------------------------------------------------------------
// This function uses libCEED to compute the local action of an operator
PetscErrorCode ApplyLocalCeedOp(Vec X, Vec Y, UserMult user);
// This function uses libCEED to compute the non-linear residual
PetscErrorCode FormResidual_Ceed(SNES snes, Vec X, Vec Y, void *ctx);
// This function uses libCEED to apply the Jacobian for assembly via a SNES
PetscErrorCode ApplyJacobianCoarse_Ceed(SNES snes, Vec X, Vec Y, void *ctx);
// This function uses libCEED to compute the action of the Jacobian
PetscErrorCode ApplyJacobian_Ceed(Mat A, Vec X, Vec Y);
// This function uses libCEED to compute the action of the prolongation operator
PetscErrorCode Prolong_Ceed(Mat A, Vec X, Vec Y);
// This function uses libCEED to compute the action of the restriction operator
PetscErrorCode Restrict_Ceed(Mat A, Vec X, Vec Y);
// This function returns the computed diagonal of the operator
PetscErrorCode GetDiag_Ceed(Mat A, Vec D);
// This function calculates the strain energy in the final solution
PetscErrorCode ComputeStrainEnergy(DM dm_energy, UserMult user,
CeedOperator op_energy, Vec X,
PetscReal *energy);
// -----------------------------------------------------------------------------
// Boundary Functions
// -----------------------------------------------------------------------------
// Note: If additional boundary conditions are added, an update is needed in
// elasticity.h for the boundaryOptions variable.
// BCMMS - boundary function
// Values on all points of the mesh is set based on given solution below
// for u[0], u[1], u[2]
PetscErrorCode BCMMS(PetscInt dim, PetscReal load_increment,
const PetscReal coords[], PetscInt num_comp_u,
PetscScalar *u, void *ctx);
// BCClamp - fix boundary values with affine transformation at fraction of load
// increment
PetscErrorCode BCClamp(PetscInt dim, PetscReal load_increment,
const PetscReal coords[], PetscInt num_comp_u,
PetscScalar *u, void *ctx);
#endif //setup_h
| {
"alphanum_fraction": 0.5698075974,
"avg_line_length": 44.306010929,
"ext": "h",
"hexsha": "f5f1dde6de935200236309dd3dc37bc9db9628a6",
"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": "fef6d6185073a4ded914e81d25fd2b60cc92d311",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "DiffeoInvariant/libCEED",
"max_forks_repo_path": "examples/solids/elasticity.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fef6d6185073a4ded914e81d25fd2b60cc92d311",
"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": "DiffeoInvariant/libCEED",
"max_issues_repo_path": "examples/solids/elasticity.h",
"max_line_length": 159,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "fef6d6185073a4ded914e81d25fd2b60cc92d311",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "DiffeoInvariant/libCEED",
"max_stars_repo_path": "examples/solids/elasticity.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3405,
"size": 16216
} |
//
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
//
// Principal developer : Felipe Bordeu (Felipe.Bordeu@ec-nantes.fr)
//
#include <iostream>
#ifdef MATLAB_MEX_FILE
#include "mex.h"
#ifdef __cplusplus
extern "C" bool utIsInterruptPending();
extern "C" void utSetInterruptPending(bool);
#else
extern bool utIsInterruptPending();
extern void utSetInterruptPending(bool);
#endif
#endif /* MATLAB_MEX_FILE */
//if in matlab we use the matlab blas library
#ifdef MATLAB_MEX_FILE
#include <blas.h>
inline double cblas_ddot( ptrdiff_t& a, double*& b,const int& c, double* d,const int& e){
ptrdiff_t cc = c;
ptrdiff_t ee = e;
return ddot(&a,b,&cc,d,&ee);
}
enum CBLAS_ORDER {CblasRowMajor=101, CblasColMajor=102 };
enum CBLAS_TRANSPOSE {CblasNoTrans=111, CblasTrans=112, CblasConjTrans=113,
AtlasConj=114};
template<typename T5,typename T6,typename T7,typename T8,typename T9,typename T12>
void cblas_dgemv(const CBLAS_ORDER& a, const CBLAS_TRANSPOSE& b, const ptrdiff_t & c, const ptrdiff_t& d,const T5& e,T6 f,T7& g,T8 h,const T9& i,const double& j,double* k,const T12& l){
char bb= 'n';
if (b ==CblasTrans) bb = 't';
ptrdiff_t cc = c;
ptrdiff_t dd = d;
double ee = e;
ptrdiff_t ii = i;
double jj = j;
ptrdiff_t ll = l;
dgemv( &bb, &cc, &dd, &ee, f, &g, h, &ii, &jj, k, &ll);
};
template<typename T5,typename T6,typename T7, typename T8,typename T9,typename T12>
void cblas_sgemv(const CBLAS_ORDER& a, const CBLAS_TRANSPOSE& b, const ptrdiff_t& c, const ptrdiff_t& d, const T5& e,T6 f,T7& g,T8 h,const T9& i,const float& j,float* k,const T12& l){
char bb= 'n';
if (b ==CblasTrans) bb = 't';
ptrdiff_t cc = c;
ptrdiff_t dd = d;
float ee = e;
ptrdiff_t ii = i;
float jj = j;
ptrdiff_t ll = l;
sgemv( &bb, &cc, &dd, &ee, f, &g, h, &ii, &jj, k, &ll);
};
void cblas_dgemm(const CBLAS_ORDER& a, const CBLAS_TRANSPOSE& b, const CBLAS_TRANSPOSE& c, ptrdiff_t d, ptrdiff_t e, ptrdiff_t f ,double g, double* h, ptrdiff_t i,double* j , ptrdiff_t k,double l,double* m,ptrdiff_t n){
char bb= 'n';
if (b ==CblasTrans) bb = 't';
char cc= 'n';
if (c ==CblasTrans) cc = 't';
dgemm( &bb, &cc, &d, &e, &f, &g, h, &i, j, &k, &l,m, &n);
}
template <typename pdiff>
void cblas_dscal (pdiff& a,double& b, double* c,const pdiff& d){
pdiff dd = d;
dscal(&a,&b,c,&dd);
}
template <typename pdiff>
void cblas_sscal (pdiff& a,float& b, float* c,const pdiff& d){
pdiff dd = d;
sscal(&a,&b,c,&dd);
}
template <typename pdiff>
inline float cblas_sdot( pdiff& a, float*& b,const pdiff& c, float* d,const pdiff& e){
pdiff cc = c;
pdiff ee = e;
return sdot(&a,b,&cc,d,&ee);
}
#else
// if not matlab we use the 'system' blas
#ifdef __APPLE__
#include <Accelerate/Accelerate.h>
#else
#if defined(_WIN32)
/// for now no compilation can be done in windows without matlab
#else
/// linux
#include <cblas.h>
#include <vector>
#endif
#endif
#endif /* MATLAB_MEX_FILE */
template <typename ptrdiff, typename T>
T cblas_Xdot( ptrdiff&, T*&,const ptrdiff&, T*,const ptrdiff& );
template <typename ptrdiff>
double cblas_Xdot( ptrdiff& a, double*& b,const ptrdiff& c, double* d,const ptrdiff& e){
return cblas_ddot(a,b,c,d,e);
}
template <typename ptrdiff>
float cblas_Xdot( ptrdiff& a, float*& b,const ptrdiff& c, float* d,const ptrdiff& e){
return cblas_sdot(a,b,c,d,e);
}
//template<typename T>
//void cblas_Xgemv(const CBLAS_ORDER& , const CBLAS_TRANSPOSE& ,int& ,int& ,const T& , T* , int& ,T* , const int& ,const T& , T* ,const int&);
//
template <typename ptrdiff>
void cblas_Xgemv(const CBLAS_ORDER& a, const CBLAS_TRANSPOSE& b,const int& c,const int& d,const double& e,double* f, ptrdiff& g,double* h,const int& i ,const double& j,double* k,const int& l){
cblas_dgemv(a,b,c,d,e,f,g,h,i,j,k,l);
};
template <typename ptrdiff>
void cblas_Xgemv(const CBLAS_ORDER& a,const CBLAS_TRANSPOSE& b,const int& c,const int& d,const float& e,float* f,ptrdiff& g,float* h,const int& i,const float& j,float* k,const int& l){
cblas_sgemv(a,b,c,d,e,f,g,h,i,j,k,l);
};
//template<typename T1,typename T2, typename T3,typename T4>
//void cblas_Xscal(T1&,T2&,T3,const T4&);
//template<typename T1>
void cblas_Xscal(ptrdiff_t& a,double& b,double* c,const ptrdiff_t& d){
cblas_dscal(a,b,c ,d);
}
//template<typename T1>
void cblas_Xscal(ptrdiff_t& a,float& b, float* c,const ptrdiff_t& d){
cblas_sscal(a,b,c,d);
}
template <typename T>
void update_C(MatLabDataMatrix <T >& C,T* r, MatLabDataMatrix <T >& MM,ptrdiff_t& N, const ptrdiff_t& dim);
template<>
void update_C(MatLabDataMatrix <double >& C,double* r, MatLabDataMatrix <double >& MM,ptrdiff_t& NN, const ptrdiff_t& dim) {
int N = NN;
int M = MM.dsizes[0];
int INCY = C.dsizes[0];
cblas_dgemv(CblasColMajor,CblasTrans, M, N, 1.0, &MM.Data[0], MM.dsizes[0], r, 1, 0, &C.Data[dim], C.dsizes[0] );
#ifdef USE_MPI
MPI_Allreduce(MPI_IN_PLACE, &C.Data[dim], NN, everydim, myOp, MPI_COMM_WORLD);
#endif /* USE_MPI */
};
template<>
void update_C(MatLabDataMatrix <float >& C,float* r, MatLabDataMatrix <float >& MM,ptrdiff_t& NN, const ptrdiff_t& dim) {
int N = NN;
int M = MM.dsizes[0];
int INCY = C.dsizes[0];
cblas_sgemv(CblasColMajor,CblasTrans, M, N, (float)1.0, &MM.Data[0], MM.dsizes[0], r, 1, 0, &C.Data[dim], C.dsizes[0] );
#ifdef USE_MPI
MPI_Allreduce(MPI_IN_PLACE, &C.Data[dim], NN, everydim, myOp, MPI_COMM_WORLD);
#endif /* USE_MPI */
};
template<typename T>
void update_D(MatLabDataMatrix <T >& D, MatLabDataMatrix <T >& FF, T* r){
int cpt = -1;
for(int j =0; j < FF.dsizes[1]; ++j){
for(int i =0; i < FF.dsizes[0]; ++i){
D.Data[++cpt] = FF(i,j)*r[i];
}
}
};
//template <typename T>
//void update_CWithFF2(MatLabDataMatrix <T >& C,T* r, MatLabDataMatrix <T >& MM);
//,unsigned& N, const unsigned& dim, MatLabDataMatrix <T >& DD, std::vector<T> &workingplace);
//template<>
void update_CU(std::vector<double >& C,MatLabDataMatrix <double >& sol, MatLabDataMatrix <double >& D) {
if( sol.dsizes[1] == 0) return;
int Sr,Sc,Dr,Dc;
Sr = sol.dsizes[0];
Sc = sol.dsizes[1];
Dr = D.dsizes[0];
Dc = D.dsizes[1];
///C(Cr,Cc) = sol(Sr,Sc)'*D(Dr,Dc);
//printf (" Initializing data for matrix multiplication C=sol'*D for matrix \n"
// " sol(%ix%i) and matrix D(%ix%i)\n\n", Sr, Sc, Dr, Dc);
//std::cout << "sol.size() : " << sol.fullsize << " =? " <<Sr*Sc << std::endl;
//std::cout << "D.size() : " << D.fullsize << " =? " <<Dr*Dc << std::endl;
//std::cout << "--------------------------------------" << std::endl;
cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans,
Sc,Dc, Dr, 1.0, sol.Data, sol.LD(), D.Data , D.LD(), 0, &C[0], sol.dsizes[1]);
//std::cout << " ------------------------- DONE ------------------------" << std::endl;
#ifdef USE_MPI
MPI_Allreduce(MPI_IN_PLACE, &C[0], C.size(), everydim, myOp, MPI_COMM_WORLD);
#endif /* USE_MPI */
};
//
void update_CU(std::vector<float >& C,MatLabDataMatrix <float >& sol, MatLabDataMatrix <float >& D) {
//#warning to correct for the double implementation
//cblas_sgemm(CblasColMajor, CblasTrans, CblasNoTrans, sol.dsizes[1], D.dsizes[1], sol.dsizes[0], 1.0, sol.Data, sol.dsizes[0], D.Data , D.dsizes[0], 0, &C[0],sol.dsizes[0]);
#ifdef USE_MPI
MPI_Allreduce(MPI_IN_PLACE, &C[0], C.size(), everydim, myOp, MPI_COMM_WORLD);
#endif /* USE_MPI */
};
#define PrintM(X) std::cout << #X " : " << std::endl << " "; \
for(int ii =0; ii < X.dsizes[0] ; ++ii){\
for(int jj =0; jj < X.dsizes[1] ; ++jj){\
std::cout << X(ii,jj) << " ";\
}\
std::cout << std::endl << " "; \
}\
std::cout << std::endl;
#define PrintV(X) std::cout << #X " : " << std::endl << " "; \
for(int ii=0; ii < X.size(); ++ii){\
std::cout << X[ii] << " "; \
} \
std::cout << std::endl;
// template<>
// void update_CWithFF2(MatLabDataMatrix <float >& C,float* r, MatLabDataMatrix <float >& MM,unsigned& NN, const unsigned& dim, MatLabDataMatrix <float >& DD, std::vector<float> &workingplace) { int N = NN;
// ///TODO function to be coded
// int M = MM.dsizes[0];
// int LDA = MM.dsizes[0];
// int INCY = C.dsizes[0];
// cblas_sgemv(CblasColMajor,CblasTrans, M, N, 1.0, &MM.Data[0], LDA, r, 1, 0, &C.Data[dim], C.dsizes[0] );
// #ifdef USE_MPI
// MPI_Allreduce(MPI_IN_PLACE, &C.Data[dim], NN, everydim, myOp, MPI_COMM_WORLD);
// #endif /* USE_MPI */
//
// };
| {
"alphanum_fraction": 0.5895392007,
"avg_line_length": 35.3590733591,
"ext": "h",
"hexsha": "09474348b33f80f4b6989cc344c229cd776ff979",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-11-26T22:26:12.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-11-26T22:26:12.000Z",
"max_forks_repo_head_hexsha": "b40ba3f85acc262055fee12629cbf685ce19a982",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "fbordeu/PGDforMatlab",
"max_forks_repo_path": "Kompressor/Src/ExtraFunctions.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b40ba3f85acc262055fee12629cbf685ce19a982",
"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": "fbordeu/PGDforMatlab",
"max_issues_repo_path": "Kompressor/Src/ExtraFunctions.h",
"max_line_length": 220,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b40ba3f85acc262055fee12629cbf685ce19a982",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "fbordeu/PGDforMatlab",
"max_stars_repo_path": "Kompressor/Src/ExtraFunctions.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3028,
"size": 9158
} |
static char help[] =
"Load a matrix A and right-hand-side b from binary files (PETSc format).\n"
"Then solve the system A x = b using KSPSolve().\n"
"Example. First save a system from tri.c:\n"
" ./tri -ksp_view_mat binary:A.dat -ksp_view_rhs binary:b.dat\n"
"then load it and solve:\n"
" ./loadsolve -fA A.dat -fb b.dat\n"
"To time the solution read the third printed number:\n"
" ./loadsolve -fA A.dat -fb b.dat -log_view |grep KSPSolve\n"
"(This is a simpler code than src/ksp/ksp/examples/tutorials/ex10.c.)\n";
/*
small system example where RHS missing:
./tri -ksp_view_mat binary:A.dat
./loadsolve -fA A.dat -ksp_view_mat -ksp_view_rhs
large tridiagonal system (m=10^7) example:
./tri -tri_m 10000000 -ksp_view_mat binary:A.dat -ksp_view_rhs binary:b.dat
./loadsolve -fA A.dat -fb b.dat -log_view |grep KSPSolve
*/
#include <petsc.h>
int main(int argc,char **args) {
PetscErrorCode ierr;
Vec x, b;
Mat A;
KSP ksp;
int m, n, mb;
PetscBool flg,
verbose = PETSC_FALSE;
char nameA[PETSC_MAX_PATH_LEN] = "",
nameb[PETSC_MAX_PATH_LEN] = "";
PetscViewer fileA, fileb;
PetscInitialize(&argc,&args,NULL,help);
ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"","options for loadsolve",""); CHKERRQ(ierr);
ierr = PetscOptionsString("-fA","input file containing matrix A",
"loadsolve.c",nameA,nameA,PETSC_MAX_PATH_LEN,NULL);CHKERRQ(ierr);
ierr = PetscOptionsString("-fb","input file containing vector b",
"loadsolve.c",nameb,nameb,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
ierr = PetscOptionsBool("-verbose","say what is going on",
"loadsolve.c",verbose,&verbose,NULL); CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
if (strlen(nameA) == 0) {
SETERRQ(PETSC_COMM_WORLD,1,
"no input matrix provided ... ending (usage: loadsolve -fA A.dat)\n");
}
if (verbose) {
ierr = PetscPrintf(PETSC_COMM_WORLD,
"reading matrix from %s ...\n",nameA); CHKERRQ(ierr);
}
ierr = MatCreate(PETSC_COMM_WORLD,&A);CHKERRQ(ierr);
ierr = MatSetFromOptions(A);CHKERRQ(ierr);
ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,nameA,FILE_MODE_READ,&fileA);CHKERRQ(ierr);
ierr = MatLoad(A,fileA);CHKERRQ(ierr);
ierr = PetscViewerDestroy(&fileA);CHKERRQ(ierr);
ierr = MatGetSize(A,&m,&n); CHKERRQ(ierr);
if (verbose) {
ierr = PetscPrintf(PETSC_COMM_WORLD,
"matrix has size m x n = %d x %d ...\n",m,n); CHKERRQ(ierr);
}
if (m != n) {
SETERRQ(PETSC_COMM_WORLD,2,"only works for square matrices\n");
}
ierr = VecCreate(PETSC_COMM_WORLD,&b);CHKERRQ(ierr);
ierr = VecSetFromOptions(b);CHKERRQ(ierr);
if (flg) {
ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,nameb,FILE_MODE_READ,&fileb);CHKERRQ(ierr);
if (verbose) {
ierr = PetscPrintf(PETSC_COMM_WORLD,
"reading vector from %s ...\n",nameb); CHKERRQ(ierr);
}
ierr = VecLoad(b,fileb);CHKERRQ(ierr);
ierr = PetscViewerDestroy(&fileb);CHKERRQ(ierr);
ierr = VecGetSize(b,&mb); CHKERRQ(ierr);
if (mb != m) {
SETERRQ(PETSC_COMM_WORLD,3,"size of matrix and vector do not match\n");
}
} else {
if (verbose) {
ierr = PetscPrintf(PETSC_COMM_WORLD,
"right-hand-side vector b not provided ... using zero vector of length %d\n",m); CHKERRQ(ierr);
}
ierr = VecSetSizes(b,PETSC_DECIDE,m); CHKERRQ(ierr);
ierr = VecSet(b,0.0); CHKERRQ(ierr);
}
ierr = KSPCreate(PETSC_COMM_WORLD,&ksp); CHKERRQ(ierr);
ierr = KSPSetOperators(ksp,A,A); CHKERRQ(ierr);
ierr = KSPSetFromOptions(ksp); CHKERRQ(ierr);
ierr = VecDuplicate(b,&x);CHKERRQ(ierr);
ierr = KSPSolve(ksp,b,x); CHKERRQ(ierr);
KSPDestroy(&ksp); MatDestroy(&A);
VecDestroy(&x); VecDestroy(&b);
return PetscFinalize();
}
| {
"alphanum_fraction": 0.6451282051,
"avg_line_length": 37.5,
"ext": "c",
"hexsha": "7201b0f82597dd923a9841756774d127442afa32",
"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": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mapengfei-nwpu/p4pdes",
"max_forks_repo_path": "c/ch2/loadsolve.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"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": "mapengfei-nwpu/p4pdes",
"max_issues_repo_path": "c/ch2/loadsolve.c",
"max_line_length": 108,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mapengfei-nwpu/p4pdes",
"max_stars_repo_path": "c/ch2/loadsolve.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1123,
"size": 3900
} |
#pragma once
#include <cstring>
#include <string>
#include <tuple>
#include <utility>
#include <gsl/assert>
namespace xmol::utils {
constexpr static int powers_of_10[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
template <int LEN> inline std::pair<bool, int> parse_uint_fixed_length(const std::string& line, int pos) noexcept {
bool success = GSL_LIKELY(line.size() >= pos + LEN);
if (GSL_UNLIKELY(!success)) {
return {false, 0};
}
int number = 0;
#pragma unroll
for (int i = 0; i < LEN; i++) {
unsigned digit = static_cast<unsigned>(line[pos + i]) - '0';
success &= digit <= 9;
number += digit * powers_of_10[LEN - i - 1];
}
return std::make_pair(success, number);
};
inline std::pair<bool, int> parse_uint(const std::string& line, int pos, int LEN) noexcept {
switch (LEN) {
case (1):
return parse_uint_fixed_length<1>(line, pos);
case (2):
return parse_uint_fixed_length<2>(line, pos);
case (3):
return parse_uint_fixed_length<3>(line, pos);
case (4):
return parse_uint_fixed_length<4>(line, pos);
case (5):
return parse_uint_fixed_length<5>(line, pos);
case (6):
return parse_uint_fixed_length<6>(line, pos);
case (7):
return parse_uint_fixed_length<7>(line, pos);
case (8):
return parse_uint_fixed_length<8>(line, pos);
case (9):
return parse_uint_fixed_length<9>(line, pos);
default:
return {false, 0};
}
};
enum class SpaceStrip { NONE, LEFT, RIGHT, LEFT_AND_RIGHT };
template <SpaceStrip stripping = SpaceStrip::NONE>
std::pair<bool, int> parse_int(const std::string& line, int pos, int LEN) noexcept {
// short-circuit for invalid
if (GSL_UNLIKELY(line.size() < pos + LEN)) {
return {false, 0};
}
if (stripping == SpaceStrip::RIGHT || stripping == SpaceStrip::LEFT_AND_RIGHT) {
while (line[pos + LEN - 1] == ' ' && LEN > 0) {
--LEN;
}
}
if (stripping == SpaceStrip::LEFT || stripping == SpaceStrip::LEFT_AND_RIGHT) {
while (line[pos] == ' ' && LEN > 0) {
++pos;
--LEN;
}
}
if (line[pos] == '-') {
bool success;
int value;
std::tie(success, value) = parse_uint(line, pos + 1, LEN - 1);
return {success, -value};
} else {
return parse_uint(line, pos, LEN);
}
};
template <int WIDTH, int PRECISION, SpaceStrip STRIP> struct parse_fixed_precision_fn {
static_assert(PRECISION >= 0);
static_assert(WIDTH > 0);
static_assert(PRECISION == 0 || WIDTH >= PRECISION + 2);
inline std::pair<bool, double> operator()(const std::string& line, int pos) const noexcept {
if (GSL_UNLIKELY(line.size() < pos + WIDTH || (PRECISION > 0 && line[pos + WIDTH - PRECISION - 1] != '.'))) {
return {false, 0};
}
int whole = WIDTH - PRECISION;
if (PRECISION > 0) {
--whole;
}
int precision = PRECISION;
if (STRIP == SpaceStrip::LEFT_AND_RIGHT || STRIP == SpaceStrip::LEFT) {
while (line[pos] == ' ' && whole > 0) {
--whole;
pos++;
}
}
if (STRIP == SpaceStrip::LEFT_AND_RIGHT || STRIP == SpaceStrip::RIGHT) {
while (line[pos + whole + precision] == ' ' && precision > 0) {
--precision;
}
}
int sign = 1;
if (line[pos] == '-') {
sign = -1;
++pos;
--whole;
}
bool success;
int whole_part;
std::tie(success, whole_part) = parse_uint(line, pos, whole);
if (GSL_UNLIKELY(!success)) {
return {false, 0};
}
if (PRECISION == 0) {
return {true, sign * whole_part};
}
bool success2;
int fraction_part;
std::tie(success2, fraction_part) = parse_uint(line, pos + whole + 1, precision);
if (GSL_UNLIKELY(!success2)) {
return {false, 0};
}
return {true, sign * (whole_part + double(fraction_part) / powers_of_10[precision])};
};
};
inline namespace functional_objects {
struct parse_fixed_precision_fn___ {
template <int WIDTH, int PRECISION, SpaceStrip STRIP = SpaceStrip::LEFT_AND_RIGHT>
inline std::pair<bool, double> parse(const std::string& line, int pos) const {
return parse_fixed_precision_fn<WIDTH,PRECISION,STRIP>{}(line,pos);
}
};
constexpr parse_fixed_precision_fn___ parse_fixed_precision{};
}
std::pair<bool, double> parse_fixed_precision_rt(const std::string& line, int pos, int width) noexcept;
} | {
"alphanum_fraction": 0.6267036267,
"avg_line_length": 27.9290322581,
"ext": "h",
"hexsha": "3adb7d7711e6a9545e749e85805decf6141ed373",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2022-03-12T11:05:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-06-04T09:16:26.000Z",
"max_forks_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sizmailov/pyxmolpp2",
"max_forks_repo_path": "include/xmol/utils/parsing.h",
"max_issues_count": 84,
"max_issues_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764",
"max_issues_repo_issues_event_max_datetime": "2020-06-17T15:03:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-04-22T12:29:31.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "sizmailov/pyxmolpp2",
"max_issues_repo_path": "include/xmol/utils/parsing.h",
"max_line_length": 115,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "9395ba1b1ddc957e0b33dc6decccdb711e720764",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sizmailov/pyxmolpp2",
"max_stars_repo_path": "include/xmol/utils/parsing.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-15T23:00:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-24T11:07:57.000Z",
"num_tokens": 1247,
"size": 4329
} |
/* cdf/gauss.c
*
* Copyright (C) 2002, 2004 Jason H. Stover.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* Computes the cumulative distribution function for the Gaussian
* distribution using a rational function approximation. The
* computation is for the standard Normal distribution, i.e., mean 0
* and standard deviation 1. If you want to compute Pr(X < t) for a
* Gaussian random variable X with non-zero mean m and standard
* deviation sd not equal to 1, find gsl_cdf_ugaussian ((t-m)/sd).
* This approximation is accurate to at least double precision. The
* accuracy was verified with a pari-gp script. The largest error
* found was about 1.4E-20. The coefficients were derived by Cody.
*
* References:
*
* W.J. Cody. "Rational Chebyshev Approximations for the Error
* Function," Mathematics of Computation, v23 n107 1969, 631-637.
*
* W. Fraser, J.F Hart. "On the Computation of Rational Approximations
* to Continuous Functions," Communications of the ACM, v5 1962.
*
* W.J. Kennedy Jr., J.E. Gentle. "Statistical Computing." Marcel Dekker. 1980.
*
*
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cdf.h>
#ifndef M_1_SQRT2PI
#define M_1_SQRT2PI (M_2_SQRTPI * M_SQRT1_2 / 2.0)
#endif
#define SQRT32 (4.0 * M_SQRT2)
/*
* IEEE double precision dependent constants.
*
* GAUSS_EPSILON: Smallest positive value such that
* gsl_cdf_gaussian(x) > 0.5.
* GAUSS_XUPPER: Largest value x such that gsl_cdf_gaussian(x) < 1.0.
* GAUSS_XLOWER: Smallest value x such that gsl_cdf_gaussian(x) > 0.0.
*/
#define GAUSS_EPSILON (GSL_DBL_EPSILON / 2)
#define GAUSS_XUPPER (8.572)
#define GAUSS_XLOWER (-37.519)
#define GAUSS_SCALE (16.0)
static double
get_del (double x, double rational)
{
double xsq = 0.0;
double del = 0.0;
double result = 0.0;
xsq = floor (x * GAUSS_SCALE) / GAUSS_SCALE;
del = (x - xsq) * (x + xsq);
del *= 0.5;
result = exp (-0.5 * xsq * xsq) * exp (-1.0 * del) * rational;
return result;
}
/*
* Normal cdf for fabs(x) < 0.66291
*/
static double
gauss_small (const double x)
{
unsigned int i;
double result = 0.0;
double xsq;
double xnum;
double xden;
const double a[5] = {
2.2352520354606839287,
161.02823106855587881,
1067.6894854603709582,
18154.981253343561249,
0.065682337918207449113
};
const double b[4] = {
47.20258190468824187,
976.09855173777669322,
10260.932208618978205,
45507.789335026729956
};
xsq = x * x;
xnum = a[4] * xsq;
xden = xsq;
for (i = 0; i < 3; i++)
{
xnum = (xnum + a[i]) * xsq;
xden = (xden + b[i]) * xsq;
}
result = x * (xnum + a[3]) / (xden + b[3]);
return result;
}
/*
* Normal cdf for 0.66291 < fabs(x) < sqrt(32).
*/
static double
gauss_medium (const double x)
{
unsigned int i;
double temp = 0.0;
double result = 0.0;
double xnum;
double xden;
double absx;
const double c[9] = {
0.39894151208813466764,
8.8831497943883759412,
93.506656132177855979,
597.27027639480026226,
2494.5375852903726711,
6848.1904505362823326,
11602.651437647350124,
9842.7148383839780218,
1.0765576773720192317e-8
};
const double d[8] = {
22.266688044328115691,
235.38790178262499861,
1519.377599407554805,
6485.558298266760755,
18615.571640885098091,
34900.952721145977266,
38912.003286093271411,
19685.429676859990727
};
absx = fabs (x);
xnum = c[8] * absx;
xden = absx;
for (i = 0; i < 7; i++)
{
xnum = (xnum + c[i]) * absx;
xden = (xden + d[i]) * absx;
}
temp = (xnum + c[7]) / (xden + d[7]);
result = get_del (x, temp);
return result;
}
/*
* Normal cdf for
* {sqrt(32) < x < GAUSS_XUPPER} union { GAUSS_XLOWER < x < -sqrt(32) }.
*/
static double
gauss_large (const double x)
{
int i;
double result;
double xsq;
double temp;
double xnum;
double xden;
double absx;
const double p[6] = {
0.21589853405795699,
0.1274011611602473639,
0.022235277870649807,
0.001421619193227893466,
2.9112874951168792e-5,
0.02307344176494017303
};
const double q[5] = {
1.28426009614491121,
0.468238212480865118,
0.0659881378689285515,
0.00378239633202758244,
7.29751555083966205e-5
};
absx = fabs (x);
xsq = 1.0 / (x * x);
xnum = p[5] * xsq;
xden = xsq;
for (i = 0; i < 4; i++)
{
xnum = (xnum + p[i]) * xsq;
xden = (xden + q[i]) * xsq;
}
temp = xsq * (xnum + p[4]) / (xden + q[4]);
temp = (M_1_SQRT2PI - temp) / absx;
result = get_del (x, temp);
return result;
}
double
gsl_cdf_ugaussian_P (const double x)
{
double result;
double absx = fabs (x);
if (absx < GAUSS_EPSILON)
{
result = 0.5;
return result;
}
else if (absx < 0.66291)
{
result = 0.5 + gauss_small (x);
return result;
}
else if (absx < SQRT32)
{
result = gauss_medium (x);
if (x > 0.0)
{
result = 1.0 - result;
}
return result;
}
else if (x > GAUSS_XUPPER)
{
result = 1.0;
return result;
}
else if (x < GAUSS_XLOWER)
{
result = 0.0;
return result;
}
else
{
result = gauss_large (x);
if (x > 0.0)
{
result = 1.0 - result;
}
}
return result;
}
double
gsl_cdf_ugaussian_Q (const double x)
{
double result;
double absx = fabs (x);
if (absx < GAUSS_EPSILON)
{
result = 0.5;
return result;
}
else if (absx < 0.66291)
{
result = gauss_small (x);
if (x < 0.0)
{
result = fabs (result) + 0.5;
}
else
{
result = 0.5 - result;
}
return result;
}
else if (absx < SQRT32)
{
result = gauss_medium (x);
if (x < 0.0)
{
result = 1.0 - result;
}
return result;
}
else if (x > -(GAUSS_XLOWER))
{
result = 0.0;
return result;
}
else if (x < -(GAUSS_XUPPER))
{
result = 1.0;
return result;
}
else
{
result = gauss_large (x);
if (x < 0.0)
{
result = 1.0 - result;
}
}
return result;
}
double
gsl_cdf_gaussian_P (const double x, const double sigma)
{
return gsl_cdf_ugaussian_P (x / sigma);
}
double
gsl_cdf_gaussian_Q (const double x, const double sigma)
{
return gsl_cdf_ugaussian_Q (x / sigma);
}
| {
"alphanum_fraction": 0.6098378983,
"avg_line_length": 20.3295454545,
"ext": "c",
"hexsha": "235c978c8cf7a8cceef25f31130c0a4a13825439",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/cdf/gauss.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/cdf/gauss.c",
"max_line_length": 79,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/cdf/gauss.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 2456,
"size": 7156
} |
#if !defined(fvSupport_h)
#define fvSupport_h
#include <petsc.h>
PETSC_EXTERN PetscErrorCode DMPlexReconstructGradientsFVM_MulfiField(DM dm, PetscFV fvm, Vec locX, Vec grad);
PETSC_EXTERN PetscErrorCode DMPlexGetDataFVM_MulfiField(DM dm, PetscFV fv, Vec *cellgeom, Vec *facegeom, DM *gradDM);
#endif | {
"alphanum_fraction": 0.8085808581,
"avg_line_length": 33.6666666667,
"ext": "h",
"hexsha": "46af1cef8747172cb543c74b3f02f635bb4d7908",
"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": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pakserep/ablate",
"max_forks_repo_path": "ablateCore/flow/fvSupport.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4",
"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": "pakserep/ablate",
"max_issues_repo_path": "ablateCore/flow/fvSupport.h",
"max_line_length": 117,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8c8443de8a252b03b3535f7c48b7a50aac1e56e4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pakserep/ablate",
"max_stars_repo_path": "ablateCore/flow/fvSupport.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 95,
"size": 303
} |
#ifndef _CSPLINE_H_
#define _CSPLINE_H_
#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
#include <vector_types.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_linalg.h>
template <typename T> class cspline{
std::vector<T> y;
std::vector<T> t;
std::vector<T> h;
std::vector<T> z;
int N;
void h_calc();
void b_calc(std::vector<T> &b);
void v_calc(std::vector<T> &v);
void u_calc(std::vector<T> &u, std::vector<T> &b);
void z_calc(std::vector<T> &v, std::vector<T> &u);
public:
cspline();
cspline(std::vector<T> &x, std::vector<T> &fx);
void initialize(std::vector<T> &x, std::vector<T> &fx);
void set_pointer_for_device(std::vector<float4> &spline);
void set_pointer_for_device(std::vector<double4> &spline);
T evaluate(T x);
};
template<typename T> void cspline<T>::h_calc() {
for (int i = 0; i < cspline<T>::N - 1; ++i)
cspline<T>::h.push_back(t[i + 1] - t[i]);
}
template<typename T> void cspline<T>::b_calc(std::vector<T> &b) {
for (int i = 0; i < cspline<T>::N - 1; ++i)
b[i] = (cspline<T>::y[i + 1] - cspline<T>::y[i])/h[i];
}
template<typename T> void cspline<T>::v_calc(std::vector<T> &v) {
for (int i = 1; i < cspline<T>::N - 1; ++i)
v[i - 1] = 2.0*(cspline<T>::h[i - 1] + cspline<T>::h[i]);
}
template<typename T> void cspline<T>::u_calc(std::vector<T> &u, std::vector<T> &b) {
for (int i = 1; i < cspline<T>::N - 1; ++i)
u[i - 1] = 6.0*(b[i] - b[i - 1]);
}
template<typename T> void cspline<T>::z_calc(std::vector<T> &v, std::vector<T> &u) {
gsl_matrix *A = gsl_matrix_alloc(cspline<T>::N - 2, cspline<T>::N - 2);
gsl_vector *Z = gsl_vector_alloc(cspline<T>::N - 2);
gsl_vector *U = gsl_vector_alloc(cspline<T>::N - 2);
for (int i = 1; i < cspline<T>::N - 1; ++i) {
gsl_vector_set(U, i - 1, u[i - 1]);
for (int j = 1; j < cspline<T>::N - 1; ++j) {
if (i == j) gsl_matrix_set(A, i - 1, j - 1, v[i - 1]);
else if (j == i + 1) gsl_matrix_set(A, i - 1, j - 1, cspline<T>::h[i]);
else if (j == i - 1) gsl_matrix_set(A, i - 1, j - 1, cspline<T>::h[j]);
else gsl_matrix_set(A, i - 1, j - 1, 0.0);
}
}
int s;
gsl_permutation *p = gsl_permutation_alloc(cspline<T>::N - 2);
gsl_linalg_LU_decomp(A, p, &s);
gsl_linalg_LU_solve(A, p, U, Z);
for (int i = 0; i < cspline<T>::N; ++i) {
if (i == 0 || i == cspline<T>::N - 1) cspline<T>::z.push_back(0.0);
else cspline<T>::z.push_back(gsl_vector_get(Z, i - 1));
}
gsl_vector_free(Z);
gsl_vector_free(U);
gsl_matrix_free(A);
gsl_permutation_free(p);
}
template<typename T> cspline<T>::cspline() {
cspline<T>::N = 1;
}
template<typename T> cspline<T>::cspline(std::vector<T> &x, std::vector<T> &fx) {
cspline<T>::N = fx.size();
for (int i = 0; i < cspline<T>::N; ++i) {
cspline<T>::t.push_back(x[i]);
cspline<T>::y.push_back(fx[i]);
}
std::vector<T> b(cspline<T>::N - 1);
std::vector<T> v(cspline<T>::N - 2);
std::vector<T> u(cspline<T>::N - 2);
cspline<T>::h_calc();
cspline<T>::b_calc(b);
cspline<T>::v_calc(v);
cspline<T>::u_calc(u, b);
cspline<T>::z_calc(v, u);
}
template<typename T> void cspline<T>::initialize(std::vector<T> &x, std::vector<T> &fx) {
cspline<T>::N = fx.size();
for (int i = 0; i < cspline<T>::N; ++i) {
cspline<T>::t.push_back(x[i]);
cspline<T>::y.push_back(fx[i]);
}
std::vector<T> b(cspline<T>::N - 1);
std::vector<T> v(cspline<T>::N - 2);
std::vector<T> u(cspline<T>::N - 2);
cspline<T>::h_calc();
cspline<T>::b_calc(b);
cspline<T>::v_calc(v);
cspline<T>::u_calc(u, b);
cspline<T>::z_calc(v, u);
}
template<typename T> void cspline<T>::set_pointer_for_device(std::vector<float4> &spline) {
for (int i = 0; i < cspline<T>::N; ++i) {
float4 temp = {cspline<T>::t[i], cspline<T>::y[i], cspline<T>::z[i], cspline<T>::h[i]};
spline.push_back(temp);
}
}
template<typename T> void cspline<T>::set_pointer_for_device(std::vector<double4> &spline) {
for (int i = 0; i < cspline<T>::N; ++i) {
double4 temp = {cspline<T>::t[i], cspline<T>::y[i], cspline<T>::z[i], cspline<T>::h[i]};
spline.push_back(temp);
}
}
template<typename T> T cspline<T>::evaluate(T x) {
if (x < cspline<T>::t[0] || x > cspline<T>::t[cspline<T>::N - 1]) {
std::stringstream message;
message << "The requested x value is outside of the allowed range." << std::endl;
throw std::runtime_error(message.str());
}
int i = 0;
while (cspline<T>::t[i] < x) ++i;
i--;
T val = (cspline<T>::z[i + 1]*(x - cspline<T>::t[i])*(x - cspline<T>::t[i])*(x - cspline<T>::t[i]))/(6.0*cspline<T>::h[i])
+ (cspline<T>::z[i]*(cspline<T>::t[i + 1] - x)*(cspline<T>::t[i + 1] - x)*(cspline<T>::t[i + 1] - x))/(6.0*cspline<T>::h[i])
+ (cspline<T>::y[i + 1]/cspline<T>::h[i] - (cspline<T>::z[i + 1]*cspline<T>::h[i])/6.0)*(x - cspline<T>::t[i])
+ (cspline<T>::y[i]/cspline<T>::h[i] - (cspline<T>::h[i]*cspline<T>::z[i])/6.0)*(cspline<T>::t[i + 1] - x);
return val;
}
#endif
| {
"alphanum_fraction": 0.5291735689,
"avg_line_length": 32.3392857143,
"ext": "h",
"hexsha": "1647a2656a83ad786ffc71dc940dede9d1f6af33",
"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": "6fd93c1f75c190629ec272786c46ff46d9d7bd98",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dpearson1983/BIMODAL",
"max_forks_repo_path": "include/cspline.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6fd93c1f75c190629ec272786c46ff46d9d7bd98",
"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": "dpearson1983/BIMODAL",
"max_issues_repo_path": "include/cspline.h",
"max_line_length": 137,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6fd93c1f75c190629ec272786c46ff46d9d7bd98",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dpearson1983/BIMODAL",
"max_stars_repo_path": "include/cspline.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1882,
"size": 5433
} |
/* sum/levin_u.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 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.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sum.h>
int
gsl_sum_levin_u_accel (const double *array, const size_t array_size,
gsl_sum_levin_u_workspace * w,
double *sum_accel, double *abserr)
{
return gsl_sum_levin_u_minmax (array, array_size,
0, array_size - 1, w, sum_accel, abserr);
}
int
gsl_sum_levin_u_minmax (const double *array, const size_t array_size,
const size_t min_terms, const size_t max_terms,
gsl_sum_levin_u_workspace * w,
double *sum_accel, double *abserr)
{
/* Ignore any trailing zeros in the array */
size_t size = array_size;
while (size > 0 && array[size - 1] == 0) {
size--;
}
if (size == 0)
{
*sum_accel = 0.0;
*abserr = 0.0;
w->sum_plain = 0.0;
w->terms_used = 0;
return GSL_SUCCESS;
}
else if (size == 1)
{
*sum_accel = array[0];
*abserr = 0.0;
w->sum_plain = array[0];
w->terms_used = 1;
return GSL_SUCCESS;
}
else
{
const double SMALL = 0.01;
const size_t nmax = GSL_MAX (max_terms, array_size) - 1;
double noise_n = 0.0, noise_nm1 = 0.0;
double trunc_n = 0.0, trunc_nm1 = 0.0;
double actual_trunc_n = 0.0, actual_trunc_nm1 = 0.0;
double result_n = 0.0, result_nm1 = 0.0;
double variance = 0;
size_t n;
unsigned int i;
int better = 0;
int before = 0;
int converging = 0;
double least_trunc = GSL_DBL_MAX;
double least_trunc_noise = GSL_DBL_MAX;
double least_trunc_result;
/* Calculate specified minimum number of terms. No convergence
tests are made, and no truncation information is stored. */
for (n = 0; n < min_terms; n++)
{
const double t = array[n];
result_nm1 = result_n;
gsl_sum_levin_u_step (t, n, nmax, w, &result_n);
}
least_trunc_result = result_n;
variance = 0;
for (i = 0; i < n; i++)
{
double dn = w->dsum[i] * GSL_MACH_EPS * array[i];
variance += dn * dn;
}
noise_n = sqrt (variance);
/* Calculate up to maximum number of terms. Check truncation
condition. */
for (; n <= nmax; n++)
{
const double t = array[n];
result_nm1 = result_n;
gsl_sum_levin_u_step (t, n, nmax, w, &result_n);
/* Compute the truncation error directly */
actual_trunc_nm1 = actual_trunc_n;
actual_trunc_n = fabs (result_n - result_nm1);
/* Average results to make a more reliable estimate of the
real truncation error */
trunc_nm1 = trunc_n;
trunc_n = 0.5 * (actual_trunc_n + actual_trunc_nm1);
noise_nm1 = noise_n;
variance = 0;
for (i = 0; i <= n; i++)
{
double dn = w->dsum[i] * GSL_MACH_EPS * array[i];
variance += dn * dn;
}
noise_n = sqrt (variance);
/* Determine if we are in the convergence region. */
better = (trunc_n < trunc_nm1 || trunc_n < SMALL * fabs (result_n));
converging = converging || (better && before);
before = better;
if (converging)
{
if (trunc_n < least_trunc)
{
/* Found a low truncation point in the convergence
region. Save it. */
least_trunc_result = result_n;
least_trunc = trunc_n;
least_trunc_noise = noise_n;
}
if (noise_n > trunc_n / 3.0)
break;
if (trunc_n < 10.0 * GSL_MACH_EPS * fabs (result_n))
break;
}
}
if (converging)
{
/* Stopped in the convergence region. Return result and
error estimate. */
*sum_accel = least_trunc_result;
*abserr = GSL_MAX_DBL (least_trunc, least_trunc_noise);
w->terms_used = n;
return GSL_SUCCESS;
}
else
{
/* Never reached the convergence region. Use the last
calculated values. */
*sum_accel = result_n;
*abserr = GSL_MAX_DBL (trunc_n, noise_n);
w->terms_used = n;
return GSL_SUCCESS;
}
}
}
int
gsl_sum_levin_u_step (const double term, const size_t n, const size_t nmax,
gsl_sum_levin_u_workspace * w, double *sum_accel)
{
#define I(i,j) ((i)*(nmax+1) + (j))
if (n == 0)
{
*sum_accel = term;
w->sum_plain = term;
w->q_den[0] = 1.0 / term;
w->q_num[0] = 1.0;
w->dq_den[I (0, 0)] = -1.0 / (term * term);
w->dq_num[I (0, 0)] = 0.0;
w->dsum[0] = 1.0;
return GSL_SUCCESS;
}
else
{
double result;
double factor = 1.0;
double ratio = (double) n / (n + 1.0);
unsigned int i;
int j;
w->sum_plain += term;
w->q_den[n] = 1.0 / (term * (n + 1.0) * (n + 1.0));
w->q_num[n] = w->sum_plain * w->q_den[n];
for (i = 0; i < n; i++)
{
w->dq_den[I (i, n)] = 0;
w->dq_num[I (i, n)] = w->q_den[n];
}
w->dq_den[I (n, n)] = -w->q_den[n] / term;
w->dq_num[I (n, n)] =
w->q_den[n] + w->sum_plain * (w->dq_den[I (n, n)]);
for (j = n - 1; j >= 0; j--)
{
double c = factor * (j + 1) / (n + 1);
factor *= ratio;
w->q_den[j] = w->q_den[j + 1] - c * w->q_den[j];
w->q_num[j] = w->q_num[j + 1] - c * w->q_num[j];
for (i = 0; i < n; i++)
{
w->dq_den[I (i, j)] =
w->dq_den[I (i, j + 1)] - c * w->dq_den[I (i, j)];
w->dq_num[I (i, j)] =
w->dq_num[I (i, j + 1)] - c * w->dq_num[I (i, j)];
}
w->dq_den[I (n, j)] = w->dq_den[I (n, j + 1)];
w->dq_num[I (n, j)] = w->dq_num[I (n, j + 1)];
}
result = w->q_num[0] / w->q_den[0];
*sum_accel = result;
for (i = 0; i <= n; i++)
{
w->dsum[i] =
(w->dq_num[I (i, 0)] -
result * w->dq_den[I (i, 0)]) / w->q_den[0];
}
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.5139174551,
"avg_line_length": 27.7300380228,
"ext": "c",
"hexsha": "81dcc75eeaa33c30732d4b629bab75362f59b360",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/sum/levin_u.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/sum/levin_u.c",
"max_line_length": 85,
"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/sum/levin_u.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z",
"num_tokens": 2147,
"size": 7293
} |
/*
* testgen.c
* Patrick Alken
*
* Compile: gcc -g -O2 -Wall -o testgen testgen.c -lm -lgsl -lcblas -latlas
*
* Usage: testgen [options]
*
* -i : incremental matrices
* -z : compute Schur vectors and test them
* -n size : size of matrices
* -l lower-bound : lower bound for matrix elements
* -u upper-bound : upper bound for matrix elements
* -c num : number of matrices to solve
*/
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_errno.h>
typedef struct
{
gsl_eigen_gen_workspace *gen_p;
gsl_matrix *A;
gsl_matrix *B;
gsl_vector_complex *alpha;
gsl_vector *beta;
gsl_vector_complex *evals;
gsl_eigen_genv_workspace *genv_p;
gsl_matrix *Av;
gsl_matrix *Bv;
gsl_vector_complex *alphav;
gsl_vector *betav;
gsl_matrix_complex *evec;
gsl_matrix *Q;
gsl_matrix *Z;
int compute_schur;
size_t n_evals;
} gen_workspace;
gen_workspace *gen_alloc(size_t n, int compute_schur);
void gen_free(gen_workspace *w);
int gen_proc(gen_workspace *w);
/*
* Global variables
*/
unsigned long count = 0;
/*
* Prototypes
*/
void make_random_matrix(gsl_matrix *m, gsl_rng *r, int lower, int upper);
void make_random_integer_matrix(gsl_matrix *m, gsl_rng *r, int lower,
int upper);
void make_start_matrix(gsl_matrix *m, int lower);
int inc_matrix (gsl_matrix *m, int lower, int upper);
void output_matrix(const gsl_matrix *m);
void print_matrix(const gsl_matrix *m, const char *str);
int test_evals(gsl_vector_complex *obs, gsl_vector_complex *expected,
gsl_matrix *A, gsl_matrix *B,
const char *obsname, const char *expname);
int test_alpha(gsl_vector_complex *obs, gsl_vector_complex *expected,
gsl_matrix *A, gsl_matrix *B, const char *obsname,
const char *expname);
int test_beta(gsl_vector *obs, gsl_vector *expected,
gsl_matrix *A, gsl_matrix *B, const char *obsname,
const char *expname);
void test_schur(gsl_matrix *A, gsl_matrix *S, gsl_matrix *Q, gsl_matrix *Z);
void print_vector(const gsl_vector_complex *eval, const char *str);
int cmp(double a, double b);
int compare(const void *a, const void *b);
void sort_complex_vector(gsl_vector_complex *v);
int test_eigenvectors(const gsl_matrix *A, const gsl_matrix *B,
const gsl_vector_complex *alpha,
const gsl_vector *beta,
const gsl_matrix_complex *evec);
gen_workspace *
gen_alloc(size_t n, int compute_schur)
{
gen_workspace *w;
w = (gen_workspace *) calloc(1, sizeof(gen_workspace));
w->gen_p = gsl_eigen_gen_alloc(n);
w->genv_p = gsl_eigen_genv_alloc(n);
w->A = gsl_matrix_alloc(n, n);
w->B = gsl_matrix_alloc(n, n);
w->alpha = gsl_vector_complex_alloc(n);
w->beta = gsl_vector_alloc(n);
w->evals = gsl_vector_complex_alloc(n);
w->Av = gsl_matrix_alloc(n, n);
w->Bv = gsl_matrix_alloc(n, n);
w->alphav = gsl_vector_complex_alloc(n);
w->betav = gsl_vector_alloc(n);
w->evec = gsl_matrix_complex_alloc(n, n);
w->compute_schur = compute_schur;
if (compute_schur)
{
w->Q = gsl_matrix_alloc(n, n);
w->Z = gsl_matrix_alloc(n, n);
gsl_eigen_gen_params(1, 1, 0, w->gen_p);
}
return (w);
} /* gen_alloc() */
void
gen_free(gen_workspace *w)
{
if (w->gen_p)
gsl_eigen_gen_free(w->gen_p);
if (w->genv_p)
gsl_eigen_genv_free(w->genv_p);
if (w->A)
gsl_matrix_free(w->A);
if (w->B)
gsl_matrix_free(w->B);
if (w->alpha)
gsl_vector_complex_free(w->alpha);
if (w->beta)
gsl_vector_free(w->beta);
if (w->evals)
gsl_vector_complex_free(w->evals);
if (w->Av)
gsl_matrix_free(w->Av);
if (w->Bv)
gsl_matrix_free(w->Bv);
if (w->alphav)
gsl_vector_complex_free(w->alphav);
if (w->betav)
gsl_vector_free(w->betav);
if (w->evec)
gsl_matrix_complex_free(w->evec);
if (w->Q)
gsl_matrix_free(w->Q);
if (w->Z)
gsl_matrix_free(w->Z);
free(w);
}
int
gen_proc(gen_workspace *w)
{
int s1, s2, s;
s1 = gsl_eigen_gen_QZ(w->A, w->B, w->alpha, w->beta, w->Q, w->Z, w->gen_p);
s2 = gsl_eigen_genv(w->Av, w->Bv, w->alphav, w->betav, w->evec, w->genv_p);
w->n_evals = w->gen_p->n_evals;
s = 0;
if (s1)
s = s1;
else if (s2)
s = s2;
return s;
} /* gen_proc() */
/**********************************************
* General routines
**********************************************/
void
make_random_matrix(gsl_matrix *m, gsl_rng *r, int lower, int upper)
{
size_t i, j;
size_t N = m->size1;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
gsl_matrix_set(m,
i,
j,
gsl_rng_uniform(r) * (upper - lower) + lower);
}
}
} /* make_random_matrix() */
void
make_random_integer_matrix(gsl_matrix *m, gsl_rng *r, int lower, int upper)
{
size_t i, j;
size_t N = m->size1;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
double a = gsl_rng_uniform(r) * (upper - lower) + lower;
gsl_matrix_set(m, i, j, floor(a));
}
}
} /* make_random_integer_matrix() */
void
make_start_matrix(gsl_matrix *m, int lower)
{
size_t i, j;
size_t N = m->size1;
for (i = 0; i < N; ++i)
for (j = 0; j < N; ++j)
gsl_matrix_set(m, i, j, (double)lower);
} /* make_start_matrix() */
int
inc_matrix (gsl_matrix *m, int lower, int upper)
{
size_t i = 0;
size_t N = m->size1 * m->size2;
int carry = 1;
for (i = 0; carry > 0 && i < N; i++)
{
double v = m->data[i] + carry;
carry = (v > upper) ? 1 : 0;
m->data[i] = (v > upper) ? lower : v;
}
return carry;
} /* inc_matrix() */
void
output_matrix(const gsl_matrix *m)
{
size_t i, j;
size_t N = m->size1;
size_t M = m->size2;
for (i = 0; i < N; ++i)
{
for (j = 0; j < M; ++j)
{
printf("%10.18e%s",
/*printf("%10.18e%s",*/
gsl_matrix_get(m, i, j),
(j < M - 1) ? "," : ";\n");
}
}
}
void
print_matrix(const gsl_matrix *m, const char *str)
{
size_t i, j;
size_t N = m->size1;
size_t M = m->size2;
size_t rows, cols;
size_t r, c;
char buf[100];
/*print_octave(m, str);
return;*/
/*rows = GSL_MIN(15, N);*/
rows = N;
cols = GSL_MIN(15, N);
/*cols = N;*/
for (i = 0; i < N; i += rows)
{
for (j = 0; j < M; j += cols)
{
r = GSL_MIN(rows, N - i);
c = GSL_MIN(cols, N - j);
sprintf(buf, "%s(%u:%u,%u:%u)",
str,
i + 1,
i + r,
j + 1,
j + c);
printf("%s = [\n", buf);
{
gsl_matrix_const_view v = gsl_matrix_const_submatrix(m, i, j, r, c);
output_matrix(&v.matrix);
}
printf("]\n");
}
}
} /* print_matrix() */
int
test_evals(gsl_vector_complex *obs, gsl_vector_complex *expected,
gsl_matrix *A, gsl_matrix *B, const char *obsname,
const char *expname)
{
size_t N = expected->size;
size_t i, k;
double max, max_abserr, max_relerr;
max = 0.0;
max_abserr = 0.0;
max_relerr = 0.0;
k = 0;
for (i = 0; i < N; ++i)
{
gsl_complex z = gsl_vector_complex_get(expected, i);
max = GSL_MAX_DBL(max, gsl_complex_abs(z));
}
for (i = 0; i < N; ++i)
{
gsl_complex z_obs = gsl_vector_complex_get(obs, i);
gsl_complex z_exp = gsl_vector_complex_get(expected, i);
double x_obs = GSL_REAL(z_obs);
double y_obs = GSL_IMAG(z_obs);
double x_exp = GSL_REAL(z_exp);
double y_exp = GSL_IMAG(z_exp);
double abserr_x = fabs(x_obs - x_exp);
double abserr_y = fabs(y_obs - y_exp);
double noise = max * GSL_DBL_EPSILON * N * N;
max_abserr = GSL_MAX_DBL(max_abserr, abserr_x + abserr_y);
if (abserr_x < noise && abserr_y < noise)
continue;
if (abserr_x > 1.0e-6 || abserr_y > 1.0e-6)
++k;
}
if (k)
{
printf("==== CASE %lu ===========================\n\n", count);
print_matrix(A, "A");
print_matrix(B, "B");
printf("=== eval - %s ===\n", expname);
print_vector(expected, expname);
printf("=== eval - %s ===\n", obsname);
print_vector(obs, obsname);
printf("max abserr = %g max relerr = %g\n", max_abserr, max_relerr);
printf("=========================================\n\n");
}
return k;
} /* test_evals() */
/* test if A = Q S Z^t */
void
test_schur(gsl_matrix *A, gsl_matrix *S, gsl_matrix *Q, gsl_matrix *Z)
{
const size_t N = A->size1;
gsl_matrix *T1, *T2;
size_t i, j, k;
double lhs, rhs;
double abserr;
T1 = gsl_matrix_alloc(N, N);
T2 = gsl_matrix_alloc(N, N);
/* compute T1 = S Z^t */
gsl_blas_dgemm(CblasNoTrans,
CblasTrans,
1.0,
S,
Z,
0.0,
T1);
/* compute T2 = Q T1 = Q S Z^t */
gsl_blas_dgemm(CblasNoTrans,
CblasNoTrans,
1.0,
Q,
T1,
0.0,
T2);
k = 0;
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
lhs = gsl_matrix_get(A, i, j);
rhs = gsl_matrix_get(T2, i, j);
abserr = fabs(lhs - rhs);
if (abserr > 1.0e-6)
++k;
}
}
if (k)
{
printf("==== CASE %lu ===========================\n\n", count);
print_matrix(A, "A");
printf("=== Schur Form matrix ===\n");
print_matrix(S, "S");
printf("=== Left Schur matrix ===\n");
print_matrix(Q, "Q");
printf("=== Right Schur matrix ===\n");
print_matrix(Z, "Z");
printf("=== Q S Z^t ===\n");
print_matrix(T1, "Q S Z^t");
printf("=== A - Q S Z^t ===\n");
gsl_matrix_sub(T2, A);
print_matrix(T1, "A - Q S Z^t");
printf("=========================================\n\n");
}
gsl_matrix_free(T1);
gsl_matrix_free(T2);
} /* test_schur() */
void
print_vector(const gsl_vector_complex *eval, const char *str)
{
size_t N = eval->size;
size_t i;
gsl_complex z;
printf("%s = [\n", str);
for (i = 0; i < N; ++i)
{
z = gsl_vector_complex_get(eval, i);
printf("%.18e + %.18ei;\n", GSL_REAL(z), GSL_IMAG(z));
}
printf("]\n");
} /* print_vector() */
int
cmp(double a, double b)
{
return ((a > b) ? 1 : ((a < b) ? -1 : 0));
} /* cmp() */
int
compare(const void *a, const void *b)
{
const double *x = a;
const double *y = b;
int r1 = cmp(y[0], x[0]);
int r2 = cmp(y[1], x[1]);
if (!gsl_finite(x[0]))
return 1;
if (!gsl_finite(y[0]))
return -1;
if (fabs(x[0] - y[0]) < 1.0e-8)
{
/* real parts are very close to each other */
return r2;
}
else
{
return r1 ? r1 : r2;
}
} /* compare() */
void
sort_complex_vector(gsl_vector_complex *v)
{
qsort(v->data, v->size, 2 * sizeof(double), &compare);
} /* sort_complex_vector() */
int
test_eigenvectors(const gsl_matrix *A, const gsl_matrix *B,
const gsl_vector_complex *alpha, const gsl_vector *beta,
const gsl_matrix_complex *evec)
{
const size_t N = A->size1;
size_t i, j;
int k, s;
gsl_matrix_complex *ma, *mb;
gsl_vector_complex *x, *y;
gsl_complex z_one, z_zero;
ma = gsl_matrix_complex_alloc(N, N);
mb = gsl_matrix_complex_alloc(N, N);
y = gsl_vector_complex_alloc(N);
x = gsl_vector_complex_alloc(N);
/* ma <- A, mb <- B */
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
gsl_complex z;
GSL_SET_COMPLEX(&z, gsl_matrix_get(A, i, j), 0.0);
gsl_matrix_complex_set(ma, i, j, z);
GSL_SET_COMPLEX(&z, gsl_matrix_get(B, i, j), 0.0);
gsl_matrix_complex_set(mb, i, j, z);
}
}
GSL_SET_COMPLEX(&z_one, 1.0, 0.0);
GSL_SET_COMPLEX(&z_zero, 0.0, 0.0);
s = 0;
/* check eigenvalues */
for (i = 0; i < N; ++i)
{
gsl_vector_complex_const_view vi = gsl_matrix_complex_const_column(evec, i);
gsl_complex ai = gsl_vector_complex_get(alpha, i);
double bi = gsl_vector_get(beta, i);
double norm = gsl_blas_dznrm2(&vi.vector);
/* check that eigenvector is normalized */
gsl_test_rel(norm, 1.0, N * GSL_DBL_EPSILON, "case %u, normalized",
count);
/* compute x = alpha * B * v */
gsl_blas_zgemv(CblasNoTrans, z_one, mb, &vi.vector, z_zero, x);
gsl_blas_zscal(ai, x);
/* compute y = beta * A v */
gsl_blas_zgemv(CblasNoTrans, z_one, ma, &vi.vector, z_zero, y);
gsl_blas_zdscal(bi, y);
k = 0;
/* now test if y = x */
for (j = 0; j < N; ++j)
{
gsl_complex z;
double lhs_r, lhs_i;
double rhs_r, rhs_i;
z = gsl_vector_complex_get(y, j);
lhs_r = GSL_REAL(z);
lhs_i = GSL_IMAG(z);
z = gsl_vector_complex_get(x, j);
rhs_r = GSL_REAL(z);
rhs_i = GSL_IMAG(z);
if (fabs(lhs_r - rhs_r) > 1e10 * GSL_DBL_EPSILON)
++k;
if (fabs(lhs_i - rhs_i) > 1e10 * GSL_DBL_EPSILON)
++k;
}
if (k)
{
s++;
printf("==== CASE %lu ===========================\n\n", count);
print_matrix(A, "A");
print_matrix(B, "B");
printf("alpha = %.10e + %.10ei\n", GSL_REAL(ai), GSL_IMAG(ai));
printf("beta = %.10e\n", bi);
printf("alpha/beta = %.10e + %.10ei\n", GSL_REAL(ai)/bi, GSL_IMAG(ai)/bi);
print_vector(&vi.vector, "v");
print_vector(y, "beta*A*v");
print_vector(x, "alpha*B*v");
printf("=========================================\n\n");
}
}
gsl_matrix_complex_free(ma);
gsl_matrix_complex_free(mb);
gsl_vector_complex_free(y);
gsl_vector_complex_free(x);
return s;
} /* test_eigenvectors() */
int
main(int argc, char *argv[])
{
gen_workspace *gen_workspace_p;
size_t N;
int c;
int lower;
int upper;
int incremental;
size_t nmat;
gsl_matrix *A, *B;
gsl_rng *r;
int s;
int compute_schur;
size_t i;
gsl_ieee_env_setup();
gsl_rng_env_setup();
/*gsl_set_error_handler_off();*/
N = 30;
lower = -10;
upper = 10;
incremental = 0;
nmat = 0;
compute_schur = 0;
while ((c = getopt(argc, argv, "ic:n:l:u:z")) != (-1))
{
switch (c)
{
case 'i':
incremental = 1;
break;
case 'n':
N = strtol(optarg, NULL, 0);
break;
case 'l':
lower = strtol(optarg, NULL, 0);
break;
case 'u':
upper = strtol(optarg, NULL, 0);
break;
case 'c':
nmat = strtoul(optarg, NULL, 0);
break;
case 'z':
compute_schur = 1;
break;
case '?':
default:
printf("usage: %s [-i] [-z] [-n size] [-l lower-bound] [-u upper-bound] [-c num]\n", argv[0]);
exit(1);
break;
} /* switch (c) */
}
A = gsl_matrix_alloc(N, N);
B = gsl_matrix_alloc(N, N);
gen_workspace_p = gen_alloc(N, compute_schur);
r = gsl_rng_alloc(gsl_rng_default);
if (incremental)
{
make_start_matrix(A, lower);
/* we need B to be non-singular */
make_random_integer_matrix(B, r, lower, upper);
}
fprintf(stderr, "testing N = %d", N);
if (incremental)
fprintf(stderr, " incrementally");
else
fprintf(stderr, " randomly");
fprintf(stderr, " on element range [%d, %d]", lower, upper);
if (compute_schur)
fprintf(stderr, ", with Schur vectors");
fprintf(stderr, "\n");
while (1)
{
if (nmat && (count >= nmat))
break;
++count;
if (!incremental)
{
make_random_matrix(A, r, lower, upper);
make_random_matrix(B, r, lower, upper);
}
else
{
s = inc_matrix(A, lower, upper);
if (s)
break; /* all done */
make_random_integer_matrix(B, r, lower, upper);
}
/*if (count != 23441872)
continue;*/
/* make copies of matrices */
gsl_matrix_memcpy(gen_workspace_p->A, A);
gsl_matrix_memcpy(gen_workspace_p->B, B);
gsl_matrix_memcpy(gen_workspace_p->Av, A);
gsl_matrix_memcpy(gen_workspace_p->Bv, B);
/* compute eigenvalues with GSL */
s = gen_proc(gen_workspace_p);
if (s != GSL_SUCCESS)
{
printf("=========== CASE %lu ============\n", count);
printf("Failed to converge: found %u eigenvalues\n",
gen_workspace_p->n_evals);
print_matrix(A, "A");
print_matrix(B, "B");
print_matrix(gen_workspace_p->Av, "S");
print_matrix(gen_workspace_p->Bv, "T");
continue;
}
/* compute alpha / beta vectors */
for (i = 0; i < N; ++i)
{
double beta = gsl_vector_get(gen_workspace_p->beta, i);
gsl_complex alpha =
gsl_vector_complex_get(gen_workspace_p->alpha, i);
gsl_complex z;
if (!gsl_finite(beta) || !gsl_finite(GSL_REAL(alpha)) ||
!gsl_finite(GSL_IMAG(alpha)))
{
printf("nan/inf in element %u of (alpha,beta): alphar = %g, alphai = %g, beta = %g\n",
i, GSL_REAL(alpha), GSL_IMAG(alpha), beta);
}
if (beta == 0.0)
GSL_SET_COMPLEX(&z, GSL_POSINF, GSL_POSINF);
else
z = gsl_complex_div_real(alpha, beta);
gsl_vector_complex_set(gen_workspace_p->evals, i, z);
}
test_eigenvectors(A,
B,
gen_workspace_p->alphav,
gen_workspace_p->betav,
gen_workspace_p->evec);
if (compute_schur)
{
test_schur(A,
gen_workspace_p->A,
gen_workspace_p->Q,
gen_workspace_p->Z);
test_schur(B,
gen_workspace_p->B,
gen_workspace_p->Q,
gen_workspace_p->Z);
}
}
gsl_matrix_free(A);
gsl_matrix_free(B);
gen_free(gen_workspace_p);
gsl_rng_free(r);
return 0;
} /* main() */
| {
"alphanum_fraction": 0.5365957447,
"avg_line_length": 23.0392156863,
"ext": "c",
"hexsha": "ec24392f5b72fcb5131b526d14fae33eeadffd9a",
"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/eigen/testgen.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/eigen/testgen.c",
"max_line_length": 106,
"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/eigen/testgen.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": 5601,
"size": 18800
} |
#include <assert.h>
#include <cblas.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "cnn_calc.h"
#include "cnn_init.h"
#include "cnn_private.h"
inline void cnn_restrict(float* mat, int size, float limit)
{
for (int __i = 0; __i < size; __i++)
{
mat[__i] = fminf(mat[__i], limit);
}
}
void cnn_mat_update(struct CNN_MAT* matPtr, float lRate, float limit)
{
int size = matPtr->rows * matPtr->cols;
// Limit gradient and update weight
#ifdef CNN_WITH_CUDA
cnn_fminf_gpu(matPtr->grad, matPtr->grad, size, limit);
cublasSaxpy(cnnInit.blasHandle, size, &lRate, matPtr->grad, 1, matPtr->mat,
1);
#else
cnn_restrict(matPtr->grad, size, limit);
cblas_saxpy(size, lRate, matPtr->grad, 1, matPtr->mat, 1);
#endif
// Clear gradient
#ifdef CNN_WITH_CUDA
cudaMemset
#else
memset
#endif
(matPtr->grad, 0, size * sizeof(float));
}
void cnn_update(cnn_t cnn, float lRate, float gradLimit)
{
int i;
struct CNN_CONFIG* cfgRef;
union CNN_LAYER* layerRef;
// Set reference
layerRef = cnn->layerList;
cfgRef = &cnn->cfg;
// Update network and clear gradient
for (i = cfgRef->layers - 1; i > 0; i--)
{
// Clear layer gradient
#ifdef CNN_WITH_CUDA
cudaMemset
#else
memset
#endif
(layerRef[i].outMat.data.grad, 0,
sizeof(float) * layerRef[i].outMat.data.rows *
layerRef[i].outMat.data.cols);
switch (cfgRef->layerCfg[i].type)
{
// Fully connected
case CNN_LAYER_FC:
cnn_mat_update(&layerRef[i].fc.weight, lRate, gradLimit);
cnn_mat_update(&layerRef[i].fc.bias, lRate, gradLimit);
break;
// Convolution
case CNN_LAYER_CONV:
cnn_mat_update(&layerRef[i].conv.kernel, lRate, gradLimit);
#if defined(CNN_CONV_BIAS_FILTER) || defined(CNN_CONV_BIAS_LAYER)
cnn_mat_update(&layerRef[i].conv.bias, lRate, gradLimit);
#endif
break;
// Batch normalization
case CNN_LAYER_BN:
cnn_mat_update(&layerRef[i].bn.bnScale, lRate, gradLimit);
cnn_mat_update(&layerRef[i].bn.bnBias, lRate, gradLimit);
break;
case CNN_LAYER_INPUT:
case CNN_LAYER_ACTIV:
case CNN_LAYER_POOL:
case CNN_LAYER_DROP:
break;
}
}
}
static inline void cnn_backward_kernel(cnn_t cnn, float* errGrad)
{
int i;
struct CNN_CONFIG* cfgRef;
union CNN_LAYER* layerRef;
// Set reference
layerRef = cnn->layerList;
cfgRef = &cnn->cfg;
// Backpropagation
for (i = cfgRef->layers - 1; i > 0; i--)
{
switch (cfgRef->layerCfg[i].type)
{
// Fully connected
case CNN_LAYER_FC:
cnn_backward_fc(layerRef, cfgRef, i);
break;
// Activation function
case CNN_LAYER_ACTIV:
cnn_backward_activ(layerRef, cfgRef, i);
break;
// Convolution
case CNN_LAYER_CONV:
cnn_backward_conv(layerRef, cfgRef, i);
break;
// Pooling
case CNN_LAYER_POOL:
cnn_backward_pool(layerRef, cfgRef, i);
break;
// Dropout
case CNN_LAYER_DROP:
cnn_backward_drop(layerRef, cfgRef, i);
break;
// Batch normalization
case CNN_LAYER_BN:
cnn_backward_bn(layerRef, cfgRef, i);
break;
default:
assert(!"Invalid layer type");
}
}
}
void cnn_backward(cnn_t cnn, float* errGrad)
{
int size;
struct CNN_CONFIG* cfgRef;
union CNN_LAYER* layerRef;
// Set reference
layerRef = cnn->layerList;
cfgRef = &cnn->cfg;
// Copy gradient vector
size = sizeof(float) * layerRef[cfgRef->layers - 1].outMat.data.rows *
layerRef[cfgRef->layers - 1].outMat.data.cols;
#ifdef CNN_WITH_CUDA
cudaMemcpy(layerRef[cfgRef->layers - 1].outMat.data.grad, errGrad, size,
cudaMemcpyHostToDevice);
#else
memcpy(layerRef[cfgRef->layers - 1].outMat.data.grad, errGrad, size);
#endif
// Backpropagation
cnn_backward_kernel(cnn, errGrad);
}
#ifdef CNN_WITH_CUDA
void cnn_backward_gpu(cnn_t cnn, float* errGrad)
{
int size;
struct CNN_CONFIG* cfgRef;
union CNN_LAYER* layerRef;
// Set reference
layerRef = cnn->layerList;
cfgRef = &cnn->cfg;
// Copy gradient vector
size = sizeof(float) * layerRef[cfgRef->layers - 1].outMat.data.rows *
layerRef[cfgRef->layers - 1].outMat.data.cols;
cudaMemcpy(layerRef[cfgRef->layers - 1].outMat.data.grad, errGrad, size,
cudaMemcpyDeviceToDevice);
// Backpropagation
cnn_backward_kernel(cnn, errGrad);
}
#endif
static inline void cnn_forward_kernel(cnn_t cnn, float* inputMat,
float* outputMat)
{
int i;
struct CNN_CONFIG* cfgRef;
union CNN_LAYER* layerRef;
// Set reference
layerRef = cnn->layerList;
cfgRef = &cnn->cfg;
// Forward computation
for (i = 1; i < cfgRef->layers; i++)
{
switch (cfgRef->layerCfg[i].type)
{
// Fully connected
case CNN_LAYER_FC:
cnn_forward_fc(layerRef, cfgRef, i);
break;
// Activation function
case CNN_LAYER_ACTIV:
cnn_forward_activ(layerRef, cfgRef, i);
break;
// Convolution
case CNN_LAYER_CONV:
cnn_forward_conv(layerRef, cfgRef, i);
break;
// Pooling
case CNN_LAYER_POOL:
cnn_forward_pool(layerRef, cfgRef, i);
break;
// Dropout
case CNN_LAYER_DROP:
if (cnn->opMode == CNN_OPMODE_TRAIN)
{
cnn_forward_drop(layerRef, cfgRef, i);
}
else
{
cnn_recall_drop(layerRef, cfgRef, i);
}
break;
// Batch normalization
case CNN_LAYER_BN:
if (cnn->opMode == CNN_OPMODE_TRAIN)
{
cnn_forward_bn(layerRef, cfgRef, i);
}
else
{
cnn_recall_bn(layerRef, cfgRef, i);
}
break;
default:
assert(!"Invalid layer type");
}
}
}
void cnn_forward(cnn_t cnn, float* inputMat, float* outputMat)
{
int size;
struct CNN_CONFIG* cfgRef;
union CNN_LAYER* layerRef;
// Set reference
layerRef = cnn->layerList;
cfgRef = &cnn->cfg;
// Copy input
size = sizeof(float) * layerRef[0].outMat.data.rows *
layerRef[0].outMat.data.cols;
#ifdef CNN_WITH_CUDA
cudaMemcpy(layerRef[0].outMat.data.mat, inputMat, size,
cudaMemcpyHostToDevice);
#else
memcpy(layerRef[0].outMat.data.mat, inputMat, size);
#endif
// Forward computation
cnn_forward_kernel(cnn, inputMat, outputMat);
// Copy output
if (outputMat != NULL)
{
size = sizeof(float) * layerRef[cfgRef->layers - 1].outMat.data.rows *
layerRef[cfgRef->layers - 1].outMat.data.cols;
#ifdef CNN_WITH_CUDA
cudaMemcpy(outputMat, layerRef[cfgRef->layers - 1].outMat.data.mat,
size, cudaMemcpyDeviceToHost);
#else
memcpy(outputMat, layerRef[cfgRef->layers - 1].outMat.data.mat, size);
#endif
}
#ifdef CNN_WITH_CUDA
else
{
cudaDeviceSynchronize();
}
#endif
}
#ifdef CNN_WITH_CUDA
void cnn_forward_gpu(cnn_t cnn, float* inputMat, float* outputMat)
{
int size;
struct CNN_CONFIG* cfgRef;
union CNN_LAYER* layerRef;
// Set reference
layerRef = cnn->layerList;
cfgRef = &cnn->cfg;
// Copy input
size = sizeof(float) * layerRef[0].outMat.data.rows *
layerRef[0].outMat.data.cols;
cudaMemcpy(layerRef[0].outMat.data.mat, inputMat, size,
cudaMemcpyDeviceToDevice);
// Forward computation
cnn_forward_kernel(cnn, inputMat, outputMat);
// Copy output
if (outputMat != NULL)
{
size = sizeof(float) * layerRef[cfgRef->layers - 1].outMat.data.rows *
layerRef[cfgRef->layers - 1].outMat.data.cols;
cudaMemcpy(outputMat, layerRef[cfgRef->layers - 1].outMat.data.mat,
size, cudaMemcpyDeviceToDevice);
}
else
{
cudaDeviceSynchronize();
}
}
#endif
| {
"alphanum_fraction": 0.5670337155,
"avg_line_length": 25.4595375723,
"ext": "c",
"hexsha": "2e4dc5a6d1518a14487dccadfce3dab53f21e15b",
"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": "8ba35edd4516f6b46a17a1bad672e38667600630",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jamesljlster/cnn",
"max_forks_repo_path": "src/cnn_calc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630",
"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": "jamesljlster/cnn",
"max_issues_repo_path": "src/cnn_calc.c",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8ba35edd4516f6b46a17a1bad672e38667600630",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jamesljlster/cnn",
"max_stars_repo_path": "src/cnn_calc.c",
"max_stars_repo_stars_event_max_datetime": "2020-06-15T07:47:10.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-15T07:47:10.000Z",
"num_tokens": 2164,
"size": 8809
} |
#pragma once
#include <gsl\gsl>
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include <map>
#include "DrawableGameComponent.h"
#include "FullScreenRenderTarget.h"
#include "FullScreenQuad.h"
namespace Library
{
class Texture2D;
}
namespace Rendering
{
enum class DistortionMaps
{
Glass,
Text,
NoDistortion,
End
};
class DiffuseLightingDemo;
class DistortionMappingDemo final : public Library::DrawableGameComponent
{
public:
DistortionMappingDemo(Library::Game& game, const std::shared_ptr<Library::Camera>& camera);
DistortionMappingDemo(const DistortionMappingDemo&) = delete;
DistortionMappingDemo(DistortionMappingDemo&&) = default;
DistortionMappingDemo& operator=(const DistortionMappingDemo&) = default;
DistortionMappingDemo& operator=(DistortionMappingDemo&&) = default;
~DistortionMappingDemo();
std::shared_ptr<DiffuseLightingDemo> DiffuseLighting() const;
float DisplacementScale() const;
void SetDisplacementScale(float displacementScale);
DistortionMaps DistortionMap() const;
const std::string& DistortionMapString() const;
void SetDistortionMap(DistortionMaps distortionMap);
virtual void Initialize() override;
virtual void Update(const Library::GameTime& gameTime) override;
virtual void Draw(const Library::GameTime& gameTime) override;
private:
static const std::map<DistortionMaps, std::string> DistortionMapNames;
struct PixelCBufferPerObject
{
float DisplacementScale{ 1.0f };
DirectX::XMFLOAT3 Padding{ 0.0f, 0.0f, 0.0f };
};
std::shared_ptr<DiffuseLightingDemo> mDiffuseLightingDemo;
Library::FullScreenRenderTarget mRenderTarget;
Library::FullScreenQuad mFullScreenQuad;
winrt::com_ptr<ID3D11Buffer> mPixelCBufferPerObject;
PixelCBufferPerObject mPixelCBufferPerObjectData;
std::map<DistortionMaps, std::shared_ptr<Library::Texture2D>> mDistortionMaps;
DistortionMaps mActiveDistortionMap{ DistortionMaps::Glass };
};
} | {
"alphanum_fraction": 0.7816504357,
"avg_line_length": 28.6911764706,
"ext": "h",
"hexsha": "bc916c2582f79b524795313a4eb1bd0c13791ae3",
"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": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_forks_repo_path": "source/7.4_Distortion_Mapping/DistortionMappingDemo.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"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": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_issues_repo_path": "source/7.4_Distortion_Mapping/DistortionMappingDemo.h",
"max_line_length": 93,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_stars_repo_path": "source/7.4_Distortion_Mapping/DistortionMappingDemo.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 521,
"size": 1951
} |
/*--------------------------------------------------------------------
* $Id$
*
* This file is part of libRadtran.
* Copyright (c) 1997-2012 by Arve Kylling, Bernhard Mayer,
* Claudia Emde, Robert Buras
*
* ######### Contact info: http://www.libradtran.org #########
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*--------------------------------------------------------------------*/
/* 03.04.2002: Fixed problem with finding correct grid cell for direct beam, AKy. */
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#ifndef _AIX
#include <getopt.h>
#else
#include <unistd.h>
#endif
#if HAVE_LIBGSL
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_plain.h>
#include <gsl/gsl_monte_miser.h>
#include <gsl/gsl_monte_vegas.h>
#endif
#include "ascii.h"
#define PROGRAM "angres"
#define VERSION "0.3"
#define DATE "3 Feb, 2003"
#define DIM_ANG_INT 2 /* Integration to be made over 2 dimensions */
#ifndef PI
#define PI 3.14159265358979323846264338327
#endif
typedef struct {
int nphi;
int numu;
double* umu;
double* phi;
double** prod;
} mcinput;
/*************************************************************/
/* print usage information */
/*************************************************************/
/*
Documentation in latex for the User's Guide. Extracted by sdoc2.awk
and input in the doc/tools.tex.
*/
/*
<lpdoc>
\subsection{Angular response and tilted surfaces - \codeidx{angres}}
The \code{angres} tool takes a precalculated radiance field and integrates
it over a given angular area using any angular response. Typical usages of
\code{angres} are calculation of radiation on tilted surfaces and estimation
of effects of imperfect angular response functions.
The \code{angres} tool is invoked as follows:
\begin{Verbatim}[fontsize=\footnotesize]
angres angres_file raddis_file
\end{Verbatim}
The two required input files will be read by the \code{angres} tool.
\begin{description}
\item[angres\_file] is a two column file with the first column holding
the angle and the second column the angular response, e.g. a
measured cosine response. To generate standard angular response
function see the \code{make\_angres\_func} tool.
\item[raddis\_file] holds the radiance distribution as output from uvspec
with the disort solvers for one single wavelength.
\end{description}
After reading the two input files the angular response will be tilted
and rotated if specified with the \code{-t} and \code{-r} options respectively. Finally
the product of the resulting angular response and radiance distribution
field are integrated using Monte Carlo methods to yield the effective
response. The integration is done for the diffuse radiation field only. To
include the direct contribution the -s and -z options must be set to give
the direction of the sun.
Output is 3 numbers:
\begin{enumerate}
\item The integral of the diffuse radiation field times angular response.
\item Estimated absolute error of the above integral.
\item The integral of the diffuse+direct radiation field times angular response
(requires that \code{-s} and \code{-z} are specified, otherwise same as first number
\end{enumerate}
The angles in the \file{angres\_file} must be in radians if not
the \code{-a} option is used. The \file{raddis\_file} must contain
output from \code{uvspec} run for one single wavelength with one of
the disort solvers and with \code{phi} and \code{umu} set.
Note that the angles in the \file{angres\_file} must follow the same
conventions as for the disort algorithm. This is different from
that typically used when reporting measurements of the angular response.
The \code{angres} tool accepts the following command line options:
\begin{description}
\item[-h] show this page.
\item[-c] number of random points used for Monte Carlo integration.
\item[-i] The diffuse radiation is assumed to be isotropic.
\item[-a] angular response angle given in degrees and not cosine of angle.
\item[-r] rotation angle in degrees.
\item[-t] tilt angle in degrees.
\item[-s] solar zenith angle in degrees.
\item[-z] solar azimuth angle in degrees.
\item[-p] pgm files are made of the angular response before
and after tilt and rotate.
\end{description}
Sample \code{angres} input and output files are found in the \file{examples} directory.
The following
\begin{Verbatim}[fontsize=\footnotesize]
angres examples/ANGRES_1_ANG.DAT \
examples/ANGRES_RADDIS_1.DAT -a -t -r 0 -s 32 -z 0
\end{Verbatim}
calculates the radiation on a horisontal surface given the angular response
in \file{examples/ANGRES_1_ANG.DAT}. The input used to calculate the radiance file is
given in the start of \file{examples/ANGRES_RADDIS_1.DAT}.
An example of the use of \code{angres} together with \code{uvspec} is given in
\citet[section 4.6]{mayer2005}.
</lpdoc>
*/
static void print_usage (char* filename) {
fprintf (stderr, "%s - %s \n\n", PROGRAM, VERSION);
fprintf (stderr, "written by Arve Kylling,\n");
fprintf (stderr, " Norwegian Institute for Air Research (NILU)\n");
fprintf (stderr, " P.O. Box 100, 2027 Kjeller, Norway\n");
fprintf (stderr, "Version %s finished %s\n\n", VERSION, DATE);
fprintf (stderr, "Be aware that this program is a beta version! Please report any\n");
fprintf (stderr, "kind of error to the author, including the error message and the\n");
fprintf (stderr, "database being processed when the error occured. Thanks!\n\n");
fprintf (stderr, "USAGE: %s [options] angres_file raddis_file \n\n", filename);
fprintf (stderr, "%s will read the two required input files:\n", PROGRAM);
fprintf (stderr, " angres_file is a two column file with the first column holding\n");
fprintf (stderr, " the angle and the second column the angular response, e.g. a\n");
fprintf (stderr, " measured cosine response.\n");
fprintf (stderr, " raddis_file holds the radiance distribution as output from uvspec\n");
fprintf (stderr, " with the disort solvers for one single wavelength.\n");
fprintf (stderr, "After reading the two input files the angular response will be tilted\n");
fprintf (stderr, "and rotated if specified with the -t and -r options respectively. Finally\n");
fprintf (stderr, "the product of the resulting angular response and radiance distribution\n");
fprintf (stderr, "field are integrated using Monte Carlo methods to yield the effective\n");
fprintf (stderr, "response. The integration is done for the diffuse radiation field only. To\n");
fprintf (stderr, "include the direct contribution the -s and -z options must be set to give\n");
fprintf (stderr, "the direction of the sun. \n");
fprintf (stderr, "\n");
fprintf (stderr, "Output is 3 numbers:\n");
fprintf (stderr, " 1: The integral of the diffuse radiation field times angular response.\n");
fprintf (stderr, " 2: Estimated absolute error of the above integral.\n");
fprintf (stderr, " 3: The integral of the diffuse+direct radiation field times angular response\n");
fprintf (stderr, " (requires that -s and -z are specified, otherwise same as 1).\n");
fprintf (stderr, "\n");
fprintf (stderr, "The angles in the angres_file must be in radians if not\n");
fprintf (stderr, "the -a option is used. The raddis_file must contain\n");
fprintf (stderr, "output from uvspec run for one single wavelength with one of\n");
fprintf (stderr, "the disort solvers and with phi and umu set.\n");
fprintf (stderr, "Note that the angles in the angres_file must follow the same\n");
fprintf (stderr, "conventions as for the disort algorithm. This is different from\n");
fprintf (stderr, "that typically used when reporting measurements of the angular response.\n");
fprintf (stderr, "\n");
fprintf (stderr, " command line options:\n");
fprintf (stderr, " -h show this page\n");
fprintf (stderr, " -c number of random points used for Monte Carlo integration\n");
fprintf (stderr, " -i The diffuse radiation is assumed to be isotropic\n");
fprintf (stderr, " -a angular response angle given in degrees and not cosine of angle\n");
fprintf (stderr, " -r rotation angle in degrees\n");
fprintf (stderr, " -t tilt angle in degrees\n");
fprintf (stderr, " -s solar zenith angle in degrees\n");
fprintf (stderr, " -z solar azimuth angle in degrees\n");
fprintf (stderr, " -p pgm files are made of the angular response before\n");
fprintf (stderr, " and after tilt and rotate\n");
}
static int get_options (int argc,
char** argv,
char* programname,
char* angresfilename,
char* raddisfilename,
int* pgm,
int* dev,
int* ang,
size_t* calls,
double* sza,
double* phi0,
double* theta_t,
double* phi_r,
int* incdir,
int* isotropic) {
int c = 0;
/* default settings */
/* save name of program */
strncpy (programname, argv[0], FILENAME_MAX - 1);
while ((c = getopt (argc, argv, "ahipc:d:s:t:r:z:")) != EOF) {
switch (c) {
case 'h': /* help */
print_usage (programname);
return (-1);
break;
case 'd':
*dev = atoi (optarg);
break;
case 'a':
*ang = 1;
break;
case 'i':
*isotropic = 1;
break;
case 'p':
*pgm = 1;
break;
case 'c':
*calls = atoi (optarg);
break;
case 'r':
*phi_r = atof (optarg);
break;
case 's':
*sza = atof (optarg);
*incdir = 1;
break;
case 'z':
*phi0 = atof (optarg);
*incdir = 1;
break;
case 't':
*theta_t = atof (optarg);
break;
case '?':
print_usage (programname);
return (-1);
break;
default:
print_usage (programname);
return (-1);
}
}
/* check number of remaining command line arguments */
if (argc - optind != 2) {
print_usage (programname);
return -1;
}
/* save command line arguments */
strncpy (angresfilename, argv[optind + 0], FILENAME_MAX - 1);
strncpy (raddisfilename, argv[optind + 1], FILENAME_MAX - 1);
return 0; /* if o.k. */
}
double**
tilt_and_rotate (double* aangres, int nphi, double* phi, int numu, double* umu, int pgm, double theta_t, double phi_r, int dev) {
int status = 0, i = 0, j = 0, k = 0, it = 0, jt = 0, ia = 0, ja = 0, nt;
/* double umu_t; */
double theta = 0, x = 0, y = 0, z = 0, xp = 0, yp = 0, zp = 0, r = 0;
double a11, a12, a13, a21, a22, a23, a31, a32, a33;
double rn = 0, theta_n = 0, phi_n = 0;
double **angres = NULL, **angrestilted = NULL;
double** angresindcnt = NULL;
double delphirad = 0;
FILE* pgmfile = NULL;
/* allocate memory for the angular response function and the tilted and rotated one */
status = ASCII_calloc_double (&angres, numu, nphi);
if (status != 0) {
fprintf (stderr, "tilt_and_rotate: error allocating memory for angular response function\n");
/* return status; */
}
status = ASCII_calloc_double (&angrestilted, numu, nphi);
if (status != 0) {
fprintf (stderr, "tilt_and_rotate: error allocating memory for angular response function\n");
/* return status; */
}
status = ASCII_calloc_double (&angresindcnt, numu, nphi);
if (status != 0) {
fprintf (stderr, "tilt_and_rotate: error allocating memory for angular response function\n");
/* return status; */
}
/* The read angular response is assumed to have no azimuth dependence, */
/* hence it is the same for all phi */
for (i = 0; i < numu; i++)
for (j = 0; j < nphi; j++)
angres[i][j] = aangres[i];
if (pgm) {
if ((pgmfile = fopen ("angres_orginal.pgm", "w")) == NULL) {
fprintf (stderr, "Error opening angres_orginal.pgm for writing\n");
return NULL;
}
fprintf (pgmfile, "P2\n");
fprintf (pgmfile, "%d %d\n", nphi, numu);
fprintf (pgmfile, "256\n");
for (i = 0; i < numu; i++) {
for (j = 0; j < nphi; j++) {
k = (int)(angres[i][j] * 256);
fprintf (pgmfile, "%d\n", k);
}
}
fclose (pgmfile);
}
if (dev == 1)
fprintf (stdout, "Tilt: %f Rotate: %f\n", theta_t, phi_r);
/* commented out by RB, because was not used but caused compiler warnings */
/* umu_t = cos(theta_t*PI/180.0); */
/* Rotation matrix. */
/* Eq 4-47., p. 147, Goldstein, Classical Mechanics. psi=0 for our purposes */
/* a11 = cos(phi_r*PI/180.0); */
/* a12 = -cos(theta_t*PI/180.0)*sin(phi_r*PI/180.0); */
/* a13 = sin(theta_t*PI/180.0)*sin(phi_r*PI/180.0); */
/* a21 = sin(phi_r*PI/180.0); */
/* a22 = cos(theta_t*PI/180.0)*cos(phi_r*PI/180.0); */
/* a23 = -sin(theta_t*PI/180.0)*cos(phi_r*PI/180.0); */
/* a31 = 0; */
/* a32 = sin(theta_t*PI/180.0); */
/* a33 = cos(theta_t*PI/180.0); */
/* First only tilt */
a11 = 1;
a12 = 0;
a13 = 0;
a21 = 0;
a22 = cos (theta_t * PI / 180.0);
a23 = -sin (theta_t * PI / 180.0);
a31 = 0;
a32 = sin (theta_t * PI / 180.0);
a33 = cos (theta_t * PI / 180.0);
if (dev == 1) {
printf ("a11: %7.3f, a12: %7.3f a13: %7.3f\n", a11, a12, a13);
printf ("a21: %7.3f, a22: %7.3f a23: %7.3f\n", a21, a22, a23);
printf ("a31: %7.3f, a32: %7.3f a33: %7.3f\n", a31, a32, a33);
}
if (dev == 1)
fprintf (stdout, "Tilt: %f Rotate: %f\n", theta_t, phi_r);
/* First tilt the angular response */
for (i = 0; i < numu; i++) {
theta = acos (umu[i]);
for (j = 0; j < nphi; j++) {
rn = 1;
xp = rn * cos (phi[j] * PI / 180) * sin (theta);
yp = rn * sin (phi[j] * PI / 180) * sin (theta);
zp = rn * cos (theta);
if (dev == 1) {
printf ("\nxp: %7.3f, yp: %7.3f zp: %7.3f theta: %7.4f phi: %5.1f r: %6.3f umu: %f\n",
xp,
yp,
zp,
theta,
phi[j],
r,
umu[i]);
}
if (dev == 1)
fprintf (stdout, "Tilt: %f Rotate: %f\n", theta_t, phi_r);
x = a11 * xp + a12 * yp + a13 * zp;
y = a21 * xp + a22 * yp + a23 * zp;
z = a31 * xp + a32 * yp + a33 * zp;
rn = sqrt (x * x + y * y + z * z);
if (rn > 0)
theta_n = acos (z / rn);
else
theta_n = 0;
if (rn > 0) {
phi_n = acos (x / (rn * sin (theta_n)));
} else {
phi_n = 0;
}
if (dev == 1) {
printf ("x: %7.3f, y: %7.3f z: %7.3f theta: %7.4f phi: %5.1f\n", x, y, z, theta * 180 / PI, phi[j]);
printf ("rn: %7.3f, theta_n: %7.4f phi_n: %5.1f phi_r: %f\n", rn, theta_n * 180 / PI, phi_n * 180 / PI, phi_r);
}
if (dev == 1)
fprintf (stdout, "Tilt: %f Rotate: %f\n", theta_t, phi_r);
it = 0;
ia = 1;
while ((theta_n * 180 / PI - acos (umu[ia++]) * 180 / PI) < 0 && ia < numu)
;
it = ia - 1; /* This one is fun:-) */
/* Make sure we get the closest grid point */
if (fabs (acos (umu[it]) * 180 / PI - theta_n * 180 / PI) > fabs (acos (umu[it - 1]) * 180 / PI - theta_n * 180 / PI))
it = it - 1;
jt = 0;
ja = 0;
delphirad = fabs (phi[1] - phi[0]) * PI / 180;
while (fabs (phi_n - phi[ja++] * PI / 180) > delphirad) {
if (dev == 1) {
printf ("%d %d %d %f %f %f %f\n",
j,
ja,
jt,
phi_n,
phi[ja - 1] * PI / 180,
fabs (phi_n - phi[ja - 1] * PI / 180),
delphirad);
}
}
jt = ja - 1;
angrestilted[i][j] = angres[it][jt];
}
}
/* Now we rotate */
nt = (phi_r * PI / 180) / delphirad;
if (jt >= nphi)
jt -= nphi;
for (i = 0; i < numu; i++) {
theta = acos (umu[i]);
for (j = 0; j < nphi; j++) {
jt = j + nt;
if (jt >= nphi)
jt -= nphi;
if (dev == 1 || dev == 10)
fprintf (stdout,
"%3d %3d nt: %d %3d jt: %3d %3d, nphi: %d, phi_r: %5.1f %3.1f\n",
i,
j,
nt,
it,
jt,
ja - 1,
nphi,
phi_r,
angres[it][jt]);
angres[i][j] = angrestilted[i][jt];
if (dev == 1) {
printf ("angrestilted: %7.4f %7.4f %7.4f\n", acos (umu[it]) * 180 / PI, phi[jt], angrestilted[i][j]);
}
}
}
if (pgm) {
if ((pgmfile = fopen ("angres_tilted.pgm", "w")) == NULL) {
fprintf (stderr, "Error opening angres_tilted.pgm for writing\n");
return NULL;
}
fprintf (pgmfile, "P2\n");
fprintf (pgmfile, "%d %d\n", nphi, numu);
fprintf (pgmfile, "256\n");
for (i = 0; i < numu; i++) {
for (j = 0; j < nphi; j++) {
k = (int)(angres[i][j] * 256);
fprintf (pgmfile, "%d\n", k);
}
}
fclose (pgmfile);
}
return angres;
}
double linpol (double x1, double x2, double y1, double y2, double x) {
/* Linearly interpolate between two points to get wanted y value for x. */
double y;
double a = 0, b = 0;
if (x2 > 0 && x1 > 0 && fabs (x2 - x1) < 0.0000001) {
y = y1;
} else {
a = (y2 - y1) / (x2 - x1);
b = y1 - a * x1;
y = a * x + b;
}
return y;
}
double mc_func (double* k, size_t dim, void* params) {
int i1 = 0, i2 = 0, j1 = 0, j2 = 0;
double p1, p2, p3;
double umu = 0, phi = 0;
mcinput lmcinp;
lmcinp = *(mcinput*)params;
umu = k[0];
phi = k[1];
i2 = 0;
while (umu > lmcinp.umu[i2++])
;
i1 = i2 - 1;
if (i2 == 0) {
i2 = 1;
i1 = 0;
}
if (i2 >= lmcinp.numu) {
i2 = lmcinp.numu - 1;
i1 = i2 - 1;
}
j2 = 0;
while (phi > lmcinp.phi[j2++])
;
j1 = j2 - 1;
if (j2 == 0) {
j2 = 1;
j1 = 0;
}
if (j2 >= lmcinp.nphi) {
j2 = lmcinp.nphi - 1;
j1 = j2 - 1;
}
p1 = linpol (lmcinp.phi[j1], lmcinp.phi[j2], lmcinp.prod[i1][j1], lmcinp.prod[i1][j2], phi);
p2 = linpol (lmcinp.phi[j1], lmcinp.phi[j2], lmcinp.prod[i2][j1], lmcinp.prod[i2][j2], phi);
p3 = linpol (lmcinp.umu[i1], lmcinp.umu[i2], p1, p2, umu);
return p3;
}
double mc_funciso (double* k, size_t dim, void* params) {
int i1 = 0, i2 = 0, j1 = 0, j2 = 0;
double p1, p2, p3;
double umu = 0, phi = 0;
mcinput lmcinp;
lmcinp = *(mcinput*)params;
umu = k[0];
phi = k[1];
i2 = 0;
while (umu > lmcinp.umu[i2++])
;
i1 = i2 - 1;
if (i2 == 0) {
i2 = 1;
i1 = 0;
}
if (i2 >= lmcinp.numu) {
i2 = lmcinp.numu - 1;
i1 = i2 - 1;
}
j2 = 0;
while (phi > lmcinp.phi[j2++])
;
j1 = j2 - 1;
if (j2 == 0) {
j2 = 1;
j1 = 0;
}
if (j2 >= lmcinp.nphi) {
j2 = lmcinp.nphi - 1;
j1 = j2 - 1;
}
p1 = linpol (lmcinp.phi[j1], lmcinp.phi[j2], lmcinp.prod[i1][j1], lmcinp.prod[i1][j2], phi);
p2 = linpol (lmcinp.phi[j1], lmcinp.phi[j2], lmcinp.prod[i2][j1], lmcinp.prod[i2][j2], phi);
p3 = linpol (lmcinp.umu[i1], lmcinp.umu[i2], p1, p2, umu);
return p3;
}
int main (int argc, char** argv) {
int i = 0, j = 0, k = 0, status = 0, pgm = 0, dev = 0, ang = 0, incdir = 0, isotropic = 0;
int ia = 0, it = 0, ja = 0, jt = 0;
double delphirad = 0, dir = 0;
char programname[FILENAME_MAX] = "";
char angresfilename[FILENAME_MAX] = ""; /* File holding angular response */
char raddisfilename[FILENAME_MAX] = ""; /* File holding radiance distribution */
double *phi = NULL, *rphi = NULL, *aumu = NULL, *rumu = NULL, *aangres = NULL;
double theta_t = 0, phi_r = 0, sza = 0, phi0 = 0, max = 0;
double dphi = 0, dtheta = 0, tmpprod = 0;
double uavgso;
/* commented out by RB, because was not used but caused compiler warnings */
/* double rfldir, rfldn, flup, uavgso, uavgdn, uavgup; */
int arows = 0, amin_columns = 0, amax_columns = 0; /* Angular response file */
int rrows = 0, rmin_columns = 0, rmax_columns = 0; /* Radiance distribution file */
int nphi = 0, numu = 0;
mcinput mcinp;
/* void *pmcinp; */
mcinput mcinpiso;
/* void *pmcinpiso; */
double **angres = NULL, **avalue = NULL, **rvalue = NULL, **raddis = NULL, **prod = NULL;
FILE* pgmfile = NULL;
/* Monte Carlo integration stuff */
double res = 0, err = 0;
double xl[DIM_ANG_INT];
double xu[DIM_ANG_INT];
/* size_t calls = 10; */
size_t calls = 5000000;
#if HAVE_LIBGSL
const gsl_rng_type* T;
const gsl_rng_type* Tiso;
gsl_rng* r;
gsl_rng* riso;
gsl_monte_function G = {&mc_func, DIM_ANG_INT, &mcinp};
gsl_monte_function Giso = {&mc_funciso, DIM_ANG_INT, &mcinpiso};
gsl_monte_plain_state* s = gsl_monte_plain_alloc (DIM_ANG_INT);
gsl_monte_plain_state* siso = gsl_monte_plain_alloc (DIM_ANG_INT);
#endif
/* commented out by RB, because was not used but caused compiler warnings */
/* pmcinp = &mcinp; */
/* pmcinpiso = &mcinpiso; */
/* get command line options */
status = get_options (argc,
argv,
programname,
angresfilename,
raddisfilename,
&pgm,
&dev,
&ang,
&calls,
&sza,
&phi0,
&theta_t,
&phi_r,
&incdir,
&isotropic);
if (status != 0)
return status;
#if !HAVE_LIBGSL
fprintf (stderr, "%s was built without the gsl-library. Thus NO SUPPORT\n", programname);
fprintf (stderr, "for integration of product of angular response and radiance field.\n");
#endif
/* read angular response file */
status = ASCII_file2double (angresfilename, &arows, &amax_columns, &amin_columns, &avalue);
if (status != 0) {
fprintf (stderr, "error %d reading input file %s\n", status, angresfilename);
return status;
}
if (amin_columns < 2) {
fprintf (stderr, "error, input file must have at least two columns\n");
return -1;
}
if (amin_columns != amax_columns) {
fprintf (stderr, " WARNING! %s is not a rectangular matrix; only the first\n", angresfilename);
fprintf (stderr, " %d columns will be used for the analysis\n", amin_columns);
}
numu = arows;
/* Read radiance field file */
status = ASCII_file2double (raddisfilename, &rrows, &rmax_columns, &rmin_columns, &rvalue);
if (status != 0) {
fprintf (stderr, "error %d reading input file %s\n", status, raddisfilename);
return status;
}
/* Get umu and phi from radiance field */
rphi = ASCII_row (rvalue, rmax_columns, 1);
j = 0;
for (i = 0; i < rmax_columns; i++) {
if (rphi[i] >= 0) {
nphi++;
}
}
phi = (double*)calloc (nphi, sizeof (double));
j = 0;
for (i = 0; i < nphi; i++) {
if (rphi[i] != NAN) { /* ??? is that correct? Not even NAN == NAN ??? */
phi[j++] = rphi[i];
}
}
rumu = ASCII_column (rvalue, rrows, 0);
for (i = 0; i < rrows - 2; i++) {
rumu[i] = rumu[i + 2];
} /* Shift to skip two first lines */
rumu[rrows - 2] = NAN;
rumu[rrows - 1] = NAN;
/* allocate memory for the radiance field */
status = ASCII_calloc_double (&raddis, numu, nphi);
if (status != 0) {
fprintf (stderr, "angres: allocating memory for produce\n");
return status;
}
for (i = 0; i < numu; i++) {
for (j = 0; j < nphi; j++) {
raddis[i][j] = rvalue[i + 2][j + 2];
}
}
/* commented out by RB, because was not used but caused compiler warnings */
/* rfldir = rvalue[0][1]; */
/* rfldn = rvalue[0][2]; */
/* flup = rvalue[0][3]; */
uavgso = rvalue[0][4];
/* uavgdn = rvalue[0][5]; */
/* uavgup = rvalue[0][6]; */
aumu = ASCII_column (avalue, arows, 0);
if (ang)
for (i = 0; i < numu; i++)
aumu[i] = cos (aumu[i] * PI / 180);
aangres = ASCII_column (avalue, arows, 1);
/* compare umu with similar from angular response file, differences should be small, */
/* otherwise interpolate angular response to radiance field. */
for (i = 0; i < numu; i++)
if (fabs (aumu[i] - rumu[i]) > 0.0001)
fprintf (stderr, "umu %f %f %f\n", aumu[i], rumu[i], aumu[i] - rumu[i]);
/* Make diffuse radiation field isotropic */
if (isotropic) {
/* Integrate (angular response)*radiance over all angles */
/* Upper and lower integration bounds for each dimension */
xl[0] = aumu[0];
xu[0] = aumu[numu - 1];
xl[1] = phi[0] * PI / 180;
xu[1] = phi[nphi - 1] * PI / 180;
mcinpiso.nphi = nphi;
mcinpiso.numu = numu;
mcinpiso.phi = (double*)calloc (nphi, sizeof (double));
mcinpiso.umu = (double*)calloc (numu, sizeof (double));
status = ASCII_calloc_double (&mcinpiso.prod, numu, nphi);
for (i = 0; i < nphi; i++)
mcinpiso.phi[i] = phi[i] * PI / 180;
for (i = 0; i < numu; i++)
mcinpiso.umu[i] = aumu[i];
for (i = 0; i < numu; i++) {
for (j = 0; j < nphi; j++) {
mcinpiso.prod[i][j] = raddis[i][j];
}
}
#if HAVE_LIBGSL
gsl_rng_env_setup();
Tiso = gsl_rng_default;
riso = gsl_rng_alloc (Tiso);
gsl_monte_plain_integrate (&Giso, xl, xu, DIM_ANG_INT, calls, riso, siso, &res, &err);
gsl_monte_plain_free (siso);
#endif
dphi = phi[1] - phi[0];
dtheta = fabs (acos (aumu[1]) * 180 / PI - acos (aumu[0]) * 180 / PI);
tmpprod = dtheta * dphi;
for (i = 0; i < numu; i++) {
for (j = 0; j < nphi; j++) {
raddis[i][j] = res / tmpprod;
}
}
}
/* Tilt and rotate angular response */
angres = tilt_and_rotate (aangres, nphi, phi, numu, aumu, pgm, theta_t, phi_r, dev);
if (angres == NULL) {
fprintf (stderr, "Error calling tilt_and_rotate()\n");
return -1;
}
/* Multiply angular response and radiance field */
/* allocate memory for the product */
status = ASCII_calloc_double (&prod, numu, nphi);
if (status != 0) {
fprintf (stderr, "angres: error allocating memory for product\n");
return status;
}
for (i = 0; i < numu; i++) {
for (j = 0; j < nphi; j++) {
prod[i][j] = angres[i][j] * raddis[i][j];
}
}
if (pgm) {
if ((pgmfile = fopen ("prod.pgm", "w")) == NULL) {
fprintf (stderr, "Error opening prod.pgm for writing\n");
return -1;
}
fprintf (pgmfile, "P2\n");
fprintf (pgmfile, "%d %d\n", nphi, numu);
fprintf (pgmfile, "256\n");
max = -9999;
for (i = 0; i < numu; i++)
for (j = 0; j < nphi; j++)
if (prod[i][j] > max)
max = prod[i][j];
for (i = 0; i < numu; i++)
for (j = 0; j < nphi; j++) {
k = (int)(prod[i][j] * 256 / max);
fprintf (pgmfile, "%d\n", k);
}
fclose (pgmfile);
if ((pgmfile = fopen ("raddis.pgm", "w")) == NULL) {
fprintf (stderr, "Error opening raddis.pgm for writing\n");
return -1;
}
fprintf (pgmfile, "P2\n");
fprintf (pgmfile, "%d %d\n", nphi, numu);
fprintf (pgmfile, "256\n");
max = -9999;
for (i = 0; i < numu; i++)
for (j = 0; j < nphi; j++)
if (raddis[i][j] > max)
max = raddis[i][j];
for (i = 0; i < numu; i++)
for (j = 0; j < nphi; j++) {
k = (int)(raddis[i][j] * 256 / max);
fprintf (pgmfile, "%d\n", k);
}
fclose (pgmfile);
}
/* Find angular response for direct beam contribution */
it = 0;
ia = 0;
while (((180 - sza) - acos (aumu[ia++]) * 180 / PI) < 0 && ia < numu)
;
it = ia - 1; /* This one is fun:-) */
/* Make sure we get the closest grid point */
if (fabs (acos (aumu[it]) * 180 / PI - (180 - sza)) > fabs (acos (aumu[it - 1]) * 180 / PI - (180 - sza)))
it = it - 1;
jt = 0;
ja = 0;
delphirad = fabs (phi[1] - phi[0]) * PI / 180;
while (fabs (phi0 - phi[ja++]) * PI / 180 > delphirad)
;
jt = ja - 1;
if (incdir) {
dir = angres[it][jt] * uavgso * 4 * PI;
} else {
dir = 0;
}
ASCII_free_double (avalue, arows);
ASCII_free_double (rvalue, rrows);
ASCII_free_double (angres, numu);
/* Integrate (angular response)*radiance over all angles */
/* Upper and lower integration bounds for each dimension */
xl[0] = aumu[0];
xu[0] = aumu[numu - 1];
xl[1] = phi[0] * PI / 180;
xu[1] = phi[nphi - 1] * PI / 180;
mcinp.nphi = nphi;
mcinp.numu = numu;
mcinp.phi = (double*)calloc (nphi, sizeof (double));
mcinp.umu = (double*)calloc (numu, sizeof (double));
status = ASCII_calloc_double (&mcinp.prod, numu, nphi);
for (i = 0; i < nphi; i++)
mcinp.phi[i] = phi[i] * PI / 180;
for (i = 0; i < numu; i++)
mcinp.umu[i] = aumu[i];
for (i = 0; i < numu; i++) {
for (j = 0; j < nphi; j++) {
mcinp.prod[i][j] = prod[i][j];
}
}
#if HAVE_LIBGSL
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
gsl_monte_plain_integrate (&G, xl, xu, DIM_ANG_INT, calls, r, s, &res, &err);
gsl_monte_plain_free (s);
#endif
/* fprintf(stdout,"Result: %f, error: %f\n", res, err); */
fprintf (stdout, "%f %f %f\n", res, err, res + dir);
ASCII_free_double (raddis, numu);
return 0; /* if o.k. */
}
| {
"alphanum_fraction": 0.5642450751,
"avg_line_length": 31.9737118822,
"ext": "c",
"hexsha": "c07a94a5c6da5f25b970b06bc122afe22d3775d1",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "AmberCrafter/docker-compose_libRadtran",
"max_forks_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/angres.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "AmberCrafter/docker-compose_libRadtran",
"max_issues_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/angres.c",
"max_line_length": 129,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "AmberCrafter/docker-compose_libRadtran",
"max_stars_repo_path": "ubuntu20/projects/libRadtran-2.0.4/src/angres.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 9808,
"size": 30407
} |
#ifndef libcv_ctf
#define libcv_ctf
#include "Array.h"
#import "Ellipse.h"
#include "MRC.h"
#include "Image.h"
#include "util.h"
#include "cvtypes.h"
#include <fftw3.h>
#include <math.h>
#include "geometry.h"
#include <gsl/gsl_math.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_multimin.h>
typedef struct CTFST {
char * imgpath;
f64 defocus_x;
f64 defocus_y;
f64 astig_angle;
f64 amplitude;
f64 volts;
f64 lambda;
f64 size;
f64 apix;
f64 scale;
f64 * ctf1d;
f64 * ctfsynth1d;
f64 * background1d;
f64 * envelope1d;
f64 ctf1dscale;
f64 ctf1dapix;
u32 ctf1dsize;
f64 * ctf2d;
f64 * ctfsynth2d;
f64 * background2d;
f64 * envelope2d;
f64 ctf2dapix;
u32 ctf2drows;
u32 ctf2dcols;
} * CTF;
@interface Array ( CTF_Functions )
-(id) ellipse1DAvg:(EllipseP)ellipse;
@end
void ctf2_calcv( f64 c[], f64 ctf[], u64 size );
f64 ctf_norm( f64 fit_data[], f64 ctf_p[], f64 ctf[], f64 norm[], u32 size );
f64 calculate_score(f64 c1[], f64 c2[], u32 lcut, u32 rcut );
ArrayP ctfNormalize( ArrayP fit_data, ArrayP ctf_params );
void estimateDefocus( ArrayP fit_data, ArrayP ctf_params );
void peakNormalize( f64 values[], u32 size );
ArrayP fitNoise( ArrayP fit_data );
ArrayP fitEnvelope( ArrayP fit_data );
f64 getTEMLambda( f64 volts );
f64 getTEMVoltage( f64 lambda );
f64 ctf_calc( f64 c[], f64 x );
void fit2DCTF( ArrayP image, f64 d1, f64 d2, f64 th, f64 apix, f64 kv, f64 cs, f64 ac );
f64 positionForPeak( f64 c[], u32 peak_pos );
f64 defocusForPeak( f64 c[], f64 peak_pos, u32 peak_num );
ArrayP generate2DCTF( f64 df1, f64 df2, f64 theta, u32 rows, u32 cols, f64 apix, f64 cs, f64 kv, f64 ac );
ArrayP g2DCTF( f64 df1, f64 df2, f64 theta, u32 rows, u32 cols, f64 apix, f64 cs, f64 kv, f64 ac );
#endif
| {
"alphanum_fraction": 0.7055214724,
"avg_line_length": 23.5921052632,
"ext": "h",
"hexsha": "f742c890c255111ca0c6d858d456bd2f2f5e51b1",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-09-05T20:58:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-05T20:58:37.000Z",
"max_forks_repo_head_hexsha": "974b8a48245222de0d9cfb0f433533487ecce60d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "leschzinerlab/myami-3.2-freeHand",
"max_forks_repo_path": "programs/ace2/ctf.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "974b8a48245222de0d9cfb0f433533487ecce60d",
"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": "leschzinerlab/myami-3.2-freeHand",
"max_issues_repo_path": "programs/ace2/ctf.h",
"max_line_length": 106,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "974b8a48245222de0d9cfb0f433533487ecce60d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "leschzinerlab/myami-3.2-freeHand",
"max_stars_repo_path": "programs/ace2/ctf.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 655,
"size": 1793
} |
/* specfunc/hyperg_2F0.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_hyperg.h>
#include "error.h"
#include "hyperg.h"
int
gsl_sf_hyperg_2F0_e(const double a, const double b, const double x, gsl_sf_result * result)
{
if(x < 0.0) {
/* Use "definition" 2F0(a,b,x) = (-1/x)^a U(a,1+a-b,-1/x).
*/
gsl_sf_result U;
double pre = pow(-1.0/x, a);
int stat_U = gsl_sf_hyperg_U_e(a, 1.0+a-b, -1.0/x, &U);
result->val = pre * U.val;
result->err = GSL_DBL_EPSILON * fabs(result->val) + pre * U.err;
return stat_U;
}
else if(x == 0.0) {
result->val = 1.0;
result->err = 0.0;
return GSL_SUCCESS;
}
else {
/* Use asymptotic series. ??
*/
/* return hyperg_2F0_series(a, b, x, -1, result, &prec); */
DOMAIN_ERROR(result);
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_hyperg_2F0(const double a, const double b, const double x)
{
EVAL_RESULT(gsl_sf_hyperg_2F0_e(a, b, x, &result));
}
| {
"alphanum_fraction": 0.6553372278,
"avg_line_length": 29.421875,
"ext": "c",
"hexsha": "022b5cb58afe5a33651aa2c697d30ba36f59bd33",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/specfunc/hyperg_2F0.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/specfunc/hyperg_2F0.c",
"max_line_length": 91,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/specfunc/hyperg_2F0.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 585,
"size": 1883
} |
// -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt
#ifndef MESH_PROCESSING_LIBHH_MY_LAPACK_H_
#define MESH_PROCESSING_LIBHH_MY_LAPACK_H_
#include "Hh.h"
#if defined(HH_USE_LAPACK_INTEGER) // Google
#include <lapack.h>
using lapack_int = lapack::integer;
#elif !(defined(_WIN32) || defined(__CYGWIN__)) // unix
#if defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wredundant-decls"
#endif
#include <lapacke.h> // in either /usr/include/ or /usr/include/lapacke/
#else // cygwin or WIN32
#if defined(__CYGWIN__)
// cygwin: c:/cygwin/usr/src/lapack-3.5.0.tgz
// lapacke_config.h
// #ifndef lapack_int
// #if defined(LAPACK_ILP64)
// #define lapack_int long
// #else
// #define lapack_int int
// #endif
// #endif
//
// lapacke.h: "#define lapack_int int"
// #define LAPACK_sgelss LAPACK_GLOBAL(sgelss, SGELSS)
// void LAPACK_sgelss( lapack_int* m, lapack_int* n, lapack_int* nrhs, float* a,
// lapack_int* lda, float* b, lapack_int* ldb, float* s,
// float* rcond, lapack_int* rank, float* work,
// lapack_int* lwork, lapack_int *info );
// c:/cygwin/usr/src/lapack-3.5.0.tgz!lapack-3.5.0/lapacke/example/example_DGELS_colmajor.c
// #include <lapacke.h>
// {
// double A[5][3] = {1, 2, 3, 4, 5, 1, 3, 5, 2, 4, 1, 4, 2, 5, 3};
// double b[5][2] = {-10, 12, 14, 16, 18, -3, 14, 12, 16, 16};
// lapack_int m = 5, n = 3, lda = 5, ldb = 5, nrhs = 2;
// lapack_int info = LAPACKE_dgels(LAPACK_COL_MAJOR, 'N', m, n, nrhs, *A, lda, *b, ldb);
// }
using lapack_int = int;
#else // _WIN32
using lapack_int = long; // was defined as "integer" in f2c.h
#endif
// Continue: cygwin or WIN32
// clapack routines in liblapack
extern "C" {
// http://www.netlib.org/lapack/explore-html/d0/db8/group__real_g_esolve.html#ga206e3084597d088b31dc054a69aec93f
// SGELSS solves overdetermined or underdetermined systems for GE matrices, using SVD.
// ~/src/lib_src/CLAPACK/SRC/sgelss.c
lapack_int sgelss_(lapack_int* m, lapack_int* n, lapack_int* nrhs, float* a, lapack_int* lda,
float* b, lapack_int* ldb, float* s, float* rcond, lapack_int* irank,
float* work, lapack_int* lwork, lapack_int* info);
// same for double-precision
lapack_int dgelss_(lapack_int* m, lapack_int* n, lapack_int* nrhs, double* a, lapack_int* lda,
double* b, lapack_int* ldb, double* s, double* rcond, lapack_int* irank,
double* work, lapack_int* lwork, lapack_int* info);
// http://www.netlib.org/lapack/explore-html/d0/d2a/sgelsx_8f.html
// SGELSX solves overdetermined or underdetermined systems for GE matrices, using QR.
// This routine is deprecated and has been replaced by routine SGELSY.
// ~/src/lib_src/CLAPACK/SRC/sgelsx.c
// lapack_int sgelsx_(lapack_int* m, lapack_int* n, lapack_int* nrhs, float* a, lapack_int* lda,
// float* b, lapack_int* ldb, lapack_int* jpvt, float* rcond, lapack_int* irank,
// float* work, lapack_int* info);
// http://www.netlib.org/lapack/explore-html/dc/db6/sgelsy_8f.html
lapack_int sgelsy_(lapack_int* m, lapack_int* n, lapack_int* nrhs, float* a, lapack_int* lda,
float* b, lapack_int* ldb, lapack_int* jpvt, float* rcond, lapack_int* irank,
float* work, lapack_int* lwork, lapack_int *info);
// http://www.netlib.org/lapack/explore-html/d4/dca/group__real_g_esing.html
// subroutine SGESVD (JOBU, JOBVT, M, N, A, LDA, S, U, LDU, VT, LDVT, WORK, LWORK, INFO)
// SGESVD computes the singular value decomposition (SVD) for GE matrices
// ~/src/lib_src/CLAPACK/SRC/sgesvd.c
lapack_int sgesvd_(char* jobu, char* jobvt, lapack_int* m, lapack_int* n, float* a, lapack_int* lda,
float* s, float* u, lapack_int* ldu, float* vt, lapack_int* ldvt,
float* work, lapack_int* lwork, lapack_int* info);
// http://www.netlib.org/lapack/explore-html/d8/ddc/group__real_g_ecomputational.html#ga7cb54fa1727bf0166523036f4948bc56
// subroutine SGEQRF (M, N, A, LDA, TAU, WORK, LWORK, INFO)
// SGEQRF computes a QR factorization of a real M-by-N matrix A:
// A = Q * R.
// ~/src/lib_src/CLAPACK/SRC/sgeqrf.c
lapack_int sgeqrf_(lapack_int* m, lapack_int* n, float* a, lapack_int* lda, float* tau,
float* work, lapack_int* lwork, lapack_int* info);
}
#if defined(_MSC_VER)
#if defined(_WIN64) && !defined(HH_NO_MKL) // for now, only use MKL on x64
#if !defined(HH_MKL_NOT_DLL)
// 2014
HH_REFERENCE_LIB("mkl_intel_lp64_dll.lib");
HH_REFERENCE_LIB("mkl_intel_thread_dll.lib");
HH_REFERENCE_LIB("mkl_core_dll.lib");
HH_REFERENCE_LIB("libiomp5md.lib");
// e.g.: depends MeshSimplify.exe
// -> mkl_intel_thread.dll -> libiomp5md.dll mkl_core.dll ("core" dispatches among several mkl_*.dll based on CPU)
#else // !defined(HH_MKL_NOT_DLL)
// 2012
#if defined(_WIN64)
HH_REFERENCE_LIB("mkl_intel_lp64.lib");
#else
HH_REFERENCE_LIB("mkl_intel_c.lib");
#endif
HH_REFERENCE_LIB("mkl_intel_thread.lib");
HH_REFERENCE_LIB("mkl_core.lib");
HH_REFERENCE_LIB("libiomp5md.lib");
#endif // !defined(HH_MKL_NOT_DLL)
#else // defined(_WIN64) && !defined(HH_NO_MKL)
HH_REFERENCE_LIB("liblapack.lib");
HH_REFERENCE_LIB("libBLAS.lib");
#if 1
HH_REFERENCE_LIB("libf2c.lib"); // CLAPACK
#else
HH_REFERENCE_LIB("libF77.lib"); // liblapack
HH_REFERENCE_LIB("libI77.lib");
#endif
#endif // defined(_WIN64) && !defined(HH_NO_MKL)
#endif // defined(_MSC_VER)
#endif // !(defined(_WIN32) || defined(__CYGWIN__))
#if 0
// from mkl_lapack.h:
// It shows that the MKL lapack functions have almost the same signatures (except for "const char*").
using MKL_INT = int; // 32-bit unless MKL_ILP64
extern "C" {
void SGESVD(const char* jobu, const char* jobvt, const MKL_INT* m,
const MKL_INT* n, float* a, const MKL_INT* lda, float* s,
float* u, const MKL_INT* ldu, float* vt, const MKL_INT* ldvt,
float* work, const MKL_INT* lwork, MKL_INT* info);
void SGESVD_(const char* jobu, const char* jobvt, const MKL_INT* m,
const MKL_INT* n, float* a, const MKL_INT* lda, float* s,
float* u, const MKL_INT* ldu, float* vt, const MKL_INT* ldvt,
float* work, const MKL_INT* lwork, MKL_INT* info);
void sgesvd(const char* jobu, const char* jobvt, const MKL_INT* m,
const MKL_INT* n, float* a, const MKL_INT* lda, float* s,
float* u, const MKL_INT* ldu, float* vt, const MKL_INT* ldvt,
float* work, const MKL_INT* lwork, MKL_INT* info);
void sgesvd_(const char* jobu, const char* jobvt, const MKL_INT* m,
const MKL_INT* n, float* a, const MKL_INT* lda, float* s,
float* u, const MKL_INT* ldu, float* vt, const MKL_INT* ldvt,
float* work, const MKL_INT* lwork, MKL_INT* info);
}
// from /usr/include/lapacke.h:
lapack_int LAPACKE_sgelss( int matrix_order, lapack_int m, lapack_int n,
lapack_int nrhs, float* a, lapack_int lda, float* b,
lapack_int ldb, float* s, float rcond,
lapack_int* rank );
void LAPACK_sgelss( lapack_int* m, lapack_int* n, lapack_int* nrhs, float* a,
lapack_int* lda, float* b, lapack_int* ldb, float* s,
float* rcond, lapack_int* rank, float* work,
lapack_int* lwork, lapack_int *info );
#endif
#endif // MESH_PROCESSING_LIBHH_MY_LAPACK_H_
| {
"alphanum_fraction": 0.6506024096,
"avg_line_length": 40.6170212766,
"ext": "h",
"hexsha": "eb444d7314ee686b87954746fd1c0fd889510495",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-04-05T05:21:43.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-05T05:21:43.000Z",
"max_forks_repo_head_hexsha": "f535502289b809446501a824e2ed3f87aa4ddbcc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "xianyuMeng/Mesh-processing-library",
"max_forks_repo_path": "libHh/my_lapack.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f535502289b809446501a824e2ed3f87aa4ddbcc",
"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": "xianyuMeng/Mesh-processing-library",
"max_issues_repo_path": "libHh/my_lapack.h",
"max_line_length": 120,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "f535502289b809446501a824e2ed3f87aa4ddbcc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "xianyuMeng/Mesh-processing-library",
"max_stars_repo_path": "libHh/my_lapack.h",
"max_stars_repo_stars_event_max_datetime": "2018-09-11T02:16:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-11T02:16:33.000Z",
"num_tokens": 2471,
"size": 7636
} |
//
// Created by pedram pakseresht on 2/18/21.
//
static char help[] = "settling in quiescent fluid";
#include <petsc.h>
#include "incompressibleFlow.h"
#include "mesh.h"
#include "particleInertial.h"
#include "particles.h"
#include "particleInitializer.h"
#include "petscviewer.h"
static PetscErrorCode uniform_u(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *u, void *ctx) {
PetscInt d;
for (d = 0; d < Dim; ++d)
u[d] = 0.0;
return 0;
}
static PetscErrorCode uniform_u_t(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *u, void *ctx) {
PetscInt d;
for (d = 0; d < Dim; ++d)
u[d] = 0.0;
return 0;
}
static PetscErrorCode uniform_p(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *p, void *ctx) {
p[0] = 0.0;
return 0;
}
static PetscErrorCode uniform_T(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *T, void *ctx) {
T[0] = 0.0;
return 0;
}
static PetscErrorCode uniform_T_t(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *T, void *ctx) {
T[0] = 0.0;
return 0;
}
static PetscErrorCode SetInitialConditions(TS ts, Vec u) {
PetscErrorCode (*initFuncs[3])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar u[], void *ctx) = {uniform_u,uniform_p,uniform_T};
// u here is the solution vector including velocity, temperature and pressure fields.
DM dm;
PetscReal t;
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = TSGetDM(ts, &dm);
CHKERRQ(ierr);
ierr = TSGetTime(ts, &t);
CHKERRQ(ierr);
ierr = DMProjectFunction(dm, 0.0, initFuncs, NULL, INSERT_ALL_VALUES, u);
CHKERRQ(ierr);
// get the flow to apply the completeFlowInitialization method
ierr = IncompressibleFlow_CompleteFlowInitialization(dm, u);
CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static PetscErrorCode MonitorFlowAndParticleError(TS ts, PetscInt step, PetscReal crtime, Vec u, void *ctx) {
// PetscErrorCode (*exactFuncs[3])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx);
// void *ctxs[3];
DM dm;
PetscDS ds;
Vec v;
PetscReal ferrors[3];
PetscInt f;
PetscErrorCode ierr;
PetscInt num;
PetscFunctionBeginUser;
ierr = TSGetDM(ts, &dm);
CHKERRQ(ierr);
ierr = DMGetDS(dm, &ds);
CHKERRQ(ierr);
// get the particle data from the context
ParticleData particlesData = (ParticleData)ctx;
PetscInt particleCount;
ierr = DMSwarmGetSize(particlesData->dm, &particleCount);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// compute the average particle location
const PetscReal *coords;
PetscInt dims;
PetscReal avg[3] = {0.0, 0.0, 0.0};
ierr = DMSwarmGetField(particlesData->dm, DMSwarmPICField_coor, &dims, NULL, (void **)&coords);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
for (PetscInt p = 0; p < particleCount; p++) {
for (PetscInt n = 0; n < dims; n++) {
avg[n] += coords[p * dims + n] / particleCount; // PetscReal
}
}
ierr = DMSwarmRestoreField(particlesData->dm, DMSwarmPICField_coor, &dims, NULL, (void **)&coords);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"Timestep: %04d time = %-8.4g \t L_2 Error: [%2.3g, %2.3g, %2.3g] ParticleCount: %d\n",
(int)step,
(double)crtime,
(double)ferrors[0],
(double)ferrors[1],
(double)ferrors[2],
particleCount,
(double)avg[0],
(double)avg[1]);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "Avg Particle Location: [%2.3g, %2.3g, %2.3g]\n", (double)avg[0], (double)avg[1], (double)avg[2]);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = VecViewFromOptions(u, NULL, "-vec_view");
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = DMSetOutputSequenceNumber(particlesData->dm, step, crtime);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
if (step == 0) {
ierr = ParticleViewFromOptions(particlesData, "-particle_init");
CHKERRABORT(PETSC_COMM_WORLD, ierr);
} else {
ierr = ParticleViewFromOptions(particlesData, "-particle_view");
CHKERRABORT(PETSC_COMM_WORLD, ierr);
}
PetscFunctionReturn(0);
}
static PetscErrorCode ParticleInertialInitialize(ParticleData particles) {
PetscFunctionBeginUser;
PetscErrorCode ierr;
Vec vel,diam,dens;
DM particleDm = particles->dm;
// input parameters required for particles
PetscScalar partVel = 0.0;
PetscScalar partDiam = 0.22;
PetscScalar partDens = 90.0;
PetscScalar fluidDens = 1.0;
PetscScalar fluidVisc = 1.0;
PetscScalar gravity[3] = {0.0,1.0,0.0};
ierr = DMSwarmCreateGlobalVectorFromField(particleDm,ParticleVelocity, &vel);CHKERRQ(ierr);
ierr = DMSwarmCreateGlobalVectorFromField(particleDm,ParticleDiameter, &diam);CHKERRQ(ierr);
ierr = DMSwarmCreateGlobalVectorFromField(particleDm,ParticleDensity, &dens);CHKERRQ(ierr);
// set particle velocity, diameter and density
ierr = VecSet(vel, partVel);CHKERRQ(ierr);
ierr = VecSet(diam, partDiam);CHKERRQ(ierr);
ierr = VecSet(dens, partDens);CHKERRQ(ierr);
ierr = DMSwarmDestroyGlobalVectorFromField(particleDm,ParticleVelocity, &vel);CHKERRQ(ierr);
ierr = DMSwarmDestroyGlobalVectorFromField(particleDm,ParticleDiameter, &diam);CHKERRQ(ierr);
ierr = DMSwarmDestroyGlobalVectorFromField(particleDm,ParticleDensity, &dens);CHKERRQ(ierr);
InertialParticleParameters *data;
PetscNew(&data);
particles->data =data;
// set fluid parameters
data->fluidDensity = fluidDens;
data->fluidViscosity = fluidVisc;
data->gravityField[0] = gravity[0];
data->gravityField[1] = gravity[1];
data->gravityField[2] = gravity[2];
PetscFunctionReturn(0);
}
int main( int argc, char *argv[] )
{
DM dm; // domain definition
TS ts; // time-stepper
PetscErrorCode ierr;
PetscBag parameterBag; // constant flow parameters
Vec flowField; // flow solution vector
FlowData flowData;
PetscReal t;
PetscInt Dim = 2;
PetscReal dt = 0.05; // dt for time stepper
PetscInt max_steps = 10; // maximum time steps
PetscReal Re = 0.1; // Reynolds number
PetscReal St = 1.0; // Strouhal number
PetscReal Pe = 1.0; // Peclet number
PetscReal Mu = 1.0; // viscosity
PetscReal K_input = 1.0; // thermal conductivity
PetscReal Cp = 1.0; // heat capacity
// PetscInt Np=10;
// initialize Petsc ...
ierr = PetscInitialize(&argc, &argv, NULL, "");CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "Settling particle in a quiescent fluid \n");CHKERRQ(ierr);
// setup the ts
ierr = TSCreate(PETSC_COMM_WORLD, &ts);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = CreateMesh(PETSC_COMM_WORLD, &dm, PETSC_TRUE, Dim);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSSetDM(ts, dm);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
//output the mesh
ierr = DMViewFromOptions(dm, NULL, "-dm_view");
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// Setup the flow data
ierr = FlowCreate(&flowData);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// setup problem
ierr = IncompressibleFlow_SetupDiscretization(flowData, dm);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
IncompressibleFlowParameters flowParameters;
// changing non-dimensional parameters manually here ...
flowParameters.strouhal = St;
flowParameters.reynolds = Re;
flowParameters.peclet = Pe;
flowParameters.mu = Mu;
flowParameters.k = K_input;
flowParameters.cp = Cp;
// print out the parameters
/*
ierr = PetscPrintf(PETSC_COMM_WORLD, "*** non-dimensional parameters ***\n");CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "St=%g\n", flowParameters.strouhal);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "Re=%g\n", flowParameters.reynolds);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "Pe=%g\n", flowParameters.peclet);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "Mu=%g\n", flowParameters.mu);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "K=%g\n", flowParameters.k);CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD, "Cp=%g\n", flowParameters.cp);CHKERRQ(ierr);
*/
// Start the problem setup
PetscScalar constants[TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS];
ierr = IncompressibleFlow_PackParameters(&flowParameters, constants);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = IncompressibleFlow_StartProblemSetup(flowData, TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS, constants);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// Override problem with source terms, boundary, and set the exact solution
PetscDS prob;
ierr = DMGetDS(dm, &prob);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// Setup Boundary Conditions
// Note: DM_BC_ESSENTIAL is a Dirichlet BC.
PetscInt id;
id = 3;
ierr = PetscDSAddBoundary(
prob, DM_BC_ESSENTIAL, "top wall velocity", "marker", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
id = 1;
ierr = PetscDSAddBoundary(
prob, DM_BC_ESSENTIAL, "bottom wall velocity", "marker", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
id = 2;
ierr = PetscDSAddBoundary(
prob, DM_BC_ESSENTIAL, "right wall velocity", "marker", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
id = 4;
ierr = PetscDSAddBoundary(
prob, DM_BC_ESSENTIAL, "left wall velocity", "marker", VEL, 0, NULL, (void (*)(void))uniform_u, (void (*)(void))uniform_u_t, 1, &id, NULL);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
id = 3;
ierr = PetscDSAddBoundary(
prob, DM_BC_ESSENTIAL, "top wall temp", "marker", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, NULL);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
id = 1;
ierr = PetscDSAddBoundary(
prob, DM_BC_ESSENTIAL, "bottom wall temp", "marker", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, parameterBag);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
id = 2;
ierr = PetscDSAddBoundary(
prob, DM_BC_ESSENTIAL, "right wall temp", "marker", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, parameterBag);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
id = 4;
ierr = PetscDSAddBoundary(
prob, DM_BC_ESSENTIAL, "left wall temp", "marker", TEMP, 0, NULL, (void (*)(void))uniform_T, (void (*)(void))uniform_T_t, 1, &id, parameterBag);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = IncompressibleFlow_CompleteProblemSetup(flowData, ts);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// Name the flow field
ierr = PetscObjectSetName(((PetscObject)flowData->flowField), "Numerical Solution");
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = SetInitialConditions(ts, flowData->flowField);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSGetTime(ts, &t);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// *** added by Pedram for dt and number of time steps ***
ierr = TSSetTimeStep(ts,dt);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSSetMaxSteps(ts,max_steps);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// ***********************************
ierr = DMSetOutputSequenceNumber(dm, 0, t);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// checks for convergence ...
ierr = DMTSCheckFromOptions(ts, flowData->flowField);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ParticleData particles;
// Setup the particle domain
ierr = ParticleInertialCreate(&particles, Dim);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// link the flow to the particles
ierr = ParticleInitializeFlow(particles, flowData);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// name the particle domain
ierr = PetscObjectSetOptionsPrefix((PetscObject)(particles->dm), "particles_");
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = PetscObjectSetName((PetscObject)particles->dm, "Particles");
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// initialize the particles position
ierr = ParticleInitialize(dm, particles->dm);CHKERRABORT(PETSC_COMM_WORLD, ierr);
// initialize inertial particles velocity, diameter and density
ierr = ParticleInertialInitialize(particles);CHKERRABORT(PETSC_COMM_WORLD, ierr);
//ierr = ParticleInertialInitialize(particles->dm);CHKERRABORT(PETSC_COMM_WORLD, ierr);
// setup the flow monitor to also check particles
ierr = TSMonitorSet(ts, MonitorFlowAndParticleError, particles, NULL);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSSetFromOptions(ts);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// Setup particle position integrator
TS particleTs;
ierr = TSCreate(PETSC_COMM_WORLD, &particleTs);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = PetscObjectSetOptionsPrefix((PetscObject)particleTs, "particle_");
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = ParticleInertialSetupIntegrator(particles, particleTs, flowData);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// ierr = VecView(particleVelocity,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr);
// Solve the one way coupled system
ierr = TSSolve(ts, flowData->flowField);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
// Cleanup
ierr = DMDestroy(&dm);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSDestroy(&ts);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = TSDestroy(&particleTs);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = FlowDestroy(&flowData);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = ParticleInertialDestroy(&particles);
CHKERRABORT(PETSC_COMM_WORLD, ierr);
ierr = PetscFinalize();
exit(ierr);
} | {
"alphanum_fraction": 0.6783996654,
"avg_line_length": 36.2297979798,
"ext": "c",
"hexsha": "c347bce39f98b175a932f3fcc78c144db2ad0083",
"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": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pakserep/ablateClient",
"max_forks_repo_path": "quiescentFluid.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b",
"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": "pakserep/ablateClient",
"max_issues_repo_path": "quiescentFluid.c",
"max_line_length": 161,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pakserep/ablateClient",
"max_stars_repo_path": "quiescentFluid.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4116,
"size": 14347
} |
/* interpolation/cspline.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2004 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_vector.h>
#include "integ_eval.h"
#include <gsl/gsl_interp.h>
typedef struct
{
double * c;
double * g;
double * diag;
double * offdiag;
} cspline_state_t;
/* common initialization */
static void *
cspline_alloc (size_t size)
{
cspline_state_t * state = (cspline_state_t *) malloc (sizeof (cspline_state_t));
if (state == NULL)
{
GSL_ERROR_NULL("failed to allocate space for state", GSL_ENOMEM);
}
state->c = (double *) malloc (size * sizeof (double));
if (state->c == NULL)
{
free (state);
GSL_ERROR_NULL("failed to allocate space for c", GSL_ENOMEM);
}
state->g = (double *) malloc (size * sizeof (double));
if (state->g == NULL)
{
free (state->c);
free (state);
GSL_ERROR_NULL("failed to allocate space for g", GSL_ENOMEM);
}
state->diag = (double *) malloc (size * sizeof (double));
if (state->diag == NULL)
{
free (state->g);
free (state->c);
free (state);
GSL_ERROR_NULL("failed to allocate space for diag", GSL_ENOMEM);
}
state->offdiag = (double *) malloc (size * sizeof (double));
if (state->offdiag == NULL)
{
free (state->diag);
free (state->g);
free (state->c);
free (state);
GSL_ERROR_NULL("failed to allocate space for offdiag", GSL_ENOMEM);
}
return state;
}
/* natural spline calculation
* see [Engeln-Mullges + Uhlig, p. 254]
*/
static int
cspline_init (void * vstate, const double xa[], const double ya[],
size_t size)
{
cspline_state_t *state = (cspline_state_t *) vstate;
size_t i;
size_t num_points = size;
size_t max_index = num_points - 1; /* Engeln-Mullges + Uhlig "n" */
size_t sys_size = max_index - 1; /* linear system is sys_size x sys_size */
state->c[0] = 0.0;
state->c[max_index] = 0.0;
for (i = 0; i < sys_size; i++)
{
const double h_i = xa[i + 1] - xa[i];
const double h_ip1 = xa[i + 2] - xa[i + 1];
const double ydiff_i = ya[i + 1] - ya[i];
const double ydiff_ip1 = ya[i + 2] - ya[i + 1];
const double g_i = (h_i != 0.0) ? 1.0 / h_i : 0.0;
const double g_ip1 = (h_ip1 != 0.0) ? 1.0 / h_ip1 : 0.0;
state->offdiag[i] = h_ip1;
state->diag[i] = 2.0 * (h_ip1 + h_i);
state->g[i] = 3.0 * (ydiff_ip1 * g_ip1 - ydiff_i * g_i);
}
if (sys_size == 1)
{
state->c[1] = state->g[0] / state->diag[0];
return GSL_SUCCESS;
}
else
{
gsl_vector_view g_vec = gsl_vector_view_array(state->g, sys_size);
gsl_vector_view diag_vec = gsl_vector_view_array(state->diag, sys_size);
gsl_vector_view offdiag_vec = gsl_vector_view_array(state->offdiag, sys_size - 1);
gsl_vector_view solution_vec = gsl_vector_view_array ((state->c) + 1, sys_size);
int status = gsl_linalg_solve_symm_tridiag(&diag_vec.vector,
&offdiag_vec.vector,
&g_vec.vector,
&solution_vec.vector);
return status;
}
}
/* periodic spline calculation
* see [Engeln-Mullges + Uhlig, p. 256]
*/
static int
cspline_init_periodic (void * vstate, const double xa[], const double ya[],
size_t size)
{
cspline_state_t *state = (cspline_state_t *) vstate;
size_t i;
size_t num_points = size;
size_t max_index = num_points - 1; /* Engeln-Mullges + Uhlig "n" */
size_t sys_size = max_index; /* linear system is sys_size x sys_size */
if (sys_size == 2) {
/* solve 2x2 system */
const double h0 = xa[1] - xa[0];
const double h1 = xa[2] - xa[1];
const double A = 2.0*(h0 + h1);
const double B = h0 + h1;
double g[2];
double det;
g[0] = 3.0 * ((ya[2] - ya[1]) / h1 - (ya[1] - ya[0]) / h0);
g[1] = 3.0 * ((ya[1] - ya[2]) / h0 - (ya[2] - ya[1]) / h1);
det = 3.0 * (h0 + h1) * (h0 + h1);
state->c[1] = ( A * g[0] - B * g[1])/det;
state->c[2] = (-B * g[0] + A * g[1])/det;
state->c[0] = state->c[2];
return GSL_SUCCESS;
} else {
for (i = 0; i < sys_size-1; i++) {
const double h_i = xa[i + 1] - xa[i];
const double h_ip1 = xa[i + 2] - xa[i + 1];
const double ydiff_i = ya[i + 1] - ya[i];
const double ydiff_ip1 = ya[i + 2] - ya[i + 1];
const double g_i = (h_i != 0.0) ? 1.0 / h_i : 0.0;
const double g_ip1 = (h_ip1 != 0.0) ? 1.0 / h_ip1 : 0.0;
state->offdiag[i] = h_ip1;
state->diag[i] = 2.0 * (h_ip1 + h_i);
state->g[i] = 3.0 * (ydiff_ip1 * g_ip1 - ydiff_i * g_i);
}
i = sys_size - 1;
{
const double h_i = xa[i + 1] - xa[i];
const double h_ip1 = xa[1] - xa[0];
const double ydiff_i = ya[i + 1] - ya[i];
const double ydiff_ip1 = ya[1] - ya[0];
const double g_i = (h_i != 0.0) ? 1.0 / h_i : 0.0;
const double g_ip1 = (h_ip1 != 0.0) ? 1.0 / h_ip1 : 0.0;
state->offdiag[i] = h_ip1;
state->diag[i] = 2.0 * (h_ip1 + h_i);
state->g[i] = 3.0 * (ydiff_ip1 * g_ip1 - ydiff_i * g_i);
}
{
gsl_vector_view g_vec = gsl_vector_view_array(state->g, sys_size);
gsl_vector_view diag_vec = gsl_vector_view_array(state->diag, sys_size);
gsl_vector_view offdiag_vec = gsl_vector_view_array(state->offdiag, sys_size);
gsl_vector_view solution_vec = gsl_vector_view_array ((state->c) + 1, sys_size);
int status = gsl_linalg_solve_symm_cyc_tridiag(&diag_vec.vector,
&offdiag_vec.vector,
&g_vec.vector,
&solution_vec.vector);
state->c[0] = state->c[max_index];
return status;
}
}
}
static
void
cspline_free (void * vstate)
{
cspline_state_t *state = (cspline_state_t *) vstate;
free (state->c);
free (state->g);
free (state->diag);
free (state->offdiag);
free (state);
}
/* function for common coefficient determination
*/
static inline void
coeff_calc (const double c_array[], double dy, double dx, size_t index,
double * b, double * c, double * d)
{
const double c_i = c_array[index];
const double c_ip1 = c_array[index + 1];
*b = (dy / dx) - dx * (c_ip1 + 2.0 * c_i) / 3.0;
*c = c_i;
*d = (c_ip1 - c_i) / (3.0 * dx);
}
static
int
cspline_eval (const void * vstate,
const double x_array[], const double y_array[], size_t size,
double x,
gsl_interp_accel * a,
double *y)
{
const cspline_state_t *state = (const cspline_state_t *) vstate;
double x_lo, x_hi;
double dx;
size_t index;
if (a != 0)
{
index = gsl_interp_accel_find (a, x_array, size, x);
}
else
{
index = gsl_interp_bsearch (x_array, x, 0, size - 1);
}
/* evaluate */
x_hi = x_array[index + 1];
x_lo = x_array[index];
dx = x_hi - x_lo;
if (dx > 0.0)
{
const double y_lo = y_array[index];
const double y_hi = y_array[index + 1];
const double dy = y_hi - y_lo;
double delx = x - x_lo;
double b_i, c_i, d_i;
coeff_calc(state->c, dy, dx, index, &b_i, &c_i, &d_i);
*y = y_lo + delx * (b_i + delx * (c_i + delx * d_i));
return GSL_SUCCESS;
}
else
{
*y = 0.0;
return GSL_EINVAL;
}
}
static
int
cspline_eval_deriv (const void * vstate,
const double x_array[], const double y_array[], size_t size,
double x,
gsl_interp_accel * a,
double *dydx)
{
const cspline_state_t *state = (const cspline_state_t *) vstate;
double x_lo, x_hi;
double dx;
size_t index;
if (a != 0)
{
index = gsl_interp_accel_find (a, x_array, size, x);
}
else
{
index = gsl_interp_bsearch (x_array, x, 0, size - 1);
}
/* evaluate */
x_hi = x_array[index + 1];
x_lo = x_array[index];
dx = x_hi - x_lo;
if (dx > 0.0)
{
const double y_lo = y_array[index];
const double y_hi = y_array[index + 1];
const double dy = y_hi - y_lo;
double delx = x - x_lo;
double b_i, c_i, d_i;
coeff_calc(state->c, dy, dx, index, &b_i, &c_i, &d_i);
*dydx = b_i + delx * (2.0 * c_i + 3.0 * d_i * delx);
return GSL_SUCCESS;
}
else
{
*dydx = 0.0;
return GSL_EINVAL;
}
}
static
int
cspline_eval_deriv2 (const void * vstate,
const double x_array[], const double y_array[], size_t size,
double x,
gsl_interp_accel * a,
double * y_pp)
{
const cspline_state_t *state = (const cspline_state_t *) vstate;
double x_lo, x_hi;
double dx;
size_t index;
if (a != 0)
{
index = gsl_interp_accel_find (a, x_array, size, x);
}
else
{
index = gsl_interp_bsearch (x_array, x, 0, size - 1);
}
/* evaluate */
x_hi = x_array[index + 1];
x_lo = x_array[index];
dx = x_hi - x_lo;
if (dx > 0.0)
{
const double y_lo = y_array[index];
const double y_hi = y_array[index + 1];
const double dy = y_hi - y_lo;
double delx = x - x_lo;
double b_i, c_i, d_i;
coeff_calc(state->c, dy, dx, index, &b_i, &c_i, &d_i);
*y_pp = 2.0 * c_i + 6.0 * d_i * delx;
return GSL_SUCCESS;
}
else
{
*y_pp = 0.0;
return GSL_EINVAL;
}
}
static
int
cspline_eval_integ (const void * vstate,
const double x_array[], const double y_array[], size_t size,
gsl_interp_accel * acc,
double a, double b,
double * result)
{
const cspline_state_t *state = (const cspline_state_t *) vstate;
size_t i, index_a, index_b;
if (acc != 0)
{
index_a = gsl_interp_accel_find (acc, x_array, size, a);
index_b = gsl_interp_accel_find (acc, x_array, size, b);
}
else
{
index_a = gsl_interp_bsearch (x_array, a, 0, size - 1);
index_b = gsl_interp_bsearch (x_array, b, 0, size - 1);
}
*result = 0.0;
/* interior intervals */
for(i=index_a; i<=index_b; i++) {
const double x_hi = x_array[i + 1];
const double x_lo = x_array[i];
const double y_lo = y_array[i];
const double y_hi = y_array[i + 1];
const double dx = x_hi - x_lo;
const double dy = y_hi - y_lo;
if(dx != 0.0) {
double b_i, c_i, d_i;
coeff_calc(state->c, dy, dx, i, &b_i, &c_i, &d_i);
if (i == index_a || i == index_b)
{
double x1 = (i == index_a) ? a : x_lo;
double x2 = (i == index_b) ? b : x_hi;
*result += integ_eval(y_lo, b_i, c_i, d_i, x_lo, x1, x2);
}
else
{
*result += dx * (y_lo + dx*(0.5*b_i + dx*(c_i/3.0 + 0.25*d_i*dx)));
}
}
else {
*result = 0.0;
return GSL_EINVAL;
}
}
return GSL_SUCCESS;
}
static const gsl_interp_type cspline_type =
{
"cspline",
3,
&cspline_alloc,
&cspline_init,
&cspline_eval,
&cspline_eval_deriv,
&cspline_eval_deriv2,
&cspline_eval_integ,
&cspline_free
};
const gsl_interp_type * gsl_interp_cspline = &cspline_type;
static const gsl_interp_type cspline_periodic_type =
{
"cspline-periodic",
2,
&cspline_alloc,
&cspline_init_periodic,
&cspline_eval,
&cspline_eval_deriv,
&cspline_eval_deriv2,
&cspline_eval_integ,
&cspline_free
};
const gsl_interp_type * gsl_interp_cspline_periodic = &cspline_periodic_type;
| {
"alphanum_fraction": 0.5645442998,
"avg_line_length": 26.4621848739,
"ext": "c",
"hexsha": "37c73d4ae1b218eca9cea206f64bcc741cb794bf",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/cspline.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/interpolation/cspline.c",
"max_line_length": 88,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/interpolation/cspline.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": 3968,
"size": 12596
} |
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#include "compearth.h"
#ifdef COMPEARTH_USE_MKL
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#pragma clang diagnostic ignored "-Wstrict-prototypes"
#endif
#include <mkl_lapacke.h>
#include <mkl_cblas.h>
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#else
#include <lapacke.h>
#include <cblas.h>
#endif
#include "cmopad.h"
/*
Copyright (C) 2010
Lars Krieger & Sebastian Heimann
Contact
lars.krieger@zmaw.de & sebastian.heimann@zmaw.de
Modifications - 2015
Converted original Python mopad.py to C - Ben Baker (ISTI)
Contact
benbaker@isti.com
#######################################################################
License:
GNU Lesser General Public License, Version 3
This program 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 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser 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.
*/
#define rad2deg 180.0/M_PI
#define epsilon 1.e-13
static double numpy_mod(double a, double b);
static int __cmopad_argsort3(double *a, int *perm);
static int __cmopad_inv3(double Amat[3][3]);
static double __cmopad_determinant3x3(double A[3][3]);
static double __cmopad_trace3(double M[3][3]);
static int __cmopad_Eigs3x3(double a[3][3], int job, double eigs[3]);
static void __cmopad_swap8(double *a, double *b);
static void array_cross3(const double *__restrict__ u,
const double *__restrict__ v,
double *__restrict__ n);
//============================================================================//
/*!
* @brief Generates basis for coordinate transform switch
*
* @param[in] in_system input system: NED, USE, XYZ, NWU
* @param[in] out_system output system: NED, USE, XYZ, NWU
*
* @param[out] r rotation matrix [3 x 3]
*
* @result 0 in indicates success
*
*/
int cmopad_basis_switcher(enum cmopad_basis_enum in_system,
enum cmopad_basis_enum out_system, double r[3][3])
{
const char *fcnm = "cmopad_basis_switcher\0";
double From[9], To[9], r9[9];
double alpha = 1.0;
double beta = 0.0;
int n3 = 3;
int i, j;
//------------------------------------------------------------------------//
//
// null out to and from
for (i=0; i<9; i++)
{
To[i] = 0.0;
From[i] = 0.0;
}
// Classify in
if (in_system == NED)
{
// Inverse of identity: From[0] = 1.0; From[4] = 1.0; From[8] = 1.0 is:
From[0] = 1.0; From[4] = 1.0; From[8] = 1.0;
}
else if (in_system == USE)
{
From[3] =-1.0; From[7] = 1.0; From[2] =-1.0;
}
else if (in_system == XYZ)
{
From[3] = 1.0; From[1] = 1.0; From[8] =-1.0;
}
else if (in_system == NWU)
{
From[0] = 1.0; From[4] =-1.0; From[8] =-1.0;
}
else
{
printf("%s: Invalid in coordinate system %d\n", fcnm, in_system);
return -1;
}
// Classify out
if (out_system == NED)
{
To[0] = 1.0; To[4] = 1.0; To[8] = 1.0;
}
else if (out_system == USE)
{
// Inverse of: To[3] =-1.0; To[7] = 1.0; To[2] =-1.0; is
To[1] =-1.0; To[5] = 1.0; To[6] =-1.0;
}
else if (out_system == XYZ)
{
// Inverse of To[3] = 1.0; To[1] = 1.0; To[8] =-1.0; is:
To[1] = 1.0; To[3] = 1.0; To[8] =-1.0;
}
else if (out_system == NWU)
{
//Inverse of: To[0] = 1.0; To[4] =-1.0; To[8] =-1.0; is
To[0] = 1.0; To[4] =-1.0; To[8] =-1.0;
}
else
{
printf("%s: Invalid out coordinate system %d\n", fcnm, out_system);
return -1;
}
// Multiply inv(in)*out
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
n3, n3, n3, alpha, From, n3, To, n3, beta,
r9, n3);
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
r[i][j] = r9[3*j + i];
}
}
return 0;
}
//============================================================================//
/*!
* @brief Transform a matrix from in_sys to out_sys. This is an interface
* routine to cmopad_basis__transformMatrixM33
* because many matrices are stored as a length 6 array.
*
* @param[in,out] m on input length 6 matrix in in_sys. the ordering is
* \f$ {1,2,3,4,5,6} = {11,22,33,12,13,23} \f$.
* on output length 6 matrix in out_sys. the ordering is
* \f$ {1,2,3,4,5,6} = {11,22,33,12,13,23} \f$.
*
* @param[in] in_sys input system: NED, USE, XYZ, NWU
* @param[in] out_sys output system: NED, USE, XYZ, NWU
*
* @result 0 indicates success
*
*/
int cmopad_basis_transformMatrixM6(double *m,
enum cmopad_basis_enum in_sys,
enum cmopad_basis_enum out_sys)
{
const char *fcnm = "cmopad_basis_transformMatrixM6\0";
double M33[3][3];
int ierr;
//------------------------------------------------------------------------//
//
// Convert array matrix to matrix matrix
M33[0][0] = m[0]; //mxx; mrr
M33[1][1] = m[1]; //myy; mtt
M33[2][2] = m[2]; //mzz; mpp
M33[0][1] = M33[1][0] = m[3]; //mxy; mrt
M33[0][2] = M33[2][0] = m[4]; //mxz; mrp
M33[1][2] = M33[2][1] = m[5]; //myz; mtp
// Switch basis
ierr = cmopad_basis_transformMatrixM33(M33, in_sys, out_sys);
if (ierr != 0)
{
printf("%s: Error changing basis\n", fcnm);
return -1;
}
// Convert matrix matrix back to array matrix
m[0] = M33[0][0]; //mxx; mrr
m[1] = M33[1][1]; //myy; mtt
m[2] = M33[2][2]; //mzz; mpp
m[3] = M33[0][1]; //mxy; mrt
m[4] = M33[0][2]; //mxz; mrp
m[5] = M33[1][2]; //myz; mtp
return 0;
}
//============================================================================//
/*!
* @brief Transform a symmetric 3x3 matrix from in_sys to out_sys.
*
* @param[in,out] m on input [3x3] symmetric matrix in in_sys.
* on output [3x3] symmetric matrix in out_sys
*
* @param[in] in_sys input system: NED, USE, XYZ, NWU
* @param[in] out_sys output system: NED, USE, XYZ, NWU
*
* @result 0 indicates success
*
*/
int cmopad_basis_transformMatrixM33(double m[3][3],
enum cmopad_basis_enum in_sys,
enum cmopad_basis_enum out_sys)
{
const char *fcnm = "cmopad_basis_transformMatrixM33\0";
double r[3][3], t9[9], invR[3][3], invR9[9], r9[9], m9[9];
double alpha = 1.0;
double beta = 0.0;
int n3 = 3;
int i, j, ierr;
//------------------------------------------------------------------------//
//
// Compute change of basis matrix
ierr = cmopad_basis_switcher(in_sys, out_sys, r);
if (ierr != 0)
{
printf("%s: Error generating basis switching matrix\n",fcnm);
return -1;
}
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
r9[3*j + i] = r[i][j];
m9[3*j + i] = m[i][j];
//invR9[3*j + i] = r[i][j];
invR[i][j] = r[i][j];
}
}
// compute inv(R)
ierr = __cmopad_inv3(invR); //double Amat[3][3])
if (ierr != 0)
{
printf("%s: Unlikely error!\n", fcnm);
return -1;
}
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
invR9[3*j + i] = invR[i][j];
}
}
// Compute R M inv(R)
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
n3, n3, n3, alpha, m9, n3, invR9, n3, beta,
t9, n3);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,
n3, n3, n3, alpha, r9, n3, t9, n3, beta,
m9, n3);
// Copy back
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
m[i][j] = m9[3*j + i];
}
}
return 0;
}
//============================================================================//
/*!
* @brief Transforms a vector v from basis in_sys to basis out_sys
*
* @param[in,out] v on input length 3 vector in in_sys.
* on output length 3 vector in out_sys.
*
* @param[in] in_sys input system: NED, USE, XYZ, NWU
* @param[in] out_sys output system: NED, USE, XYZ, NWU
*
* @result 0 indicates success
*
*/
int cmopad_basis_transformVector(double v[3],
enum cmopad_basis_enum in_sys,
enum cmopad_basis_enum out_sys)
{
const char *fcnm = "cmopad_basis_transformVector\0";
double r[3][3], r9[9], x[3];
double alpha = 1.0;
double beta = 0.0;
int n3 = 3;
int incx = 1;
int incy = 1;
int i,j,ierr;
//------------------------------------------------------------------------//
//
// Compute change of basis matrix
ierr = cmopad_basis_switcher(in_sys, out_sys, r);
if (ierr != 0)
{
printf("%s: Error making basis switcher matrix\n", fcnm);
return -1;
}
for (i=0; i<3; i++)
{
x[i] = v[i];
for (j=0; j<3; j++)
{
r9[3*j + i] = r[i][j];
}
}
// Compute v <- R*v
cblas_dgemv(CblasColMajor, CblasNoTrans, n3, n3, alpha, r9,
n3, x, incx, beta, v, incy);
return 0;
}
//============================================================================//
/*!
* @brief Cross product of 2 length 3 vectors u and v. Returns normal vector n.
*
* @param[in] u first vector in cross product u x v [3]
* @param[in] v second vector in cross product u x v [3]
*
* @param[out] n normal vector n = u x v [3]
*
*/
static void array_cross3(const double *__restrict__ u,
const double *__restrict__ v,
double *__restrict__ n)
{
n[0] = u[1]*v[2] - u[2]*v[1];
n[1] = u[2]*v[0] - u[0]*v[2];
n[2] = u[0]*v[1] - u[1]*v[0];
return;
}
//============================================================================//
/*!
* @brief Converts the unit eigenvector of length eig in coordinate system
* coord to length, azimuth, plunge.
* http://docs.obspy.org/_modules/obspy/imaging/beachball.html#PrincipalAxis
* This is an extension of MoPaD
*
* @param[in] coord coordinate system (e.g., NED,USE,XYZ)
* @param[in] eig length of eigenvector
* @param[in] ev eigenvector in system coordinate system [3]
*
* @param[out] paxis principal axis store azimuth, plunge, length [3]
*
* @result 0 indicates success
*
*/
int cmopad_Eigenvector2PrincipalAxis(enum cmopad_basis_enum coord, double eig,
double ev[3], double paxis[3])
{
const char *fcnm = "cmopad_Eigenvector2PrincipalAxis\0";
double v[3], az, plunge;
double twopi = 2.0*M_PI;
double pi180i = 180.0/M_PI;
int ierr;
//------------------------------------------------------------------------//
//
// Convert eigenvector ev to USE convention
cblas_dcopy(3, ev, 1, v, 1);
ierr = cmopad_basis_transformVector(v, coord, USE);
if (ierr != 0)
{
printf("%s: Error switching basis\n", fcnm);
return -1;
}
// Compute azimuth and plunge angles
plunge = asin(-v[0]); //arcsin(-z/r)
az = atan2(v[2],-v[1]); //atan(x/y)
if (plunge <= 0.0)
{
plunge =-plunge;
az = az + M_PI;
}
if (az < 0.0){az = az + twopi;} //Shift to [0,360]
if (az > twopi){az = az - twopi;} //Shift to [0,360]
// Convert to degrees
plunge = plunge*pi180i;
az = az*pi180i;
// Copy back result
paxis[0] = az; //First value is azimuth (degrees)
paxis[1] = plunge; //Second value is plunge (degrees)
paxis[2] = eig; //Final value is eigenvalue (distance)
return 0;
}
//============================================================================//
/*!
* @brief Given coordinate system (x,y,z) and rotated system (xs,ys,zs)
* the line of nodes is the intersection between the x-y and the xs-ys
* planes.
*
* @param[in] alpha is the angle between the z-axis and the zs-axis
* and represents the dip angle (radians)
* @param[in] beta is the angle between the x-axis and the line of nodes
* and represents the strike (radians)
* @param[in] gamma is the angle between the line of nodes and the xs-axis
* and represents the rake angle (radians)
*
* @param[out] mat rotation matrix built from euler angles [3 x 3]
*
* @note Original Python usage for moment tensors:
*
* m_unrot = numpy.matrix([[0,0,-1],[0,0,0],[-1,0,0]])
* rotmat = cmopadEulerToMatrix(dip,strike,-rake)
* m = rotmat.T * m_unrot * rotmat'''
*
*/
void cmopad_eulerToMatrix(double alpha, double beta, double gamma,
double mat[3][3])
{
double ca, cb, cg, sa, sb, sg;
ca = cos(alpha);
cb = cos(beta);
cg = cos(gamma);
sa = sin(alpha);
sb = sin(beta);
sg = sin(gamma);
mat[0][0] = cb*cg-ca*sb*sg; mat[0][1] = sb*cg+ca*cb*sg; mat[0][2] = sa*sg;
mat[1][0] =-cb*sg-ca*sb*cg; mat[1][1] =-sb*sg+ca*cb*cg; mat[1][2] = sa*cg;
mat[2][0] = sa*sb; mat[2][1] =-sa*cb; mat[2][2] = ca;
return;
}
//============================================================================//
/*!
* @brief Computes the moment magnitude from a 6 vector
*
* @param[in] M6 moment tensor stored:
* \f$ \{m_{11},m_{22},m_{33},m_{12},m_{13},m_{23} \} \f$
* with the moment tensor terms of units Newton-meters
*
* @param[out] ierr 0 indicates success
*
* @result moment magnitue
*
* @author Ben Baker (ISTI)
*
*/
double cmopad_momentMagnitudeM6(const double M6[6], int *ierr)
{
const char *fcnm = "cmopad_momentMagnitudeM6\0";
double mag;
const double two_third = 2.0/3.0;
*ierr = 0;
mag = M6[0]*M6[0] + M6[1]*M6[1] + M6[2]*M6[2]
+ 2.0*(M6[3]*M6[3] + M6[4]*M6[4] + M6[5]*M6[5]);
if (mag == 0.0)
{
*ierr = 1;
printf("%s: Error magnitude is zero\n", fcnm);
}
else
{
mag = two_third*(log10(mag) - 9.1);
}
return mag;
}
//============================================================================//
/*!
* @brief Computes the moment magnitude from a the symmetric moment tensor
*
* @param[in] M symmetric moment tensor with terms given in Newton-meters
*
* @param[out] ierr 0 indicates success
*
* @result moment magnitue
*
* @author Ben Baker (ISTI)
*
*/
double cmopad_momentMagnitudeM3x3(const double M[3][3], int *ierr)
{
const char *fcnm = "cmopad_momentMagnitudeM33\0";
double M6[6], mag;
M6[0] = M[0][0];
M6[1] = M[1][1];
M6[2] = M[2][2];
M6[3] = M[0][1];
M6[4] = M[0][2];
M6[5] = M[1][2];
mag = cmopad_momentMagnitudeM6(M6, ierr);
if (*ierr != 0)
{
printf("%s: Error computing moment magnitude\n", fcnm);
}
return mag;
}
//============================================================================//
/*!
* @brief Sets the two angle-triples, describing the faultplanes of the
* Double Couple, defined by the eigenvectors P and T of the
* moment tensor object.
*
* Define a reference Double Couple with strike = dip =
* slip-rake = 0, the moment tensor object's DC is transformed
* (rotated) w.r.t. this orientation. The respective rotation
* matrix yields the first fault plane angles as the Euler
* angles. After flipping the first reference plane by
* multiplying the appropriate flip-matrix, one gets the second fault
* plane's geometry.
*
* All output angles are in degree
*
* @param[in] iverb controls verbosity for debugging. 0 should be quiet.
*
* @param[in,out] src on input holds plot_clr_order
* on output holds the strike, dips, and rakes
* describing fault planes fp1 and fp2
*
* @result 0 indicates success
*
*/
int cmopad_findFaultPlanes(int iverb, struct cmopad_struct *src)
{
const char *fcnm = "cmopad_findFaultPlanes\0";
int n3 = 3;
double rot_matrix_fp1[3][3], rot_matrix_fp2[3][3],
refDC_evecs[9], flip_dc[9], work1[9], work2[9],
pnt_sorted_EV_matrix[3][3],
det;
double sqrt22 = 0.7071067811865476; //sqrt(2)/2
double alpha = 1.0, beta = 0.0;
int i, j;
//------------------------------------------------------------------------//
//
// reference Double Couple (in NED) basis w/ (strike,dip,slip) = (0,0,0)
refDC_evecs[0] =-sqrt22; refDC_evecs[3] = 0.0; refDC_evecs[6] =-sqrt22;
refDC_evecs[1] = 0.0; refDC_evecs[4] = 1.0; refDC_evecs[7] = 0.0;
refDC_evecs[2] =-sqrt22; refDC_evecs[5] = 0.0; refDC_evecs[8] = sqrt22;
//refDC_evals[0] =-1.0;
//refDC_evals[1] = 0.0;
//refDC_evals[2] = 1.0;
// Matrix which is turning from one fault plane to the other
flip_dc[0] = 0.0; flip_dc[3] = 0.0; flip_dc[6] =-1.0;
flip_dc[1] = 0.0; flip_dc[4] =-1.0; flip_dc[7] = 0.0;
flip_dc[2] =-1.0; flip_dc[5] = 0.0; flip_dc[8] = 0.0;
// Euler-tools need matrices of EV sorted in PNT (pressure,null,tension):
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
pnt_sorted_EV_matrix[i][j] = src->rotation_matrix[i][j];
}
}
// Re-sort only necessary if abs(p) <= abs(t)
if (src->plot_clr_order < 0)
{
for (i=0; i<3; i++)
{
pnt_sorted_EV_matrix[i][0] = src->rotation_matrix[i][2];
pnt_sorted_EV_matrix[i][2] = src->rotation_matrix[i][0];
}
}
// Rotation matrix, describing the rotation of the eigenvector
// system of the input moment tensor into the eigenvector
// system of the reference Double Couple
if (iverb > 1)
{
printf("%s: Pressure, null, tension eigenvectors:\n",fcnm);
}
for (j=0; j<3; j++)
{
for (i=0; i<3; i++)
{
work1[j*n3 + i] = pnt_sorted_EV_matrix[i][j];
}
if (iverb > 1)
{
printf(
"%8.5f %8.5f %8.5f\n",pnt_sorted_EV_matrix[j][0],
pnt_sorted_EV_matrix[j][1],
pnt_sorted_EV_matrix[j][2]);
}
}
if (iverb > 1)
{
printf("%s: Reference double couple eigenvectors:\n",fcnm);
for (i=0; i<3; i++)
{
printf(
"%8.5f %8.5f %8.5f\n",refDC_evecs[i],
refDC_evecs[3+i],refDC_evecs[6+i]);
}
}
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n3, n3, n3,
alpha, work1, n3, refDC_evecs, n3, beta,
work2, n3);
for (j=0; j<3; j++)
{
for (i=0; i<3; i++)
{
rot_matrix_fp1[j][i] = work2[j*n3 + i]; //Copy transpose
}
}
// check if rotation has correct orientation
det = __cmopad_determinant3x3(rot_matrix_fp1);
if (det < 0.0)
{
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
rot_matrix_fp1[i][j] =-1.0*rot_matrix_fp1[i][j];
}
}
}
for (j=0; j<3; j++)
{
for (i=0; i<3; i++)
{
work1[j*3 + i] = rot_matrix_fp1[i][j];
}
}
// adding a rotation into the (ambiguous) system of the 2nd fault plane
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n3, n3, n3,
alpha, flip_dc, n3, work1, n3, beta,
work2, n3);
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
rot_matrix_fp2[i][j] = work2[j*3 + i];
}
}
// Calculate strike, dip, rake of fault planes
cmopad_findStrikeDipRake(rot_matrix_fp1,
&src->fp1[1], &src->fp1[0], &src->fp1[2]);
cmopad_findStrikeDipRake(rot_matrix_fp2,
&src->fp2[1], &src->fp2[0], &src->fp2[2]);
// For convenience if choose the first fault plane to be the one with
// the smaller strike
if (src->fp2[0] < src->fp1[0])
{
for (i=0; i<3; i++)
{
__cmopad_swap8(&src->fp1[i], &src->fp2[i]);
}
}
return 0;
}
//============================================================================//
/*!
* @brief Returns dip, strike, and slip(rake) angles in degrees describing the
* fault plane.
*
* @param[in] rot_mat matrix of eignevectors for fault plane [3 x 3]
*
* @param[out] alpha dip angle (degrees)
* @param[out] beta strike angle (degrees)
* @param[out] gamma rake angle (degrees)
*
*/
void cmopad_findStrikeDipRake(double rot_mat[3][3],
double *alpha, double *beta, double *gamma)
{
double a = 0.0, b = 0.0, g = 0.0;
cmopad_MatrixToEuler(rot_mat, &a, &b, &g);
*alpha = a*rad2deg;
*beta = b*rad2deg;
*gamma =-g*rad2deg;
return;
}
//============================================================================//
/*!
* @brief Returns three Euler angles alpha, beta, and gamma (radians) from a
* rotation matrix.
*
* @param[in] rotmat rotation matrix of which to decompose into euler angles
* [3 x 3]
*
* @param[out] alpha euler angle representing dip (radians)
* @param[out] beta euler angle representing strike (radians)
* @param[out] gamma euler angle representing -rake (radians)
*
*/
void cmopad_MatrixToEuler(double rotmat[3][3],
double *alpha, double *beta, double *gamma)
{
const int n3 = 3;
int inc = 1;
double ex[3], ez[3], exs[3], ezs[3], enodes[3], enodess[3],
xnorm, cos_alpha, a,b,g,a1,a2;
double twopi = 2.0*M_PI;
int i,j;
//------------------------------------------------------------------------//
//
// transpose matrix vector multiply
ex[0] = 1.0; ex[1] = 0.0; ex[2] = 0.0;
ez[0] = 0.0; ez[1] = 0.0; ez[2] = 1.0;
for (i=0; i<3; i++)
{
exs[i] = 0.0; ezs[i] = 0.0;
for (j=0; j<3; j++)
{
exs[i] = exs[i] + rotmat[j][i]*ex[j];
ezs[i] = ezs[i] + rotmat[j][i]*ez[j];
}
}
// Cross product
array_cross3(ez, ezs, enodes);
xnorm = sqrt(pow(enodes[0],2) + pow(enodes[1],2) + pow(enodes[2],2));
if (xnorm < 1.e-10)
{
for (i=0; i<3; i++)
{
enodes[i] = exs[i];
}
}
for (i=0; i<3; i++)
{
enodess[i] = 0.0;
for (j=0; j<3; j++)
{
enodess[i] = enodess[i] + rotmat[i][j]*enodes[j];
}
}
// Multiply
cos_alpha = cblas_ddot(n3, ez, inc, ezs, inc);
cos_alpha = fmin( 1.0, cos_alpha);
cos_alpha = fmax(-1.0, cos_alpha);
a = acos(cos_alpha);
a1 = atan2( enodes[1], enodes[0]);
a2 =-atan2(enodess[1], enodess[0]);
b = numpy_mod(a1, twopi);
g = numpy_mod(a2, twopi);
// Compute unique Euler angles
cmopad_uniqueEuler(&a, &b, &g);
*alpha = a;
*beta = b;
*gamma = g;
return;
}
//============================================================================//
/*!
* @brief Clone of the numpy mod(a,b) function
*
* @result numpy.mod(a, b)
*
*/
static double numpy_mod(double a, double b)
{
if (b == 0.0){return a;}
if (a >= 0.0)
{
if (b > 0.0)
{
return a - floor(a/b)*b;
}
else
{
return a - fabs(floor(a/b))*fabs(b);
}
}
else
{
if (b > 0.0)
{
return a + fabs(floor(a/b))*fabs(b);
}
else
{
return a + floor(a/b)*fabs(b);
}
}
}
//============================================================================//
/*!
* Read in Matrix M and set up eigenvalues (EW) and eigenvectors
* (EV) for setting up the principal axis system.
*
* The internal convention is the 'HNS'-system: H is the
* eigenvector for the smallest absolute eigenvalue, S is the
* eigenvector for the largest absolute eigenvalue, N is the null
* axis.
*
* Naming due to the geometry: a CLVD is
* Symmetric to the S-axis,
* Null-axis is common sense, and the third (auxiliary) axis
* Helps to construct the RA3.
*
* Additionally builds matrix for basis transformation back to NED system.
*
* The eigensystem setup defines the colouring order for a later
* plotting in the BeachBall class. This order is set by the
* `_plot_clr_order' attribute.
*
* @param[in] iverb controls verbosity. 0 is quiet.
*
* @param[in,out] src on input holds the input moment tensor
* on output has the eigenvalues and fault planes
*
*/
int cmopad_MT2PrincipalAxisSystem(int iverb, struct cmopad_struct *src)
{
const char *fcnm = "cmopad_MT2PrincipalAxisSystem\0";
int ival = 0;
double M[3][3], M_devi[3][3], EV_devi[3][3], EV[3][3], EW[3],
EW_devi[3], EV1[3], EV2[3], EV3[3], EVh[3], EVs[3], EVn[3],
EWs, EWh, EWn,
EW1, EW2, EW3, EW1_devi, EW2_devi, EW3_devi,
trace_M, xsum;
int EW_order[3], symmetry_around_tension, clr, i, j, ierr;
//------------------------------------------------------------------------//
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
M[i][j] = src->M[i][j];
M_devi[i][j] = src->M_devi[i][j];
EV[i][j] = M[i][j];
EV_devi[i][j] = M_devi[i][j];
}
}
ierr = __cmopad_Eigs3x3(EV_devi, ival, EW_devi);
if (ierr != 0)
{
printf("%s: Error computing eigenvalues (a)!", fcnm);
return -1;
}
ierr = __cmopad_argsort3(EW_devi, EW_order);
// Removed if statement, always true in python code
trace_M = __cmopad_trace3(M); // M[0][0] + M[1][1] + M[2][2];
if (trace_M < epsilon){trace_M = 0.0;}
ierr = __cmopad_Eigs3x3(EV, ival, EW);
if (ierr != 0)
{
printf("%s: Error computing eigenvalues (b)!", fcnm);
return -1;
}
for (i=0; i<3; i++)
{
if (fabs(EW[i]) < epsilon){EW[i] = 0.0;}
}
//trace_M_devi = cmopadTrace(3,M_devi);
// Save eigenvalues/eigenvectors for deviatoric and full moment tensor
EW1_devi = EW_devi[EW_order[0]];
EW2_devi = EW_devi[EW_order[1]];
EW3_devi = EW_devi[EW_order[2]];
if (fabs(EW2_devi) < epsilon){EW2_devi = 0.0;}
EW1 = EW[EW_order[0]];
EW2 = EW[EW_order[1]];
EW3 = EW[EW_order[2]];
for (i=0; i<3; i++)
{
//EV1_devi[i] = EV_devi[i][EW_order[0]];
//EV2_devi[i] = EV_devi[i][EW_order[1]];
//EV3_devi[i] = EV_devi[i][EW_order[2]];
EV1[i] = EV[i][EW_order[0]];
EV2[i] = EV[i][EW_order[1]];
EV3[i] = EV[i][EW_order[2]];
}
// Classify tension axis symmetry
symmetry_around_tension = 1;
clr = 1;
xsum = EW1 + EW2 + EW3;
// implosion
if (EW1 < 0.0 && EW2 < 0.0 && EW3 < 0.0)
{
if (iverb > 2){printf("%s: Implosion\n", fcnm);}
symmetry_around_tension = 0;
clr = 1;
}
// explosion
else if (EW1 > 0.0 && EW2 > 0.0 && EW3 > 0.0)
{
if (iverb > 2){printf("%s: Explosion\n", fcnm);}
symmetry_around_tension = 1;
if (fabs(EW1_devi) > fabs(EW3_devi))
{
symmetry_around_tension = 0;
}
clr = -1;
}
// net-implosion
else if (EW2 < 0.0 && xsum < 0.0)
{
if (iverb > 2){printf("%s: Net-implosion (1)\n", fcnm);}
if (fabs(EW1_devi) < fabs(EW3_devi))
{
symmetry_around_tension = 1;
clr = 1;
}
else
{
symmetry_around_tension = 1;
clr = 1;
}
}
// net-implosion
else if (EW2_devi >= 0.0 && xsum < 0.0)
{
if (iverb > 2){printf("%s: Net-impolosion (2)\n", fcnm);}
symmetry_around_tension = 0;
clr = -1;
if (fabs(EW1_devi) < fabs(EW3_devi))
{
symmetry_around_tension = 1;
clr = 1;
}
}
// net-explosion
else if (EW2_devi < 0.0 && xsum > 0.0)
{
if (iverb > 2){printf("%s: Net-explosion (1)\n", fcnm);}
symmetry_around_tension = 1;
clr = 1;
if (fabs(EW1_devi) > fabs(EW3_devi))
{
symmetry_around_tension = 0;
clr = -1;
}
}
// net-explosion
else if ( EW2_devi >= 0.0 && xsum > 0.0)
{
if (iverb > 2){printf("%s: Net-explosion (2)\n", fcnm);}
symmetry_around_tension = 0;
clr = -1;
}
else
{
// If the trace is 0 to machine epsilon then purely deviatoric
if (trace_M/fmax(fabs(EW1_devi),fabs(EW3_devi)) > 1.e-10){ //!= 0.0){
printf("%s: Warning should not be here %f %f %f\n",
fcnm, EW2_devi, trace_M, xsum);
}
}
if (iverb > 1)
{
printf("%s: sym/clr %d %d\n",
fcnm, symmetry_around_tension, clr);
}
// Deviatoric classification
if (fabs(EW1_devi) < fabs(EW3_devi))
{
symmetry_around_tension = 1;
clr = 1;
}
if (fabs(EW1_devi) >= fabs(EW3_devi))
{
symmetry_around_tension = 0;
clr = -1;
}
//explosive src with all neg evals? - TODO: email lars. an edge
//case is (-1,-1,-1, 0,0,0) which has trace_M == 0.0 and is a pure
//implosion. in this case there is a breakdown of the code because
//trace_M == 0.0
if (EW3 < 0.0 && trace_M > 0.0)
{
printf("%s: Critical error!\n", fcnm);
return -1;
}
// Classify pure deviatoric - pure deviatoric
if (trace_M == 0.0)
{
if (iverb > 1){printf("%s: Pure-deviatoric\n", fcnm);}
// pure shear
if (EW2 == 0.0)
{
if (iverb > 1){printf("%s: Pure-shear\n", fcnm);}
symmetry_around_tension = 1;
clr = 1;
}
else if (2.0*fabs(EW2) == fabs(EW1) || 2.0*fabs(EW2) == fabs(EW3))
{
if (iverb > 1){printf("%s: Pure CLVD\n", fcnm);}
// CLVD symmetry around tension
if (fabs(EW1) < EW3)
{
if (iverb > 2)
{
printf("%s: CLVD symmetry around tension\n", fcnm);
}
symmetry_around_tension = 1;
clr = 1;
}
// CLVD symmetry around pressure
else
{
if (iverb > 2)
{
printf("%s: CLVD symmetry around pressure\n", fcnm);
}
symmetry_around_tension = 0;
clr = -1;
}
}
// mix of DC and CLVD
else
{
if (iverb > 1)
{
printf("%s: Mix of DC and CLVD\n", fcnm);
}
// symmetry around tension
if (fabs(EW1) < EW3)
{
if (iverb > 2)
{
printf("%s: Symmetry around tension\n", fcnm);
}
symmetry_around_tension = 1;
clr = 1;
}
// symmetry around pressure
else
{
if (iverb > 2)
{
printf("%s: Symmetry around pressure\n", fcnm);
}
symmetry_around_tension = 0;
clr = -1;
}
}
}
if (iverb > 0)
{
printf("%s: Final symmetry %d %d\n",
fcnm, symmetry_around_tension, clr);
}
// Define order of eigenvectors and values according to symmetry axis
if (symmetry_around_tension == 1)
{
EWs = EW3;
EWh = EW1;
EWn = EW2;
for (i=0; i<3; i++)
{
EVs[i] = EV3[i];
EVh[i] = EV1[i];
EVn[i] = EV2[i];
}
}
else
{
EWs = EW1;
EWh = EW3;
EWn = EW2;
for (i=0; i<3; i++)
{
EVs[i] = EV1[i];
EVh[i] = EV3[i];
EVn[i] = EV2[i];
}
}
// Order of eigenvector's basis: (H,N,S)
for (i=0; i<3; i++)
{
// Matrix for basis transform
src->rotation_matrix[i][0] = EVh[i];
src->rotation_matrix[i][1] = EVn[i];
src->rotation_matrix[i][2] = EVs[i];
// Save eigenvectors
src->eigenvectors[i][0] = EVh[i];
src->eigenvectors[i][1] = EVn[i];
src->eigenvectors[i][2] = EVs[i];
// Principal axis
src->p_axis[i] = EV1[i]; //Smallest (most negative) eval/evec pair
src->null_axis[i] = EVn[i]; //Intermediate eval/evec pair
src->t_axis[i] = EV3[i]; //Largest (most positive) eval/evec pair
/* TODO the above is definitionally correct but the following works.
What's going on here? Did someone switch conventions on me? */
//src->t_axis[i] = EV1[i];
//src->null_axis[i] = EVn[i];
//src->p_axis[i] = EV3[i];
}
src->eig_pnt[0] = EW1_devi; // Smallest - most negative eigenvalue
src->eig_pnt[1] = EW2_devi;
src->eig_pnt[2] = EW3_devi; // Largest eigenvalue
// TODO - these are reversed to match above t_axis, null_axis, and p_axis
//printf("%f %f\n", EW1_devi, EW3_devi);
//src->eig_pnt[0] = EW3_devi; // Make pressure most positive eigenvalue?
//src->eig_pnt[1] = EW2_devi;
//src->eig_pnt[2] = EW1_devi; // Make tension most negative eigenvalue
// Eigenvalues corresponding to eigenvectors (H,N,S) basis
src->eigenvalues[0] = EWh;
src->eigenvalues[1] = EWn;
src->eigenvalues[2] = EWs;
// Important for plot in BeachBall class (also used in FindFaultPlanes)
src->plot_clr_order = clr;
ierr = cmopad_findFaultPlanes(iverb, src);
if (ierr != 0)
{
printf("%s: Error computing fault planes!\n", fcnm);
}
return ierr;
}
//============================================================================//
/*!
* @brief Prints a 3x3 matrix in a Mopad-esque style.
*
* @param[in] lfact if true then use a normalization factor
* @param[in] m the 3x3 matrix to write to standard out
*
*/
void cmopad_printMatrix3x3(bool lfact, double m[3][3])
{
const char *fcnm = "cmopad_printMatrix3x3\0";
double norm_fact, m11,m22,m33,m12,m13,m23;
int i,j;
//------------------------------------------------------------------------//
norm_fact = 1.0;
if (lfact)
{
norm_fact = 0.0;
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
//norm_fact = fmax(norm_fact,fabs(mathRound(m[i][j],5)));
norm_fact = fabs(m[i][j]);
}
}
if (norm_fact == 0.0)
{
printf("%s: Warning norm_fact = 0.0!\n", fcnm);
return;
}
}
m11 = m[0][0]/norm_fact;
m22 = m[1][1]/norm_fact;
m33 = m[2][2]/norm_fact;
m12 = m[0][1]/norm_fact;
m13 = m[0][2]/norm_fact;
m23 = m[1][2]/norm_fact;
if (lfact)
{
printf(" [ %5.2f %5.2f %5.2f ] \n",m11,m12,m13);
printf(" [ %5.2f %5.2f %5.2f ] x %f\n",
m12,m22,m23,norm_fact);
printf(" [ %5.2f %5.2f %5.2f ] \n",m13,m23,m33);
}
else
{
printf(" [ %5.2f %5.2f %5.2f ]\n",m11,m12,m13);
printf(" [ %5.2f %5.2f %5.2f ]\n",m12,m22,m23);
printf(" [ %5.2f %5.2f %5.2f ]\n",m13,m23,m33);
}
return;
}
//============================================================================//
/*!
* @brief Brings the provided mechanism into symmetric 3x3 matrix form.
*
* The source mechanism may be provided in different forms:
*
* -- as 3x3 matrix - symmetry is checked - one basis
* system has to be chosen, or NED as default is taken
* -- as 3-element tuple or array - interpreted as
* strike, dip, slip-rake angles in degree
* -- as 4-element tuple or array - interpreted as strike, dip,
* slip-rake angles in degree + seismic scalar moment in Nm
* -- as 6-element tuple or array - interpreted as the 6 independent
* entries of the moment tensor
* -- as 7-element tuple or array - interpreted as the 6 independent
* entries of the moment tensor + seismic scalar moment in Nm
* -- as 9-element tuple or array - interpreted as the 9 entries
* of the moment tensor - checked for symmetry
* -- as a nesting of one of the upper types (e.g. a list of
* n-tuples) - first element of outer nesting is taken
*
*/
int cmopad_SetupMT(int nmech, double *mech,
enum cmopad_basis_enum input_basisIn,
double Mech_out[3][3])
{
const char *fcnm = "cmopad_SetupMT\0";
enum cmopad_basis_enum input_basis;
double rotmat[9], mtemp1[9], mtemp2[9], m_unrot[9], scalar_moment,
strike, dip, rake;
int i, j, ierr;
double pi180 = M_PI/180.0;
double alpha = 1.0;
double beta = 0.0;
int n3 = 3;
//------------------------------------------------------------------------//
//
// All 9 elements are specified
input_basis = input_basisIn;
if (nmech == 9)
{
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
Mech_out[i][j] = mech[3*j + i];
}
}
}
// Mechanism given as 6 or 7 element array
else if (nmech == 6 || nmech == 7)
{
scalar_moment = 1.0;
if (nmech == 7){scalar_moment = mech[6];}
Mech_out[0][0] = scalar_moment*mech[0];
Mech_out[1][1] = scalar_moment*mech[1];
Mech_out[2][2] = scalar_moment*mech[2];
Mech_out[0][1] = Mech_out[1][0] = scalar_moment*mech[3];
Mech_out[0][2] = Mech_out[2][0] = scalar_moment*mech[4];
Mech_out[1][2] = Mech_out[2][1] = scalar_moment*mech[5];
}
// Strike dip rake; conventions from Jost and Herrmann; NED-basis
else if (nmech == 3 || nmech == 4)
{
scalar_moment = 1.0;
if (nmech == 4){scalar_moment = mech[3];}
// Set matrix as function of Euler angles
strike = mech[0]*pi180;
dip = mech[1]*pi180;
rake = mech[2]*pi180;
cmopad_eulerToMatrix(dip, strike, -rake, Mech_out);
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
m_unrot[3*j + i] = 0.0;
rotmat[3*j + i] = Mech_out[i][j];
mtemp1[3*j + i] = 0.0;
mtemp2[3*j + i] = 0.0;
}
}
m_unrot[6] =-1.0;
m_unrot[2] =-1.0;
// Multiply trans(Rotmat)*m_unrot*Rotmat
cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, n3, n3, n3,
alpha, rotmat, n3, m_unrot, n3, beta,
mtemp1, n3);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n3, n3, n3,
alpha, rotmat, n3, mtemp1, n3, beta,
mtemp2, n3);
// Copy back and include scalar moment
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
Mech_out[i][j] = scalar_moment*mtemp2[3*j + i];
}
}
// Assure right basis system
input_basis = NED;
}
// Unknown mechanism
else
{
printf("%s: Invalid mechanism!\n", fcnm);
return -1;
}
// Rotate into NED basis for local processing
ierr = cmopad_basis_transformMatrixM33(Mech_out, input_basis, NED);
if (ierr != 0)
{
printf("%s: Error transforming matrix\n", fcnm);
return -1;
}
return 0;
}
//============================================================================//
/*!
* @brief Sorts eigenvalues/eigenvectors of a matrix into ascending order.
* Optionally, can sort based on the absolute magnitude of eigenvalues
*
* @param[in] isabs if true then sort on absolute value of eigenvalues
*
* @param[in,out] e eigenvalues sorted in ascending order [3]
* @param[in,out] ev corresponding eigenvectors sorted along with eigenvalues
* [3 x 3]
*
* @result 0 indicates success
*
*/
int cmopad_sortEigenvAscending(bool isabs, double e[3], double ev[3][3])
{
const char *fcnm = "cmopad_sortEigenvAscending\0";
const int n = 3;
double evwork[3][3], ework[3], esave[3];
int iperm[3], i, ierr, j;
ierr = 0;
for (i=0; i<n; i++)
{
esave[i] = e[i];
if (isabs)
{
ework[i] = fabs(e[i]);
}
else
{
ework[i] = e[i];
}
for (j=0; j<n; j++)
{
evwork[i][j] = ev[i][j];
}
}
// Sort
ierr = __cmopad_argsort3(ework, iperm);
if (ierr != 0)
{
printf("%s: Error in permutation sort\n", fcnm);
return -1;
}
// Copy back into ascending order
for (i=0; i<n; i++)
{
e[i] = esave[iperm[i]];
for (j=0; j<n; j++)
{
ev[i][j] = evwork[i][iperm[j]];
}
}
return ierr;
}
//============================================================================//
/*!
* @brief Decomposes the input moment tensor Min in the North, East, Down
* coordinates into an isotropic, compensated linear vector dipole,
* and pure double couple.
*
* @param[in] Min 3 x 3 moment tensor in NED coordinates to decompose
* into a pure isotropic, CLVD, and DC
*
* @param[out] src internal mopad structure. this routine will compute:
* M: copy of the original moment tensor
* M_iso: diagonal isotropic moment tensor
* M_devi: deviatoric moment tensor (M - M_iso)
* M_CLVD: CLVD contribution to M_devi
* M_DC: DC contribution to M_devi
* DC_percentage: Percent (0,100) double couple
* CLVD_percentage: Percent (0,100) CLVD
* ISO_Percetnage: Percent (0,100) isotropic
* seismic_moment: seismic moment (Nm) Bowers & Hudson
* 1999
* moment_magnitude: moment magnitude Hanks and Kanamori
* 1979
*
* @result 0 indicates success
*
*/
int cmopad_standardDecomposition(double Min[3][3], struct cmopad_struct *src)
{
const char *fcnm = "cmopad_standardDecomposition\0";
double M[3][3], M_devi[3][3], M_iso[3][3],
M_DC[3][3], M_CLVD[3][3], eigenvtot[3][3], eigenvdevi[3][3],
a3out, a2out, a1out, eigenwtot[3], eigenwdevi[3],
a1[3], a2[3], a3[3];
double M0, M0_iso, M0_devi, F, M_DC_percentage, M_iso_percentage, tracem;
int lsub, i,j, ierr;
int ival = 0; //Calculate eigenvalues only (1)
// Copy
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
M[i][j] = Min[i][j];
}
}
// Isotropic part
tracem = __cmopad_trace3(M); //M[0][0] + M[1][1] + M[2][2];
M_iso[0][0] = M_iso[0][1] = M_iso[0][2] = 0.0;
M_iso[1][0] = M_iso[1][1] = M_iso[1][2] = 0.0;
M_iso[2][0] = M_iso[2][1] = M_iso[2][2] = 0.0;
M_iso[0][0] = M_iso[1][1] = M_iso[2][2] = (1.0/3.0)*tracem;
M0_iso = fabs(1.0/3.0*tracem);
// Deviatoric part
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
M_devi[i][j] = M[i][j] - M_iso[i][j];
}
}
// Copy to structure
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
src->M[i][j] = M[i][j];
src->M_iso[i][j] = M_iso[i][j];
src->M_devi[i][j] = M_devi[i][j];
}
}
// Eigenvalues and eigenvectors
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
eigenvtot[i][j] = M_devi[i][j]; //I dont understand this
eigenvdevi[i][j]= M_devi[i][j];
}
}
ierr = __cmopad_Eigs3x3(eigenvtot, ival, eigenwtot);
if (ierr != 0)
{
printf("%s: Error computing eigs (a)!\n",fcnm);
return -1;
}
ierr = __cmopad_Eigs3x3(eigenvdevi, ival, eigenwdevi);
if (ierr != 0)
{
printf("%s: Error computing eigs (b)!\n",fcnm);
return -1;
}
// Eigenvalues in ascending order
ierr = ierr + cmopad_sortEigenvAscending(true, eigenwtot , eigenvtot);
ierr = ierr + cmopad_sortEigenvAscending(true, eigenwdevi, eigenvdevi);
if (ierr != 0)
{
printf("%s: Error sorting eigenvalues/eigenvectors\n", fcnm);
return -1;
}
/* TODO: Email Lars Krieger; confirm this is a mistake
: Jost and Herrmann Eqn 19
M0_devi =-1.0;
for (i=0; i<3; i++){
M0_devi = fmax(M0_devi, fabs(eigenwdevi[i]));
}
*/
// Compute mangnitude (Jost and Herrmann Eqn 19 noting the eigenvalues are
// in ascending order)
M0_devi = 0.5*(fabs(eigenwdevi[1]) + fabs(eigenwdevi[2]));
// Named according to Jost and Herrmann
for (i=0; i<3; i++)
{
a1[i] = eigenvtot[i][0];
a2[i] = eigenvtot[i][1];
a3[i] = eigenvtot[i][2];
}
// If only isotropic part exists
if (M0_devi < epsilon)
{
F = 0.5;
}
else
{
F =-eigenwdevi[0]/eigenwdevi[2];
}
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
a3out = a3[i]*a3[j];
a2out = a2[i]*a2[j];
a1out = a1[i]*a1[j];
// Second term of eqn 37 Jost and Herrmann
M_DC[i][j] = eigenwdevi[2]*(1.0 - 2.0*F)*(a3out - a2out);
// Remainder of deviatoric is CLVD (could do 3rd term of eqn 37)
lsub = 1;
if (lsub == 1)
{
M_CLVD[i][j] = M_devi[i][j] - M_DC[i][j];
}
else
{
M_CLVD[i][j] = eigenwdevi[2]*F
*(2.0*a3out - a2out - a1out);
}
}
}
//according to Bowers & Hudson:
M0 = M0_iso + M0_devi;
// Really shouldn't be rounding
/*
M_iso_percentage = mathRound(M0_iso/M0*100.0,6);
//cmopad.iso_percentage = M_iso_percentage;
M_DC_percentage = ( mathRound( (1.0 - 2.0*fabs(F))
*(1.0 - M_iso_percentage/100.0)*100,6));
*/
M_iso_percentage = M0_iso/M0*100.0;
M_DC_percentage = (1.0 - 2.0*fabs(F))*(1.0 - M_iso_percentage/100.0)*100.0;
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
src->DC[i][j] = M_DC[i][j];
src->CLVD[i][j] = M_CLVD[i][j];
}
}
src->DC_percentage = M_DC_percentage;
src->ISO_percentage = M_iso_percentage;
src->DEV_percentage = 100.0 - src->ISO_percentage;
src->CLVD_percentage = 100.0 - src->ISO_percentage - src->DC_percentage;
////src->seismic_moment = sqrt(1./2.0*(pow(eigenw[0],2) + pow(eigenw[0],2) + pow(eigenw[0],2)));
src->seismic_moment = M0;
src->moment_magnitude = log10(src->seismic_moment*1.0e7)/1.5 - 16.1/1.5;
return 0;
}
//============================================================================//
/*!
* @brief Return 6-tuple containing entries of M, calculated from fault plane
* angles (defined as in Jost&Herman), given in degrees.
* Basis for output is NED (= X,Y,Z)
*
* @param[in] strike angle clockwise between north and plane (in [0,360])
* @param[in] dip angle between surface and dipping plane (in [0,90])
* 0 = horizontal, 90 = vertical
* @param[in] rake angle on the rupture plane between strike vector
* and actual movement (defined mathematically
* counter-clockwise rotation is positive)
*
* @param[out] moments M = {M_nn, M_ee, M_dd, M_ne, M_nd, M_ed}
*
*/
void cmopad_strikeDipRake2MT6(double strike, double dip, double rake,
double moments[6])
{
double M1,M2,M3,M4,M5,M6;
double S_rad = strike/rad2deg;
double D_rad = dip/rad2deg;
double R_rad = rake/rad2deg;
//-------------------------------------------------------------------------//
if (fabs(S_rad) < epsilon){S_rad = 0.0;}
if (fabs(D_rad) < epsilon){D_rad = 0.0;}
if (fabs(R_rad) < epsilon){R_rad = 0.0;}
M1 =-( sin(D_rad)*cos(R_rad)*sin(2.0*S_rad)
+ sin(2.0*D_rad)*sin(R_rad)*pow(sin(S_rad),2) );
M2 = ( sin(D_rad)*cos(R_rad)*sin(2.0*S_rad)
- sin(2.0*D_rad)*sin(R_rad)*pow(cos(S_rad),2) );
M3 = sin(2.0*D_rad)*sin(R_rad);
M4 = sin(D_rad)*cos(R_rad)*cos(2.0*S_rad)
+ 0.5*sin(2.0*D_rad)*sin(R_rad)*sin(2.0*S_rad);
M5 =-( cos(D_rad)*cos(R_rad)*cos(S_rad)
+ cos(2.0*D_rad)*sin(R_rad)*sin(S_rad) );
M6 =-( cos(D_rad)*cos(R_rad)*sin(S_rad)
- cos(2.0*D_rad)*sin(R_rad)*cos(S_rad));
moments[0] = M1;
moments[1] = M2;
moments[2] = M3;
moments[3] = M4;
moments[4] = M5;
moments[5] = M6;
return;
}
//============================================================================//
/*!
* @brief Uniquify euler angle triplet.
*
* Puts euler angles into ranges compatible with (dip,strike,-rake) in
* seismology:
*
* @param[in,out] alpha dip angle to put into range [0, pi/2]
* @param[in,out] beta strike angle to put into range [0, 2*pi)
* @param[in,out] gamma -rake angle to put into range [-pi, pi)
*
* @note If alpha is near to zero, beta is replaced by beta+gamma and gamma is
* set to zero, to prevent that additional ambiguity.
*
* If alpha is near to pi/2, beta is put into the range [0,pi).
*
*/
void cmopad_uniqueEuler(double *alpha, double *beta, double *gamma)
{
const char *fcnm = "cmopad_uniqueEuler\0";
*alpha = numpy_mod(*alpha, 2.0*M_PI);
if (0.5*M_PI < *alpha && *alpha <= M_PI)
{
*alpha = M_PI - *alpha;
*beta = *beta + M_PI;
*gamma = 2.0*M_PI - *gamma;
}
else if(M_PI < *alpha && *alpha <= 1.5*M_PI)
{
*alpha = *alpha - M_PI;
*gamma = M_PI - *gamma;
}
else if(1.5*M_PI < *alpha && *alpha <= 2.0*M_PI)
{
*alpha = 2.0*M_PI - *alpha;
*beta = *beta + M_PI;
*gamma = M_PI + *gamma;
}
*alpha = numpy_mod(*alpha, 2.0*M_PI);
*beta = numpy_mod(*beta, 2.0*M_PI);
*gamma = numpy_mod(*gamma+M_PI, 2.0*M_PI) - M_PI;
// If dip is exactly 90 degrees, one is still
// free to choose between looking at the plane from either side.
// Choose to look at such that beta is in the range [0,180)
// This should prevent some problems, when dip is close to 90 degrees:
if (fabs(*alpha - 0.5*M_PI) < 1e-10){*alpha = 0.5*M_PI;}
if (fabs(*beta - M_PI) < 1e-10){*beta = M_PI;}
if (fabs(*beta - 2.*M_PI) < 1e-10){*beta = 0.;}
if (fabs(*beta) < 1e-10){*beta = 0.;}
if ((fabs(*alpha - 0.5*M_PI) < 1.e-14) && *beta >= M_PI)
{
*gamma =-*gamma;
*beta = numpy_mod(*beta-M_PI, 2.0*M_PI);
*gamma = numpy_mod(*gamma+M_PI, 2.0*M_PI) - M_PI;
if (!(0. <= *beta && *beta < M_PI))
{
printf("%s: Warning on bounds on beta!", fcnm);
}
if (!(-M_PI <= *gamma && *gamma < M_PI))
{
printf("%s: Warning on bounds on gamma!", fcnm);
}
}
if (*alpha < 1e-7)
{
*beta = numpy_mod(*beta + *gamma, 2.0*M_PI);
*gamma = 0.;
}
return;
}
//============================================================================//
/*!
* @brief Ascending argument sort for three numbers. For more information:
* http://stackoverflow.com/questions/4367745/simpler-way-of-sorting-three-numbers
*
* @param[in] x array to sort into ascending[3]
*
* @param[out] iperm permutation such that x3[iperm[:]] is in ascending
* order
*
*/
static int __cmopad_argsort3(double x[3], int iperm[3])
{
const char *fcnm = "__cmopad_argsort3\0";
int i, temp;
const int a = 0;
const int b = 1;
const int c = 2;
// Copy
iperm[a] = a;
iperm[b] = b;
iperm[c] = c;
if (x[iperm[a]] > x[iperm[c]])
{
temp = iperm[c];
iperm[c] = iperm[a];
iperm[a] = temp;
}
if (x[iperm[a]] > x[iperm[b]])
{
temp = iperm[b];
iperm[b] = iperm[a];
iperm[a] = temp;
}
//Now the smallest element is the first one. Just check the 2-nd and 3-rd
if (x[iperm[b]] > x[iperm[c]])
{
temp = iperm[c];
iperm[c] = iperm[b];
iperm[b] = temp;
}
// Verify
for (i=1; i<3; i++)
{
if (x[iperm[i-1]] > x[iperm[i]])
{
printf("%s: Failed to sort numbers in ascending order\n", fcnm);
return -1;
}
}
return 0;
}
//============================================================================//
/*!
* @brief Determinant of a 3 x 3 matrix
*
* @result determinant of a 3 x 3 matrix
*
*/
static double __cmopad_determinant3x3(double A[3][3])
{
double determinant;
determinant = A[0][0]*( A[1][1]*A[2][2] - A[1][2]*A[2][1])
- A[0][1]*( A[1][0]*A[2][2] - A[1][2]*A[2][0])
+ A[0][2]*( A[1][0]*A[2][1] - A[1][1]*A[2][0]);
return determinant;
}
//============================================================================//
/*!
* @brief Computes the inverse of a 3 x 3 matrix
*
* @param[in,out] Amat on input the 3 x 3 matrix to invert.
* on output the inverted matrix
*
* @result 0 indicates success
*
*/
static int __cmopad_inv3(double Amat[3][3])
{
const char *fcnm = "__cmopad_inv3\0";
double a11, a12, a13, a21, a22, a23, a31, a32, a33, detA, detAi;
// Determinant of a
detA = __cmopad_determinant3x3(Amat);
if (detA == 0.0)
{
printf("%s: Error matrix is singular!\n", fcnm);
return -1;
}
detAi = 1.0/detA;
a11 = Amat[0][0]; a12 = Amat[0][1]; a13 = Amat[0][2];
a21 = Amat[1][0]; a22 = Amat[1][1]; a23 = Amat[1][2];
a31 = Amat[2][0]; a32 = Amat[2][1]; a33 = Amat[2][2];
// Row 1
Amat[0][0] = detAi*(a22*a33 - a32*a23);
Amat[0][1] = detAi*(a13*a32 - a12*a33);
Amat[0][2] = detAi*(a12*a23 - a13*a22);
// Row 2
Amat[1][0] = detAi*(a23*a31 - a21*a33);
Amat[1][1] = detAi*(a11*a33 - a13*a31);
Amat[1][2] = detAi*(a13*a21 - a11*a23);
// Row 3
Amat[2][0] = detAi*(a21*a32 - a22*a31);
Amat[2][1] = detAi*(a12*a31 - a11*a32);
Amat[2][2] = detAi*(a11*a22 - a12*a21);
return 0;
}
//============================================================================//
/*!
* @brief Computes the trace (sum of diagonal) of a 3x3 matrix
*
* @param[in] M matrix of which to compute trace
*
* @result trace of matrix
*
*/
static double __cmopad_trace3(double M[3][3])
{
double trace;
trace = M[0][0] + M[1][1] + M[2][2];
return trace;
}
//===========================================================================//
/*!
* @brief Calculates all eigenvalues and eigenvectors (job = 0) of a
* symmetric 3 x 3 matrix using LAPACK.
*
* @param[in,out] a on input matrix of which to calculate eigenvalues
* and optionally eigenvectors.
* on output if the eigenvectors are desired they are
* stored on a
*
* @param[in] job = 0 calculate eigenvectors, otherwise, just eigenvalues
*
* @param[out] eigs eigenvalues of matrix a [3]
*
* @result 0 indicates success
*
* @author B. Baker (ISTI)
* @date April 2016
*/
static int __cmopad_Eigs3x3(double a[3][3], int job, double eigs[3])
{
const char *fcnm = "__cmopad_Eigs3x3\0";
double avec[9];
int n = 3;
int i, j, indx, ierr;
int lda = n;
for (i = 0; i < n; i++)
{
for (j = i; j < n; j++)
{
// fill lower half
if (i != j)
{
indx = i * lda + j;
avec[indx] = a[j][i];
}
indx = j * lda + i;
avec[indx] = a[i][j];
}
}
// Calculate eigenvalues/eigenvectors
if (job != 0)
{
ierr = LAPACKE_dsyev(LAPACK_COL_MAJOR, 'N', 'L', n, avec, lda, eigs);
}
else
{
ierr = LAPACKE_dsyev(LAPACK_COL_MAJOR, 'V', 'L', n, avec, lda, eigs);
}
if (ierr != 0)
{
printf("%s: Error computing eigenvalues\n", fcnm);
ierr = 1;
}
// Copy eigenvectors back onto A
if (job == 0 && ierr == 0)
{
indx = 0;
for (j = 0; j < n; j++)
{
for (i = 0; i < n; i++)
{
indx = j * lda + i;
a[i][j] = avec[indx];
}
}
}
return 0;
}
/*!
* @brief Function for swapping to two numbers a, b
*
* @param[in,out] a on input a = a, on output a = b
* @param[in,out] b on input b = b, on output b = a
*
*/
static void __cmopad_swap8(double *a, double *b)
{
double temp;
temp = *a;
*a = *b;
*b = temp;
return;
}
| {
"alphanum_fraction": 0.4963271514,
"avg_line_length": 31.2571582928,
"ext": "c",
"hexsha": "fffe93dabcae2db33b27ed8f59be55e424960289",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-28T13:42:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-08T00:13:50.000Z",
"max_forks_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "carltape/mtbeach",
"max_forks_repo_path": "c_src/unit_tests/cmopad.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_issues_repo_issues_event_max_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-02T17:30:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "carltape/mtbeach",
"max_issues_repo_path": "c_src/unit_tests/cmopad.c",
"max_line_length": 103,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "188058083602cebf1471ea88939b07999c90b655",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "OUCyf/mtbeach",
"max_stars_repo_path": "c_src/unit_tests/cmopad.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-28T23:55:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-03-13T01:18:12.000Z",
"num_tokens": 18438,
"size": 57857
} |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
int main(int argc, char *argv[]) {
unsigned long seed = 1234;
int n = 10;
if (argc > 1)
n = atoi(argv[1]);
gsl_rng_env_setup();
gsl_rng *rng = gsl_rng_alloc(gsl_rng_mt19937);
gsl_rng_set(rng, seed);
for (int i = 0; i < n; i++) {
double x = gsl_rng_uniform(rng);
printf("%.12f\n", x);
}
gsl_rng_free(rng);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.5881188119,
"avg_line_length": 21.9565217391,
"ext": "c",
"hexsha": "5e8cd47ef7ffca185cc21f68658bd5764f75b6ac",
"lang": "C",
"max_forks_count": 59,
"max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z",
"max_forks_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "Gjacquenot/training-material",
"max_forks_repo_path": "Math/GSL/RNGs/generate_uniform_distr.c",
"max_issues_count": 56,
"max_issues_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "Gjacquenot/training-material",
"max_issues_repo_path": "Math/GSL/RNGs/generate_uniform_distr.c",
"max_line_length": 50,
"max_stars_count": 115,
"max_stars_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "Gjacquenot/training-material",
"max_stars_repo_path": "Math/GSL/RNGs/generate_uniform_distr.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z",
"num_tokens": 154,
"size": 505
} |
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
// MAX and MIN aren't defined in the standard library. O:
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
typedef struct PopulationParametersStruct {
int n; ///< Population size, used for determining the number of generations between events.
float f; ///< Scaling factor for the total mutation rate. Smaller = shorter time to coalescence.
float c; ///< Constant bias for the upward mutation rate.
float d; ///< Linear bias for the downward mutation rate.
int kappa; ///< Lower bound of repeat lengths.
int omega; ///< Upper bound of repeat lengths.
} PopulationParameters;
typedef struct CoalescentStruct {
PopulationParameters theta; ///< Mutation model parameters.
int *coalescent_tree; ///< Pointer to our tree, stored as an array.
int offset; ///< We generalize to include 1+ ancestors. Determine the offset for array representation of tree.
gsl_rng *r; ///< Pointer to our RNG. This is preserved across the trace and evolve steps.
} PopulationTree;
int _triangle (int a) { return (int) (a * (a + 1) / 2.0); }
int _round_num (int a) { return (a < 0) ? (int) (a - 0.5) : (int) (a + 0.5); }
typedef int (*_mutate_f) (int, int, float, float, int, int, const gsl_rng *);
int _mutate_generation (int t, int ell, float c, float d, int kappa, int omega, const gsl_rng *r) {
for (int k = 0; k < t; k++) {
// Compute our upward mutation rate. We are bounded by omega.
ell = (gsl_ran_flat(r, 0, 1) < c) ? MIN(omega, ell + 1) : ell;
// Compute our downward mutation rate. We are bounded by kappa.
ell = (gsl_ran_flat(r, 0, 1) < ell * d) ? MAX(kappa, ell - 1) : ell;
}
// Return the result of mutating over several generations.
return ell;
}
int _mutate_draw (int t, int ell, float c, float d, int kappa, int omega, const gsl_rng *r) {
return MIN((unsigned) omega, MAX((unsigned) kappa, ell + gsl_ran_poisson(r, t * c) -
gsl_ran_poisson(r, t * ell * d)));
}
void _trace_tree (int *coalescent_tree, int n, const gsl_rng *r) {
for (int tau = 0; tau < 2 * n - 1; tau++) { // Diploid!
int tau_0 = _triangle(tau + 0), tau_1 = _triangle(tau + 1); // Start at 2nd coalescence.
// We save the indices of our ancestors to our descendants.
for (int k = 0; k < tau_1 - tau_0; k++) {
coalescent_tree[tau_1 + k + 1] = tau_0 + k;
}
// Determine the individual whose frequency increases.
gsl_ran_choose(r, &coalescent_tree[tau_1], 1, &coalescent_tree[tau_1 + 1], tau_1 - tau_0, sizeof(int));
// Finally, shuffle the individuals in this generation.
gsl_ran_shuffle(r, &coalescent_tree[tau_1], tau_1 - tau_0 + 1, sizeof(int));
}
}
void _evolve_individual (int k, int *descendants, int t_coalescence, _mutate_f mutate, PopulationTree *p) {
int *descendant_to_evolve = &(p->coalescent_tree[descendants[k]]);
// Evolve each ancestor according to the average time to coalescence and the scaling factor f.
*descendant_to_evolve = (*mutate)(t_coalescence, *descendant_to_evolve, p->theta.c, p->theta.d,
p->theta.kappa, p->theta.omega, p->r);
// Save our descendant state.
descendants[k] = *descendant_to_evolve;
}
/**
* We assumed our tree has been traced. Given the population tree structure and a pointer to a mutation function,
* determine the repeat length of all individuals in our tree. We do so by iterating through each coalescent event.
*/
void _evolve_event (PopulationTree *p, _mutate_f mutate) {
int descendants_size, expected_time, t_coalescence;
int *descendants = NULL;
for (int tau = p->offset; tau < 2 * p->theta.n - 1; tau++) {
// We define our descendants for the tau'th coalescent.
descendants = &(p->coalescent_tree[_triangle(tau + 1)]);
descendants_size = _triangle(tau + 2) - _triangle(tau + 1);
// Determine time to coalescence. This is exponentially distributed, but the mean stays the same. Scale by f.
expected_time = (int) (p->theta.f * 2 * p->theta.n / (float) _triangle(tau + 1));
t_coalescence = MAX(1, _round_num(gsl_ran_exponential(p->r, expected_time)));
// Iterate through each of the descendants (currently indices) and determine each ancestor.
for (int k = 0; k < descendants_size; k++) {
_evolve_individual(k, descendants, t_coalescence, mutate, p);
}
}
}
void _evolve (int *i_0, int i_0_size, PopulationTree *p) {
// Determine our offset, and seed our ancestors for the tree.
p->offset = i_0_size - 1;
for (int k = 0; k < i_0_size; k++) {
p->coalescent_tree[k + _triangle(p->offset)] = i_0[k];
}
// From our common ancestors, descend forward in time and populate our tree with repeat lengths.
_evolve_event(p, _mutate_draw);
}
void _cleanup (PopulationTree *p) {
free(p->coalescent_tree);
gsl_rng_free(p->r);
}
| {
"alphanum_fraction": 0.6453804348,
"avg_line_length": 43.6610169492,
"ext": "h",
"hexsha": "4b5838255eb2f9bdc9395c2ea982b01e3a97edfb",
"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": "18a6b1b8dbde1c78f5615af6bf391ef52c98cf77",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "glennga/kumulaau",
"max_forks_repo_path": "kumulaau/_single.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "18a6b1b8dbde1c78f5615af6bf391ef52c98cf77",
"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": "glennga/kumulaau",
"max_issues_repo_path": "kumulaau/_single.h",
"max_line_length": 117,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "18a6b1b8dbde1c78f5615af6bf391ef52c98cf77",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "glennga/kumulaau",
"max_stars_repo_path": "kumulaau/_single.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1461,
"size": 5152
} |
#ifndef VECTORS_H
#define VECTORS_H
#include <cmath>
#include <gsl/gsl_blas.h>
#include "types.h"
#include "cuda.h"
__host__ __device__ void angle_ab(const double dir1[3], const double vel[3], double dir2[3]);
__host__ __device__ double doppler(const double dir1[3], const double vel[3]);
__host__ __device__ void scatter_dir(const double dir_in[3], double cos_theta, double dir_out[3]);
__host__ __device__ void get_rand_isotropic_unitvec(double vecout[3]);
__host__ __device__ void move_pkt(PKT *pkt_ptr, double distance, const double time);
__host__ __device__
inline double vec_len(const double x[3])
// return the the magnitude of a vector
{
#ifdef __CUDA_ARCH__
return sqrt((x[0] * x[0]) + (x[1] * x[1]) + (x[2] * x[2]));
#else
return cblas_dnrm2(3, x, 1);
#endif
}
__host__ __device__
inline void vec_norm(const double vec_in[3], double vec_out[3])
// Routine for normalizing a vector.
{
const double magnitude = vec_len(vec_in);
vec_out[0] = vec_in[0] / magnitude;
vec_out[1] = vec_in[1] / magnitude;
vec_out[2] = vec_in[2] / magnitude;
// vec_copy(vec_out, vec_in);
// cblas_dscal(3, 1 / magnitude, vec_out, 1)
}
__host__ __device__
inline double dot(const double x[3], const double y[3])
// Routine for taking dot product.
{
#ifdef __CUDA_ARCH__
return (x[0] * y[0]) + (x[1] * y[1]) + (x[2] * y[2]);
#else
return cblas_ddot(3, x, 1, y, 1);
#endif
}
__host__ __device__
inline void get_velocity(const double x[3], double y[3], const double t)
// Routine for getting velocity vector of the flow at a position with homologous expansion.
{
y[0] = x[0] / t;
y[1] = x[1] / t;
y[2] = x[2] / t;
}
__host__ __device__
inline void cross_prod(const double vec1[3], const double vec2[3], double vecout[3])
{
vecout[0] = (vec1[1] * vec2[2]) - (vec2[1] * vec1[2]);
vecout[1] = (vec1[2] * vec2[0]) - (vec2[2] * vec1[0]);
vecout[2] = (vec1[0] * vec2[1]) - (vec2[0] * vec1[1]);
}
__host__ __device__
inline void vec_scale(double vec[3], const double scalefactor)
{
#ifdef __CUDA_ARCH__
for (int d = 0; d < 3; d++)
{
vec[d] *= scalefactor;
}
#else
cblas_dscal(3, scalefactor, vec, 1);
#endif
}
__host__ __device__
inline void vec_copy(double destination[3], const double source[3])
{
#ifdef __CUDA_ARCH__
for (int d = 0; d < 3; d++)
{
destination[d] = source[d];
}
#else
cblas_dcopy(3, source, 1, destination, 1);
#endif
}
__host__ __device__
inline double doppler_packetpos(const PKT *const pkt_ptr)
{
double vel_vec[3];
get_velocity(pkt_ptr->pos, vel_vec, pkt_ptr->prop_time); // homologous flow velocity
const double dopplerfactor = doppler(pkt_ptr->dir, vel_vec);
return dopplerfactor;
}
#endif //VECTORS_H
| {
"alphanum_fraction": 0.6737226277,
"avg_line_length": 24.4642857143,
"ext": "h",
"hexsha": "77931a367071071204d5f2a55bad88864cb0df4d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "artis-mcrt/artis",
"max_forks_repo_path": "vectors.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_issues_repo_issues_event_max_datetime": "2021-11-17T15:03:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-11-17T09:37:45.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "artis-mcrt/artis",
"max_issues_repo_path": "vectors.h",
"max_line_length": 98,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "eeb4ba06353a34be949d9662ab300a78f852ebdb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "artis-mcrt/artis",
"max_stars_repo_path": "vectors.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-10T21:56:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-12T12:09:31.000Z",
"num_tokens": 921,
"size": 2740
} |
#ifndef UTIL_H
#define UTIL_H
#define PRECISION 2
#define MAX_LINE_LENGTH 9046
#define USE_CBLAS
#define USE_LAPACK
#include <assert.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#ifdef USE_CBLAS
#include <cblas.h>
#endif
#ifdef USE_LAPACK
#include <lapacke.h>
#endif
/******************************************************************************
* LOGGING
******************************************************************************/
/* DEBUG */
#ifdef NDEBUG
#define DEBUG(M, ...)
#else
#define DEBUG(M, ...) \
fprintf(stderr, "[DEBUG] %s:%d: " M "\n", __func__, __LINE__, ##__VA_ARGS__)
#endif
/* LOG */
#define LOG_ERROR(M, ...) \
fprintf(stderr, "[ERROR] [%s] " M "\n", __func__, ##__VA_ARGS__)
#define LOG_WARN(M, ...) fprintf(stderr, "[WARN] " M "\n", ##__VA_ARGS__)
#define LOG_INFO(M, ...) fprintf(stderr, "[INFO] " M "\n", ##__VA_ARGS__)
/* FATAL */
#define FATAL(M, ...) \
fprintf(stderr, "[FATAL] " M "\n", ##__VA_ARGS__); \
exit(-1);
/* CHECK */
#define CHECK(A, M, ...) \
if (!(A)) { \
log_err(M, ##__VA_ARGS__); \
goto error; \
}
/******************************************************************************
* DATA
******************************************************************************/
#if PRECISION == 1
typedef float real_t;
#elif PRECISION == 2
typedef double real_t;
#else
#error "Precision not defined!"
#endif
char *malloc_string(const char *s);
int dsv_rows(const char *fp);
int dsv_cols(const char *fp, const char delim);
char **dsv_fields(const char *fp, const char delim, int *nb_fields);
real_t **dsv_data(const char *fp, const char delim, int *nb_rows, int *nb_cols);
real_t **csv_data(const char *fp, int *nb_rows, int *nb_cols);
int **load_iarrays(const char *csv_path, int *nb_arrays);
real_t **load_darrays(const char *csv_path, int *nb_arrays);
real_t *load_vector(const char *file_path);
/******************************************************************************
* MATHS
******************************************************************************/
#define UNUSED(expr) \
do { \
(void)(expr); \
} while (0)
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
#define MIN(x, y) ((x) < (y) ? (x) : (y))
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#define SIGN(a, b) ((b) >= 0.0 ? fabs(a) : -fabs(a))
float randf(float a, float b);
real_t deg2rad(const real_t d);
real_t rad2deg(const real_t r);
int fltcmp(const real_t x, const real_t y);
real_t pythag(const real_t a, const real_t b);
real_t lerp(const real_t a, const real_t b, const real_t t);
void lerp3(const real_t *a, const real_t *b, const real_t t, real_t *x);
real_t sinc(const real_t x);
/******************************************************************************
* LINEAR ALGEBRA
******************************************************************************/
void print_matrix(const char *prefix, const real_t *data, const size_t m,
const size_t n);
void print_vector(const char *prefix, const real_t *data, const size_t length);
void eye(real_t *A, const size_t m, const size_t n);
void ones(real_t *A, const size_t m, const size_t n);
void zeros(real_t *A, const size_t m, const size_t n);
real_t *mat_new(const size_t m, const size_t n);
int mat_cmp(const real_t *A, const real_t *B, const size_t m, const size_t n);
int mat_equals(const real_t *A, const real_t *B, const size_t m, const size_t n,
const real_t tol);
int mat_save(const char *save_path, const real_t *A, const int m, const int n);
real_t *mat_load(const char *save_path, int *nb_rows, int *nb_cols);
void mat_set(real_t *A, const size_t stride, const size_t i, const size_t j,
const real_t val);
real_t mat_val(const real_t *A, const size_t stride, const size_t i,
const size_t j);
void mat_copy(const real_t *src, const int m, const int n, real_t *dest);
void mat_block_get(const real_t *A, const size_t stride, const size_t rs,
const size_t cs, const size_t re, const size_t ce,
real_t *block);
void mat_block_set(real_t *A, const size_t stride, const size_t rs,
const size_t cs, const size_t re, const size_t ce,
const real_t *block);
void mat_diag_get(const real_t *A, const int m, const int n, real_t *d);
void mat_diag_set(real_t *A, const int m, const int n, const real_t *d);
void mat_triu(const real_t *A, const size_t n, real_t *U);
void mat_tril(const real_t *A, const size_t n, real_t *L);
real_t mat_trace(const real_t *A, const size_t m, const size_t n);
void mat_transpose(const real_t *A, size_t m, size_t n, real_t *A_t);
void mat_add(const real_t *A, const real_t *B, real_t *C, size_t m, size_t n);
void mat_sub(const real_t *A, const real_t *B, real_t *C, size_t m, size_t n);
void mat_scale(real_t *A, const size_t m, const size_t n, const real_t scale);
real_t *vec_new(const size_t length);
void vec_copy(const real_t *src, const size_t length, real_t *dest);
int vec_equals(const real_t *x, const real_t *y, const size_t length);
void vec_add(const real_t *x, const real_t *y, real_t *z, size_t length);
void vec_sub(const real_t *x, const real_t *y, real_t *z, size_t length);
void vec_scale(real_t *x, const size_t length, const real_t scale);
real_t vec_norm(const real_t *x, const size_t length);
void dot(const real_t *A, const size_t A_m, const size_t A_n, const real_t *B,
const size_t B_m, const size_t B_n, real_t *C);
void skew(const real_t x[3], real_t A[3 * 3]);
void fwdsubs(const real_t *L, const real_t *b, real_t *y, const size_t n);
void bwdsubs(const real_t *U, const real_t *y, real_t *x, const size_t n);
int check_jacobian(const char *jac_name, const real_t *fdiff, const real_t *jac,
const size_t m, const size_t n, const real_t tol,
const int print);
#ifdef USE_CBLAS
void cblas_dot(const real_t *A, const size_t A_m, const size_t A_n,
const real_t *B, const size_t B_m, const size_t B_n, real_t *C);
#endif
/******************************************************************************
* SVD
******************************************************************************/
int svd(real_t *A, int m, int n, real_t *U, real_t *s, real_t *V_t);
int svdcomp(real_t *A, int m, int n, real_t *w, real_t *V);
int pinv(real_t *A, const int m, const int n, real_t *A_inv);
#ifdef USE_LAPACK
#endif
/******************************************************************************
* CHOL
******************************************************************************/
void chol(const real_t *A, const size_t n, real_t *L);
void chol_solve(const real_t *A, const real_t *b, real_t *x, const size_t n);
#ifdef USE_LAPACK
void lapack_chol_solve(const real_t *A, const real_t *b, real_t *x,
const size_t n);
#endif
/******************************************************************************
* TIME
******************************************************************************/
typedef uint64_t timestamp_t;
struct timespec tic();
float toc(struct timespec *tic);
float mtoc(struct timespec *tic);
float time_now();
/******************************************************************************
* TRANSFORMS
******************************************************************************/
void tf(const real_t params[7], real_t T[4 * 4]);
void tf_params(const real_t T[4 * 4], real_t params[7]);
void tf_rot_set(real_t T[4 * 4], const real_t C[3 * 3]);
void tf_trans_set(real_t T[4 * 4], const real_t r[3]);
void tf_trans_get(const real_t T[4 * 4], real_t r[3]);
void tf_rot_get(const real_t T[4 * 4], real_t C[3 * 3]);
void tf_quat_get(const real_t T[4 * 4], real_t q[4]);
void tf_inv(const real_t T[4 * 4], real_t T_inv[4 * 4]);
void tf_point(const real_t T[4 * 4], const real_t p[3], real_t retval[3]);
void tf_hpoint(const real_t T[4 * 4], const real_t p[4], real_t retval[4]);
void tf_perturb_rot(real_t T[4 * 4], const real_t step_size, const int i);
void tf_perturb_trans(real_t T[4 * 4], const real_t step_size, const int i);
void rvec2rot(const real_t *rvec, const real_t eps, real_t *R);
void euler321(const real_t euler[3], real_t C[3 * 3]);
void rot2quat(const real_t C[3 * 3], real_t q[4]);
void quat2euler(const real_t q[4], real_t euler[3]);
void quat2rot(const real_t q[4], real_t C[3 * 3]);
void quat_lmul(const real_t p[4], const real_t q[4], real_t r[4]);
void quat_rmul(const real_t p[4], const real_t q[4], real_t r[4]);
void quat_mul(const real_t p[4], const real_t q[4], real_t r[4]);
void quat_delta(const real_t dalpha[3], real_t dq[4]);
/******************************************************************************
* IMAGE
******************************************************************************/
typedef struct image_t {
int width;
int height;
uint8_t *data;
} image_t;
void image_init(image_t *img, uint8_t *data, int width, int height);
/******************************************************************************
* CV
******************************************************************************/
/******************************** RADTAN **************************************/
void radtan4_distort(const real_t params[4], const real_t p[2], real_t p_d[2]);
void radtan4_point_jacobian(const real_t params[4], const real_t p[2],
real_t J_point[2 * 2]);
void radtan4_params_jacobian(const real_t params[4], const real_t p[2],
real_t J_param[2 * 4]);
/********************************* EQUI ***************************************/
void equi4_distort(const real_t params[4], const real_t p[2], real_t p_d[2]);
void equi4_point_jacobian(const real_t params[4], const real_t p[2],
real_t J_point[2 * 2]);
void equi4_params_jacobian(const real_t params[4], const real_t p[2],
real_t J_param[2 * 4]);
/******************************** PINHOLE *************************************/
real_t pinhole_focal(const int image_width, const real_t fov);
int pinhole_project(const real_t params[4], const real_t p_C[3], real_t x[2]);
void pinhole_point_jacobian(const real_t params[4], real_t J_point[2 * 3]);
void pinhole_params_jacobian(const real_t params[4], const real_t x[2],
real_t J[2 * 4]);
/**************************** PINHOLE-RADTAN4 *********************************/
void pinhole_radtan4_project(const real_t params[8], const real_t p_C[3],
real_t x[2]);
void pinhole_radtan4_project_jacobian(const real_t params[8],
const real_t p_C[3], real_t J[2 * 3]);
void pinhole_radtan4_params_jacobian(const real_t params[8],
const real_t p_C[3], real_t J[2 * 8]);
/***************************** PINHOLE-EQUI4 **********************************/
void pinhole_equi4_project(const real_t params[8], const real_t p_C[3],
real_t x[2]);
void pinhole_equi4_project_jacobian(const real_t params[8], const real_t p_C[3],
real_t J[2 * 3]);
void pinhole_equi4_params_jacobian(const real_t params[8], const real_t p_C[3],
real_t J[2 * 8]);
#endif // ZERO_H
| {
"alphanum_fraction": 0.536038713,
"avg_line_length": 41.1853146853,
"ext": "h",
"hexsha": "0b7993c7e2f9a76f8394d22e469bcea7e2f4ce42",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-01-09T04:22:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-11-27T07:12:36.000Z",
"max_forks_repo_head_hexsha": "d38e58a1f9a1130e78626de34bfc3d722a968e5c",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "daoran/ba",
"max_forks_repo_path": "ba/c/util.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d38e58a1f9a1130e78626de34bfc3d722a968e5c",
"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": "daoran/ba",
"max_issues_repo_path": "ba/c/util.h",
"max_line_length": 80,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "d38e58a1f9a1130e78626de34bfc3d722a968e5c",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "daoran/ba",
"max_stars_repo_path": "ba/c/util.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-13T10:22:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-04-26T02:40:48.000Z",
"num_tokens": 2905,
"size": 11779
} |
/* Copyright (C) 2015 Atsushi Togo */
/* All rights reserved. */
/* This file is part of phonopy. */
/* 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 the phonopy project 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. */
#ifndef __frequency_shift4_H__
#define __frequency_shift4_H__
#include <lapacke.h>
#include <phonoc_array.h>
void get_fc4_frequency_shifts(double *frequency_shifts,
const double *fc4_normal_real,
const double *frequencies,
const Iarray *grid_points1,
const Darray *temperatures,
const int *band_indicies,
const int num_band0,
const int num_band,
const double unit_conversion_factor);
void
get_fc4_normal_for_frequency_shift(double *fc4_normal_real,
const double *frequencies,
const lapack_complex_double *eigenvectors,
const int grid_point0,
const Iarray *grid_points1,
const int *grid_address,
const int *mesh,
const double *fc4,
const Darray *shortest_vectors,
const Iarray *multiplicity,
const double *masses,
const int *p2s_map,
const int *s2p_map,
const Iarray *band_indicies,
const double cutoff_frequency);
void reciprocal_to_normal4(lapack_complex_double *fc4_normal,
const lapack_complex_double *fc4_reciprocal,
const double *freqs0,
const double *freqs1,
const lapack_complex_double *eigvecs0,
const lapack_complex_double *eigvecs1,
const double *masses,
const int *band_indices,
const int num_band0,
const int num_band,
const double cutoff_frequency);
void set_phonons_for_frequency_shift(Darray *frequencies,
Carray *eigenvectors,
char *phonon_done,
const Iarray *grid_points,
const int *grid_address,
const int *mesh,
const Darray *fc2,
const Darray *svecs_fc2,
const Iarray *multi_fc2,
const double *masses_fc2,
const int *p2s_fc2,
const int *s2p_fc2,
const double unit_conversion_factor,
const double *born,
const double *dielectric,
const double *reciprocal_lattice,
const double *q_direction,
const double nac_factor,
const char uplo);
#endif
| {
"alphanum_fraction": 0.6969778016,
"avg_line_length": 38.1530612245,
"ext": "h",
"hexsha": "02d54e396607e921f589c0d76577dfd61b6e47ed",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-01-30T08:36:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-08-02T13:53:25.000Z",
"max_forks_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "atztogo/forcefit",
"max_forks_repo_path": "c/anharmonic_h/phonon4_h/frequency_shift.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934",
"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": "atztogo/forcefit",
"max_issues_repo_path": "c/anharmonic_h/phonon4_h/frequency_shift.h",
"max_line_length": 74,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "faa1aea23a31faa3d642b99c51ebb8756e53c934",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "atztogo/forcefit",
"max_stars_repo_path": "c/anharmonic_h/phonon4_h/frequency_shift.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-20T23:19:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-20T23:19:49.000Z",
"num_tokens": 827,
"size": 3739
} |
/*
obtainerr2_par.c
written by Eunseok Lee
function: solve a linear equation system and obtain the squared error
v1: Feb 2, 2018
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//#include <cem.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
double obtainerr2_par(int row_ini, int row_end, double *matA, int n_row, int n_col, int *col_ids, int n_col_ids, double *y) {
int i, j, k, tmp;
double err[n_row];
double sum;
gsl_matrix * A = gsl_matrix_alloc (n_row-1,n_col_ids);
gsl_matrix * V = gsl_matrix_alloc (n_col_ids,n_col_ids);
gsl_vector * S = gsl_vector_alloc (n_col_ids);
gsl_vector * work = gsl_vector_alloc (n_col_ids);
// gsl_matrix * U = gsl_matrix_alloc (n_row-1,n_col_ids);
gsl_vector * b = gsl_vector_alloc (n_row-1);
gsl_vector * x = gsl_vector_alloc (n_col_ids);
for (i=0;i<n_row;i++)
err[i] = 0.0;
// need to copy y to b!
for (i=row_ini;i<row_end;i++) {
for (j=0;j<i;j++) {
for (k=0; k<n_col_ids; k++) {
tmp = *(col_ids+k);
gsl_matrix_set (A, j, k, *(matA+j*n_col+tmp));
}
gsl_vector_set (b, j, y[j]);
}
for (j=i+1;j<n_row;j++) {
for (k=0; k<n_col_ids; k++) {
tmp = *(col_ids+k);
gsl_matrix_set (A, j-1, k, *(matA+j*n_col+tmp));
}
gsl_vector_set (b, j-1, y[j]);
}
gsl_linalg_SV_decomp(A, V, S, work); // on output, A is replaced by U!
gsl_linalg_SV_solve (A, V, S, b, x); // So, A should be used instead of U, here.
sum = 0.0;
for (k=0;k<n_col_ids;k++) {
sum += *(matA+i*n_col+col_ids[k]) * gsl_vector_get(x,k);
}
err[i] = y[i] - sum;
}
sum = 0.0;
for (i=row_ini;i<row_end;i++)
sum += err[i]*err[i];
gsl_matrix_free(A);
gsl_matrix_free(V);
gsl_vector_free(S);
gsl_vector_free(work);
gsl_vector_free(b);
gsl_vector_free(x);
return(sum);
}
| {
"alphanum_fraction": 0.5503579952,
"avg_line_length": 27.9333333333,
"ext": "c",
"hexsha": "a196102587b20a3c1390d43880671910f0768a72",
"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": "17c2ddb309f02e1203411b0bc2ff23bc4d1177ca",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "eunseok-lee/spin_atom_ce",
"max_forks_repo_path": "src_findcluster/obtainerr2_par.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "17c2ddb309f02e1203411b0bc2ff23bc4d1177ca",
"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": "eunseok-lee/spin_atom_ce",
"max_issues_repo_path": "src_findcluster/obtainerr2_par.c",
"max_line_length": 125,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "17c2ddb309f02e1203411b0bc2ff23bc4d1177ca",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "eunseok-lee/spin_atom_ce",
"max_stars_repo_path": "src_findcluster/obtainerr2_par.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 643,
"size": 2095
} |
/* -*- c++ -*- */
/*
* Copyright (C) 2017 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.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <gsl/gsl_integration.h>
#define NSTEPS 10 // how many steps of mu are in the generated table
#define MAX_NSTEPS 256
#define NTAPS 8 // # of taps in the interpolator
#define MAX_NTAPS 128
extern void initpt (double x[], int ntaps);
extern double objective (double x[], int *ntaps);
extern double global_mu;
extern double global_B;
extern gsl_integration_workspace *global_gsl_int_workspace;
// fortran
extern double prax2_ (double (fct)(double x[], int *ntaps),
double initv[], int *ntaps, double result[]);
static void
usage (char *name)
{
fprintf (stderr, "usage: %s [-v] [-n <nsteps>] [-t <ntaps>] [-B <bw>]\n", name);
exit (1);
}
static void
printline (double x[], int ntaps, int imu, int nsteps)
{
int i;
printf (" { ");
for (i = 0; i < ntaps; i++){
printf ("%12.5e", x[i]);
if (i != ntaps - 1)
printf (", ");
else
printf (" }, // %3d/%d\n", imu, nsteps);
}
}
int
main (int argc, char **argv)
{
double xx[MAX_NSTEPS+1][MAX_NTAPS];
int ntaps = NTAPS;
int nsteps = NSTEPS;
int i, j;
double result;
double step_size;
int c;
int verbose = 0;
global_B = 0.25;
while ((c = getopt (argc, argv, "n:t:B:v")) != EOF){
switch (c){
case 'n':
nsteps = strtol (optarg, 0, 0);
break;
case 't':
ntaps = strtol (optarg, 0, 0);
break;
case 'B':
global_B = strtod (optarg, 0);
break;
case 'v':
verbose = 1;
break;
default:
usage (argv[0]);
break;
}
}
if ((nsteps & 1) != 0){
fprintf (stderr, "%s: nsteps must be even\n", argv[0]);
exit (1);
}
if (nsteps > MAX_NSTEPS){
fprintf (stderr, "%s: nsteps must be < %d\n", argv[0], MAX_NSTEPS);
exit (1);
}
if ((ntaps & 1) != 0){
fprintf (stderr, "%s: ntaps must be even\n", argv[0]);
exit (1);
}
if (nsteps > MAX_NTAPS){
fprintf (stderr, "%s: ntaps must be < %d\n", argv[0], MAX_NTAPS);
exit (1);
}
if (global_B < 0 || global_B > 0.5){
fprintf (stderr, "%s: bandwidth must be in the range (0, 0.5)\n", argv[0]);
exit (1);
}
global_gsl_int_workspace = gsl_integration_workspace_alloc(4000);
if (global_gsl_int_workspace == NULL) {
fprintf (stderr, "%s: unable to allocate GSL integration work space\n",
argv[0]);
exit (1);
}
step_size = 1.0/nsteps;
// compute optimal values for mu <= 1.0
for (j = 0; j <= nsteps; j++){
global_mu = j * step_size; // this determines the MU for which we're computing the taps
// initialize X to a reasonable starting value
initpt (&xx[j][0], ntaps);
// find the value of X that minimizes the value of OBJECTIVE
result = prax2_ (objective, &xx[j][0], &ntaps, &xx[j][0]);
if (verbose){
fprintf (stderr, "Mu: %10.8f\t", global_mu);
fprintf (stderr, "Objective: %g\n", result);
}
}
gsl_integration_workspace_free(global_gsl_int_workspace);
// now print out the table
printf ("\
/*\n\
* This file was machine generated by gen_interp_differentiator_taps.\n\
* DO NOT EDIT BY HAND.\n\
*/\n\n");
printf ("static const int DNTAPS = %4d;\n", ntaps);
printf ("static const int DNSTEPS = %4d;\n", nsteps);
printf ("static const double DBANDWIDTH = %g;\n\n", global_B);
printf ("static const float Dtaps[DNSTEPS+1][DNTAPS] = {\n");
printf (" // -4 -3 -2 -1 0 1 2 3 mu\n");
for (i = 0; i <= nsteps; i++)
printline (xx[i], ntaps, i, nsteps);
printf ("};\n\n");
return 0;
}
| {
"alphanum_fraction": 0.5971479501,
"avg_line_length": 24.5245901639,
"ext": "c",
"hexsha": "d34ccea6c6f43e8ea5c2a29a37e51a1cc967d045",
"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-filter/lib/gen_interpolator_taps/gen_interp_differentiator_taps.c",
"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-filter/lib/gen_interpolator_taps/gen_interp_differentiator_taps.c",
"max_line_length": 142,
"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-filter/lib/gen_interpolator_taps/gen_interp_differentiator_taps.c",
"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": 1367,
"size": 4488
} |
/* vector/vector.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 <gsl/gsl_errno.h>
#include <gsl/gsl_vector.h>
/* turn off range checking at runtime if zero */
int gsl_check_range = 1;
#define BASE_GSL_COMPLEX_LONG
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_GSL_COMPLEX_LONG
#define BASE_GSL_COMPLEX
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_GSL_COMPLEX
#define BASE_GSL_COMPLEX_FLOAT
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_GSL_COMPLEX_FLOAT
#define BASE_LONG_DOUBLE
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_LONG_DOUBLE
#define BASE_DOUBLE
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_FLOAT
#define BASE_ULONG
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_ULONG
#define BASE_LONG
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_LONG
#define BASE_UINT
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_UINT
#define BASE_INT
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_INT
#define BASE_USHORT
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_USHORT
#define BASE_SHORT
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_SHORT
#define BASE_UCHAR
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_UCHAR
#define BASE_CHAR
#include "templates_on.h"
#include "vector_source.c"
#include "templates_off.h"
#undef BASE_CHAR
| {
"alphanum_fraction": 0.7698324022,
"avg_line_length": 24.4090909091,
"ext": "c",
"hexsha": "05ffab26b4c4033f3e719165d874f4911503143e",
"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/vector/vector.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/vector/vector.c",
"max_line_length": 73,
"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/vector/vector.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": 643,
"size": 2685
} |
/********************************************************************
* BenchIT - Performance Measurement for Scientific Applications
* Contact: developer@benchit.org
*
* $Id: kernel_main.c 1 2009-09-11 12:26:19Z william $
* $URL: svn+ssh://william@rupert.zih.tu-dresden.de/svn-base/benchit-root/BenchITv6/kernel/numerical/BLAS3/C/0/MKL/sgemm/kernel_main.c $
* For license details see COPYING in the package base directory
*******************************************************************/
/* Kernel: Measurment of sgemm performance
*******************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "interface.h"
#include "aligned_memory.h"
#ifdef USE_MKL
#include <mkl_cblas.h>
#define BLASOP cblas_sgemm /* blas operation */
#endif
#ifdef USE_ACML
#include <acml.h>
#define BLASOP sgemm /* blas operation */
#endif
#ifdef USE_ATLAS
#include <cblas.h>
#define BLASOP cblas_sgemm /* blas operation */
#endif
#define DT float /* datatype */
#define ALIGN 16 /* alignment */
#define EPSILON 1.0e-6 /* epsilon for result validation, 1.0e-6 for single and 1.0e-15 for double */
#define KERNELDES "sgemm"
#define LEGENDY "FLOPS (sgemm)"
#ifndef __work_h
#define __work_h
#if (defined (_CRAYMPP) || \
defined (_USE_SHORT_AS_INT))
typedef short myinttype;
#elif (defined (_USE_LONG_AS_INT))
typedef long myinttype;
#else
typedef int myinttype;
#endif
/** The data structure that holds all the data.
* Please use this construct instead of global variables.
* Global Variables seem to have large access times (?).
*/
typedef struct mydata
{
myinttype maxsize;
DT *A, *B, *C;
} mydata_t;
#endif
/** The implementation of the bi_getinfo from the BenchIT interface.
* Here the infostruct is filled with information about the
* kernel.
* @param infostruct a pointer to a structure filled with zeros
*/
void bi_getinfo(bi_info * infostruct)
{
char * p = 0;
mydata_t * penv;
penv = (mydata_t *) malloc(sizeof(mydata_t));
/* get environment variables for the kernel */
/* parameter list */
p = bi_getenv("BENCHIT_KERNEL_PROBLEMLIST", 0);
bi_parselist(p);
/* get environment variables for the kernel */
infostruct->codesequence = bi_strdup("start kernel; matrix-matrix multiplication; ");
infostruct->kerneldescription = bi_strdup(KERNELDES);
infostruct->xaxistext = bi_strdup("Problem Size");
infostruct->num_measurements = infostruct->listsize;
infostruct->num_processes = 1;
infostruct->num_threads_per_process = 0;
infostruct->kernel_execs_mpi1 = 0;
infostruct->kernel_execs_mpi2 = 0;
infostruct->kernel_execs_pvm = 0;
infostruct->kernel_execs_omp = 0;
infostruct->kernel_execs_pthreads = 0;
infostruct->numfunctions = 1;
/* allocating memory for y axis texts and properties */
allocYAxis(infostruct);
/* setting up y axis texts and properties */
infostruct->yaxistexts[0] = bi_strdup("flop/s");
infostruct->selected_result[0] = SELECT_RESULT_HIGHEST;
infostruct->base_yaxis[0] = 0; //logarythmic axis 10^x
infostruct->legendtexts[0] = bi_strdup(LEGENDY);
/* free all used space */
if (penv) free(penv);
}
/** Implementation of the bi_init of the BenchIT interface.
* Here you have the chance to allocate the memory you need.
* It is also possible to allocate the memory at the beginning
* of every single measurement and to free the memory thereafter.
* But always making use of the same memory is faster.
* HAVE A LOOK INTO THE HOWTO !
*/
void* bi_init(int problemSizemax)
{
mydata_t * pmydata;
myinttype i, m, tmp;
pmydata = (mydata_t*)malloc(sizeof(mydata_t));
if (pmydata == 0)
{
fprintf(stderr, "Allocation of structure mydata_t failed\n"); fflush(stderr);
exit(127);
}
m = (myinttype)bi_get_list_element(1);
for(i=2; i<=problemSizemax; i++){
tmp = (myinttype)bi_get_list_element(i);
if(tmp>m) m = tmp;
}
pmydata->maxsize = m;
IDL(3, printf("\nAllocate (%d,%d)-Matrix\n",m,m));
pmydata->A = (DT*)_aligned_malloc(m*m * sizeof(DT), ALIGN);
pmydata->B = (DT*)_aligned_malloc(m*m * sizeof(DT), ALIGN);
pmydata->C = (DT*)_aligned_malloc(m*m * sizeof(DT), ALIGN);
/* matrix A is stored column by column like in fortran
* elseif you must call cblas_sgemm with "CblasRowMajor" and thru that the algo
* first transpose the matrix -> less performance
*/
for(i=0; i<m*m; i++){
pmydata->A[i] = 0.5;
pmydata->B[i] = 2.0;
}
return (void *)pmydata;
}
/** initialize array with 0
*/
void initzero(DT *array, int size)
{
myinttype i;
for(i=0; i<size; i++){
array[i] = 0.0;
}
}
/** The central function within each kernel. This function
* is called for each measurement step seperately.
* @param mdpv a pointer to the structure created in bi_init,
* it is the pointer the bi_init returns
* @param problemSize the actual problemSize
* @param results a pointer to a field of doubles, the
* size of the field depends on the number
* of functions, there are #functions+1
* doubles
* @return 0 if the measurement was sucessfull, something
* else in the case of an error
*/
int bi_entry(void * mdpv, int iproblemSize, double * dresults)
{
/* dstart, dend: the start and end time of the measurement */
/* dtime: the time for a single measurement in seconds */
double dstart = 0.0, dend = 0.0, dtime = 0.0;
/* flops stores the calculated FLOPS */
double dres = 0.0, dm = 0.0;
/* ii is used for loop iterations */
myinttype imyproblemSize;
/* cast void* pointer */
mydata_t * pmydata = (mydata_t *) mdpv;
#ifdef USE_ACML
char trans = 'N';
#endif
DT alpha=1.0;
myinttype m, incxy=1;
/* get current problem size from problemlist */
imyproblemSize = (myinttype)bi_get_list_element(iproblemSize);
m = imyproblemSize;
/* check wether the pointer to store the results in is valid or not */
if (dresults == NULL) return 1;
initzero(pmydata->C, pmydata->maxsize*pmydata->maxsize);
/* get the actual time
* do the measurement / your algorythm
* get the actual time
*/
dstart = bi_gettime();
#ifdef USE_ACML
BLASOP(trans, trans, m, m, m, alpha, pmydata->A, m, pmydata->B, m, alpha, pmydata->C, m);
#else
BLASOP(CblasColMajor, CblasNoTrans, CblasNoTrans, m, m, m, alpha, pmydata->A, m, pmydata->B, m, alpha, pmydata->C, m);
#endif
dend = bi_gettime();
if(abs((pmydata->C)[0]-(DT)m) > abs((DT)m)*EPSILON || abs((pmydata->C)[m*m-1]-(DT)m) > abs((DT)m)*EPSILON) {
IDL(0, printf("ERROR: the result is not valid!\n"));
IDL(0, printf("expected: C(1,1)=%e, C(m,m)=%e, got: C(1,1)=%e, C(m,m)=%e\n",(DT)m,(DT)m,(pmydata->C)[0],(pmydata->C)[m*m-1]));
}
/* calculate the used time and FLOPS */
dtime = dend - dstart;
dtime -= dTimerOverhead;
dm = (double)m;
dres = dm * dm * dm + (dm-1) * dm * dm; /* m*m*m mult and m-1*m*m add for A*B */
dres += dm * dm; /* m*m mult for alpha */
dres += 2.0 * dm * dm; /* m*m mult for C and m*m add for final result */
/* If the operation was too fast to be measured by the timer function,
* mark the result as invalid
*/
if(dtime < dTimerGranularity) dtime = INVALID_MEASUREMENT;
/* store the results in results[1], results[2], ...
* [1] for the first function, [2] for the second function
* and so on ...
* the index 0 always keeps the value for the x axis
*/
dresults[0] = (double)imyproblemSize;
dresults[1] = (dtime!=INVALID_MEASUREMENT) ? dres / dtime : INVALID_MEASUREMENT;
return 0;
}
/** Clean up the memory
*/
void bi_cleanup(void* mdpv)
{
mydata_t * pmydata = (mydata_t*)mdpv;
_aligned_free(pmydata->A);
_aligned_free(pmydata->B);
_aligned_free(pmydata->C);
if (pmydata) free(pmydata);
return;
}
| {
"alphanum_fraction": 0.6488155242,
"avg_line_length": 30.5230769231,
"ext": "c",
"hexsha": "aac2fee6d3593d18c7c210ad689c9fcd4cf03944",
"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": "38461e73617c92449f85a84176cd108fb82434b2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Arka2009/x86_64-ubench-ecolab",
"max_forks_repo_path": "kernel/numerical/BLAS3/C/0/MKL/sgemm/kernel_main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "38461e73617c92449f85a84176cd108fb82434b2",
"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": "Arka2009/x86_64-ubench-ecolab",
"max_issues_repo_path": "kernel/numerical/BLAS3/C/0/MKL/sgemm/kernel_main.c",
"max_line_length": 136,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "38461e73617c92449f85a84176cd108fb82434b2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Arka2009/x86_64-ubench-ecolab",
"max_stars_repo_path": "kernel/numerical/BLAS3/C/0/MKL/sgemm/kernel_main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2386,
"size": 7936
} |
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include "allvars.h"
#include "proto.h"
#ifdef CR_DIFFUSION_GREEN
#include "cosmic_rays.h"
void compute_diff_weights(int target, int mode);
void scatter_diffusion(int target, int mode);
#define m_p (PROTONMASS * All.HubbleParam / All.UnitMass_in_g)
void greenf_diffusion(void)
{
int *noffset, *nbuffer, *nsend, *nsend_local, *numlist, *ndonelist;
int i, j, n;
int ndone;
long long ntot, ntotleft;
int maxfill, source;
int level, ngrp, sendTask, recvTask;
int place, nexport;
double cr_efac_i, kappa_egy;
double kappa, a3inv, egysum, egytot, egytot_before;
double meanKineticEnergy, qmeanKin;
double CR_q_i;
MPI_Status status;
if(ThisTask == 0)
{
printf("Doing diffusion step with Green function method\n");
fflush(stdout);
}
for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)
{
noffset = mymalloc(sizeof(int) * NTask); /* offsets of bunches in common list */
nbuffer = mymalloc(sizeof(int) * NTask);
nsend_local = mymalloc(sizeof(int) * NTask);
nsend = mymalloc(sizeof(int) * NTask * NTask);
ndonelist = mymalloc(sizeof(int) * NTask);
if(All.ComovingIntegrationOn)
a3inv = 1 / (All.Time * All.Time * All.Time);
else
a3inv = 1;
egysum = 0;
for(n = 0, NumSphUpdate = 0; n < N_gas; n++)
{
if(P[n].Type == 0)
{
NumSphUpdate++;
egysum += SphP[n].CR_E0[CRpop];
SphP[n].CR_DeltaE[CRpop] = 0;
SphP[n].CR_DeltaN[CRpop] = 0;
kappa = All.CR_DiffusionCoeff;
if(All.CR_DiffusionDensScaling != 0.0)
kappa *= pow(SphP[n].d.Density * a3inv / All.CR_DiffusionDensZero, All.CR_DiffusionDensScaling);
if(All.CR_DiffusionEntropyScaling != 0.0)
kappa *= pow(SphP[n].Entropy / All.CR_DiffusionEntropyZero, All.CR_DiffusionEntropyScaling);
if(SphP[n].CR_E0[CRpop] > 0)
{
CR_q_i = SphP[n].CR_q0[CRpop] * pow(SphP[n].d.Density * a3inv, 0.33333);
cr_efac_i =
CR_Tab_MeanEnergy(CR_q_i, All.CR_Alpha[CRpop] - 0.3333, CRpop)
/ CR_Tab_MeanEnergy(CR_q_i, All.CR_Alpha[CRpop], CRpop);
kappa *= (All.CR_Alpha[CRpop] - 1) / (All.CR_Alpha[CRpop] - 1.33333) * pow(CR_q_i, 0.3333);
kappa_egy = kappa * cr_efac_i;
}
else
kappa_egy = kappa;
SphP[n].CR_Kappa[CRpop] = kappa;
SphP[n].CR_Kappa_egy[CRpop] = kappa_egy;
}
}
MPI_Allreduce(&egysum, &egytot_before, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
numlist = mymalloc(NTask * sizeof(int) * NTask);
MPI_Allgather(&NumSphUpdate, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);
for(i = 0, ntot = 0; i < NTask; i++)
ntot += numlist[i];
myfree(numlist);
/* first, sum the weights */
i = 0; /* beginn with this index */
ntotleft = ntot; /* particles left for all tasks together */
while(ntotleft > 0)
{
for(j = 0; j < NTask; j++)
nsend_local[j] = 0;
/* do local particles and prepare export list */
for(nexport = 0, ndone = 0; i < NumPart && nexport < All.BunchSizeDensity - NTask; i++)
if(P[i].Type == 0)
{
ndone++;
for(j = 0; j < NTask; j++)
Exportflag[j] = 0;
compute_diff_weights(i, 0);
for(j = 0; j < NTask; j++)
{
if(Exportflag[j])
{
DensDataIn[nexport].Pos[0] = P[i].Pos[0];
DensDataIn[nexport].Pos[1] = P[i].Pos[1];
DensDataIn[nexport].Pos[2] = P[i].Pos[2];
DensDataIn[nexport].Hsml = PPP[i].Hsml;
DensDataIn[nexport].CR_Kappa[CRpop] = SphP[i].CR_Kappa[CRpop];
DensDataIn[nexport].CR_Kappa_egy[CRpop] = SphP[i].CR_Kappa_egy[CRpop];
DensDataIn[nexport].Index = i;
DensDataIn[nexport].Task = j;
nexport++;
nsend_local[j]++;
}
}
}
qsort(DensDataIn, nexport, sizeof(struct densdata_in), dens_compare_key);
for(j = 1, noffset[0] = 0; j < NTask; j++)
noffset[j] = noffset[j - 1] + nsend_local[j - 1];
MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, MPI_COMM_WORLD);
/* now do the particles that need to be exported */
for(level = 1; level < (1 << PTask); level++)
{
for(j = 0; j < NTask; j++)
nbuffer[j] = 0;
for(ngrp = level; ngrp < (1 << PTask); ngrp++)
{
maxfill = 0;
for(j = 0; j < NTask; j++)
{
if((j ^ ngrp) < NTask)
if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])
maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];
}
if(maxfill >= All.BunchSizeDensity)
break;
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)
{
/* get the particles */
MPI_Sendrecv(&DensDataIn[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct densdata_in), MPI_BYTE,
recvTask, TAG_CONDUCT_A,
&DensDataGet[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct densdata_in),
MPI_BYTE, recvTask, TAG_CONDUCT_A, MPI_COMM_WORLD, &status);
}
}
for(j = 0; j < NTask; j++)
if((j ^ ngrp) < NTask)
nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
}
for(j = 0; j < nbuffer[ThisTask]; j++)
compute_diff_weights(j, 1);
for(j = 0; j < NTask; j++)
nbuffer[j] = 0;
for(ngrp = level; ngrp < (1 << PTask); ngrp++)
{
maxfill = 0;
for(j = 0; j < NTask; j++)
{
if((j ^ ngrp) < NTask)
if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])
maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];
}
if(maxfill >= All.BunchSizeDensity)
break;
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)
{
/* send the results */
MPI_Sendrecv(&DensDataResult[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct densdata_out),
MPI_BYTE, recvTask, TAG_CONDUCT_B,
&DensDataPartialResult[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct densdata_out),
MPI_BYTE, recvTask, TAG_CONDUCT_B, MPI_COMM_WORLD, &status);
/* add the result to the particles */
for(j = 0; j < nsend_local[recvTask]; j++)
{
source = j + noffset[recvTask];
place = DensDataIn[source].Index;
SphP[place].CR_WeightSum += DensDataPartialResult[source].CR_WeightSum;
SphP[place].CR_WeightSum_egy += DensDataPartialResult[source].CR_WeightSum_egy;
}
}
}
for(j = 0; j < NTask; j++)
if((j ^ ngrp) < NTask)
nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
}
level = ngrp - 1;
}
MPI_Allgather(&ndone, 1, MPI_INT, ndonelist, 1, MPI_INT, MPI_COMM_WORLD);
for(j = 0; j < NTask; j++)
ntotleft -= ndonelist[j];
}
/*************** now do the diffusion step itself */
numlist = mymalloc(NTask * sizeof(int) * NTask);
MPI_Allgather(&NumSphUpdate, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);
for(i = 0, ntot = 0; i < NTask; i++)
ntot += numlist[i];
myfree(numlist);
/* first, sum the weights */
i = 0; /* beginn with this index */
ntotleft = ntot; /* particles left for all tasks together */
while(ntotleft > 0)
{
for(j = 0; j < NTask; j++)
nsend_local[j] = 0;
/* do local particles and prepare export list */
for(nexport = 0, ndone = 0; i < NumPart && nexport < All.BunchSizeDensity - NTask; i++)
if(P[i].Type == 0)
{
ndone++;
for(j = 0; j < NTask; j++)
Exportflag[j] = 0;
scatter_diffusion(i, 0);
for(j = 0; j < NTask; j++)
{
if(Exportflag[j])
{
DensDataIn[nexport].Pos[0] = P[i].Pos[0];
DensDataIn[nexport].Pos[1] = P[i].Pos[1];
DensDataIn[nexport].Pos[2] = P[i].Pos[2];
DensDataIn[nexport].CR_Kappa[CRpop] = SphP[i].CR_Kappa[CRpop];
DensDataIn[nexport].CR_Kappa_egy[CRpop] = SphP[i].CR_Kappa_egy[CRpop];
DensDataIn[nexport].CR_WeightSum = SphP[i].CR_WeightSum;
DensDataIn[nexport].CR_WeightSum_egy = SphP[i].CR_WeightSum_egy;
DensDataIn[nexport].Hsml = PPP[i].Hsml;
DensDataIn[nexport].CR_E0[CRpop] = SphP[i].CR_E0[CRpop];
DensDataIn[nexport].CR_n0[CRpop] = SphP[i].CR_n0[CRpop];
DensDataIn[nexport].Index = i;
DensDataIn[nexport].Task = j;
nexport++;
nsend_local[j]++;
}
}
}
qsort(DensDataIn, nexport, sizeof(struct densdata_in), dens_compare_key);
for(j = 1, noffset[0] = 0; j < NTask; j++)
noffset[j] = noffset[j - 1] + nsend_local[j - 1];
MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, MPI_COMM_WORLD);
/* now do the particles that need to be exported */
for(level = 1; level < (1 << PTask); level++)
{
for(j = 0; j < NTask; j++)
nbuffer[j] = 0;
for(ngrp = level; ngrp < (1 << PTask); ngrp++)
{
maxfill = 0;
for(j = 0; j < NTask; j++)
{
if((j ^ ngrp) < NTask)
if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])
maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];
}
if(maxfill >= All.BunchSizeDensity)
break;
sendTask = ThisTask;
recvTask = ThisTask ^ ngrp;
if(recvTask < NTask)
{
if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)
{
/* get the particles */
MPI_Sendrecv(&DensDataIn[noffset[recvTask]],
nsend_local[recvTask] * sizeof(struct densdata_in), MPI_BYTE,
recvTask, TAG_CONDUCT_A,
&DensDataGet[nbuffer[ThisTask]],
nsend[recvTask * NTask + ThisTask] * sizeof(struct densdata_in),
MPI_BYTE, recvTask, TAG_CONDUCT_A, MPI_COMM_WORLD, &status);
}
}
for(j = 0; j < NTask; j++)
if((j ^ ngrp) < NTask)
nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];
}
for(j = 0; j < nbuffer[ThisTask]; j++)
scatter_diffusion(j, 1);
level = ngrp - 1;
}
MPI_Allgather(&ndone, 1, MPI_INT, ndonelist, 1, MPI_INT, MPI_COMM_WORLD);
for(j = 0; j < NTask; j++)
ntotleft -= ndonelist[j];
}
/* now set the new cosmic ray prorperties */
egysum = 0;
for(n = 0; n < N_gas; n++)
{
if(P[n].Type == 0)
{
SphP[n].CR_E0[CRpop] = SphP[n].CR_DeltaE[CRpop];
SphP[n].CR_n0[CRpop] = SphP[n].CR_DeltaN[CRpop];
egysum += SphP[n].CR_E0[CRpop];
SphP[n].CR_DeltaE[CRpop] = 0;
SphP[n].CR_DeltaN[CRpop] = 0;
if(SphP[n].CR_n0[CRpop] > 1.0e-12 && SphP[n].CR_E0[CRpop] > 0)
{
meanKineticEnergy = SphP[n].CR_E0[CRpop] * m_p / SphP[n].CR_n0[CRpop];
qmeanKin = CR_q_from_mean_kinetic_energy(meanKineticEnergy[CRpop], CRpop);
SphP[n].CR_q0[CRpop] = qmeanKin * pow(SphP[n].d.Density * a3inv, -(1.0 / 3.0));
SphP[n].CR_C0[CRpop] = SphP[n].CR_n0[CRpop] * (All.CR_Alpha[CRpop] - 1.0) *
pow(SphP[n].CR_q0[CRpop], All.CR_Alpha[CRpop] - 1.0);
}
else
{
SphP[n].CR_E0[CRpop] = 0.0;
SphP[n].CR_n0[CRpop] = 0.0;
SphP[n].CR_q0[CRpop] = 1.0e10;
SphP[n].CR_C0[CRpop] = 0.0;
}
}
}
MPI_Allreduce(&egysum, &egytot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
if(ThisTask == 0)
{
printf("Energy before/after= %g | %g\n", egytot_before, egytot);
fflush(stdout);
}
myfree(ndonelist);
myfree(nsend);
myfree(nsend_local);
myfree(nbuffer);
myfree(noffset);
All.TimeOfLastDiffusion = All.Time;
}
}
void compute_diff_weights(int target, int mode)
{
int j, n;
int startnode, numngb_inbox;
double h;
double weightsum, weightsum_egy, kappa, kappa_egy, kappaeff, kappaeff_egy;;
double dx, dy, dz, r, r2;
MyFloat *pos;
if(mode == 0)
{
pos = P[target].Pos;
h = PPP[target].Hsml;
kappa = SphP[target].CR_Kappa;
kappa_egy = SphP[target].CR_Kappa_egy;
}
else
{
pos = DensDataGet[target].Pos;
h = DensDataGet[target].Hsml;
kappa = DensDataGet[target].CR_Kappa;
kappa_egy = DensDataGet[target].CR_Kappa_egy;
}
weightsum = weightsum_egy = 0;
startnode = All.MaxPart;
kappaeff = 4 * kappa * (All.Time - All.TimeOfLastDiffusion);
kappaeff_egy = 4 * kappa_egy * (All.Time - All.TimeOfLastDiffusion);
if(kappaeff > 0)
{
do
{
numngb_inbox = ngb_treefind_variable(&pos[0], h, &startnode);
for(n = 0; n < numngb_inbox; n++)
{
j = Ngblist[n];
dx = pos[0] - P[j].Pos[0];
dy = pos[1] - P[j].Pos[1];
dz = pos[2] - P[j].Pos[2];
#ifdef PERIODIC /* now find the closest image in the given box size */
if(dx > boxHalf_X)
dx -= boxSize_X;
if(dx < -boxHalf_X)
dx += boxSize_X;
if(dy > boxHalf_Y)
dy -= boxSize_Y;
if(dy < -boxHalf_Y)
dy += boxSize_Y;
if(dz > boxHalf_Z)
dz -= boxSize_Z;
if(dz < -boxHalf_Z)
dz += boxSize_Z;
#endif
r2 = dx * dx + dy * dy + dz * dz;
if(r2 < h * h)
{
r = sqrt(r2);
weightsum += P[j].Mass * exp(-r2 / kappaeff);
weightsum_egy += P[j].Mass * exp(-r2 / kappaeff_egy);
}
}
}
while(startnode >= 0);
}
if(mode == 0)
{
SphP[target].CR_WeightSum = weightsum;
SphP[target].CR_WeightSum_egy = weightsum_egy;
}
else
{
DensDataResult[target].CR_WeightSum = weightsum;
DensDataResult[target].CR_WeightSum_egy = weightsum_egy;
}
}
void scatter_diffusion(int target, int mode)
{
int j, n;
int startnode, numngb_inbox;
double h, weight;
double weightsum, kappa, kappaeff, CR_E0, CR_n0;
double weightsum_egy, kappa_egy, kappaeff_egy;
double dx, dy, dz, r, r2;
MyFloat *pos;
if(mode == 0)
{
pos = P[target].Pos;
h = PPP[target].Hsml;
kappa = SphP[target].CR_Kappa;
kappa_egy = SphP[target].CR_Kappa_egy;
weightsum = SphP[target].CR_WeightSum;
weightsum_egy = SphP[target].CR_WeightSum_egy;
CR_E0 = SphP[target].CR_E0;
CR_n0 = SphP[target].CR_n0;
}
else
{
pos = DensDataGet[target].Pos;
h = DensDataGet[target].Hsml;
kappa = DensDataGet[target].CR_Kappa;
kappa_egy = DensDataGet[target].CR_Kappa_egy;
weightsum = DensDataGet[target].CR_WeightSum;
weightsum_egy = DensDataGet[target].CR_WeightSum_egy;
CR_E0 = DensDataGet[target].CR_E0;
CR_n0 = DensDataGet[target].CR_n0;
}
startnode = All.MaxPart;
kappaeff = 4 * kappa * (All.Time - All.TimeOfLastDiffusion);
kappaeff_egy = 4 * kappa_egy * (All.Time - All.TimeOfLastDiffusion);
if(kappaeff > 0)
{
do
{
numngb_inbox = ngb_treefind_variable(&pos[0], h, &startnode);
for(n = 0; n < numngb_inbox; n++)
{
j = Ngblist[n];
dx = pos[0] - P[j].Pos[0];
dy = pos[1] - P[j].Pos[1];
dz = pos[2] - P[j].Pos[2];
#ifdef PERIODIC /* now find the closest image in the given box size */
if(dx > boxHalf_X)
dx -= boxSize_X;
if(dx < -boxHalf_X)
dx += boxSize_X;
if(dy > boxHalf_Y)
dy -= boxSize_Y;
if(dy < -boxHalf_Y)
dy += boxSize_Y;
if(dz > boxHalf_Z)
dz -= boxSize_Z;
if(dz < -boxHalf_Z)
dz += boxSize_Z;
#endif
r2 = dx * dx + dy * dy + dz * dz;
if(r2 < h * h)
{
r = sqrt(r2);
weight = P[j].Mass * exp(-r2 / kappaeff) / weightsum;
SphP[j].CR_DeltaN += CR_n0 * weight;
weight = P[j].Mass * exp(-r2 / kappaeff_egy) / weightsum_egy;
SphP[j].CR_DeltaE += CR_E0 * weight;
}
}
}
while(startnode >= 0);
}
}
#endif
| {
"alphanum_fraction": 0.5685348577,
"avg_line_length": 25.8330658106,
"ext": "c",
"hexsha": "2d51081502288f4c4b2ad4bf99a5f20b5acf95b9",
"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/greenf_diffusion.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/greenf_diffusion.c",
"max_line_length": 98,
"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/greenf_diffusion.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5622,
"size": 16094
} |
/**
*
* @file pzgbrdb.c
*
* PLASMA auxiliary routines
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Azzam Haidar
* @date 2011-05-15
* @precisions normal z -> c d s
*
**/
#include "common.h"
#include <lapacke.h>
#undef REAL
#define COMPLEX
#define DEP(m) &(DEP[m])
#define A(_m, _n) (PLASMA_Complex64_t *)plasma_geteltaddr(&A, (_m), (_n), eltsize)
/***************************************************************************//**
* Parallel Reduction from BAND Bidiagonal to the final condensed form - dynamic scheduler
**/
void plasma_pzgbrdb_quark(PLASMA_enum uplo,
PLASMA_desc A, double *D, double *E, PLASMA_desc T,
PLASMA_sequence *sequence, PLASMA_request *request)
{
plasma_context_t *plasma;
Quark_Task_Flags task_flags = Quark_Task_Flags_Initializer;
#ifdef COMPLEX
static double dzero = (double) 0.0;
double absztmp;
#endif
static PLASMA_Complex64_t zone = (PLASMA_Complex64_t) 1.0;
static PLASMA_Complex64_t zzero = (PLASMA_Complex64_t) 0.0;
PLASMA_Complex64_t *VQ, *TAUQ,*VP, *TAUP;
PLASMA_Complex64_t ztmp, V, TAU;
int M, N, NB, MINMN, INgrsiz, INthgrsiz, BAND;
int myid, grsiz, shift=3, stt, st, ed, stind, edind;
int blklastind, colpt, PCOL, ACOL, MCOL;
int stepercol, mylastid, grnb, grid;
int *DEP,*MAXID;
int i, sweepid, m;
int thgrsiz, thgrnb, thgrid, thed;
size_t eltsize = plasma_element_size(A.dtyp);
plasma = plasma_context_self();
if (sequence->status != PLASMA_SUCCESS)
return;
QUARK_Task_Flag_Set(&task_flags, TASK_SEQUENCE, (intptr_t)sequence->quark_sequence);
M = A.m;
N = A.n;
NB = A.mb;
MINMN = min(M,N);
/* Quick return */
if ( MINMN == 0 ){
return;
}
if ( NB == 0 ) {
memset(D, 0, MINMN *sizeof(double));
memset(E, 0, (MINMN-1)*sizeof(double));
#ifdef COMPLEX
for (i=0; i<MINMN; i++)
D[i] = cabs(*A(i,i));
#else
for (i=0; i<MINMN; i++)
D[i] = *A(i,i);
#endif
return;
}
/*
* Barrier is used because the bulge have to wait until
* the reduction to band has been finish.
* otherwise, I can remove this BARRIER when I integrate
* the function dependencies link inside the reduction to
* band. Keep in mind the case when NB=1, where no bulge-chasing.
*/
/***************************************************************/
QUARK_Barrier(plasma->quark);
/***************************************************************/
/*
* Case NB=1 ==> matrix is already Bidiagonal. no need to bulge.
* Make diagonal and superdiagonal elements real, storing them in
* D and E. if PlasmaLower, first transform lower bidiagonal form
* to upper bidiagonal by applying plane rotations/ Householder
* from the left, overwriting superdiagonal elements then make
* elements real of the resulting upper Bidiagonal. if PlasmaUpper
* then make its elements real. For Q, PT: ZSCAL should be done
* in case of WANTQ.
*/
if ( NB == 1 ) {
memset(D, 0, MINMN*sizeof(double));
memset(E, 0, (MINMN-1)*sizeof(double));
if(uplo==PlasmaLower){
for (i=0; i<(MINMN-1); i++)
{
/* generate Householder to annihilate a(i+1,i) and create a(i,i+1) */
V = *A((i+1), i);
*A((i+1), i) = zzero;
LAPACKE_zlarfg_work( 2, A(i, i), &V, 1, &TAU);
/* apply Left*/
TAU = conj(TAU);
ztmp = TAU*V;
V = conj(V);
*A(i, i+1) = - V * TAU * (*A(i+1, i+1));
*A(i+1, i+1) = *(A(i+1, i+1)) * (zone - V * ztmp);
}
}
/* PlasmaLower or PlasmaUpper, both are now upper */
/* Make diagonal and superdiagonal elements real,
* storing them in D and E
*/
#ifdef COMPLEX
ztmp = zone;
for (i=0; i<MINMN; i++)
{
ztmp = *A(i, i) * conj(ztmp);
absztmp = cabs(ztmp);
D[i] = absztmp; /* diag value */
if(absztmp != dzero)
ztmp = (PLASMA_Complex64_t) (ztmp / absztmp);
else
ztmp = zone;
if(i<(MINMN-1)) {
ztmp = *A(i, (i+1)) * conj(ztmp);
absztmp = cabs(ztmp);
E[i] = absztmp; /* upper off-diag value */
if(absztmp != dzero)
ztmp = (PLASMA_Complex64_t) (ztmp / absztmp);
else
ztmp = zone;
}
}
#else
for (i=0; i < MINMN-1; i++) {
D[i] = *A(i, i );
E[i] = *A(i, i+1);
}
D[i] = *A(i, i);
#endif
return;
}
/*
* Case MINMN<NB ==> matrix is very small and better to call lapack ZGETRD.
*
* Use fact that one row of block is stored the same way than in LAPACK
* Doesn't work if M > NB because of tile storage
*/
if ( MINMN <= 0 )
{
PLASMA_Complex64_t *work, *taup, *tauq;
int info, ldwork = N*N;
work = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, ldwork, PlasmaComplexDouble);
taup = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, MINMN, PlasmaComplexDouble);
tauq = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, MINMN, PlasmaComplexDouble);
info = LAPACKE_zgebrd_work(LAPACK_COL_MAJOR, M, N,
A(0,0), A.lm, D, E, taup, tauq, work, ldwork);
plasma_shared_free(plasma, (void*) work);
plasma_shared_free(plasma, (void*) taup);
plasma_shared_free(plasma, (void*) tauq);
if( info == 0 )
sequence->status = PLASMA_SUCCESS;
else
plasma_sequence_flush(plasma->quark, sequence, request, info);
return;
}
/* General case NB > 1 && N > NB */
DEP = (int *) plasma_shared_alloc(plasma, MINMN+1, PlasmaInteger );
MAXID = (int *) plasma_shared_alloc(plasma, MINMN+1, PlasmaInteger );
memset(MAXID,0,(MINMN+1)*sizeof(int));
VQ = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaComplexDouble);
TAUQ = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaComplexDouble);
VP = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaComplexDouble);
TAUP = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*MINMN, PlasmaComplexDouble);
memset(VQ,0,2*MINMN*sizeof(PLASMA_Complex64_t));
memset(TAUQ,0,2*MINMN*sizeof(PLASMA_Complex64_t));
memset(VP,0,2*MINMN*sizeof(PLASMA_Complex64_t));
memset(TAUP,0,2*MINMN*sizeof(PLASMA_Complex64_t));
/***************************************************************************
* START BULGE CHASING CODE
**************************************************************************/
printf("converting tile to lap A.lm %d ln %d \n",A.lm,A.ln);
PLASMA_Complex64_t *AB = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, A.lm*A.ln, PlasmaComplexDouble);
memset(AB,0,A.lm*A.ln*sizeof(PLASMA_Complex64_t));
plasma_zooptile2lap( A, AB, NB, NB, A.lm, A.ln, sequence, request);
int LDAB = A.lm;
/*
plasma_dynamic_call_6( plasma_pzhbcpy_t2bl,
PLASMA_enum, uplo,
PLASMA_desc, A,
PLASMA_Complex64_t*, &(AB[NB]),
int, M,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
*/
QUARK_Barrier(plasma->quark);
/*
* Initialisation of local parameter. those parameter should be
* input or tuned parameter.
*/
INgrsiz = 1;
if( NB > 160 ) {
INgrsiz = 2;
}
else if( NB > 100 ) {
if( MINMN < 5000 )
INgrsiz = 2;
else
INgrsiz = 4;
} else {
INgrsiz = 6;
}
INthgrsiz = MINMN;
BAND = 0;
grsiz = INgrsiz;
thgrsiz = INthgrsiz;
if( grsiz == 0 ) grsiz = 6;
if( thgrsiz == 0 ) thgrsiz = MINMN;
i = shift/grsiz;
stepercol = i*grsiz == shift ? i:i+1;
i = (MINMN-1)/thgrsiz;
thgrnb = i*thgrsiz == (MINMN-1) ? i:i+1;
printf("starting code grsiz %d thgr %d\n", grsiz, thgrsiz);
for (thgrid = 1; thgrid<=thgrnb; thgrid++){
stt = (thgrid-1)*thgrsiz+1;
thed = min( (stt + thgrsiz -1), (MINMN-1));
for (i = stt; i <= MINMN-1; i++){
ed=min(i,thed);
if(stt>ed)break;
for (m = 1; m <=stepercol; m++){
st=stt;
for (sweepid = st; sweepid <=ed; sweepid++){
/* PCOL: dependency on the ID of the master of the group of the previous column. (Previous Column:PCOL). */
/* ACOL: dependency on the ID of the master of the previous group of my column. (Acctual Column:ACOL). (it is 0(NULL) for myid=1) */
/* MCOL: OUTPUT dependency on the my ID, to be used by the next ID. (My Column: MCOL). I am the master of this group. */
myid = (i-sweepid)*(stepercol*grsiz) +(m-1)*grsiz + 1;
mylastid = myid+grsiz-1;
PCOL = mylastid+shift-1; /* to know the dependent ID of the previous column. need to know the master of its group*/
MAXID[sweepid] = myid;
PCOL = min(PCOL,MAXID[sweepid-1]); /* for the last columns, we might do only 1 or 2 kernel, so the PCOL will be wrong. this is to force it to the last ID of the previous col.*/
grnb = PCOL/grsiz;
grid = grnb*grsiz == PCOL ? grnb:grnb+1;
PCOL = (grid-1)*grsiz +1; /* give me the ID of the master of the group of the previous column.*/
ACOL = myid-grsiz;
if(myid==1)ACOL=0;
MCOL = myid;
QUARK_CORE_zbrdalg2(
plasma->quark, &task_flags,
uplo, MINMN, NB,
AB, LDAB, VQ, TAUQ, VP, TAUP, i, sweepid, m, grsiz, BAND,
DEP(PCOL), DEP(ACOL), DEP(MCOL) );
if(mylastid%2 ==0){
blklastind = (mylastid/2)*NB+1+sweepid-1;
}else{
colpt = ((mylastid+1)/2)*NB + 1 +sweepid -1 ;
stind = colpt-NB+1;
edind = min(colpt,MINMN);
if( (stind>=edind-1) && (edind==MINMN) )
blklastind=MINMN;
else
blklastind=0;
}
if(blklastind >= (MINMN-1)) stt=stt+1;
} /* END for sweepid=st:ed */
} /* END for m=1:stepercol */
} /* END for i=1:MINMN-2 */
} /* END for thgrid=1:thgrnb */
/*
* Barrier used only for now, to be sure that everything
* is done before copying the D and E and free workspace.
* this will be removed later when D and E are directly filled
* during the bulge process.
*/
QUARK_Barrier(plasma->quark);
printf("converting back to tile\n");
plasma_zooplap2tile( A, AB, NB, NB, A.lm, A.ln, 0, 0, M, N, sequence, request, plasma_desc_mat_free(&A));
/*
A = plasma_desc_init(PlasmaComplexDouble, NB,NB, NB*NB, M, N, 0, 0, M, N);
if ( plasma_desc_mat_alloc( &(A) ) ) {
plasma_error( __func__, "plasma_shared_alloc() failed");
{free;};
return PLASMA_ERR_OUT_OF_RESOURCES;
}
*/
/*
plasma_parallel_call_5( plasma_pzlapack_to_tile,
PLASMA_Complex64_t*, AB,
int, MINMN,
PLASMA_desc, A,
PLASMA_sequence*, sequence,
PLASMA_request*, request);
*/
QUARK_Barrier(plasma->quark);
printf("converting done\n");
plasma_shared_free(plasma, (void*) DEP);
plasma_shared_free(plasma, (void*) MAXID);
plasma_shared_free(plasma, (void*) VQ);
plasma_shared_free(plasma, (void*) TAUQ);
plasma_shared_free(plasma, (void*) VP);
plasma_shared_free(plasma, (void*) TAUP);
/*
* STORE THE RESULTING diagonal/off-diagonal in D AND E
*/
memset(D, 0, MINMN*sizeof(double));
memset(E, 0, (MINMN-1)*sizeof(double));
/* Make diagonal and superdiagonal elements real,
* storing them in D and E
*/
if(uplo==PlasmaUpper){
for (i=0; i < MINMN-1; i++) {
D[i] = *A(i, i );
E[i] = *A(i, i+1);
}
D[i] = *A(i, i);
}
else{
for (i=0; i < MINMN-1; i++) {
D[i] = *A(i, i );
E[i] = *A(i+1, i);
}
D[i] = *A(i, i);
}
} /* END FUNCTION */
| {
"alphanum_fraction": 0.5090786315,
"avg_line_length": 37.3333333333,
"ext": "c",
"hexsha": "0275712d274a6bb97e357210800135f544f9cc12",
"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": "compute/pzgbrdb.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": "compute/pzgbrdb.c",
"max_line_length": 200,
"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": "compute/pzgbrdb.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3923,
"size": 13328
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C header defining useful physical constants (values taken from LAL).
* Also defines boolean conventions.
*
*/
#ifndef _CONSTANTS_H
#define _CONSTANTS_H
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#if defined(__cplusplus)
extern "C" {
#elif 0
} /* so that editors will match preceding brace */
#endif
/***************************************************/
/****** Boolean conventions for loading files ******/
#define SUCCESS 0
#define FAILURE 1
/*********************************************************/
/*************** Mathematical constants ******************/
#define PI 3.1415926535897932384626433832795029
#define GAMMA 0.577215664901532860606512090082402431
#define sqrt2 1.4142135623730950488
#define sqrt3 1.7320508075688772935
#define sqrt6 2.4494897427831780982
#define invsqrt2 0.70710678118654752440
#define invsqrt3 0.57735026918962576451
#define invsqrt6 0.40824829046386301637
/**********************************************************************/
/**************** Physical constants in SI units **********************/
#define C_SI 299792458.
#define G_SI 6.67259e-11
#define MSUN_SI 1.98892e30
#define MTSUN_SI 4.9254923218988636432342917247829673e-6
#define PC_SI 3.0856775807e16
#define AU_SI 1.4959787066e11
#define YRSID_SI 3.15581497635e7 /* Sideral year as found on http://hpiers.obspm.fr/eop-pc/models/constants.html */
//#define Omega_SI 1.99098659277e-6 /* Orbital pulsation: 20pi/year for "fast-orbit-LISA2017 "*/
//#define Omega_SI 6e-7 /* Orbital pulsation: ~6pi/year for "fast-orbit-LISA2017 "*/
//#define Omega_SI 1.99098659277e-7 /* Orbital pulsation: 2pi/year - use sidereal year as found on http://hpiers.obspm.fr/eop-pc/models/constants.html */
#define EarthOrbitOmega_SI 1.99098659277e-7 /* Orbital pulsation: 2pi/year - use sidereal year as found on http://hpiers.obspm.fr/eop-pc/models/constants.html */
//#define Omega_SI 1.99098659277e-9 /* Orbital pulsation: 2pi/century - alternative model to test the impact of a non-moving LISA*/
//#define Omega_SI 1.99098659277e-11 /* Orbital pulsation: 2pi/century - alternative model to test the impact of a non-moving LISA*/
//#define f0_SI 3.168753575e-8 /* Orbital frequency: 1/year */ //not used?
//#define L_SI 5.0e9 /* Arm length of the detector (in m): (Standard LISA) */
//#define L_SI 2.5e9 /* Arm length of the detector (in m): (L3 reference LISA) */
//#define R_SI 1.4959787066e11 /* Radius of the orbit around the sun: 1AU */
#define AU_SI 1.4959787066e11 /* Radius of the orbit around the sun: 1AU */
//#define R_SI 1.4959787066e8 /* Radius of the orbit around the sun: 0.001 AU for hacked LISA test*/
/**********************************************************/
/********** Constants used to relate time scales **********/
#define EPOCH_J2000_0_TAI_UTC 32 /* Leap seconds (TAI-UTC) on the J2000.0 epoch (2000 JAN 1 12h UTC) */
#define EPOCH_J2000_0_GPS 630763213 /* GPS seconds of the J2000.0 epoch (2000 JAN 1 12h UTC) */
/*******************************************/
/**************** NaN **********************/
#ifndef NAN
# define NAN (INFINITY-INFINITY)
#endif
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif /* _CONSTANTS_H */
| {
"alphanum_fraction": 0.6583446404,
"avg_line_length": 35.0952380952,
"ext": "h",
"hexsha": "e48f96f92eef8a0dc2f00a63b09f01523f530a9d",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "tools/constants.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"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": "titodalcanton/flare",
"max_issues_repo_path": "tools/constants.h",
"max_line_length": 161,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "tools/constants.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 1035,
"size": 3685
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include <codecvt>
#include <string>
#include <locale>
#include <gsl/gsl>
namespace mira
{
inline std::string utf16_to_utf8(const wchar_t* input)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.to_bytes(input);
}
inline std::wstring utf8_to_utf16(const char* input)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
return converter.from_bytes(input);
}
inline std::string utf16_to_utf8(const std::wstring& input)
{
return utf16_to_utf8(input.data());
}
inline std::wstring utf8_to_utf16(const std::string& input)
{
return utf8_to_utf16(input.data());
}
struct string_compare
{
using is_transparent = std::true_type;
bool operator()(gsl::cstring_span<> a, gsl::cstring_span<> b) const
{
return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());
}
bool operator()(gsl::czstring_span<> a, gsl::czstring_span<> b) const
{
return (*this)(a.as_string_span(), b.as_string_span());
}
bool operator()(const char* a, const char* b) const
{
return strcmp(a, b) < 0;
}
};
}
| {
"alphanum_fraction": 0.6122599705,
"avg_line_length": 24.1785714286,
"ext": "h",
"hexsha": "8df3646470491bb0c8c828d44f12dc1eea22a166",
"lang": "C",
"max_forks_count": 16,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T15:36:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-05-07T03:09:13.000Z",
"max_forks_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "syntheticmagus/mageslam",
"max_forks_repo_path": "Dependencies/Arcana/Shared/arcana/string.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_issues_repo_issues_event_max_datetime": "2020-10-08T07:43:32.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-01T00:34:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "syntheticmagus/mageslam",
"max_issues_repo_path": "Dependencies/Arcana/Shared/arcana/string.h",
"max_line_length": 88,
"max_stars_count": 70,
"max_stars_repo_head_hexsha": "ba79a4e6315689c072c29749de18d70279a4c5e4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "syntheticmagus/mageslam",
"max_stars_repo_path": "Dependencies/Arcana/Shared/arcana/string.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T01:04:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-05-07T03:09:09.000Z",
"num_tokens": 333,
"size": 1354
} |
#ifndef CG_H_
#define CG_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "util.h"
#include "parameters.h"
#include <cblas.h>
void cgsolver( double *A, double *b, double *x, int m, int n );
double * init_source_term(int n, double h);
void smvm(int m, const double* val, const int* col, const int* row, const double* x, double* y);
void cgsolver_sparse( double *Aval, int *I, int *J, double *b, double *x, int n);
#endif /*CG_H_*/
| {
"alphanum_fraction": 0.679245283,
"avg_line_length": 23.85,
"ext": "h",
"hexsha": "a424f0d3b45e04ed22e91e8c8bc559a849d21334",
"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": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "vkeller/math-454",
"max_forks_repo_path": "projects/CG/C/cg.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"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": "vkeller/math-454",
"max_issues_repo_path": "projects/CG/C/cg.h",
"max_line_length": 96,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "vkeller/math-454",
"max_stars_repo_path": "projects/CG/C/cg.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z",
"num_tokens": 146,
"size": 477
} |
///
/// @file
///
/// @brief This file contains functions and macros that are used in the sanity
/// checks.
///
/// @author Mirko Myllykoski (mirkom@cs.umu.se), Umeå University
///
/// @internal LICENSE
///
/// Copyright (c) 2019-2020, Umeå Universitet
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions are met:
///
/// 1. Redistributions of source code must retain the above copyright notice,
/// this list of conditions and the following disclaimer.
///
/// 2. Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///
/// 3. Neither the name of the copyright holder nor the names of its
/// contributors may be used to endorse or promote products derived from this
/// software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///
#ifndef STARNEIG_COMMON_SANITY
#define STARNEIG_COMMON_SANITY
#include <starneig_config.h>
#include <starneig/configuration.h>
#ifdef STARNEIG_ENABLE_SANITY_CHECKS
#include "math.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cblas.h>
///
/// @brief Reports a sanity check error. Aborts the program.
///
/// @param[in] message
/// Message.
///
#define STARNEIG_SANITY_REPORT(message) { \
fprintf(stderr, "[starneig][sanity] %s:%d: %s\n", \
__FILE__, __LINE__, message); \
abort(); \
}
///
/// @brief Reports a sanity check error. Aborts the program.
///
/// @param[in] message
/// printf formatted message.
///
/// @param[in] ...
/// Additional printf compatible arguments.
///
#define STARNEIG_SANITY_REPORT_ARGS(message, ...) { \
fprintf(stderr, "[starneig][sanity] %s:%d: %s\n", \
__FILE__, __LINE__, message, __VA_ARGS__); \
abort(); \
}
///
/// @brief Checks a conditional statement and reports a sanity check error if
/// the condition is not satisfied. Aborts the program.
///
/// @param[in] cond
/// The conditional statement.
///
/// @param[in] message
/// Message.
///
#define STARNEIG_SANITY_CHECK(cond, message) { \
if (!(cond)) { \
fprintf(stderr, "[starneig][sanity] %s:%d: %s\n", \
__FILE__, __LINE__, message); \
abort(); \
} \
}
///
/// @brief Checks a conditional statement and reports a sanity check error if
/// the condition is not satisfied. Aborts the program.
///
/// @param[in] cond
/// The conditional statement.
///
/// @param[in] message
/// printf formatted message.
///
/// @param[in] ...
/// Additional printf compatible arguments.
///
#define STARNEIG_SANITY_CHECK_ARGS(cond, message, ...) { \
if (!(cond)) { \
fprintf(stderr, "[starneig][sanity] %s:%d: %s\n", \
__FILE__, __LINE__, message, __VA_ARGS__); \
abort(); \
} \
}
static inline void starneig_sanity_check_inf(
int rbegin, int rend, int cbegin, int cend, int ldA, double const *A,
char const *mat, char const *file, int line)
{
if (A == NULL)
return;
for (int i = cbegin; i < cend; i++) {
for (int j = rbegin; j < rend; j++) {
if (isinf(A[i*ldA+j])) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix %s has an infinite "
"element.\n", file, line, mat);
abort();
}
if (isnan(A[i*ldA+j])) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix %s has a NaN element.\n",
file, line, mat);
abort();
}
}
}
}
#define STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, mat) \
starneig_sanity_check_inf(rbegin, rend, cbegin, cend, ldA, A, mat, \
__FILE__, __LINE__)
static inline void starneig_sanity_check_multiplicities(
int n, double *real, double *imag, char const *file, int line)
{
for (int i = 0; i < n; i++) {
double lambda_re = real[i];
double lambda_im = imag[i];
if (lambda_im == 0.0) { // real eigenvalue
for (int j = i+1; j < n; j++) {
if (real[j] == lambda_re && imag[j] == 0.0) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Multiple eigenvalues at "
"S(%d,%d) and S(%d,%d).\n", file, line, i, i, j, j);
abort();
}
}
}
else { // complex eigenvalue
for (int j = i+1; j < n; j++) {
if (real[j] == lambda_re && imag[j] == lambda_im) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Multiple eigenvalues at "
"S(%d:%d,%d:%d) and S(%d:%d,%d:%d).\n",
file, line, i, i+1, i, i+1, j, j+1, j, j+1);
abort();
}
}
}
}
}
///
/// @brief A sanity check that checks for multiple eigenvalues.
///
/// @param[in] n
/// The length of the vectors real and imag.
///
/// @param[in] real
/// A vector that contains the real parts of the eigenvalues.
///
/// @param[in] imag
/// A vector that contains the imaginary parts of the eigenvalues.
///
#define STARNEIG_SANITY_CHECK_MULTIPLICITIES(n, real, imag) \
starneig_sanity_check_multiplicities(n, real, imag, __FILE__, __LINE__)
static inline void starneig_sanity_check_orthogonality(
int n, int ldQ, double const *Q, char const *mat, char const *file,
int line)
{
if (Q == NULL)
return;
starneig_sanity_check_inf(0, n, 0, n, ldQ, Q, mat, file, line);
size_t ldT;
double *T = starneig_alloc_matrix(n, n, sizeof(double), &ldT);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0,
Q, ldQ, Q, ldQ, 0.0, T, ldT);
double dot = 0.0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
dot += squ(T[i*ldT+j] - (i == j ? 1.0 : 0.0));
double norm = ((long long)1<<52) * sqrt(dot)/sqrt(n);
if (10000 < norm || isnan(norm)) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix %s is not orthogonal.\n",
file, line, mat);
fprintf(stderr,
"[starneig][sanity] %s:%d: |%s %s^T - I| / |I| = %.0f u.\n",
file, line, mat, mat, norm);
abort();
}
starneig_free_matrix(T);
}
///
/// @brief A sanity check that makes sure a matrix Q is orthogonal.
///
/// @param[in] n
/// The order of the matrix Q.
///
/// @param[in] ldQ
/// The leading dimension of the matrix Q.
///
/// @param[in] Q
/// The matrix Q.
///
/// @param[in] mat
/// A string that identifies the matrix Q.
///
#define STARNEIG_SANITY_CHECK_ORTHOGONALITY(n, ldQ, Q, mat) \
starneig_sanity_check_orthogonality(n, ldQ, Q, mat, __FILE__, __LINE__)
struct starneig_sanity_check_args {
double *A; size_t ldA;
double *B; size_t ldB;
};
static inline struct starneig_sanity_check_args *
starneig_sanity_check_residuals_begin(
int n, int ldQ, int ldZ, int ldA, int ldB, double const *Q, double const *Z,
double const *A, double const *B, char const *file, int line)
{
starneig_sanity_check_inf(0, n, 0, n, ldA, A, "A", file, line);
starneig_sanity_check_inf(0, n, 0, n, ldB, B, "B", file, line);
starneig_sanity_check_orthogonality(n, ldQ, Q, "Q", file, line);
starneig_sanity_check_orthogonality(n, ldZ, Z, "Z", file, line);
if (Z == NULL) {
Z = Q; ldZ = ldQ;
}
struct starneig_sanity_check_args *ret =
malloc(sizeof(struct starneig_sanity_check_args));
size_t ldT;
double *T = starneig_alloc_matrix(n, n, sizeof(double), &ldT);
ret->A = starneig_alloc_matrix(n, n, sizeof(double), &ret->ldA);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0,
Q, ldQ, A, ldA, 0.0, T, ldT);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0,
T, ldT, Z, ldZ, 0.0, ret->A, ret->ldA);
ret->B = NULL; ret->ldB = 0;
if (B != NULL) {
ret->B = starneig_alloc_matrix(n, n, sizeof(double), &ret->ldB);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0,
Q, ldQ, B, ldB, 0.0, T, ldT);
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, n, n, n, 1.0,
T, ldT, Z, ldZ, 0.0, ret->B, ret->ldB);
}
starneig_free_matrix(T);
starneig_sanity_check_inf(0, n, 0, n, ret->ldA, ret->A, "A", file, line);
starneig_sanity_check_inf(0, n, 0, n, ret->ldB, ret->B, "B", file, line);
return ret;
}
///
/// @brief The first part of a sanity check that makes sure a matrix pencil
/// Q (A,B) X^T and an updated matrix pencil ~Q (~A,~B) ~X^T are equivalent.
///
/// @param[in] name
/// An unique identifier.
///
/// @param[in] n
/// The order of the matrices A, B, Q and Z.
///
/// @param[in] ldQ
/// The leading dimension of the matrix Q.
///
/// @param[in] ldZ
/// The leading dimension of the matrix Z.
///
/// @param[in] ldA
/// The leading dimension of the matrix A.
///
/// @param[in] ldB
/// The leading dimension of the matrix B.
///
/// @param[in] Q
/// The matrix Q.
///
/// @param[in] Z
/// The matrix Z.
///
/// @param[in] A
/// The matrix A.
///
/// @param[in] B
/// The matrix B.
///
#define STARNEIG_SANITY_CHECK_RESIDUALS_BEGIN( \
name, n, ldQ, ldZ, ldA, ldB, Q, Z, A, B) \
struct starneig_sanity_check_args *name = \
starneig_sanity_check_residuals_begin( \
n, ldQ, ldZ, ldA, ldB, Q, Z, A, B, __FILE__, __LINE__)
static inline void starneig_sanity_check_residuals_end(
int n, int ldQ, int ldZ, int ldA, int ldB, double const *Q, double const *Z,
double const *A, double const *B,
struct starneig_sanity_check_args const *args, char const *file, int line)
{
struct starneig_sanity_check_args *ret =
starneig_sanity_check_residuals_begin(
n, ldQ, ldZ, ldA, ldB, Q, Z, A, B, file, line);
int failure = 0;
{
double dot = 0.0;
for(int i = 0; i < n; ++i )
for(int j = 0; j < n; ++j )
dot += squ(ret->A[ret->ldA*i+j] - args->A[args->ldA*i+j]);
double a_dot = 0.0;
for(int i = 0; i < n; ++i )
for(int j = 0; j < n; ++j )
a_dot += squ(args->A[args->ldA*i+j]);
double norm = ((long long)1<<52) * sqrt(dot)/sqrt(a_dot);
if (10000 < norm || isnan(norm)) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Residual check failed for the "
"matrix A.\n", file, line);
fprintf(stderr,
"[starneig][sanity] %s:%d: The norm was %.0f u.\n",
file, line, norm);
failure++;
}
}
if (B != NULL) {
double dot = 0.0;
for(int i = 0; i < n; ++i )
for(int j = 0; j < n; ++j )
dot += squ(ret->B[ret->ldB*i+j] - args->B[args->ldB*i+j]);
double a_dot = 0.0;
for(int i = 0; i < n; ++i )
for(int j = 0; j < n; ++j )
a_dot += squ(args->B[args->ldB*i+j]);
double norm = ((long long)1<<52) * sqrt(dot)/sqrt(a_dot);
if (10000 < norm || isnan(norm)) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Residual check failed for the "
"matrix B.\n", file, line);
fprintf(stderr,
"[starneig][sanity] %s:%d: The norm was %.0f u.\n",
file, line, norm);
failure++;
}
}
if (failure)
abort();
starneig_free_matrix(ret->A);
starneig_free_matrix(ret->B);
free(ret);
}
///
/// @brief The second part of a sanity check that makes sure a matrix pencil
/// Q (A,B) X^T and an updated matrix pencil ~Q (~A,~B) ~X^T are equivalent.
///
/// @param[in] name
/// An unique identifier.
///
/// @param[in] n
/// The order of the matrices A, B, Q and Z.
///
/// @param[in] ldQ
/// The leading dimension of the matrix Q.
///
/// @param[in] ldZ
/// The leading dimension of the matrix Z.
///
/// @param[in] ldA
/// The leading dimension of the matrix A.
///
/// @param[in] ldB
/// The leading dimension of the matrix B.
///
/// @param[in] Q
/// The matrix Q.
///
/// @param[in] Z
/// The matrix Z.
///
/// @param[in] A
/// The matrix A.
///
/// @param[in] B
/// The matrix B.
///
#define STARNEIG_SANITY_CHECK_RESIDUALS_END( \
name, n, ldQ, ldZ, ldA, ldB, Q, Z, A, B) \
starneig_sanity_check_residuals_end( \
n, ldQ, ldZ, ldA, ldB, Q, Z, A, B, name, __FILE__, __LINE__); \
if (name != NULL) { \
starneig_free_matrix(name->A); \
starneig_free_matrix(name->B); \
free(name); \
name = NULL; \
}
///
/// @brief Skips the second part of a sanity check that makes sure a matrix
/// pencil Q (A,B) X^T and an updated matrix pencil ~Q (~A,~B) ~X^T are
/// equivalent.
///
/// @param[in] name
/// An unique identifier.
///
#define STARNEIG_SANITY_CHECK_RESIDUALS_SKIP(name) \
if (name != NULL) { \
starneig_free_matrix(name->A); \
starneig_free_matrix(name->B); \
free(name); \
name = NULL; \
}
static inline void starneig_sanity_check_bulges(
int begin, int shifts, int n, int ldA, int ldB,
double const *A, double const *B, char const *file, int line)
{
starneig_sanity_check_inf(
0, n, begin, begin+3*(shifts/2)+1, ldA, A, "A", file, line);
starneig_sanity_check_inf(
0, n, begin, begin+3*(shifts/2)+1, ldB, B, "B", file, line);
if (n < begin+3*(shifts/2)+1) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix A has an invalid bulge.\n",
file, line);
abort();
}
double const *_A = A+begin*ldA+begin;
double const *_B = B != NULL ? B+begin*ldB+begin : NULL;
int _n = n - begin;
for (int i = 0; i < shifts/2; i++) {
for (int j = 3*i+4; j < _n; j++) {
if (_A[3*i*ldA+j] != 0.0 || _A[(3*i+1)*ldA+j] != 0.0 ||
_A[(3*i+2)*ldA+j] != 0.0) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix A has an invalid "
"bulge.\n", file, line);
abort();
}
}
for (int j = 3*i+3; _B != NULL && j < _n; j++) {
if (_B[3*i*ldB+j] != 0.0 || _B[(3*i+1)*ldB+j] != 0.0 ||
_B[(3*i+2)*ldB+j] != 0.0) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix B has invalid bulge .\n",
file, line);
abort();
}
}
if (_B != NULL &&
(_B[3*i*ldB+3*i+1] != 0.0 || _B[3*i*ldB+3*i+2] != 0.0)) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix B has invalid bulge.\n",
file, line);
abort();
}
}
}
///
/// @brief A sanity check that makes sure that matrix pencil (A,B) contains the
/// correct number of bulges.
///
/// @param[in] begin
/// The column that should contain the first bulge.
///
/// @param[in] shifts
/// The number of shifts (shifts/2 bulges).
///
/// @param[in] n
/// The order of the matrices A and B.
///
/// @param[in] ldA
/// The leading dimension of the matrix A.
///
/// @param[in] ldB
/// The leading dimension of the matrix B.
///
/// @param[in] A
/// The matrix A.
///
/// @param[in] B
/// The matrix B.
///
#define STARNEIG_SANITY_CHECK_BULGES(begin, shifts, n, ldA, ldB, A, B) \
starneig_sanity_check_bulges( \
begin, shifts, n, ldA, ldB, A, B, __FILE__, __LINE__)
static inline void starneig_sanity_check_schur(
int begin, int end, int n, int ldA, int ldB,
double const *A, double const *B, char const *file, int line)
{
starneig_sanity_check_inf(0, n, begin, end, ldA, A, "A", file, line);
starneig_sanity_check_inf(0, n, begin, end, ldB, B, "B", file, line);
const double safmin = dlamch("S");
int two_by_two = 0;
for (int i = begin; i < end; i++) {
if (i+1 < end && A[i*ldA+i+1] != 0.0) {
if (two_by_two) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix A is not in Schur "
"form.\n", file, line);
abort();
}
if (B != NULL) {
if (B[(i+1)*ldB+i] != 0.0 || B[i*ldB+i+1] != 0.0) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix pencil (A,B) "
"contains a non-normalized 2-by-2 block.\n",
file, line);
abort();
}
if (B[i*ldB+i] == 0.0 || B[(i+1)*ldB+i+1] == 0.0) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix B is singular.",
file, line);
abort();
}
double s1, s2, wr1, wr2, wi;
extern void dlag2_(double const *, int const *, double const *,
int const *, double const *, double *, double *,
double *, double *, double *);
dlag2_(&A[i*ldA+i], &ldA, &B[i*ldB+i], &ldB, &safmin,
&s1, &s2, &wr1, &wr2, &wi);
if (wi == 0.0) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix pencil (A,B) "
"contains a fake 2-by-2 block.\n", file, line);
abort();
}
}
else {
if (A[i*ldA+i] != A[(i+1)*ldA+i+1]) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix A contains a "
"non-normalized 2-by-2 block.\n",
file, line);
abort();
}
double a[] = {
A[i*ldA+i], A[i*ldA+i+1], A[(i+1)*ldA+i], A[(i+1)*ldA+i+1]
};
double rt1r, rt1i, rt2r, rt2i, cs, ss;
extern void dlanv2_(
double *, double *, double *, double *, double *,
double *, double *, double *, double *, double *);
dlanv2_(&a[0], &a[2], &a[1], &a[3],
&rt1r, &rt1i, &rt2r, &rt2i, &cs, &ss);
if (rt1i == 0.0 || rt2i == 0.0) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix A contains a fake "
"2-by-2 block.\n", file, line);
abort();
}
}
two_by_two = 1;
}
else {
two_by_two = 0;
}
for (int j = i+2; j < n; j++) {
if (A[i*ldA+j] != 0.0) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix A is not in Schur "
"form.\n", file, line);
abort();
}
}
}
if (B != NULL) {
for (int i = begin; i < end; i++) {
for (int j = i+2; j < n; j++) {
if (B[i*ldB+j] != 0.0) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix B is not in upper "
"Hessenberg form.\n", file, line);
abort();
}
}
}
}
}
///
/// @brief A sanity check that makes sure that matrix pencil (A,B) is in Schur
/// form.
///
/// @param[in] begin
/// The first column to check.
///
/// @param[in] end
/// The last column to check + 1;
///
/// @param[in] n
/// The order of the matrices A and B.
///
/// @param[in] ldA
/// The leading dimension of the matrix A.
///
/// @param[in] ldB
/// The leading dimension of the matrix B.
///
/// @param[in] A
/// The matrix A.
///
/// @param[in] B
/// The matrix B.
///
#define STARNEIG_SANITY_CHECK_SCHUR(begin, end, n, ldA, ldB, A, B) \
starneig_sanity_check_schur( \
begin, end, n, ldA, ldB, A, B, __FILE__, __LINE__)
static inline void starneig_sanity_check_hessenberg(
int begin, int end, int n, int ldA, int ldB,
double const *A, double const *B, char const *file, int line)
{
starneig_sanity_check_inf(0, n, begin, end, ldA, A, "A", file, line);
starneig_sanity_check_inf(0, n, begin, end, ldB, B, "B", file, line);
for (int i = begin; i < end; i++) {
for (int j = i+2; j < n; j++) {
if (A[i*ldA+j] != 0.0) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix A is not in upper "
"Hessenberg form.\n", file, line);
abort();
}
}
}
for (int i = begin; B != NULL && i < end; i++) {
for (int j = i+1; j < n; j++) {
if (B[i*ldB+j] != 0.0) {
fprintf(stderr,
"[starneig][sanity] %s:%d: Matrix B is not in upper "
"triangular form.\n", file, line);
abort();
}
}
}
}
///
/// @brief A sanity check that makes sure that matrix pencil (A,B) is in
/// Hessenberg-triangular form.
///
/// @param[in] begin
/// The first column to check.
///
/// @param[in] end
/// The last column to check + 1;
///
/// @param[in] n
/// The order of the matrices A and B.
///
/// @param[in] ldA
/// The leading dimension of the matrix A.
///
/// @param[in] ldB
/// The leading dimension of the matrix B.
///
/// @param[in] A
/// The matrix A.
///
/// @param[in] B
/// The matrix B.
///
#define STARNEIG_SANITY_CHECK_HESSENBERG(begin, end, n, ldA, ldB, A, B) \
starneig_sanity_check_hessenberg( \
begin, end, n, ldA, ldB, A, B, __FILE__, __LINE__)
#else
#define STARNEIG_SANITY_REPORT(message) {}
#define STARNEIG_SANITY_REPORT_ARGS(message, ...) {}
#define STARNEIG_SANITY_CHECK(cond, message) {}
#define STARNEIG_SANITY_CHECK_ARGS(cond, message, ...) {}
#define STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, mat) {}
#define STARNEIG_SANITY_CHECK_MULTIPLICITIES(n, real, imag) {}
#define STARNEIG_SANITY_CHECK_ORTHOGONALITY(n, ldQ, Q, mat) {}
#define STARNEIG_SANITY_CHECK_RESIDUALS_BEGIN( \
name, n, ldQ, ldZ, ldA, ldB, Q, Z, A, B) {}
#define STARNEIG_SANITY_CHECK_RESIDUALS_END( \
name, n, ldQ, ldZ, ldA, ldB, Q, Z, A, B) {}
#define STARNEIG_SANITY_CHECK_RESIDUALS_SKIP(name) {}
#define STARNEIG_SANITY_CHECK_BULGES(begin, shifts, n, ldA, ldB, A, B) {}
#define STARNEIG_SANITY_CHECK_SCHUR(begin, end, n, ldA, ldB, A, B) {}
#define STARNEIG_SANITY_CHECK_HESSENBERG(begin, end, n, ldA, ldB, A, B) {}
#endif // STARNEIG_ENABLE_SANITY_CHECKS
#endif // STARNEIG_COMMON_SANITY
| {
"alphanum_fraction": 0.5288976246,
"avg_line_length": 31.4631578947,
"ext": "h",
"hexsha": "92d9aa30d0011880227fb0953c091cc6e00f9774",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z",
"max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/StarNEig",
"max_forks_repo_path": "src/common/sanity.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/StarNEig",
"max_issues_repo_path": "src/common/sanity.h",
"max_line_length": 80,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/StarNEig",
"max_stars_repo_path": "src/common/sanity.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z",
"num_tokens": 7020,
"size": 23912
} |
#ifndef _EM_LA_H_
#define _EM_LA_H_ 1
#include <petsc.h>
struct EMContext;
PetscErrorCode access_vec(Vec, std::vector<PetscInt> &, int, double *);
PetscErrorCode setup_ams(EMContext *);
PetscErrorCode destroy_ams(EMContext *);
PetscErrorCode create_pc(EMContext *);
PetscErrorCode destroy_pc(EMContext *);
PetscErrorCode pc_apply_b(PC, Vec, Vec);
PetscErrorCode matshell_createvecs_a(Mat, Vec *, Vec *);
PetscErrorCode matshell_mult_a(Mat, Vec, Vec);
PetscErrorCode solve_linear_system(EMContext *, const PETScBlockVector &, PETScBlockVector &, PetscInt, PetscReal);
#endif
| {
"alphanum_fraction": 0.7869415808,
"avg_line_length": 25.3043478261,
"ext": "h",
"hexsha": "9c3aec455363042c12b60ac9cd105df02d534f56",
"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": "9129e28610d7fcb83a88021528575dfeaadad502",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "emfem/emfem",
"max_forks_repo_path": "src/em_la.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502",
"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": "emfem/emfem",
"max_issues_repo_path": "src/em_la.h",
"max_line_length": 115,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "9129e28610d7fcb83a88021528575dfeaadad502",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "emfem/emfem",
"max_stars_repo_path": "src/em_la.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-03T12:22:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-03T12:22:37.000Z",
"num_tokens": 151,
"size": 582
} |
//
// Copyright (c) 2009, Markus Rickert
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include <chrono>
#include <memory>
#include <nlopt.h>
#include <random>
#include <utility>
#include "Exception.h"
#include "IterativeInverseKinematics.h"
namespace rl
{
namespace mdl
{
class RL_MDL_EXPORT WeightedInverseKinematics : public IterativeInverseKinematics
{
public:
class Exception : public ::rl::mdl::Exception
{
public:
Exception(const ::nlopt_result& result);
virtual ~Exception() throw();
static void check(const ::nlopt_result& result);
::nlopt_result getResult() const;
virtual const char* what() const throw();
protected:
private:
::nlopt_result result;
};
WeightedInverseKinematics(Kinematic* kinematic);
virtual ~WeightedInverseKinematics();
::rl::math::Real getFunctionToleranceAbsolute() const;
::rl::math::Real getFunctionToleranceRelative() const;
const ::rl::math::Vector& getLowerBound() const;
::rl::math::Vector getOptimizationToleranceAbsolute() const;
::rl::math::Real getOptimizationToleranceRelative() const;
const ::rl::math::Vector& getUpperBound() const;
void seed(const ::std::mt19937::result_type& value);
void setEpsilon(const ::rl::math::Real& epsilon);
void setFunctionToleranceAbsolute(const ::rl::math::Real& functionToleranceAbsolute);
void setFunctionToleranceRelative(const ::rl::math::Real& functionToleranceRelative);
void setLowerBound(const ::rl::math::Vector& lb);
void setOptimizationToleranceAbsolute(const ::rl::math::Real& optimizationToleranceAbsolute);
void setOptimizationToleranceAbsolute(const ::rl::math::Vector& optimizationToleranceAbsolute);
void setOptimizationToleranceRelative(const ::rl::math::Real& optimizationToleranceRelative);
void setUpperBound(const ::rl::math::Vector& ub);
bool solve();
protected:
private:
static double f(unsigned int n, const double* x, double* grad, void* data);
::std::size_t iteration;
::rl::math::Vector lb;
::std::unique_ptr<::nlopt_opt_s, decltype(&::nlopt_destroy)> opt;
::std::uniform_real_distribution<::rl::math::Real> randDistribution;
::std::mt19937 randEngine;
::rl::math::Vector ub;
};
}
}
| {
"alphanum_fraction": 0.7157778999,
"avg_line_length": 30.8305084746,
"ext": "h",
"hexsha": "5830386a1c346daec1e62af981f0962ef06cc7fa",
"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": "1579ba2097576818dadb447d314edfb336293c6d",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "Mark-Yeatman/rl",
"max_forks_repo_path": "src/rl/mdl/WeightedInverseKinematics.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1579ba2097576818dadb447d314edfb336293c6d",
"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": "Mark-Yeatman/rl",
"max_issues_repo_path": "src/rl/mdl/WeightedInverseKinematics.h",
"max_line_length": 98,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1579ba2097576818dadb447d314edfb336293c6d",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "Mark-Yeatman/rl",
"max_stars_repo_path": "src/rl/mdl/WeightedInverseKinematics.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 867,
"size": 3638
} |
#ifndef SETTINGSWIDGET_H
#define SETTINGSWIDGET_H
#include <QWidget>
#include "utilities/usersettings.h"
#include <gsl/gsl>
#include <memory>
class QDoubleSpinBox;
namespace Ui {
class DisparitySettingsWidget;
}
class DisparitySettingsWidget : public QWidget {
Q_OBJECT
public:
explicit DisparitySettingsWidget(QWidget* parent = 0);
~DisparitySettingsWidget() override;
void setUserSettings(gsl::not_null<UserSettings*> settings);
UserSettings getUserSettings();
void conditionalAutoUpdate();
signals:
void settingsUpdated(UserSettings updatedSettings);
void accepted();
void rejected();
private:
void ensureMinSmallerThanMax(gsl::not_null<QDoubleSpinBox*> min,
gsl::not_null<QDoubleSpinBox*> max);
void ensureMaxLargerThanMin(gsl::not_null<QDoubleSpinBox*> min,
gsl::not_null<QDoubleSpinBox*> max);
std::unique_ptr<Ui::DisparitySettingsWidget> ui;
};
#endif // SETTINGSWIDGET_H
| {
"alphanum_fraction": 0.7270875764,
"avg_line_length": 21.8222222222,
"ext": "h",
"hexsha": "182e9c1770f346eece1ad8b396a5a3cf1bfad504",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-05-18T16:22:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-13T21:51:09.000Z",
"max_forks_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "hugbed/OpenS3D",
"max_forks_repo_path": "src/apps/S3DAnalyzer/widgets/disparitysettingswidget.h",
"max_issues_count": 40,
"max_issues_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_issues_repo_issues_event_max_datetime": "2017-12-21T18:41:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-04-12T17:24:44.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "hugbed/OpenS3D",
"max_issues_repo_path": "src/apps/S3DAnalyzer/widgets/disparitysettingswidget.h",
"max_line_length": 67,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "4ffad16f9b0973404b59eb1424cc45f68754fe12",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "hugbed/OpenS3D",
"max_stars_repo_path": "src/apps/S3DAnalyzer/widgets/disparitysettingswidget.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-20T03:23:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-04-16T16:38:15.000Z",
"num_tokens": 217,
"size": 982
} |
/**
Copyright (c) 2014, Konstantinos Chatzilygeroudis
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.
**/
#ifndef GEOMETRIC_TOOLS_MATH_VECTOR_H
#define GEOMETRIC_TOOLS_MATH_VECTOR_H
/**
* Includes
**/
#include <iostream>
#include <limits>
#include <cmath>
#include <cstring>
#include <geometric_tools/Misc/Helper.h>
#include <cblas.h>
namespace GeometricTools { namespace Math {
template<unsigned int ROWS, unsigned int COLS>
class Matrix;
/**
* General Vector Class
* Supports N-dimension vectors
**/
template<unsigned int N>
class Vector
{
protected:
// values of vector
double values_[N];
// helper variable for initialization
unsigned int index_;
/**
* Initialize Vector from double values
* C++11 feature - variadic templates for multiple arguments
**/
template<typename... Args>
void initialize(double h, Args&&... args)
{
if(index_>=N)
index_=0;
// add first argument to the vector data
values_[index_] = h;
index_++;
// Initialize with rest of arguments
initialize(std::forward<Args>(args)...);
}
/**
* Initialize Vector from double values
* C++11 feature - variadic templates for multiple arguments
* Terminating Case - end of arguments
**/
template<typename... Args>
void initialize()
{
index_ = 0;
}
public:
/**
* Default Constructor
* initialize all data to zero
**/
Vector()
{
memset(values_,0,N*sizeof(double));
}
/**
* Copy Constructor
* @param other - Vector to copy from
**/
Vector(const Vector& other)
{
memcpy(values_,other.values_,N*sizeof(double));
}
/**
* Constructor
* @param h - list of double values
**/
template<typename... Args>
Vector(double h, Args&&... args)
{
index_ = 0;
memset(values_,0,N*sizeof(double));
// use recursive initialization
initialize(h, args...);
}
/**
* Overloading += operator
* Addition of 2 Vectors
* @param other - vector to perform addition with
* @return Vector - self (as the result is saved there)
**/
Vector operator+=(const Vector& other)
{
cblas_daxpy(N, 1.0, &other.values_[0], 1, &values_[0], 1);
return *this;
}
/**
* Overloading -= operator
* Subtraction of 2 Vectors
* @param other - vector to perform subtraction with
* @return Vector - self (as the result is saved there)
**/
Vector operator-=(const Vector& other)
{
cblas_daxpy(N, -1.0, &other.values_[0], 1, &values_[0], 1);
return *this;
}
/**
* Overloading += operator
* Addition with scalar (double)
* @param other - double to add with
* @return Vector - self (result)
**/
Vector operator+=(const double& other)
{
Vector tmp;
tmp.ones();
cblas_daxpy(N, other, &tmp.values_[0], 1, &values_[0], 1);
return *this;
}
/**
* Overloading -= operator
* Subtraction of scalar (double)
* @param other - double to substract
* @return Vector - self (result)
**/
Vector operator-=(const double& other)
{
Vector tmp;
tmp.ones();
cblas_daxpy(N, -other, &tmp.values_[0], 1, &values_[0], 1);
return *this;
}
/**
* Overloading *= operator
* Multiplication with scalar (double)
* @param other - double to multiply with
* @return Vector - self (result)
**/
Vector operator*=(const double& other)
{
cblas_dscal(N, other, &values_[0], 1);
return *this;
}
/**
* Overloading /= operator
* Division with scalar (double) - if zero ignores division (returns self)
* @param other - double to divide with
* @return Vector - self (result)
**/
Vector operator/=(const double& other)
{
if(std::abs(other) < std::numeric_limits<double>::epsilon())
return (*this);
cblas_dscal(N, 1.0/other, &values_[0], 1);
return *this;
}
/**
* Overloading + operator
* Addition of 2 Vectors
* @return Vector - the result of the addition
**/
Vector operator+(const Vector& lh) const
{
Vector t = (*this);
t += lh;
return t;
}
/**
* Overloading - operator
* Subtraction of 2 Vectors
* @return Vector - the result of the subtraction
**/
Vector operator-(const Vector& lh) const
{
Vector t = (*this);
t -= lh;
return t;
}
/**
* Overloading * operator
* Multiplication of 2 Vectors (Dot product)
* @return double - the result of the multiplication
**/
double operator*(const Vector& lh) const
{
double s = 0.0;
for(unsigned int i=0;i<N;i++)
s += (*this)[i]*lh[i];
return s;
}
/**
* Overloading + operator
* Addition with scalar (double)
* @param other - double to add with
* @return Vector - the result
**/
Vector operator+(const double& other) const
{
Vector tmp = (*this);
tmp += other;
return tmp;
}
/**
* Overloading - operator
* Subtraction of scalar (double)
* @param other - double to subtract
* @return Vector - the result
**/
Vector operator-(const double& other) const
{
Vector tmp = (*this);
tmp -= other;
return tmp;
}
/**
* Overloading * operator
* Multiplication with scalar (double)
* @param other - double to multiply with
* @return Vector - the result
**/
Vector operator*(const double& other) const
{
Vector tmp = (*this);
tmp *= other;
return tmp;
}
/**
* Overloading / operator
* Division with scalar (double) - if zero ignores division (returns self)
* @param other - double to divide with
* @return Vector - the result
**/
Vector operator/(const double& other) const
{
Vector tmp = (*this);
tmp /= other;
return tmp;
}
/**
* Overloading minus (-) operator
**/
Vector operator-()
{
return -1*(*this);
}
/**
* Overloading == operator
* @param other - Vector to compare
* @return bool
**/
bool operator==(const Vector& other) const
{
Vector tmp = (*this)-other;
return (tmp.lengthSq()<std::numeric_limits<double>::epsilon());
}
/**
* Overloading != operator
* @param other - Vector to compare
* @return bool
**/
bool operator!=(const Vector& other) const
{
Vector tmp = (*this)-other;
return (tmp.lengthSq()>=std::numeric_limits<double>::epsilon());
}
// !-- THIS NEEDS TO BE REMOVED --! //
/**
* Get pointer to values array
* @return pointer to array
**/
double* data()
{
return values_;
}
/**
* Get Length of Vector
* @return double - length
**/
double length() const
{
return cblas_dnrm2(N, &values_[0], 1);
}
/**
* Set vector to 1s
**/
void ones()
{
memset(&values_[0], 1, N*sizeof(double));
}
/**
* Get LengthSq of Vector
* @return double - length squared
**/
double lengthSq() const
{
double s = cblas_dnrm2(N, &values_[0], 1);
return s*s;
}
/**
* Normalize Vector
**/
void normalize()
{
double l = length();
if(l>std::numeric_limits<double>::epsilon())
*this /= l;
}
/**
* Normalized Vector
**/
Vector normalized()
{
Vector tmp = Vector(*this);
tmp.normalize();
return tmp;
}
/**
* Overloading () operator
* Access Vector Matlab-like
* @param i - index to return
* @return double - value of i-th element
**/
double& operator()(int i) //needs assert legal index
{
return values_[i];
}
/**
* Overloading () operator - const version
* Access Vector Matlab-like
* @param i - index to return
* @return double - value of i-th element
**/
double operator()(int i) const //needs assert legal index
{
return values_[i];
}
/**
* Overloading [] operator
* Access Vector Array-like
* @param i - index to return
* @return double - value of i-th element
**/
double& operator[](int i) //assert legal index
{
return values_[i];
}
/**
* Overloading [] operator - const version
* Access Vector Array-like
* @param i - index to return
* @return double - value of i-th element
**/
double operator[](int i) const //assert legal index
{
return values_[i];
}
/**
* Get ith unit vector with size N
* @param i
* @return Vector - unit vector
**/
static Vector e(const unsigned int& i)
{
Vector k;
k[i] = 1;
return k;
}
/**
* Destructor
**/
~Vector(void)
{
}
template<unsigned int ROWS, unsigned int COLS>
friend class Matrix;
};
/**
* Cross Product
* Applies only to 3D Vectors
* @return Vector - the result of the cross product
**/
inline Vector<3> cross(const Vector<3>& rh, const Vector<3>& lh)
{
return Vector<3>(rh[1]*lh[2]-rh[2]*lh[1], rh[2]*lh[0]-rh[0]*lh[2], rh[0]*lh[1]-rh[1]*lh[0]);
}
/**
* Projection of a to e
* @return Vector - the result of the cross product
**/
template <unsigned int N>
Vector<N> projection(const Vector<N>& a, const Vector<N>& e)
{
return ((e*a)*e/(e*e));
}
/**
* Overloading << operator
* "print" vector to stream
* @param ostream - stream to print the vector to
* @param Vector - vector to print
**/
template <unsigned int N>
std::ostream& operator<<(std::ostream& os, const Vector<N>& obj)
{
for(unsigned int i=0;i<N-1;i++)
os<<obj[i]<<" ";
os<<obj[N-1];
return os;
}
/**
* Overloading >> operator
* read vector from stream
* @param istream - stream to read the vector from
* @param Vector - vector to read
**/
template <unsigned int N>
std::istream& operator>>(std::istream& in, Vector<N>& obj)
{
for(unsigned int i=0;i<N;i++)
in>>obj[i];
return in;
}
/**
* Overloading / operator
* Division with scalar (double)
* Perform Vector / scalar (as opposed to Vector / scalar inside Class)
**/
template <unsigned int N>
Vector<N> operator/(const double& a, const Vector<N>& b)
{
if(std::abs(a) < std::numeric_limits<double>::epsilon())
return Vector<N>();
Vector<N> tmp = Vector<N>(b);
for(unsigned int i=0;i<N;i++) {
if(std::abs(tmp[i]) < std::numeric_limits<double>::epsilon())
return b;
tmp[i] = a/tmp[i];
}
return tmp;
}
/**
* Overloading * operator
* Multiplication with scalar (double)
* Perform scalar * Vector (as opposed to Vector * scalar inside Class)
**/
template <unsigned int N>
Vector<N> operator*(const double& a, const Vector<N>& b)
{
return b*a;
}
/**
* Typedefs for frequently used types
**/
typedef Vector<2> Vector2;
typedef Vector<3> Vector3;
typedef Vector<4> Vector4;
} }
#endif
| {
"alphanum_fraction": 0.5956127802,
"avg_line_length": 24.1034482759,
"ext": "h",
"hexsha": "32a8c2fe2c9eb0ac0cbdfa3c184c810b6e758784",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-05-28T02:34:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-05-15T00:32:17.000Z",
"max_forks_repo_head_hexsha": "456b1a50764d600a97fb6c7770f01a54049af78f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "costashatz/GeometricTools",
"max_forks_repo_path": "include/geometric_tools/Math/Vector.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "456b1a50764d600a97fb6c7770f01a54049af78f",
"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": "costashatz/GeometricTools",
"max_issues_repo_path": "include/geometric_tools/Math/Vector.h",
"max_line_length": 142,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "456b1a50764d600a97fb6c7770f01a54049af78f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "costashatz/GeometricTools",
"max_stars_repo_path": "include/geometric_tools/Math/Vector.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-23T06:44:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-09-15T11:07:50.000Z",
"num_tokens": 3145,
"size": 12582
} |
/*
* mcmc_lotkavolterra.c
*
* Created on: 15/11/2015
* Author: Laura Ferrer
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#define USAGE "./mcmc_lotkavolterra.x n_steps n_burn"
void leer(double *tiempo, double *presa, double *depredador, int n_puntos);
double* iniciar(int n_puntos);
int main (int argc, char **argv)
{
int i=0;
int lineas = 0;
int iteraciones = atof(argv[2])+atof(argv[1]);
int corte = atof(argv[2]);
double a = 1;
double b = 1;
double c = 1;
double d = 1;
double a2;
double b2;
double c2;
double d2;
FILE *file;
file = fopen("lotka_volterra_obs.dat", "r");
while(!feof(file)) //Cuenta la cantidad de datos provistos.
{
char ch = fgetc(file);
if(ch == '\n')
{
lineas++;
}
}
fclose(file);
lineas --;// menos la primera línea
double *x = iniciar(lineas);
double *y= iniciar(lineas);
double *x_real= iniciar(lineas);
double *y_real = iniciar(lineas);
double *t = iniciar(lineas);
double *lay = iniciar(lineas);
double *lax = iniciar(lineas);
leer(t,x_real,y_real,lineas);
lay[0]=y_real[0];
lax[0]=x_real[0];
double parecido (double modo)
{
i = 0;
double suma=0;
if (modo == 1)
{
for (i = 0; i < lineas; i += 1)
{
suma += pow(x[i]-y_real[i],2.0);
suma += pow(y[i]-x_real[i],2.0);
}
}
if (modo == 2)
{
for (i = 0; i < lineas; i += 1)
{
suma += pow(lax[i]-y_real[i],2.0);
suma += pow(lay[i]-x_real[i],2.0);
}
}
return (1.0/2.0)*suma;
}
double dx (double x, double y, double la, double lb)
{
double dx = x*(la-lb*y);
return dx;
}
double dy (double x, double y, double lc, double ld)
{
double dy = -y*(lc-ld*x);
return dy;
}
void kutta4 (double la, double lb, double lc, double ld)
{
double h = t[1]-t[0];
i = 1;
for (i = 1; i < lineas; i += 1)
{
//Inicio
double kx1 = dx(lax[i-1],lay[i-1],la,lb);
double ky1 = dy(lax[i-1],lay[i-1],lc,ld);
//paso 1
double x1 = lax[i-1] + (h/2.0)*kx1;
double y1 = lay[i-1] + (h/2.0)*ky1;
double kx2 = dx(x1,y1,la,lb);
double ky2 = dy(x1,y1,lc,ld);
//paso 2
double x2 = lax[i-1] + (h/2.0)*kx2;
double y2 = lay[i-1] + (h/2.0)*ky2;
double kx3 = dx(x2,y2,la,lb);
double ky3 = dy(x2,y2,lc,ld);
//paso 3
double x3 = lax[i-1] + h*kx3;
double y3 = lay[i-1] + h*ky3;
double kx4 = dx(x3,y3,la,lb);
double ky4 = dy(x3,y3,lc,ld);
//paso 4
double mx = (1.0/6.0)*(kx1 + 2.0*kx2+2.0*kx3+kx4);
double my = (1.0/6.0)*(ky1 + 2.0*ky2+2.0*ky3+ky4);
lax[i]= lax[i-1] + h*mx;
lay[i]= lay[i-1] + h*my;
}
}
void mcmc()
{
int k = 1;
for (k = 1; k < iteraciones; k++)
{
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
a2 = a + (2*gsl_ran_gaussian(r,drand48())+1);
srand((unsigned)time(NULL));
b2 = b + (2*gsl_ran_gaussian(r,drand48())+1);
srand((unsigned)time(NULL));
c2 = c + (2*gsl_ran_gaussian(r,drand48())+1);
srand((unsigned)time(NULL));
d2 = d + (2*gsl_ran_gaussian(r,drand48())+1);
srand((unsigned)time(NULL));
kutta4(a,b,c,d);
int j =0;
for (j = 0; j < lineas; j++) // Copia las listas
{
x[j] = lax[j];
y[j] = lay[j];
}
kutta4(a2,b2,c2,d2);
// Calculo de los errores y similitudes
double difvieja = parecido(1);
double difnueva = parecido(2);
if (difnueva < difvieja)
{
a=a2;
b=b2;
c=c2;
d=d2;
if (k>corte) {printf ("%g,%g,%g,%g\n",a,b,c,d);}
}
else
{
srand((unsigned)time(NULL));
double alfa = difvieja/difnueva;
double beta = drand48();
if (beta >= alfa)
{
a=a2;
b=b2;
c=c2;
d=d2;
if (k>corte) {printf ("%g,%g,%g,%g\n",a,b,c,d);}
}
else if (k>corte)
{
printf ("%g,%g,%g,%g\n",a,b,c,d);
}
}
}
}
mcmc();
return 0;
}
void leer(double *tiempo, double *presa, double *depredador, int n_puntos)
{
FILE *file;
int j;
file = fopen("lotka_volterra_obs.dat", "r");
rewind(file);
fscanf(file,"%*[^\n]\n"); //Lee cualquier cosa en la primera línea
for(j=0;j<n_puntos;j++)
{
fscanf(file, "%lf %lf %lf\n", &tiempo[j], &presa[j], &depredador[j]);
}
fclose(file);
}
double* iniciar(int n_puntos)
{
double *array;
int i;
if(!(array = malloc(n_puntos * sizeof(double))))
{
printf("Problema en reserva\n");
exit(1);
}
for(i=0;i<n_puntos;i++)
{
array[i] = 0.0;
}
return array;
}
| {
"alphanum_fraction": 0.5156057495,
"avg_line_length": 19.6370967742,
"ext": "c",
"hexsha": "ff34d0f9197045bddef1b4f8972b3e0abbafac5d",
"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": "8f8fa38695d23a6aaa97fed7facc6bf03481c03d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "laluferu/hw_7",
"max_forks_repo_path": "poblaciones/mcmc_lotkavolterra.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8f8fa38695d23a6aaa97fed7facc6bf03481c03d",
"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": "laluferu/hw_7",
"max_issues_repo_path": "poblaciones/mcmc_lotkavolterra.c",
"max_line_length": 76,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8f8fa38695d23a6aaa97fed7facc6bf03481c03d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "laluferu/hw_7",
"max_stars_repo_path": "poblaciones/mcmc_lotkavolterra.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1798,
"size": 4870
} |
#include <err.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
#define X y[0]
#define V_X y[1]
#define Y y[2]
#define V_Y y[3]
const double g = 9.81; /* m/s^2 */
const double v_0 = 700.0; /* m/s */
const double B2_m = 4.0e-5; /* 1/m */
const double y_d = 1.0e4; /* m */
int func(double t, const double y[], double f[], void *params);
int main(int argc, char *argv[]) {
gsl_odeiv2_system sys = {func, NULL, 4, NULL};
gsl_odeiv2_driver *driver = gsl_odeiv2_driver_alloc_y_new(
&sys, gsl_odeiv2_step_rkf45, 1.0e-6, 1.0e-6, 0.0
);
int i = 1;
double t = 0.0;
double alpha = argc > 1 ? strtod(argv[1], NULL) : 1.0;
double y[4];
X = Y = 0.0;
V_X = v_0*cos(alpha);
V_Y = v_0*sin(alpha);
while (Y >= 0.0) {
double t_i = i/50.0;
int status = gsl_odeiv2_driver_apply(driver, &t, t_i, y);
if (status != GSL_SUCCESS) {
warnx("apply status = %d", status);
break;
}
printf("%.12le %.12le %.12le %.12le %.12le\n", t, X, Y, V_X, V_Y);
i++;
}
gsl_odeiv2_driver_free(driver);
return EXIT_SUCCESS;
}
#define DX_DT f[0]
#define DVX_DT f[1]
#define DY_DT f[2]
#define DVY_DT f[3]
int func(double t, const double y[], double f[], void *params) {
double v = sqrt(V_X*V_X + V_Y*V_Y);
double corr = exp(-Y/y_d);
DX_DT = V_X;
DVX_DT = -B2_m*corr*v*V_X;
DY_DT = V_Y;
DVY_DT = -g - B2_m*corr*v*V_Y;
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.5665594855,
"avg_line_length": 25.9166666667,
"ext": "c",
"hexsha": "88ec89e597463e54c21416fe85c7a350af7c70ff",
"lang": "C",
"max_forks_count": 59,
"max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z",
"max_forks_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "Gjacquenot/training-material",
"max_forks_repo_path": "LinuxTools/Autotools/Libraries/src/cannon_ode.c",
"max_issues_count": 56,
"max_issues_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "Gjacquenot/training-material",
"max_issues_repo_path": "LinuxTools/Autotools/Libraries/src/cannon_ode.c",
"max_line_length": 74,
"max_stars_count": 115,
"max_stars_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "Gjacquenot/training-material",
"max_stars_repo_path": "LinuxTools/Autotools/Libraries/src/cannon_ode.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z",
"num_tokens": 565,
"size": 1555
} |
/*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.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.openairinterface.org/?page_id=698
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
/*! \file oaisim.c
* \brief oaisim top level
* \author Navid Nikaein
* \date 2013-2015
* \version 1.0
* \company Eurecom
* \email: openair_tech@eurecom.fr
* \note
* \warning
*/
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <cblas.h>
#include <execinfo.h>
#include "event_handler.h"
#include "SIMULATION/RF/defs.h"
#include "PHY/types.h"
#include "PHY/defs.h"
#include "PHY/LTE_TRANSPORT/proto.h"
#include "PHY/vars.h"
#include "SIMULATION/ETH_TRANSPORT/proto.h"
//#ifdef OPENAIR2
#include "LAYER2/MAC/defs.h"
#include "LAYER2/MAC/proto.h"
#include "LAYER2/MAC/vars.h"
#include "pdcp.h"
#include "RRC/LITE/vars.h"
#include "RRC/NAS/nas_config.h"
#include "SCHED/defs.h"
#include "SCHED/vars.h"
#include "system.h"
#include "PHY/TOOLS/lte_phy_scope.h"
#ifdef SMBV
// Rohde&Schwarz SMBV100A vector signal generator
#include "PHY/TOOLS/smbv.h"
char smbv_fname[] = "smbv_config_file.smbv";
unsigned short smbv_nframes = 4; // how many frames to configure 1,..,4
unsigned short config_frames[4] = {2,9,11,13};
unsigned char smbv_frame_cnt = 0;
uint8_t config_smbv = 0;
char smbv_ip[16];
#endif
#if defined(FLEXRAN_AGENT_SB_IF)
# include "flexran_agent.h"
#endif
#include "oaisim_functions.h"
#include "oaisim.h"
#include "oaisim_config.h"
#include "UTIL/OCG/OCG_extern.h"
#include "cor_SF_sim.h"
#include "UTIL/OMG/omg_constants.h"
#include "UTIL/FIFO/pad_list.h"
#include "enb_app.h"
#include "../PROC/interface.h"
#include "../PROC/channel_sim_proc.h"
#include "../PROC/Tsync.h"
#include "../PROC/Process.h"
#include "UTIL/LOG/vcd_signal_dumper.h"
#include "UTIL/OTG/otg_kpi.h"
#include "assertions.h"
#if defined(ENABLE_ITTI)
# include "intertask_interface.h"
# include "create_tasks.h"
#endif
#include "T.h"
/*
DCI0_5MHz_TDD0_t UL_alloc_pdu;
DCI1A_5MHz_TDD_1_6_t CCCH_alloc_pdu;
DCI2_5MHz_2A_L10PRB_TDD_t DLSCH_alloc_pdu1;
DCI2_5MHz_2A_M10PRB_TDD_t DLSCH_alloc_pdu2;
*/
#define UL_RB_ALLOC computeRIV(lte_frame_parms->N_RB_UL,0,24)
#define CCCH_RB_ALLOC computeRIV(lte_frame_parms->N_RB_UL,0,3)
#define RA_RB_ALLOC computeRIV(lte_frame_parms->N_RB_UL,0,3)
#define DLSCH_RB_ALLOC 0x1fff
#define DECOR_DIST 100
#define SF_VAR 10
//constant for OAISIM soft realtime calibration
//#define SF_DEVIATION_OFFSET_NS 100000 /*= 0.1ms : should be as a number of UE */
//#define SLEEP_STEP_US 100 /* = 0.01ms could be adaptive, should be as a number of UE */
//#define K 2 /* averaging coefficient */
//#define TARGET_SF_TIME_NS 1000000 /* 1ms = 1000000 ns */
uint8_t usim_test = 0;
frame_t frame = 0;
char stats_buffer[16384];
channel_desc_t *eNB2UE[NUMBER_OF_eNB_MAX][NUMBER_OF_UE_MAX][MAX_NUM_CCs];
channel_desc_t *UE2eNB[NUMBER_OF_UE_MAX][NUMBER_OF_eNB_MAX][MAX_NUM_CCs];
//Added for PHY abstraction
node_desc_t *enb_data[NUMBER_OF_eNB_MAX];
node_desc_t *ue_data[NUMBER_OF_UE_MAX];
pthread_cond_t sync_cond;
pthread_mutex_t sync_mutex;
int sync_var=-1;
pthread_mutex_t subframe_mutex;
int subframe_eNB_mask=0,subframe_UE_mask=0;
openair0_config_t openair0_cfg[MAX_CARDS];
uint32_t downlink_frequency[MAX_NUM_CCs][4];
int32_t uplink_frequency_offset[MAX_NUM_CCs][4];
openair0_rf_map rf_map[MAX_NUM_CCs];
#if defined(ENABLE_ITTI)
volatile int start_eNB = 0;
volatile int start_UE = 0;
#endif
volatile int oai_exit = 0;
//int32_t **rxdata;
//int32_t **txdata;
// Added for PHY abstraction
extern node_list* ue_node_list;
extern node_list* enb_node_list;
extern int pdcp_period, omg_period;
extern double **s_re, **s_im, **r_re, **r_im, **r_re0, **r_im0;
int map1, map2;
extern double **ShaF;
double snr_dB, sinr_dB, snr_direction; //,sinr_direction;
extern double snr_step;
extern uint8_t set_sinr;
extern uint8_t ue_connection_test;
extern uint8_t set_seed;
extern uint8_t target_dl_mcs;
extern uint8_t target_ul_mcs;
extern uint8_t abstraction_flag;
extern uint8_t ethernet_flag;
extern uint16_t Nid_cell;
extern LTE_DL_FRAME_PARMS *frame_parms[MAX_NUM_CCs];
double cpuf;
#include "threads_t.h"
threads_t threads= {-1,-1,-1,-1,-1,-1,-1};
//#ifdef XFORMS
int otg_enabled;
int xforms=0;
//#endif
time_stats_t oaisim_stats;
time_stats_t oaisim_stats_f;
time_stats_t dl_chan_stats;
time_stats_t ul_chan_stats;
// this should reflect the channel models in openair1/SIMULATION/TOOLS/defs.h
mapping small_scale_names[] = {
{ "custom", custom }, { "SCM_A", SCM_A },
{ "SCM_B", SCM_B }, { "SCM_C", SCM_C },
{ "SCM_D", SCM_D }, { "EPA", EPA },
{ "EVA", EVA }, { "ETU", ETU },
{ "MBSFN", MBSFN }, { "Rayleigh8", Rayleigh8 },
{ "Rayleigh1", Rayleigh1 }, { "Rayleigh1_800", Rayleigh1_800 },
{ "Rayleigh1_corr", Rayleigh1_corr }, { "Rayleigh1_anticorr", Rayleigh1_anticorr },
{ "Rice8", Rice8 }, { "Rice1", Rice1 }, { "Rice1_corr", Rice1_corr },
{ "Rice1_anticorr", Rice1_anticorr }, { "AWGN", AWGN }, { NULL,-1 }
};
#if !defined(ENABLE_ITTI)
static void *
sigh (void *arg);
#endif
void
oai_shutdown (void);
void reset_opp_meas_oaisim (void);
void
help (void)
{
printf ("Usage: oaisim -h -a -F -C tdd_config -K [log_file] -V [vcd_file] -R N_RB_DL -e -x transmission_mode -m target_dl_mcs -r(ate_adaptation) -n n_frames -s snr_dB -k ricean_factor -t max_delay -f forgetting factor -A channel_model -z cooperation_flag -u nb_local_ue -U UE mobility -b nb_local_enb -B eNB_mobility -M ethernet_flag -p nb_master -g multicast_group -l log_level -c ocg_enable -T traffic model -D multicast network device\n");
printf ("-h provides this help message!\n");
printf ("-a Activates PHY abstraction mode\n");
printf ("-A set the multipath channel simulation, options are: SCM_A, SCM_B, SCM_C, SCM_D, EPA, EVA, ETU, Rayleigh8, Rayleigh1, Rayleigh1_corr,Rayleigh1_anticorr, Rice8,, Rice1, AWGN \n");
printf ("-b Set the number of local eNB\n");
printf ("-B Set the mobility model for eNB, options are: STATIC, RWP, RWALK, \n");
printf ("-c [1,2,3,4] Activate the config generator (OCG) to process the scenario descriptor, or give the scenario manually: -c template_1.xml \n");
printf ("-C [0-6] Sets TDD configuration\n");
printf ("-e Activates extended prefix mode\n");
printf ("-E Random number generator seed\n");
printf ("-f Set the forgetting factor for time-variation\n");
printf ("-F Activates FDD transmission (TDD is default)\n");
printf ("-g Set multicast group ID (0,1,2,3) - valid if M is set\n");
printf ("-G Enable background traffic \n");
printf ("-H Enable handover operation (default disabled) \n");
printf ("-I Enable CLI interface (to connect use telnet localhost 1352)\n");
printf ("-k Set the Ricean factor (linear)\n");
printf ("-K [log_file] Enable ITTI logging into log_file\n");
printf ("-l Set the global log level (8:trace, 7:debug, 6:info, 4:warn, 3:error) \n");
printf ("-L [0-1] 0 to disable new link adaptation, 1 to enable new link adapatation\n");
printf ("-m Gives a fixed DL mcs for eNB scheduler\n");
printf ("-M Set the machine ID for Ethernet-based emulation\n");
printf ("-n Set the number of frames for the simulation. 0 for no limit\n");
printf ("-O [enb_conf_file] eNB configuration file name\n");
printf ("-p Set the total number of machine in emulation - valid if M is set\n");
printf ("-P [trace type] Enable protocol analyzer. Possible values for OPT:\n");
printf (" - wireshark: Enable tracing of layers above PHY using an UDP socket\n");
printf (" - pcap: Enable tracing of layers above PHY to a pcap file\n");
printf (" - tshark: Not implemented yet\n");
printf ("-q Enable Openair performance profiler \n");
printf ("-Q Activate and set the MBMS service: 0 : not used (default eMBMS disabled), 1: eMBMS and RRC Connection enabled, 2: eMBMS relaying and RRC Connection enabled, 3: eMBMS enabled, RRC Connection disabled, 4: eMBMS relaying enabled, RRC Connection disabled\n");
printf ("-R [6,15,25,50,75,100] Sets N_RB_DL\n");
printf ("-r Activates rate adaptation (DL for now)\n");
printf ("-s snr_dB set a fixed (average) SNR, this deactivates the openair channel model generator (OCM)\n");
printf ("-S snir_dB set a fixed (average) SNIR, this deactivates the openair channel model generator (OCM)\n");
printf ("-t Gives a fixed UL mcs for eNB scheduler\n");
printf ("-T activate the traffic generator. Valide options are m2m,scbr,mcbr,bcbr,auto_pilot,bicycle_race,open_arena,team_fortress,m2m_traffic,auto_pilot_l,auto_pilot_m,auto_pilot_h,auto_pilot_e,virtual_game_l,virtual_game_m,virtual_game_h,virtual_game_f,alarm_humidity,alarm_smoke,alarm_temperature,openarena_dl,openarena_ul,voip_g711,voip_g729,video_vbr_10mbps,video_vbr_4mbps,video_vbr_2mbp,video_vbr_768kbps,video_vbr_384kbps,video_vbr_192kpbs,background_users\n");
printf ("-u Set the number of local UE\n");
printf ("-U Set the mobility model for UE, options are: STATIC, RWP, RWALK\n");
printf ("-V [vcd_file] Enable VCD dump into vcd_file\n");
printf ("-w number of CBA groups, if not specified or zero, CBA is inactive\n");
#ifdef SMBV
printf ("-W IP address to connect to Rohde&Schwarz SMBV100A and configure SMBV from config file. -W0 uses default IP 192.168.12.201\n");
#else
printf ("-W [Rohde&Schwarz SMBV100A functions disabled. Recompile with SMBV=1]\n");
#endif
printf ("-x deprecated. Set the transmission mode in config file!\n");
printf ("-y Set the number of receive antennas at the UE (1 or 2)\n");
printf ("-Y Set the global log verbosity (none, low, medium, high, full) \n");
printf ("-z Set the cooperation flag (0 for no cooperation, 1 for delay diversity and 2 for distributed alamouti\n");
printf ("-Z Reserved\n");
printf ("--xforms Activate the grapical scope\n");
#if T_TRACER
printf ("--T_port [port] use given port\n");
printf ("--T_nowait don't wait for tracer, start immediately\n");
printf ("--T_dont_fork to ease debugging with gdb\n");
#endif
}
pthread_t log_thread;
void
log_thread_init (void)
{
//create log_list
//log_list_init(&log_list);
#ifndef LOG_NO_THREAD
log_shutdown = 0;
if ((pthread_mutex_init (&log_lock, NULL) != 0)
|| (pthread_cond_init (&log_notify, NULL) != 0)) {
return;
}
if (pthread_create (&log_thread, NULL, log_thread_function, (void*) NULL)
!= 0) {
log_thread_finalize ();
return;
}
#endif
}
//Call it after the last LOG call
int
log_thread_finalize (void)
{
int err = 0;
#ifndef LOG_NO_THREAD
if (pthread_mutex_lock (&log_lock) != 0) {
return -1;
}
log_shutdown = 1;
/* Wake up LOG thread */
if ((pthread_cond_broadcast (&log_notify) != 0)
|| (pthread_mutex_unlock (&log_lock) != 0)) {
err = -1;
}
if (pthread_join (log_thread, NULL) != 0) {
err = -1;
}
if (pthread_mutex_unlock (&log_lock) != 0) {
err = -1;
}
if (!err) {
//log_list_free(&log_list);
pthread_mutex_lock (&log_lock);
pthread_mutex_destroy (&log_lock);
pthread_cond_destroy (&log_notify);
}
#endif
return err;
}
#if defined(ENABLE_ITTI)
static void set_cli_start(module_id_t module_idP, uint8_t start)
{
if (module_idP < NB_eNB_INST) {
oai_emulation.info.cli_start_enb[module_idP] = start;
} else {
oai_emulation.info.cli_start_ue[module_idP - NB_eNB_INST] = start;
}
}
#endif
#ifdef OPENAIR2
int omv_write(int pfd, node_list* enb_node_list, node_list* ue_node_list, Data_Flow_Unit omv_data)
{
module_id_t i, j;
omv_data.end = 0;
//omv_data.total_num_nodes = NB_UE_INST + NB_eNB_INST;
for (i = 0; i < NB_eNB_INST; i++) {
if (enb_node_list != NULL) {
omv_data.geo[i].x = (enb_node_list->node->x_pos < 0.0) ? 0.0 : enb_node_list->node->x_pos;
omv_data.geo[i].y = (enb_node_list->node->y_pos < 0.0) ? 0.0 : enb_node_list->node->y_pos;
omv_data.geo[i].z = 1.0;
omv_data.geo[i].mobility_type = oai_emulation.info.omg_model_enb;
omv_data.geo[i].node_type = 0; //eNB
enb_node_list = enb_node_list->next;
omv_data.geo[i].Neighbors = 0;
for (j = NB_eNB_INST; j < NB_UE_INST + NB_eNB_INST; j++) {
if (is_UE_active (i, j - NB_eNB_INST) == 1) {
omv_data.geo[i].Neighbor[omv_data.geo[i].Neighbors] = j;
omv_data.geo[i].Neighbors++;
LOG_D(
OMG,
"[eNB %d][UE %d] is_UE_active(i,j) %d geo (x%d, y%d) num neighbors %d\n", i, j-NB_eNB_INST, is_UE_active(i,j-NB_eNB_INST), omv_data.geo[i].x, omv_data.geo[i].y, omv_data.geo[i].Neighbors);
}
}
}
}
for (i = NB_eNB_INST; i < NB_UE_INST + NB_eNB_INST; i++) {
if (ue_node_list != NULL) {
omv_data.geo[i].x = (ue_node_list->node->x_pos < 0.0) ? 0.0 : ue_node_list->node->x_pos;
omv_data.geo[i].y = (ue_node_list->node->y_pos < 0.0) ? 0.0 : ue_node_list->node->y_pos;
omv_data.geo[i].z = 1.0;
omv_data.geo[i].mobility_type = oai_emulation.info.omg_model_ue;
omv_data.geo[i].node_type = 1; //UE
//trial
omv_data.geo[i].state = 1;
omv_data.geo[i].rnti = 88;
omv_data.geo[i].connected_eNB = 0;
omv_data.geo[i].RSRP = 66;
omv_data.geo[i].RSRQ = 55;
omv_data.geo[i].Pathloss = 44;
omv_data.geo[i].RSSI[0] = 33;
omv_data.geo[i].RSSI[1] = 22;
if ((sizeof(omv_data.geo[0].RSSI) / sizeof(omv_data.geo[0].RSSI[0])) > 2) {
omv_data.geo[i].RSSI[2] = 11;
}
ue_node_list = ue_node_list->next;
omv_data.geo[i].Neighbors = 0;
for (j = 0; j < NB_eNB_INST; j++) {
if (is_UE_active (j, i - NB_eNB_INST) == 1) {
omv_data.geo[i].Neighbor[omv_data.geo[i].Neighbors] = j;
omv_data.geo[i].Neighbors++;
LOG_D(
OMG,
"[UE %d][eNB %d] is_UE_active %d geo (x%d, y%d) num neighbors %d\n", i-NB_eNB_INST, j, is_UE_active(j,i-NB_eNB_INST), omv_data.geo[i].x, omv_data.geo[i].y, omv_data.geo[i].Neighbors);
}
}
}
}
LOG_E(OMG, "pfd %d \n", pfd);
if (write (pfd, &omv_data, sizeof(struct Data_Flow_Unit)) == -1)
perror ("write omv failed");
return 1;
}
void omv_end(int pfd, Data_Flow_Unit omv_data)
{
omv_data.end = 1;
if (write (pfd, &omv_data, sizeof(struct Data_Flow_Unit)) == -1)
perror ("write omv failed");
}
#endif
#ifdef OPENAIR2
int pfd[2]; // fd for omv : fixme: this could be a local var
#endif
#ifdef OPENAIR2
static Data_Flow_Unit omv_data;
#endif //ALU
static module_id_t UE_inst = 0;
static module_id_t eNB_inst = 0;
Packet_OTG_List_t *otg_pdcp_buffer;
typedef enum l2l1_task_state_e {
L2L1_WAITTING, L2L1_RUNNING, L2L1_TERMINATED,
} l2l1_task_state_t;
l2l1_task_state_t l2l1_state = L2L1_WAITTING;
extern openair0_timestamp current_eNB_rx_timestamp[NUMBER_OF_eNB_MAX][MAX_NUM_CCs];
extern openair0_timestamp current_UE_rx_timestamp[NUMBER_OF_UE_MAX][MAX_NUM_CCs];
extern openair0_timestamp last_eNB_rx_timestamp[NUMBER_OF_eNB_MAX][MAX_NUM_CCs];
extern openair0_timestamp last_UE_rx_timestamp[NUMBER_OF_UE_MAX][MAX_NUM_CCs];
/*------------------------------------------------------------------------------*/
void *
l2l1_task (void *args_p)
{
int CC_id;
// Framing variables
int32_t sf;
//char fname[64], vname[64];
//#ifdef XFORMS
// current status is that every UE has a DL scope for a SINGLE eNB (eNB_id=0)
// at eNB 0, an UL scope for every UE
FD_lte_phy_scope_ue *form_ue[MAX_NUM_CCs][NUMBER_OF_UE_MAX];
FD_lte_phy_scope_enb *form_enb[NUMBER_OF_UE_MAX];
char title[255];
char xname[32] = "oaisim";
int xargc = 1;
char *xargv[1];
//#endif
#undef PRINT_STATS /* this undef is to avoid gcc warnings */
#define PRINT_STATS
#ifdef PRINT_STATS
int len;
FILE *UE_stats[NUMBER_OF_UE_MAX];
FILE *UE_stats_th[NUMBER_OF_UE_MAX];
FILE *eNB_stats[NUMBER_OF_eNB_MAX];
FILE *eNB_avg_thr;
FILE *eNB_l2_stats;
char UE_stats_filename[255];
char eNB_stats_filename[255];
char UE_stats_th_filename[255];
char eNB_stats_th_filename[255];
#endif
if (xforms==1) {
xargv[0] = xname;
fl_initialize (&xargc, xargv, NULL, 0, 0);
eNB_inst = 0;
for (UE_inst = 0; UE_inst < NB_UE_INST; UE_inst++) {
for (CC_id=0;CC_id<MAX_NUM_CCs;CC_id++) {
// DL scope at UEs
form_ue[CC_id][UE_inst] = create_lte_phy_scope_ue();
sprintf (title, "LTE DL SCOPE eNB %d to UE %d CC_id %d", eNB_inst, UE_inst, CC_id);
fl_show_form (form_ue[CC_id][UE_inst]->lte_phy_scope_ue, FL_PLACE_HOTSPOT, FL_FULLBORDER, title);
if (PHY_vars_UE_g[UE_inst][CC_id]->use_ia_receiver == 1) {
fl_set_button(form_ue[CC_id][UE_inst]->button_0,1);
fl_set_object_label(form_ue[CC_id][UE_inst]->button_0, "IA Receiver ON");
fl_set_object_color(form_ue[CC_id][UE_inst]->button_0, FL_GREEN, FL_GREEN);
}
}
// UL scope at eNB 0
form_enb[UE_inst] = create_lte_phy_scope_enb();
sprintf (title, "LTE UL SCOPE UE %d to eNB %d", UE_inst, eNB_inst);
fl_show_form (form_enb[UE_inst]->lte_phy_scope_enb, FL_PLACE_HOTSPOT, FL_FULLBORDER, title);
}
}
#ifdef PRINT_STATS
for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {
sprintf(UE_stats_filename,"UE_stats%d.txt",UE_inst);
UE_stats[UE_inst] = fopen (UE_stats_filename, "w");
}
for (eNB_inst=0; eNB_inst<NB_eNB_INST; eNB_inst++) {
sprintf(eNB_stats_filename,"eNB_stats%d.txt",eNB_inst);
eNB_stats[eNB_inst] = fopen (eNB_stats_filename, "w");
}
if(abstraction_flag==0) {
for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {
/* TODO: transmission_mode is defined per CC, we set 0 for now */
sprintf(UE_stats_th_filename,"UE_stats_th%d_tx%d.txt",UE_inst,oai_emulation.info.transmission_mode[0]);
UE_stats_th[UE_inst] = fopen (UE_stats_th_filename, "w");
}
/* TODO: transmission_mode is defined per CC, we set 0 for now */
sprintf(eNB_stats_th_filename,"eNB_stats_th_tx%d.txt",oai_emulation.info.transmission_mode[0]);
eNB_avg_thr = fopen (eNB_stats_th_filename, "w");
} else {
for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {
/* TODO: transmission_mode is defined per CC, we set 0 for now */
sprintf(UE_stats_th_filename,"UE_stats_abs_th%d_tx%d.txt",UE_inst,oai_emulation.info.transmission_mode[0]);
UE_stats_th[UE_inst] = fopen (UE_stats_th_filename, "w");
}
/* TODO: transmission_mode is defined per CC, we set 0 for now */
sprintf(eNB_stats_th_filename,"eNB_stats_abs_th_tx%d.txt",oai_emulation.info.transmission_mode[0]);
eNB_avg_thr = fopen (eNB_stats_th_filename, "w");
}
#ifdef OPENAIR2
eNB_l2_stats = fopen ("eNB_l2_stats.txt", "w");
LOG_I(EMU,"eNB_l2_stats=%p\n", eNB_l2_stats);
#endif
#endif
#if defined(ENABLE_ITTI)
MessageDef *message_p = NULL;
const char *msg_name = NULL;
int result;
itti_mark_task_ready (TASK_L2L1);
LOG_I(EMU, "TASK_L2L1 is READY\n");
if ((oai_emulation.info.nb_enb_local > 0) &&
(oai_emulation.info.node_function[0] < NGFI_RAU_IF4p5)) {
/* Wait for the initialize message */
do {
if (message_p != NULL) {
result = itti_free (ITTI_MSG_ORIGIN_ID(message_p), message_p);
AssertFatal (result == EXIT_SUCCESS, "Failed to free memory (%d)!\n", result);
}
itti_receive_msg (TASK_L2L1, &message_p);
msg_name = ITTI_MSG_NAME (message_p);
LOG_I(EMU, "TASK_L2L1 received %s in state L2L1_WAITTING\n", msg_name);
switch (ITTI_MSG_ID(message_p)) {
case INITIALIZE_MESSAGE:
l2l1_state = L2L1_RUNNING;
start_eNB = 1;
break;
case ACTIVATE_MESSAGE:
set_cli_start(ITTI_MSG_INSTANCE (message_p), 1);
break;
case DEACTIVATE_MESSAGE:
set_cli_start(ITTI_MSG_INSTANCE (message_p), 0);
break;
case TERMINATE_MESSAGE:
l2l1_state = L2L1_TERMINATED;
break;
default:
LOG_E(EMU, "Received unexpected message %s\n", ITTI_MSG_NAME(message_p));
break;
}
} while (l2l1_state == L2L1_WAITTING);
result = itti_free (ITTI_MSG_ORIGIN_ID(message_p), message_p);
AssertFatal (result == EXIT_SUCCESS, "Failed to free memory (%d)!\n", result);
}
#endif
module_id_t enb_id;
module_id_t UE_id;
for (enb_id = 0; enb_id < NB_eNB_INST; enb_id++)
mac_xface->mrbch_phy_sync_failure (enb_id, 0, enb_id);
if (abstraction_flag == 1) {
for (UE_id = 0; UE_id < NB_UE_INST; UE_id++)
mac_xface->dl_phy_sync_success (UE_id, 0, 0,1); //UE_id%NB_eNB_INST);
}
start_meas (&oaisim_stats);
for (frame = 0;
(l2l1_state != L2L1_TERMINATED) &&
((oai_emulation.info.n_frames_flag == 0) ||
(frame < oai_emulation.info.n_frames));
frame++) {
#if defined(ENABLE_ITTI)
do {
// Checks if a message has been sent to L2L1 task
itti_poll_msg (TASK_L2L1, &message_p);
if (message_p != NULL) {
msg_name = ITTI_MSG_NAME (message_p);
LOG_I(EMU, "TASK_L2L1 received %s\n", msg_name);
switch (ITTI_MSG_ID(message_p)) {
case ACTIVATE_MESSAGE:
set_cli_start(ITTI_MSG_INSTANCE (message_p), 1);
break;
case DEACTIVATE_MESSAGE:
set_cli_start(ITTI_MSG_INSTANCE (message_p), 0);
break;
case TERMINATE_MESSAGE:
l2l1_state = L2L1_TERMINATED;
break;
case MESSAGE_TEST:
break;
default:
LOG_E(EMU, "Received unexpected message %s\n", ITTI_MSG_NAME(message_p));
break;
}
result = itti_free (ITTI_MSG_ORIGIN_ID(message_p), message_p);
AssertFatal (result == EXIT_SUCCESS, "Failed to free memory (%d)!\n", result);
}
} while(message_p != NULL);
#endif
//Run the aperiodic user-defined events
if (oai_emulation.info.oeh_enabled == 1)
execute_events (frame);
if (ue_connection_test == 1) {
if ((frame % 20) == 0) {
snr_dB += snr_direction;
sinr_dB -= snr_direction;
}
if (snr_dB == -20) {
snr_direction = snr_step;
} else if (snr_dB == 20) {
snr_direction = -snr_step;
}
}
oai_emulation.info.frame = frame;
//oai_emulation.info.time_ms += 1;
oai_emulation.info.time_s += 0.01; // emu time in s, each frame lasts for 10 ms // JNote: TODO check the coherency of the time and frame (I corrected it to 10 (instead of 0.01)
update_omg (frame); // frequency is defined in the omg_global params configurable by the user
update_omg_ocm ();
#ifdef OPENAIR2
// check if pipe is still open
if ((oai_emulation.info.omv_enabled == 1)) {
omv_write (pfd[1], enb_node_list, ue_node_list, omv_data);
}
#endif
update_ocm ();
for (sf = 0; sf < 10; sf++) {
LOG_D(EMU,"************************* Subframe %d\n",sf);
start_meas (&oaisim_stats_f);
wait_for_slot_isr ();
#if defined(ENABLE_ITTI)
itti_update_lte_time(frame % MAX_FRAME_NUMBER, sf<<1);
#endif
oai_emulation.info.time_ms = frame * 10 + sf;
#ifdef PROC
if(Channel_Flag==1)
Channel_Func(s_re2,s_im2,r_re2,r_im2,r_re02,r_im02,r_re0_d,r_im0_d,r_re0_u,r_im0_u,eNB2UE,UE2eNB,enb_data,ue_data,abstraction_flag,frame_parms,sf<<1);
if(Channel_Flag==0)
#endif
{ // SUBFRAME INNER PART
#if defined(ENABLE_ITTI)
log_set_instance_type (LOG_INSTANCE_ENB);
#endif
clear_eNB_transport_info (oai_emulation.info.nb_enb_local);
int all_done=0;
while (all_done==0) {
int i;
all_done = 1;
for (i = oai_emulation.info.first_enb_local;
i < oai_emulation.info.first_enb_local + oai_emulation.info.nb_enb_local;
i++)
for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++)
if (last_eNB_rx_timestamp[i][CC_id] != current_eNB_rx_timestamp[i][CC_id]) {
all_done = 0;
break;
}
if (all_done == 1)
for (i = 0; i < NB_UE_INST; i++)
for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++)
if (last_UE_rx_timestamp[i][CC_id] != current_UE_rx_timestamp[i][CC_id]) {
all_done = 0;
break;
}
if (all_done == 0)
usleep(500);
}
// increment timestamps
for (eNB_inst = oai_emulation.info.first_enb_local;
(eNB_inst
< (oai_emulation.info.first_enb_local
+ oai_emulation.info.nb_enb_local));
eNB_inst++) {
for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++)
current_eNB_rx_timestamp[eNB_inst][CC_id] += PHY_vars_eNB_g[eNB_inst][CC_id]->frame_parms.samples_per_tti;
}
for (UE_inst = 0; UE_inst<NB_UE_INST;UE_inst++) {
for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++)
current_UE_rx_timestamp[UE_inst][CC_id] += PHY_vars_UE_g[UE_inst][CC_id]->frame_parms.samples_per_tti;
}
for (eNB_inst = oai_emulation.info.first_enb_local;
(eNB_inst
< (oai_emulation.info.first_enb_local
+ oai_emulation.info.nb_enb_local));
eNB_inst++) {
if (oai_emulation.info.cli_start_enb[eNB_inst] != 0) {
/*
LOG_D(EMU,
"PHY procedures eNB %d for frame %d, subframe %d TDD %d/%d Nid_cell %d\n",
eNB_inst,
frame % MAX_FRAME_NUMBER,
sf,
PHY_vars_eNB_g[eNB_inst][0]->frame_parms.frame_type,
PHY_vars_eNB_g[eNB_inst][0]->frame_parms.tdd_config,
PHY_vars_eNB_g[eNB_inst][0]->frame_parms.Nid_cell);
*/
#ifdef OPENAIR2
//Application: traffic gen
update_otg_eNB (eNB_inst, oai_emulation.info.time_ms);
//IP/OTG to PDCP and PDCP to IP operation
// pdcp_run (frame, 1, 0, eNB_inst); //PHY_vars_eNB_g[eNB_id]->Mod_id
#endif
#ifdef PRINT_STATS
if((sf==9) && frame%10==0)
if(eNB_avg_thr)
fprintf(eNB_avg_thr,"%d %d\n",PHY_vars_eNB_g[eNB_inst][0]->proc.proc_rxtx[sf&1].frame_tx,
(PHY_vars_eNB_g[eNB_inst][0]->total_system_throughput)/((PHY_vars_eNB_g[eNB_inst][0]->proc.proc_rxtx[sf&1].frame_tx+1)*10));
if (eNB_stats[eNB_inst]) {
len = dump_eNB_stats(PHY_vars_eNB_g[eNB_inst][0], stats_buffer, 0);
rewind (eNB_stats[eNB_inst]);
fwrite (stats_buffer, 1, len, eNB_stats[eNB_inst]);
fflush(eNB_stats[eNB_inst]);
}
#ifdef OPENAIR2
if (eNB_l2_stats) {
len = dump_eNB_l2_stats (stats_buffer, 0);
rewind (eNB_l2_stats);
fwrite (stats_buffer, 1, len, eNB_l2_stats);
fflush(eNB_l2_stats);
}
#endif
#endif
}
}// eNB_inst loop
// Call ETHERNET emulation here
//emu_transport (frame, last_slot, next_slot, direction, oai_emulation.info.frame_type, ethernet_flag);
#if defined(ENABLE_ITTI)
log_set_instance_type (LOG_INSTANCE_UE);
#endif
/*
clear_UE_transport_info (oai_emulation.info.nb_ue_local);
clear_UE_transport_info (oai_emulation.info.nb_ue_local);
for (UE_inst = oai_emulation.info.first_ue_local;
(UE_inst < (oai_emulation.info.first_ue_local + oai_emulation.info.nb_ue_local));
UE_inst++) {
if (oai_emulation.info.cli_start_ue[UE_inst] != 0) {
#if defined(ENABLE_ITTI) && defined(ENABLE_USE_MME)
#else
if (frame >= (UE_inst * 20)) // activate UE only after 20*UE_id frames so that different UEs turn on separately
#endif
{
LOG_D(EMU,
"PHY procedures UE %d for frame %d, slot %d (subframe TX %d, RX %d)\n",
UE_inst, frame % MAX_FRAME_NUMBER, slot, next_slot >> 1,
last_slot >> 1);
if (PHY_vars_UE_g[UE_inst][0]->UE_mode[0]
!= NOT_SYNCHED) {
if (frame > 0) {
PHY_vars_UE_g[UE_inst][0]->frame_rx = frame % MAX_FRAME_NUMBER;
PHY_vars_UE_g[UE_inst][0]->slot_rx = last_slot;
PHY_vars_UE_g[UE_inst][0]->slot_tx = next_slot;
if (next_slot > 1)
PHY_vars_UE_g[UE_inst][0]->frame_tx = frame % MAX_FRAME_NUMBER;
else
PHY_vars_UE_g[UE_inst][0]->frame_tx = (frame + 1) % MAX_FRAME_NUMBER;
#ifdef OPENAIR2
//Application
update_otg_UE (UE_inst, oai_emulation.info.time_ms);
//Access layer
// PROTOCOL_CTXT_SET_BY_MODULE_ID(&ctxt, UE_inst, ENB_FLAG_NO, NOT_A_RNTI, frame, next_slot>>1, 0);
PROTOCOL_CTXT_SET_BY_MODULE_ID(&ctxt, UE_inst, 0, ENB_FLAG_NO, NOT_A_RNTI, frame % MAX_FRAME_NUMBER, next_slot);
pdcp_run (&ctxt);
#endif
for (CC_id = 0; CC_id < MAX_NUM_CCs;
CC_id++) {
phy_procedures_UE_lte (
PHY_vars_UE_g[UE_inst][CC_id],
0, abstraction_flag,
normal_txrx, no_relay,
NULL);
}
ue_data[UE_inst]->tx_power_dBm =
PHY_vars_UE_g[UE_inst][0]->tx_power_dBm;
}
} else {
if (abstraction_flag == 1) {
LOG_E(EMU,
"sync not supported in abstraction mode (UE%d,mode%d)\n",
UE_inst,
PHY_vars_UE_g[UE_inst][0]->UE_mode[0]);
exit (-1);
}
if ((frame > 0)
&& (last_slot
== (LTE_SLOTS_PER_FRAME
- 2))) {
initial_sync (PHY_vars_UE_g[UE_inst][0],
normal_txrx);
}
}
#ifdef PRINT_STATS
if(last_slot==2 && frame%10==0) {
if (UE_stats_th[UE_inst]) {
fprintf(UE_stats_th[UE_inst],"%d %d\n",frame%MAX_FRAME_NUMBER, PHY_vars_UE_g[UE_inst][0]->bitrate[0]/1000);
}
}
if (UE_stats[UE_inst]) {
len = dump_ue_stats (PHY_vars_UE_g[UE_inst][0], stats_buffer, 0, normal_txrx, 0);
rewind (UE_stats[UE_inst]);
fwrite (stats_buffer, 1, len, UE_stats[UE_inst]);
fflush(UE_stats[UE_inst]);
}
#endif
}
}
}
#if defined(Rel10) || defined(Rel14)
for (RN_id=oai_emulation.info.first_rn_local;
RN_id<oai_emulation.info.first_rn_local+oai_emulation.info.nb_rn_local;
RN_id++) {
// UE id and eNB id of the RN
UE_inst= oai_emulation.info.first_ue_local+oai_emulation.info.nb_ue_local + RN_id;// NB_UE_INST + RN_id
eNB_inst= oai_emulation.info.first_enb_local+oai_emulation.info.nb_enb_local + RN_id;// NB_eNB_INST + RN_id
// currently only works in FDD
if (oai_emulation.info.eMBMS_active_state == 4) {
r_type = multicast_relay;
//LOG_I(EMU,"Activating the multicast relaying\n");
} else {
LOG_E(EMU,"Not supported eMBMS option when relaying is enabled %d\n", r_type);
exit(-1);
}
PHY_vars_RN_g[RN_id]->frame = frame % MAX_FRAME_NUMBER;
if ( oai_emulation.info.frame_type == 0) {
// RN == UE
if (frame>0) {
if (PHY_vars_UE_g[UE_inst][0]->UE_mode[0] != NOT_SYNCHED) {
LOG_D(EMU,"[RN %d] PHY procedures UE %d for frame %d, slot %d (subframe TX %d, RX %d)\n",
RN_id, UE_inst, frame, slot, next_slot >> 1,last_slot>>1);
PHY_vars_UE_g[UE_inst][0]->frame_rx = frame % MAX_FRAME_NUMBER;
PHY_vars_UE_g[UE_inst][0]->slot_rx = last_slot;
PHY_vars_UE_g[UE_inst][0]->slot_tx = next_slot;
if (next_slot>1) PHY_vars_UE_g[UE_inst][0]->frame_tx = frame % MAX_FRAME_NUMBER;
else PHY_vars_UE_g[UE_inst][0]->frame_tx = (frame+1) % MAX_FRAME_NUMBER;
phy_procedures_UE_lte (PHY_vars_UE_g[UE_inst][0], 0, abstraction_flag,normal_txrx,
r_type, PHY_vars_RN_g[RN_id]);
} else if (last_slot == (LTE_SLOTS_PER_FRAME-2)) {
initial_sync(PHY_vars_UE_g[UE_inst][0],normal_txrx);
}
}
emu_transport (frame % MAX_FRAME_NUMBER, sf<<1, ((sf+4)%10)<<1, subframe_select(&PHY_vars_eNB_g[0][0]->frame_parms,sf),
oai_emulation.info.frame_type[0], ethernet_flag);
start_meas (&dl_chan_stats);
for (UE_inst = 0; UE_inst < NB_UE_INST; UE_inst++)
for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++) {
//#warning figure out what to do with UE frame_parms during initial_sync
do_DL_sig (r_re0,
r_im0,
r_re,
r_im,
s_re,
s_im,
eNB2UE,
enb_data,
ue_data,
PHY_vars_eNB_g[0][CC_id]->proc.proc_rxtx[sf&1].subframe_tx<<1,
abstraction_flag,
&PHY_vars_eNB_g[0][CC_id]->frame_parms,
UE_inst, CC_id);
do_DL_sig (r_re0,
r_im0,
r_re,
r_im,n
s_re,
s_im,
eNB2UE,
enb_data,
ue_data,
(PHY_vars_eNB_g[0][CC_id]->proc.proc_rxtx[sf&1].subframe_tx<<1)+1,
abstraction_flag,
&PHY_vars_eNB_g[0][CC_id]->frame_parms,
UE_inst, CC_id);
}
stop_meas (&dl_chan_stats);
start_meas (&ul_chan_stats);
for (CC_id = 0; CC_id < MAX_NUM_CCs; CC_id++) {
//#warning figure out what to do with UE frame_parms during initial_sync
do_UL_sig (r_re0, r_im0, r_re, r_im, s_re, s_im, UE2eNB,
enb_data, ue_data,
PHY_vars_UE_g[0][CC_id]->proc.proc_rxtx[sf&1].subframe_tx<<1,
abstraction_flag,
&PHY_vars_eNB_g[0][CC_id]->frame_parms,
frame % MAX_FRAME_NUMBER, CC_id);
do_UL_sig (r_re0, r_im0, r_re, r_im, s_re, s_im, UE2eNB,
enb_data, ue_data,
(PHY_vars_UE_g[0][CC_id]->proc.proc_rxtx[sf&1].subframe_tx<<1)+1,
abstraction_flag,
&PHY_vars_eNB_g[0][CC_id]->frame_parms,
frame % MAX_FRAME_NUMBER, CC_id);
}
stop_meas (&ul_chan_stats);
*/
if ((sf == 0) && ((frame % MAX_FRAME_NUMBER) == 0) && (abstraction_flag == 0)
&& (oai_emulation.info.n_frames == 1)) {
write_output ("dlchan0.m",
"dlch0",
&(PHY_vars_UE_g[0][0]->common_vars.common_vars_rx_data_per_thread[0].dl_ch_estimates[0][0][0]),
(6
* (PHY_vars_UE_g[0][0]->frame_parms.ofdm_symbol_size)),
1, 1);
write_output ("dlchan1.m",
"dlch1",
&(PHY_vars_UE_g[0][0]->common_vars.common_vars_rx_data_per_thread[0].dl_ch_estimates[1][0][0]),
(6
* (PHY_vars_UE_g[0][0]->frame_parms.ofdm_symbol_size)),
1, 1);
write_output ("dlchan2.m",
"dlch2",
&(PHY_vars_UE_g[0][0]->common_vars.common_vars_rx_data_per_thread[0].dl_ch_estimates[2][0][0]),
(6
* (PHY_vars_UE_g[0][0]->frame_parms.ofdm_symbol_size)),
1, 1);
write_output ("pbch_rxF_comp0.m",
"pbch_comp0",
PHY_vars_UE_g[0][0]->pbch_vars[0]->rxdataF_comp[0],
6 * 12 * 4, 1, 1);
write_output ("pbch_rxF_llr.m", "pbch_llr",
PHY_vars_UE_g[0][0]->pbch_vars[0]->llr,
(frame_parms[0]->Ncp == 0) ? 1920 : 1728, 1,
4);
}
stop_meas (&oaisim_stats_f);
} // SUBFRAME INNER PART
}
/*
if ((frame >= 10) && (frame <= 11) && (abstraction_flag == 0)
#ifdef PROC
&&(Channel_Flag==0)
#endif
) {
sprintf (fname, "UEtxsig%d.m", frame % MAX_FRAME_NUMBER);
sprintf (vname, "txs%d", frame % MAX_FRAME_NUMBER);
write_output (fname,
vname,
PHY_vars_UE_g[0][0]->common_vars.txdata[0],
PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti
* 10,
1, 1);
sprintf (fname, "eNBtxsig%d.m", frame % MAX_FRAME_NUMBER);
sprintf (vname, "txs%d", frame % MAX_FRAME_NUMBER);
write_output (fname,
vname,
PHY_vars_eNB_g[0][0]->common_vars.txdata[0][0],
PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti
* 10,
1, 1);
sprintf (fname, "eNBtxsigF%d.m", frame % MAX_FRAME_NUMBER);
sprintf (vname, "txsF%d", frame % MAX_FRAME_NUMBER);
write_output (fname,
vname,
PHY_vars_eNB_g[0][0]->common_vars.txdataF[0][0],
PHY_vars_eNB_g[0][0]->frame_parms.symbols_per_tti
* PHY_vars_eNB_g[0][0]->frame_parms.ofdm_symbol_size,
1, 1);
sprintf (fname, "UErxsig%d.m", frame % MAX_FRAME_NUMBER);
sprintf (vname, "rxs%d", frame % MAX_FRAME_NUMBER);
write_output (fname,
vname,
PHY_vars_UE_g[0][0]->common_vars.rxdata[0],
PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti
* 10,
1, 1);
sprintf (fname, "eNBrxsig%d.m", frame % MAX_FRAME_NUMBER);
sprintf (vname, "rxs%d", frame % MAX_FRAME_NUMBER);
write_output (fname,
vname,
PHY_vars_eNB_g[0][0]->common_vars.rxdata[0][0],
PHY_vars_UE_g[0][0]->frame_parms.samples_per_tti
* 10,
1, 1);
}
*/
//#ifdef XFORMS
if (xforms==1) {
eNB_inst = 0;
for (UE_inst = 0; UE_inst < NB_UE_INST; UE_inst++) {
for (CC_id=0;CC_id<MAX_NUM_CCs;CC_id++) {
phy_scope_UE(form_ue[CC_id][UE_inst],
PHY_vars_UE_g[UE_inst][CC_id],
eNB_inst,
UE_inst,
7);
}
phy_scope_eNB(form_enb[UE_inst],
PHY_vars_eNB_g[eNB_inst][0],
UE_inst);
}
}
//#endif
#ifdef SMBV
// Rohde&Schwarz SMBV100A vector signal generator
if ((frame % MAX_FRAME_NUMBER == config_frames[0]) || (frame % MAX_FRAME_NUMBER == config_frames[1]) || (frame % MAX_FRAME_NUMBER == config_frames[2]) || (frame % MAX_FRAME_NUMBER == config_frames[3])) {
smbv_frame_cnt++;
}
#endif
} // frame loop
stop_meas (&oaisim_stats);
oai_shutdown ();
#ifdef PRINT_STATS
for (UE_inst=0; UE_inst<NB_UE_INST; UE_inst++) {
if (UE_stats[UE_inst])
fclose (UE_stats[UE_inst]);
if(UE_stats_th[UE_inst])
fclose (UE_stats_th[UE_inst]);
}
for (eNB_inst=0; eNB_inst<NB_eNB_INST; eNB_inst++) {
if (eNB_stats[eNB_inst])
fclose (eNB_stats[eNB_inst]);
}
if (eNB_avg_thr)
fclose (eNB_avg_thr);
if (eNB_l2_stats)
fclose (eNB_l2_stats);
#endif
#if defined(ENABLE_ITTI)
itti_terminate_tasks(TASK_L2L1);
#endif
return NULL;
}
#if defined(FLEXRAN_AGENT_SB_IF)
/*
* The following two functions are meant to restart *the lte-softmodem* and are
* here to make oaisim compile. A restart command from the controller will be
* ignored in oaisim.
*/
int stop_L1L2(int enb_id)
{
LOG_W(FLEXRAN_AGENT, "stop_L1L2() not supported in oaisim\n");
return 0;
}
int restart_L1L2(int enb_id)
{
LOG_W(FLEXRAN_AGENT, "restart_L1L2() not supported in oaisim\n");
return 0;
}
#endif
#if T_TRACER
int T_wait = 1; /* by default we wait for the tracer */
int T_port = 2021; /* default port to listen to to wait for the tracer */
int T_dont_fork = 0; /* default is to fork, see 'T_init' to understand */
#endif
static void print_current_directory(void)
{
char dir[8192]; /* arbitrary size (should be big enough) */
if (getcwd(dir, 8192) == NULL)
printf("ERROR getting working directory\n");
else
printf("working directory: %s\n", dir);
}
/*------------------------------------------------------------------------------*/
int
main (int argc, char **argv)
{
clock_t t;
print_current_directory();
start_background_system();
#ifdef SMBV
// Rohde&Schwarz SMBV100A vector signal generator
strcpy(smbv_ip,DEFAULT_SMBV_IP);
#endif
#ifdef PROC
int node_id;
int port,Process_Flag=0,wgt,Channel_Flag=0,temp;
#endif
//default parameters
oai_emulation.info.n_frames = MAX_FRAME_NUMBER; //1024; //10;
oai_emulation.info.n_frames_flag = 0; //fixme
snr_dB = 30;
//Default values if not changed by the user in get_simulation_options();
pdcp_period = 1;
omg_period = 1;
//Clean ip rule table
for(int i =0; i<NUMBER_OF_UE_MAX; i++){
char command_line[100];
sprintf(command_line, "while ip rule del table %d; do true; done",i+201);
/* we don't care about return value from system(), but let's the
* compiler be silent, so let's do "if (XX);"
*/
if (system(command_line)) /* nothing */;
}
// start thread for log gen
log_thread_init ();
init_oai_emulation (); // to initialize everything !!!
// get command-line options
get_simulation_options (argc, argv); //Command-line options
#if T_TRACER
T_init(T_port, T_wait, T_dont_fork);
#endif
// Initialize VCD LOG module
VCD_SIGNAL_DUMPER_INIT (oai_emulation.info.vcd_file);
#if !defined(ENABLE_ITTI)
pthread_t tid;
int err;
sigset_t sigblock;
sigemptyset (&sigblock);
sigaddset (&sigblock, SIGHUP);
sigaddset (&sigblock, SIGINT);
sigaddset (&sigblock, SIGTERM);
sigaddset (&sigblock, SIGQUIT);
//sigaddset(&sigblock, SIGKILL);
if ((err = pthread_sigmask (SIG_BLOCK, &sigblock, NULL)) != 0) {
printf ("SIG_BLOCK error\n");
return -1;
}
if (pthread_create (&tid, NULL, sigh, NULL)) {
printf ("Pthread for tracing Signals is not created!\n");
return -1;
} else {
printf ("Pthread for tracing Signals is created!\n");
}
#endif
// configure oaisim with OCG
oaisim_config (); // config OMG and OCG, OPT, OTG, OLG
if (ue_connection_test == 1) {
snr_direction = -snr_step;
snr_dB = 20;
sinr_dB = -20;
}
pthread_cond_init(&sync_cond,NULL);
pthread_mutex_init(&sync_mutex, NULL);
pthread_mutex_init(&subframe_mutex, NULL);
#ifdef OPENAIR2
init_omv ();
#endif
//Before this call, NB_UE_INST and NB_eNB_INST are not set correctly
check_and_adjust_params ();
set_seed = oai_emulation.emulation_config.seed.value;
init_otg_pdcp_buffer ();
init_seed (set_seed);
init_openair1 ();
init_openair2 ();
void init_openair0(void);
init_openair0();
init_ocm ();
#if defined(ENABLE_ITTI)
// Note: Cannot handle both RRU/RAU and eNB at the same time, if the first "eNB" is an RRU/RAU, no NAS
if (oai_emulation.info.node_function[0] < NGFI_RAU_IF4p5) {
if (create_tasks(oai_emulation.info.nb_enb_local,
oai_emulation.info.nb_ue_local) < 0)
exit(-1); // need a softer mode
}
else {
if (create_tasks(0,
oai_emulation.info.nb_ue_local) < 0)
exit(-1); // need a softer mode
}
#endif
// wait for all threads to startup
sleep(3);
printf("Sending sync to all threads\n");
pthread_mutex_lock(&sync_mutex);
sync_var=0;
pthread_cond_broadcast(&sync_cond);
pthread_mutex_unlock(&sync_mutex);
#ifdef SMBV
// Rohde&Schwarz SMBV100A vector signal generator
smbv_init_config(smbv_fname, smbv_nframes);
smbv_write_config_from_frame_parms(smbv_fname, &PHY_vars_eNB_g[0][0]->frame_parms);
#endif
/* #if defined (FLEXRAN_AGENT_SB_IF)
flexran_agent_start();
#endif */
// add events to future event list: Currently not used
//oai_emulation.info.oeh_enabled = 1;
if (oai_emulation.info.oeh_enabled == 1)
schedule_events ();
// oai performance profiler is enabled
if (oai_emulation.info.opp_enabled == 1)
reset_opp_meas_oaisim ();
cpuf=get_cpu_freq_GHz();
init_time ();
init_slot_isr ();
t = clock ();
LOG_N(EMU,
">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU initialization done <<<<<<<<<<<<<<<<<<<<<<<<<<\n\n");
#ifndef PACKAGE_VERSION
# define PACKAGE_VERSION "UNKNOWN-EXPERIMENTAL"
#endif
LOG_I(EMU, "Version: %s\n", PACKAGE_VERSION);
#if defined(ENABLE_ITTI)
// Handle signals until all tasks are terminated
itti_wait_tasks_end();
#else
if (oai_emulation.info.nb_enb_local > 0) {
eNB_app_task (NULL); // do nothing for the moment
}
l2l1_task (NULL);
#endif
t = clock () - t;
LOG_I(EMU, "Duration of the simulation: %f seconds\n",
((float) t) / CLOCKS_PER_SEC);
LOG_N(EMU,
">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU Ending <<<<<<<<<<<<<<<<<<<<<<<<<<\n\n");
raise (SIGINT);
// oai_shutdown ();
return (0);
}
void
reset_opp_meas_oaisim (void)
{
uint8_t eNB_id = 0, UE_id = 0;
reset_meas (&oaisim_stats);
reset_meas (&oaisim_stats_f); // frame
// init time stats here (including channel)
reset_meas (&dl_chan_stats);
reset_meas (&ul_chan_stats);
for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {
reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[0]);
reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[1]);
reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[0]);
reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[1]);
reset_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_tx);
reset_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_demod_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->rx_dft_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_channel_estimation_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_freq_offset_estimation_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[0]);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[1]);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_rate_unmatching_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_turbo_decoding_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_deinterleaving_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_llr_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_unscrambling_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_init_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_alpha_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_beta_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_gamma_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_ext_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl1_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl2_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->tx_prach);
reset_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_mod_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_encoding_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_modulation_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_segmentation_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_rate_matching_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_turbo_encoding_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_interleaving_stats);
reset_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_multiplexing_stats);
/*
* L2 functions
*/
// UE MAC
reset_meas (&UE_mac_inst[UE_id].ue_scheduler); // total
reset_meas (&UE_mac_inst[UE_id].tx_ulsch_sdu); // inlcude rlc_data_req + mac header gen
reset_meas (&UE_mac_inst[UE_id].rx_dlsch_sdu); // include mac_rrc_data_ind or mac_rlc_status_ind+mac_rlc_data_ind and mac header parser
reset_meas (&UE_mac_inst[UE_id].ue_query_mch);
reset_meas (&UE_mac_inst[UE_id].rx_mch_sdu); // include rld_data_ind+ parse mch header
reset_meas (&UE_mac_inst[UE_id].rx_si); // include rlc_data_ind + mac header parser
reset_meas (&UE_pdcp_stats[UE_id].pdcp_run);
reset_meas (&UE_pdcp_stats[UE_id].data_req);
reset_meas (&UE_pdcp_stats[UE_id].data_ind);
reset_meas (&UE_pdcp_stats[UE_id].apply_security);
reset_meas (&UE_pdcp_stats[UE_id].validate_security);
reset_meas (&UE_pdcp_stats[UE_id].pdcp_ip);
reset_meas (&UE_pdcp_stats[UE_id].ip_pdcp);
}
for (eNB_id = 0; eNB_id < NB_eNB_INST; eNB_id++) {
for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {
reset_meas (&eNB2UE[eNB_id][UE_id][0]->random_channel);
reset_meas (&eNB2UE[eNB_id][UE_id][0]->interp_time);
reset_meas (&eNB2UE[eNB_id][UE_id][0]->interp_freq);
reset_meas (&eNB2UE[eNB_id][UE_id][0]->convolution);
reset_meas (&UE2eNB[UE_id][eNB_id][0]->random_channel);
reset_meas (&UE2eNB[UE_id][eNB_id][0]->interp_time);
reset_meas (&UE2eNB[UE_id][eNB_id][0]->interp_freq);
reset_meas (&UE2eNB[UE_id][eNB_id][0]->convolution);
}
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc_rx);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc_tx);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->rx_prach);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ofdm_mod_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_encoding_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_modulation_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_scrambling_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_rate_matching_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_turbo_encoding_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_interleaving_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ofdm_demod_stats);
//reset_meas(&PHY_vars_eNB_g[eNB_id]->rx_dft_stats);
//reset_meas(&PHY_vars_eNB_g[eNB_id]->ulsch_channel_estimation_stats);
//reset_meas(&PHY_vars_eNB_g[eNB_id]->ulsch_freq_offset_estimation_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_decoding_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_demodulation_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_rate_unmatching_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_turbo_decoding_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_deinterleaving_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_demultiplexing_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_llr_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_init_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_alpha_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_beta_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_gamma_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_ext_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_intl1_stats);
reset_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_intl2_stats);
#ifdef LOCALIZATION
reset_meas(&PHY_vars_eNB_g[eNB_id][0]->localization_stats);
#endif
/*
* L2 functions
*/
// eNB MAC
reset_meas (&eNB_mac_inst[eNB_id].eNB_scheduler); // total
reset_meas (&eNB_mac_inst[eNB_id].schedule_si); // only schedule + tx
reset_meas (&eNB_mac_inst[eNB_id].schedule_ra); // only ra
reset_meas (&eNB_mac_inst[eNB_id].schedule_ulsch); // onlu ulsch
reset_meas (&eNB_mac_inst[eNB_id].fill_DLSCH_dci); // only dci
reset_meas (&eNB_mac_inst[eNB_id].schedule_dlsch_preprocessor); // include rlc_data_req + MAC header gen
reset_meas (&eNB_mac_inst[eNB_id].schedule_dlsch); // include rlc_data_req + MAC header gen + pre-processor
reset_meas (&eNB_mac_inst[eNB_id].schedule_mch); // only embms
reset_meas (&eNB_mac_inst[eNB_id].rx_ulsch_sdu); // include rlc_data_ind + mac header parser
reset_meas (&eNB_pdcp_stats[eNB_id].pdcp_run);
reset_meas (&eNB_pdcp_stats[eNB_id].data_req);
reset_meas (&eNB_pdcp_stats[eNB_id].data_ind);
reset_meas (&eNB_pdcp_stats[eNB_id].apply_security);
reset_meas (&eNB_pdcp_stats[eNB_id].validate_security);
reset_meas (&eNB_pdcp_stats[eNB_id].pdcp_ip);
reset_meas (&eNB_pdcp_stats[eNB_id].ip_pdcp);
}
}
void
print_opp_meas_oaisim (void)
{
uint8_t eNB_id = 0, UE_id = 0;
print_meas (&oaisim_stats, "[OAI][total_exec_time]", &oaisim_stats,
&oaisim_stats);
print_meas (&oaisim_stats_f, "[OAI][SF_exec_time]", &oaisim_stats,
&oaisim_stats_f);
print_meas (&dl_chan_stats, "[DL][chan_stats]", &oaisim_stats,
&oaisim_stats_f);
print_meas (&ul_chan_stats, "[UL][chan_stats]", &oaisim_stats,
&oaisim_stats_f);
for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {
for (eNB_id = 0; eNB_id < NB_eNB_INST; eNB_id++) {
print_meas (&eNB2UE[eNB_id][UE_id][0]->random_channel,
"[DL][random_channel]", &oaisim_stats, &oaisim_stats_f);
print_meas (&eNB2UE[eNB_id][UE_id][0]->interp_time,
"[DL][interp_time]", &oaisim_stats, &oaisim_stats_f);
print_meas (&eNB2UE[eNB_id][UE_id][0]->interp_freq,
"[DL][interp_freq]", &oaisim_stats, &oaisim_stats_f);
print_meas (&eNB2UE[eNB_id][UE_id][0]->convolution,
"[DL][convolution]", &oaisim_stats, &oaisim_stats_f);
print_meas (&UE2eNB[UE_id][eNB_id][0]->random_channel,
"[UL][random_channel]", &oaisim_stats, &oaisim_stats_f);
print_meas (&UE2eNB[UE_id][eNB_id][0]->interp_time,
"[UL][interp_time]", &oaisim_stats, &oaisim_stats_f);
print_meas (&UE2eNB[UE_id][eNB_id][0]->interp_freq,
"[UL][interp_freq]", &oaisim_stats, &oaisim_stats_f);
print_meas (&UE2eNB[UE_id][eNB_id][0]->convolution,
"[UL][convolution]", &oaisim_stats, &oaisim_stats_f);
}
}
for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {
print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[0], "[UE][total_phy_proc[0]]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc[1], "[UE][total_phy_proc[1]]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[0],
"[UE][total_phy_proc_rx[0]]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_rx[1],
"[UE][total_phy_proc_rx[1]]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_demod_stats,
"[UE][ofdm_demod]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->rx_dft_stats, "[UE][rx_dft]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_channel_estimation_stats,
"[UE][channel_est]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_freq_offset_estimation_stats,
"[UE][freq_offset]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_llr_stats, "[UE][llr]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_unscrambling_stats,
"[UE][unscrambling]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[0],
"[UE][decoding[0]]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_decoding_stats[1],
"[UE][decoding[1]]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_rate_unmatching_stats,
"[UE][rate_unmatching]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_deinterleaving_stats,
"[UE][deinterleaving]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_turbo_decoding_stats,
"[UE][turbo_decoding]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_init_stats,
"[UE][ |_tc_init]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_alpha_stats,
"[UE][ |_tc_alpha]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_beta_stats,
"[UE][ |_tc_beta]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_gamma_stats,
"[UE][ |_tc_gamma]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_ext_stats,
"[UE][ |_tc_ext]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl1_stats,
"[UE][ |_tc_intl1]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->dlsch_tc_intl2_stats,
"[UE][ |_tc_intl2]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->phy_proc_tx,
"[UE][total_phy_proc_tx]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->ofdm_mod_stats, "[UE][ofdm_mod]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_modulation_stats,
"[UE][modulation]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_encoding_stats,
"[UE][encoding]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_segmentation_stats,
"[UE][segmentation]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_rate_matching_stats,
"[UE][rate_matching]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_turbo_encoding_stats,
"[UE][turbo_encoding]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_interleaving_stats,
"[UE][interleaving]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_UE_g[UE_id][0]->ulsch_multiplexing_stats,
"[UE][multiplexing]", &oaisim_stats, &oaisim_stats_f);
}
for (eNB_id = 0; eNB_id < NB_eNB_INST; eNB_id++) {
print_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc,
"[eNB][total_phy_proc]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc_tx,
"[eNB][total_phy_proc_tx]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ofdm_mod_stats,
"[eNB][ofdm_mod]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_modulation_stats,
"[eNB][modulation]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_scrambling_stats,
"[eNB][scrambling]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_encoding_stats,
"[eNB][encoding]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_interleaving_stats,
"[eNB][|_interleaving]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_rate_matching_stats,
"[eNB][|_rate_matching]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->dlsch_turbo_encoding_stats,
"[eNB][|_turbo_encoding]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->phy_proc_rx,
"[eNB][total_phy_proc_rx]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ofdm_demod_stats,
"[eNB][ofdm_demod]", &oaisim_stats, &oaisim_stats_f);
//print_meas(&PHY_vars_eNB_g[eNB_id][0]->ulsch_channel_estimation_stats,"[eNB][channel_est]");
//print_meas(&PHY_vars_eNB_g[eNB_id][0]->ulsch_freq_offset_estimation_stats,"[eNB][freq_offset]");
//print_meas(&PHY_vars_eNB_g[eNB_id][0]->rx_dft_stats,"[eNB][rx_dft]");
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_demodulation_stats,
"[eNB][demodulation]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_decoding_stats,
"[eNB][decoding]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_deinterleaving_stats,
"[eNB][|_deinterleaving]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_demultiplexing_stats,
"[eNB][|_demultiplexing]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_rate_unmatching_stats,
"[eNB][|_rate_unmatching]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_turbo_decoding_stats,
"[eNB][|_turbo_decoding]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_init_stats,
"[eNB][ |_tc_init]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_alpha_stats,
"[eNB][ |_tc_alpha]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_beta_stats,
"[eNB][ |_tc_beta]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_gamma_stats,
"[eNB][ |_tc_gamma]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_ext_stats,
"[eNB][ |_tc_ext]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_intl1_stats,
"[eNB][ |_tc_intl1]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->ulsch_tc_intl2_stats,
"[eNB][ |_tc_intl2]", &oaisim_stats, &oaisim_stats_f);
print_meas (&PHY_vars_eNB_g[eNB_id][0]->rx_prach, "[eNB][rx_prach]",
&oaisim_stats, &oaisim_stats_f);
#ifdef LOCALIZATION
print_meas(&PHY_vars_eNB_g[eNB_id][0]->localization_stats, "[eNB][LOCALIZATION]",&oaisim_stats,&oaisim_stats_f);
#endif
}
for (UE_id = 0; UE_id < NB_UE_INST; UE_id++) {
print_meas (&UE_mac_inst[UE_id].ue_scheduler, "[UE][mac_scheduler]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&UE_mac_inst[UE_id].tx_ulsch_sdu, "[UE][tx_ulsch_sdu]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&UE_mac_inst[UE_id].rx_dlsch_sdu, "[UE][rx_dlsch_sdu]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&UE_mac_inst[UE_id].ue_query_mch, "[UE][query_MCH]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&UE_mac_inst[UE_id].rx_mch_sdu, "[UE][rx_mch_sdu]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&UE_mac_inst[UE_id].rx_si, "[UE][rx_si]", &oaisim_stats,
&oaisim_stats_f);
print_meas (&UE_pdcp_stats[UE_id].pdcp_run, "[UE][total_pdcp_run]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&UE_pdcp_stats[UE_id].data_req, "[UE][DL][pdcp_data_req]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&UE_pdcp_stats[UE_id].data_ind, "[UE][UL][pdcp_data_ind]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&UE_pdcp_stats[UE_id].apply_security,
"[UE][DL][apply_security]", &oaisim_stats, &oaisim_stats_f);
print_meas (&UE_pdcp_stats[UE_id].validate_security,
"[UE][UL][validate_security]", &oaisim_stats,
&oaisim_stats_f);
print_meas (&UE_pdcp_stats[UE_id].ip_pdcp, "[UE][DL][ip_pdcp]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&UE_pdcp_stats[UE_id].pdcp_ip, "[UE][UL][pdcp_ip]",
&oaisim_stats, &oaisim_stats_f);
}
for (eNB_id = 0; eNB_id < NB_eNB_INST; eNB_id++) {
print_meas (&eNB_mac_inst[eNB_id].eNB_scheduler, "[eNB][mac_scheduler]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_mac_inst[eNB_id].schedule_si, "[eNB][DL][SI]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_mac_inst[eNB_id].schedule_ra, "[eNB][DL][RA]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_mac_inst[eNB_id].fill_DLSCH_dci,
"[eNB][DL/UL][fill_DCI]", &oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_mac_inst[eNB_id].schedule_dlsch_preprocessor,
"[eNB][DL][preprocessor]", &oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_mac_inst[eNB_id].schedule_dlsch,
"[eNB][DL][schedule_tx_dlsch]", &oaisim_stats,
&oaisim_stats_f);
print_meas (&eNB_mac_inst[eNB_id].schedule_mch, "[eNB][DL][mch]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_mac_inst[eNB_id].schedule_ulsch, "[eNB][UL][ULSCH]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_mac_inst[eNB_id].rx_ulsch_sdu,
"[eNB][UL][rx_ulsch_sdu]", &oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_pdcp_stats[eNB_id].pdcp_run, "[eNB][pdcp_run]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_pdcp_stats[eNB_id].data_req,
"[eNB][DL][pdcp_data_req]", &oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_pdcp_stats[eNB_id].data_ind,
"[eNB][UL][pdcp_data_ind]", &oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_pdcp_stats[eNB_id].apply_security,
"[eNB][DL][apply_security]", &oaisim_stats,
&oaisim_stats_f);
print_meas (&eNB_pdcp_stats[eNB_id].validate_security,
"[eNB][UL][validate_security]", &oaisim_stats,
&oaisim_stats_f);
print_meas (&eNB_pdcp_stats[eNB_id].ip_pdcp, "[eNB][DL][ip_pdcp]",
&oaisim_stats, &oaisim_stats_f);
print_meas (&eNB_pdcp_stats[eNB_id].pdcp_ip, "[eNB][UL][pdcp_ip]",
&oaisim_stats, &oaisim_stats_f);
}
}
#if !defined(ENABLE_ITTI)
static void *
sigh (void *arg)
{
int signum;
sigset_t sigcatch;
sigemptyset (&sigcatch);
sigaddset (&sigcatch, SIGHUP);
sigaddset (&sigcatch, SIGINT);
sigaddset (&sigcatch, SIGTERM);
sigaddset (&sigcatch, SIGQUIT);
for (;;) {
sigwait (&sigcatch, &signum);
//sigwait(&sigblock, &signum);
switch (signum) {
case SIGHUP:
case SIGINT:
case SIGTERM:
case SIGQUIT:
fprintf (stderr, "received signal %d \n", signum);
// no need for mutx: when ITTI not used, this variable is only accessed by this function
l2l1_state = L2L1_TERMINATED;
break;
default:
fprintf (stderr, "Unexpected signal %d \n", signum);
exit (-1);
break;
}
}
pthread_exit (NULL);
}
#endif /* !defined(ENABLE_ITTI) */
void
oai_shutdown (void)
{
static int done = 0;
if (done)
return;
free (otg_pdcp_buffer);
otg_pdcp_buffer = 0;
#ifdef SMBV
// Rohde&Schwarz SMBV100A vector signal generator
if (config_smbv) {
smbv_send_config (smbv_fname,smbv_ip);
}
#endif
//Perform KPI measurements
if (oai_emulation.info.otg_enabled == 1){
LOG_N(EMU,"calling OTG kpi gen .... \n");
kpi_gen ();
}
if (oai_emulation.info.opp_enabled == 1)
print_opp_meas_oaisim ();
// relase all rx state
if (ethernet_flag == 1) {
emu_transport_release ();
}
#ifdef PROC
if (abstraction_flag == 0 && Channel_Flag==0 && Process_Flag==0)
#else
if (abstraction_flag == 0)
#endif
{
/*
#ifdef IFFT_FPGA
free(txdataF2[0]);
free(txdataF2[1]);
free(txdataF2);
free(txdata[0]);
free(txdata[1]);
free(txdata);
#endif
*/
/*
for (int i = 0; i < 2; i++) {
free (s_re[i]);
free (s_im[i]);
free (r_re[i]);
free (r_im[i]);
}
free (s_re);
free (s_im);
free (r_re);
free (r_im);
s_re = 0;
s_im = 0;
r_re = 0;
r_im = 0;*/
lte_sync_time_free ();
}
// added for PHY abstraction
if (oai_emulation.info.ocm_enabled == 1) {
for (eNB_inst = 0; eNB_inst < NUMBER_OF_eNB_MAX; eNB_inst++) {
free (enb_data[eNB_inst]);
enb_data[eNB_inst] = 0;
}
for (UE_inst = 0; UE_inst < NUMBER_OF_UE_MAX; UE_inst++) {
free (ue_data[UE_inst]);
ue_data[UE_inst] = 0;
}
} //End of PHY abstraction changes
#ifdef OPENAIR2
mac_top_cleanup ();
#endif
// stop OMG
stop_mobility_generator (omg_param_list); //omg_param_list.mobility_type
#ifdef OPENAIR2
if (oai_emulation.info.omv_enabled == 1)
omv_end (pfd[1], omv_data);
#endif
if ((oai_emulation.info.ocm_enabled == 1) && (ethernet_flag == 0)
&& (ShaF != NULL)) {
destroyMat (ShaF, map1, map2);
ShaF = 0;
}
if (opt_enabled == 1)
terminate_opt ();
if (oai_emulation.info.cli_enabled)
cli_server_cleanup ();
for (int i = 0; i < NUMBER_OF_eNB_MAX + NUMBER_OF_UE_MAX; i++)
if (oai_emulation.info.oai_ifup[i] == 1) {
char interfaceName[8];
snprintf (interfaceName, sizeof(interfaceName), "oai%d", i);
bringInterfaceUp (interfaceName, 0);
}
log_thread_finalize ();
logClean ();
VCD_SIGNAL_DUMPER_CLOSE ();
done = 1; // prevent next invokation of this function
LOG_N(EMU,
">>>>>>>>>>>>>>>>>>>>>>>>>>> OAIEMU shutdown <<<<<<<<<<<<<<<<<<<<<<<<<<\n\n");
}
eNB_MAC_INST*
get_eNB_mac_inst (module_id_t module_idP)
{
return (&eNB_mac_inst[module_idP]);
}
OAI_Emulation*
get_OAI_emulation ()
{
return &oai_emulation;
}
| {
"alphanum_fraction": 0.6499870104,
"avg_line_length": 34.9752650177,
"ext": "c",
"hexsha": "5cb2289b37d91727fbb2e162d7bd740d08d74fbf",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-01-05T03:52:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-14T16:06:26.000Z",
"max_forks_repo_head_hexsha": "acd54a34e1840e4c7f295b134f8f2117b1899e83",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "kashyab12/flexran-agent",
"max_forks_repo_path": "targets/SIMU/USER/oaisim.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "acd54a34e1840e4c7f295b134f8f2117b1899e83",
"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": "kashyab12/flexran-agent",
"max_issues_repo_path": "targets/SIMU/USER/oaisim.c",
"max_line_length": 471,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "acd54a34e1840e4c7f295b134f8f2117b1899e83",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "kashyab12/flexran-agent",
"max_stars_repo_path": "targets/SIMU/USER/oaisim.c",
"max_stars_repo_stars_event_max_datetime": "2019-11-05T16:22:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-05T16:22:05.000Z",
"num_tokens": 21290,
"size": 69286
} |
/* specfunc/airy.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_trig.h>
#include <gsl/gsl_sf_airy.h>
#include "error.h"
#include "check.h"
#include "chebyshev.h"
#include "cheb_eval_mode.c"
/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/
/* chebyshev expansions for Airy modulus and phase
based on SLATEC r9aimp()
Series for AM21 on the interval -1.25000D-01 to 0.
with weighted error 2.89E-17
log weighted error 16.54
significant figures required 14.15
decimal places required 17.34
Series for ATH1 on the interval -1.25000D-01 to 0.
with weighted error 2.53E-17
log weighted error 16.60
significant figures required 15.15
decimal places required 17.38
Series for AM22 on the interval -1.00000D+00 to -1.25000D-01
with weighted error 2.99E-17
log weighted error 16.52
significant figures required 14.57
decimal places required 17.28
Series for ATH2 on the interval -1.00000D+00 to -1.25000D-01
with weighted error 2.57E-17
log weighted error 16.59
significant figures required 15.07
decimal places required 17.34
*/
static double am21_data[37] = {
0.0065809191761485,
0.0023675984685722,
0.0001324741670371,
0.0000157600904043,
0.0000027529702663,
0.0000006102679017,
0.0000001595088468,
0.0000000471033947,
0.0000000152933871,
0.0000000053590722,
0.0000000020000910,
0.0000000007872292,
0.0000000003243103,
0.0000000001390106,
0.0000000000617011,
0.0000000000282491,
0.0000000000132979,
0.0000000000064188,
0.0000000000031697,
0.0000000000015981,
0.0000000000008213,
0.0000000000004296,
0.0000000000002284,
0.0000000000001232,
0.0000000000000675,
0.0000000000000374,
0.0000000000000210,
0.0000000000000119,
0.0000000000000068,
0.0000000000000039,
0.0000000000000023,
0.0000000000000013,
0.0000000000000008,
0.0000000000000005,
0.0000000000000003,
0.0000000000000001,
0.0000000000000001
};
static cheb_series am21_cs = {
am21_data,
36,
-1, 1,
20
};
static double ath1_data[36] = {
-0.07125837815669365,
-0.00590471979831451,
-0.00012114544069499,
-0.00000988608542270,
-0.00000138084097352,
-0.00000026142640172,
-0.00000006050432589,
-0.00000001618436223,
-0.00000000483464911,
-0.00000000157655272,
-0.00000000055231518,
-0.00000000020545441,
-0.00000000008043412,
-0.00000000003291252,
-0.00000000001399875,
-0.00000000000616151,
-0.00000000000279614,
-0.00000000000130428,
-0.00000000000062373,
-0.00000000000030512,
-0.00000000000015239,
-0.00000000000007758,
-0.00000000000004020,
-0.00000000000002117,
-0.00000000000001132,
-0.00000000000000614,
-0.00000000000000337,
-0.00000000000000188,
-0.00000000000000105,
-0.00000000000000060,
-0.00000000000000034,
-0.00000000000000020,
-0.00000000000000011,
-0.00000000000000007,
-0.00000000000000004,
-0.00000000000000002
};
static cheb_series ath1_cs = {
ath1_data,
35,
-1, 1,
15
};
static double am22_data[33] = {
-0.01562844480625341,
0.00778336445239681,
0.00086705777047718,
0.00015696627315611,
0.00003563962571432,
0.00000924598335425,
0.00000262110161850,
0.00000079188221651,
0.00000025104152792,
0.00000008265223206,
0.00000002805711662,
0.00000000976821090,
0.00000000347407923,
0.00000000125828132,
0.00000000046298826,
0.00000000017272825,
0.00000000006523192,
0.00000000002490471,
0.00000000000960156,
0.00000000000373448,
0.00000000000146417,
0.00000000000057826,
0.00000000000022991,
0.00000000000009197,
0.00000000000003700,
0.00000000000001496,
0.00000000000000608,
0.00000000000000248,
0.00000000000000101,
0.00000000000000041,
0.00000000000000017,
0.00000000000000007,
0.00000000000000002
};
static cheb_series am22_cs = {
am22_data,
32,
-1, 1,
15
};
static double ath2_data[32] = {
0.00440527345871877,
-0.03042919452318455,
-0.00138565328377179,
-0.00018044439089549,
-0.00003380847108327,
-0.00000767818353522,
-0.00000196783944371,
-0.00000054837271158,
-0.00000016254615505,
-0.00000005053049981,
-0.00000001631580701,
-0.00000000543420411,
-0.00000000185739855,
-0.00000000064895120,
-0.00000000023105948,
-0.00000000008363282,
-0.00000000003071196,
-0.00000000001142367,
-0.00000000000429811,
-0.00000000000163389,
-0.00000000000062693,
-0.00000000000024260,
-0.00000000000009461,
-0.00000000000003716,
-0.00000000000001469,
-0.00000000000000584,
-0.00000000000000233,
-0.00000000000000093,
-0.00000000000000037,
-0.00000000000000015,
-0.00000000000000006,
-0.00000000000000002
};
static cheb_series ath2_cs = {
ath2_data,
31,
-1, 1,
16
};
/* Airy modulus and phase for x < -1 */
static
int
airy_mod_phase(const double x, gsl_mode_t mode, gsl_sf_result * mod, gsl_sf_result * phase)
{
gsl_sf_result result_m;
gsl_sf_result result_p;
double m, p;
double sqx;
if(x < -2.0) {
double z = 16.0/(x*x*x) + 1.0;
cheb_eval_mode_e(&am21_cs, z, mode, &result_m);
cheb_eval_mode_e(&ath1_cs, z, mode, &result_p);
}
else if(x <= -1.0) {
double z = (16.0/(x*x*x) + 9.0)/7.0;
cheb_eval_mode_e(&am22_cs, z, mode, &result_m);
cheb_eval_mode_e(&ath2_cs, z, mode, &result_p);
}
else {
mod->val = 0.0;
mod->err = 0.0;
phase->val = 0.0;
phase->err = 0.0;
GSL_ERROR ("x is greater than 1.0", GSL_EDOM);
}
m = 0.3125 + result_m.val;
p = -0.625 + result_p.val;
sqx = sqrt(-x);
mod->val = sqrt(m/sqx);
mod->err = fabs(mod->val) * (GSL_DBL_EPSILON + fabs(result_m.err/result_m.val));
phase->val = M_PI_4 - x*sqx * p;
phase->err = fabs(phase->val) * (GSL_DBL_EPSILON + fabs(result_p.err/result_p.val));
return GSL_SUCCESS;
}
/* Chebyshev series for Ai(x) with x in [-1,1]
based on SLATEC ai(x)
series for aif on the interval -1.00000d+00 to 1.00000d+00
with weighted error 1.09e-19
log weighted error 18.96
significant figures required 17.76
decimal places required 19.44
series for aig on the interval -1.00000d+00 to 1.00000d+00
with weighted error 1.51e-17
log weighted error 16.82
significant figures required 15.19
decimal places required 17.27
*/
static double ai_data_f[9] = {
-0.03797135849666999750,
0.05919188853726363857,
0.00098629280577279975,
0.00000684884381907656,
0.00000002594202596219,
0.00000000006176612774,
0.00000000000010092454,
0.00000000000000012014,
0.00000000000000000010
};
static cheb_series aif_cs = {
ai_data_f,
8,
-1, 1,
8
};
static double ai_data_g[8] = {
0.01815236558116127,
0.02157256316601076,
0.00025678356987483,
0.00000142652141197,
0.00000000457211492,
0.00000000000952517,
0.00000000000001392,
0.00000000000000001
};
static cheb_series aig_cs = {
ai_data_g,
7,
-1, 1,
7
};
/* Chebvyshev series for Bi(x) with x in [-1,1]
based on SLATEC bi(x)
series for bif on the interval -1.00000d+00 to 1.00000d+00
with weighted error 1.88e-19
log weighted error 18.72
significant figures required 17.74
decimal places required 19.20
series for big on the interval -1.00000d+00 to 1.00000d+00
with weighted error 2.61e-17
log weighted error 16.58
significant figures required 15.17
decimal places required 17.03
*/
static double data_bif[9] = {
-0.01673021647198664948,
0.10252335834249445610,
0.00170830925073815165,
0.00001186254546774468,
0.00000004493290701779,
0.00000000010698207143,
0.00000000000017480643,
0.00000000000000020810,
0.00000000000000000018
};
static cheb_series bif_cs = {
data_bif,
8,
-1, 1,
8
};
static double data_big[8] = {
0.02246622324857452,
0.03736477545301955,
0.00044476218957212,
0.00000247080756363,
0.00000000791913533,
0.00000000001649807,
0.00000000000002411,
0.00000000000000002
};
static cheb_series big_cs = {
data_big,
7,
-1, 1,
7
};
/* Chebyshev series for Bi(x) with x in [1,8]
based on SLATEC bi(x)
*/
static double data_bif2[10] = {
0.0998457269381604100,
0.4786249778630055380,
0.0251552119604330118,
0.0005820693885232645,
0.0000074997659644377,
0.0000000613460287034,
0.0000000003462753885,
0.0000000000014288910,
0.0000000000000044962,
0.0000000000000000111
};
static cheb_series bif2_cs = {
data_bif2,
9,
-1, 1,
9
};
static double data_big2[10] = {
0.033305662145514340,
0.161309215123197068,
0.0063190073096134286,
0.0001187904568162517,
0.0000013045345886200,
0.0000000093741259955,
0.0000000000474580188,
0.0000000000001783107,
0.0000000000000005167,
0.0000000000000000011
};
static cheb_series big2_cs = {
data_big2,
9,
-1, 1,
9
};
/* chebyshev for Ai(x) asymptotic factor
based on SLATEC aie()
Series for AIP on the interval 0. to 1.00000D+00
with weighted error 5.10E-17
log weighted error 16.29
significant figures required 14.41
decimal places required 17.06
[GJ] Sun Apr 19 18:14:31 EDT 1998
There was something wrong with these coefficients. I was getting
errors after 3 or 4 digits. So I recomputed this table. Now I get
double precision agreement with Mathematica. But it does not seem
possible that the small differences here would account for the
original discrepancy. There must have been something wrong with my
original usage...
*/
static double data_aip[36] = {
-0.0187519297793867540198,
-0.0091443848250055004725,
0.0009010457337825074652,
-0.0001394184127221491507,
0.0000273815815785209370,
-0.0000062750421119959424,
0.0000016064844184831521,
-0.0000004476392158510354,
0.0000001334635874651668,
-0.0000000420735334263215,
0.0000000139021990246364,
-0.0000000047831848068048,
0.0000000017047897907465,
-0.0000000006268389576018,
0.0000000002369824276612,
-0.0000000000918641139267,
0.0000000000364278543037,
-0.0000000000147475551725,
0.0000000000060851006556,
-0.0000000000025552772234,
0.0000000000010906187250,
-0.0000000000004725870319,
0.0000000000002076969064,
-0.0000000000000924976214,
0.0000000000000417096723,
-0.0000000000000190299093,
0.0000000000000087790676,
-0.0000000000000040927557,
0.0000000000000019271068,
-0.0000000000000009160199,
0.0000000000000004393567,
-0.0000000000000002125503,
0.0000000000000001036735,
-0.0000000000000000509642,
0.0000000000000000252377,
-0.0000000000000000125793
/*
-.0187519297793868
-.0091443848250055,
.0009010457337825,
-.0001394184127221,
.0000273815815785,
-.0000062750421119,
.0000016064844184,
-.0000004476392158,
.0000001334635874,
-.0000000420735334,
.0000000139021990,
-.0000000047831848,
.0000000017047897,
-.0000000006268389,
.0000000002369824,
-.0000000000918641,
.0000000000364278,
-.0000000000147475,
.0000000000060851,
-.0000000000025552,
.0000000000010906,
-.0000000000004725,
.0000000000002076,
-.0000000000000924,
.0000000000000417,
-.0000000000000190,
.0000000000000087,
-.0000000000000040,
.0000000000000019,
-.0000000000000009,
.0000000000000004,
-.0000000000000002,
.0000000000000001,
-.0000000000000000
*/
};
static cheb_series aip_cs = {
data_aip,
35,
-1, 1,
17
};
/* chebyshev for Bi(x) asymptotic factor
based on SLATEC bie()
Series for BIP on the interval 1.25000D-01 to 3.53553D-01
with weighted error 1.91E-17
log weighted error 16.72
significant figures required 15.35
decimal places required 17.41
Series for BIP2 on the interval 0. to 1.25000D-01
with weighted error 1.05E-18
log weighted error 17.98
significant figures required 16.74
decimal places required 18.71
*/
static double data_bip[24] = {
-0.08322047477943447,
0.01146118927371174,
0.00042896440718911,
-0.00014906639379950,
-0.00001307659726787,
0.00000632759839610,
-0.00000042226696982,
-0.00000019147186298,
0.00000006453106284,
-0.00000000784485467,
-0.00000000096077216,
0.00000000070004713,
-0.00000000017731789,
0.00000000002272089,
0.00000000000165404,
-0.00000000000185171,
0.00000000000059576,
-0.00000000000012194,
0.00000000000001334,
0.00000000000000172,
-0.00000000000000145,
0.00000000000000049,
-0.00000000000000011,
0.00000000000000001
};
static cheb_series bip_cs = {
data_bip,
23,
-1, 1,
14
};
static double data_bip2[29] = {
-0.113596737585988679,
0.0041381473947881595,
0.0001353470622119332,
0.0000104273166530153,
0.0000013474954767849,
0.0000001696537405438,
-0.0000000100965008656,
-0.0000000167291194937,
-0.0000000045815364485,
0.0000000003736681366,
0.0000000005766930320,
0.0000000000621812650,
-0.0000000000632941202,
-0.0000000000149150479,
0.0000000000078896213,
0.0000000000024960513,
-0.0000000000012130075,
-0.0000000000003740493,
0.0000000000002237727,
0.0000000000000474902,
-0.0000000000000452616,
-0.0000000000000030172,
0.0000000000000091058,
-0.0000000000000009814,
-0.0000000000000016429,
0.0000000000000005533,
0.0000000000000002175,
-0.0000000000000001737,
-0.0000000000000000010
};
static cheb_series bip2_cs = {
data_bip2,
28,
-1, 1,
10
};
/* assumes x >= 1.0 */
inline static int
airy_aie(const double x, gsl_mode_t mode, gsl_sf_result * result)
{
double sqx = sqrt(x);
double z = 2.0/(x*sqx) - 1.0;
double y = sqrt(sqx);
gsl_sf_result result_c;
cheb_eval_mode_e(&aip_cs, z, mode, &result_c);
result->val = (0.28125 + result_c.val)/y;
result->err = result_c.err/y + GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
/* assumes x >= 2.0 */
static int airy_bie(const double x, gsl_mode_t mode, gsl_sf_result * result)
{
const double ATR = 8.7506905708484345;
const double BTR = -2.0938363213560543;
if(x < 4.0) {
double sqx = sqrt(x);
double z = ATR/(x*sqx) + BTR;
double y = sqrt(sqx);
gsl_sf_result result_c;
cheb_eval_mode_e(&bip_cs, z, mode, &result_c);
result->val = (0.625 + result_c.val)/y;
result->err = result_c.err/y + GSL_DBL_EPSILON * fabs(result->val);
}
else {
double sqx = sqrt(x);
double z = 16.0/(x*sqx) - 1.0;
double y = sqrt(sqx);
gsl_sf_result result_c;
cheb_eval_mode_e(&bip2_cs, z, mode, &result_c);
result->val = (0.625 + result_c.val)/y;
result->err = result_c.err/y + GSL_DBL_EPSILON * fabs(result->val);
}
return GSL_SUCCESS;
}
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int
gsl_sf_airy_Ai_e(const double x, const gsl_mode_t mode, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x < -1.0) {
gsl_sf_result mod;
gsl_sf_result theta;
gsl_sf_result cos_result;
int stat_mp = airy_mod_phase(x, mode, &mod, &theta);
int stat_cos = gsl_sf_cos_err_e(theta.val, theta.err, &cos_result);
result->val = mod.val * cos_result.val;
result->err = fabs(mod.val * cos_result.err) + fabs(cos_result.val * mod.err);
result->err += GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_mp, stat_cos);
}
else if(x <= 1.0) {
const double z = x*x*x;
gsl_sf_result result_c0;
gsl_sf_result result_c1;
cheb_eval_mode_e(&aif_cs, z, mode, &result_c0);
cheb_eval_mode_e(&aig_cs, z, mode, &result_c1);
result->val = 0.375 + (result_c0.val - x*(0.25 + result_c1.val));
result->err = result_c0.err + fabs(x*result_c1.err);
result->err += GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
double x32 = x * sqrt(x);
double s = exp(-2.0*x32/3.0);
gsl_sf_result result_aie;
int stat_aie = airy_aie(x, mode, &result_aie);
result->val = result_aie.val * s;
result->err = result_aie.err * s + result->val * x32 * GSL_DBL_EPSILON;
result->err += GSL_DBL_EPSILON * fabs(result->val);
CHECK_UNDERFLOW(result);
return stat_aie;
}
}
int
gsl_sf_airy_Ai_scaled_e(const double x, gsl_mode_t mode, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x < -1.0) {
gsl_sf_result mod;
gsl_sf_result theta;
gsl_sf_result cos_result;
int stat_mp = airy_mod_phase(x, mode, &mod, &theta);
int stat_cos = gsl_sf_cos_err_e(theta.val, theta.err, &cos_result);
result->val = mod.val * cos_result.val;
result->err = fabs(mod.val * cos_result.err) + fabs(cos_result.val * mod.err);
result->err += GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_mp, stat_cos);
}
else if(x <= 1.0) {
const double z = x*x*x;
gsl_sf_result result_c0;
gsl_sf_result result_c1;
cheb_eval_mode_e(&aif_cs, z, mode, &result_c0);
cheb_eval_mode_e(&aig_cs, z, mode, &result_c1);
result->val = 0.375 + (result_c0.val - x*(0.25 + result_c1.val));
result->err = result_c0.err + fabs(x*result_c1.err);
result->err += GSL_DBL_EPSILON * fabs(result->val);
if(x > 0.0) {
const double scale = exp(2.0/3.0 * sqrt(z));
result->val *= scale;
result->err *= scale;
}
return GSL_SUCCESS;
}
else {
return airy_aie(x, mode, result);
}
}
int gsl_sf_airy_Bi_e(const double x, gsl_mode_t mode, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x < -1.0) {
gsl_sf_result mod;
gsl_sf_result theta;
gsl_sf_result sin_result;
int stat_mp = airy_mod_phase(x, mode, &mod, &theta);
int stat_sin = gsl_sf_sin_err_e(theta.val, theta.err, &sin_result);
result->val = mod.val * sin_result.val;
result->err = fabs(mod.val * sin_result.err) + fabs(sin_result.val * mod.err);
result->err += GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_mp, stat_sin);
}
else if(x < 1.0) {
const double z = x*x*x;
gsl_sf_result result_c0;
gsl_sf_result result_c1;
cheb_eval_mode_e(&bif_cs, z, mode, &result_c0);
cheb_eval_mode_e(&big_cs, z, mode, &result_c1);
result->val = 0.625 + result_c0.val + x*(0.4375 + result_c1.val);
result->err = result_c0.err + fabs(x * result_c1.err);
result->err += GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else if(x <= 2.0) {
const double z = (2.0*x*x*x - 9.0)/7.0;
gsl_sf_result result_c0;
gsl_sf_result result_c1;
cheb_eval_mode_e(&bif2_cs, z, mode, &result_c0);
cheb_eval_mode_e(&big2_cs, z, mode, &result_c1);
result->val = 1.125 + result_c0.val + x*(0.625 + result_c1.val);
result->err = result_c0.err + fabs(x * result_c1.err);
result->err += GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
const double y = 2.0*x*sqrt(x)/3.0;
const double s = exp(y);
if(y > GSL_LOG_DBL_MAX - 1.0) {
OVERFLOW_ERROR(result);
}
else {
gsl_sf_result result_bie;
int stat_bie = airy_bie(x, mode, &result_bie);
result->val = result_bie.val * s;
result->err = result_bie.err * s + fabs(1.5*y * (GSL_DBL_EPSILON * result->val));
result->err += GSL_DBL_EPSILON * fabs(result->val);
return stat_bie;
}
}
}
int
gsl_sf_airy_Bi_scaled_e(const double x, gsl_mode_t mode, gsl_sf_result * result)
{
/* CHECK_POINTER(result) */
if(x < -1.0) {
gsl_sf_result mod;
gsl_sf_result theta;
gsl_sf_result sin_result;
int stat_mp = airy_mod_phase(x, mode, &mod, &theta);
int stat_sin = gsl_sf_sin_err_e(theta.val, theta.err, &sin_result);
result->val = mod.val * sin_result.val;
result->err = fabs(mod.val * sin_result.err) + fabs(sin_result.val * mod.err);
result->err += GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_mp, stat_sin);
}
else if(x < 1.0) {
const double z = x*x*x;
gsl_sf_result result_c0;
gsl_sf_result result_c1;
cheb_eval_mode_e(&bif_cs, z, mode, &result_c0);
cheb_eval_mode_e(&big_cs, z, mode, &result_c1);
result->val = 0.625 + result_c0.val + x*(0.4375 + result_c1.val);
result->err = result_c0.err + fabs(x * result_c1.err);
result->err += GSL_DBL_EPSILON * fabs(result->val);
if(x > 0.0) {
const double scale = exp(-2.0/3.0 * sqrt(z));
result->val *= scale;
result->err *= scale;
}
return GSL_SUCCESS;
}
else if(x <= 2.0) {
const double x3 = x*x*x;
const double z = (2.0*x3 - 9.0)/7.0;
const double s = exp(-2.0/3.0 * sqrt(x3));
gsl_sf_result result_c0;
gsl_sf_result result_c1;
cheb_eval_mode_e(&bif2_cs, z, mode, &result_c0);
cheb_eval_mode_e(&big2_cs, z, mode, &result_c1);
result->val = s * (1.125 + result_c0.val + x*(0.625 + result_c1.val));
result->err = s * (result_c0.err + fabs(x * result_c1.err));
result->err += GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
else {
return airy_bie(x, mode, result);
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_airy_Ai(const double x, gsl_mode_t mode)
{
EVAL_RESULT(gsl_sf_airy_Ai_e(x, mode, &result));
}
double gsl_sf_airy_Ai_scaled(const double x, gsl_mode_t mode)
{
EVAL_RESULT(gsl_sf_airy_Ai_scaled_e(x, mode, &result));
}
double gsl_sf_airy_Bi(const double x, gsl_mode_t mode)
{
EVAL_RESULT(gsl_sf_airy_Bi_e(x, mode, &result));
}
double gsl_sf_airy_Bi_scaled(const double x, gsl_mode_t mode)
{
EVAL_RESULT(gsl_sf_airy_Bi_scaled_e(x, mode, &result));
}
| {
"alphanum_fraction": 0.6553979444,
"avg_line_length": 27.0643678161,
"ext": "c",
"hexsha": "18b78107aa8de1608d93e7e45126db2c29774a0e",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/airy.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/airy.c",
"max_line_length": 91,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/specfunc/airy.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-25T17:31:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-11T02:53:04.000Z",
"num_tokens": 8392,
"size": 23546
} |
/* vectorviews.c */
// 8.4.13 Example programs for matrices of gsl-ref.pdf
// GNU GSL GNU Scientific Library reference book
// pp. 99,100
/*
Compiling advice:
gcc vectorviews.c -lgsl -lgslcblas -lm
*/
#include <math.h>
#include <stdio.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
int main (void)
{
size_t i,j;
gsl_matrix *m = gsl_matrix_alloc(10,10);
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
gsl_matrix_set (m, i, j, sin(i) + cos(j));
for (j = 0; j < 10; j++)
{
gsl_vector_view column = gsl_matrix_column(m, j);
double d;
d = gsl_blas_dnrm2 (&column.vector);
printf("matrix column %zu, norm = %g\n", j, d);
}
gsl_matrix_free(m);
return 0;
}
| {
"alphanum_fraction": 0.5940054496,
"avg_line_length": 17.0697674419,
"ext": "c",
"hexsha": "dd1799286a2cda22913587d917d3c966cc886f19",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2021-03-01T07:13:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-01-24T19:18:42.000Z",
"max_forks_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ernestyalumni/CompPhys",
"max_forks_repo_path": "gslExamples/vectorviews.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855",
"max_issues_repo_issues_event_max_datetime": "2019-01-29T22:37:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-01-16T22:34:47.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ernestyalumni/CompPhys",
"max_issues_repo_path": "gslExamples/vectorviews.c",
"max_line_length": 55,
"max_stars_count": 70,
"max_stars_repo_head_hexsha": "1f5d7559146a14a21182653b77fd35e6d6829855",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ernestyalumni/CompPhys",
"max_stars_repo_path": "gslExamples/vectorviews.c",
"max_stars_repo_stars_event_max_datetime": "2021-12-24T16:00:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-07-24T04:09:27.000Z",
"num_tokens": 243,
"size": 734
} |
#include <math.h>
#include <gsl/gsl_math.h>
#include "egsl_macros.h"
int main() {
egsl_push();
/* Creates a vector from a double array */
double p[2] = {1,2};
val vp = egsl_vFa(2,p);
/* Creates a matrix from a double array */
double md[4] = {
1, 2,
0, -1
};
val m = egsl_vFda(2,2,md);
/* Creates a rotation matrix */
val R = rot(M_PI/2);
/* Multiplies the three together */
val vrot = m3(R, m, vp);
/* Displays the results */
egsl_print("R", R);
egsl_print("vp", vp);
egsl_print("vrot", vrot);
/* Create a semidifinite matrix (symmetric part of R) */
val A = sc(0.5, sum(m, tr(m)) );
/* Displays spectrum */
egsl_print("A",A);
egsl_print_spectrum("A",A);
egsl_pop();
return 0;
}
| {
"alphanum_fraction": 0.5782493369,
"avg_line_length": 17.9523809524,
"ext": "c",
"hexsha": "8439a5d60558ebccf8f5444d8b251bd0a4c9b567",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alecone/ROS_project",
"max_forks_repo_path": "src/csm/sm/lib/egsl/egsl_test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "alecone/ROS_project",
"max_issues_repo_path": "src/csm/sm/lib/egsl/egsl_test.c",
"max_line_length": 58,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alecone/ROS_project",
"max_stars_repo_path": "src/csm/sm/lib/egsl/egsl_test.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 277,
"size": 754
} |
#ifndef OPENMC_MATERIAL_H
#define OPENMC_MATERIAL_H
#include <memory> // for unique_ptr
#include <string>
#include <unordered_map>
#include <vector>
#include <gsl/gsl>
#include <hdf5.h>
#include "pugixml.hpp"
#include "xtensor/xtensor.hpp"
#include "openmc/constants.h"
#include "openmc/bremsstrahlung.h"
#include "openmc/particle.h"
namespace openmc {
//==============================================================================
// Global variables
//==============================================================================
class Material;
namespace model {
extern std::unordered_map<int32_t, int32_t> material_map;
extern std::vector<std::unique_ptr<Material>> materials;
} // namespace model
//==============================================================================
//! A substance with constituent nuclides and thermal scattering data
//==============================================================================
class Material
{
public:
//----------------------------------------------------------------------------
// Types
struct ThermalTable {
int index_table; //!< Index of table in data::thermal_scatt
int index_nuclide; //!< Index in nuclide_
double fraction; //!< How often to use table
};
//----------------------------------------------------------------------------
// Constructors, destructors, factory functions
Material() {};
explicit Material(pugi::xml_node material_node);
~Material();
//----------------------------------------------------------------------------
// Methods
void calculate_xs(Particle& p) const;
//! Assign thermal scattering tables to specific nuclides within the material
//! so the code knows when to apply bound thermal scattering data
void init_thermal();
//! Set up mapping between global nuclides vector and indices in nuclide_
void init_nuclide_index();
//! Finalize the material, assigning tables, normalize density, etc.
void finalize();
//! Write material data to HDF5
void to_hdf5(hid_t group) const;
//! Add nuclide to the material
//
//! \param[in] nuclide Name of the nuclide
//! \param[in] density Density of the nuclide in [atom/b-cm]
void add_nuclide(const std::string& nuclide, double density);
//! Set atom densities for the material
//
//! \param[in] name Name of each nuclide
//! \param[in] density Density of each nuclide in [atom/b-cm]
void set_densities(const std::vector<std::string>& name,
const std::vector<double>& density);
//----------------------------------------------------------------------------
// Accessors
//! Get density in [atom/b-cm]
//! \return Density in [atom/b-cm]
double density() const { return density_; }
//! Get density in [g/cm^3]
//! \return Density in [g/cm^3]
double density_gpcc() const { return density_gpcc_; }
//! Get name
//! \return Material name
const std::string& name() const { return name_; }
//! Set name
void set_name(const std::string& name) { name_ = name; }
//! Set total density of the material
//
//! \param[in] density Density value
//! \param[in] units Units of density
void set_density(double density, gsl::cstring_span units);
//! Get nuclides in material
//! \return Indices into the global nuclides vector
gsl::span<const int> nuclides() const { return {nuclide_.data(), nuclide_.size()}; }
//! Get densities of each nuclide in material
//! \return Densities in [atom/b-cm]
gsl::span<const double> densities() const { return {atom_density_.data(), atom_density_.size()}; }
//! Get ID of material
//! \return ID of material
int32_t id() const { return id_; }
//! Assign a unique ID to the material
//! \param[in] Unique ID to assign. A value of -1 indicates that an ID
//! should be automatically assigned.
void set_id(int32_t id);
//! Get whether material is fissionable
//! \return Whether material is fissionable
bool fissionable() const { return fissionable_; }
//! Get volume of material
//! \return Volume in [cm^3]
double volume() const;
//! Get temperature of material
//! \return Temperature in [K]
double temperature() const;
//----------------------------------------------------------------------------
// Data
int32_t id_ {C_NONE}; //!< Unique ID
std::string name_; //!< Name of material
std::vector<int> nuclide_; //!< Indices in nuclides vector
std::vector<int> element_; //!< Indices in elements vector
xt::xtensor<double, 1> atom_density_; //!< Nuclide atom density in [atom/b-cm]
double density_; //!< Total atom density in [atom/b-cm]
double density_gpcc_; //!< Total atom density in [g/cm^3]
double volume_ {-1.0}; //!< Volume in [cm^3]
bool fissionable_ {false}; //!< Does this material contain fissionable nuclides
bool depletable_ {false}; //!< Is the material depletable?
std::vector<bool> p0_; //!< Indicate which nuclides are to be treated with iso-in-lab scattering
// To improve performance of tallying, we store an array (direct address
// table) that indicates for each nuclide in data::nuclides the index of the
// corresponding nuclide in the nuclide_ vector. If it is not present in the
// material, the entry is set to -1.
std::vector<int> mat_nuclide_index_;
// Thermal scattering tables
std::vector<ThermalTable> thermal_tables_;
std::unique_ptr<Bremsstrahlung> ttb_;
private:
//----------------------------------------------------------------------------
// Private methods
//! Calculate the collision stopping power
void collision_stopping_power(double* s_col, bool positron);
//! Initialize bremsstrahlung data
void init_bremsstrahlung();
//! Normalize density
void normalize_density();
void calculate_neutron_xs(Particle& p) const;
void calculate_photon_xs(Particle& p) const;
//----------------------------------------------------------------------------
// Private data members
gsl::index index_;
//! \brief Default temperature for cells containing this material.
//!
//! A negative value indicates no default temperature was specified.
double temperature_ {-1};
};
//==============================================================================
// Non-member functions
//==============================================================================
//! Calculate Sternheimer adjustment factor
double sternheimer_adjustment(const std::vector<double>& f, const
std::vector<double>& e_b_sq, double e_p_sq, double n_conduction, double
log_I, double tol, int max_iter);
//! Calculate density effect correction
double density_effect(const std::vector<double>& f, const std::vector<double>&
e_b_sq, double e_p_sq, double n_conduction, double rho, double E, double tol,
int max_iter);
//! Read material data from materials.xml
void read_materials_xml();
void free_memory_material();
} // namespace openmc
#endif // OPENMC_MATERIAL_H
| {
"alphanum_fraction": 0.6013043478,
"avg_line_length": 32.8571428571,
"ext": "h",
"hexsha": "9adb9ff97df39079e7058830f872e60be184f75f",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-03-22T20:54:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-31T21:03:25.000Z",
"max_forks_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Hit-Weixg/openmc",
"max_forks_repo_path": "include/openmc/material.h",
"max_issues_count": 9,
"max_issues_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b",
"max_issues_repo_issues_event_max_datetime": "2021-04-01T15:23:23.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-03-14T12:18:06.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Hit-Weixg/openmc",
"max_issues_repo_path": "include/openmc/material.h",
"max_line_length": 100,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "c5f66a3af5c1a57087e330f7b870e89a82267e4b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Hit-Weixg/openmc",
"max_stars_repo_path": "include/openmc/material.h",
"max_stars_repo_stars_event_max_datetime": "2019-05-05T10:18:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-01-10T13:14:35.000Z",
"num_tokens": 1542,
"size": 6900
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#pragma once
#include <type_traits>
#include <algorithm>
#include <limits>
#include <iostream>
#include <cstring>
#include "seal/memorymanager.h"
#include "seal/serialization.h"
#include "seal/util/pointer.h"
#include "seal/util/defines.h"
#include "seal/util/common.h"
#ifdef SEAL_USE_MSGSL_SPAN
#include <gsl/span>
#endif
namespace seal
{
class Ciphertext;
// Forward-declaring the deflate_size_bound function
namespace util::ztools
{
SEAL_NODISCARD std::size_t deflate_size_bound(std::size_t in_size) noexcept;
}
/**
A resizable container for storing an array of arithmetic data types or
SEAL_BYTE types (e.g., std::byte). The allocations are done from a memory
pool. The IntArray class is mainly intended for internal use and provides
the underlying data structure for Plaintext and Ciphertext classes.
@par Size and Capacity
IntArray allows the user to pre-allocate memory (capacity) for the array
in cases where the array is known to be resized in the future and memory
moves are to be avoided at the time of resizing. The size of the IntArray
can never exceed its capacity. The capacity and size can be changed using
the reserve and resize functions, respectively.
@par Thread Safety
In general, reading from IntArray is thread-safe as long as no other thread
is concurrently mutating it.
*/
template<typename T_,
typename = std::enable_if_t<std::is_arithmetic<T_>::value ||
std::is_same<typename std::decay<T_>::type, SEAL_BYTE>::value>>
class IntArray
{
friend class Ciphertext;
public:
using T = typename std::decay<T_>::type;
/**
Creates a new IntArray. No memory is allocated by this constructor.
@param[in] pool The MemoryPoolHandle pointing to a valid memory pool
@throws std::invalid_argument if pool is uninitialized
*/
IntArray(MemoryPoolHandle pool = MemoryManager::GetPool()) :
pool_(std::move(pool))
{
if (!pool_)
{
throw std::invalid_argument("pool is uninitialized");
}
}
/**
Creates a new IntArray with given size.
@param[in] size The size of the array
@param[in] pool The MemoryPoolHandle pointing to a valid memory pool
@throws std::invalid_argument if pool is uninitialized
*/
explicit IntArray(std::size_t size,
MemoryPoolHandle pool = MemoryManager::GetPool()) :
pool_(std::move(pool))
{
if (!pool_)
{
throw std::invalid_argument("pool is uninitialized");
}
// Reserve memory, resize, and set to zero
resize(size);
}
/**
Creates a new IntArray with given capacity and size.
@param[in] capacity The capacity of the array
@param[in] size The size of the array
@param[in] pool The MemoryPoolHandle pointing to a valid memory pool
@throws std::invalid_argument if capacity is less than size
@throws std::invalid_argument if pool is uninitialized
*/
explicit IntArray(std::size_t capacity, std::size_t size,
MemoryPoolHandle pool = MemoryManager::GetPool()) :
pool_(std::move(pool))
{
if (!pool_)
{
throw std::invalid_argument("pool is uninitialized");
}
if (capacity < size)
{
throw std::invalid_argument("capacity cannot be smaller than size");
}
// Reserve memory, resize, and set to zero
reserve(capacity);
resize(size);
}
/**
Creates a new IntArray with given size wrapping a given pointer. This
constructor allocates no memory. If the IntArray goes out of scope, the
Pointer object given here is destroyed. On resizing the IntArray to larger
size, the data will be copied over to a new allocation from the memory pool
pointer to by the given MemoryPoolHandle and the Pointer object given here
will subsequently be destroyed. Unlike the other constructors, this one
exposes the option of not automatically zero-filling the allocated memory.
@param[in] ptr An initial Pointer object to wrap
@param[in] capacity The capacity of the array
@param[in] size The size of the array
@param[in] fill_zero If true, fills ptr with zeros
@param[in] pool The MemoryPoolHandle pointing to a valid memory pool
@throws std::invalid_argument if ptr is null and capacity is positive
@throws std::invalid_argument if capacity is less than size
@throws std::invalid_argument if pool is uninitialized
*/
explicit IntArray(util::Pointer<T> &&ptr,
std::size_t capacity, std::size_t size, bool fill_zero,
MemoryPoolHandle pool = MemoryManager::GetPool()) :
pool_(std::move(pool)),
capacity_(capacity)
{
if (!ptr && capacity)
{
throw std::invalid_argument("ptr cannot be null");
}
if (!pool_)
{
throw std::invalid_argument("pool is uninitialized");
}
if (capacity < size)
{
throw std::invalid_argument("capacity cannot be smaller than size");
}
// Grab the given Pointer
data_ = std::move(ptr);
// Resize, and optionally set to zero
resize(size, fill_zero);
}
/**
Creates a new IntArray with given size wrapping a given pointer. This
constructor allocates no memory. If the IntArray goes out of scope, the
Pointer object given here is destroyed. On resizing the IntArray to larger
size, the data will be copied over to a new allocation from the memory pool
pointer to by the given MemoryPoolHandle and the Pointer object given here
will subsequently be destroyed. Unlike the other constructors, this one
exposes the option of not automatically zero-filling the allocated memory.
@param[in] ptr An initial Pointer object to wrap
@param[in] size The size of the array
@param[in] fill_zero If true, fills ptr with zeros
@param[in] pool The MemoryPoolHandle pointing to a valid memory pool
@throws std::invalid_argument if ptr is null and size is positive
@throws std::invalid_argument if pool is uninitialized
*/
explicit IntArray(util::Pointer<T> &&ptr, std::size_t size, bool fill_zero,
MemoryPoolHandle pool = MemoryManager::GetPool()) :
IntArray(std::move(ptr), size, size, fill_zero, std::move(pool))
{
}
/**
Constructs a new IntArray by copying a given one.
@param[in] copy The IntArray to copy from
*/
IntArray(const IntArray<T> ©) :
pool_(MemoryManager::GetPool()),
capacity_(copy.size_),
size_(copy.size_),
data_(util::allocate<T>(copy.size_, pool_))
{
// Copy over value
std::copy_n(copy.cbegin(), copy.size_, begin());
}
/**
Constructs a new IntArray by moving a given one.
@param[in] source The IntArray to move from
*/
IntArray(IntArray<T> &&source) noexcept :
pool_(std::move(source.pool_)),
capacity_(source.capacity_),
size_(source.size_),
data_(std::move(source.data_))
{
}
/**
Destroys the IntArray.
*/
~IntArray()
{
release();
}
/**
Returns a pointer to the beginning of the array data.
*/
SEAL_NODISCARD inline T *begin() noexcept
{
return data_.get();
}
/**
Returns a constant pointer to the beginning of the array data.
*/
SEAL_NODISCARD inline const T *cbegin() const noexcept
{
return data_.get();
}
/**
Returns a pointer to the end of the array data.
*/
SEAL_NODISCARD inline T *end() noexcept
{
return size_ ? begin() + size_ : begin();
}
/**
Returns a constant pointer to the end of the array data.
*/
SEAL_NODISCARD inline const T *cend() const noexcept
{
return size_ ? cbegin() + size_ : cbegin();
}
#ifdef SEAL_USE_MSGSL_SPAN
/**
Returns a span pointing to the beginning of the IntArray.
*/
SEAL_NODISCARD inline gsl::span<T> span()
{
return gsl::span<T>(
begin(), static_cast<std::ptrdiff_t>(size_));
}
/**
Returns a span pointing to the beginning of the IntArray.
*/
SEAL_NODISCARD inline gsl::span<const T> span() const
{
return gsl::span<const T>(
cbegin(), static_cast<std::ptrdiff_t>(size_));
}
#endif
/**
Returns a constant reference to the array element at a given index.
This function performs bounds checking and will throw an error if
the index is out of range.
@param[in] index The index of the array element
@throws std::out_of_range if index is out of range
*/
SEAL_NODISCARD inline const T &at(std::size_t index) const
{
if (index >= size_)
{
throw std::out_of_range("index must be within [0, size)");
}
return data_[index];
}
/**
Returns a reference to the array element at a given index. This
function performs bounds checking and will throw an error if the
index is out of range.
@param[in] index The index of the array element
@throws std::out_of_range if index is out of range
*/
SEAL_NODISCARD inline T &at(std::size_t index)
{
if (index >= size_)
{
throw std::out_of_range("index must be within [0, size)");
}
return data_[index];
}
/**
Returns a constant reference to the array element at a given index.
This function does not perform bounds checking.
@param[in] index The index of the array element
*/
SEAL_NODISCARD inline const T &operator [](std::size_t index) const
{
return data_[index];
}
/**
Returns a reference to the array element at a given index. This
function does not perform bounds checking.
@param[in] index The index of the array element
*/
SEAL_NODISCARD inline T &operator [](std::size_t index)
{
return data_[index];
}
/**
Returns whether the array has size zero.
*/
SEAL_NODISCARD inline bool empty() const noexcept
{
return (size_ == 0);
}
/**
Returns the largest possible array size.
*/
SEAL_NODISCARD inline std::size_t max_size() const noexcept
{
return std::numeric_limits<std::size_t>::max();
}
/**
Returns the size of the array.
*/
SEAL_NODISCARD inline std::size_t size() const noexcept
{
return size_;
}
/**
Returns the capacity of the array.
*/
SEAL_NODISCARD inline std::size_t capacity() const noexcept
{
return capacity_;
}
/**
Returns the currently used MemoryPoolHandle.
*/
SEAL_NODISCARD inline MemoryPoolHandle pool() const noexcept
{
return pool_;
}
/**
Releases any allocated memory to the memory pool and sets the size
and capacity of the array to zero.
*/
inline void release() noexcept
{
capacity_ = 0;
size_ = 0;
data_.release();
}
/**
Sets the size of the array to zero. The capacity is not changed.
*/
inline void clear() noexcept
{
size_ = 0;
}
/**
Allocates enough memory for storing a given number of elements without
changing the size of the array. If the given capacity is smaller than
the current size, the size is automatically set to equal the new capacity.
@param[in] capacity The capacity of the array
*/
inline void reserve(std::size_t capacity)
{
std::size_t copy_size = std::min(capacity, size_);
// Create new allocation and copy over value
auto new_data(util::allocate<T>(capacity, pool_));
std::copy_n(cbegin(), copy_size, new_data.get());
std::swap(data_, new_data);
// Set the coeff_count and capacity
capacity_ = capacity;
size_ = copy_size;
}
/**
Reallocates the array so that its capacity exactly matches its size.
*/
inline void shrink_to_fit()
{
reserve(size_);
}
/**
Resizes the array to given size. When resizing to larger size the data
in the array remains unchanged and any new space is initialized to zero
if fill_zero is set to true; when resizing to smaller size the last
elements of the array are dropped. If the capacity is not already large
enough to hold the new size, the array is also reallocated.
@param[in] size The size of the array
@param[in] fill_zero If true, fills expanded space with zeros
*/
inline void resize(std::size_t size, bool fill_zero = true)
{
if (size <= capacity_)
{
// Are we changing size to bigger within current capacity?
// If so, need to set top terms to zero
if (size > size_ && fill_zero)
{
std::fill(end(), begin() + size, T(0));
}
// Set the size
size_ = size;
return;
}
// At this point we know for sure that size_ <= capacity_ < size so need
// to reallocate to bigger
auto new_data(util::allocate<T>(size, pool_));
std::copy_n(cbegin(), size_, new_data.get());
if (fill_zero)
{
std::fill(new_data.get() + size_, new_data.get() + size, T(0));
}
std::swap(data_, new_data);
// Set the coeff_count and capacity
capacity_ = size;
size_ = size;
}
/**
Copies a given IntArray to the current one.
@param[in] assign The IntArray to copy from
*/
inline IntArray<T> &operator =(const IntArray<T> &assign)
{
// Check for self-assignment
if (this == &assign)
{
return *this;
}
// First resize to correct size
resize(assign.size_);
// Size is guaranteed to be OK now so copy over
std::copy_n(assign.cbegin(), assign.size_, begin());
return *this;
}
/**
Moves a given IntArray to the current one.
@param[in] assign The IntArray to move from
*/
IntArray<T> &operator =(IntArray<T> &&assign) noexcept
{
capacity_ = assign.capacity_;
size_ = assign.size_;
data_ = std::move(assign.data_);
pool_ = std::move(assign.pool_);
return *this;
}
/**
Returns an upper bound on the size of the IntArray, as if it was written
to an output stream.
@param[in] compr_mode The compression mode
@throws std::invalid_argument if the compression mode is not supported
@throws std::logic_error if the size does not fit in the return type
*/
SEAL_NODISCARD inline std::streamoff save_size(
compr_mode_type compr_mode) const
{
std::size_t members_size = Serialization::ComprSizeEstimate(
util::add_safe(
sizeof(std::uint64_t), // size_
util::mul_safe(size_, sizeof(T))), // data_
compr_mode);
return util::safe_cast<std::streamoff>(util::add_safe(
sizeof(Serialization::SEALHeader),
members_size
));
}
/**
Saves the IntArray to an output stream. The output is in binary format
and not human-readable. The output stream must have the "binary" flag set.
@param[out] stream The stream to save the IntArray to
@param[in] compr_mode The desired compression mode
@throws std::logic_error if the data to be saved is invalid, if compression
mode is not supported, or if compression failed
@throws std::runtime_error if I/O operations failed
*/
inline std::streamoff save(
std::ostream &stream,
compr_mode_type compr_mode = Serialization::compr_mode_default) const
{
using namespace std::placeholders;
return Serialization::Save(
std::bind(&IntArray<T_>::save_members, this, _1),
save_size(compr_mode_type::none),
stream, compr_mode);
}
/**
Loads a IntArray from an input stream overwriting the current IntArray.
This function takes optionally a bound on the size for the loaded IntArray
and throws an exception if the size indicated by the loaded metadata exceeds
the provided value. The check is omitted if in_size_bound is zero.
@param[in] stream The stream to load the IntArray from
@param[in] in_size_bound A bound on the size of the loaded IntArray
@throws std::logic_error if the loaded data is invalid, if the loaded size
exceeds in_size_bound, or if decompression failed
@throws std::runtime_error if I/O operations failed
*/
inline std::streamoff load(
std::istream &stream, std::size_t in_size_bound = 0)
{
using namespace std::placeholders;
return Serialization::Load(
std::bind(&IntArray<T_>::load_members, this, _1, in_size_bound),
stream);
}
/**
Saves the IntArray to a given memory location. The output is in binary
format and not human-readable.
@param[out] out The memory location to write the SmallModulus to
@param[in] size The number of bytes available in the given memory location
@param[in] compr_mode The desired compression mode
@throws std::invalid_argument if out is null or if size is too small to
contain a SEALHeader
@throws std::logic_error if the data to be saved is invalid, if compression
mode is not supported, or if compression failed
@throws std::runtime_error if I/O operations failed
*/
inline std::streamoff save(
SEAL_BYTE *out,
std::size_t size,
compr_mode_type compr_mode = Serialization::compr_mode_default) const
{
using namespace std::placeholders;
return Serialization::Save(
std::bind(&IntArray<T_>::save_members, this, _1),
save_size(compr_mode_type::none),
out, size, compr_mode);
}
/**
Loads a IntArray from a given memory location overwriting the current
IntArray. This function takes optionally a bound on the size for the loaded
IntArray and throws an exception if the size indicated by the loaded
metadata exceeds the provided value. The check is omitted if in_size_bound
is zero.
@param[in] in The memory location to load the SmallModulus from
@param[in] size The number of bytes available in the given memory location
@param[in] in_size_bound A bound on the size of the loaded IntArray
@throws std::invalid_argument if in is null or if size is too small to
contain a SEALHeader
@throws std::logic_error if the loaded data is invalid, if the loaded size
exceeds in_size_bound, or if decompression failed
@throws std::runtime_error if I/O operations failed
*/
inline std::streamoff load(
const SEAL_BYTE *in, std::size_t size, std::size_t in_size_bound = 0)
{
using namespace std::placeholders;
return Serialization::Load(
std::bind(&IntArray<T_>::load_members, this, _1, in_size_bound),
in, size);
}
private:
void save_members(std::ostream &stream) const
{
auto old_except_mask = stream.exceptions();
try
{
// Throw exceptions on std::ios_base::badbit and std::ios_base::failbit
stream.exceptions(std::ios_base::badbit | std::ios_base::failbit);
std::uint64_t size64 = size_;
stream.write(reinterpret_cast<const char*>(&size64), sizeof(std::uint64_t));
if (size_)
{
stream.write(reinterpret_cast<const char*>(cbegin()),
util::safe_cast<std::streamsize>(util::mul_safe(size_, sizeof(T))));
}
}
catch (const std::ios_base::failure &)
{
stream.exceptions(old_except_mask);
throw std::runtime_error("I/O error");
}
catch (...)
{
stream.exceptions(old_except_mask);
throw;
}
stream.exceptions(old_except_mask);
}
void load_members(std::istream &stream, std::size_t in_size_bound)
{
auto old_except_mask = stream.exceptions();
try
{
// Throw exceptions on std::ios_base::badbit and std::ios_base::failbit
stream.exceptions(std::ios_base::badbit | std::ios_base::failbit);
std::uint64_t size64 = 0;
stream.read(reinterpret_cast<char*>(&size64), sizeof(std::uint64_t));
// Check (optionally) that the size in the metadata does not exceed
// in_size_bound
if (in_size_bound && util::unsigned_gt(size64, in_size_bound))
{
throw std::logic_error("unexpected size");
}
// Set new size; this is potentially unsafe if size64 was not checked
// against expected_size
resize(util::safe_cast<std::size_t>(size64));
// Read data
if (size_)
{
stream.read(reinterpret_cast<char*>(begin()),
util::safe_cast<std::streamsize>(util::mul_safe(size_, sizeof(T))));
}
}
catch (const std::ios_base::failure &)
{
stream.exceptions(old_except_mask);
throw std::runtime_error("I/O error");
}
catch (...)
{
stream.exceptions(old_except_mask);
throw;
}
stream.exceptions(old_except_mask);
}
MemoryPoolHandle pool_;
std::size_t capacity_ = 0;
std::size_t size_ = 0;
util::Pointer<T> data_;
};
}
| {
"alphanum_fraction": 0.5724215433,
"avg_line_length": 34.8202898551,
"ext": "h",
"hexsha": "7609262c2144faaed7d36f8c8f365a01ef8d0c24",
"lang": "C",
"max_forks_count": 11,
"max_forks_repo_forks_event_max_datetime": "2021-12-10T02:17:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-12-02T22:02:39.000Z",
"max_forks_repo_head_hexsha": "9fc376c19488be2bfd213780ee06789754f4b2c2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nitrieu/SEAL",
"max_forks_repo_path": "native/src/seal/intarray.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "9fc376c19488be2bfd213780ee06789754f4b2c2",
"max_issues_repo_issues_event_max_datetime": "2020-09-14T06:19:36.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-09-14T06:19:36.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "nitrieu/SEAL",
"max_issues_repo_path": "native/src/seal/intarray.h",
"max_line_length": 92,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "9fc376c19488be2bfd213780ee06789754f4b2c2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nitrieu/SEAL",
"max_stars_repo_path": "native/src/seal/intarray.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-03T03:59:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-12-02T09:26:24.000Z",
"num_tokens": 4998,
"size": 24026
} |
/*
* test_suite.h
*
* Created on: Oct 16, 2013
* Author: vbonnici
*/
#ifndef TEST_SUITE_H_
#define TEST_SUITE_H_
/*
* a set of functions for binomial tests, or other distribution
*/
//#define DEBUG_TEST_SUITE_H_
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <math.h>
#include <vector>
#include <limits>
#include "data_ts.h"
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
namespace dolierlib{
/*
* Pietro's binomial test
*/
inline
double dolier_binomial(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){
double p = (double)b_dcount / (double)b_total;
double result = 0;
for(usize_t i = f_dcount; i<=f_total; i++){
result += gsl_ran_binomial_pdf(static_cast<unsigned int>(i), p, static_cast<unsigned int>(f_total));
}
return result;
}
/*
* a more efficient binomial test, thanks to gsl
*/
inline
double dolier_binomial_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){
double p = (double)b_dcount / (double)b_total;
//return gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total));
return gsl_ran_binomial_pdf(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
+ gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total));
}
/*
* Pietro's binomial test with Bon Ferroni correction
*/
inline
double dolier_binomial_bonf(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){
double p = (double)b_dcount / (double)b_total;
double result = 0;
for(usize_t i = f_dcount; i<=f_total; i++){
result += gsl_ran_binomial_pdf(static_cast<unsigned int>(i), p, static_cast<unsigned int>(f_total));
}
return double(nof_kmers) * result;
}
/*
* a more efficient binomial test with Bon Ferroni correction, thanks to gsl
*/
inline
double dolier_binomial_bonf_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){
double p = (double)b_dcount / (double)b_total;
//return gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total)) * nof_kmers;
return (
gsl_ran_binomial_pdf(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
+
gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
)
* nof_kmers;
}
/*
* other distributions tried during tests
*/
inline
double dolier_poisson_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){
double p = (double)b_dcount / (double)b_total;
double mu = p * static_cast<double>(f_total);
return gsl_ran_poisson_pdf(static_cast<unsigned int>(f_dcount),mu)
+ gsl_cdf_poisson_Q(static_cast<unsigned int>(f_dcount), mu);
// return gsl_ran_binomial_pdf(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
// + gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total));
}
inline
double dolier_poisson_bonf_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){
double p = (double)b_dcount / (double)b_total;
double mu = p * static_cast<double>(f_total);
if(mu==0) std::cout<<"#mu=0#\t"<<f_dcount<<"\t"<<f_total<<"\t"<<b_dcount<<"\t"<<b_total<<"\t"<<p<<"\n";
return (gsl_ran_poisson_pdf(static_cast<unsigned int>(f_dcount),mu)
+ gsl_cdf_poisson_Q(static_cast<unsigned int>(f_dcount), mu))
* nof_kmers;
// return (
// gsl_ran_binomial_pdf(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
// +
// gsl_cdf_binomial_Q(static_cast<unsigned int>(f_dcount), p, static_cast<unsigned int>(f_total))
// )
// * nof_kmers;
}
inline
double dolier_poisson_mu1_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){
return gsl_ran_poisson_pdf(static_cast<unsigned int>(f_dcount),1)
+ gsl_cdf_poisson_Q(static_cast<unsigned int>(f_dcount), 1);
}
inline
double dolier_poisson_mu1_bonf_Q(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total, const usize_t nof_kmers){
return (gsl_ran_poisson_pdf(static_cast<unsigned int>(f_dcount),1)
+ gsl_cdf_poisson_Q(static_cast<unsigned int>(f_dcount), 1))
* nof_kmers;
}
const double SQRT_PI = sqrt(3.141592653589793238462);
inline
double dolier_normal(double x, double sigma, double mu){
return (1/(sigma * SQRT_PI))*(exp(-(((x-mu)*(x-mu)) / (2*sigma*sigma))));
}
inline
double dolier_approx_binomial(const usize_t f_dcount, const usize_t f_total, const usize_t b_dcount, const usize_t b_total){
double p = (double)b_dcount / (double)b_total;
double result = 0;
double np = static_cast<double>(f_total) * p;
double npp = np * (1-p);
for(usize_t i = f_dcount; i<=f_total; i++){
result += dolier_normal(static_cast<double>(i), np, npp);
}
return result;
}
inline
double dolier_binomial(unsigned int x, double p, unsigned int total){
return gsl_ran_binomial_pdf(x, p, total);
}
inline
double dolier_normall(unsigned int x, double p, unsigned int total){
double np = static_cast<double>(total) * p;
double npp = np * (1-p);
return dolier_normal(static_cast<double>(x), np, npp);
}
}
#endif /* TEST_SUITE_H_ */
| {
"alphanum_fraction": 0.737746891,
"avg_line_length": 26.2884615385,
"ext": "h",
"hexsha": "93211e10d2f6959c5337de03a4984f285f76d419",
"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": "6f628b4ac5ddcbe941196813cb5faba551bd2a26",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "vbonnici/DoLiER",
"max_forks_repo_path": "dolierlib/test_suite.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6f628b4ac5ddcbe941196813cb5faba551bd2a26",
"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": "vbonnici/DoLiER",
"max_issues_repo_path": "dolierlib/test_suite.h",
"max_line_length": 152,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6f628b4ac5ddcbe941196813cb5faba551bd2a26",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "vbonnici/DoLiER",
"max_stars_repo_path": "dolierlib/test_suite.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1575,
"size": 5468
} |
/* cdf/negbinom.c
*
* Copyright (C) 2004 Jason H. Stover.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_cdf.h>
#include "error.h"
/*
* Pr(X <= k) for a negative binomial random variable X, i.e.,
* the probability of k or fewer failuers before success n.
*/
double
gsl_cdf_negative_binomial_P (const unsigned int k, const double p, const double n)
{
double P;
double a;
double b;
if (p > 1.0 || p < 0.0)
{
CDF_ERROR ("p < 0 or p > 1", GSL_EDOM);
}
if (n < 0)
{
CDF_ERROR ("n < 0", GSL_EDOM);
}
a = (double) n;
b = (double) k + 1.0;
P = gsl_cdf_beta_P (p, a, b);
return P;
}
/*
* Pr ( X > k ).
*/
double
gsl_cdf_negative_binomial_Q (const unsigned int k, const double p, const double n)
{
double Q;
double a;
double b;
if (p > 1.0 || p < 0.0)
{
CDF_ERROR ("p < 0 or p > 1", GSL_EDOM);
}
if (n < 0)
{
CDF_ERROR ("n < 0", GSL_EDOM);
}
a = (double) n;
b = (double) k + 1.0;
Q = gsl_cdf_beta_Q (p, a, b);
return Q;
}
| {
"alphanum_fraction": 0.6344026549,
"avg_line_length": 21.5238095238,
"ext": "c",
"hexsha": "c2c17e7fe1ec931bd2faed366c0c2e82a5490da0",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/cdf/nbinomial.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/cdf/nbinomial.c",
"max_line_length": 82,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/cdf/nbinomial.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 563,
"size": 1808
} |
/* bspline/greville.c
*
* Copyright (C) 2006, 2007, 2008, 2009 Patrick Alken
* Copyright (C) 2008, 2011 Rhys Ulerich
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_vector.h>
/* Return the location of the i-th Greville abscissa */
double
gsl_bspline_greville_abscissa (size_t i, gsl_bspline_workspace *w)
{
const size_t stride = w->knots->stride;
size_t km1 = w->km1;
double * data = w->knots->data + (i+1)*stride;
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= gsl_bspline_ncoeffs(w)))
{
GSL_ERROR_VAL ("Greville abscissa index out of range", GSL_EINVAL, 0);
}
#endif
if (km1 == 0)
{
/* Return interval midpoints in degenerate k = 1 case*/
km1 = 2;
data -= stride;
}
return gsl_stats_mean(data, stride, km1);
}
int
gsl_bspline_knots_greville (const gsl_vector *abscissae,
gsl_bspline_workspace *w,
double *abserr)
{
/* Limited function: see https://savannah.gnu.org/bugs/index.php?34361 */
int s;
/* Check incoming arguments satisfy mandatory algorithmic assumptions */
if (w->k < 2)
GSL_ERROR ("w->k must be at least 2", GSL_EINVAL);
else if (abscissae->size < 2)
GSL_ERROR ("abscissae->size must be at least 2", GSL_EINVAL);
else if (w->nbreak != abscissae->size - w->k + 2)
GSL_ERROR ("w->nbreak must equal abscissae->size - w->k + 2", GSL_EINVAL);
if (w->nbreak == 2)
{
/* No flexibility in abscissae values possible in this degenerate case */
s = gsl_bspline_knots_uniform (
gsl_vector_get (abscissae, 0),
gsl_vector_get (abscissae, abscissae->size - 1), w);
}
else
{
double * storage;
gsl_matrix_view A;
gsl_vector_view tau, b, x, r;
size_t i, j;
/* Constants derived from the B-spline workspace and abscissae details */
const size_t km2 = w->k - 2;
const size_t M = abscissae->size - 2;
const size_t N = w->nbreak - 2;
const double invkm1 = 1.0 / w->km1;
/* Allocate working storage and prepare multiple, zero-filled views */
storage = (double *) calloc (M*N + 2*N + 2*M, sizeof (double));
if (storage == 0)
GSL_ERROR ("failed to allocate working storage", GSL_ENOMEM);
A = gsl_matrix_view_array (storage, M, N);
tau = gsl_vector_view_array (storage + M*N, N);
b = gsl_vector_view_array (storage + M*N + N, M);
x = gsl_vector_view_array (storage + M*N + N + M, N);
r = gsl_vector_view_array (storage + M*N + N + M + N, M);
/* Build matrix from interior breakpoints to interior Greville abscissae.
* For example, when w->k = 4 and w->nbreak = 7 the matrix is
* [ 1, 0, 0, 0, 0;
* 2/3, 1/3, 0, 0, 0;
* 1/3, 1/3, 1/3, 0, 0;
* 0, 1/3, 1/3, 1/3, 0;
* 0, 0, 1/3, 1/3, 1/3;
* 0, 0, 0, 1/3, 2/3;
* 0, 0, 0, 0, 1 ]
* but only center formed as first/last breakpoint is known.
*/
for (j = 0; j < N; ++j)
for (i = 0; i <= km2; ++i)
gsl_matrix_set (&A.matrix, i+j, j, invkm1);
/* Copy interior collocation points from abscissae into b */
for (i = 0; i < M; ++i)
gsl_vector_set (&b.vector, i, gsl_vector_get (abscissae, i+1));
/* Adjust b to account for constraint columns not stored in A */
for (i = 0; i < km2; ++i)
{
double * const v = gsl_vector_ptr (&b.vector, i);
*v -= (1 - (i+1)*invkm1) * gsl_vector_get (abscissae, 0);
}
for (i = 0; i < km2; ++i)
{
double * const v = gsl_vector_ptr (&b.vector, M - km2 + i);
*v -= (i+1)*invkm1 * gsl_vector_get (abscissae, abscissae->size - 1);
}
/* Perform linear least squares to determine interior breakpoints */
s = gsl_linalg_QR_decomp (&A.matrix, &tau.vector)
|| gsl_linalg_QR_lssolve (&A.matrix, &tau.vector,
&b.vector, &x.vector, &r.vector);
if (s)
{
free (storage);
return s;
}
/* "Expand" solution x by adding known first and last breakpoints. */
x = gsl_vector_view_array_with_stride (
gsl_vector_ptr (&x.vector, 0) - x.vector.stride,
x.vector.stride, x.vector.size + 2);
gsl_vector_set (&x.vector, 0, gsl_vector_get (abscissae, 0));
gsl_vector_set (&x.vector, x.vector.size - 1,
gsl_vector_get (abscissae, abscissae->size - 1));
/* Finally, initialize workspace knots using the now-known breakpoints */
s = gsl_bspline_knots (&x.vector, w);
free (storage);
}
/* Sum absolute errors in the resulting vs requested interior abscissae */
/* Provided as a fit quality metric which may be monitored by callers */
if (!s && abserr)
{
size_t i;
*abserr = 0;
for (i = 1; i < abscissae->size - 1; ++i)
*abserr += fabs ( gsl_bspline_greville_abscissa (i, w)
- gsl_vector_get (abscissae, i) );
}
return s;
}
| {
"alphanum_fraction": 0.5825529818,
"avg_line_length": 36.4491017964,
"ext": "c",
"hexsha": "585a38e9e59b662ecdb5f62d2abe61fe4c633584",
"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/bspline/greville.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/bspline/greville.c",
"max_line_length": 81,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/bspline/greville.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": 1834,
"size": 6087
} |
//Include guard
#ifndef SEQUENCE_H
#define SEQUENCE_H
//Forward declared dependencies
//Included dependencies
#include <vector>
#include <string>
#include <gsl/gsl_rng.h>
class Sequence{
private:
//Internal variables
std::vector<char> seq;
public:
Sequence();
Sequence(int length);
Sequence(std::vector<char>& s);
Sequence(std::string s);
~Sequence();
void setSeq(std::vector<char>& s);
std::string getSeqAsString();
void setBase(int index, char b);
void addBase(char b);
void removeBase(int index);
char getBase(int index);
int getLength();
void print();
std::string printToString();
std::string printToStringNoHyphens();
Sequence subset(int start, int finish);
void addBaseFront(char b);
};
#endif
| {
"alphanum_fraction": 0.6692111959,
"avg_line_length": 19.65,
"ext": "h",
"hexsha": "80700d79ad4a1268dbb3ea5def779bca9b02236b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-06-12T13:25:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-12T13:25:36.000Z",
"max_forks_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CasperLumby/Bottleneck_Size_Estimation",
"max_forks_repo_path": "Codes/Codes_for_xStar/sequence.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1",
"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": "CasperLumby/Bottleneck_Size_Estimation",
"max_issues_repo_path": "Codes/Codes_for_xStar/sequence.h",
"max_line_length": 43,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CasperLumby/Bottleneck_Size_Estimation",
"max_stars_repo_path": "Codes/Codes_for_xStar/sequence.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 185,
"size": 786
} |
static char help[] =
"ODE system solver example using TS. Solves N-dimensional system\n"
" dy/dt = G(t,y)\n"
"with y(t0) = y0 to compute y(tf). Serial only.\n"
"Sets TS type to Runge-Kutta. The implemented example has\n"
"G_0 = y_1, G_1 = - y_0 + t, y_0(0) = 0, y_1(0) = 0. The exact solution is\n"
"y_0(t) = t - sin(t), y_1(t) = 1 - cos(t).\n\n";
#include <petsc.h>
extern PetscErrorCode ExactSolution(double, Vec);
extern PetscErrorCode FormRHSFunction(TS, double, Vec, Vec, void*);
//STARTMAIN
int main(int argc,char **argv) {
PetscErrorCode ierr;
int steps;
double t0 = 0.0, tf = 20.0, dt = 0.1, err;
Vec y, yexact;
TS ts;
PetscInitialize(&argc,&argv,(char*)0,help);
ierr = VecCreate(PETSC_COMM_WORLD,&y); CHKERRQ(ierr);
ierr = VecSetSizes(y,PETSC_DECIDE,2); CHKERRQ(ierr);
ierr = VecSetFromOptions(y); CHKERRQ(ierr);
ierr = VecDuplicate(y,&yexact); CHKERRQ(ierr);
ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);
ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);
ierr = TSSetRHSFunction(ts,NULL,FormRHSFunction,NULL); CHKERRQ(ierr);
ierr = TSSetType(ts,TSRK); CHKERRQ(ierr);
// set time axis
ierr = TSSetTime(ts,t0); CHKERRQ(ierr);
ierr = TSSetMaxTime(ts,tf); CHKERRQ(ierr);
ierr = TSSetTimeStep(ts,dt); CHKERRQ(ierr);
ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);
ierr = TSSetFromOptions(ts); CHKERRQ(ierr);
// set initial values and solve
ierr = TSGetTime(ts,&t0); CHKERRQ(ierr);
ierr = ExactSolution(t0,y); CHKERRQ(ierr);
ierr = TSSolve(ts,y); CHKERRQ(ierr);
// compute error and report
ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr);
ierr = TSGetTime(ts,&tf); CHKERRQ(ierr);
ierr = ExactSolution(tf,yexact); CHKERRQ(ierr);
ierr = VecAXPY(y,-1.0,yexact); CHKERRQ(ierr); // y <- y - yexact
ierr = VecNorm(y,NORM_INFINITY,&err); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"error at tf = %.3f with %d steps: |y-y_exact|_inf = %g\n",
tf,steps,err); CHKERRQ(ierr);
VecDestroy(&y); VecDestroy(&yexact); TSDestroy(&ts);
return PetscFinalize();
}
//ENDMAIN
//STARTCALLBACKS
PetscErrorCode ExactSolution(double t, Vec y) {
double *ay;
VecGetArray(y,&ay);
ay[0] = t - sin(t);
ay[1] = 1.0 - cos(t);
VecRestoreArray(y,&ay);
return 0;
}
PetscErrorCode FormRHSFunction(TS ts, double t, Vec y, Vec g, void *ptr) {
const double *ay;
double *ag;
VecGetArrayRead(y,&ay);
VecGetArray(g,&ag);
ag[0] = ay[1]; // = G_1(t,y)
ag[1] = - ay[0] + t; // = G_2(t,y)
VecRestoreArrayRead(y,&ay);
VecRestoreArray(g,&ag);
return 0;
}
//ENDCALLBACKS
| {
"alphanum_fraction": 0.6418518519,
"avg_line_length": 32.1428571429,
"ext": "c",
"hexsha": "f81e299f1ac3ced2fd966c16e230dc29d8f1d181",
"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": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mapengfei-nwpu/p4pdes",
"max_forks_repo_path": "c/ch5/ode.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"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": "mapengfei-nwpu/p4pdes",
"max_issues_repo_path": "c/ch5/ode.c",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mapengfei-nwpu/p4pdes",
"max_stars_repo_path": "c/ch5/ode.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 896,
"size": 2700
} |
#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_trmv (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.987f };
float X[] = { -0.138f };
int incX = -1;
float x_expected[] = { -0.136206f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 814)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.987f };
float X[] = { -0.138f };
int incX = -1;
float x_expected[] = { -0.138f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 815)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.987f };
float X[] = { -0.138f };
int incX = -1;
float x_expected[] = { -0.136206f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 816)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.987f };
float X[] = { -0.138f };
int incX = -1;
float x_expected[] = { -0.138f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 817)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.987f };
float X[] = { -0.138f };
int incX = -1;
float x_expected[] = { -0.136206f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 818)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.987f };
float X[] = { -0.138f };
int incX = -1;
float x_expected[] = { -0.138f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 819)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.987f };
float X[] = { -0.138f };
int incX = -1;
float x_expected[] = { -0.136206f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 820)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.987f };
float X[] = { -0.138f };
int incX = -1;
float x_expected[] = { -0.138f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 821)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { -0.329f };
float X[] = { 0.463f };
int incX = -1;
float x_expected[] = { -0.152327f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 822)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { -0.329f };
float X[] = { 0.463f };
int incX = -1;
float x_expected[] = { 0.463f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 823)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { -0.329f };
float X[] = { 0.463f };
int incX = -1;
float x_expected[] = { -0.152327f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 824)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { -0.329f };
float X[] = { 0.463f };
int incX = -1;
float x_expected[] = { 0.463f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 825)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { -0.329f };
float X[] = { 0.463f };
int incX = -1;
float x_expected[] = { -0.152327f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 826)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { -0.329f };
float X[] = { 0.463f };
int incX = -1;
float x_expected[] = { 0.463f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 827)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { -0.329f };
float X[] = { 0.463f };
int incX = -1;
float x_expected[] = { -0.152327f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 828)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { -0.329f };
float X[] = { 0.463f };
int incX = -1;
float x_expected[] = { 0.463f };
cblas_strmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], flteps, "strmv(case 829)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.429 };
double X[] = { -0.899 };
int incX = -1;
double x_expected[] = { 0.385671 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 830)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.429 };
double X[] = { -0.899 };
int incX = -1;
double x_expected[] = { -0.899 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 831)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.429 };
double X[] = { -0.899 };
int incX = -1;
double x_expected[] = { 0.385671 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 832)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.429 };
double X[] = { -0.899 };
int incX = -1;
double x_expected[] = { -0.899 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 833)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.429 };
double X[] = { -0.899 };
int incX = -1;
double x_expected[] = { 0.385671 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 834)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.429 };
double X[] = { -0.899 };
int incX = -1;
double x_expected[] = { -0.899 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 835)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.429 };
double X[] = { -0.899 };
int incX = -1;
double x_expected[] = { 0.385671 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 836)");
}
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.429 };
double X[] = { -0.899 };
int incX = -1;
double x_expected[] = { -0.899 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 837)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { 0.842 };
double X[] = { 0.192 };
int incX = -1;
double x_expected[] = { 0.161664 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 838)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { 0.842 };
double X[] = { 0.192 };
int incX = -1;
double x_expected[] = { 0.192 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 839)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { 0.842 };
double X[] = { 0.192 };
int incX = -1;
double x_expected[] = { 0.161664 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 840)");
}
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { 0.842 };
double X[] = { 0.192 };
int incX = -1;
double x_expected[] = { 0.192 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 841)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { 0.842 };
double X[] = { 0.192 };
int incX = -1;
double x_expected[] = { 0.161664 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 842)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { 0.842 };
double X[] = { 0.192 };
int incX = -1;
double x_expected[] = { 0.192 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 843)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { 0.842 };
double X[] = { 0.192 };
int incX = -1;
double x_expected[] = { 0.161664 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 844)");
}
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { 0.842 };
double X[] = { 0.192 };
int incX = -1;
double x_expected[] = { 0.192 };
cblas_dtrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[i], x_expected[i], dbleps, "dtrmv(case 845)");
}
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { -0.162f, -0.108f };
float X[] = { 0.542f, 0.461f };
int incX = -1;
float x_expected[] = { -0.038016f, -0.133218f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 846) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 846) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { -0.162f, -0.108f };
float X[] = { 0.542f, 0.461f };
int incX = -1;
float x_expected[] = { 0.542f, 0.461f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 847) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 847) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { -0.162f, -0.108f };
float X[] = { 0.542f, 0.461f };
int incX = -1;
float x_expected[] = { -0.038016f, -0.133218f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 848) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 848) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { -0.162f, -0.108f };
float X[] = { 0.542f, 0.461f };
int incX = -1;
float x_expected[] = { 0.542f, 0.461f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 849) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 849) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { -0.162f, -0.108f };
float X[] = { 0.542f, 0.461f };
int incX = -1;
float x_expected[] = { -0.038016f, -0.133218f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 850) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 850) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { -0.162f, -0.108f };
float X[] = { 0.542f, 0.461f };
int incX = -1;
float x_expected[] = { 0.542f, 0.461f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 851) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 851) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { -0.162f, -0.108f };
float X[] = { 0.542f, 0.461f };
int incX = -1;
float x_expected[] = { -0.038016f, -0.133218f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 852) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 852) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { -0.162f, -0.108f };
float X[] = { 0.542f, 0.461f };
int incX = -1;
float x_expected[] = { 0.542f, 0.461f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 853) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 853) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.547f, 0.583f };
float X[] = { -0.302f, 0.434f };
int incX = -1;
float x_expected[] = { -0.418216f, 0.061332f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 854) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 854) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.547f, 0.583f };
float X[] = { -0.302f, 0.434f };
int incX = -1;
float x_expected[] = { -0.302f, 0.434f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 855) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 855) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.547f, 0.583f };
float X[] = { -0.302f, 0.434f };
int incX = -1;
float x_expected[] = { -0.418216f, 0.061332f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 856) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 856) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.547f, 0.583f };
float X[] = { -0.302f, 0.434f };
int incX = -1;
float x_expected[] = { -0.302f, 0.434f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 857) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 857) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.547f, 0.583f };
float X[] = { -0.302f, 0.434f };
int incX = -1;
float x_expected[] = { -0.418216f, 0.061332f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 858) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 858) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.547f, 0.583f };
float X[] = { -0.302f, 0.434f };
int incX = -1;
float x_expected[] = { -0.302f, 0.434f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 859) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 859) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.547f, 0.583f };
float X[] = { -0.302f, 0.434f };
int incX = -1;
float x_expected[] = { -0.418216f, 0.061332f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 860) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 860) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.547f, 0.583f };
float X[] = { -0.302f, 0.434f };
int incX = -1;
float x_expected[] = { -0.302f, 0.434f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 861) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 861) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.216f, 0.192f };
float X[] = { -0.564f, -0.297f };
int incX = -1;
float x_expected[] = { -0.178848f, 0.044136f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 862) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 862) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.216f, 0.192f };
float X[] = { -0.564f, -0.297f };
int incX = -1;
float x_expected[] = { -0.564f, -0.297f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 863) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 863) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.216f, 0.192f };
float X[] = { -0.564f, -0.297f };
int incX = -1;
float x_expected[] = { -0.178848f, 0.044136f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 864) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 864) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.216f, 0.192f };
float X[] = { -0.564f, -0.297f };
int incX = -1;
float x_expected[] = { -0.564f, -0.297f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 865) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 865) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.216f, 0.192f };
float X[] = { -0.564f, -0.297f };
int incX = -1;
float x_expected[] = { -0.178848f, 0.044136f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 866) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 866) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.216f, 0.192f };
float X[] = { -0.564f, -0.297f };
int incX = -1;
float x_expected[] = { -0.564f, -0.297f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 867) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 867) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
float A[] = { 0.216f, 0.192f };
float X[] = { -0.564f, -0.297f };
int incX = -1;
float x_expected[] = { -0.178848f, 0.044136f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 868) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 868) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
float A[] = { 0.216f, 0.192f };
float X[] = { -0.564f, -0.297f };
int incX = -1;
float x_expected[] = { -0.564f, -0.297f };
cblas_ctrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], flteps, "ctrmv(case 869) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], flteps, "ctrmv(case 869) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { 0.693, -0.22 };
double X[] = { -0.101, 0.889 };
int incX = -1;
double x_expected[] = { 0.125587, 0.638297 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 870) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 870) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { 0.693, -0.22 };
double X[] = { -0.101, 0.889 };
int incX = -1;
double x_expected[] = { -0.101, 0.889 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 871) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 871) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { 0.693, -0.22 };
double X[] = { -0.101, 0.889 };
int incX = -1;
double x_expected[] = { 0.125587, 0.638297 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 872) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 872) imag");
};
};
};
{
int order = 101;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { 0.693, -0.22 };
double X[] = { -0.101, 0.889 };
int incX = -1;
double x_expected[] = { -0.101, 0.889 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 873) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 873) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { 0.693, -0.22 };
double X[] = { -0.101, 0.889 };
int incX = -1;
double x_expected[] = { 0.125587, 0.638297 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 874) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 874) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { 0.693, -0.22 };
double X[] = { -0.101, 0.889 };
int incX = -1;
double x_expected[] = { -0.101, 0.889 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 875) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 875) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { 0.693, -0.22 };
double X[] = { -0.101, 0.889 };
int incX = -1;
double x_expected[] = { 0.125587, 0.638297 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 876) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 876) imag");
};
};
};
{
int order = 102;
int trans = 111;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { 0.693, -0.22 };
double X[] = { -0.101, 0.889 };
int incX = -1;
double x_expected[] = { -0.101, 0.889 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 877) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 877) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.216, -0.623 };
double X[] = { 0.048, 0.293 };
int incX = -1;
double x_expected[] = { 0.172171, -0.093192 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 878) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 878) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.216, -0.623 };
double X[] = { 0.048, 0.293 };
int incX = -1;
double x_expected[] = { 0.048, 0.293 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 879) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 879) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.216, -0.623 };
double X[] = { 0.048, 0.293 };
int incX = -1;
double x_expected[] = { 0.172171, -0.093192 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 880) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 880) imag");
};
};
};
{
int order = 101;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.216, -0.623 };
double X[] = { 0.048, 0.293 };
int incX = -1;
double x_expected[] = { 0.048, 0.293 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 881) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 881) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.216, -0.623 };
double X[] = { 0.048, 0.293 };
int incX = -1;
double x_expected[] = { 0.172171, -0.093192 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 882) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 882) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.216, -0.623 };
double X[] = { 0.048, 0.293 };
int incX = -1;
double x_expected[] = { 0.048, 0.293 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 883) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 883) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.216, -0.623 };
double X[] = { 0.048, 0.293 };
int incX = -1;
double x_expected[] = { 0.172171, -0.093192 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 884) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 884) imag");
};
};
};
{
int order = 102;
int trans = 112;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.216, -0.623 };
double X[] = { 0.048, 0.293 };
int incX = -1;
double x_expected[] = { 0.048, 0.293 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 885) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 885) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.345, -0.851 };
double X[] = { -0.708, 0.298 };
int incX = -1;
double x_expected[] = { -0.009338, -0.705318 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 886) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 886) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.345, -0.851 };
double X[] = { -0.708, 0.298 };
int incX = -1;
double x_expected[] = { -0.708, 0.298 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 887) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 887) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.345, -0.851 };
double X[] = { -0.708, 0.298 };
int incX = -1;
double x_expected[] = { -0.009338, -0.705318 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 888) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 888) imag");
};
};
};
{
int order = 101;
int trans = 113;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.345, -0.851 };
double X[] = { -0.708, 0.298 };
int incX = -1;
double x_expected[] = { -0.708, 0.298 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 889) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 889) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 121;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.345, -0.851 };
double X[] = { -0.708, 0.298 };
int incX = -1;
double x_expected[] = { -0.009338, -0.705318 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 890) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 890) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 121;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.345, -0.851 };
double X[] = { -0.708, 0.298 };
int incX = -1;
double x_expected[] = { -0.708, 0.298 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 891) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 891) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 122;
int diag = 131;
int N = 1;
int lda = 1;
double A[] = { -0.345, -0.851 };
double X[] = { -0.708, 0.298 };
int incX = -1;
double x_expected[] = { -0.009338, -0.705318 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 892) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 892) imag");
};
};
};
{
int order = 102;
int trans = 113;
int uplo = 122;
int diag = 132;
int N = 1;
int lda = 1;
double A[] = { -0.345, -0.851 };
double X[] = { -0.708, 0.298 };
int incX = -1;
double x_expected[] = { -0.708, 0.298 };
cblas_ztrmv(order, uplo, trans, diag, N, A, lda, X, incX);
{
int i;
for (i = 0; i < 1; i++) {
gsl_test_rel(X[2*i], x_expected[2*i], dbleps, "ztrmv(case 893) real");
gsl_test_rel(X[2*i+1], x_expected[2*i+1], dbleps, "ztrmv(case 893) imag");
};
};
};
}
| {
"alphanum_fraction": 0.4937482634,
"avg_line_length": 22.7522988506,
"ext": "c",
"hexsha": "82bc18d37ff5dda959607b53d8b24f682c04e86c",
"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_trmv.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_trmv.c",
"max_line_length": 81,
"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_trmv.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": 16010,
"size": 39589
} |
/* Linear algebra operations in double-precision matrices.
*
* Implements ESL_DMATRIX (double-precision matrix) and
* ESL_PERMUTATION (permutation matrix) objects.
*
* Table of contents:
* 1. The ESL_DMATRIX object
* 2. Debugging/validation code for ESL_DMATRIX
* 3. Visualization tools
* 4. The ESL_PERMUTATION object
* 5. Debugging/validation code for ESL_PERMUTATION
* 6. The rest of the dmatrix API
* 7. Optional: Interoperability with GSL
* 8. Optional: Interfaces to LAPACK
* 9. Unit tests
* 10. Test driver
* 11. Examples
*
* To do:
* - eventually probably want additional matrix types
* - unit tests poor
*/
#include "esl_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "easel.h"
#include "esl_vectorops.h"
#include "esl_dmatrix.h"
/*****************************************************************
* 1. The ESL_DMATRIX object.
*****************************************************************/
/* Function: esl_dmatrix_Create()
*
* Purpose: Creates a general <n> x <m> matrix (<n> rows, <m>
* columns).
*
* Args: <n> - number of rows; $>= 1$
* <m> - number of columns; $>= 1$
*
* Returns: a pointer to a new <ESL_DMATRIX> object. Caller frees
* with <esl_dmatrix_Destroy()>.
*
* Throws: <NULL> if an allocation failed.
*/
ESL_DMATRIX *
esl_dmatrix_Create(int n, int m)
{
ESL_DMATRIX *A = NULL;
int r;
int status;
ESL_ALLOC(A, sizeof(ESL_DMATRIX));
A->mx = NULL;
A->n = n;
A->m = m;
ESL_ALLOC(A->mx, sizeof(double *) * n);
A->mx[0] = NULL;
ESL_ALLOC(A->mx[0], sizeof(double) * n * m);
for (r = 1; r < n; r++)
A->mx[r] = A->mx[0] + r*m;
A->type = eslGENERAL;
A->ncells = n * m;
return A;
ERROR:
esl_dmatrix_Destroy(A);
return NULL;
}
/* Function: esl_dmatrix_CreateUpper()
* Incept: SRE, Wed Feb 28 08:45:45 2007 [Janelia]
*
* Purpose: Creates a packed upper triangular matrix of <n> rows and
* <n> columns. Caller may only access cells $i \leq j$.
* Cells $i > j$ are not stored and are implicitly 0.
*
* Not all matrix operations in Easel can work on packed
* upper triangular matrices.
*
* Returns: a pointer to a new <ESL_DMATRIX> object of type
* <eslUPPER>. Caller frees with <esl_dmatrix_Destroy()>.
*
* Throws: <NULL> if allocation fails.
*
* Xref: J1/10
*/
ESL_DMATRIX *
esl_dmatrix_CreateUpper(int n)
{
int status;
ESL_DMATRIX *A = NULL;
int r; /* counter over rows */
int nc; /* cell counter */
/* matrix structure allocation */
ESL_ALLOC(A, sizeof(ESL_DMATRIX));
A->mx = NULL;
A->n = n;
A->m = n;
/* n row ptrs */
ESL_ALLOC(A->mx, sizeof(double *) * n);
A->mx[0] = NULL;
/* cell storage */
ESL_ALLOC(A->mx[0], sizeof(double) * n * (n+1) / 2);
/* row pointers set in a tricksy overlapping way, so
* mx[i][j] access works normally but only i<=j are valid.
* xref J1/10.
*/
nc = n; /* nc is the number of valid cells assigned to rows so far */
for (r = 1; r < n; r++) {
A->mx[r] = A->mx[0] + nc - r; /* -r overlaps this row w/ previous row */
nc += n-r;
}
A->type = eslUPPER;
A->ncells = n * (n+1) / 2;
return A;
ERROR:
esl_dmatrix_Destroy(A);
return NULL;
}
/* Function: esl_dmatrix_Destroy()
*
* Purpose: Frees an <ESL_DMATRIX> object <A>.
*/
int
esl_dmatrix_Destroy(ESL_DMATRIX *A)
{
if (A != NULL && A->mx != NULL && A->mx[0] != NULL) free(A->mx[0]);
if (A != NULL && A->mx != NULL) free(A->mx);
if (A != NULL) free(A);
return eslOK;
}
/* Function: esl_dmatrix_Copy()
*
* Purpose: Copies <src> matrix into <dest> matrix. <dest> must
* be allocated already by the caller.
*
* You may copy to a matrix of a different type, so long as
* the copy makes sense. If <dest> matrix is a packed type
* and <src> is not, the values that should be zeros must
* be zero in <src>, else the routine throws
* <eslEINCOMPAT>. If the <src> matrix is a packed type and
* <dest> is not, the values that are implicitly zeros are
* set to zeros in the <dest> matrix.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINCOMPAT> if <src>, <dest> are different sizes,
* or if their types differ and <dest> cannot represent
* <src>.
*/
int
esl_dmatrix_Copy(const ESL_DMATRIX *src, ESL_DMATRIX *dest)
{
int i,j;
if (dest->n != src->n || dest->m != src->m)
ESL_EXCEPTION(eslEINCOMPAT, "matrices of different size");
if (src->type == dest->type) /* simple case. */
memcpy(dest->mx[0], src->mx[0], src->ncells * sizeof(double));
else if (src->type == eslGENERAL && dest->type == eslUPPER)
{
for (i = 1; i < src->n; i++)
for (j = 0; j < i; j++)
if (src->mx[i][j] != 0.)
ESL_EXCEPTION(eslEINCOMPAT, "general matrix isn't upper triangular, can't be copied/packed");
for (i = 0; i < src->n; i++)
for (j = i; j < src->m; j++)
dest->mx[i][j] = src->mx[i][j];
}
else if (src->type == eslUPPER && dest->type == eslGENERAL)
{
for (i = 1; i < src->n; i++)
for (j = 0; j < i; j++)
dest->mx[i][j] = 0.;
for (i = 0; i < src->n; i++)
for (j = i; j < src->m; j++)
dest->mx[i][j] = src->mx[i][j];
}
return eslOK;
}
/* Function: esl_dmatrix_Clone()
* Incept: SRE, Tue May 2 14:38:45 2006 [St. Louis]
*
* Purpose: Duplicates matrix <A>, making a copy in newly
* allocated space.
*
* Returns: a pointer to the copy. Caller frees with
* <esl_dmatrix_Destroy()>.
*
* Throws: <NULL> on allocation failure.
*/
ESL_DMATRIX *
esl_dmatrix_Clone(const ESL_DMATRIX *A)
{
ESL_DMATRIX *new;
switch (A->type) {
case eslUPPER: if ( (new = esl_dmatrix_CreateUpper(A->n)) == NULL) return NULL; break;
default: case eslGENERAL: if ( (new = esl_dmatrix_Create(A->n, A->m)) == NULL) return NULL; break;
}
esl_dmatrix_Copy(A, new);
return new;
}
/* Function: esl_dmatrix_Compare()
*
* Purpose: Compares matrix <A> to matrix <B> element by element,
* using <esl_DCompare()> on each cognate element pair,
* with relative equality defined by a fractional tolerance
* <tol>. If all elements are equal, return <eslOK>; if
* any elements differ, return <eslFAIL>.
*
* <A> and <B> may be of different types; for example,
* a packed upper triangular matrix A is compared to
* a general matrix B by assuming <A->mx[i][j] = 0.> for
* all $i>j$.
*/
int
esl_dmatrix_Compare(const ESL_DMATRIX *A, const ESL_DMATRIX *B, double tol)
{
int i,j,c;
double x1,x2;
if (A->n != B->n) return eslFAIL;
if (A->m != B->m) return eslFAIL;
if (A->type == B->type)
{ /* simple case. */
for (c = 0; c < A->ncells; c++) /* can deal w/ packed or unpacked storage */
if (esl_DCompare(A->mx[0][c], B->mx[0][c], tol) == eslFAIL) return eslFAIL;
}
else
{ /* comparing matrices of different types */
for (i = 0; i < A->n; i++)
for (j = 0; j < A->m; j++)
{
if (A->type == eslUPPER && i > j) x1 = 0.;
else x1 = A->mx[i][j];
if (B->type == eslUPPER && i > j) x2 = 0.;
else x2 = B->mx[i][j];
if (esl_DCompare(x1, x2, tol) == eslFAIL) return eslFAIL;
}
}
return eslOK;
}
/* Function: esl_dmatrix_CompareAbs()
*
* Purpose: Compares matrix <A> to matrix <B> element by element,
* using <esl_DCompareAbs()> on each cognate element pair,
* with absolute equality defined by a absolute difference tolerance
* <tol>. If all elements are equal, return <eslOK>; if
* any elements differ, return <eslFAIL>.
*
* <A> and <B> may be of different types; for example,
* a packed upper triangular matrix A is compared to
* a general matrix B by assuming <A->mx[i][j] = 0.> for
* all $i>j$.
*/
int
esl_dmatrix_CompareAbs(const ESL_DMATRIX *A, const ESL_DMATRIX *B, double tol)
{
int i,j,c;
double x1,x2;
if (A->n != B->n) return eslFAIL;
if (A->m != B->m) return eslFAIL;
if (A->type == B->type)
{ /* simple case. */
for (c = 0; c < A->ncells; c++) /* can deal w/ packed or unpacked storage */
if (esl_DCompareAbs(A->mx[0][c], B->mx[0][c], tol) == eslFAIL) return eslFAIL;
}
else
{ /* comparing matrices of different types */
for (i = 0; i < A->n; i++)
for (j = 0; j < A->m; j++)
{
if (A->type == eslUPPER && i > j) x1 = 0.;
else x1 = A->mx[i][j];
if (B->type == eslUPPER && i > j) x2 = 0.;
else x2 = B->mx[i][j];
if (esl_DCompareAbs(x1, x2, tol) == eslFAIL) return eslFAIL;
}
}
return eslOK;
}
/* Function: esl_dmatrix_Set()
*
* Purpose: Set all elements $a_{ij}$ in matrix <A> to <x>,
* and returns <eslOK>.
*/
int
esl_dmatrix_Set(ESL_DMATRIX *A, double x)
{
int i;
for (i = 0; i < A->ncells; i++) A->mx[0][i] = x;
return eslOK;
}
/* Function: esl_dmatrix_SetZero()
*
* Purpose: Sets all elements $a_{ij}$ in matrix <A> to 0,
* and returns <eslOK>.
*/
int
esl_dmatrix_SetZero(ESL_DMATRIX *A)
{
int i;
for (i = 0; i < A->ncells; i++) A->mx[0][i] = 0.;
return eslOK;
}
/* Function: esl_dmatrix_SetIdentity()
*
* Purpose: Given a square matrix <A>, sets all diagonal elements
* $a_{ii}$ to 1, and all off-diagonal elements $a_{ij},
* j \ne i$ to 0. Returns <eslOK> on success.
*
* Throws: <eslEINVAL> if the matrix isn't square.
*/
int
esl_dmatrix_SetIdentity(ESL_DMATRIX *A)
{
int i;
if (A->n != A->m) ESL_EXCEPTION(eslEINVAL, "matrix isn't square");
esl_dmatrix_SetZero(A);
for (i = 0; i < A->n; i++) A->mx[i][i] = 1.;
return eslOK;
}
/*****************************************************************
* 2. Debugging, validation code
*****************************************************************/
/* Function: esl_dmatrix_Dump()
* Incept: SRE, Mon Nov 29 19:21:20 2004 [St. Louis]
*
* Purpose: Given a matrix <A>, dump it to output stream <ofp> in human-readable
* format.
*
* If <rowlabel> or <collabel> are non-NULL, they specify a
* string of single-character labels to put on the rows and
* columns, respectively. (For example, these might be a
* sequence alphabet for a 4x4 or 20x20 rate matrix or
* substitution matrix.) Numbers <1..ncols> or <1..nrows> are
* used if <collabel> or <rowlabel> are passed as <NULL>.
*
* Args: ofp - output file pointer; stdout, for example.
* A - matrix to dump.
* rowlabel - optional: NULL, or character labels for rows
* collabel - optional: NULL, or character labels for cols
*
* Returns: <eslOK> on success.
*/
int
esl_dmatrix_Dump(FILE *ofp, const ESL_DMATRIX *A, const char *rowlabel, const char *collabel)
{
int a,b;
fprintf(ofp, " ");
if (collabel != NULL)
for (b = 0; b < A->m; b++) fprintf(ofp, " %c ", collabel[b]);
else
for (b = 0; b < A->m; b++) fprintf(ofp, "%8d ", b+1);
fprintf(ofp, "\n");
for (a = 0; a < A->n; a++) {
if (rowlabel != NULL) fprintf(ofp, " %c ", rowlabel[a]);
else fprintf(ofp, "%5d ", a+1);
for (b = 0; b < A->m; b++) {
switch (A->type) {
case eslUPPER:
if (a > b) fprintf(ofp, "%8s ", "");
else fprintf(ofp, "%8.4f ", A->mx[a][b]);
break;
default: case eslGENERAL:
fprintf(ofp, "%8.4f ", A->mx[a][b]);
break;
}
}
fprintf(ofp, "\n");
}
return eslOK;
}
/*****************************************************************
* 3. Visualization tools
*****************************************************************/
/* Function: esl_dmatrix_PlotHeatMap()
* Synopsis: Export a heat map visualization, in PostScript
*
* Purpose: Export a heat map visualization of the matrix in <D>
* to open stream <fp>, in PostScript format.
*
* All values between <min> and <max> in <D> are rescaled
* linearly and assigned to shades. Values below <min>
* are assigned to the lowest shade; values above <max>, to
* the highest shade.
*
* The plot is hardcoded to be a full US 8x11.5" page,
* with at least a 20pt margin.
*
* Several color schemes are enumerated in the code
* but all but one is commented out. The currently enabled
* scheme is a 10-class scheme consisting of the 9-class
* Reds from colorbrewer2.org plus a blue background class.
*
* Note: Binning rules basically follow same convention as
* esl_histogram. nb = xmax-xmin/w, so w = xmax-xmin/nb;
* picking bin is (int) ceil((x - xmin)/w) - 1. (xref
* esl_histogram_Score2Bin()). This makes bin b contain
* values bw+min < x <= (b+1)w+min. (Which means that
* min itself falls in bin -1, whoops - but we catch
* all bin<0 and bin>=nshades and put them in the extremes.
*
* Returns: <eslOK> on success.
*
* Throws: (no abnormal error conditions)
*/
int
esl_dmatrix_PlotHeatMap(FILE *fp, ESL_DMATRIX *D, double min, double max)
{
#if 0
/*
* This color scheme roughly follows Tufte, Envisioning Information,
* p.91, where he shows a beautiful bathymetric chart. The CMYK
* values conjoin two recommendations from ColorBrewer (Cindy Brewer
* and Mark Harrower, colorbrewer2.org), specifically the 9-class
* sequential2 Blues and 9-class sequential YlOrBr.
*/
int nshades = 18;
double cyan[] = { 1.00, 1.00, 0.90, 0.75, 0.57, 0.38, 0.24, 0.13, 0.03,
0.00, 0.00, 0.00, 0.00, 0.00, 0.07, 0.20, 0.40, 0.60};
double magenta[] = { 0.55, 0.45, 0.34, 0.22, 0.14, 0.08, 0.06, 0.03, 0.01,
0.00, 0.03, 0.11, 0.23, 0.40, 0.55, 0.67, 0.75, 0.80};
double yellow[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00,
0.10, 0.25, 0.40, 0.65, 0.80, 0.90, 1.00, 1.00, 1.00};
double black[] = { 0.30, 0.07, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00,
0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00};
#endif
#if 0
/* colorbrewer2.org 5-class YlOrBr scheme: sequential, multihue, 5-class, CMYK */
int nshades = 5;
double cyan[] = { 0.00, 0.00, 0.00, 0.15, 0.40 };
double magenta[] = { 0.00, 0.15, 0.40, 0.60, 0.75 };
double yellow[] = { 0.17, 0.40, 0.80, 0.95, 1.00 };
double black[] = { 0, 0, 0, 0, 0 };
#endif
#if 0
/* colorbrewer2.org 9-class YlOrBr scheme, +zero class */
int nshades = 10;
double cyan[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.07, 0.20, 0.40, 0.60 };
double magenta[] = { 0.00, 0.00, 0.03, 0.11, 0.23, 0.40, 0.55, 0.67, 0.75, 0.80 };
double yellow[] = { 0.00, 0.10, 0.25, 0.40, 0.65, 0.80, 0.90, 1.00, 1.00, 1.00 };
double black[] = { 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 };
#endif
/* colorbrewer2.org 9-class Reds + zero class as dim blue */
int nshades = 10;
double cyan[] = { 0.30, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.20, 0.35, 0.60 };
double magenta[] = { 0.03, 0.04, 0.12, 0.27, 0.43, 0.59, 0.77, 0.90, 0.95, 1.00 };
double yellow[] = { 0.00, 0.04, 0.12, 0.27, 0.43, 0.59, 0.72, 0.80, 0.85, 0.90 };
double black[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 };
int pageheight = 792;
int pagewidth = 612;
double w;
int i,j;
int bin;
float boxsize; /* box size in points */
float xcoord, ycoord; /* postscript coords in points */
float leftmargin;
float bottommargin;
/* Set some defaults that might become arguments later.
*/
leftmargin = 20.;
bottommargin = 20.;
/* Determine some working parameters
*/
w = (max-min) / (double) nshades; /* w = bin size for assigning values->colors*/
boxsize = ESL_MIN( (pageheight - (bottommargin * 2.)) / (float) D->n,
(pagewidth - (leftmargin * 2.)) / (float) D->m);
/* or start from j=i, to do diagonals */
for (i = 0; i < D->n; i++)
for (j = 0; j < D->m; j++)
{
xcoord = (float) j * boxsize + leftmargin;
ycoord = (float) (D->n-i+1) * boxsize + bottommargin;
if (D->mx[i][j] == -eslINFINITY) bin = 0;
else if (D->mx[i][j] == eslINFINITY) bin = nshades-1;
else {
bin = (int) ceil((D->mx[i][j] - min) / w) - 1;
if (bin < 0) bin = 0;
if (bin >= nshades) bin = nshades-1;
}
fprintf(fp, "newpath\n");
fprintf(fp, " %.2f %.2f moveto\n", xcoord, ycoord);
fprintf(fp, " 0 %.2f rlineto\n", boxsize);
fprintf(fp, " %.2f 0 rlineto\n", boxsize);
fprintf(fp, " 0 -%.2f rlineto\n", boxsize);
fprintf(fp, " closepath\n");
fprintf(fp, " %.2f %.2f %.2f %.2f setcmykcolor\n",
cyan[bin], magenta[bin], yellow[bin], black[bin]);
fprintf(fp, " fill\n");
}
fprintf(fp, "showpage\n");
return eslOK;
}
/*****************************************************************
* 4. The ESL_PERMUTATION object.
*****************************************************************/
/* Function: esl_permutation_Create()
*
* Purpose: Creates a new permutation "matrix" of size <n> for
* permuting <n> x <n> square matrices; returns a
* pointer to it.
*
* A permutation matrix consists of 1's and 0's such that
* any given row or column contains only one 1. We store it
* more efficiently as a vector; each value $p_i$
* represents the column $j$ that has the 1. Thus, on
* initialization, $p_i = i$ for all $i = 0..n-1$.
*
* Returns: a pointer to a new <ESL_PERMUTATION> object. Free with
* <esl_permutation_Destroy()>.
*
* Throws: <NULL> if allocation fails.
*/
ESL_PERMUTATION *
esl_permutation_Create(int n)
{
int status;
ESL_PERMUTATION *P = NULL;
ESL_DASSERT1(( n > 0 ));
ESL_ALLOC(P, sizeof(ESL_PERMUTATION));
P->pi = NULL;
P->n = n;
ESL_ALLOC(P->pi, sizeof(int) * n);
esl_permutation_Reuse(P); /* initialize it */
return P;
ERROR:
esl_permutation_Destroy(P);
return NULL;
}
/* Function: esl_permutation_Destroy()
*
* Purpose: Frees an <ESL_PERMUTATION> object <P>.
*/
int
esl_permutation_Destroy(ESL_PERMUTATION *P)
{
if (P != NULL && P->pi != NULL) free(P->pi);
if (P != NULL) free(P);
return eslOK;
}
/* Function: esl_permutation_Reuse()
*
* Purpose: Resets a permutation matrix <P> to
* $p_i = i$ for all $i = 0..n-1$.
*
* Returns: <eslOK> on success.
*/
int
esl_permutation_Reuse(ESL_PERMUTATION *P)
{
int i;
for (i = 0; i < P->n; i++)
P->pi[i] = i;
return eslOK;
}
/*****************************************************************
* 5. Debugging/validation for ESL_PERMUTATION.
*****************************************************************/
/* Function: esl_permutation_Dump()
*
* Purpose: Given a permutation matrix <P>, dump it to output stream <ofp>
* in human-readable format.
*
* If <rowlabel> or <collabel> are non-NULL, they represent
* single-character labels to put on the rows and columns,
* respectively. (For example, these might be a sequence
* alphabet for a 4x4 or 20x20 rate matrix or substitution
* matrix.) Numbers 1..ncols or 1..nrows are used if
* <collabel> or <rowlabel> are NULL.
*
* Args: ofp - output file pointer; stdout, for example
* P - permutation matrix to dump
* rowlabel - optional: NULL, or character labels for rows
* collabel - optional: NULL, or character labels for cols
*
* Returns: <eslOK> on success.
*/
int
esl_permutation_Dump(FILE *ofp, const ESL_PERMUTATION *P, const char *rowlabel, const char *collabel)
{
int i,j;
fprintf(ofp, " ");
if (collabel != NULL)
for (j = 0; j < P->n; j++) fprintf(ofp, " %c ", collabel[j]);
else
for (j = 0; j < P->n; j++) fprintf(ofp, "%3d ", j+1);
fprintf(ofp, "\n");
for (i = 0; i < P->n; i++) {
if (rowlabel != NULL) fprintf(ofp, " %c ", rowlabel[i]);
else fprintf(ofp, "%3d ", i+1);
for (j = 0; j < P->n; j++)
fprintf(ofp, "%3d ", (j == P->pi[i]) ? 1 : 0);
fprintf(ofp, "\n");
}
return eslOK;
}
/*****************************************************************
* 6. The rest of the dmatrix API.
*****************************************************************/
/* Function: esl_dmx_Max()
* Incept: SRE, Thu Mar 1 14:46:48 2007 [Janelia]
*
* Purpose: Returns the maximum value of all the elements $a_{ij}$ in matrix <A>.
*/
double
esl_dmx_Max(const ESL_DMATRIX *A)
{
int i;
double best;
best = A->mx[0][0];
for (i = 0; i < A->ncells; i++)
if (A->mx[0][i] > best) best = A->mx[0][i];
return best;
}
/* Function: esl_dmx_Min()
* Incept: SRE, Thu Mar 1 14:49:29 2007 [Janelia]
*
* Purpose: Returns the minimum value of all the elements $a_{ij}$ in matrix <A>.
*/
double
esl_dmx_Min(const ESL_DMATRIX *A)
{
int i;
double best;
best = A->mx[0][0];
for (i = 0; i < A->ncells; i++)
if (A->mx[0][i] < best) best = A->mx[0][i];
return best;
}
/* Function: esl_dmx_MinMax()
* Incept: SRE, Wed Mar 14 16:58:03 2007 [Janelia]
*
* Purpose: Finds the maximum and minimum values of the
* elements $a_{ij}$ in matrix <A>, and returns
* them in <ret_min> and <ret_max>.
*
* Returns: <eslOK> on success.
*
*/
int
esl_dmx_MinMax(const ESL_DMATRIX *A, double *ret_min, double *ret_max)
{
double min, max;
int i;
min = max = A->mx[0][0];
for (i = 0; i < A->ncells; i++) {
if (A->mx[0][i] < min) min = A->mx[0][i];
if (A->mx[0][i] > max) max = A->mx[0][i];
}
*ret_min = min;
*ret_max = max;
return eslOK;
}
/* Function: esl_dmx_Sum()
* Incept: SRE, Thu Mar 1 16:45:16 2007
*
* Purpose: Returns the scalar sum of all the elements $a_{ij}$ in matrix <A>,
* $\sum_{ij} a_{ij}$.
*/
double
esl_dmx_Sum(const ESL_DMATRIX *A)
{
int i;
double sum = 0.;
for (i = 0; i < A->ncells; i++)
sum += A->mx[0][i];
return sum;
}
/* Function: esl_dmx_FrobeniusNorm()
* Incept: SRE, Thu Mar 15 17:59:35 2007 [Janelia]
*
* Purpose: Calculates the Frobenius norm of a matrix, which
* is the element-wise equivalant of a
* Euclidean vector norm:
* $ = \sqrt(\sum a_{ij}^2)$
*
* Args: A - matrix
* ret_fnorm - Frobenius norm.
*
* Returns: <eslOK> on success, and the Frobenius norm
* is in <ret_fnorm>.
*/
int
esl_dmx_FrobeniusNorm(const ESL_DMATRIX *A, double *ret_fnorm)
{
double F = 0.;
int i;
for (i = 0; i < A->ncells; i++)
F += A->mx[0][i] * A->mx[0][i];
*ret_fnorm = sqrt(F);
return eslOK;
}
/* Function: esl_dmx_Multiply()
*
* Purpose: Matrix multiplication: calculate <AB>, store result in <C>.
* <A> is $n times m$; <B> is $m \times p$; <C> is $n \times p$.
* Matrix <C> must be allocated appropriately by the caller.
*
* Not supported for anything but general (<eslGENERAL>)
* matrix type, at present.
*
* Throws: <eslEINVAL> if matrices don't have compatible dimensions,
* or if any of them isn't a general (<eslGENERAL>) matrix.
*/
int
esl_dmx_Multiply(const ESL_DMATRIX *A, const ESL_DMATRIX *B, ESL_DMATRIX *C)
{
int i, j, k;
if (A->m != B->n) ESL_EXCEPTION(eslEINVAL, "can't multiply A,B");
if (A->n != C->n) ESL_EXCEPTION(eslEINVAL, "A,C # of rows not equal");
if (B->m != C->m) ESL_EXCEPTION(eslEINVAL, "B,C # of cols not equal");
if (A->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "A isn't of type eslGENERAL");
if (B->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "B isn't of type eslGENERAL");
if (C->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "B isn't of type eslGENERAL");
/* i,k,j order should optimize stride, relative to a more textbook
* order for the indices
*/
esl_dmatrix_SetZero(C);
for (i = 0; i < A->n; i++)
for (k = 0; k < A->m; k++)
for (j = 0; j < B->m; j++)
C->mx[i][j] += A->mx[i][k] * B->mx[k][j];
return eslOK;
}
/*::cexcerpt::function_comment_example::begin::*/
/* Function: esl_dmx_Exp()
* Synopsis: Calculates matrix exponential $\mathbf{P} = e^{t\mathbf{Q}}$.
* Incept: SRE, Thu Mar 8 18:41:38 2007 [Janelia]
*
* Purpose: Calculates the matrix exponential $\mathbf{P} = e^{t\mathbf{Q}}$,
* using a scaling and squaring algorithm with
* the Taylor series approximation \citep{MolerVanLoan03}.
*
* <Q> must be a square matrix of type <eslGENERAL>.
* Caller provides an allocated <P> matrix of the same size and type as <Q>.
*
* A typical use of this function is to calculate a
* conditional substitution probability matrix $\mathbf{P}$
* (whose elements $P_{xy}$ are conditional substitution
* probabilities $\mathrm{Prob}(y \mid x, t)$ from time $t$
* and instantaneous rate matrix $\mathbf{Q}$.
*
* Args: Q - matrix to exponentiate (an instantaneous rate matrix)
* t - time units
* P - RESULT: $e^{tQ}$.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation error.
*
* Xref: J1/19.
*/
int
esl_dmx_Exp(const ESL_DMATRIX *Q, double t, ESL_DMATRIX *P)
{
/*::cexcerpt::function_comment_example::end::*/
ESL_DMATRIX *Qz = NULL; /* Q/2^z rescaled matrix*/
ESL_DMATRIX *Qpow = NULL; /* keeps running product Q^k */
ESL_DMATRIX *C = NULL; /* tmp storage for matrix multiply result */
double factor = 1.0;
double fnorm;
int z;
double zfac;
int k;
int status;
/* Contract checks */
if (Q->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "Q isn't general");
if (Q->n != Q->m) ESL_EXCEPTION(eslEINVAL, "Q isn't square");
if (P->type != Q->type) ESL_EXCEPTION(eslEINVAL, "P isn't of same type as Q");
if (P->n != P->m) ESL_EXCEPTION(eslEINVAL, "P isn't square");
if (P->n != Q->n) ESL_EXCEPTION(eslEINVAL, "P isn't same size as Q");
/* Allocation of working space */
if ((Qz = esl_dmatrix_Create(Q->n, Q->n)) == NULL) { status = eslEMEM; goto ERROR; }
if ((Qpow = esl_dmatrix_Create(Q->n, Q->n)) == NULL) { status = eslEMEM; goto ERROR; }
if ((C = esl_dmatrix_Create(Q->n, Q->n)) == NULL) { status = eslEMEM; goto ERROR; }
/* Figure out how much to scale the matrix down by. This is not
* magical; we're just knocking its magnitude down in an ad hoc way.
*/
esl_dmx_FrobeniusNorm(Q, &fnorm);
zfac = 1.;
z = 0;
while (t*fnorm*zfac > 0.1) { zfac /= 2.; z++; }
/* Make a scaled-down copy of Q in Qz.
*/
esl_dmatrix_Copy(Q, Qz);
esl_dmx_Scale(Qz, zfac);
/* Calculate e^{t Q_z} by the Taylor, to complete convergence. */
esl_dmatrix_SetIdentity(P);
esl_dmatrix_Copy(Qz, Qpow); /* Qpow is now Qz^1 */
for (k = 1; k < 100; k++)
{
factor *= t/k;
esl_dmatrix_Copy(P, C); /* C now holds the previous P */
esl_dmx_AddScale(P, factor, Qpow); /* P += factor*Qpow */
if (esl_dmatrix_Compare(C, P, 0.) == eslOK) break;
esl_dmx_Multiply(Qpow, Qz, C); /* C = Q^{k+1} */
esl_dmatrix_Copy(C, Qpow); /* Qpow = C = Q^{k+1} */
}
/* Now square it back up: e^{tQ} = [e^{tQ_z}]^{2^z} */
while (z--) {
esl_dmx_Multiply(P, P, C);
esl_dmatrix_Copy(C, P);
}
esl_dmatrix_Destroy(Qz);
esl_dmatrix_Destroy(Qpow);
esl_dmatrix_Destroy(C);
return eslOK;
ERROR:
if (Qz != NULL) esl_dmatrix_Destroy(Qz);
if (Qpow != NULL) esl_dmatrix_Destroy(Qpow);
if (C != NULL) esl_dmatrix_Destroy(C);
return status;
}
/* Function: esl_dmx_Transpose()
*
* Purpose: Transpose a square matrix <A> in place.
*
* <A> must be a general (<eslGENERAL>) matrix type.
*
* Throws: <eslEINVAL> if <A> isn't square, or if it isn't
* of type <eslGENERAL>.
*/
int
esl_dmx_Transpose(ESL_DMATRIX *A)
{
int i,j;
double swap;
if (A->n != A->m) ESL_EXCEPTION(eslEINVAL, "matrix isn't square");
if (A->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "A isn't of type eslGENERAL");
for (i = 0; i < A->n; i++)
for (j = i+1; j < A->m; j++)
{ swap = A->mx[i][j]; A->mx[i][j] = A->mx[j][i]; A->mx[j][i] = swap; }
return eslOK;
}
/* Function: esl_dmx_Add()
*
* Purpose: <A = A+B>; adds matrix <B> to matrix <A> and leaves result
* in matrix <A>.
*
* <A> and <B> may be of any type. However, if <A> is a
* packed upper triangular matrix (type
* <eslUPPER>), all values $i>j$ in <B> must be
* zero (i.e. <B> must also be upper triangular, though
* not necessarily packed upper triangular).
*
* Throws: <eslEINVAL> if matrices aren't the same dimensions, or
* if <A> is <eslUPPER> and any cell $i>j$ in
* <B> is nonzero.
*/
int
esl_dmx_Add(ESL_DMATRIX *A, const ESL_DMATRIX *B)
{
int i,j;
if (A->n != B->n) ESL_EXCEPTION(eslEINVAL, "matrices of different size");
if (A->m != B->m) ESL_EXCEPTION(eslEINVAL, "matrices of different size");
if (A->type == B->type) /* in this case, can just add cell by cell */
{
for (i = 0; i < A->ncells; i++)
A->mx[0][i] += B->mx[0][i];
}
else if (A->type == eslUPPER || B->type == eslUPPER)
{
/* Logic is: if either matrix is upper triangular, then the operation is
* to add upper triangles only. If we try to add a general matrix <B>
* to packed UT <A>, make sure all lower triangle entries in <B> are zero.
*/
if (B->type != eslUPPER) {
for (i = 1; i < A->n; i++)
for (j = 0; j < i; j++)
if (B->mx[i][j] != 0.) ESL_EXCEPTION(eslEINVAL, "<B> has nonzero cells in lower triangle");
}
for (i = 0; i < A->n; i++)
for (j = i; j < A->m; j++)
A->mx[i][j] += B->mx[i][j];
}
return eslOK;
}
/* Function: esl_dmx_Scale()
*
* Purpose: Calculates <A = kA>: multiply matrix <A> by scalar
* <k> and leave answer in <A>.
*/
int
esl_dmx_Scale(ESL_DMATRIX *A, double k)
{
int i;
for (i = 0; i < A->ncells; i++) A->mx[0][i] *= k;
return eslOK;
}
/* Function: esl_dmx_AddScale()
*
* Purpose: Calculates <A + kB>, leaves answer in <A>.
*
* Only defined for matrices of the same type (<eslGENERAL>
* or <eslUPPER>).
*
* Throws: <eslEINVAL> if matrices aren't the same dimensions, or
* of different types.
*/
int
esl_dmx_AddScale(ESL_DMATRIX *A, double k, const ESL_DMATRIX *B)
{
int i;
if (A->n != B->n) ESL_EXCEPTION(eslEINVAL, "matrices of different size");
if (A->m != B->m) ESL_EXCEPTION(eslEINVAL, "matrices of different size");
if (A->type != B->type) ESL_EXCEPTION(eslEINVAL, "matrices of different type");
for (i = 0; i < A->ncells; i++) A->mx[0][i] += k * B->mx[0][i];
return eslOK;
}
/* Function: esl_dmx_Permute_PA()
*
* Purpose: Computes <B = PA>: do a row-wise permutation of a square
* matrix <A>, using the permutation matrix <P>, and put
* the result in a square matrix <B> that the caller has
* allocated.
*
* Throws: <eslEINVAL> if <A>, <B>, <P> do not have compatible dimensions,
* or if <A> or <B> is not of type <eslGENERAL>.
*/
int
esl_dmx_Permute_PA(const ESL_PERMUTATION *P, const ESL_DMATRIX *A, ESL_DMATRIX *B)
{
int i,ip,j;
if (A->n != P->n) ESL_EXCEPTION(eslEINVAL, "matrix dimensions not compatible");
if (A->n != B->n) ESL_EXCEPTION(eslEINVAL, "matrix dimensions not compatible");
if (A->n != A->m) ESL_EXCEPTION(eslEINVAL, "matrix dimensions not compatible");
if (B->n != B->m) ESL_EXCEPTION(eslEINVAL, "matrix dimensions not compatible");
if (A->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "matrix A not of type eslGENERAL");
if (B->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "matrix B not of type eslGENERAL");
for (i = 0; i < A->n; i++)
{
ip = P->pi[i];
for (j = 0; j < A->m; j++)
B->mx[i][j] = A->mx[ip][j];
}
return eslOK;
}
/* Function: esl_dmx_LUP_decompose()
*
* Purpose: Calculates a permuted LU decomposition of square matrix
* <A>; upon return, <A> is replaced by this decomposition,
* where <U> is in the lower triangle (inclusive of the
* diagonal) and <L> is the upper triangle (exclusive of
* diagonal, which is 1's by definition), and <P> is the
* permutation matrix. Caller provides an allocated
* permutation matrix <P> compatible with the square matrix
* <A>.
*
* Implements Gaussian elimination with pivoting
* \citep[p.~759]{Cormen99}.
*
* Throws: <eslEINVAL> if <A> isn't square, or if <P> isn't the right
* size for <A>, or if <A> isn't of general type.
*/
int
esl_dmx_LUP_decompose(ESL_DMATRIX *A, ESL_PERMUTATION *P)
{
int i,j,k;
int kpiv = 0; // initialization serves to quiet overzealous static analyzers
double max;
double swap;
if (A->n != A->m) ESL_EXCEPTION(eslEINVAL, "matrix isn't square");
if (P->n != A->n) ESL_EXCEPTION(eslEINVAL, "permutation isn't the right size");
if (A->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "matrix isn't of general type");
esl_permutation_Reuse(P);
for (k = 0; k < A->n-1; k++)
{
/* Identify our pivot; find row with maximum value in col[k].
* This is guaranteed to succeed and set <kpiv>
* (no matter what a static analyzer tells you)
*/
max = 0.;
for (i = k; i < A->n; i++)
if (fabs(A->mx[i][k]) > max) {
max = fabs(A->mx[i][k]);
kpiv = i;
}
if (max == 0.) ESL_EXCEPTION(eslEDIVZERO, "matrix is singular");
/* Swap those rows (k and kpiv);
* and keep track of that permutation in P. (misuse j for swapping integers)
*/
j = P->pi[k]; P->pi[k] = P->pi[kpiv]; P->pi[kpiv] = j;
for (j = 0; j < A->m; j++)
{ swap = A->mx[k][j]; A->mx[k][j] = A->mx[kpiv][j]; A->mx[kpiv][j] = swap; }
/* Gaussian elimination for all rows k+1..n.
*/
for (i = k+1; i < A->n; i++)
{
A->mx[i][k] /= A->mx[k][k];
for (j = k+1; j < A->m; j++)
A->mx[i][j] -= A->mx[i][k] * A->mx[k][j];
}
}
return eslOK;
}
/* Function: esl_dmx_LU_separate()
*
* Purpose: Separate a square <LU> decomposition matrix into its two
* triangular matrices <L> and <U>. Caller provides two
* allocated <L> and <U> matrices of same size as <LU> for
* storing the results.
*
* <U> may be an upper triangular matrix in either unpacked
* (<eslGENERAL>) or packed (<eslUPPER>) form.
* <LU> and <L> must be of <eslGENERAL> type.
*
* Throws: <eslEINVAL> if <LU>, <L>, <U> are not of compatible dimensions,
* or if <LU> or <L> aren't of general type.
*/
int
esl_dmx_LU_separate(const ESL_DMATRIX *LU, ESL_DMATRIX *L, ESL_DMATRIX *U)
{
int i,j;
if (LU->n != LU->m) ESL_EXCEPTION(eslEINVAL, "LU isn't square");
if (L->n != L->m) ESL_EXCEPTION(eslEINVAL, "L isn't square");
if (U->n != U->m) ESL_EXCEPTION(eslEINVAL, "U isn't square");
if (LU->n != L->n) ESL_EXCEPTION(eslEINVAL, "LU, L have incompatible dimensions");
if (LU->n != U->n) ESL_EXCEPTION(eslEINVAL, "LU, U have incompatible dimensions");
if (LU->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "matrix isn't of general type");
if (L->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "matrix isn't of general type");
esl_dmatrix_SetZero(L);
esl_dmatrix_SetZero(U);
for (i = 0; i < LU->n; i++)
for (j = i; j < LU->m; j++)
U->mx[i][j] = LU->mx[i][j];
for (i = 0; i < LU->n; i++)
{
L->mx[i][i] = 1.;
for (j = 0; j < i; j++)
L->mx[i][j] = LU->mx[i][j];
}
return eslOK;
}
/* Function: esl_dmx_Invert()
*
* Purpose: Calculates the inverse of square matrix <A>, and stores the
* result in matrix <Ai>. Caller provides an allocated
* matrix <Ai> of same dimensions as <A>. Both must be
* of type <eslGENERAL>.
*
* Peforms the inversion by LUP decomposition followed by
* forward/back-substitution \citep[p.~753]{Cormen99}.
*
* Throws: <eslEINVAL> if <A>, <Ai> do not have same dimensions,
* if <A> isn't square, or if either isn't of
* type <eslGENERAL>.
* <eslEMEM> if internal allocations (for LU, and some other
* bookkeeping) fail.
*/
int
esl_dmx_Invert(const ESL_DMATRIX *A, ESL_DMATRIX *Ai)
{
ESL_DMATRIX *LU = NULL;
ESL_PERMUTATION *P = NULL;
double *y = NULL; /* column vector, intermediate calculation */
double *b = NULL; /* column vector of permuted identity matrix */
int i,j,k;
int status;
if (A->n != A->m) ESL_EXCEPTION(eslEINVAL, "matrix isn't square");
if (A->n != Ai->n || A->m != Ai->m) ESL_EXCEPTION(eslEINVAL, "matrices are different size");
if (A->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "matrix A not of general type");
if (Ai->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "matrix B not of general type");
/* Copy A to LU, and do an LU decomposition.
*/
if ((LU = esl_dmatrix_Create(A->n, A->m)) == NULL) { status = eslEMEM; goto ERROR; }
if ((P = esl_permutation_Create(A->n)) == NULL) { status = eslEMEM; goto ERROR; }
if (( status = esl_dmatrix_Copy(A, LU)) != eslOK) goto ERROR;
if (( status = esl_dmx_LUP_decompose(LU, P)) != eslOK) goto ERROR;
/* Now we have:
* PA = LU
*
* to invert a matrix A, we want A A^-1 = I;
* that's PAx = Pb, for columns x of A^-1 and b of the identity matrix;
* and that's n equations LUx = Pb;
*
* so, solve Ly = Pb for y by forward substitution;
* then Ux = y by back substitution;
* x is then a column of A^-1.
*
* Do that for all columns.
*/
ESL_ALLOC(b, sizeof(double) * A->n);
ESL_ALLOC(y, sizeof(double) * A->n);
for (k = 0; k < A->m; k++) /* for each column... */
{
/* build Pb for column j of the identity matrix */
for (i = 0; i < A->n; i++)
if (P->pi[i] == k) b[i] = 1.; else b[i] = 0.;
/* forward substitution
*/
for (i = 0; i < A->n; i++)
{
y[i] = b[i];
for (j = 0; j < i; j++) y[i] -= LU->mx[i][j] * y[j];
}
/* back substitution
*/
for (i = A->n-1; i >= 0; i--)
{
Ai->mx[i][k] = y[i];
for (j = i+1; j < A->n; j++) Ai->mx[i][k] -= LU->mx[i][j] * Ai->mx[j][k];
Ai->mx[i][k] /= LU->mx[i][i];
}
}
free(b);
free(y);
esl_dmatrix_Destroy(LU);
esl_permutation_Destroy(P);
return eslOK;
ERROR:
if (y != NULL) free(y);
if (b != NULL) free(b);
if (LU != NULL) esl_dmatrix_Destroy(LU);
if (P != NULL) esl_permutation_Destroy(P);
return status;
}
/*****************************************************************
* 7. Optional: interoperability with GSL
*****************************************************************/
#ifdef HAVE_LIBGSL
#include <gsl/gsl_matrix.h>
int
esl_dmx_MorphGSL(const ESL_DMATRIX *E, gsl_matrix **ret_G)
{
gsl_matrix *G = NULL;
int i,j;
if (E->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "can only morph general matrices to GSL right now");
G = gsl_matrix_alloc(E->m, E->n);
for (i = 0; i < E->m; i++)
for (j = 0; j < E->n; j++)
gsl_matrix_set(G, i, j, E->mx[i][j]);
*ret_G = G;
return eslOK;
}
int
esl_dmx_UnmorphGSL(const gsl_matrix *G, ESL_DMATRIX **ret_E)
{
ESL_DMATRIX *E = NULL;
int i,j;
if ((E = esl_dmatrix_Create(G->size1, G->size2)) == NULL) return eslEMEM;
for (i = 0; i < G->size1; i++)
for (j = 0; j < G->size2; j++)
E->mx[i][j] = gsl_matrix_get(G, i, j);
*ret_E = E;
return eslOK;
}
#endif /*HAVE_LIBGSL*/
/*****************************************************************
* 8. Optional: Interfaces to LAPACK
*****************************************************************/
#ifdef HAVE_LIBLAPACK
/* To include LAPACK code, you need to:
* 1. declare the C interface to the Fortran routine,
* appending _ to the Fortran routine's name (dgeev becomes dgeev_)
*
* 2. Remember to transpose matrices into column-major
* Fortran form
*
* 3. everything must be passed by reference, not by value
*
* 4. you don't need any include files, just lapack.a
*
* 5. Add -llapack to the compile line.
* (It doesn't appear that blas or g2c are needed?)
*/
/* Declare the C interface to the Fortran77 dgeev routine
* provided by the LAPACK library:
*/
extern void dgeev_(char *jobvl, char *jobvr, int *n, double *a,
int *lda, double *wr, double *wi, double *vl,
int *ldvl, double *vr, int *ldvr,
double *work, int *lwork, int *info);
/* Function: esl_dmx_Diagonalize()
* Incept: SRE, Thu Mar 15 09:28:03 2007 [Janelia]
*
* Purpose: Given a square real matrix <A>, diagonalize it:
* solve for $U^{-1} A U = diag(\lambda_1... \lambda_n)$.
*
* Upon return, <ret_Er> and <ret_Ei> are vectors
* containing the real and complex parts of the eigenvalues
* $\lambda_i$; <ret_UL> is the $U^{-1}$ matrix containing
* the left eigenvectors; and <ret_UR> is the $U$ matrix
* containing the right eigenvectors.
*
* <ret_UL> and <ret_UR> are optional; pass <NULL> for
* either if you don't want that set of eigenvectors.
*
* This is a C interface to the <dgeev()> routine in the
* LAPACK linear algebra library.
*
* Args: A - square nxn matrix to diagonalize
* ret_Er - RETURN: real part of eigenvalues (0..n-1)
* ret_Ei - RETURN: complex part of eigenvalues (0..n-1)
* ret_UL - optRETURN: nxn matrix of left eigenvectors
* ret_UR - optRETURN:
*
* Returns: <eslOK> on success.
* <ret_Er> and <ret_Ei> (and <ret_UL>,<ret_UR> when they are
* requested) are allocated here, and must be free'd by the caller.
*
* Throws: <eslEMEM> on allocation failure.
* In this case, the four return pointers are returned <NULL>.
*
* Xref: J1/19.
*/
int
esl_dmx_Diagonalize(const ESL_DMATRIX *A, double **ret_Er, double **ret_Ei,
ESL_DMATRIX **ret_UL, ESL_DMATRIX **ret_UR)
{
int status;
double *Er = NULL;
double *Ei = NULL;
ESL_DMATRIX *At = NULL;
ESL_DMATRIX *UL = NULL;
ESL_DMATRIX *UR = NULL;
double *work = NULL;
char jobul, jobur;
int lda;
int ldul, ldur;
int lwork;
int info;
if (A->n != A->m) ESL_EXCEPTION(eslEINVAL, "matrix isn't square");
if ((At = esl_dmatrix_Clone(A)) == NULL) { status = eslEMEM; goto ERROR; }
if ((UL = esl_dmatrix_Create(A->n,A->n)) == NULL) { status = eslEMEM; goto ERROR; }
if ((UR = esl_dmatrix_Create(A->n,A->n)) == NULL) { status = eslEMEM; goto ERROR; }
ESL_ALLOC(Er, sizeof(double) * A->n);
ESL_ALLOC(Ei, sizeof(double) * A->n);
ESL_ALLOC(work, sizeof(double) * 8 * A->n);
jobul = (ret_UL == NULL) ? 'N' : 'V'; /* do we want left eigenvectors? */
jobur = (ret_UR == NULL) ? 'N' : 'V'; /* do we want right eigenvectors? */
lda = A->n;
ldul = A->n;
ldur = A->n;
lwork = 8*A->n;
/* Fortran convention is colxrow, not rowxcol; so transpose
* a copy of A before passing it to a Fortran routine.
*/
esl_dmx_Transpose(At);
/* The Fortran77 interface call to LAPACK's dgeev().
* All args must be passed by reference.
* Fortran 2D arrays are 1D: so pass the A[0] part of a DSMX.
*/
dgeev_(&jobul, &jobur, &(At->n), At->mx[0], &lda, Er, Ei,
UL->mx[0], &ldul, UR->mx[0], &ldur, work, &lwork, &info);
if (info < 0) ESL_XEXCEPTION(eslEINVAL, "argument %d to LAPACK dgeev is invalid", -info);
if (info > 0) ESL_XEXCEPTION(eslEINVAL,
"diagonalization failed; only eigenvalues %d..%d were computed",
info+1, At->n);
/* Now, UL, UR are transposed (col x row), so transpose them back to
* C language convention.
*/
esl_dmx_Transpose(UL);
esl_dmx_Transpose(UR);
esl_dmatrix_Destroy(At);
if (ret_UL != NULL) *ret_UL = UL; else esl_dmatrix_Destroy(UL);
if (ret_UR != NULL) *ret_UR = UR; else esl_dmatrix_Destroy(UR);
if (ret_Er != NULL) *ret_Er = Er; else free(Er);
if (ret_Ei != NULL) *ret_Ei = Ei; else free(Ei);
free(work);
return eslOK;
ERROR:
if (ret_UL != NULL) *ret_UL = NULL;
if (ret_UR != NULL) *ret_UR = NULL;
if (ret_Er != NULL) *ret_Er = NULL;
if (ret_Ei != NULL) *ret_Ei = NULL;
if (At != NULL) esl_dmatrix_Destroy(At);
if (UL != NULL) esl_dmatrix_Destroy(UL);
if (UR != NULL) esl_dmatrix_Destroy(UR);
if (Er != NULL) free(Er);
if (Ei != NULL) free(Ei);
if (work != NULL) free(work);
return status;
}
#endif /*HAVE_LIBLAPACK*/
/*****************************************************************
* 9. Unit tests
*****************************************************************/
#ifdef eslDMATRIX_TESTDRIVE
static void
utest_misc_ops(void)
{
char *msg = "miscellaneous unit test failed";
ESL_DMATRIX *A, *B, *C;
int n = 20;
if ((A = esl_dmatrix_Create(n,n)) == NULL) esl_fatal(msg);
if ((B = esl_dmatrix_Create(n,n)) == NULL) esl_fatal(msg);
if ((C = esl_dmatrix_Create(n,n)) == NULL) esl_fatal(msg);
if (esl_dmatrix_SetIdentity(A) != eslOK) esl_fatal(msg); /* A=I */
if (esl_dmx_Invert(A, B) != eslOK) esl_fatal(msg); /* B=I^-1=I */
if (esl_dmx_Multiply(A,B,C) != eslOK) esl_fatal(msg); /* C=I */
if (esl_dmx_Transpose(A) != eslOK) esl_fatal(msg); /* A=I still */
if (esl_dmx_Scale(A, 0.5) != eslOK) esl_fatal(msg); /* A= 0.5I */
if (esl_dmx_AddScale(B, -0.5, C) != eslOK) esl_fatal(msg); /* B= 0.5I */
if (esl_dmx_Add(A,B) != eslOK) esl_fatal(msg); /* A=I */
if (esl_dmx_Scale(B, 2.0) != eslOK) esl_fatal(msg); /* B=I */
if (esl_dmatrix_Compare(A, B, 1e-12) != eslOK) esl_fatal(msg);
if (esl_dmatrix_Compare(A, C, 1e-12) != eslOK) esl_fatal(msg);
if (esl_dmatrix_Copy(B, C) != eslOK) esl_fatal(msg);
if (esl_dmatrix_Compare(A, C, 1e-12) != eslOK) esl_fatal(msg);
esl_dmatrix_Destroy(A);
esl_dmatrix_Destroy(B);
esl_dmatrix_Destroy(C);
return;
}
static void
utest_Invert(ESL_DMATRIX *A)
{
char *msg = "Failure in matrix inversion unit test";
ESL_DMATRIX *Ai = NULL;
ESL_DMATRIX *B = NULL;
ESL_DMATRIX *I = NULL;
if ((Ai = esl_dmatrix_Create(A->n, A->m)) == NULL) esl_fatal(msg);
if ((B = esl_dmatrix_Create(A->n, A->m)) == NULL) esl_fatal(msg);
if ((I = esl_dmatrix_Create(A->n, A->m)) == NULL) esl_fatal(msg);
if (esl_dmx_Invert(A, Ai) != eslOK) esl_fatal("matrix inversion failed");
if (esl_dmx_Multiply(A,Ai,B) != eslOK) esl_fatal(msg);
if (esl_dmatrix_SetIdentity(I) != eslOK) esl_fatal(msg);
if (esl_dmatrix_Compare(B,I, 1e-12) != eslOK) esl_fatal("inverted matrix isn't right");
esl_dmatrix_Destroy(Ai);
esl_dmatrix_Destroy(B);
esl_dmatrix_Destroy(I);
return;
}
#endif /*eslDMATRIX_TESTDRIVE*/
/*****************************************************************
* 10. Test driver
*****************************************************************/
/* gcc -g -Wall -o test -I. -L. -DeslDMATRIX_TESTDRIVE esl_dmatrix.c -leasel -lm
*/
#ifdef eslDMATRIX_TESTDRIVE
#include "easel.h"
#include "esl_dmatrix.h"
#include "esl_random.h"
int main(void)
{
ESL_RANDOMNESS *r;
ESL_DMATRIX *A;
int n = 30;
int seed = 42;
int i,j;
double range = 100.;
/* Create a square matrix with random values from -range..range */
if ((r = esl_randomness_Create(seed)) == NULL) esl_fatal("failed to create random source");
if ((A = esl_dmatrix_Create(n, n)) == NULL) esl_fatal("failed to create matrix");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
A->mx[i][j] = esl_random(r) * range * 2.0 - range;
utest_misc_ops();
utest_Invert(A);
esl_randomness_Destroy(r);
esl_dmatrix_Destroy(A);
return 0;
}
#endif /*eslDMATRIX_TESTDRIVE*/
/*****************************************************************
* 11. Examples
*****************************************************************/
/* gcc -g -Wall -o example -I. -DeslDMATRIX_EXAMPLE esl_dmatrix.c easel.c -lm
*/
#ifdef eslDMATRIX_EXAMPLE
/*::cexcerpt::dmatrix_example::begin::*/
#include "easel.h"
#include "esl_dmatrix.h"
int main(void)
{
ESL_DMATRIX *A, *B, *C;
A = esl_dmatrix_Create(4,4);
B = esl_dmatrix_Create(4,4);
C = esl_dmatrix_Create(4,4);
esl_dmatrix_SetIdentity(A);
esl_dmatrix_Copy(A, B);
esl_dmx_Multiply(A,B,C);
esl_dmatrix_Dump(stdout, C, NULL, NULL);
esl_dmatrix_Destroy(A);
esl_dmatrix_Destroy(B);
esl_dmatrix_Destroy(C);
return 0;
}
/*::cexcerpt::dmatrix_example::end::*/
#endif /*eslDMATRIX_EXAMPLE*/
| {
"alphanum_fraction": 0.5512385712,
"avg_line_length": 31.7512594458,
"ext": "c",
"hexsha": "367ea314a9b1d9607f1d0cd11e8b87ac7468b38d",
"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": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "WooMichael/Project_Mendel",
"max_forks_repo_path": "hmmer-3.3/easel/esl_dmatrix.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8",
"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": "WooMichael/Project_Mendel",
"max_issues_repo_path": "hmmer-3.3/easel/esl_dmatrix.c",
"max_line_length": 106,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ff572f7ce7f9beca148f7351cf34dbf11d670bc8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "WooMichael/Project_Mendel",
"max_stars_repo_path": "hmmer-3.3/easel/esl_dmatrix.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 16241,
"size": 50421
} |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2010 The Boeing Company
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Gary Pei <guangyu.pei@boeing.com>
*/
#ifndef DSSS_ERROR_RATE_MODEL_H
#define DSSS_ERROR_RATE_MODEL_H
#ifdef HAVE_GSL
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_sf_bessel.h>
#endif
namespace ns3 {
#ifdef HAVE_GSL
/**
* Structure for integral function parameters
*/
typedef struct FunctionParameterType
{
double beta; ///< Beta parameter
double n; ///< n parameter
} FunctionParameters;
/**
* Integral function using GSL library
*
* \param x the input x variable
* \param params a pointer to FunctionParameters struct
*
* \return the integral function
*/
double IntegralFunction (double x, void *params);
#endif
/**
* \brief an implementation of DSSS error rate model
* \ingroup wifi
*
* The 802.11b modulations:
* - 1 Mbps mode is based on DBPSK. BER is from equation 5.2-69 from John G. Proakis
* Digital Communications, 2001 edition
* - 2 Mbps model is based on DQPSK. Equation 8 from "Tight bounds and accurate
* approximations for DQPSK transmission bit error rate", G. Ferrari and G.E. Corazza
* ELECTRONICS LETTERS, 40(20):1284-1285, September 2004
* - 5.5 Mbps and 11 Mbps are based on equations (18) and (17) from "Properties and
* performance of the IEEE 802.11b complementarycode-key signal sets",
* Michael B. Pursley and Thomas C. Royster. IEEE TRANSACTIONS ON COMMUNICATIONS,
* 57(2):440-449, February 2009.
*
* This model is designed to run with highest accuracy using the GNU
* Scientific Library (GSL), but if GSL is not installed on the platform,
* will fall back to (slightly less accurate) Matlab-derived models for
* the CCK modulation types.
*
* More detailed description and validation can be found in
* http://www.nsnam.org/~pei/80211b.pdf
*/
class DsssErrorRateModel
{
public:
/**
* A function DQPSK
*
* \param x the input variable
*
* \return DQPSK (x)
*/
static double DqpskFunction (double x);
/**
* Return the chunk success rate of the differential BPSK.
*
* \param sinr the SINR ratio (not dB) of the chunk
* \param nbits the size of the chunk
*
* \return the chunk success rate of the differential BPSK
*/
static double GetDsssDbpskSuccessRate (double sinr, uint64_t nbits);
/**
* Return the chunk success rate of the differential encoded QPSK.
*
* \param sinr the SINR ratio (not dB) of the chunk
* \param nbits the size of the chunk
*
* \return the chunk success rate of the differential encoded QPSK.
*/
static double GetDsssDqpskSuccessRate (double sinr,uint64_t nbits);
/**
* Return the chunk success rate of the differential encoded QPSK for
* 5.5Mbps data rate.
*
* \param sinr the SINR ratio (not dB) of the chunk
* \param nbits the size of the chunk
*
* \return the chunk success rate of the differential encoded QPSK for
*/
static double GetDsssDqpskCck5_5SuccessRate (double sinr,uint64_t nbits);
/**
* Return the chunk success rate of the differential encoded QPSK for
* 11Mbps data rate.
*
* \param sinr the SINR ratio (not dB) of the chunk
* \param nbits the size of the chunk
*
* \return the chunk success rate of the differential encoded QPSK for
*/
static double GetDsssDqpskCck11SuccessRate (double sinr,uint64_t nbits);
#ifdef HAVE_GSL
static double SymbolErrorProb16Cck (double e2); /// equation (18) in Pursley's paper
static double SymbolErrorProb256Cck (double e1); /// equation (17) in Pursley's paper
#else
protected:
/// WLAN perfect
static const double WLAN_SIR_PERFECT;
/// WLAN impossible
static const double WLAN_SIR_IMPOSSIBLE;
#endif
};
} //namespace ns3
#endif /* DSSS_ERROR_RATE_MODEL_H */
| {
"alphanum_fraction": 0.710718232,
"avg_line_length": 31.6433566434,
"ext": "h",
"hexsha": "1090885d5715c001872dddd875c72ac0a326cb19",
"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": "1086759b6dbe7da192225780d5fe6a3da0c5eb07",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Marquez607/Wireless-Perf-Sim",
"max_forks_repo_path": "ns-3-dev/src/wifi/model/non-ht/dsss-error-rate-model.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1086759b6dbe7da192225780d5fe6a3da0c5eb07",
"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": "Marquez607/Wireless-Perf-Sim",
"max_issues_repo_path": "ns-3-dev/src/wifi/model/non-ht/dsss-error-rate-model.h",
"max_line_length": 90,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "487aa9e322b2b01b6af3a92e38545c119e4980a3",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "usi-systems/cc",
"max_stars_repo_path": "ns-allinone-3.35/ns-3.35/src/wifi/model/non-ht/dsss-error-rate-model.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T08:08:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-22T08:08:35.000Z",
"num_tokens": 1240,
"size": 4525
} |
//
// gemm.h
// Linear Algebra Template Library
//
// Created by Rodney James on 1/30/12.
// Copyright (c) 2012 University of Colorado Denver. All rights reserved.
//
#ifndef _gemm_h
#define _gemm_h
/// @file gemm.h Computes general matrix-matrix products.
#include <cctype>
#include "latl.h"
namespace LATL
{
/// @brief Computes products of real matrices.
///
/// For real matrices A,B,C and real scalars alpha, beta
///
/// C := alpha * op(A) * op(B) + beta * C
///
/// is calculated, where op(X) = X or X'.
/// @return 0 if success.
/// @return -i if the ith argument is invalid.
/// @tparam real_t Floating point type.
/// @param transA Specifies whether op(A)=A or A' as follows:
///
/// if transA = 'N' or 'n' then op(A)=A
/// if transA = 'T' or 't' then op(A)=A'
/// if transA = 'C' or 'c' then op(A)=A'
///
/// @param transB Specifies whether op(B)=B or B' as follows:
///
/// if transB = 'N' or 'n' then op(B)=B
/// if transB = 'T' or 't' then op(B)=B'
/// if transB = 'C' or 'c' then op(B)=B'
///
/// @param m The number of rows of the matrices C and op(A). m>=0
/// @param n The number of columns of the matrices C and op(B). n>=0
/// @param k The number of columns of the matrix op(A), and the number of rows of the matrix op(B). k>=0
/// @param alpha Real scalar.
/// @param A Pointer to real matrix A, where op(A) is m-by-k.
/// @param ldA Column length of the matrix A. If transA='N' or 'n', ldA>=m; otherwise, ldA>=k.
/// @param B Pointer to real matrix B, where op(B) is k-by-n.
/// @param ldB Column length of the matrix B. If transB='N' or 'n', ldB>=k; otherwise, ldA>=n.
/// @param beta Real scalar.
/// @param C Pointer to real matrix C, where C is m-by-n.
/// @param ldC Column length of the matrix C. ldC>=m.
/// @ingroup BLAS
template<typename real_t>
int GEMM(char transA, char transB, int_t m, int_t n, int_t k, real_t alpha, real_t *A, int_t ldA, real_t *B, int_t ldB, real_t beta, real_t *C, int_t ldC)
{
using std::toupper;
const real_t zero(0.0);
const real_t one(1.0);
int_t i,j,l;
real_t s,t;
real_t *a,*b,*c;
transA=toupper(transA);
transB=toupper(transB);
if((transA!='N')&&(transA!='T')&&(transA!='C'))
return -1;
else if((transB!='N')&&(transB!='T')&&(transB!='C'))
return -2;
else if(m<0)
return -3;
else if(n<0)
return -4;
else if(k<0)
return -5;
else if(ldA<((transA!='N')?k:m))
return -8;
else if(ldB<((transB!='N')?n:k))
return -10;
else if(ldC<m)
return -13;
else if((m==0)||(n==0)||(((alpha==zero)||(k==0))&&(beta==one)))
return 0;
if(alpha==zero)
{
c=C;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
c[i]*=beta;
c+=ldC;
}
}
else if((transA=='N')&&(transB=='N'))
{
c=C;
b=B;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
c[i]*=beta;
a=A;
for(l=0;l<k;l++)
{
for(i=0;i<m;i++)
{
c[i]+=alpha*b[l]*a[i];
}
a+=ldA;
}
b+=ldB;
c+=ldC;
}
}
else if((transA!='N')&&(transB=='N'))
{
b=B;
c=C;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
s=zero;
for(l=0;l<k;l++)
{
s+=a[l]*b[l];
}
c[i]=alpha*s+beta*c[i];
a+=ldA;
}
b+=ldB;
c+=ldC;
}
}
else if((transA=='N')&&(transB!='N'))
{
c=C;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
c[i]*=beta;
a=A;
b=B;
for(l=0;l<k;l++)
{
t=alpha*b[j];
for(i=0;i<m;i++)
{
c[i]+=t*a[i];
}
a+=ldA;
b+=ldB;
}
c+=ldC;
}
}
else
{
c=C;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
s=zero;
b=B;
for(l=0;l<k;l++)
{
s+=a[l]*b[j];
b+=ldB;
}
c[i]=alpha*s+beta*c[i];
a+=ldA;
}
c+=ldC;
}
}
return 0;
}
/// @brief Computes products of complex matrices.
///
/// For complex matrices A,B,C and complex scalars alpha, beta
///
/// C := alpha * op(A) * op(B) + beta * C
///
/// is calculated, where op(X) = X, X' or X.'.
/// @return 0 if success.
/// @return -i if the ith argument is invalid.
/// @tparam real_t Floating point type.
/// @param transA Specifies whether op(A)=A, A.' or A' as follows:
///
/// if transA = 'N' or 'n' then op(A)=A
/// if transA = 'T' or 't' then op(A)=A.'
/// if transA = 'C' or 'c' then op(A)=A'
///
/// @param transB Specifies whether op(B)=B, B.' or B' as follows:
///
/// if transB = 'N' or 'n' then op(B)=B
/// if transB = 'T' or 't' then op(B)=B.'
/// if transB = 'C' or 'c' then op(B)=B'
///
/// @param m The number of rows of the matrices C and op(A). m>=0
/// @param n The number of columns of the matrices C and op(B). n>=0
/// @param k The number of columns of the matrix op(A), and the number of rows of the matrix op(B). k>=0
/// @param alpha Complex scalar.
/// @param A Pointer to complex matrix A, where op(A) is m-by-k.
/// @param ldA Column length of the matrix A. If transA='N' or 'n', ldA>=m; otherwise, ldA>=k.
/// @param B Pointer to complex matrix B, where op(B) is k-by-n.
/// @param ldB Column length of the matrix B. If transB='N' or 'n', ldB>=k; otherwise, ldA>=n.
/// @param beta Complex scalar.
/// @param C Pointer to complex matrix C, where C is m-by-n.
/// @param ldC Column length of the matrix C. ldC>=m.
/// @ingroup BLAS
template<typename real_t>
int GEMM(char transA, char transB, int_t m, int_t n, int_t k, complex<real_t> alpha, complex<real_t> *A, int_t ldA, complex<real_t> *B, int_t ldB, complex<real_t> beta, complex<real_t> *C, int_t ldC)
{
using std::conj;
using std::toupper;
const complex<real_t> zero(0.0,0.0);
const complex<real_t> one(1.0,0.0);
int_t i,j,l;
complex<real_t> *a,*b,*c;
complex<real_t> s,t;
transA=toupper(transA);
transB=toupper(transB);
if((transA!='N')&&(transA!='T')&&(transA!='C'))
return -1;
else if((transB!='N')&&(transB!='T')&&(transB!='C'))
return -2;
else if(m<0)
return -3;
else if(n<0)
return -4;
else if(k<0)
return -5;
else if(ldA<((transA!='N')?k:m))
return -8;
else if(ldB<((transB!='N')?n:k))
return -10;
else if(ldC<m)
return -13;
else if((m==0)||(n==0)||(((alpha==zero)||(k==0))&&(beta==one)))
return 0;
if(alpha==zero)
{
c=C;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
c[i]*=beta;
c+=ldC;
}
}
else if((transA=='N')&&(transB=='N'))
{
c=C;
b=B;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
c[i]*=beta;
a=A;
for(l=0;l<k;l++)
{
for(i=0;i<m;i++)
{
c[i]+=alpha*b[l]*a[i];
}
a+=ldA;
}
b+=ldB;
c+=ldC;
}
}
else if((transA=='T')&&(transB=='N'))
{
b=B;
c=C;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
s=zero;
for(l=0;l<k;l++)
{
s+=a[l]*b[l];
}
c[i]=alpha*s+beta*c[i];
a+=ldA;
}
b+=ldB;
c+=ldC;
}
}
else if((transA=='C')&&(transB=='N'))
{
b=B;
c=C;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
s=zero;
for(l=0;l<k;l++)
{
s+=conj(a[l])*b[l];
}
c[i]=alpha*s+beta*c[i];
a+=ldA;
}
b+=ldB;
c+=ldC;
}
}
else if((transA=='N')&&(transB=='T'))
{
c=C;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
c[i]*=beta;
a=A;
b=B;
for(l=0;l<k;l++)
{
t=alpha*b[j];
for(i=0;i<m;i++)
{
c[i]+=t*a[i];
}
a+=ldA;
b+=ldB;
}
c+=ldC;
}
}
else if((transA=='N')&&(transB=='C'))
{
c=C;
for(j=0;j<n;j++)
{
for(i=0;i<m;i++)
c[i]*=beta;
a=A;
b=B;
for(l=0;l<k;l++)
{
t=alpha*conj(b[j]);
for(i=0;i<m;i++)
{
c[i]+=t*a[i];
}
a+=ldA;
b+=ldB;
}
c+=ldC;
}
}
else if((transA=='T')&&(transB=='T'))
{
c=C;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
s=zero;
b=B;
for(l=0;l<k;l++)
{
s+=a[l]*b[j];
b+=ldB;
}
c[i]=alpha*s+beta*c[i];
a+=ldA;
}
c+=ldC;
}
}
else if((transA=='C')&&(transB=='T'))
{
c=C;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
s=zero;
b=B;
for(l=0;l<k;l++)
{
s+=conj(a[l])*b[j];
b+=ldB;
}
c[i]=alpha*s+beta*c[i];
a+=ldA;
}
c+=ldC;
}
}
else if((transA=='T')&&(transB=='C'))
{
c=C;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
s=zero;
b=B;
for(l=0;l<k;l++)
{
s+=a[l]*conj(b[j]);
b+=ldB;
}
c[i]=alpha*s+beta*c[i];
a+=ldA;
}
c+=ldC;
}
}
else if((transA=='C')&&(transB=='C'))
{
c=C;
for(j=0;j<n;j++)
{
a=A;
for(i=0;i<m;i++)
{
s=zero;
b=B;
for(l=0;l<k;l++)
{
s+=conj(a[l])*conj(b[j]);
b+=ldB;
}
c[i]=alpha*s+beta*c[i];
a+=ldA;
}
c+=ldC;
}
}
return 0;
}
#ifdef __latl_cblas
#include <cblas.h>
template<> int GEMM<float>(char transA, char transB, int_t m, int_t n, int_t k, float alpha, float *A, int_t ldA, float *B, int_t ldB, float beta, float *C, int_t ldC)
{
transA=toupper(transA);
transB=toupper(transB);
if((transA!='N')&&(transA!='T')&&(transA!='C'))
return -1;
else if((transB!='N')&&(transB!='T')&&(transB!='C'))
return -2;
else if(m<0)
return -3;
else if(n<0)
return -4;
else if(k<0)
return -5;
else if(ldA<((transA!='N')?k:m))
return -8;
else if(ldB<((transB!='N')?n:k))
return -10;
else if(ldC<m)
return -13;
const CBLAS_TRANSPOSE TransA=(transA=='N')?CblasNoTrans:((transA=='T')?CblasTrans:CblasConjTrans);
const CBLAS_TRANSPOSE TransB=(transB=='N')?CblasNoTrans:((transB=='T')?CblasTrans:CblasConjTrans);
cblas_sgemm(CblasColMajor,TransA,TransB,m,n,k,alpha,A,ldA,B,ldB,beta,C,ldC);
return 0;
}
template<> int GEMM<double>(char transA, char transB, int_t m, int_t n, int_t k, double alpha, double *A, int_t ldA, double *B, int_t ldB, double beta, double *C, int_t ldC)
{
transA=toupper(transA);
transB=toupper(transB);
if((transA!='N')&&(transA!='T')&&(transA!='C'))
return -1;
else if((transB!='N')&&(transB!='T')&&(transB!='C'))
return -2;
else if(m<0)
return -3;
else if(n<0)
return -4;
else if(k<0)
return -5;
else if(ldA<((transA!='N')?k:m))
return -8;
else if(ldB<((transB!='N')?n:k))
return -10;
else if(ldC<m)
return -13;
const CBLAS_TRANSPOSE TransA=(transA=='N')?CblasNoTrans:((transA=='T')?CblasTrans:CblasConjTrans);
const CBLAS_TRANSPOSE TransB=(transB=='N')?CblasNoTrans:((transB=='T')?CblasTrans:CblasConjTrans);
cblas_dgemm(CblasColMajor,TransA,TransB,m,n,k,alpha,A,ldA,B,ldB,beta,C,ldC);
return 0;
}
template<> int GEMM<float>(char transA, char transB, int_t m, int_t n, int_t k, complex<float> alpha, complex<float> *A, int_t ldA, complex<float> *B, int_t ldB, complex<float> beta, complex<float> *C, int_t ldC)
{
transA=toupper(transA);
transB=toupper(transB);
if((transA!='N')&&(transA!='T')&&(transA!='C'))
return -1;
else if((transB!='N')&&(transB!='T')&&(transB!='C'))
return -2;
else if(m<0)
return -3;
else if(n<0)
return -4;
else if(k<0)
return -5;
else if(ldA<((transA!='N')?k:m))
return -8;
else if(ldB<((transB!='N')?n:k))
return -10;
else if(ldC<m)
return -13;
const CBLAS_TRANSPOSE TransA=(transA=='N')?CblasNoTrans:((transA=='T')?CblasTrans:CblasConjTrans);
const CBLAS_TRANSPOSE TransB=(transB=='N')?CblasNoTrans:((transB=='T')?CblasTrans:CblasConjTrans);
cblas_cgemm(CblasColMajor,TransA,TransB,m,n,k,&alpha,A,ldA,B,ldB,&beta,C,ldC);
return 0;
}
template<> int GEMM<double>(char transA, char transB, int_t m, int_t n, int_t k, complex<double> alpha, complex<double> *A, int_t ldA, complex<double> *B, int_t ldB, complex<double> beta, complex<double> *C, int_t ldC)
{
transA=toupper(transA);
transB=toupper(transB);
if((transA!='N')&&(transA!='T')&&(transA!='C'))
return -1;
else if((transB!='N')&&(transB!='T')&&(transB!='C'))
return -2;
else if(m<0)
return -3;
else if(n<0)
return -4;
else if(k<0)
return -5;
else if(ldA<((transA!='N')?k:m))
return -8;
else if(ldB<((transB!='N')?n:k))
return -10;
else if(ldC<m)
return -13;
const CBLAS_TRANSPOSE TransA=(transA=='N')?CblasNoTrans:((transA=='T')?CblasTrans:CblasConjTrans);
const CBLAS_TRANSPOSE TransB=(transB=='N')?CblasNoTrans:((transB=='T')?CblasTrans:CblasConjTrans);
cblas_zgemm(CblasColMajor,TransA,TransB,m,n,k,&alpha,A,ldA,B,ldB,&beta,C,ldC);
return 0;
}
#endif
}
#endif
| {
"alphanum_fraction": 0.4126566416,
"avg_line_length": 27.3287671233,
"ext": "h",
"hexsha": "fdf1e9311356e182ebf2da156a4efcb509f6eba5",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-02-09T23:18:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-01T06:46:36.000Z",
"max_forks_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "langou/latl",
"max_forks_repo_path": "include/gemm.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492",
"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": "langou/latl",
"max_issues_repo_path": "include/gemm.h",
"max_line_length": 221,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "df838fb44a1ef5c77b57bf60bd46eaeff8db3492",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "langou/latl",
"max_stars_repo_path": "include/gemm.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-09T23:18:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-13T09:10:11.000Z",
"num_tokens": 4788,
"size": 15960
} |
/* monte/miser.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Michael Booth
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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.
*/
/* MISER. Based on the algorithm described in the following article,
W.H. Press, G.R. Farrar, "Recursive Stratified Sampling for
Multidimensional Monte Carlo Integration", Computers in Physics,
v4 (1990), pp190-195.
*/
/* Author: MJB */
/* Modified by Brian Gough 12/2000 */
#include <config.h>
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_miser.h>
static int
estimate_corrmc (gsl_monte_function * f,
const double xl[], const double xu[],
size_t dim, size_t calls,
gsl_rng * r,
gsl_monte_miser_state * state,
double *result, double *abserr,
const double xmid[], double sigma_l[], double sigma_r[]);
int
gsl_monte_miser_integrate (gsl_monte_function * f,
const double xl[], const double xu[],
size_t dim, size_t calls,
gsl_rng * r,
gsl_monte_miser_state * state,
double *result, double *abserr)
{
size_t n, estimate_calls, calls_l, calls_r;
const size_t min_calls = state->min_calls;
size_t i;
size_t i_bisect;
int found_best;
double res_est = 0, err_est = 0;
double res_r = 0, err_r = 0, res_l = 0, err_l = 0;
double xbi_l, xbi_m, xbi_r, s;
double vol;
double weight_l, weight_r;
double *x = state->x;
double *xmid = state->xmid;
double *sigma_l = state->sigma_l, *sigma_r = state->sigma_r;
if (dim != state->dim)
{
GSL_ERROR ("number of dimensions must match allocated size", GSL_EINVAL);
}
for (i = 0; i < dim; i++)
{
if (xu[i] <= xl[i])
{
GSL_ERROR ("xu must be greater than xl", GSL_EINVAL);
}
if (xu[i] - xl[i] > GSL_DBL_MAX)
{
GSL_ERROR ("Range of integration is too large, please rescale",
GSL_EINVAL);
}
}
if (state->alpha < 0)
{
GSL_ERROR ("alpha must be non-negative", GSL_EINVAL);
}
/* Compute volume */
vol = 1;
for (i = 0; i < dim; i++)
{
vol *= xu[i] - xl[i];
}
if (calls < state->min_calls_per_bisection)
{
double m = 0.0, q = 0.0;
if (calls < 2)
{
GSL_ERROR ("insufficient calls for subvolume", GSL_EFAILED);
}
for (n = 0; n < calls; n++)
{
/* Choose a random point in the integration region */
for (i = 0; i < dim; i++)
{
x[i] = xl[i] + gsl_rng_uniform_pos (r) * (xu[i] - xl[i]);
}
{
double fval = GSL_MONTE_FN_EVAL (f, x);
/* recurrence for mean and variance */
double d = fval - m;
m += d / (n + 1.0);
q += d * d * (n / (n + 1.0));
}
}
*result = vol * m;
*abserr = vol * sqrt (q / (calls * (calls - 1.0)));
return GSL_SUCCESS;
}
estimate_calls = GSL_MAX (min_calls, calls * (state->estimate_frac));
if (estimate_calls < 4 * dim)
{
GSL_ERROR ("insufficient calls to sample all halfspaces", GSL_ESANITY);
}
/* Flip coins to bisect the integration region with some fuzz */
for (i = 0; i < dim; i++)
{
s = (gsl_rng_uniform (r) - 0.5) >= 0.0 ? state->dither : -state->dither;
state->xmid[i] = (0.5 + s) * xl[i] + (0.5 - s) * xu[i];
}
/* The idea is to chose the direction to bisect based on which will
give the smallest total variance. We could (and may do so later)
use MC to compute these variances. But the NR guys simply estimate
the variances by finding the min and max function values
for each half-region for each bisection. */
estimate_corrmc (f, xl, xu, dim, estimate_calls,
r, state, &res_est, &err_est, xmid, sigma_l, sigma_r);
/* We have now used up some calls for the estimation */
calls -= estimate_calls;
/* Now find direction with the smallest total "variance" */
{
double best_var = GSL_DBL_MAX;
double beta = 2.0 / (1.0 + state->alpha);
found_best = 0;
i_bisect = 0;
weight_l = weight_r = 1.0;
for (i = 0; i < dim; i++)
{
if (sigma_l[i] >= 0 && sigma_r[i] >= 0)
{
/* estimates are okay */
double var = pow (sigma_l[i], beta) + pow (sigma_r[i], beta);
if (var <= best_var)
{
found_best = 1;
best_var = var;
i_bisect = i;
weight_l = pow (sigma_l[i], beta);
weight_r = pow (sigma_r[i], beta);
}
}
else
{
if (sigma_l[i] < 0)
{
GSL_ERROR ("no points in left-half space!", GSL_ESANITY);
}
if (sigma_r[i] < 0)
{
GSL_ERROR ("no points in right-half space!", GSL_ESANITY);
}
}
}
}
if (!found_best)
{
/* All estimates were the same, so chose a direction at random */
i_bisect = gsl_rng_uniform_int (r, dim);
}
xbi_l = xl[i_bisect];
xbi_m = xmid[i_bisect];
xbi_r = xu[i_bisect];
/* Get the actual fractional sizes of the two "halves", and
distribute the remaining calls among them */
{
double fraction_l = fabs ((xbi_m - xbi_l) / (xbi_r - xbi_l));
double fraction_r = 1 - fraction_l;
double a = fraction_l * weight_l;
double b = fraction_r * weight_r;
calls_l = min_calls + (calls - 2 * min_calls) * a / (a + b);
calls_r = min_calls + (calls - 2 * min_calls) * b / (a + b);
}
/* Compute the integral for the left hand side of the bisection */
/* Due to the recursive nature of the algorithm we must allocate
some new memory for each recursive call */
{
int status;
double *xu_tmp = (double *) malloc (dim * sizeof (double));
if (xu_tmp == 0)
{
GSL_ERROR_VAL ("out of memory for left workspace", GSL_ENOMEM, 0);
}
for (i = 0; i < dim; i++)
{
xu_tmp[i] = xu[i];
}
xu_tmp[i_bisect] = xbi_m;
status = gsl_monte_miser_integrate (f, xl, xu_tmp,
dim, calls_l, r, state,
&res_l, &err_l);
free (xu_tmp);
if (status != GSL_SUCCESS)
{
return status;
}
}
/* Compute the integral for the right hand side of the bisection */
{
int status;
double *xl_tmp = (double *) malloc (dim * sizeof (double));
if (xl_tmp == 0)
{
GSL_ERROR_VAL ("out of memory for right workspace", GSL_ENOMEM, 0);
}
for (i = 0; i < dim; i++)
{
xl_tmp[i] = xl[i];
}
xl_tmp[i_bisect] = xbi_m;
status = gsl_monte_miser_integrate (f, xl_tmp, xu,
dim, calls_r, r, state,
&res_r, &err_r);
free (xl_tmp);
if (status != GSL_SUCCESS)
{
return status;
}
}
*result = res_l + res_r;
*abserr = sqrt (err_l * err_l + err_r * err_r);
return GSL_SUCCESS;
}
gsl_monte_miser_state *
gsl_monte_miser_alloc (size_t dim)
{
gsl_monte_miser_state *s =
(gsl_monte_miser_state *) malloc (sizeof (gsl_monte_miser_state));
if (s == 0)
{
GSL_ERROR_VAL ("failed to allocate space for miser state struct",
GSL_ENOMEM, 0);
}
s->x = (double *) malloc (dim * sizeof (double));
if (s->x == 0)
{
free (s);
GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
}
s->xmid = (double *) malloc (dim * sizeof (double));
if (s->xmid == 0)
{
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for xmid", GSL_ENOMEM, 0);
}
s->sigma_l = (double *) malloc (dim * sizeof (double));
if (s->sigma_l == 0)
{
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for sigma_l", GSL_ENOMEM, 0);
}
s->sigma_r = (double *) malloc (dim * sizeof (double));
if (s->sigma_r == 0)
{
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for sigma_r", GSL_ENOMEM, 0);
}
s->fmax_l = (double *) malloc (dim * sizeof (double));
if (s->fmax_l == 0)
{
free (s->sigma_r);
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for fmax_l", GSL_ENOMEM, 0);
}
s->fmax_r = (double *) malloc (dim * sizeof (double));
if (s->fmax_r == 0)
{
free (s->fmax_l);
free (s->sigma_r);
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for fmax_r", GSL_ENOMEM, 0);
}
s->fmin_l = (double *) malloc (dim * sizeof (double));
if (s->fmin_l == 0)
{
free (s->fmax_r);
free (s->fmax_l);
free (s->sigma_r);
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for fmin_l", GSL_ENOMEM, 0);
}
s->fmin_r = (double *) malloc (dim * sizeof (double));
if (s->fmin_r == 0)
{
free (s->fmin_l);
free (s->fmax_r);
free (s->fmax_l);
free (s->sigma_r);
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for fmin_r", GSL_ENOMEM, 0);
}
s->fsum_l = (double *) malloc (dim * sizeof (double));
if (s->fsum_l == 0)
{
free (s->fmin_r);
free (s->fmin_l);
free (s->fmax_r);
free (s->fmax_l);
free (s->sigma_r);
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for fsum_l", GSL_ENOMEM, 0);
}
s->fsum_r = (double *) malloc (dim * sizeof (double));
if (s->fsum_r == 0)
{
free (s->fsum_l);
free (s->fmin_r);
free (s->fmin_l);
free (s->fmax_r);
free (s->fmax_l);
free (s->sigma_r);
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for fsum_r", GSL_ENOMEM, 0);
}
s->fsum2_l = (double *) malloc (dim * sizeof (double));
if (s->fsum2_l == 0)
{
free (s->fsum_r);
free (s->fsum_l);
free (s->fmin_r);
free (s->fmin_l);
free (s->fmax_r);
free (s->fmax_l);
free (s->sigma_r);
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for fsum2_l", GSL_ENOMEM, 0);
}
s->fsum2_r = (double *) malloc (dim * sizeof (double));
if (s->fsum2_r == 0)
{
free (s->fsum2_l);
free (s->fsum_r);
free (s->fsum_l);
free (s->fmin_r);
free (s->fmin_l);
free (s->fmax_r);
free (s->fmax_l);
free (s->sigma_r);
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for fsum2_r", GSL_ENOMEM, 0);
}
s->hits_r = (size_t *) malloc (dim * sizeof (size_t));
if (s->hits_r == 0)
{
free (s->fsum2_r);
free (s->fsum2_l);
free (s->fsum_r);
free (s->fsum_l);
free (s->fmin_r);
free (s->fmin_l);
free (s->fmax_r);
free (s->fmax_l);
free (s->sigma_r);
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for fsum2_r", GSL_ENOMEM, 0);
}
s->hits_l = (size_t *) malloc (dim * sizeof (size_t));
if (s->hits_l == 0)
{
free (s->hits_r);
free (s->fsum2_r);
free (s->fsum2_l);
free (s->fsum_r);
free (s->fsum_l);
free (s->fmin_r);
free (s->fmin_l);
free (s->fmax_r);
free (s->fmax_l);
free (s->sigma_r);
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for fsum2_r", GSL_ENOMEM, 0);
}
s->dim = dim;
gsl_monte_miser_init (s);
return s;
}
int
gsl_monte_miser_init (gsl_monte_miser_state * s)
{
/* We use 8 points in each halfspace to estimate the variance. There are
2*dim halfspaces. A variance estimate requires a minimum of 2 points. */
s->min_calls = 16 * s->dim;
s->min_calls_per_bisection = 32 * s->min_calls;
s->estimate_frac = 0.1;
s->alpha = 2.0;
s->dither = 0.0;
return GSL_SUCCESS;
}
void
gsl_monte_miser_free (gsl_monte_miser_state * s)
{
free (s->hits_r);
free (s->hits_l);
free (s->fsum2_r);
free (s->fsum2_l);
free (s->fsum_r);
free (s->fsum_l);
free (s->fmin_r);
free (s->fmin_l);
free (s->fmax_r);
free (s->fmax_l);
free (s->sigma_r);
free (s->sigma_l);
free (s->xmid);
free (s->x);
free (s);
}
static int
estimate_corrmc (gsl_monte_function * f,
const double xl[], const double xu[],
size_t dim, size_t calls,
gsl_rng * r,
gsl_monte_miser_state * state,
double *result, double *abserr,
const double xmid[], double sigma_l[], double sigma_r[])
{
size_t i, n;
double *x = state->x;
double *fsum_l = state->fsum_l;
double *fsum_r = state->fsum_r;
double *fsum2_l = state->fsum2_l;
double *fsum2_r = state->fsum2_r;
size_t *hits_l = state->hits_l;
size_t *hits_r = state->hits_r;
double m = 0.0, q = 0.0;
double vol = 1.0;
for (i = 0; i < dim; i++)
{
vol *= xu[i] - xl[i];
hits_l[i] = hits_r[i] = 0;
fsum_l[i] = fsum_r[i] = 0.0;
fsum2_l[i] = fsum2_r[i] = 0.0;
sigma_l[i] = sigma_r[i] = -1;
}
for (n = 0; n < calls; n++)
{
double fval;
unsigned int j = (n/2) % dim;
unsigned int side = (n % 2);
for (i = 0; i < dim; i++)
{
double z = gsl_rng_uniform_pos (r) ;
if (i != j)
{
x[i] = xl[i] + z * (xu[i] - xl[i]);
}
else
{
if (side == 0)
{
x[i] = xmid[i] + z * (xu[i] - xmid[i]);
}
else
{
x[i] = xl[i] + z * (xmid[i] - xl[i]);
}
}
}
fval = GSL_MONTE_FN_EVAL (f, x);
/* recurrence for mean and variance */
{
double d = fval - m;
m += d / (n + 1.0);
q += d * d * (n / (n + 1.0));
}
/* compute the variances on each side of the bisection */
for (i = 0; i < dim; i++)
{
if (x[i] <= xmid[i])
{
fsum_l[i] += fval;
fsum2_l[i] += fval * fval;
hits_l[i]++;
}
else
{
fsum_r[i] += fval;
fsum2_r[i] += fval * fval;
hits_r[i]++;
}
}
}
for (i = 0; i < dim; i++)
{
double fraction_l = (xmid[i] - xl[i]) / (xu[i] - xl[i]);
if (hits_l[i] > 0)
{
fsum_l[i] /= hits_l[i];
sigma_l[i] = sqrt (fsum2_l[i] - fsum_l[i] * fsum_l[i] / hits_l[i]);
sigma_l[i] *= fraction_l * vol / hits_l[i];
}
if (hits_r[i] > 0)
{
fsum_r[i] /= hits_r[i];
sigma_r[i] = sqrt (fsum2_r[i] - fsum_r[i] * fsum_r[i] / hits_r[i]);
sigma_r[i] *= (1 - fraction_l) * vol / hits_r[i];
}
}
*result = vol * m;
if (calls < 2)
{
*abserr = GSL_POSINF;
}
else
{
*abserr = vol * sqrt (q / (calls * (calls - 1.0)));
}
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.551511254,
"avg_line_length": 22.8005865103,
"ext": "c",
"hexsha": "4e5932aa1d58da2b8fa0045867a0b9a04d8aa5e8",
"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/monte/miser.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/monte/miser.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/monte/miser.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": 5100,
"size": 15550
} |
/**
* @file MeshAdaptors.h
*
* @brief This file contains mesh <-> Eigen matrix adaptors
*
* @author Stefan Reinhold
* @copyright Copyright (C) 2018 Stefan Reinhold -- All Rights Reserved.
* You may use, distribute and modify this code under the terms of
* the AFL 3.0 license; see LICENSE for full license details.
*/
#pragma once
#include "Mesh.h"
#include <Eigen/Core>
#include <gsl/gsl>
namespace CortidQCT {
namespace Internal {
namespace Adaptor {
template <class T>
inline Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic> const>
vertexMap(Mesh<T> const &mesh) {
return mesh.withUnsafeVertexPointer([&mesh](auto const *ptr) {
return Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic> const>{
ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};
});
}
template <class T>
inline Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic>>
vertexMap(Mesh<T> &mesh) {
return mesh.withUnsafeVertexPointer([&mesh](auto *ptr) {
return Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic>>{
ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};
});
}
template <class T>
inline Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic> const>
vertexNormalMap(Mesh<T> const &mesh) {
return mesh.withUnsafeVertexNormalPointer([&mesh](auto const *ptr) {
return Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic> const>{
ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};
});
}
template <class T>
inline Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic>>
vertexNormalMap(Mesh<T> &mesh) {
return mesh.withUnsafeVertexNormalPointer([&mesh](auto *ptr) {
return Eigen::Map<Eigen::Matrix<T, 3, Eigen::Dynamic>>{
ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};
});
}
template <class T>
inline Eigen::Map<
Eigen::Matrix<typename Mesh<T>::Index, 3, Eigen::Dynamic> const>
indexMap(Mesh<T> const &mesh) {
using S = typename Mesh<T>::Index;
return mesh.withUnsafeIndexPointer([&mesh](auto const *ptr) {
return Eigen::Map<Eigen::Matrix<S, 3, Eigen::Dynamic> const>{
ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.triangleCount())};
});
}
template <class T>
inline Eigen::Map<Eigen::Matrix<typename Mesh<T>::Index, 3, Eigen::Dynamic>>
indexMap(Mesh<T> &mesh) {
using S = typename Mesh<T>::Index;
return mesh.withUnsafeIndexPointer([&mesh](auto *ptr) {
return Eigen::Map<Eigen::Matrix<S, 3, Eigen::Dynamic>>{
ptr, 3, gsl::narrow_cast<Eigen::Index>(mesh.triangleCount())};
});
}
template <class T>
inline Eigen::Map<
Eigen::Matrix<typename Mesh<T>::Label, Eigen::Dynamic, 1> const>
labelMap(Mesh<T> const &mesh) {
using S = typename Mesh<T>::Label;
return mesh.withUnsafeLabelPointer([&mesh](auto const *ptr) {
return Eigen::Map<Eigen::Matrix<S, Eigen::Dynamic, 1> const>{
ptr, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};
});
}
template <class T>
inline Eigen::Map<Eigen::Matrix<typename Mesh<T>::Label, Eigen::Dynamic, 1>>
labelMap(Mesh<T> &mesh) {
using S = typename Mesh<T>::Label;
return mesh.withUnsafeLabelPointer([&mesh](auto *ptr) {
return Eigen::Map<Eigen::Matrix<S, Eigen::Dynamic, 1>>{
ptr, gsl::narrow_cast<Eigen::Index>(mesh.vertexCount())};
});
}
} // namespace Adaptor
} // namespace Internal
} // namespace CortidQCT
| {
"alphanum_fraction": 0.6707905854,
"avg_line_length": 31.8653846154,
"ext": "h",
"hexsha": "88404ba1bc3b6faae517d0bc40ff7f4a037e649a",
"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": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59",
"max_forks_repo_licenses": [
"AFL-3.0"
],
"max_forks_repo_name": "ithron/CortidQCT",
"max_forks_repo_path": "lib/MeshAdaptors.h",
"max_issues_count": 28,
"max_issues_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59",
"max_issues_repo_issues_event_max_datetime": "2021-04-22T08:11:33.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-10-23T10:51:36.000Z",
"max_issues_repo_licenses": [
"AFL-3.0"
],
"max_issues_repo_name": "ithron/CortidQCT",
"max_issues_repo_path": "lib/MeshAdaptors.h",
"max_line_length": 77,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5b74c18a3cb7e16541b0cef16ec794c33ef9fa59",
"max_stars_repo_licenses": [
"AFL-3.0"
],
"max_stars_repo_name": "ithron/CortidQCT",
"max_stars_repo_path": "lib/MeshAdaptors.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-21T17:30:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-21T17:30:23.000Z",
"num_tokens": 937,
"size": 3314
} |
#ifndef VEC3_H
#define VEC3_H
#include <cmath>
#include <iostream>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
// you need to add the following libraries to your project : gsl, gslcblas
class Vec3 {
private:
float mVals[3];
public:
Vec3() {}
Vec3( float x , float y , float z ) {
mVals[0] = x; mVals[1] = y; mVals[2] = z;
}
float & operator [] (unsigned int c) { return mVals[c]; }
float operator [] (unsigned int c) const { return mVals[c]; }
void operator = (Vec3 const & other) {
mVals[0] = other[0] ; mVals[1] = other[1]; mVals[2] = other[2];
}
float squareLength() const {
return mVals[0]*mVals[0] + mVals[1]*mVals[1] + mVals[2]*mVals[2];
}
float length() const { return sqrt( squareLength() ); }
void normalize() { float L = length(); mVals[0] /= L; mVals[1] /= L; mVals[2] /= L; }
static float dot( Vec3 const & a , Vec3 const & b ) {
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
}
static Vec3 cross( Vec3 const & a , Vec3 const & b ) {
return Vec3( a[1]*b[2] - a[2]*b[1] ,
a[2]*b[0] - a[0]*b[2] ,
a[0]*b[1] - a[1]*b[0] );
}
void operator += (Vec3 const & other) {
mVals[0] += other[0];
mVals[1] += other[1];
mVals[2] += other[2];
}
void operator -= (Vec3 const & other) {
mVals[0] -= other[0];
mVals[1] -= other[1];
mVals[2] -= other[2];
}
void operator *= (float s) {
mVals[0] *= s;
mVals[1] *= s;
mVals[2] *= s;
}
void operator /= (float s) {
mVals[0] /= s;
mVals[1] /= s;
mVals[2] /= s;
}
static Vec3 Rand(float magnitude = 1.f) {
return Vec3( magnitude * (-1.f + 2.f * rand() / (float)(RAND_MAX)) , magnitude * (-1.f + 2.f * rand() / (float)(RAND_MAX)) , magnitude * (-1.f + 2.f * rand() / (float)(RAND_MAX)) );
}
Vec3 getOrthogonal() const {
// CAREFUL ! THE NORM IS NOT PRESERVED !!!!
if( mVals[0] == 0 ) {
return Vec3( 0 , mVals[2] , -mVals[1] );
}
else if( mVals[1] == 0 ) {
return Vec3( mVals[2] , 0 , -mVals[0] );
}
return Vec3( mVals[1] , -mVals[0] , 0 );
}
};
static inline Vec3 operator + (Vec3 const & a , Vec3 const & b) {
return Vec3(a[0]+b[0] , a[1]+b[1] , a[2]+b[2]);
}
static inline Vec3 operator - (Vec3 const & a , Vec3 const & b) {
return Vec3(a[0]-b[0] , a[1]-b[1] , a[2]-b[2]);
}
static inline Vec3 operator * (float a , Vec3 const & b) {
return Vec3(a*b[0] , a*b[1] , a*b[2]);
}
static inline Vec3 operator / (Vec3 const & a , float b) {
return Vec3(a[0]/b , a[1]/b , a[2]/b);
}
static inline std::ostream & operator << (std::ostream & s , Vec3 const & p) {
s << p[0] << " " << p[1] << " " << p[2];
return s;
}
static inline std::istream & operator >> (std::istream & s , Vec3 & p) {
s >> p[0] >> p[1] >> p[2];
return s;
}
class Mat3
{
public:
//////////// CONSTRUCTORS //////////////
Mat3()
{
vals[0] = 0;
vals[1] = 0;
vals[2] = 0;
vals[3] = 0;
vals[4] = 0;
vals[5] = 0;
vals[6] = 0;
vals[7] = 0;
vals[8] = 0;
}
Mat3( float v1 , float v2 , float v3 , float v4 , float v5 , float v6 , float v7 , float v8 , float v9)
{
vals[0] = v1;
vals[1] = v2;
vals[2] = v3;
vals[3] = v4;
vals[4] = v5;
vals[5] = v6;
vals[6] = v7;
vals[7] = v8;
vals[8] = v9;
}
Mat3( const Mat3 & m )
{
for(int i = 0 ; i < 3 ; ++i )
for(int j = 0 ; j < 3 ; ++j )
(*this)(i,j) = m(i,j);
}
bool isnan() const {
return std::isnan(vals[0]) || std::isnan(vals[1]) || std::isnan(vals[2])
|| std::isnan(vals[3]) || std::isnan(vals[4]) || std::isnan(vals[5])
|| std::isnan(vals[6]) || std::isnan(vals[7]) || std::isnan(vals[8]);
}
void operator = (const Mat3 & m)
{
for(int i = 0 ; i < 3 ; ++i )
for(int j = 0 ; j < 3 ; ++j )
(*this)(i,j) = m(i,j);
}
void operator += (const Mat3 & m)
{
for(int i = 0 ; i < 3 ; ++i )
for(int j = 0 ; j < 3 ; ++j )
(*this)(i,j) += m(i,j);
}
void operator -= (const Mat3 & m)
{
for(int i = 0 ; i < 3 ; ++i )
for(int j = 0 ; j < 3 ; ++j )
(*this)(i,j) -= m(i,j);
}
void operator /= (double s)
{
for( unsigned int c = 0 ; c < 9 ; ++c )
vals[c] /= s;
}
Mat3 operator - (const Mat3 & m2)
{
return Mat3( (*this)(0,0)-m2(0,0) , (*this)(0,1)-m2(0,1) , (*this)(0,2)-m2(0,2) , (*this)(1,0)-m2(1,0) , (*this)(1,1)-m2(1,1) , (*this)(1,2)-m2(1,2) , (*this)(2,0)-m2(2,0) , (*this)(2,1)-m2(2,1) , (*this)(2,2)-m2(2,2) );
}
Mat3 operator + (const Mat3 & m2)
{
return Mat3( (*this)(0,0)+m2(0,0) , (*this)(0,1)+m2(0,1) , (*this)(0,2)+m2(0,2) , (*this)(1,0)+m2(1,0) , (*this)(1,1)+m2(1,1) , (*this)(1,2)+m2(1,2) , (*this)(2,0)+m2(2,0) , (*this)(2,1)+m2(2,1) , (*this)(2,2)+m2(2,2) );
}
Mat3 operator / (float s)
{
return Mat3( (*this)(0,0)/s , (*this)(0,1)/s , (*this)(0,2)/s , (*this)(1,0)/s , (*this)(1,1)/s , (*this)(1,2)/s , (*this)(2,0)/s , (*this)(2,1)/s , (*this)(2,2)/s );
}
Mat3 operator * (float s)
{
return Mat3( (*this)(0,0)*s , (*this)(0,1)*s , (*this)(0,2)*s , (*this)(1,0)*s , (*this)(1,1)*s , (*this)(1,2)*s , (*this)(2,0)*s , (*this)(2,1)*s , (*this)(2,2)*s );
}
Vec3 operator * (const Vec3 & p) // computes m.p
{
return Vec3(
(*this)(0,0)*p[0] + (*this)(0,1)*p[1] + (*this)(0,2)*p[2],
(*this)(1,0)*p[0] + (*this)(1,1)*p[1] + (*this)(1,2)*p[2],
(*this)(2,0)*p[0] + (*this)(2,1)*p[1] + (*this)(2,2)*p[2]);
}
Mat3 operator * (const Mat3 & m2)
{
return Mat3(
(*this)(0,0)*m2(0,0) + (*this)(0,1)*m2(1,0) + (*this)(0,2)*m2(2,0) ,
(*this)(0,0)*m2(0,1) + (*this)(0,1)*m2(1,1) + (*this)(0,2)*m2(2,1) ,
(*this)(0,0)*m2(0,2) + (*this)(0,1)*m2(1,2) + (*this)(0,2)*m2(2,2) ,
(*this)(1,0)*m2(0,0) + (*this)(1,1)*m2(1,0) + (*this)(1,2)*m2(2,0) ,
(*this)(1,0)*m2(0,1) + (*this)(1,1)*m2(1,1) + (*this)(1,2)*m2(2,1) ,
(*this)(1,0)*m2(0,2) + (*this)(1,1)*m2(1,2) + (*this)(1,2)*m2(2,2) ,
(*this)(2,0)*m2(0,0) + (*this)(2,1)*m2(1,0) + (*this)(2,2)*m2(2,0) ,
(*this)(2,0)*m2(0,1) + (*this)(2,1)*m2(1,1) + (*this)(2,2)*m2(2,1) ,
(*this)(2,0)*m2(0,2) + (*this)(2,1)*m2(1,2) + (*this)(2,2)*m2(2,2)
);
}
//////// ACCESS TO COORDINATES /////////
float operator () (unsigned int i , unsigned int j) const
{ return vals[3*i + j]; }
float & operator () (unsigned int i , unsigned int j)
{ return vals[3*i + j]; }
//////// BASICS /////////
inline float sqrnorm()
{
return vals[0]*vals[0] + vals[1]*vals[1] + vals[2]*vals[2]
+ vals[3]*vals[3] + vals[4]*vals[4] + vals[5]*vals[5]
+ vals[6]*vals[6] + vals[7]*vals[7] + vals[8]*vals[8];
}
inline float norm()
{ return sqrt( sqrnorm() ); }
inline float determinant() const
{
return vals[0] * ( vals[4] * vals[8] - vals[7] * vals[5] )
- vals[1] * ( vals[3] * vals[8] - vals[6] * vals[5] )
+ vals[2] * ( vals[3] * vals[7] - vals[6] * vals[4] );
}
static
Mat3 pseudoInverse( Mat3 const & m , bool & isRealInverse , double defaultValueForInverseSingularValue = 0.0 )
{
float det = m.determinant();
if( fabs(det) != 0.0 )
{
isRealInverse = true;
return Mat3( m(1,1)*m(2,2) - m(2,1)*m(1,2) , m(0,2)*m(2,1) - m(0,1)*m(2,2) , m(0,1)*m(1,2) - m(0,2)*m(1,1) ,
m(1,2)*m(2,0) - m(1,0)*m(2,2) , m(0,0)*m(2,2) - m(0,2)*m(2,0) , m(0,2)*m(1,0) - m(0,0)*m(1,2) ,
m(1,0)*m(2,1) - m(1,1)*m(2,0) , m(0,1)*m(2,0) - m(0,0)*m(2,1) , m(0,0)*m(1,1) - m(0,1)*m(1,0) ) / det ;
}
// otherwise:
isRealInverse = false;
Mat3 U ; float sx ; float sy ; float sz ; Mat3 Vt;
m.SVD(U,sx,sy,sz,Vt);
float sxInv = sx == 0.0 ? 1.0 / sx : defaultValueForInverseSingularValue;
float syInv = sy == 0.0 ? 1.0 / sy : defaultValueForInverseSingularValue;
float szInv = sz == 0.0 ? 1.0 / sz : defaultValueForInverseSingularValue;
return Vt.getTranspose() * Mat3::diag(sxInv , syInv , szInv) * U.getTranspose();
}
inline float trace() const
{ return vals[0] + vals[4] + vals[8]; }
//////// TRANSPOSE /////////
inline
void transpose()
{
float xy = vals[1] , xz = vals[2] , yz = vals[5];
vals[1] = vals[3];
vals[3] = xy;
vals[2] = vals[6];
vals[6] = xz;
vals[5] = vals[7];
vals[7] = yz;
}
Mat3 getTranspose() const
{
return Mat3(vals[0],vals[3],vals[6],vals[1],vals[4],vals[7],vals[2],vals[5],vals[8]);
}
// ---------- ROTATION <-> AXIS/ANGLE ---------- //
template< class point_t >
void getAxisAndAngleFromRotationMatrix( point_t & axis , float & angle )
{
angle = acos( (trace() - 1.f) / 2.f );
axis[0] = vals[7] - vals[5];
axis[1] = vals[2] - vals[6];
axis[2] = vals[3] - vals[1];
axis.normalize();
}
template< class point_t >
inline static
Mat3 getRotationMatrixFromAxisAndAngle( const point_t & axis , float angle )
{
Mat3 w = vectorial(axis);
return Identity() + w * std::sin(angle) + w * w * ((1.0) - std::cos(angle));
}
// ---------- STATIC STANDARD MATRICES ---------- //
inline static Mat3 Identity()
{ return Mat3(1,0,0 , 0,1,0 , 0,0,1); }
inline static Mat3 Zero()
{ return Mat3(0,0,0 , 0,0,0 , 0,0,0); }
template< typename T2 >
inline static Mat3 diag( T2 x , T2 y ,T2 z )
{ return Mat3(x,0,0 , 0,y,0 , 0,0,z); }
template< class point_t >
inline static Mat3 getFromCols(const point_t & c1 , const point_t & c2 , const point_t & c3)
{
// 0 1 2
// 3 4 5
// 6 7 8
return Mat3( c1[0] , c2[0] , c3[0] ,
c1[1] , c2[1] , c3[1] ,
c1[2] , c2[2] , c3[2] );
}
template< class point_t >
inline static Mat3 getFromRows(const point_t & r1 , const point_t & r2 , const point_t & r3)
{
// 0 1 2
// 3 4 5
// 6 7 8
return Mat3( r1[0] , r1[1] , r1[2] ,
r2[0] , r2[1] , r2[2] ,
r3[0] , r3[1] , r3[2] );
}
inline static Mat3 RandRotation()
{
Vec3 axis(-1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) ,
-1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) ,
-1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) );
axis.normalize();
float angle = 2.0 * M_PI * ((float)(rand()) / (float)( RAND_MAX ) - 0.5 );
return Mat3::getRotationMatrixFromAxisAndAngle( axis , angle );
}
inline static Mat3 RandRotation( float maxAngle )
{
Vec3 axis(-1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) ,
-1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) ,
-1.0 + 2.0* (float)(rand()) / (float)( RAND_MAX ) );
axis.normalize();
float angle = maxAngle * ((float)(rand()) / (float)( RAND_MAX ) - 0.5 );
return Mat3::getRotationMatrixFromAxisAndAngle( axis , angle );
}
inline static Mat3 RandRotation( Vec3 twistAxis , double maxTwist , double maxRotation )
{
twistAxis.normalize();
Vec3 u = twistAxis.getOrthogonal();
u.normalize();
const Vec3 & v = Vec3::cross(u,twistAxis);
double uv_axis_angle = 2.0*M_PI * (double)(rand()) / (double)(RAND_MAX);
const Vec3 & uv = cos(uv_axis_angle)*u + sin(uv_axis_angle)*v;
double rotation_angle = maxRotation * ( ( 2.0 *(double)(rand()) / (double)(RAND_MAX) ) - 1.0 );
double twist_angle = maxTwist * ( ( 2.0 *(double)(rand()) / (double)(RAND_MAX) ) - 1.0 );
return Mat3::getRotationMatrixFromAxisAndAngle(uv , rotation_angle) * Mat3::getRotationMatrixFromAxisAndAngle(twistAxis , twist_angle);
}
void SVD( Mat3 & U , float & sx , float & sy , float & sz , Mat3 & Vt ) const
{
gsl_matrix * u = gsl_matrix_alloc(3,3);
for(unsigned int i = 0 ; i < 3; ++i)
for(unsigned int j = 0 ; j < 3; ++j)
gsl_matrix_set( u , i , j , (*this)(i,j) );
gsl_matrix * v = gsl_matrix_alloc(3,3);
gsl_vector * s = gsl_vector_alloc(3);
gsl_vector * work = gsl_vector_alloc(3);
gsl_linalg_SV_decomp (u,
v,
s,
work);
sx = s->data[0];
sy = s->data[1];
sz = s->data[2];
for(unsigned int i = 0 ; i < 3; ++i)
{
for(unsigned int j = 0 ; j < 3; ++j)
{
U(i,j) = gsl_matrix_get( u , i , j );
Vt(i,j) = gsl_matrix_get( v , j , i );
}
}
gsl_matrix_free(u);
gsl_matrix_free(v);
gsl_vector_free(s);
gsl_vector_free(work);
// a transformation float is given as R.B.S.Bt, R = rotation , B = local basis (rotation matrix), S = scales in the basis B
// it can be obtained from the svd decomposition of float = U Sigma Vt :
// B = V
// S = Sigma
// R = U.Vt
}
// ---------- Projections onto Rotations ----------- //
void setRotation()
{
Mat3 U,Vt;
float sx,sy,sz;
SVD(U,sx,sy,sz,Vt);
const Mat3 & res = U*Vt;
if( res.determinant() < 0 )
{
U(0,2) = -U(0,2);
U(1,2) = -U(1,2);
U(2,2) = -U(2,2);
*this = (U*Vt);
return;
}
// else
*this = (res);
}
template< class point_t >
inline static
Mat3 tensor( const point_t & p1 , const point_t & p2 )
{
return Mat3(
p1[0]*p2[0] , p1[0]*p2[1] , p1[0]*p2[2],
p1[1]*p2[0] , p1[1]*p2[1] , p1[1]*p2[2],
p1[2]*p2[0] , p1[2]*p2[1] , p1[2]*p2[2]);
}
template< class point_t >
inline static
Mat3 vectorial( const point_t & p )
{
return Mat3(
0 , -p[2] , p[1] ,
p[2] , 0 , - p[0] ,
- p[1] , p[0] , 0
);
}
Mat3 operator - () const
{
return Mat3( - vals[0],- vals[1],- vals[2],- vals[3],- vals[4],- vals[5],- vals[6],- vals[7],- vals[8] );
}
private:
float vals[9];
// will be noted as :
// 0 1 2
// 3 4 5
// 6 7 8
};
inline static
Mat3 operator * (float s , const Mat3 & m)
{
return Mat3( m(0,0)*s , m(0,1)*s , m(0,2)*s , m(1,0)*s , m(1,1)*s , m(1,2)*s , m(2,0)*s , m(2,1)*s , m(2,2)*s );
}
inline static std::ostream & operator << (std::ostream & s , Mat3 const & m)
{
s << m(0,0) << " \t" << m(0,1) << " \t" << m(0,2) << std::endl << m(1,0) << " \t" << m(1,1) << " \t" << m(1,2) << std::endl << m(2,0) << " \t" << m(2,1) << " \t" << m(2,2) << std::endl;
return s;
}
#endif
| {
"alphanum_fraction": 0.4449648712,
"avg_line_length": 29.5308411215,
"ext": "h",
"hexsha": "085a5dd0b20b8460af4309a00b6447f05090970c",
"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": "6e37ef755bd5312fc808ec599b3bd76084d35568",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Eikins/M2-Imagina",
"max_forks_repo_path": "HMIN323/TP4_MLS/src/Vec3.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6e37ef755bd5312fc808ec599b3bd76084d35568",
"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": "Eikins/M2-Imagina",
"max_issues_repo_path": "HMIN323/TP4_MLS/src/Vec3.h",
"max_line_length": 228,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6e37ef755bd5312fc808ec599b3bd76084d35568",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Eikins/M2-Imagina",
"max_stars_repo_path": "HMIN323/TP4_MLS/src/Vec3.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5807,
"size": 15799
} |
#include <math.h>
#include <string.h>
#include <stdio.h>
#include "extra_compile_macros.h"
#if USE_GSL == 1
#include <gsl/gsl_sf_gamma.h>
#endif
double nan_density(double t, double *pars, double *q, int n_dim) { return NAN; }
double nan_value(double t, double *pars, double *q, int n_dim) { return NAN; }
void nan_gradient(double t, double *pars, double *q, int n_dim, double *grad) {}
void nan_hessian(double t, double *pars, double *q, int n_dim, double *hess) {}
double null_density(double t, double *pars, double *q, int n_dim) { return 0; }
double null_value(double t, double *pars, double *q, int n_dim) { return 0; }
void null_gradient(double t, double *pars, double *q, int n_dim, double *grad){}
void null_hessian(double t, double *pars, double *q, int n_dim, double *hess) {}
/* Note: many Hessians generated with sympy in
gala-notebooks/Make-all-Hessians.ipynb
*/
/* ---------------------------------------------------------------------------
Henon-Heiles potential
*/
double henon_heiles_value(double t, double *pars, double *q, int n_dim) {
/* no parameters... */
return 0.5 * (q[0]*q[0] + q[1]*q[1] + 2*q[0]*q[0]*q[1] - 2/3.*q[1]*q[1]*q[1]);
}
void henon_heiles_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* no parameters... */
grad[0] = grad[0] + q[0] + 2*q[0]*q[1];
grad[1] = grad[1] + q[1] + q[0]*q[0] - q[1]*q[1];
}
void henon_heiles_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* no parameters... */
double x = q[0];
double y = q[1];
double tmp_0 = 2.0 * y;
double tmp_1 = 2.0 * x;
hess[0] = hess[0] + tmp_0 + 1.0;
hess[1] = hess[1] + tmp_1;
hess[2] = hess[2] + tmp_1;
hess[3] = hess[3] + 1.0 - tmp_0;
}
/* ---------------------------------------------------------------------------
Kepler potential
*/
double kepler_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
*/
double R;
R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
return -pars[0] * pars[1] / R;
}
void kepler_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
*/
double R, fac;
R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
fac = pars[0] * pars[1] / (R*R*R);
grad[0] = grad[0] + fac*q[0];
grad[1] = grad[1] + fac*q[1];
grad[2] = grad[2] + fac*q[2];
}
double kepler_density(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
*/
double r2;
r2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];
if (r2 == 0.) {
return INFINITY;
} else {
return 0.;
}
}
void kepler_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
*/
double G = pars[0];
double m = pars[1];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(x, 2);
double tmp_1 = pow(y, 2);
double tmp_2 = pow(z, 2);
double tmp_3 = tmp_0 + tmp_1 + tmp_2;
double tmp_4 = G*m;
double tmp_5 = tmp_4/pow(tmp_3, 3.0/2.0);
double tmp_6 = 3*tmp_4/pow(tmp_3, 5.0/2.0);
double tmp_7 = tmp_6*x;
double tmp_8 = -tmp_7*y;
double tmp_9 = -tmp_7*z;
double tmp_10 = -tmp_6*y*z;
hess[0] = hess[0] + -tmp_0*tmp_6 + tmp_5;
hess[1] = hess[1] + tmp_8;
hess[2] = hess[2] + tmp_9;
hess[3] = hess[3] + tmp_8;
hess[4] = hess[4] + -tmp_1*tmp_6 + tmp_5;
hess[5] = hess[5] + tmp_10;
hess[6] = hess[6] + tmp_9;
hess[7] = hess[7] + tmp_10;
hess[8] = hess[8] + -tmp_2*tmp_6 + tmp_5;
}
/* ---------------------------------------------------------------------------
Isochrone potential
*/
double isochrone_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- b (core scale)
*/
double R2;
R2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];
return -pars[0] * pars[1] / (sqrt(R2 + pars[2]*pars[2]) + pars[2]);
}
void isochrone_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- b (core scale)
*/
double sqrt_r2_b2, fac, denom;
sqrt_r2_b2 = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + pars[2]*pars[2]);
denom = sqrt_r2_b2 * (sqrt_r2_b2 + pars[2])*(sqrt_r2_b2 + pars[2]);
fac = pars[0] * pars[1] / denom;
grad[0] = grad[0] + fac*q[0];
grad[1] = grad[1] + fac*q[1];
grad[2] = grad[2] + fac*q[2];
}
double isochrone_density(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- b (core scale)
*/
double r2, a, b;
b = pars[2];
r2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];
a = sqrt(b*b + r2);
return pars[1] * (3*(b+a)*a*a - r2*(b+3*a)) / (4*M_PI*pow(b+a,3)*a*a*a);
}
void isochrone_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- b (length scale)
*/
double G = pars[0];
double m = pars[1];
double b = pars[2];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(x, 2);
double tmp_1 = pow(y, 2);
double tmp_2 = pow(z, 2);
double tmp_3 = pow(b, 2) + tmp_0 + tmp_1 + tmp_2;
double tmp_4 = sqrt(tmp_3);
double tmp_5 = b + tmp_4;
double tmp_6 = G*m;
double tmp_7 = tmp_6/pow(tmp_5, 2);
double tmp_8 = tmp_7/tmp_4;
double tmp_9 = 2*tmp_6/(tmp_3*pow(tmp_5, 3));
double tmp_10 = tmp_7/pow(tmp_3, 3.0/2.0);
double tmp_11 = tmp_9*x;
double tmp_12 = tmp_10*x;
double tmp_13 = -tmp_11*y - tmp_12*y;
double tmp_14 = -tmp_11*z - tmp_12*z;
double tmp_15 = y*z;
double tmp_16 = -tmp_10*tmp_15 - tmp_15*tmp_9;
hess[0] = hess[0] + -tmp_0*tmp_10 - tmp_0*tmp_9 + tmp_8;
hess[1] = hess[1] + tmp_13;
hess[2] = hess[2] + tmp_14;
hess[3] = hess[3] + tmp_13;
hess[4] = hess[4] + -tmp_1*tmp_10 - tmp_1*tmp_9 + tmp_8;
hess[5] = hess[5] + tmp_16;
hess[6] = hess[6] + tmp_14;
hess[7] = hess[7] + tmp_16;
hess[8] = hess[8] + -tmp_10*tmp_2 - tmp_2*tmp_9 + tmp_8;
}
/* ---------------------------------------------------------------------------
Hernquist sphere
*/
double hernquist_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- c (length scale)
*/
double R;
R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
return -pars[0] * pars[1] / (R + pars[2]);
}
void hernquist_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- c (length scale)
*/
double R, fac;
R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
fac = pars[0] * pars[1] / ((R + pars[2]) * (R + pars[2]) * R);
grad[0] = grad[0] + fac*q[0];
grad[1] = grad[1] + fac*q[1];
grad[2] = grad[2] + fac*q[2];
}
double hernquist_density(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- c (length scale)
*/
double r, rho0;
r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
rho0 = pars[1]/(2*M_PI*pars[2]*pars[2]*pars[2]);
return rho0 / ((r/pars[2]) * pow(1+r/pars[2],3));
}
void hernquist_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- c (length scale)
*/
double G = pars[0];
double m = pars[1];
double c = pars[2];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(x, 2);
double tmp_1 = pow(y, 2);
double tmp_2 = pow(z, 2);
double tmp_3 = tmp_0 + tmp_1 + tmp_2;
double tmp_4 = sqrt(tmp_3);
double tmp_5 = c + tmp_4;
double tmp_6 = G*m;
double tmp_7 = tmp_6/pow(tmp_5, 2);
double tmp_8 = tmp_7/tmp_4;
double tmp_9 = 2*tmp_6/(tmp_3*pow(tmp_5, 3));
double tmp_10 = tmp_7/pow(tmp_3, 3.0/2.0);
double tmp_11 = tmp_9*x;
double tmp_12 = tmp_10*x;
double tmp_13 = -tmp_11*y - tmp_12*y;
double tmp_14 = -tmp_11*z - tmp_12*z;
double tmp_15 = y*z;
double tmp_16 = -tmp_10*tmp_15 - tmp_15*tmp_9;
hess[0] = hess[0] + -tmp_0*tmp_10 - tmp_0*tmp_9 + tmp_8;
hess[1] = hess[1] + tmp_13;
hess[2] = hess[2] + tmp_14;
hess[3] = hess[3] + tmp_13;
hess[4] = hess[4] + -tmp_1*tmp_10 - tmp_1*tmp_9 + tmp_8;
hess[5] = hess[5] + tmp_16;
hess[6] = hess[6] + tmp_14;
hess[7] = hess[7] + tmp_16;
hess[8] = hess[8] + -tmp_10*tmp_2 - tmp_2*tmp_9 + tmp_8;
}
/* ---------------------------------------------------------------------------
Plummer sphere
*/
double plummer_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- b (length scale)
*/
double R2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];
return -pars[0]*pars[1] / sqrt(R2 + pars[2]*pars[2]);
}
void plummer_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- b (length scale)
*/
double R2b, fac;
R2b = q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + pars[2]*pars[2];
fac = pars[0] * pars[1] / sqrt(R2b) / R2b;
grad[0] = grad[0] + fac*q[0];
grad[1] = grad[1] + fac*q[1];
grad[2] = grad[2] + fac*q[2];
}
double plummer_density(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- b (length scale)
*/
double r2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];
return 3*pars[1] / (4*M_PI*pars[2]*pars[2]*pars[2]) * pow(1 + r2/(pars[2]*pars[2]), -2.5);
}
void plummer_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- b (length scale)
*/
double G = pars[0];
double m = pars[1];
double b = pars[2];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(x, 2);
double tmp_1 = pow(y, 2);
double tmp_2 = pow(z, 2);
double tmp_3 = pow(b, 2) + tmp_0 + tmp_1 + tmp_2;
double tmp_4 = G*m;
double tmp_5 = tmp_4/pow(tmp_3, 3.0/2.0);
double tmp_6 = 3*tmp_4/pow(tmp_3, 5.0/2.0);
double tmp_7 = tmp_6*x;
double tmp_8 = -tmp_7*y;
double tmp_9 = -tmp_7*z;
double tmp_10 = -tmp_6*y*z;
hess[0] = hess[0] + -tmp_0*tmp_6 + tmp_5;
hess[1] = hess[1] + tmp_8;
hess[2] = hess[2] + tmp_9;
hess[3] = hess[3] + tmp_8;
hess[4] = hess[4] + -tmp_1*tmp_6 + tmp_5;
hess[5] = hess[5] + tmp_10;
hess[6] = hess[6] + tmp_9;
hess[7] = hess[7] + tmp_10;
hess[8] = hess[8] + -tmp_2*tmp_6 + tmp_5;
}
/* ---------------------------------------------------------------------------
Jaffe sphere
*/
double jaffe_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- c (length scale)
*/
double R;
R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
return -pars[0] * pars[1] / pars[2] * log(1 + pars[2]/R);
}
void jaffe_gradient(double t, double *pars, double *q, int n_dim, double *grad){
/* pars:
- G (Gravitational constant)
- m (mass scale)
- c (length scale)
*/
double R, fac;
R = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
fac = pars[0] * pars[1] / pars[2] * (pars[2] / (R * (pars[2] + R)));
grad[0] = grad[0] + fac*q[0]/R;
grad[1] = grad[1] + fac*q[1]/R;
grad[2] = grad[2] + fac*q[2]/R;
}
double jaffe_density(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- c (length scale)
*/
double r, rho0;
r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
rho0 = pars[1] / (4*M_PI*pars[2]*pars[2]*pars[2]);
return rho0 / (pow(r/pars[2],2) * pow(1+r/pars[2],2));
}
void jaffe_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- c (length scale)
*/
double G = pars[0];
double m = pars[1];
double c = pars[2];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(x, 2);
double tmp_1 = pow(y, 2);
double tmp_2 = pow(z, 2);
double tmp_3 = tmp_0 + tmp_1 + tmp_2;
double tmp_4 = 1.0/tmp_3;
double tmp_5 = sqrt(tmp_3);
double tmp_6 = c + tmp_5;
double tmp_7 = pow(tmp_6, -2);
double tmp_8 = tmp_7*x;
double tmp_9 = 1.0/tmp_5;
double tmp_10 = 1.0/tmp_6;
double tmp_11 = tmp_10*tmp_9;
double tmp_12 = G*m/c;
double tmp_13 = tmp_12*(tmp_11*x - tmp_8);
double tmp_14 = tmp_13*tmp_4;
double tmp_15 = pow(tmp_3, -3.0/2.0);
double tmp_16 = tmp_13*tmp_15*tmp_6;
double tmp_17 = tmp_10*tmp_15;
double tmp_18 = tmp_4*tmp_7;
double tmp_19 = 2*tmp_9/pow(tmp_6, 3);
double tmp_20 = tmp_11 - tmp_7;
double tmp_21 = tmp_12*tmp_6;
double tmp_22 = tmp_21*tmp_9;
double tmp_23 = tmp_19*x;
double tmp_24 = tmp_4*tmp_8;
double tmp_25 = tmp_17*x;
double tmp_26 = tmp_14*y - tmp_16*y + tmp_22*(tmp_23*y - tmp_24*y - tmp_25*y);
double tmp_27 = tmp_4*z;
double tmp_28 = tmp_13*tmp_27 - tmp_16*z + tmp_22*(tmp_23*z - tmp_24*z - tmp_25*z);
double tmp_29 = tmp_7*y;
double tmp_30 = tmp_11*y - tmp_29;
double tmp_31 = tmp_12*tmp_30;
double tmp_32 = tmp_15*tmp_21;
double tmp_33 = tmp_30*tmp_32;
double tmp_34 = y*z;
double tmp_35 = tmp_22*(-tmp_17*tmp_34 + tmp_19*tmp_34 - tmp_27*tmp_29) + tmp_27*tmp_31 - tmp_33*z;
double tmp_36 = tmp_11*z - tmp_7*z;
hess[0] = hess[0] + tmp_14*x - tmp_16*x + tmp_22*(-tmp_0*tmp_17 - tmp_0*tmp_18 + tmp_0*tmp_19 + tmp_20);
hess[1] = hess[1] + tmp_26;
hess[2] = hess[2] + tmp_28;
hess[3] = hess[3] + tmp_26;
hess[4] = hess[4] + tmp_22*(-tmp_1*tmp_17 - tmp_1*tmp_18 + tmp_1*tmp_19 + tmp_20) + tmp_31*tmp_4*y - tmp_33*y;
hess[5] = hess[5] + tmp_35;
hess[6] = hess[6] + tmp_28;
hess[7] = hess[7] + tmp_35;
hess[8] = hess[8] + tmp_12*tmp_27*tmp_36 + tmp_22*(-tmp_17*tmp_2 - tmp_18*tmp_2 + tmp_19*tmp_2 + tmp_20) - tmp_32*tmp_36*z;
}
/* ---------------------------------------------------------------------------
Power-law potential with exponential cutoff
*/
#if USE_GSL == 1
double safe_gamma_inc(double a, double x) {
int N, m, n;
double A = 1.;
double B = 0.;
double tmp;
if (a > 0) {
return gsl_sf_gamma_inc_P(a, x) * gsl_sf_gamma(a);;
} else {
N = (int) ceil(-a);
for (n=0; n < N; n++) {
A = A * (a + n);
tmp = 1.;
for (m=N-1; m > n; m--) {
tmp = tmp * (a + m);
}
B = B + pow(x, a+n) * exp(-x) * tmp;
}
return (B + gsl_sf_gamma_inc_P(a + N, x) * gsl_sf_gamma(a + N)) / A;
}
}
double powerlawcutoff_value(double t, double *pars, double *q, int n_dim) {
/* pars:
0 - G (Gravitational constant)
1 - m (total mass)
2 - a (power-law index)
3 - c (cutoff radius)
*/
double G = pars[0];
double m = pars[1];
double alpha = pars[2];
double r_c = pars[3];
double x = q[0];
double y = q[1];
double z = q[2];
double r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
if (r == 0.) {
return -INFINITY;
} else {
double tmp_0 = (1.0/2.0)*alpha;
double tmp_1 = -tmp_0;
double tmp_2 = tmp_1 + 1.5;
double tmp_3 = pow(x, 2) + pow(y, 2) + pow(z, 2);
double tmp_4 = tmp_3/pow(r_c, 2);
double tmp_5 = G*m;
double tmp_6 = tmp_5*safe_gamma_inc(tmp_2, tmp_4)/(sqrt(tmp_3)*tgamma(tmp_1 + 2.5));
return tmp_0*tmp_6 - 3.0/2.0*tmp_6 + tmp_5*safe_gamma_inc(tmp_1 + 1, tmp_4)/(r_c*tgamma(tmp_2));
}
}
double powerlawcutoff_density(double t, double *pars, double *q, int n_dim) {
/* pars:
0 - G (Gravitational constant)
1 - m (total mass)
2 - a (power-law index)
3 - c (cutoff radius)
*/
double r, A;
r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
A = pars[1] / (2*M_PI) * pow(pars[3], pars[2] - 3) / gsl_sf_gamma(0.5 * (3 - pars[2]));
return A * pow(r, -pars[2]) * exp(-r*r / (pars[3]*pars[3]));
}
void powerlawcutoff_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
0 - G (Gravitational constant)
1 - m (total mass)
2 - a (power-law index)
3 - c (cutoff radius)
*/
double r, dPhi_dr;
r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
dPhi_dr = (pars[0] * pars[1] / (r*r) *
gsl_sf_gamma_inc_P(0.5 * (3-pars[2]), r*r/(pars[3]*pars[3]))); // / gsl_sf_gamma(0.5 * (3-pars[2])));
grad[0] = grad[0] + dPhi_dr * q[0]/r;
grad[1] = grad[1] + dPhi_dr * q[1]/r;
grad[2] = grad[2] + dPhi_dr * q[2]/r;
}
void powerlawcutoff_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- alpha (exponent)
- r_c (cutoff radius)
*/
double G = pars[0];
double m = pars[1];
double alpha = pars[2];
double r_c = pars[3];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(x, 2);
double tmp_1 = pow(y, 2);
double tmp_2 = pow(z, 2);
double tmp_3 = tmp_0 + tmp_1 + tmp_2;
double tmp_4 = (1.0/2.0)*alpha;
double tmp_5 = -tmp_4;
double tmp_6 = tmp_5 + 1.5;
double tmp_7 = pow(r_c, -2);
double tmp_8 = tmp_3*tmp_7;
double tmp_9 = G*m;
double tmp_10 = tmp_9/tgamma(tmp_5 + 2.5);
double tmp_11 = tmp_10*safe_gamma_inc(tmp_6, tmp_8);
double tmp_12 = tmp_11/pow(tmp_3, 5.0/2.0);
double tmp_13 = (9.0/2.0)*tmp_12;
double tmp_14 = exp(-tmp_8);
double tmp_15 = tmp_0*tmp_14;
double tmp_16 = pow(tmp_8, -tmp_4)*tmp_9/tgamma(tmp_6);
double tmp_17 = 4*tmp_16/pow(r_c, 5);
double tmp_18 = alpha*tmp_0;
double tmp_19 = (3.0/2.0)*tmp_12;
double tmp_20 = 6*tmp_15;
double tmp_21 = pow(r_c, -4);
double tmp_22 = tmp_5 + 0.5;
double tmp_23 = pow(tmp_8, tmp_22);
double tmp_24 = tmp_10*tmp_23/sqrt(tmp_3);
double tmp_25 = tmp_21*tmp_24;
double tmp_26 = pow(tmp_3, -3.0/2.0);
double tmp_27 = tmp_10*tmp_23*tmp_26*tmp_7;
double tmp_28 = tmp_20*tmp_27;
double tmp_29 = 2*tmp_14;
double tmp_30 = tmp_18*tmp_29;
double tmp_31 = tmp_16*tmp_29/pow(r_c, 3);
double tmp_32 = tmp_31/tmp_3;
double tmp_33 = tmp_27*tmp_30;
double tmp_34 = tmp_11*tmp_26;
double tmp_35 = tmp_14*tmp_24;
double tmp_36 = tmp_35*tmp_7;
double tmp_37 = alpha*tmp_36 + tmp_31 - tmp_34*tmp_4 + (3.0/2.0)*tmp_34 - 3*tmp_36;
double tmp_38 = tmp_13*x;
double tmp_39 = alpha*tmp_19;
double tmp_40 = x*y;
double tmp_41 = tmp_14*tmp_17;
double tmp_42 = alpha*tmp_40;
double tmp_43 = tmp_21*tmp_35;
double tmp_44 = 6*tmp_40;
double tmp_45 = tmp_14*tmp_27;
double tmp_46 = tmp_44*tmp_45;
double tmp_47 = tmp_29*tmp_42;
double tmp_48 = tmp_27*tmp_47;
double tmp_49 = -tmp_22*tmp_46 + tmp_22*tmp_48 - tmp_25*tmp_47 - tmp_32*tmp_42 - tmp_38*y + tmp_39*tmp_40 - tmp_40*tmp_41 + tmp_43*tmp_44 + tmp_46 - tmp_48;
double tmp_50 = x*z;
double tmp_51 = alpha*tmp_50;
double tmp_52 = 6*tmp_50;
double tmp_53 = tmp_45*tmp_52;
double tmp_54 = tmp_29*tmp_51;
double tmp_55 = tmp_27*tmp_54;
double tmp_56 = -tmp_22*tmp_53 + tmp_22*tmp_55 - tmp_25*tmp_54 - tmp_32*tmp_51 - tmp_38*z + tmp_39*tmp_50 - tmp_41*tmp_50 + tmp_43*tmp_52 + tmp_53 - tmp_55;
double tmp_57 = 6*tmp_1;
double tmp_58 = tmp_45*tmp_57;
double tmp_59 = alpha*tmp_1;
double tmp_60 = tmp_29*tmp_59;
double tmp_61 = tmp_27*tmp_60;
double tmp_62 = y*z;
double tmp_63 = alpha*tmp_62;
double tmp_64 = 6*tmp_62;
double tmp_65 = tmp_45*tmp_64;
double tmp_66 = tmp_29*tmp_63;
double tmp_67 = tmp_27*tmp_66;
double tmp_68 = -tmp_13*tmp_62 - tmp_22*tmp_65 + tmp_22*tmp_67 - tmp_25*tmp_66 - tmp_32*tmp_63 + tmp_39*tmp_62 - tmp_41*tmp_62 + tmp_43*tmp_64 + tmp_65 - tmp_67;
double tmp_69 = 6*tmp_2;
double tmp_70 = tmp_45*tmp_69;
double tmp_71 = alpha*tmp_2;
double tmp_72 = tmp_29*tmp_71;
double tmp_73 = tmp_27*tmp_72;
hess[0] = hess[0] + -tmp_0*tmp_13 - tmp_15*tmp_17 + tmp_18*tmp_19 - tmp_18*tmp_32 + tmp_20*tmp_25 - tmp_22*tmp_28 + tmp_22*tmp_33 - tmp_25*tmp_30 + tmp_28 - tmp_33 + tmp_37;
hess[1] = hess[1] + tmp_49;
hess[2] = hess[2] + tmp_56;
hess[3] = hess[3] + tmp_49;
hess[4] = hess[4] + -tmp_1*tmp_13 + tmp_1*tmp_39 - tmp_1*tmp_41 - tmp_22*tmp_58 + tmp_22*tmp_61 - tmp_25*tmp_60 - tmp_32*tmp_59 + tmp_37 + tmp_43*tmp_57 + tmp_58 - tmp_61;
hess[5] = hess[5] + tmp_68;
hess[6] = hess[6] + tmp_56;
hess[7] = hess[7] + tmp_68;
hess[8] = hess[8] + -tmp_13*tmp_2 + tmp_2*tmp_39 - tmp_2*tmp_41 - tmp_22*tmp_70 + tmp_22*tmp_73 - tmp_25*tmp_72 - tmp_32*tmp_71 + tmp_37 + tmp_43*tmp_69 + tmp_70 - tmp_73;
}
#endif
/* ---------------------------------------------------------------------------
Stone-Ostriker potential from Stone & Ostriker (2015)
*/
double stone_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- M (total mass)
- r_c (core radius)
- r_h (halo radius)
*/
double r, u_c, u_h, fac;
r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
u_c = r / pars[2];
u_h = r / pars[3];
fac = 2*pars[0]*pars[1] / M_PI / (pars[3] - pars[2]);
return -fac * (atan(u_h)/u_h - atan(u_c)/u_c +
0.5*log((r*r + pars[3]*pars[3])/(r*r + pars[2]*pars[2])));
}
void stone_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
- G (Gravitational constant)
- M (total mass)
- r_c (core radius)
- r_h (halo radius)
*/
double r, u_c, u_h, fac, dphi_dr;
r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
u_c = r / pars[2];
u_h = r / pars[3];
fac = 2*pars[0]*pars[1] / (M_PI*r*r) / (pars[2] - pars[3]); // order flipped from value
dphi_dr = fac * (pars[2]*atan(u_c) - pars[3]*atan(u_h));
grad[0] = grad[0] + dphi_dr*q[0]/r;
grad[1] = grad[1] + dphi_dr*q[1]/r;
grad[2] = grad[2] + dphi_dr*q[2]/r;
}
double stone_density(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- M (total mass)
- r_c (core radius)
- r_h (halo radius)
*/
double r, u_c, u_t, rho;
rho = pars[1] * (pars[2] + pars[3]) / (2*M_PI*M_PI*pars[2]*pars[2]*pars[3]*pars[3]);
r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
u_c = r / pars[2];
u_t = r / pars[3];
return rho / ((1 + u_c*u_c)*(1 + u_t*u_t));
}
void stone_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- r_c (core radius)
- r_h (halo radius)
*/
double G = pars[0];
double m = pars[1];
double r_c = pars[2];
double r_h = pars[3];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(r_h, 2);
double tmp_1 = 1.0/tmp_0;
double tmp_2 = pow(x, 2);
double tmp_3 = pow(y, 2);
double tmp_4 = pow(z, 2);
double tmp_5 = tmp_2 + tmp_3 + tmp_4;
double tmp_6 = tmp_1*tmp_5 + 1;
double tmp_7 = 1.0/tmp_6;
double tmp_8 = 3/pow(tmp_5, 2);
double tmp_9 = tmp_2*tmp_8;
double tmp_10 = pow(r_c, 2);
double tmp_11 = 1.0/tmp_10;
double tmp_12 = tmp_11*tmp_5 + 1;
double tmp_13 = 1.0/tmp_12;
double tmp_14 = tmp_10 + tmp_5;
double tmp_15 = pow(tmp_14, -2);
double tmp_16 = 8*tmp_15;
double tmp_17 = tmp_0 + tmp_5;
double tmp_18 = 8*tmp_17/pow(tmp_14, 3);
double tmp_19 = 2/tmp_14;
double tmp_20 = 2*tmp_15*tmp_17;
double tmp_21 = tmp_19 - tmp_20;
double tmp_22 = 1.0/tmp_17;
double tmp_23 = 0.5*tmp_14*tmp_22;
double tmp_24 = tmp_19*x - tmp_20*x;
double tmp_25 = 1.0*tmp_22;
double tmp_26 = tmp_24*tmp_25;
double tmp_27 = sqrt(tmp_5);
double tmp_28 = r_c*atan(tmp_27/r_c);
double tmp_29 = 3/pow(tmp_5, 5.0/2.0);
double tmp_30 = tmp_2*tmp_29;
double tmp_31 = 1.0/tmp_5;
double tmp_32 = 2*tmp_31;
double tmp_33 = tmp_2*tmp_32;
double tmp_34 = tmp_1/pow(tmp_6, 2);
double tmp_35 = tmp_11/pow(tmp_12, 2);
double tmp_36 = r_h*atan(tmp_27/r_h);
double tmp_37 = 1.0*tmp_14/pow(tmp_17, 2);
double tmp_38 = tmp_24*tmp_37;
double tmp_39 = pow(tmp_5, -3.0/2.0);
double tmp_40 = -tmp_13*tmp_31 + tmp_28*tmp_39 + tmp_31*tmp_7 - tmp_36*tmp_39;
double tmp_41 = 2*G*m/(-3.1415926535897931*r_c + 3.1415926535897931*r_h);
double tmp_42 = x*y;
double tmp_43 = tmp_42*tmp_8;
double tmp_44 = tmp_29*tmp_42;
double tmp_45 = tmp_32*tmp_42;
double tmp_46 = tmp_16*x;
double tmp_47 = -tmp_41*(tmp_13*tmp_43 + tmp_23*(tmp_18*tmp_42 - tmp_46*y) + tmp_26*y - tmp_28*tmp_44 - tmp_34*tmp_45 + tmp_35*tmp_45 + tmp_36*tmp_44 - tmp_38*y - tmp_43*tmp_7);
double tmp_48 = x*z;
double tmp_49 = tmp_48*tmp_8;
double tmp_50 = tmp_29*tmp_48;
double tmp_51 = tmp_32*tmp_48;
double tmp_52 = -tmp_41*(tmp_13*tmp_49 + tmp_23*(tmp_18*tmp_48 - tmp_46*z) + tmp_26*z - tmp_28*tmp_50 - tmp_34*tmp_51 + tmp_35*tmp_51 + tmp_36*tmp_50 - tmp_38*z - tmp_49*tmp_7);
double tmp_53 = tmp_3*tmp_8;
double tmp_54 = tmp_19*y - tmp_20*y;
double tmp_55 = tmp_25*tmp_54;
double tmp_56 = tmp_29*tmp_3;
double tmp_57 = tmp_3*tmp_32;
double tmp_58 = tmp_37*tmp_54;
double tmp_59 = y*z;
double tmp_60 = tmp_59*tmp_8;
double tmp_61 = tmp_29*tmp_59;
double tmp_62 = tmp_32*tmp_59;
double tmp_63 = -tmp_41*(tmp_13*tmp_60 + tmp_23*(-tmp_16*tmp_59 + tmp_18*tmp_59) - tmp_28*tmp_61 - tmp_34*tmp_62 + tmp_35*tmp_62 + tmp_36*tmp_61 + tmp_55*z - tmp_58*z - tmp_60*tmp_7);
double tmp_64 = tmp_4*tmp_8;
double tmp_65 = z*(tmp_19*z - tmp_20*z);
double tmp_66 = tmp_29*tmp_4;
double tmp_67 = tmp_32*tmp_4;
hess[0] = hess[0] + -tmp_41*(tmp_13*tmp_9 + tmp_23*(-tmp_16*tmp_2 + tmp_18*tmp_2 + tmp_21) + tmp_26*x - tmp_28*tmp_30 + tmp_30*tmp_36 - tmp_33*tmp_34 + tmp_33*tmp_35 - tmp_38*x + tmp_40 - tmp_7*tmp_9);
hess[1] = hess[1] + tmp_47;
hess[2] = hess[2] + tmp_52;
hess[3] = hess[3] + tmp_47;
hess[4] = hess[4] + -tmp_41*(tmp_13*tmp_53 + tmp_23*(-tmp_16*tmp_3 + tmp_18*tmp_3 + tmp_21) - tmp_28*tmp_56 - tmp_34*tmp_57 + tmp_35*tmp_57 + tmp_36*tmp_56 + tmp_40 - tmp_53*tmp_7 + tmp_55*y - tmp_58*y);
hess[5] = hess[5] + tmp_63;
hess[6] = hess[6] + tmp_52;
hess[7] = hess[7] + tmp_63;
hess[8] = hess[8] + -tmp_41*(tmp_13*tmp_64 + tmp_23*(-tmp_16*tmp_4 + tmp_18*tmp_4 + tmp_21) + tmp_25*tmp_65 - tmp_28*tmp_66 - tmp_34*tmp_67 + tmp_35*tmp_67 + tmp_36*tmp_66 - tmp_37*tmp_65 + tmp_40 - tmp_64*tmp_7);
}
/* ---------------------------------------------------------------------------
Spherical NFW
*/
double sphericalnfw_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- r_s (scale radius)
*/
double u, v_h2;
// v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);
v_h2 = -pars[0] * pars[1] / pars[2];
u = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]) / pars[2];
return v_h2 * log(1 + u) / u;
}
void sphericalnfw_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- r_s (scale radius)
*/
double fac, u, v_h2;
// v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);
v_h2 = pars[0] * pars[1] / pars[2];
u = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]) / pars[2];
fac = v_h2 / (u*u*u) / (pars[2]*pars[2]) * (log(1+u) - u/(1+u));
grad[0] = grad[0] + fac*q[0];
grad[1] = grad[1] + fac*q[1];
grad[2] = grad[2] + fac*q[2];
}
double sphericalnfw_density(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- r_s (scale radius)
*/
// double v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);
double v_h2 = pars[0] * pars[1] / pars[2];
double r, rho0;
r = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]);
rho0 = v_h2 / (4*M_PI*pars[0]*pars[2]*pars[2]);
return rho0 / ((r/pars[2]) * pow(1+r/pars[2],2));
}
void sphericalnfw_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- r_s (scale radius)
*/
double G = pars[0];
double m = pars[1];
double r_s = pars[2];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(x, 2);
double tmp_1 = pow(y, 2);
double tmp_2 = pow(z, 2);
double tmp_3 = tmp_0 + tmp_1 + tmp_2;
double tmp_4 = pow(tmp_3, 7);
double tmp_5 = 3*tmp_0;
double tmp_6 = sqrt(tmp_3);
double tmp_7 = r_s + tmp_6;
double tmp_8 = pow(tmp_3, 13.0/2.0)*tmp_7;
double tmp_9 = pow(tmp_7, 2);
double tmp_10 = 1.0/r_s;
double tmp_11 = tmp_9*log(tmp_10*tmp_7);
double tmp_12 = tmp_11*pow(tmp_3, 6);
double tmp_13 = tmp_11*tmp_4 - pow(tmp_3, 15.0/2.0)*tmp_7;
double tmp_14 = G*m;
double tmp_15 = tmp_14/tmp_9;
double tmp_16 = tmp_15/pow(tmp_3, 17.0/2.0);
double tmp_17 = x*y;
double tmp_18 = 4*tmp_15/pow(tmp_3, 3.0/2.0);
double tmp_19 = 3*tmp_17;
double tmp_20 = r_s*tmp_15/pow(tmp_3, 2);
double tmp_21 = tmp_14*log(tmp_10*tmp_6 + 1)/pow(tmp_3, 5.0/2.0);
double tmp_22 = tmp_17*tmp_18 + tmp_19*tmp_20 - tmp_19*tmp_21;
double tmp_23 = x*z;
double tmp_24 = 3*tmp_20;
double tmp_25 = 3*tmp_21;
double tmp_26 = tmp_18*tmp_23 + tmp_23*tmp_24 - tmp_23*tmp_25;
double tmp_27 = 3*tmp_8;
double tmp_28 = 3*tmp_12;
double tmp_29 = y*z;
double tmp_30 = tmp_18*tmp_29 + tmp_24*tmp_29 - tmp_25*tmp_29;
hess[0] = hess[0] + tmp_16*(tmp_0*tmp_4 - tmp_12*tmp_5 + tmp_13 + tmp_5*tmp_8);
hess[1] = hess[1] + tmp_22;
hess[2] = hess[2] + tmp_26;
hess[3] = hess[3] + tmp_22;
hess[4] = hess[4] + tmp_16*(tmp_1*tmp_27 - tmp_1*tmp_28 + tmp_1*tmp_4 + tmp_13);
hess[5] = hess[5] + tmp_30;
hess[6] = hess[6] + tmp_26;
hess[7] = hess[7] + tmp_30;
hess[8] = hess[8] + tmp_16*(tmp_13 + tmp_2*tmp_27 - tmp_2*tmp_28 + tmp_2*tmp_4);
}
/* ---------------------------------------------------------------------------
Flattened NFW
*/
double flattenednfw_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (scale mass)
- r_s (scale radius)
- qz (flattening)
*/
double u, v_h2;
// v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);
v_h2 = -pars[0] * pars[1] / pars[2];
u = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]/(pars[3]*pars[3])) / pars[2];
return v_h2 * log(1 + u) / u;
}
void flattenednfw_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
- G (Gravitational constant)
- m (scale mass)
- r_s (scale radius)
- qz (flattening)
*/
double fac, u, v_h2;
// v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);
v_h2 = pars[0] * pars[1] / pars[2];
u = sqrt(q[0]*q[0] + q[1]*q[1] + q[2]*q[2]/(pars[3]*pars[3])) / pars[2];
fac = v_h2 / (u*u*u) / (pars[2]*pars[2]) * (log(1+u) - u/(1+u));
grad[0] = grad[0] + fac*q[0];
grad[1] = grad[1] + fac*q[1];
grad[2] = grad[2] + fac*q[2]/(pars[3]*pars[3]);
}
void flattenednfw_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- r_s (scale radius)
- c (flattening)
*/
double G = pars[0];
double m = pars[1];
double r_s = pars[2];
double c = pars[3];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(x, 2);
double tmp_1 = pow(z, 2);
double tmp_2 = pow(c, 2);
double tmp_3 = pow(y, 2);
double tmp_4 = tmp_1 + tmp_2*(tmp_0 + tmp_3);
double tmp_5 = pow(tmp_4, 4);
double tmp_6 = 3*tmp_0;
double tmp_7 = tmp_4/tmp_2;
double tmp_8 = sqrt(tmp_7);
double tmp_9 = r_s + tmp_8;
double tmp_10 = pow(c, 8);
double tmp_11 = tmp_10*tmp_9;
double tmp_12 = tmp_11*pow(tmp_7, 7.0/2.0);
double tmp_13 = pow(tmp_4, 3);
double tmp_14 = pow(tmp_9, 2);
double tmp_15 = tmp_14*log(tmp_9/r_s);
double tmp_16 = tmp_15*tmp_2;
double tmp_17 = -tmp_11*pow(tmp_7, 9.0/2.0) + tmp_15*tmp_5;
double tmp_18 = G*m/tmp_14;
double tmp_19 = tmp_18/pow(tmp_7, 11.0/2.0);
double tmp_20 = tmp_19/tmp_10;
double tmp_21 = pow(c, 4);
double tmp_22 = pow(tmp_4, 2);
double tmp_23 = 3*tmp_9;
double tmp_24 = pow(tmp_7, 3.0/2.0);
double tmp_25 = tmp_18*x;
double tmp_26 = tmp_21*tmp_25*y*(-3*tmp_15*tmp_21*tmp_24 + tmp_21*pow(tmp_7, 5.0/2.0) + tmp_22*tmp_23)/tmp_5;
double tmp_27 = 3*tmp_16;
double tmp_28 = tmp_2*z*(tmp_2*tmp_24 + tmp_23*tmp_4 - tmp_27*tmp_8)/tmp_13;
double tmp_29 = tmp_25*tmp_28;
double tmp_30 = tmp_18*tmp_28*y;
hess[0] = hess[0] + tmp_20*(tmp_0*tmp_5 + tmp_12*tmp_6 - tmp_13*tmp_16*tmp_6 + tmp_17);
hess[1] = hess[1] + tmp_26;
hess[2] = hess[2] + tmp_29;
hess[3] = hess[3] + tmp_26;
hess[4] = hess[4] + tmp_20*(3*tmp_12*tmp_3 - tmp_13*tmp_27*tmp_3 + tmp_17 + tmp_3*tmp_5);
hess[5] = hess[5] + tmp_30;
hess[6] = hess[6] + tmp_29;
hess[7] = hess[7] + tmp_30;
hess[8] = hess[8] + tmp_13*tmp_19*(tmp_1*tmp_2*tmp_23*tmp_8 - tmp_1*tmp_27 + tmp_1*tmp_4 + tmp_16*tmp_4 - tmp_22*tmp_9/tmp_8)/pow(c, 12);
}
/* ---------------------------------------------------------------------------
Triaxial NFW - triaxiality in potential!
*/
double triaxialnfw_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (scale mass)
- r_s (scale radius)
- a (major axis)
- b (intermediate axis)
- c (minor axis)
*/
double u, v_h2;
// v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);
v_h2 = -pars[0] * pars[1] / pars[2];
u = sqrt(q[0]*q[0]/(pars[3]*pars[3])
+ q[1]*q[1]/(pars[4]*pars[4])
+ q[2]*q[2]/(pars[5]*pars[5])) / pars[2];
return v_h2 * log(1 + u) / u;
}
void triaxialnfw_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
- G (Gravitational constant)
- v_c (circular velocity at the scale radius)
- r_s (scale radius)
- a (major axis)
- b (intermediate axis)
- c (minor axis)
*/
double fac, u, v_h2;
// v_h2 = pars[1]*pars[1] / (log(2.) - 0.5);
v_h2 = pars[0] * pars[1] / pars[2];
u = sqrt(q[0]*q[0]/(pars[3]*pars[3])
+ q[1]*q[1]/(pars[4]*pars[4])
+ q[2]*q[2]/(pars[5]*pars[5])) / pars[2];
fac = v_h2 / (u*u*u) / (pars[2]*pars[2]) * (log(1+u) - u/(1+u));
grad[0] = grad[0] + fac*q[0]/(pars[3]*pars[3]);
grad[1] = grad[1] + fac*q[1]/(pars[4]*pars[4]);
grad[2] = grad[2] + fac*q[2]/(pars[5]*pars[5]);
}
void triaxialnfw_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- r_s (scale radius)
- a (major axis)
- b (intermediate axis)
- c (minor axis)
*/
double G = pars[0];
double m = pars[1];
double r_s = pars[2];
double a = pars[3];
double b = pars[4];
double c = pars[5];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(a, -2);
double tmp_1 = G*m;
double tmp_2 = tmp_0*tmp_1;
double tmp_3 = pow(x, 2);
double tmp_4 = pow(b, -2);
double tmp_5 = pow(y, 2);
double tmp_6 = pow(c, -2);
double tmp_7 = pow(z, 2);
double tmp_8 = tmp_0*tmp_3 + tmp_4*tmp_5 + tmp_6*tmp_7;
double tmp_9 = pow(tmp_8, -3.0/2.0);
double tmp_10 = 1.0/r_s;
double tmp_11 = tmp_10*sqrt(tmp_8) + 1;
double tmp_12 = log(tmp_11);
double tmp_13 = tmp_12*tmp_9;
double tmp_14 = tmp_3/pow(a, 4);
double tmp_15 = 3*tmp_1;
double tmp_16 = tmp_12/pow(tmp_8, 5.0/2.0);
double tmp_17 = tmp_15*tmp_16;
double tmp_18 = tmp_10/tmp_11;
double tmp_19 = tmp_18/tmp_8;
double tmp_20 = tmp_9/(pow(r_s, 2)*pow(tmp_11, 2));
double tmp_21 = tmp_1*tmp_20;
double tmp_22 = tmp_18/pow(tmp_8, 2);
double tmp_23 = tmp_15*tmp_22;
double tmp_24 = tmp_4*y;
double tmp_25 = tmp_2*x;
double tmp_26 = 3*tmp_25;
double tmp_27 = tmp_16*tmp_26;
double tmp_28 = tmp_20*tmp_25;
double tmp_29 = tmp_22*tmp_26;
double tmp_30 = -tmp_24*tmp_27 + tmp_24*tmp_28 + tmp_24*tmp_29;
double tmp_31 = tmp_6*z;
double tmp_32 = -tmp_27*tmp_31 + tmp_28*tmp_31 + tmp_29*tmp_31;
double tmp_33 = tmp_1*tmp_13;
double tmp_34 = tmp_5/pow(b, 4);
double tmp_35 = tmp_1*tmp_19;
double tmp_36 = tmp_24*tmp_31;
double tmp_37 = -tmp_17*tmp_36 + tmp_21*tmp_36 + tmp_23*tmp_36;
double tmp_38 = tmp_7/pow(c, 4);
hess[0] = hess[0] + tmp_13*tmp_2 - tmp_14*tmp_17 + tmp_14*tmp_21 + tmp_14*tmp_23 - tmp_19*tmp_2;
hess[1] = hess[1] + tmp_30;
hess[2] = hess[2] + tmp_32;
hess[3] = hess[3] + tmp_30;
hess[4] = hess[4] + -tmp_17*tmp_34 + tmp_21*tmp_34 + tmp_23*tmp_34 + tmp_33*tmp_4 - tmp_35*tmp_4;
hess[5] = hess[5] + tmp_37;
hess[6] = hess[6] + tmp_32;
hess[7] = hess[7] + tmp_37;
hess[8] = hess[8] + -tmp_17*tmp_38 + tmp_21*tmp_38 + tmp_23*tmp_38 + tmp_33*tmp_6 - tmp_35*tmp_6;
}
/* ---------------------------------------------------------------------------
Satoh potential
*/
double satoh_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- a (length scale 1) TODO
- b (length scale 2) TODO
*/
double S2;
S2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + pars[2]*(pars[2] + 2*sqrt(q[2]*q[2] + pars[3]*pars[3]));
return -pars[0] * pars[1] / sqrt(S2);
}
void satoh_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- a (length scale 1) TODO
- b (length scale 2) TODO
*/
double S2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + pars[2]*(pars[2] + 2*sqrt(q[2]*q[2] + pars[3]*pars[3]));
double dPhi_dS = pars[0] * pars[1] / S2;
grad[0] = grad[0] + dPhi_dS*q[0]/sqrt(S2);
grad[1] = grad[1] + dPhi_dS*q[1]/sqrt(S2);
grad[2] = grad[2] + dPhi_dS/sqrt(S2) * q[2]*(1 + pars[2] / sqrt(q[2]*q[2] + pars[3]*pars[3]));
}
double satoh_density(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- a (length scale 1) TODO
- b (length scale 2) TODO
*/
double z2b2 = q[2]*q[2] + pars[3]*pars[3];
double xyz2 = q[0]*q[0] + q[1]*q[1] + q[2]*q[2];
double S2 = xyz2 + pars[2]*(pars[2] + 2*sqrt(z2b2));
double A = pars[1] * pars[2] * pars[3]*pars[3] / (4*M_PI*S2*sqrt(S2)*z2b2);
return A * (1/sqrt(z2b2) + 3/pars[2]*(1 - xyz2/S2));
}
void satoh_hessian(double t, double *pars, double *q, int n_dim, double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- a ()
- b ()
*/
double G = pars[0];
double m = pars[1];
double a = pars[2];
double b = pars[3];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(x, 2);
double tmp_1 = pow(y, 2);
double tmp_2 = pow(z, 2);
double tmp_3 = pow(b, 2) + tmp_2;
double tmp_4 = sqrt(tmp_3);
double tmp_5 = a*(a + 2*tmp_4) + tmp_0 + tmp_1 + tmp_2;
double tmp_6 = G*m;
double tmp_7 = tmp_6/pow(tmp_5, 3.0/2.0);
double tmp_8 = tmp_6/pow(tmp_5, 5.0/2.0);
double tmp_9 = 3*tmp_8;
double tmp_10 = -tmp_9*x*y;
double tmp_11 = 3*z;
double tmp_12 = a/tmp_4;
double tmp_13 = tmp_8*(-tmp_11*tmp_12 - tmp_11);
double tmp_14 = tmp_13*x;
double tmp_15 = tmp_13*y;
hess[0] = hess[0] + -tmp_0*tmp_9 + tmp_7;
hess[1] = hess[1] + tmp_10;
hess[2] = hess[2] + tmp_14;
hess[3] = hess[3] + tmp_10;
hess[4] = hess[4] + -tmp_1*tmp_9 + tmp_7;
hess[5] = hess[5] + tmp_15;
hess[6] = hess[6] + tmp_14;
hess[7] = hess[7] + tmp_15;
hess[8] = hess[8] + -tmp_13*(-tmp_12*z - z) - tmp_7*(a*tmp_2/pow(tmp_3, 3.0/2.0) - tmp_12 - 1);
}
/* ---------------------------------------------------------------------------
Kuzmin potential
*/
double kuzmin_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- a (length scale 1) TODO
*/
double S2 = q[0]*q[0] + q[1]*q[1] + pow(pars[2] + fabs(q[2]), 2);
return -pars[0] * pars[1] / sqrt(S2);
}
void kuzmin_gradient(double t, double *pars, double *q, int n_dim,
double *grad) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- a (length scale 1) TODO
*/
double S2 = q[0]*q[0] + q[1]*q[1] + pow(pars[2] + fabs(q[2]), 2);
double fac = pars[0] * pars[1] * pow(S2, -1.5);
double zsign;
if (q[2] > 0) {
zsign = 1.;
} else if (q[2] < 0) {
zsign = -1.;
} else {
zsign = 0.;
}
grad[0] = grad[0] + fac * q[0];
grad[1] = grad[1] + fac * q[1];
grad[2] = grad[2] + fac * zsign * (pars[2] + fabs(q[2]));
}
double kuzmin_density(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- a (length scale 1) TODO
*/
if (q[2] != 0.) {
return 0.;
} else {
return pars[1] * pars[2] / (2 * M_PI) *
pow(q[0]*q[0] + q[1]*q[1] + pars[2]*pars[2], -1.5);
}
}
/* ---------------------------------------------------------------------------
Miyamoto-Nagai flattened potential
*/
double miyamotonagai_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- a (length scale 1) TODO
- b (length scale 2) TODO
*/
double zd;
zd = (pars[2] + sqrt(q[2]*q[2] + pars[3]*pars[3]));
return -pars[0] * pars[1] / sqrt(q[0]*q[0] + q[1]*q[1] + zd*zd);
}
void miyamotonagai_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- a (length scale 1) TODO
- b (length scale 2) TODO
*/
double sqrtz, zd, fac;
sqrtz = sqrt(q[2]*q[2] + pars[3]*pars[3]);
zd = pars[2] + sqrtz;
fac = pars[0]*pars[1] * pow(q[0]*q[0] + q[1]*q[1] + zd*zd, -1.5);
grad[0] = grad[0] + fac*q[0];
grad[1] = grad[1] + fac*q[1];
grad[2] = grad[2] + fac*q[2] * (1. + pars[2] / sqrtz);
}
double miyamotonagai_density(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- a (length scale 1) TODO
- b (length scale 2) TODO
*/
double M, a, b;
M = pars[1];
a = pars[2];
b = pars[3];
double R2 = q[0]*q[0] + q[1]*q[1];
double sqrt_zb = sqrt(q[2]*q[2] + b*b);
double numer = (b*b*M / (4*M_PI)) * (a*R2 + (a + 3*sqrt_zb)*(a + sqrt_zb)*(a + sqrt_zb));
double denom = pow(R2 + (a + sqrt_zb)*(a + sqrt_zb), 2.5) * sqrt_zb*sqrt_zb*sqrt_zb;
return numer/denom;
}
void miyamotonagai_hessian(double t, double *pars, double *q, int n_dim,
double *hess) {
/* pars:
- G (Gravitational constant)
- m (mass scale)
- a (length scale 1) TODO
- b (length scale 2) TODO
*/
double G = pars[0];
double m = pars[1];
double a = pars[2];
double b = pars[3];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(x, 2);
double tmp_1 = pow(y, 2);
double tmp_2 = pow(z, 2);
double tmp_3 = pow(b, 2) + tmp_2;
double tmp_4 = sqrt(tmp_3);
double tmp_5 = a + tmp_4;
double tmp_6 = pow(tmp_5, 2);
double tmp_7 = tmp_0 + tmp_1 + tmp_6;
double tmp_8 = G*m;
double tmp_9 = tmp_8/pow(tmp_7, 3.0/2.0);
double tmp_10 = 3*tmp_8/pow(tmp_7, 5.0/2.0);
double tmp_11 = tmp_10*x;
double tmp_12 = -tmp_11*y;
double tmp_13 = tmp_5/tmp_4;
double tmp_14 = tmp_13*z;
double tmp_15 = -tmp_11*tmp_14;
double tmp_16 = -tmp_10*tmp_14*y;
double tmp_17 = 1.0/tmp_3;
double tmp_18 = tmp_2*tmp_9;
hess[0] = hess[0] + -tmp_0*tmp_10 + tmp_9;
hess[1] = hess[1] + tmp_12;
hess[2] = hess[2] + tmp_15;
hess[3] = hess[3] + tmp_12;
hess[4] = hess[4] + -tmp_1*tmp_10 + tmp_9;
hess[5] = hess[5] + tmp_16;
hess[6] = hess[6] + tmp_15;
hess[7] = hess[7] + tmp_16;
hess[8] = hess[8] + -tmp_10*tmp_17*tmp_2*tmp_6 + tmp_13*tmp_9 + tmp_17*tmp_18 - tmp_18*tmp_5/pow(tmp_3, 3.0/2.0);
}
/* ---------------------------------------------------------------------------
Lee-Suto triaxial NFW from Lee & Suto (2003)
*/
double leesuto_value(double t, double *pars, double *q, int n_dim) {
/* pars: (alpha = 1)
0 - G
1 - v_c
2 - r_s
3 - a
4 - b
5 - c
*/
double x, y, z, _r, u, phi0;
double e_b2 = 1-pow(pars[4]/pars[3],2);
double e_c2 = 1-pow(pars[5]/pars[3],2);
double F1,F2,F3,costh2,sinth2,sinph2;
phi0 = pars[1]*pars[1] / (log(2.) - 0.5 + (log(2.)-0.75)*e_b2 + (log(2.)-0.75)*e_c2);
x = q[0];
y = q[1];
z = q[2];
_r = sqrt(x*x + y*y + z*z);
u = _r / pars[2];
F1 = -log(1+u)/u;
F2 = -1/3. + (2*u*u - 3*u + 6)/(6*u*u) + (1/u - pow(u,-3.))*log(1+u);
F3 = (u*u - 3*u - 6)/(2*u*u*(1+u)) + 3*pow(u,-3)*log(1+u);
costh2 = z*z / (_r*_r);
sinth2 = 1 - costh2;
sinph2 = y*y / (x*x + y*y);
//return phi0 * ((e_b2/2 + e_c2/2)*((1/u - 1/(u*u*u))*log(u + 1) - 1 + (2*u*u - 3*u + 6)/(6*u*u)) + (e_b2*y*y/(2*_r*_r) + e_c2*z*z/(2*_r*_r))*((u*u - 3*u - 6)/(2*u*u*(u + 1)) + 3*log(u + 1)/(u*u*u)) - log(u + 1)/u);
return phi0 * (F1 + (e_b2+e_c2)/2.*F2 + (e_b2*sinth2*sinph2 + e_c2*costh2)/2. * F3);
}
void leesuto_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars: (alpha = 1)
0 - G
1 - v_c
2 - r_s
3 - a
4 - b
5 - c
*/
double x, y, z, _r, _r2, _r4, ax, ay, az;
double v_h2, x0, x2, x22;
double x20, x21, x7, x1;
double x10, x13, x15, x16, x17;
double e_b2 = 1-pow(pars[4]/pars[3],2);
double e_c2 = 1-pow(pars[5]/pars[3],2);
v_h2 = pars[1]*pars[1] / (log(2.) - 0.5 + (log(2.)-0.75)*e_b2 + (log(2.)-0.75)*e_c2);
x = q[0];
y = q[1];
z = q[2];
_r2 = x*x + y*y + z*z;
_r = sqrt(_r2);
_r4 = _r2*_r2;
x0 = _r + pars[2];
x1 = x0*x0;
x2 = v_h2/(12.*_r4*_r2*_r*x1);
x10 = log(x0/pars[2]);
x13 = _r*3.*pars[2];
x15 = x13 - _r2;
x16 = x15 + 6.*(pars[2]*pars[2]);
x17 = 6.*pars[2]*x0*(_r*x16 - x0*x10*6.*(pars[2]*pars[2]));
x20 = x0*_r2;
x21 = 2.*_r*x0;
x7 = e_b2*y*y + e_c2*z*z;
x22 = -12.*_r4*_r*pars[2]*x0 + 12.*_r4*pars[2]*x1*x10 + 3.*pars[2]*x7*(x16*_r2 - 18.*x1*x10*(pars[2]*pars[2]) + x20*(2.*_r - 3.*pars[2]) + x21*(x15 + 9.*(pars[2]*pars[2]))) - x20*(e_b2 + e_c2)*(-6.*_r*pars[2]*(_r2 - (pars[2]*pars[2])) + 6.*pars[2]*x0*x10*(_r2 - 3.*(pars[2]*pars[2])) + x20*(-4.*_r + 3.*pars[2]) + x21*(-x13 + 2.*_r2 + 6.*(pars[2]*pars[2])));
ax = x2*x*(x17*x7 + x22);
ay = x2*y*(x17*(x7 - _r2*e_b2) + x22);
az = x2*z*(x17*(x7 - _r2*e_c2) + x22);
grad[0] = grad[0] + ax;
grad[1] = grad[1] + ay;
grad[2] = grad[2] + az;
}
double leesuto_density(double t, double *pars, double *q, int n_dim) {
/* pars: (alpha = 1)
0 - G
1 - v_c
2 - r_s
3 - a
4 - b
5 - c
*/
double x, y, z, u, v_h2;
double b_a2, c_a2;
b_a2 = pars[4]*pars[4] / (pars[3]*pars[3]);
c_a2 = pars[5]*pars[5] / (pars[3]*pars[3]);
double e_b2 = 1-b_a2;
double e_c2 = 1-c_a2;
v_h2 = pars[1]*pars[1] / (log(2.) - 0.5 + (log(2.)-0.75)*e_b2 + (log(2.)-0.75)*e_c2);
x = q[0];
y = q[1];
z = q[2];
u = sqrt(x*x + y*y/b_a2 + z*z/c_a2) / pars[2];
return v_h2 / (u * (1+u)*(1+u)) / (4.*M_PI*pars[2]*pars[2]*pars[0]);
}
/* ---------------------------------------------------------------------------
Logarithmic (triaxial)
*/
double logarithmic_value(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- v_c (velocity scale)
- r_h (length scale)
- q1
- q2
- q3
*/
double x, y, z;
x = q[0]*cos(pars[6]) + q[1]*sin(pars[6]);
y = -q[0]*sin(pars[6]) + q[1]*cos(pars[6]);
z = q[2];
return 0.5*pars[1]*pars[1] * log(pars[2]*pars[2] + // scale radius
x*x/(pars[3]*pars[3]) +
y*y/(pars[4]*pars[4]) +
z*z/(pars[5]*pars[5]));
}
double logarithmic_density(double t, double *pars, double *q, int n_dim) {
/* pars:
- G (Gravitational constant)
- v_c (velocity scale)
- r_h (length scale)
- q1
- q2
- q3
*/
double tmp_0 = pow(pars[3], 2);
double tmp_1 = pow(pars[4], 2);
double tmp_2 = tmp_0*tmp_1;
double tmp_3 = tmp_2*pow(q[2], 2);
double tmp_4 = pow(pars[5], 2);
double tmp_5 = tmp_0*tmp_4;
double tmp_6 = tmp_5*pow(q[1], 2);
double tmp_7 = tmp_1*tmp_4;
double tmp_8 = tmp_7*pow(q[0], 2);
double tmp_9 = pow(pars[2], 2)*tmp_2*tmp_4;
double tmp_10 = tmp_6 + tmp_8 + tmp_9;
double tmp_11 = tmp_3 + tmp_9;
return pow(pars[1], 2)*(tmp_2*(tmp_10 - tmp_3) + tmp_5*(tmp_11 - tmp_6 + tmp_8) + tmp_7*(tmp_11 + tmp_6 - tmp_8))/pow(tmp_10 + tmp_3, 2) / (4*M_PI*pars[0]);
}
void logarithmic_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* pars:
- G (Gravitational constant)
- v_c (velocity scale)
- r_h (length scale)
- q1
- q2
- q3
*/
double x, y, z, ax, ay, az, fac;
x = q[0]*cos(pars[6]) + q[1]*sin(pars[6]);
y = -q[0]*sin(pars[6]) + q[1]*cos(pars[6]);
z = q[2];
fac = pars[1]*pars[1] / (pars[2]*pars[2] + x*x/(pars[3]*pars[3]) + y*y/(pars[4]*pars[4]) + z*z/(pars[5]*pars[5]));
ax = fac*x/(pars[3]*pars[3]);
ay = fac*y/(pars[4]*pars[4]);
az = fac*z/(pars[5]*pars[5]);
grad[0] = grad[0] + (ax*cos(pars[6]) - ay*sin(pars[6]));
grad[1] = grad[1] + (ax*sin(pars[6]) + ay*cos(pars[6]));
grad[2] = grad[2] + az;
}
void logarithmic_hessian(double t, double *pars, double *q, int n_dim,
double *hess) {
/* pars:
- G (Gravitational constant)
- v_c (velocity scale)
- r_h (length scale)
- q1
- q2
- q3
*/
double v_c = pars[1];
double r_h = pars[2];
double q1 = pars[3];
double q2 = pars[4];
double q3 = pars[5];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = pow(q1, -2);
double tmp_1 = pow(v_c, 2);
double tmp_2 = tmp_0*tmp_1;
double tmp_3 = pow(x, 2);
double tmp_4 = pow(q2, -2);
double tmp_5 = pow(y, 2);
double tmp_6 = pow(q3, -2);
double tmp_7 = pow(z, 2);
double tmp_8 = pow(r_h, 2) + tmp_0*tmp_3 + tmp_4*tmp_5 + tmp_6*tmp_7;
double tmp_9 = 1.0/tmp_8;
double tmp_10 = 2.0/pow(tmp_8, 2);
double tmp_11 = tmp_1*tmp_10;
double tmp_12 = tmp_4*y;
double tmp_13 = tmp_10*tmp_2*x;
double tmp_14 = tmp_12*tmp_13;
double tmp_15 = tmp_6*z;
double tmp_16 = tmp_13*tmp_15;
double tmp_17 = tmp_1*tmp_9;
double tmp_18 = tmp_11*tmp_12*tmp_15;
// minus signs because I initially borked the sympy definition
hess[0] = hess[0] - (-tmp_2*tmp_9 + tmp_11*tmp_3/pow(q1, 4));
hess[1] = hess[1] - (tmp_14);
hess[2] = hess[2] - (tmp_16);
hess[3] = hess[3] - (tmp_14);
hess[4] = hess[4] - (-tmp_17*tmp_4 + tmp_11*tmp_5/pow(q2, 4));
hess[5] = hess[5] - (tmp_18);
hess[6] = hess[6] - (tmp_16);
hess[7] = hess[7] - (tmp_18);
hess[8] = hess[8] - (-tmp_17*tmp_6 + tmp_11*tmp_7/pow(q3, 4));
}
/* ---------------------------------------------------------------------------
Logarithmic (triaxial)
*/
double longmuralibar_value(double t, double *pars, double *q, int n_dim) {
/* http://adsabs.harvard.edu/abs/1992ApJ...397...44L
pars:
- G (Gravitational constant)
- m (mass scale)
- a
- b
- c
- alpha
*/
double x, y, z;
double a, b, c;
double Tm, Tp;
x = q[0]*cos(pars[5]) + q[1]*sin(pars[5]);
y = -q[0]*sin(pars[5]) + q[1]*cos(pars[5]);
z = q[2];
a = pars[2];
b = pars[3];
c = pars[4];
Tm = sqrt((a-x)*(a-x) + y*y + pow(b + sqrt(c*c + z*z),2));
Tp = sqrt((a+x)*(a+x) + y*y + pow(b + sqrt(c*c + z*z),2));
return pars[0]*pars[1]/(2*a) * log((x - a + Tm) / (x + a + Tp));
}
void longmuralibar_gradient(double t, double *pars, double *q, int n_dim, double *grad) {
/* http://adsabs.harvard.edu/abs/1992ApJ...397...44L
pars:
- G (Gravitational constant)
- m (mass scale)
- a
- b
- c
- alpha
*/
double x, y, z;
double a, b, c;
double Tm, Tp, fac1, fac2, fac3, bcz;
double gx, gy, gz;
x = q[0]*cos(pars[5]) + q[1]*sin(pars[5]);
y = -q[0]*sin(pars[5]) + q[1]*cos(pars[5]);
z = q[2];
a = pars[2];
b = pars[3];
c = pars[4];
bcz = b + sqrt(c*c + z*z);
Tm = sqrt((a-x)*(a-x) + y*y + bcz*bcz);
Tp = sqrt((a+x)*(a+x) + y*y + bcz*bcz);
fac1 = pars[0]*pars[1] / (2*Tm*Tp);
fac2 = 1 / (y*y + bcz*bcz);
fac3 = Tp + Tm - (4*x*x)/(Tp+Tm);
gx = 4 * fac1 * x / (Tp + Tm);
gy = fac1 * y * fac2 * fac3;
gz = fac1 * z * fac2 * fac3 * bcz / sqrt(z*z + c*c);
grad[0] = grad[0] + (gx*cos(pars[5]) - gy*sin(pars[5]));
grad[1] = grad[1] + (gx*sin(pars[5]) + gy*cos(pars[5]));
grad[2] = grad[2] + gz;
}
double longmuralibar_density(double t, double *pars, double *q, int n_dim) {
/*
Generated by sympy...
pars:
- G (Gravitational constant)
- m (mass scale)
- a
- b
- c
- alpha
*/
double a = pars[2];
double b = pars[3];
double c = pars[4];
double x = q[0]*cos(pars[5]) + q[1]*sin(pars[5]);
double y = -q[0]*sin(pars[5]) + q[1]*cos(pars[5]);
double z = q[2];
double tmp0 = a - x;
double tmp1 = pow(tmp0, 2);
double tmp2 = pow(y, 2);
double tmp3 = pow(z, 2);
double tmp4 = pow(c, 2) + tmp3;
double tmp5 = sqrt(tmp4);
double tmp6 = b + tmp5;
double tmp7 = pow(tmp6, 2);
double tmp8 = tmp2 + tmp7;
double tmp9 = tmp1 + tmp8;
double tmp10 = sqrt(tmp9);
double tmp11 = -a + tmp10 + x;
double tmp12 = 1.0/tmp11;
double tmp13 = 1.0/tmp10;
double tmp14 = pow(tmp9, -1.5);
double tmp15 = 1.0/tmp4;
double tmp16 = tmp13*tmp3;
double tmp17 = tmp6/tmp5;
double tmp18 = pow(tmp4, -1.5);
double tmp19 = tmp15*tmp3*tmp7;
double tmp20 = 2*tmp2;
double tmp21 = a + x;
double tmp22 = pow(tmp21, 2);
double tmp23 = tmp22 + tmp8;
double tmp24 = sqrt(tmp23);
double tmp25 = 1.0/tmp24;
double tmp26 = tmp21 + tmp24;
double tmp27 = 1.0/tmp26;
double tmp28 = tmp25*tmp27;
double tmp29 = tmp11*tmp28;
double tmp30 = tmp11*tmp27/pow(tmp23, 1.5);
double tmp31 = 1.0/tmp23;
double tmp32 = pow(tmp26, -2);
double tmp33 = tmp11*tmp31*tmp32;
double tmp34 = tmp21*tmp25 + 1;
double tmp35 = tmp27*tmp34;
double tmp36 = tmp13*tmp15*tmp3*tmp7;
double tmp37 = -tmp13 + tmp29;
double tmp38 = tmp2*tmp37;
double tmp39 = tmp0*tmp13;
double tmp40 = tmp11*tmp27*tmp34 + tmp39 - 1;
return pars[1]/8.*tmp12*(2*tmp11*tmp32*pow(tmp34, 2) +
tmp12*tmp13*tmp38 + tmp12*tmp36*tmp37 + tmp12*tmp40*(-tmp39 + 1) +
tmp13*tmp17 - tmp13*tmp20*tmp25*tmp27 + tmp13*(-tmp1/tmp9 + 1) + tmp13 -
tmp14*tmp19 - tmp14*tmp2 + tmp15*tmp16 - tmp15*tmp28*tmp3*tmp37*tmp7 -
tmp15*tmp29*tmp3 + 2*tmp15*tmp3*tmp33*tmp7 - tmp16*tmp18*tmp6 -
tmp17*tmp29 + tmp18*tmp29*tmp3*tmp6 + tmp19*tmp30 + tmp2*tmp30 +
tmp20*tmp33 - 2*tmp25*tmp27*tmp36 - tmp28*tmp38 - tmp29*(-tmp22*tmp31 +
1) - tmp29 - tmp35*tmp40 - tmp35*(-2*tmp0*tmp13 + 2))/(M_PI*a);
}
void longmuralibar_hessian(double t, double *pars, double *q, int n_dim,
double *hess) {
/* Generated by sympy...
pars:
- G (Gravitational constant)
- m (mass scale)
- a
- b
- c
- alpha
*/
double G = pars[0];
double m = pars[1];
double a = pars[2];
double b = pars[3];
double c = pars[4];
double alpha = pars[5];
double x = q[0];
double y = q[1];
double z = q[2];
double tmp_0 = cos(alpha);
double tmp_1 = tmp_0*x;
double tmp_2 = sin(alpha);
double tmp_3 = tmp_2*y;
double tmp_4 = tmp_1 + tmp_3;
double tmp_5 = a + tmp_4;
double tmp_6 = tmp_0*tmp_5;
double tmp_7 = tmp_0*y - tmp_2*x;
double tmp_8 = tmp_2*tmp_7;
double tmp_9 = -tmp_8;
double tmp_10 = tmp_6 + tmp_9;
double tmp_11 = pow(z, 2);
double tmp_12 = pow(c, 2) + tmp_11;
double tmp_13 = sqrt(tmp_12);
double tmp_14 = b + tmp_13;
double tmp_15 = pow(tmp_14, 2);
double tmp_16 = tmp_15 + pow(tmp_7, 2);
double tmp_17 = tmp_16 + pow(tmp_5, 2);
double tmp_18 = sqrt(tmp_17);
double tmp_19 = 1.0/tmp_18;
double tmp_20 = tmp_10*tmp_19;
double tmp_21 = tmp_18 + tmp_5;
double tmp_22 = 1.0/tmp_21;
double tmp_23 = a - tmp_1 - tmp_3;
double tmp_24 = tmp_0*tmp_23;
double tmp_25 = -tmp_24 + tmp_9;
double tmp_26 = tmp_16 + pow(tmp_23, 2);
double tmp_27 = sqrt(tmp_26);
double tmp_28 = 1.0/tmp_27;
double tmp_29 = tmp_25*tmp_28;
double tmp_30 = tmp_0 + tmp_29;
double tmp_31 = -tmp_0;
double tmp_32 = -tmp_20 + tmp_31;
double tmp_33 = pow(tmp_21, -2);
double tmp_34 = -a + tmp_27 + tmp_4;
double tmp_35 = tmp_33*tmp_34;
double tmp_36 = tmp_22*tmp_30 + tmp_32*tmp_35;
double tmp_37 = (1.0/2.0)*G*m/a;
double tmp_38 = tmp_37/tmp_34;
double tmp_39 = tmp_36*tmp_38;
double tmp_40 = tmp_21*tmp_37/pow(tmp_34, 2);
double tmp_41 = tmp_36*tmp_40;
double tmp_42 = tmp_32*tmp_33;
double tmp_43 = pow(tmp_0, 2) + pow(tmp_2, 2);
double tmp_44 = tmp_28*tmp_43;
double tmp_45 = pow(tmp_26, -3.0/2.0);
double tmp_46 = tmp_25*tmp_45;
double tmp_47 = -tmp_19*tmp_43;
double tmp_48 = pow(tmp_17, -3.0/2.0);
double tmp_49 = tmp_10*tmp_48;
double tmp_50 = tmp_34/pow(tmp_21, 3);
double tmp_51 = tmp_32*tmp_50;
double tmp_52 = tmp_21*tmp_38;
double tmp_53 = tmp_0*tmp_7;
double tmp_54 = tmp_2*tmp_5;
double tmp_55 = tmp_53 + tmp_54;
double tmp_56 = tmp_19*tmp_55;
double tmp_57 = tmp_2 + tmp_56;
double tmp_58 = -tmp_2;
double tmp_59 = tmp_2*tmp_23;
double tmp_60 = tmp_53 - tmp_59;
double tmp_61 = tmp_28*tmp_60;
double tmp_62 = tmp_58 - tmp_61;
double tmp_63 = -tmp_53;
double tmp_64 = tmp_59 + tmp_63;
double tmp_65 = tmp_22*tmp_46;
double tmp_66 = -tmp_56 + tmp_58;
double tmp_67 = tmp_33*tmp_66;
double tmp_68 = tmp_2 + tmp_61;
double tmp_69 = -tmp_54 + tmp_63;
double tmp_70 = tmp_35*tmp_49;
double tmp_71 = -2*tmp_2 - 2*tmp_56;
double tmp_72 = tmp_39*tmp_57 + tmp_41*tmp_62 + tmp_52*(tmp_30*tmp_67 + tmp_42*tmp_68 + tmp_51*tmp_71 + tmp_64*tmp_65 - tmp_69*tmp_70);
double tmp_73 = 1.0/tmp_13;
double tmp_74 = tmp_14*tmp_73;
double tmp_75 = tmp_74*z;
double tmp_76 = tmp_19*tmp_75;
double tmp_77 = tmp_28*tmp_75;
double tmp_78 = tmp_19*tmp_33;
double tmp_79 = tmp_75*tmp_78;
double tmp_80 = 2*tmp_76;
double tmp_81 = tmp_39*tmp_76 - tmp_41*tmp_77 + tmp_52*(-tmp_30*tmp_79 + tmp_42*tmp_77 - tmp_51*tmp_80 - tmp_65*tmp_75 + tmp_70*tmp_75);
double tmp_82 = tmp_22*tmp_68 + tmp_35*tmp_66;
double tmp_83 = tmp_38*tmp_82;
double tmp_84 = tmp_40*tmp_82;
double tmp_85 = tmp_45*tmp_60;
double tmp_86 = tmp_50*tmp_66;
double tmp_87 = tmp_48*tmp_55;
double tmp_88 = tmp_52*(-tmp_22*tmp_75*tmp_85 + tmp_35*tmp_75*tmp_87 + tmp_67*tmp_77 - tmp_68*tmp_79 - tmp_80*tmp_86) + tmp_76*tmp_83 - tmp_77*tmp_84;
double tmp_89 = tmp_22*tmp_28;
double tmp_90 = tmp_14*tmp_89;
double tmp_91 = tmp_73*tmp_90;
double tmp_92 = tmp_19*tmp_35;
double tmp_93 = tmp_74*tmp_92;
double tmp_94 = tmp_91*z - tmp_93*z;
double tmp_95 = tmp_11/tmp_12;
double tmp_96 = tmp_11/pow(tmp_12, 3.0/2.0);
double tmp_97 = tmp_15*tmp_95;
double tmp_98 = 2*tmp_97;
hess[0] = hess[0] + tmp_39*(tmp_0 + tmp_20) + tmp_41*(-tmp_29 + tmp_31) + tmp_52*(tmp_22*(tmp_44 + tmp_46*(tmp_24 + tmp_8)) + 2*tmp_30*tmp_42 + tmp_35*(tmp_47 - tmp_49*(-tmp_6 + tmp_8)) + tmp_51*(-2*tmp_0 - 2*tmp_20));
hess[1] = hess[1] + tmp_72;
hess[2] = hess[2] + tmp_81;
hess[3] = hess[3] + tmp_72;
hess[4] = hess[4] + tmp_52*(tmp_22*(tmp_44 + tmp_64*tmp_85) + tmp_35*(tmp_47 - tmp_69*tmp_87) + 2*tmp_67*tmp_68 + tmp_71*tmp_86) + tmp_57*tmp_83 + tmp_62*tmp_84;
hess[5] = hess[5] + tmp_88;
hess[6] = hess[6] + tmp_81;
hess[7] = hess[7] + tmp_88;
hess[8] = hess[8] + tmp_38*tmp_76*tmp_94 - tmp_40*tmp_77*tmp_94 + tmp_52*(tmp_14*tmp_92*tmp_96 - tmp_22*tmp_45*tmp_97 - tmp_28*tmp_78*tmp_98 + tmp_35*tmp_48*tmp_97 + tmp_89*tmp_95 - tmp_90*tmp_96 + tmp_91 - tmp_92*tmp_95 - tmp_93 + tmp_50*tmp_98/tmp_17);
}
| {
"alphanum_fraction": 0.5374982189,
"avg_line_length": 33.4195767196,
"ext": "c",
"hexsha": "3f820ef9ad22e2051c24b79bcf72153651db886e",
"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": "0fdaf9159bccc59af2a3525f2926e04501754f48",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "akeemlh/gala",
"max_forks_repo_path": "gala/potential/potential/builtin/builtin_potentials.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0fdaf9159bccc59af2a3525f2926e04501754f48",
"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": "akeemlh/gala",
"max_issues_repo_path": "gala/potential/potential/builtin/builtin_potentials.c",
"max_line_length": 362,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0fdaf9159bccc59af2a3525f2926e04501754f48",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "akeemlh/gala",
"max_stars_repo_path": "gala/potential/potential/builtin/builtin_potentials.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 25274,
"size": 63163
} |
#ifndef INCLUDED_BLAS_L3_SYRK_H
#define INCLUDED_BLAS_L3_SYRK_H
#include <complex>
#include <cblas.h>
namespace blas{
void syrk( CBLAS_ORDER order, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans,
std::size_t n, std::size_t k, float alpha, const float* A,
std::size_t lda, float beta, float* C, std::size_t ldc ){
return cblas_ssyrk( order, uplo, trans, n, k, alpha, A, lda, beta, C,
ldc );
}
void syrk( CBLAS_ORDER order, CBLAS_UPLO uplo,
CBLAS_TRANSPOSE trans, std::size_t n, std::size_t k, double alpha,
const double* A, std::size_t lda, double beta, double* C,
std::size_t ldc ){
return cblas_dsyrk( order, uplo, trans, n, k, alpha, A, lda, beta, C,
ldc );
}
void syrk( CBLAS_ORDER order, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans,
std::size_t n, std::size_t k, const std::complex<float>* alpha,
const std::complex<float>* A, std::size_t lda,
const std::complex<float>* beta, std::complex<float>* C,
std::size_t ldc ){
return cblas_csyrk( order, uplo, trans, n, k, (float*) alpha,
(float*) A, lda, (float*) beta, (float*) C, ldc );
}
void syrk( CBLAS_ORDER order, CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans,
std::size_t n, std::size_t k, const std::complex<double>* alpha,
const std::complex<double>* A, std::size_t lda,
const std::complex<double>* beta, std::complex<double>* C,
std::size_t ldc ){
return cblas_zsyrk( order, uplo, trans, n, k, (double*) alpha,
(double*) A, lda, (double*) beta, (double*) C, ldc );
}
} //namespace blas
#endif
| {
"alphanum_fraction": 0.6155703078,
"avg_line_length": 39.4523809524,
"ext": "h",
"hexsha": "ff23941bea4eb73a133d8cdc7ad811f7e1d5243b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tbepler/telepath",
"max_forks_repo_path": "include/telepath/blas/level3/syrk.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tbepler/telepath",
"max_issues_repo_path": "include/telepath/blas/level3/syrk.h",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "636f7345b6479d5c48dbf03cb17343b14c305c7c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tbepler/telepath",
"max_stars_repo_path": "include/telepath/blas/level3/syrk.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 507,
"size": 1657
} |
/********************************\
* Matrix Multiply Test Benchmark *
* *
* by *
* Elliott Forney *
* 3.15.2010 *
\********************************/
/*
* Libraries
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <getopt.h>
#include <cblas.h>
#include "matrix.h"
#include "benchmark.h"
#include "errcheck.h"
/*
* Macros
*/
// print command line usage
#define print_usage() fprintf(stdout, "Usage: %s [-m a_rows] [-n a_cols] [-p b_cols] [-s]\n", arg[0])
// acceptable maximum relative error tolerance
#define TOLERANCE 0.01
#define DEBUG 0
/*
* Global variables
*/
// flag for simple, one line output
bool simple_out = false;
/*
* Function prototypes
*/
// parse command line arguments
void parse_args(int narg, char **arg,
unsigned *m, unsigned *n,
unsigned *p);
/*
* Function bodies
*/
// setup network
int main(int narg, char **arg)
{
// default matrix dimensions
unsigned m = 6400;
unsigned n = 0;
unsigned p = 0;
// parse command line arguments
parse_args(narg, arg, &m, &n, &p);
// if n or p == 0 then set to m
if (n == 0)
n = m;
if (p == 0)
p = m;
if (DEBUG > 0)
printf("m: %d\nn: %d\np: %d\n", m, n, p);
// create matrix to hold result
matrix result;
matrix_init(&result, m, p);
matrix_load_runif(result, 500, 600);
// load test matrix a
matrix a;
matrix_init(&a, m, p);
// matrix_load_testa(a, n);
// load test matrix b
matrix b;
matrix_init(&b, m, n);
// matrix_load_testb(b);
matrix_load_runif(b, 0, 1);
// load test matrix c
matrix c;
matrix_init(&c, n, p);
matrix_load_testc(c);
matrix_load_runif(c, 0, 1);
// figure a with BLAS
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
b.r, c.c, b.c, 1.0f,
b.cpu_data, b.cstride, c.cpu_data, c.cstride,
0.0f, a.cpu_data, a.cstride);
// run warm up
matrix_mult(result, b, c);
// wait for all kernels to finish
matrix_wait();
// create a new benchmark timer
benchmark ben;
benchmark_init(&ben);
// start timer
benchmark_start_timer(&ben);
// run multiplication
matrix_mult(result, b, c);
// wait for all kernels to finish
matrix_wait();
if (DEBUG > 5)
{
printf("a:\n");
matrix_print_padded(a);
printf("b:\n");
matrix_print_padded(b);
printf("c:\n");
matrix_print_padded(c);
printf("result:\n");
matrix_print_padded(result);
}
// stop timer
benchmark_stop_timer(&ben);
// figure giga floating point operatins per second
benchmark_add_flop(&ben, matmult_nflop(m,n,p));
benchmark_add_byte(&ben, (m*n+n*p+m*p)*sizeof(float));
double gbytes = benchmark_check_gbytes(ben);
double gflops = benchmark_check_gflops(ben);
double time = benchmark_check_timer(ben);
//
float rmse = matrix_rmse(a, result);
bool passed = true;
if (rmse > TOLERANCE)
passed = false;
// if simple output requested
if (simple_out)
// simply print time, gflops and error
printf("%f %f\n", time*1e3f, gflops);
// if full output requested
else
{
if (passed)
printf("Test Passed!\n=======\n");
else
printf("Test Failed!\n=======\n");
// print time and gflops
printf("Time: %f GByteS: %f GFlopS: %f RMSE: %f\n",
time, gbytes, gflops, rmse);
}
// clean up
matrix_dest(&a);
matrix_dest(&b);
matrix_dest(&c);
matrix_dest(&result);
benchmark_dest(&ben);
// Come back soon now ya'hear!
return 0;
}
// parse command line arguments
void parse_args(int narg, char **arg,
unsigned *m, unsigned *n,
unsigned *p)
{
int opt; // getopt output
// for each argument
while ((opt = getopt(narg, arg, "sm:n:p:")) != -1)
{
if (opt == 's')
simple_out = true;
else if (opt == 'm')
*m = (unsigned)atoi(arg[optind-1]);
else if (opt == 'n')
*n = (unsigned)atoi(arg[optind-1]);
else if (opt == 'p')
*p = (unsigned)atoi(arg[optind-1]);
// print usage and quit on unknown option
else
{
print_usage();
exit(1);
}
}
// assume last non dash arg is m
if (optind < narg)
*m = (unsigned)atoi(arg[optind]);
}
| {
"alphanum_fraction": 0.5769761029,
"avg_line_length": 20.1481481481,
"ext": "c",
"hexsha": "174bfd46ae9e8ee435b02d07045feba0ed103016",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "75028a7e42e4a02460f20f1aa82c289801de1b05",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "idfah/badger",
"max_forks_repo_path": "mult.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "75028a7e42e4a02460f20f1aa82c289801de1b05",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "idfah/badger",
"max_issues_repo_path": "mult.c",
"max_line_length": 101,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "75028a7e42e4a02460f20f1aa82c289801de1b05",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "idfah/badger",
"max_stars_repo_path": "mult.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1281,
"size": 4352
} |
/*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*
** **
** 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. **
** **
**~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*/
#if 0
/*
Performs y = ( G^T G )^{-1} ( G^T K G ) ( G^T G )^{-1} x
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <petsc.h>
#include <petscmat.h>
#include <petscvec.h>
#include <petscksp.h>
#include <petscpc.h>
#include "common-driver-utils.h"
#include <petscversion.h>
#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )
#if (PETSC_VERSION_MINOR >=6)
#include "petsc/private/pcimpl.h"
#include "petsc/private/kspimpl.h"
#else
#include "petsc-private/pcimpl.h"
#include "petsc-private/kspimpl.h"
#endif
#else
#include "private/pcimpl.h"
#include "private/kspimpl.h"
#endif
#include "pc_ScaledGtKG.h"
#include <StGermain/StGermain.h>
#include <StgDomain/StgDomain.h>
#define PCTYPE_SCGtKG "scgtkg"
/* private data */
typedef struct {
Mat B, Bt, F, C; /* Bt \in [M x N], F \in [M x M] */
Vec X1,X2, Y1,Y2; /* the scaling vectors */
Vec s,t,X; /* s \in [M], t \in [N], X \in [M] */
KSP ksp_BBt; /* The user MUST provide this operator */
PetscTruth BBt_has_cnst_nullspace;
PetscTruth monitor_activated;
} _PC_SC_GtKG;
typedef _PC_SC_GtKG* PC_SC_GtKG;
/* private prototypes */
PetscErrorCode BSSCR_PCApply_ScGtKG( PC pc, Vec x, Vec y );
PetscErrorCode BSSCR_PCApplyTranspose_ScGtKG( PC pc, Vec x, Vec y );
PetscErrorCode BSSCR_PCSetUp_GtKG( PC pc );
PetscErrorCode BSSCR_BSSCR_pc_error_ScGtKG( PC pc, const char func_name[] )
{
const PCType type;
PCGetType( pc, &type );
if( strcmp(type,PCTYPE_SCGtKG)!=0 ) {
printf("Error(%s): PC type (%s) should be scgtkg. \n",func_name, type );
PetscFinalize();
exit(0);
}
PetscFunctionReturn(0);
}
void BSSCR_BSSCR_get_number_nonzeros_AIJ_ScGtKG( Mat A, PetscInt *nnz )
{
MatInfo info;
MatGetInfo( A, MAT_GLOBAL_SUM, &info );
*nnz = info.nz_used;
}
PetscErrorCode BSSCR_PCScGtKGBBtContainsConstantNullSpace( PC pc, PetscTruth *has_cnst_nullsp )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
PetscInt N;
PetscScalar sum;
PetscReal nrm;
Vec l,r;
Mat BBt,A;
Stg_KSPGetOperators( ctx->ksp_BBt, &BBt, PETSC_NULL, PETSC_NULL );
A = BBt;
MatGetVecs( A, &r, &l ); // l = A r
VecGetSize(r,&N);
sum = 1.0/N;
VecSet(r,sum);
/* scale */
VecPointwiseMult( r, r, ctx->Y2 );
/* {l} = [A] {r} */
MatMult( A,r, l );
/* scale */
VecPointwiseMult( l, l, ctx->X2 );
VecNorm(l,NORM_2,&nrm);
if (nrm < 1.e-7) {
*has_cnst_nullsp = PETSC_TRUE;
}
else {
*has_cnst_nullsp = PETSC_FALSE;
}
Stg_VecDestroy(&l);
Stg_VecDestroy(&r);
PetscFunctionReturn(0);
}
/*
I should not modify setup called!!
This is handled via petsc.
*/
PetscErrorCode BSSCR_PCSetUp_ScGtKG( PC pc )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
if( ctx->F == PETSC_NULL ) { Stg_SETERRQ( PETSC_ERR_SUP, "gtkg: F not set" ); }
if( ctx->Bt == PETSC_NULL ) { Stg_SETERRQ( PETSC_ERR_SUP, "gtkg: Bt not set" ); }
if(ctx->ksp_BBt==PETSC_NULL) {
BSSCR_PCScGtKGUseStandardBBtOperator( pc ) ;
}
BSSCR_PCScGtKGBBtContainsConstantNullSpace( pc, &ctx->BBt_has_cnst_nullspace );
if( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {
PetscPrintf( PETSC_COMM_WORLD, "\t* Detected prescence of constant nullspace in BBt-C\n" );
}
PetscFunctionReturn(0);
}
PetscErrorCode BSSCR_PCDestroy_ScGtKG( PC pc )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
if( ctx == PETSC_NULL ) { PetscFunctionReturn(0); }
if( ctx->ksp_BBt != PETSC_NULL ) { Stg_KSPDestroy(&ctx->ksp_BBt ); }
if( ctx->s != PETSC_NULL ) { Stg_VecDestroy(&ctx->s ); }
if( ctx->X != PETSC_NULL ) { Stg_VecDestroy(&ctx->X ); }
if( ctx->t != PETSC_NULL ) { Stg_VecDestroy(&ctx->t ); }
if( ctx->X1 != PETSC_NULL ) { Stg_VecDestroy(&ctx->X1 ); }
if( ctx->X2 != PETSC_NULL ) { Stg_VecDestroy(&ctx->X2 ); }
if( ctx->Y1 != PETSC_NULL ) { Stg_VecDestroy(&ctx->Y1 ); }
if( ctx->Y2 != PETSC_NULL ) { Stg_VecDestroy(&ctx->Y2 ); }
PetscFree( ctx );
PetscFunctionReturn(0);
}
PetscErrorCode BSSCR_PCView_ScGtKG( PC pc, PetscViewer viewer )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
PetscViewerASCIIPushTab(viewer); //1
PetscViewerASCIIPrintf( viewer, "gtkg-ksp \n" );
PetscViewerASCIIPrintf(viewer,"---------------------------------\n");
PetscViewerASCIIPushTab(viewer);
KSPView( ctx->ksp_BBt, viewer );
PetscViewerASCIIPopTab(viewer);
PetscViewerASCIIPrintf(viewer,"---------------------------------\n");
PetscViewerASCIIPopTab(viewer); //1
PetscFunctionReturn(0);
}
PetscErrorCode BSSCRBSSCR_Lp_monitor_ScGtKG( KSP ksp, PetscInt index )
{
PetscInt max_it;
PetscReal rnorm;
KSPConvergedReason reason;
KSPGetIterationNumber( ksp, &max_it );
KSPGetResidualNorm( ksp, &rnorm );
KSPGetConvergedReason( ksp, &reason );
if (reason >= 0) {
PetscPrintf(((PetscObject)ksp)->comm,"\t<Lp(%d)>: Linear solve converged. its.=%.4d ; |r|=%5.5e ; Reason=%s\n",
index, max_it, rnorm, KSPConvergedReasons[reason] );
} else {
PetscPrintf(((PetscObject)ksp)->comm,"\t<Lp(%d)>: Linear solve did not converge. its.=%.4d ; |r|=%5.5e ; Residual reduction=%2.2e ; Reason=%s\n",
index, max_it, rnorm, (ksp->rnorm0/rnorm), KSPConvergedReasons[reason]);
}
PetscFunctionReturn(0);
}
PetscErrorCode BSSCR_PCScBFBTSubKSPMonitor( KSP ksp, PetscInt index, PetscLogDouble time )
{
PetscInt max_it;
PetscReal rnorm;
KSPConvergedReason reason;
KSPGetIterationNumber( ksp, &max_it );
KSPGetResidualNorm( ksp, &rnorm );
KSPGetConvergedReason( ksp, &reason );
PetscPrintf(((PetscObject)ksp)->comm," PCScBFBTSubKSP (%d): %D Residual norm; r0 %12.12e, r %12.12e: Reason %s: Time %5.5e \n",
index, max_it, ksp->rnorm0, rnorm, KSPConvergedReasons[reason], time );
PetscFunctionReturn(0);
}
/*
Performs y <- S*^{-1} x
S*^{-1} = ( B' Bt' )^{-1} B' F' Bt' ( B' Bt' )^{-1}
where
F' = X1 F Y1
Bt' = X1 Bt Y2
B' = X2 B Y1
Thus, S*^{-1} = [ X2 B Y1 X1 Bt Y2 ]^{-1} . [ X2 B Y1 . X1 F Y1 . X1 Bt Y2 ] . [ X2 B Y1 X1 Bt Y2 ]^{-1}
= Y2^{-1} ksp_BBt X2^{-1} . [ B' F' Bt' ] . Y2^{-1} ksp_BBt X2^{-1}
= Y2^{-1} ksp_BBt . [ B Y1 . X1 F Y1 . X1 Bt ] . ksp_BBt X2^{-1}
*/
PetscErrorCode BSSCR_PCApply_ScGtKG( PC pc, Vec x, Vec y )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
KSP ksp;
Mat F, Bt;
Vec s,t,X;
PetscLogDouble t0,t1;
ksp = ctx->ksp_BBt;
F = ctx->F;
Bt = ctx->Bt;
s = ctx->s;
t = ctx->t;
X = ctx->X;
/* Apply scaled Poisson operator */
/* scale x */
/* ========================================================
NOTE:
I THINK TO OMIT THESE AS WE WANT TO UNSCALE THE
PRECONDITIONER AS S IN THIS CASE IS NOT SCALED
======================================================== */
// VecPointwiseDivide( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */
if( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {
BSSCR_VecRemoveConstNullspace( x, PETSC_NULL );
}
PetscGetTime(&t0);
KSPSolve( ksp, x, t ); /* t <- GtG_inv x */
PetscGetTime(&t1);
if (ctx->monitor_activated) {
BSSCR_PCScBFBTSubKSPMonitor(ksp,1,(t1-t0));
}
/* Apply Bt */
MatMult( Bt, t, s ); /* s <- G t */
VecPointwiseMult( s, s, ctx->X1 ); /* s <- s * X1 */
/* Apply F */
VecPointwiseMult( s, s, ctx->Y1 ); /* s <- s * Y1 */
MatMult( F, s, X ); /* X <- K s */
VecPointwiseMult( X, X, ctx->X1 ); /* X <- X * X1 */
/* Apply B */
VecPointwiseMult( X, X, ctx->Y1 ); /* X <- X * Y1 */
MatMultTranspose( Bt, X, t ); /* t <- Gt X */
if( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {
BSSCR_VecRemoveConstNullspace( t, PETSC_NULL );
}
PetscGetTime(&t0);
KSPSolve( ksp, t, y ); /* y <- GtG_inv t */
PetscGetTime(&t1);
if (ctx->monitor_activated) {
BSSCR_PCScBFBTSubKSPMonitor(ksp,2,(t1-t0));
}
VecPointwiseMult( y, y, ctx->Y2 ); /* y <- y/Y2 */
/* undo modification made to x on entry */
// VecPointwiseMult( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */
PetscFunctionReturn(0);
}
/*
Performs y <- S*^{-1} x
S*^{-1} = ( B' Bt' )^{-1} B' F' Bt' - C' ( B' Bt' )^{-1}
where
F' = X1 F Y1
Bt' = X1 Bt Y2
B' = X2 B Y1
C' = X2 C Y2
Thus, S*^{-1} = [ X2 B Y1 X1 Bt Y2 ]^{-1} . [ X2 B Y1 . X1 F Y1 . X1 Bt Y2 - X2 C Y2 ] . [ X2 B Y1 X1 Bt Y2 ]^{-1}
= Y2^{-1} ksp_BBt X2^{-1} . [ B' F' Bt' - C' ] . Y2^{-1} ksp_BBt X2^{-1}
= Y2^{-1} ksp_BBt . [ B Y1 . X1 F Y1 . X1 Bt - C ] . ksp_BBt X2^{-1}
*/
PetscErrorCode BSSCR_BSSCR_PCApply_ScGtKG_C( PC pc, Vec x, Vec y )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
KSP ksp;
Mat F, Bt,C;
Vec s,t,X;
PetscLogDouble t0,t1;
ksp = ctx->ksp_BBt;
F = ctx->F;
Bt = ctx->Bt;
C = ctx->C;
s = ctx->s;
t = ctx->t;
X = ctx->X;
/* Apply scaled Poisson operator */
/* scale x */
/* ========================================================
NOTE:
I THINK TO OMIT THESE AS WE WANT TO UNSCALE THE
PRECONDITIONER AS S IN THIS CASE IS NOT SCALED
======================================================== */
// VecPointwiseDivide( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */
if( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {
BSSCR_VecRemoveConstNullspace( x, PETSC_NULL );
}
PetscGetTime(&t0);
KSPSolve( ksp, x, t ); /* t <- GtG_inv x */
PetscGetTime(&t1);
if (ctx->monitor_activated) {
BSSCR_PCScBFBTSubKSPMonitor(ksp,1,(t1-t0));
}
/* Apply Bt */
MatMult( Bt, t, s ); /* s <- G t */
VecPointwiseMult( s, s, ctx->X1 ); /* s <- s * X1 */
/* Apply F */
VecPointwiseMult( s, s, ctx->Y1 ); /* s <- s * Y1 */
MatMult( F, s, X ); /* X <- K s */
VecPointwiseMult( X, X, ctx->X1 ); /* X <- X * X1 */
/* Apply B */
VecPointwiseMult( X, X, ctx->Y1 ); /* X <- X * Y1 */
MatMultTranspose( Bt, X, s ); /* s <- Gt X */
/* s <- s - C t */
VecScale( s, -1.0 );
MatMultAdd( C, t, s, s );
VecScale( s, -1.0 );
if( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {
BSSCR_VecRemoveConstNullspace( s, PETSC_NULL );
}
PetscGetTime(&t0);
KSPSolve( ksp, s, y ); /* y <- GtG_inv s */
PetscGetTime(&t1);
if (ctx->monitor_activated) {
BSSCR_PCScBFBTSubKSPMonitor(ksp,2,(t1-t0));
}
VecPointwiseMult( y, y, ctx->Y2 ); /* y <- y/Y2 */
/* undo modification made to x on entry */
// VecPointwiseMult( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */
PetscFunctionReturn(0);
}
/* Need to check this one if correct */
/*
S^{-1} = ( G^T G )^{-1} G^T K G ( G^T G )^{-1}
= A C A
S^{-T} = A^T (A C)^T
= A^T C^T A^T, but A = G^T G which is symmetric
= A C^T A
= A G^T ( G^T K )^T A
= A G^T K^T G A
*/
PetscErrorCode BSSCR_PCApplyTranspose_ScGtKG( PC pc, Vec x, Vec y )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
KSP ksp;
Mat F, Bt;
Vec s,t,X;
PetscLogDouble t0,t1;
ksp = ctx->ksp_BBt;
F = ctx->F;
Bt = ctx->Bt;
s = ctx->s;
t = ctx->t;
X = ctx->X;
/* Apply scaled Poisson operator */
/* scale x */
/* ========================================================
NOTE:
I THINK TO OMIT THESE AS WE WANT TO UNSCALE THE
PRECONDITIONER AS S IN THIS CASE IS NOT SCALED
======================================================== */
// VecPointwiseDivide( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */
if( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {
BSSCR_VecRemoveConstNullspace( x, PETSC_NULL );
}
PetscGetTime(&t0);
KSPSolveTranspose( ksp, x, t ); /* t <- GtG_inv x */
PetscGetTime(&t1);
if (ctx->monitor_activated) {
BSSCR_PCScBFBTSubKSPMonitor(ksp,1,(t1-t0));
}
/* Apply Bt */
MatMult( Bt, t, s ); /* s <- G t */
VecPointwiseMult( s, s, ctx->X1 ); /* s <- s * X1 */
/* Apply F */
VecPointwiseMult( s, s, ctx->Y1 ); /* s <- s * Y1 */
MatMultTranspose( F, s, X ); /* X <- K s */
VecPointwiseMult( X, X, ctx->X1 ); /* X <- X * X1 */
/* Apply B */
VecPointwiseMult( X, X, ctx->Y1 ); /* X <- X * Y1 */
MatMultTranspose( Bt, X, t ); /* t <- Gt X */
if( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {
BSSCR_VecRemoveConstNullspace( t, PETSC_NULL );
}
PetscGetTime(&t0);
KSPSolveTranspose( ksp, t, y ); /* y <- GtG_inv t */
PetscGetTime(&t1);
if (ctx->monitor_activated) {
BSSCR_PCScBFBTSubKSPMonitor(ksp,2,(t1-t0));
}
VecPointwiseMult( y, y, ctx->Y2 ); /* y <- y/Y2 */
/* undo modification made to x on entry */
// VecPointwiseMult( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */
PetscFunctionReturn(0);
}
/*
Performs y <- S^{-1} x
S^{-1} = ( G^T Di G )^{-1} G^T Di K Di G ( G^T Di G )^{-1}
where Di = diag(M)^{-1}
*/
/*
Only the options related to GtKG should be set here.
*/
PetscErrorCode BSSCR_PCSetFromOptions_ScGtKG( PC pc )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
PetscTruth ivalue, flg;
if(ctx->ksp_BBt!=PETSC_NULL) {
PetscOptionsGetTruth( PETSC_NULL, "-pc_gtkg_monitor", &ivalue, &flg );
BSSCR_PCScGtKGSetSubKSPMonitor( pc, ivalue );
}
PetscFunctionReturn(0);
}
/* ---- Exposed functions ---- */
PetscErrorCode BSSCR_PCCreate_ScGtKG( PC pc )
{
PC_SC_GtKG pc_data;
PetscErrorCode ierr;
/* create memory for ctx */
ierr = Stg_PetscNew( _PC_SC_GtKG,&pc_data);CHKERRQ(ierr);
/* init ctx */
pc_data->F = PETSC_NULL;
pc_data->Bt = PETSC_NULL;
pc_data->B = PETSC_NULL;
pc_data->BBt_has_cnst_nullspace = PETSC_FALSE;
pc_data->ksp_BBt = PETSC_NULL;
pc_data->monitor_activated = PETSC_FALSE;
pc_data->X1 = PETSC_NULL;
pc_data->X2 = PETSC_NULL;
pc_data->Y1 = PETSC_NULL;
pc_data->Y2 = PETSC_NULL;
pc_data->s = PETSC_NULL;
pc_data->t = PETSC_NULL;
pc_data->X = PETSC_NULL;
/* set ctx onto pc */
pc->data = (void*)pc_data;
ierr = PetscLogObjectMemory(pc,sizeof(_PC_SC_GtKG));CHKERRQ(ierr);
/* define operations */
pc->ops->setup = BSSCR_PCSetUp_ScGtKG;
pc->ops->view = BSSCR_PCView_ScGtKG;
pc->ops->destroy = BSSCR_PCDestroy_ScGtKG;
pc->ops->setfromoptions = BSSCR_PCSetFromOptions_ScGtKG;
pc->ops->apply = BSSCR_PCApply_ScGtKG;
pc->ops->applytranspose = BSSCR_PCApplyTranspose_ScGtKG;
PetscFunctionReturn(0);
}
PetscErrorCode BSSCR_PCScGtKGGetScalings( PC pc, Vec *X1, Vec *X2, Vec *Y1, Vec *Y2 )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
BSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );
if( X1 != PETSC_NULL ) { *X1 = ctx->X1; }
if( X2 != PETSC_NULL ) { *X2 = ctx->X2; }
if( Y1 != PETSC_NULL ) { *Y1 = ctx->Y1; }
if( Y2 != PETSC_NULL ) { *Y2 = ctx->Y2; }
PetscFunctionReturn(0);
}
/*
F & Bt must different to PETSC_NULL
B may be PETSC_NULL
C can be PETSC_NULL
*/
PetscErrorCode BSSCR_PCScGtKGSetOperators( PC pc, Mat F, Mat Bt, Mat B, Mat C )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
BSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );
ctx->F = F;
ctx->Bt = Bt;
ctx->B = B;
ctx->C = C;
if( C != PETSC_NULL ) {
pc->ops->apply = BSSCR_BSSCR_PCApply_ScGtKG_C;
pc->ops->applytranspose = PETSC_NULL;
}
/* Create vectors */
if( ctx->s == PETSC_NULL ) { MatGetVecs( ctx->F, &ctx->s, PETSC_NULL ); }
if( ctx->X == PETSC_NULL ) { MatGetVecs( ctx->F, PETSC_NULL, &ctx->X ); }
if( ctx->t == PETSC_NULL ) { MatGetVecs( ctx->Bt, &ctx->t, PETSC_NULL ); }
if( ctx->F == PETSC_NULL ) { Stg_SETERRQ( PETSC_ERR_SUP, "gtkg: F not set" ); }
if( ctx->Bt == PETSC_NULL ) { Stg_SETERRQ( PETSC_ERR_SUP, "gtkg: Bt not set" ); }
if( ctx->X1 == PETSC_NULL ) { MatGetVecs( ctx->F, &ctx->X1, PETSC_NULL ); }
if( ctx->Y1 == PETSC_NULL ) { MatGetVecs( ctx->F, &ctx->Y1, PETSC_NULL ); }
if( ctx->X2 == PETSC_NULL ) { MatGetVecs( ctx->Bt, &ctx->X2, PETSC_NULL ); }
if( ctx->Y2 == PETSC_NULL ) { MatGetVecs( ctx->Bt, &ctx->Y2, PETSC_NULL ); }
VecSet( ctx->X1, 1.0 );
VecSet( ctx->Y1, 1.0 );
VecSet( ctx->X2, 1.0 );
VecSet( ctx->Y2, 1.0 );
PetscFunctionReturn(0);
}
PetscErrorCode BSSCR_PCScGtKGAttachNullSpace( PC pc )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
MatNullSpace nsp;
BSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );
/* Attach a null space */
MatNullSpaceCreate( PETSC_COMM_WORLD, PETSC_TRUE, PETSC_NULL, PETSC_NULL, &nsp );
#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR <6) )
KSPSetNullSpace( ctx->ksp_BBt, nsp );
#else
Mat A;
KSPGetOperators(ctx->ksp_BBt,&A,NULL);//Note: DOES NOT increase the reference counts of the matrix, so you should NOT destroy them.
MatSetNullSpace( A, nsp);
#endif
/*
NOTE: This does NOT destroy the memory for nsp, it just decrements the nsp->refct, so that
the next time MatNullSpaceDestroy() is called, the memory will be released. The next time this
is called will be by KSPDestroy();
*/
MatNullSpaceDestroy( nsp );
PetscFunctionReturn(0);
}
PetscErrorCode BSSCR_PCScGtKGGetKSP( PC pc, KSP *ksp )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
BSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );
if( ksp != PETSC_NULL ) {
(*ksp) = ctx->ksp_BBt;
}
PetscFunctionReturn(0);
}
PetscErrorCode BSSCR_PCScGtKGSetKSP( PC pc, KSP ksp )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
BSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );
if( ctx->ksp_BBt != PETSC_NULL ) {
Stg_KSPDestroy(&ctx->ksp_BBt);
}
PetscObjectReference( (PetscObject)ksp );
ctx->ksp_BBt = ksp;
PetscFunctionReturn(0);
}
PetscErrorCode BSSCR_PCScGtKGSetSubKSPMonitor( PC pc, PetscTruth flg )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
BSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );
ctx->monitor_activated = flg;
PetscFunctionReturn(0);
}
PetscErrorCode BSSCR_PCScGtKGUseStandardScaling( PC pc )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
Mat K,G,D,C;
Vec rG;
PetscScalar rg2, rg, ra;
PetscInt N;
Vec rA, rC;
Vec L1,L2, R1,R2;
BSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );
L1 = ctx->X1;
L2 = ctx->X2;
R1 = ctx->Y1;
R2 = ctx->Y2;
rA = L1;
rC = L2;
K = ctx->F;
G = ctx->Bt;
D = ctx->B;
C = ctx->C;
VecDuplicate( rA, &rG );
/* Get magnitude of K */
MatGetRowMax( K, rA, PETSC_NULL );
VecSqrt( rA );
VecReciprocal( rA );
VecDot( rA,rA, &ra );
VecGetSize( rA, &N );
ra = PetscSqrtScalar( ra/N );
/* Get magnitude of G */
MatGetRowMax( G, rG, PETSC_NULL );
VecDot( rG, rG, &rg2 );
VecGetSize( rG, &N );
rg = PetscSqrtScalar(rg2/N);
// printf("rg = %f \n", rg );
VecSet( rC, 1.0/(rg*ra) );
Stg_VecDestroy(&rG );
VecCopy( L1, R1 );
VecCopy( L2, R2 );
PetscFunctionReturn(0);
}
/*
Builds
B Y1 X1 Bt
and creates a ksp when C=0, otherwise it builds
B Y1 X1 Bt - C
*/
PetscErrorCode BSSCR_PCScGtKGUseStandardBBtOperator( PC pc )
{
PC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;
PetscReal fill;
Mat diag_mat,C;
Vec diag;
PetscInt M,N, m,n;
MPI_Comm comm;
PetscInt nnz_I, nnz_G;
MatType mtype;
const char *prefix;
Mat BBt;
KSP ksp;
PetscTruth ivalue, flg, has_cnst_nullsp;
BSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );
/* Assemble BBt */
MatGetSize( ctx->Bt, &M, &N );
MatGetLocalSize( ctx->Bt, &m, &n );
MatGetVecs( ctx->Bt, PETSC_NULL, &diag );
/* Define diagonal matrix Y1 X1 */
VecPointwiseMult( diag, ctx->Y1, ctx->X1 );
PetscObjectGetComm( (PetscObject)ctx->F, &comm );
MatCreate( comm, &diag_mat );
MatSetSizes( diag_mat, m,m , M, M );
#if (((PETSC_VERSION_MAJOR==3) && (PETSC_VERSION_MINOR>=3)) || (PETSC_VERSION_MAJOR>3) )
MatSetUp(diag_mat);
#endif
MatGetType( ctx->Bt, &mtype );
MatSetType( diag_mat, mtype );
MatDiagonalSet( diag_mat, diag, INSERT_VALUES );
/* Build operator B Y1 X1 Bt */
BSSCR_BSSCR_get_number_nonzeros_AIJ_ScGtKG( diag_mat, &nnz_I );
BSSCR_BSSCR_get_number_nonzeros_AIJ_ScGtKG( ctx->Bt, &nnz_G );
/*
Not sure the best way to estimate the fill factor.
BBt is a laplacian on the pressure space.
This might tell us something useful...
*/
fill = (PetscReal)(nnz_G)/(PetscReal)( nnz_I );
MatPtAP( diag_mat, ctx->Bt, MAT_INITIAL_MATRIX, fill, &BBt );
Stg_MatDestroy(&diag_mat );
Stg_VecDestroy(&diag );
C = ctx->C;
if( C !=PETSC_NULL ) {
MatAXPY( BBt, -1.0, C, DIFFERENT_NONZERO_PATTERN );
}
/* Build the solver */
KSPCreate( ((PetscObject)pc)->comm, &ksp );
Stg_KSPSetOperators( ksp, BBt, BBt, SAME_NONZERO_PATTERN );
PCGetOptionsPrefix( pc,&prefix );
KSPSetOptionsPrefix( ksp, prefix );
KSPAppendOptionsPrefix( ksp, "pc_gtkg_" ); /* -pc_GtKG_ksp_type <type>, -ksp_GtKG_pc_type <type> */
BSSCR_PCScGtKGSetKSP( pc, ksp );
BSSCR_MatContainsConstNullSpace( BBt, NULL, &has_cnst_nullsp );
if( has_cnst_nullsp == PETSC_TRUE ) {
BSSCR_PCScGtKGAttachNullSpace( pc );
}
PetscOptionsGetTruth( PETSC_NULL, "-pc_gtkg_monitor", &ivalue, &flg );
BSSCR_PCScGtKGSetSubKSPMonitor( pc, ivalue );
Stg_KSPDestroy(&ksp);
Stg_MatDestroy(&BBt);
PetscFunctionReturn(0);
}
#endif
| {
"alphanum_fraction": 0.6039725125,
"avg_line_length": 24.5902777778,
"ext": "c",
"hexsha": "a340d405c50ef9e211278fa82e8199623cdfb402",
"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/pc_ScaledGtKG.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/pc_ScaledGtKG.c",
"max_line_length": 148,
"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/pc_ScaledGtKG.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": 8070,
"size": 21246
} |
#pragma once
#include "SimpleEvaluator.h"
#include "BooleanDAG.h"
#include "Interface.h"
#include "SuggestionGenerator.h"
#include <map>
#include <set>
#ifndef _NOGSL
#include <gsl/gsl_vector.h>
#else
#include "FakeGSL.h"
#endif
class SimpleSuggestionGenerator: public SuggestionGenerator {
vector<int> nodesToSuggest;
Interface* interf;
BooleanDAG* dag;
map<string, int>& ctrls;
SimpleEvaluator* seval;
public:
SimpleSuggestionGenerator(BooleanDAG* _dag, Interface* _interface, map<string, int>& _ctrls): dag(_dag), interf(_interface), ctrls(_ctrls) {
seval = new SimpleEvaluator(*dag, ctrls);
seval->setInputs(interf);
for (auto it = interf->varsMapping.begin(); it != interf->varsMapping.end(); it++) {
int nodeid = it->first;
bool_node* n = (*dag)[nodeid];
if (n->type == bool_node::LT) {
nodesToSuggest.push_back(nodeid);
}
}
}
pair<int, int> getSuggestion(const gsl_vector* state) {
return make_pair(-1, 0);
}
pair<int, int> getUnsatSuggestion(const gsl_vector* state) {
return make_pair(-1, 0);
}
virtual IClause* getConflictClause(int level, LocalState * state) {
return NULL;
}
virtual SClause* getUnsatClause(const gsl_vector* state) {
return NULL;
}
virtual SClause* getUnsatClause(const gsl_vector* state, const gsl_vector* prevState) {
return NULL;
}
};
| {
"alphanum_fraction": 0.6349631614,
"avg_line_length": 27.6481481481,
"ext": "h",
"hexsha": "37d5fcdf3180ef159caab8babba583a342392d93",
"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/SuggestionGenerators/SimpleSuggestionGenerator.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/SuggestionGenerators/SimpleSuggestionGenerator.h",
"max_line_length": 144,
"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/SuggestionGenerators/SimpleSuggestionGenerator.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": 385,
"size": 1493
} |
/* Copied from the article:
http://amitsaha.github.io/site/notes/articles/c_scientific/article.html
*/
/*Listing-1: gsl_vector.c*/
/* Simple demo of the vector support in GSL
* Also uses the random number generation feature
*/
#include <stdio.h>
#include <gsl/gsl_vector.h> /*For Vectors*/
#include <gsl/gsl_rng.h> /* For Random numbers*/
int main ()
{
int i,n;
/* Setup the Random number generator*/
const gsl_rng_type * T;
gsl_rng * r;
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
n = 10;
/* Allocate the vector of the specified size*/
gsl_vector * v = gsl_vector_alloc (n);
/* Set the elements to a uniform random number in [0,1]*/
for (i = 0; i < n; i++)
{
gsl_vector_set (v, i, gsl_rng_uniform (r));
}
/* Print the vector*/
for (i = 0; i < n; i++)
{
printf ("v_%d = %g\n", i, gsl_vector_get (v, i));
}
gsl_vector_free (v);
return 0;
}
| {
"alphanum_fraction": 0.6259378349,
"avg_line_length": 20.2826086957,
"ext": "c",
"hexsha": "86d291ef0009b38ba1fbb203dbdda330c7a55153",
"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": "953620749c50092e0265846f49d89b1de77e93d3",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "FedoraScientific/scientific_spin_tests",
"max_forks_repo_path": "c/gsl_vector.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "953620749c50092e0265846f49d89b1de77e93d3",
"max_issues_repo_issues_event_max_datetime": "2018-03-27T06:42:26.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-03-27T06:42:26.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "FedoraScientific/scientific_spin_tests",
"max_issues_repo_path": "c/gsl_vector.c",
"max_line_length": 71,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "953620749c50092e0265846f49d89b1de77e93d3",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "FedoraScientific/scientific_spin_tests",
"max_stars_repo_path": "c/gsl_vector.c",
"max_stars_repo_stars_event_max_datetime": "2015-04-06T02:09:57.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-06T02:09:57.000Z",
"num_tokens": 278,
"size": 933
} |
/* randist/gsl_randist.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_RANDIST_H__
#define __GSL_RANDIST_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_rng.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
GSL_FUN unsigned int gsl_ran_bernoulli (const gsl_rng * r, double p);
GSL_FUN double gsl_ran_bernoulli_pdf (const unsigned int k, double p);
GSL_FUN double gsl_ran_beta (const gsl_rng * r, const double a, const double b);
GSL_FUN double gsl_ran_beta_pdf (const double x, const double a, const double b);
GSL_FUN unsigned int gsl_ran_binomial (const gsl_rng * r, double p, unsigned int n);
GSL_FUN unsigned int gsl_ran_binomial_knuth (const gsl_rng * r, double p, unsigned int n);
GSL_FUN unsigned int gsl_ran_binomial_tpe (const gsl_rng * r, double p, unsigned int n);
GSL_FUN double gsl_ran_binomial_pdf (const unsigned int k, const double p, const unsigned int n);
GSL_FUN double gsl_ran_exponential (const gsl_rng * r, const double mu);
GSL_FUN double gsl_ran_exponential_pdf (const double x, const double mu);
GSL_FUN double gsl_ran_exppow (const gsl_rng * r, const double a, const double b);
GSL_FUN double gsl_ran_exppow_pdf (const double x, const double a, const double b);
GSL_FUN double gsl_ran_cauchy (const gsl_rng * r, const double a);
GSL_FUN double gsl_ran_cauchy_pdf (const double x, const double a);
GSL_FUN double gsl_ran_chisq (const gsl_rng * r, const double nu);
GSL_FUN double gsl_ran_chisq_pdf (const double x, const double nu);
GSL_FUN void gsl_ran_dirichlet (const gsl_rng * r, const size_t K, const double alpha[], double theta[]);
GSL_FUN double gsl_ran_dirichlet_pdf (const size_t K, const double alpha[], const double theta[]);
GSL_FUN double gsl_ran_dirichlet_lnpdf (const size_t K, const double alpha[], const double theta[]);
GSL_FUN double gsl_ran_erlang (const gsl_rng * r, const double a, const double n);
GSL_FUN double gsl_ran_erlang_pdf (const double x, const double a, const double n);
GSL_FUN double gsl_ran_fdist (const gsl_rng * r, const double nu1, const double nu2);
GSL_FUN double gsl_ran_fdist_pdf (const double x, const double nu1, const double nu2);
GSL_FUN double gsl_ran_flat (const gsl_rng * r, const double a, const double b);
GSL_FUN double gsl_ran_flat_pdf (double x, const double a, const double b);
GSL_FUN double gsl_ran_gamma (const gsl_rng * r, const double a, const double b);
GSL_FUN double gsl_ran_gamma_int (const gsl_rng * r, const unsigned int a);
GSL_FUN double gsl_ran_gamma_pdf (const double x, const double a, const double b);
GSL_FUN double gsl_ran_gamma_mt (const gsl_rng * r, const double a, const double b);
GSL_FUN double gsl_ran_gamma_knuth (const gsl_rng * r, const double a, const double b);
GSL_FUN double gsl_ran_gaussian (const gsl_rng * r, const double sigma);
GSL_FUN double gsl_ran_gaussian_ratio_method (const gsl_rng * r, const double sigma);
GSL_FUN double gsl_ran_gaussian_ziggurat (const gsl_rng * r, const double sigma);
GSL_FUN double gsl_ran_gaussian_pdf (const double x, const double sigma);
GSL_FUN double gsl_ran_ugaussian (const gsl_rng * r);
GSL_FUN double gsl_ran_ugaussian_ratio_method (const gsl_rng * r);
GSL_FUN double gsl_ran_ugaussian_pdf (const double x);
GSL_FUN double gsl_ran_gaussian_tail (const gsl_rng * r, const double a, const double sigma);
GSL_FUN double gsl_ran_gaussian_tail_pdf (const double x, const double a, const double sigma);
GSL_FUN double gsl_ran_ugaussian_tail (const gsl_rng * r, const double a);
GSL_FUN double gsl_ran_ugaussian_tail_pdf (const double x, const double a);
GSL_FUN void gsl_ran_bivariate_gaussian (const gsl_rng * r, double sigma_x, double sigma_y, double rho, double *x, double *y);
GSL_FUN double gsl_ran_bivariate_gaussian_pdf (const double x, const double y, const double sigma_x, const double sigma_y, const double rho);
GSL_FUN int gsl_ran_multivariate_gaussian (const gsl_rng * r, const gsl_vector * mu, const gsl_matrix * L, gsl_vector * result);
GSL_FUN int gsl_ran_multivariate_gaussian_log_pdf (const gsl_vector * x,
const gsl_vector * mu,
const gsl_matrix * L,
double * result,
gsl_vector * work);
GSL_FUN int gsl_ran_multivariate_gaussian_pdf (const gsl_vector * x,
const gsl_vector * mu,
const gsl_matrix * L,
double * result,
gsl_vector * work);
GSL_FUN int gsl_ran_multivariate_gaussian_mean (const gsl_matrix * X, gsl_vector * mu_hat);
GSL_FUN int gsl_ran_multivariate_gaussian_vcov (const gsl_matrix * X, gsl_matrix * sigma_hat);
GSL_FUN int gsl_ran_wishart (const gsl_rng * r,
const double df,
const gsl_matrix * L,
gsl_matrix * result,
gsl_matrix * work);
GSL_FUN int gsl_ran_wishart_log_pdf (const gsl_matrix * X,
const gsl_matrix * L_X,
const double df,
const gsl_matrix * L,
double * result,
gsl_matrix * work);
GSL_FUN int gsl_ran_wishart_pdf (const gsl_matrix * X,
const gsl_matrix * L_X,
const double df,
const gsl_matrix * L,
double * result,
gsl_matrix * work);
GSL_FUN double gsl_ran_landau (const gsl_rng * r);
GSL_FUN double gsl_ran_landau_pdf (const double x);
GSL_FUN unsigned int gsl_ran_geometric (const gsl_rng * r, const double p);
GSL_FUN double gsl_ran_geometric_pdf (const unsigned int k, const double p);
GSL_FUN unsigned int gsl_ran_hypergeometric (const gsl_rng * r, unsigned int n1, unsigned int n2, unsigned int t);
GSL_FUN double gsl_ran_hypergeometric_pdf (const unsigned int k, const unsigned int n1, const unsigned int n2, unsigned int t);
GSL_FUN double gsl_ran_gumbel1 (const gsl_rng * r, const double a, const double b);
GSL_FUN double gsl_ran_gumbel1_pdf (const double x, const double a, const double b);
GSL_FUN double gsl_ran_gumbel2 (const gsl_rng * r, const double a, const double b);
GSL_FUN double gsl_ran_gumbel2_pdf (const double x, const double a, const double b);
GSL_FUN double gsl_ran_logistic (const gsl_rng * r, const double a);
GSL_FUN double gsl_ran_logistic_pdf (const double x, const double a);
GSL_FUN double gsl_ran_lognormal (const gsl_rng * r, const double zeta, const double sigma);
GSL_FUN double gsl_ran_lognormal_pdf (const double x, const double zeta, const double sigma);
GSL_FUN unsigned int gsl_ran_logarithmic (const gsl_rng * r, const double p);
GSL_FUN double gsl_ran_logarithmic_pdf (const unsigned int k, const double p);
GSL_FUN void gsl_ran_multinomial (const gsl_rng * r, const size_t K,
const unsigned int N, const double p[],
unsigned int n[] );
GSL_FUN double gsl_ran_multinomial_pdf (const size_t K,
const double p[], const unsigned int n[] );
GSL_FUN double gsl_ran_multinomial_lnpdf (const size_t K,
const double p[], const unsigned int n[] );
GSL_FUN unsigned int gsl_ran_negative_binomial (const gsl_rng * r, double p, double n);
GSL_FUN double gsl_ran_negative_binomial_pdf (const unsigned int k, const double p, double n);
GSL_FUN unsigned int gsl_ran_pascal (const gsl_rng * r, double p, unsigned int n);
GSL_FUN double gsl_ran_pascal_pdf (const unsigned int k, const double p, unsigned int n);
GSL_FUN double gsl_ran_pareto (const gsl_rng * r, double a, const double b);
GSL_FUN double gsl_ran_pareto_pdf (const double x, const double a, const double b);
GSL_FUN unsigned int gsl_ran_poisson (const gsl_rng * r, double mu);
GSL_FUN void gsl_ran_poisson_array (const gsl_rng * r, size_t n, unsigned int array[],
double mu);
GSL_FUN double gsl_ran_poisson_pdf (const unsigned int k, const double mu);
GSL_FUN double gsl_ran_rayleigh (const gsl_rng * r, const double sigma);
GSL_FUN double gsl_ran_rayleigh_pdf (const double x, const double sigma);
GSL_FUN double gsl_ran_rayleigh_tail (const gsl_rng * r, const double a, const double sigma);
GSL_FUN double gsl_ran_rayleigh_tail_pdf (const double x, const double a, const double sigma);
GSL_FUN double gsl_ran_tdist (const gsl_rng * r, const double nu);
GSL_FUN double gsl_ran_tdist_pdf (const double x, const double nu);
GSL_FUN double gsl_ran_laplace (const gsl_rng * r, const double a);
GSL_FUN double gsl_ran_laplace_pdf (const double x, const double a);
GSL_FUN double gsl_ran_levy (const gsl_rng * r, const double c, const double alpha);
GSL_FUN double gsl_ran_levy_skew (const gsl_rng * r, const double c, const double alpha, const double beta);
GSL_FUN double gsl_ran_weibull (const gsl_rng * r, const double a, const double b);
GSL_FUN double gsl_ran_weibull_pdf (const double x, const double a, const double b);
GSL_FUN void gsl_ran_dir_2d (const gsl_rng * r, double * x, double * y);
GSL_FUN void gsl_ran_dir_2d_trig_method (const gsl_rng * r, double * x, double * y);
GSL_FUN void gsl_ran_dir_3d (const gsl_rng * r, double * x, double * y, double * z);
GSL_FUN void gsl_ran_dir_nd (const gsl_rng * r, size_t n, double * x);
GSL_FUN void gsl_ran_shuffle (const gsl_rng * r, void * base, size_t nmembm, size_t size);
GSL_FUN int gsl_ran_choose (const gsl_rng * r, void * dest, size_t k, void * src, size_t n, size_t size) ;
GSL_FUN void gsl_ran_sample (const gsl_rng * r, void * dest, size_t k, void * src, size_t n, size_t size) ;
typedef struct { /* struct for Walker algorithm */
size_t K;
size_t *A;
double *F;
} gsl_ran_discrete_t;
GSL_FUN gsl_ran_discrete_t * gsl_ran_discrete_preproc (size_t K, const double *P);
GSL_FUN void gsl_ran_discrete_free(gsl_ran_discrete_t *g);
GSL_FUN size_t gsl_ran_discrete (const gsl_rng *r, const gsl_ran_discrete_t *g);
GSL_FUN double gsl_ran_discrete_pdf (size_t k, const gsl_ran_discrete_t *g);
__END_DECLS
#endif /* __GSL_RANDIST_H__ */
| {
"alphanum_fraction": 0.7062365591,
"avg_line_length": 50.5434782609,
"ext": "h",
"hexsha": "c909e07549397375826700946b2171795f3c7078",
"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": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/VimbaCamJILA",
"max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_randist.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/VimbaCamJILA",
"max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_randist.h",
"max_line_length": 142,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mgreter/astrometrylib",
"max_stars_repo_path": "vendor/gsl/gsl/gsl_randist.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 3013,
"size": 11625
} |
#include <cblas.h>
#ifdef LAPACKE_FOLDER
#include <lapacke/lapacke.h>
#include <lapacke/lapacke_utils.h>
#else
#include <lapacke.h>
#include <lapacke_utils.h>
#endif
#include "math.h"
#include "stdbool.h"
#include "stdio.h"
#include "string.h"
#include "sv_matrix.h"
#include <limits.h>
#include <stdarg.h>
#include "linmath.h"
#ifdef _WIN32
#define SURVIVE_LOCAL_ONLY
#include <malloc.h>
#define alloca _alloca
#else
#define SURVIVE_LOCAL_ONLY __attribute__((visibility("hidden")))
#endif
#define SV_Error(code, msg) assert(0 && msg); // cv::error( code, msg, SV_Func, __FILE__, __LINE__ )
const int DECOMP_SVD = 1;
const int DECOMP_LU = 2;
void print_mat(const SvMat *M);
static size_t mat_size_bytes(const SvMat *mat) { return (size_t)sizeof(FLT) * mat->cols * mat->rows; }
#ifdef USE_FLOAT
#define cblas_gemm cblas_sgemm
#define cblas_symm cblas_ssymm
#define LAPACKE_getrs LAPACKE_sgetrs
#define LAPACKE_getrf LAPACKE_sgetrf
#define LAPACKE_getri LAPACKE_sgetri
#define LAPACKE_gelss LAPACKE_sgelss
#define LAPACKE_gesvd LAPACKE_sgesvd
#define LAPACKE_gesvd_work LAPACKE_sgesvd_work
#define LAPACKE_getri_work LAPACKE_sgetri_work
#define LAPACKE_ge_trans LAPACKE_sge_trans
#else
#define cblas_gemm cblas_dgemm
#define cblas_symm cblas_dsymm
#define LAPACKE_getrs LAPACKE_dgetrs
#define LAPACKE_getrf LAPACKE_dgetrf
#define LAPACKE_getri LAPACKE_dgetri
#define LAPACKE_gelss LAPACKE_dgelss
#define LAPACKE_gesvd LAPACKE_dgesvd
#define LAPACKE_gesvd_work LAPACKE_dgesvd_work
#define LAPACKE_getri_work LAPACKE_dgetri_work
#define LAPACKE_ge_trans LAPACKE_dge_trans
#endif
// dst = alpha * src1 * src2 + beta * src3 or dst = alpha * src2 * src1 + beta * src3 where src1 is symm
SURVIVE_LOCAL_ONLY void svSYMM(const SvMat *src1, const SvMat *src2, double alpha, const SvMat *src3, double beta,
SvMat *dst, bool src1First) {
int rows1 = src1->rows;
int cols1 = src1->cols;
int rows2 = src2->rows;
int cols2 = src2->cols;
if (src3) {
int rows3 = src3->rows;
int cols3 = src3->cols;
assert(rows3 == dst->rows);
assert(cols3 == dst->cols);
}
// assert(src3 == 0 || beta != 0);
assert(cols1 == rows2);
assert(rows1 == dst->rows);
assert(cols2 == dst->cols);
lapack_int lda = src1->cols;
lapack_int ldb = src2->cols;
if (src3)
svCopy(src3, dst, 0);
else
beta = 0;
assert(SV_RAW_PTR(dst) != SV_RAW_PTR(src1));
assert(SV_RAW_PTR(dst) != SV_RAW_PTR(src2));
/*
void cblas_dsymm(OPENBLAS_CONST enum CBLAS_ORDER Order,
OPENBLAS_CONST enum CBLAS_SIDE Side,
OPENBLAS_CONST enum CBLAS_UPLO Uplo,
OPENBLAS_CONST blasint M,
OPENBLAS_CONST blasint N,
OPENBLAS_CONST double alpha,
OPENBLAS_CONST double *A,
OPENBLAS_CONST blasint lda,
OPENBLAS_CONST double *B,
OPENBLAS_CONST blasint ldb,
OPENBLAS_CONST double beta,
double *C,
OPENBLAS_CONST blasint ldc);
*/
cblas_symm(CblasRowMajor, src1First ? CblasLeft : CblasRight, CblasUpper, dst->rows, dst->cols, alpha,
SV_RAW_PTR(src1), lda, SV_RAW_PTR(src2), ldb, beta, SV_RAW_PTR(dst), dst->cols);
}
// Special case dst = alpha * src2 * src1 * src2' + beta * src3
void mulBABt(const SvMat *src1, const SvMat *src2, double alpha, const SvMat *src3, double beta, SvMat *dst) {
size_t dims = src2->rows;
assert(src2->cols == src2->rows);
SV_CREATE_STACK_MAT(tmp, dims, dims);
// This has been profiled; and weirdly enough the SYMM version is slower for a 19x19 matrix. Guessing access order
// or some other cache thing matters more than the additional 2x multiplications.
//#define USE_SYM
#ifdef USE_SYM
svSYMM(src1, src2, 1, 0, 0, &tmp, false);
svGEMM(&tmp, src2, alpha, src3, beta, dst, SV_GEMM_B_T);
#else
svGEMM(src1, src2, 1, 0, 0, &tmp, SV_GEMM_FLAG_B_T);
svGEMM(src2, &tmp, alpha, src3, beta, dst, 0);
#endif
SV_FREE_STACK_MAT(tmp);
}
// dst = alpha * src1 * src2 + beta * src3
SURVIVE_LOCAL_ONLY void svGEMM(const SvMat *src1, const SvMat *src2, double alpha, const SvMat *src3, double beta,
SvMat *dst, enum svGEMMFlags tABC) {
int rows1 = (tABC & SV_GEMM_FLAG_A_T) ? src1->cols : src1->rows;
int cols1 = (tABC & SV_GEMM_FLAG_A_T) ? src1->rows : src1->cols;
int rows2 = (tABC & SV_GEMM_FLAG_B_T) ? src2->cols : src2->rows;
int cols2 = (tABC & SV_GEMM_FLAG_B_T) ? src2->rows : src2->cols;
if (src3) {
int rows3 = (tABC & SV_GEMM_FLAG_C_T) ? src3->cols : src3->rows;
int cols3 = (tABC & SV_GEMM_FLAG_C_T) ? src3->rows : src3->cols;
assert(rows3 == dst->rows);
assert(cols3 == dst->cols);
}
// assert(src3 == 0 || beta != 0);
assert(cols1 == rows2);
assert(rows1 == dst->rows);
assert(cols2 == dst->cols);
lapack_int lda = src1->cols;
lapack_int ldb = src2->cols;
if (src3)
svCopy(src3, dst, 0);
else
beta = 0;
assert(SV_RAW_PTR(dst) != SV_RAW_PTR(src1));
assert(SV_RAW_PTR(dst) != SV_RAW_PTR(src2));
assert(dst->cols > 0);
cblas_gemm(CblasRowMajor, (tABC & SV_GEMM_FLAG_A_T) ? CblasTrans : CblasNoTrans,
(tABC & SV_GEMM_FLAG_B_T) ? CblasTrans : CblasNoTrans, dst->rows, dst->cols, cols1, alpha,
SV_RAW_PTR(src1), lda, SV_RAW_PTR(src2), ldb, beta, SV_RAW_PTR(dst), dst->cols);
}
// dst = scale * src ^ t * src iff order == 1
// dst = scale * src * src ^ t iff order == 0
SURVIVE_LOCAL_ONLY void svMulTransposed(const SvMat *src, SvMat *dst, int order, const SvMat *delta, double scale) {
lapack_int rows = src->rows;
lapack_int cols = src->cols;
lapack_int drows = order == 0 ? dst->rows : dst->cols;
assert(drows == dst->cols);
assert(order == 1 ? (dst->cols == src->cols) : (dst->cols == src->rows));
assert(delta == 0 && "This isn't implemented yet");
double beta = 0;
bool isAT = order == 1;
bool isBT = !isAT;
lapack_int dstCols = dst->cols;
assert(dstCols > 0);
cblas_gemm(CblasRowMajor, isAT ? CblasTrans : CblasNoTrans, isBT ? CblasTrans : CblasNoTrans, dst->rows, dst->cols,
order == 1 ? src->rows : src->cols, scale, SV_RAW_PTR(src), src->cols, SV_RAW_PTR(src), src->cols, beta,
SV_RAW_PTR(dst), dstCols);
}
/* IEEE754 constants and macros */
#define SV_TOGGLE_FLT(x) ((x) ^ ((int)(x) < 0 ? 0x7fffffff : 0))
#define SV_TOGGLE_DBL(x) ((x) ^ ((int64)(x) < 0 ? SV_BIG_INT(0x7fffffffffffffff) : 0))
#define SV_DbgAssert assert
#define SV_CREATE_MAT_HEADER_ALLOCA(stack_mat, rows, cols) \
SvMat *stack_mat = svInitMatHeader(SV_MATRIX_ALLOC(sizeof(SvMat)), rows, cols);
#define SV_CREATE_MAT_ALLOCA(stack_mat, height, width) \
SV_CREATE_MAT_HEADER_ALLOCA(stack_mat, height, width); \
(stack_mat)->data = SV_MATRIX_ALLOC(mat_size_bytes(stack_mat));
#define SV_MAT_ALLOCA_FREE(stack_mat) \
{ \
SV_MATRIX_FREE(stack_mat->data); \
SV_MATRIX_FREE(stack_mat); \
}
#define CREATE_SV_STACK_MAT(name, rows, cols, type) \
FLT *_##name = alloca(rows * cols * sizeof(FLT)); \
SvMat name = svMat(rows, cols, _##name);
static lapack_int LAPACKE_gesvd_static_alloc(int matrix_layout, char jobu, char jobvt, lapack_int m, lapack_int n,
FLT *a, lapack_int lda, FLT *s, FLT *u, lapack_int ldu, FLT *vt,
lapack_int ldvt, FLT *superb) {
lapack_int info = 0;
lapack_int lwork = -1;
FLT *work = NULL;
FLT work_query;
lapack_int i;
if (matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR) {
LAPACKE_xerbla("LAPACKE_dgesvd", -1);
return -1;
}
/* Query optimal working array(s) size */
info = LAPACKE_gesvd_work(matrix_layout, jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, &work_query, lwork);
if (info != 0) {
goto exit_level_0;
}
lwork = (lapack_int)work_query;
/* Allocate memory for work arrays */
work = (FLT *)SV_MATRIX_ALLOC(sizeof(FLT) * lwork);
memset(work, 0, sizeof(FLT) * lwork);
if (work == NULL) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_0;
}
/* Call middle-level interface */
info = LAPACKE_gesvd_work(matrix_layout, jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork);
/* Backup significant data from working array(s) */
for (i = 0; i < MIN(m, n) - 1; i++) {
superb[i] = work[i + 1];
}
SV_MATRIX_FREE(work);
exit_level_0:
if (info == LAPACK_WORK_MEMORY_ERROR) {
LAPACKE_xerbla("LAPACKE_dgesvd", info);
}
return info;
}
static inline lapack_int LAPACKE_getri_static_alloc(int matrix_layout, lapack_int n, FLT *a, lapack_int lda,
const lapack_int *ipiv) {
lapack_int info = 0;
lapack_int lwork = -1;
FLT *work = NULL;
FLT work_query;
if (matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR) {
LAPACKE_xerbla("LAPACKE_dgetri", -1);
return -1;
}
/* Query optimal working array(s) size */
info = LAPACKE_getri_work(matrix_layout, n, a, lda, ipiv, &work_query, lwork);
if (info != 0) {
goto exit_level_0;
}
lwork = (lapack_int)work_query;
/* Allocate memory for work arrays */
work = (FLT *)alloca(sizeof(FLT) * lwork);
memset(work, 0, sizeof(FLT) * lwork);
if (work == NULL) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_0;
}
/* Call middle-level interface */
info = LAPACKE_getri_work(matrix_layout, n, a, lda, ipiv, work, lwork);
/* Release memory and exit */
exit_level_0:
if (info == LAPACK_WORK_MEMORY_ERROR) {
LAPACKE_xerbla("LAPACKE_dgetri", info);
}
return info;
}
SURVIVE_LOCAL_ONLY double svInvert(const SvMat *srcarr, SvMat *dstarr, enum svInvertMethod method) {
lapack_int inf;
lapack_int rows = srcarr->rows;
lapack_int cols = srcarr->cols;
lapack_int lda = srcarr->cols;
svCopy(srcarr, dstarr, 0);
FLT *a = SV_RAW_PTR(dstarr);
#ifdef DEBUG_PRINT
printf("a: \n");
print_mat(srcarr);
#endif
if (method == SV_INVERT_METHOD_LU) {
lapack_int *ipiv = SV_MATRIX_ALLOC(sizeof(lapack_int) * MIN(srcarr->rows, srcarr->cols));
lapack_int lda_t = MAX(1, rows);
FLT *a_t = (FLT *)SV_MATRIX_ALLOC(sizeof(FLT) * lda_t * MAX(1, cols));
LAPACKE_ge_trans(LAPACK_ROW_MAJOR, rows, cols, a, lda, a_t, lda_t);
inf = LAPACKE_getrf(LAPACK_COL_MAJOR, rows, cols, a_t, lda, ipiv);
assert(inf == 0);
inf = LAPACKE_getri_static_alloc(LAPACK_COL_MAJOR, rows, a_t, lda, ipiv);
assert(inf >= 0);
LAPACKE_ge_trans(LAPACK_COL_MAJOR, rows, cols, a_t, lda, a, lda_t);
if (inf > 0) {
printf("Warning: Singular matrix: \n");
// print_mat(srcarr);
}
SV_MATRIX_FREE(a_t);
SV_MATRIX_FREE(ipiv);
// free(ipiv);
} else if (method == DECOMP_SVD) {
// TODO: There is no way this needs this many allocations,
// but in my defense I was very tired when I wrote this code
SV_CREATE_STACK_MAT(w, 1, MIN(dstarr->rows, dstarr->cols));
SV_CREATE_STACK_MAT(u, dstarr->cols, dstarr->cols);
SV_CREATE_STACK_MAT(v, dstarr->rows, dstarr->rows);
SV_CREATE_STACK_MAT(um, w.cols, w.cols);
svSVD(dstarr, &w, &u, &v, 0);
svSetZero(&um);
for (int i = 0; i < w.cols; i++) {
if (_w[i] != 0.0)
svMatrixSet(&um, i, i, 1. / (_w)[i]);
}
SvMat *tmp = svCreateMat(dstarr->cols, dstarr->rows);
svGEMM(&v, &um, 1, 0, 0, tmp, SV_GEMM_FLAG_A_T);
svGEMM(tmp, &u, 1, 0, 0, dstarr, SV_GEMM_FLAG_B_T);
svReleaseMat(&tmp);
SV_FREE_STACK_MAT(um);
SV_FREE_STACK_MAT(v);
SV_FREE_STACK_MAT(u);
SV_FREE_STACK_MAT(w);
} else {
assert(0 && "Bad argument");
return -1;
}
return 0;
}
#define SV_CLONE_MAT_ALLOCA(stack_mat, mat) \
SV_CREATE_MAT_ALLOCA(stack_mat, mat->rows, mat->cols) \
svCopy(mat, stack_mat, 0);
static int svSolve_LU(const SvMat *Aarr, const SvMat *Barr, SvMat *xarr) {
lapack_int inf;
lapack_int arows = Aarr->rows;
lapack_int acols = Aarr->cols;
lapack_int xcols = Barr->cols;
lapack_int xrows = Barr->rows;
lapack_int lda = acols; // Aarr->step / sizeof(double);
assert(Aarr->cols == xarr->rows);
assert(Barr->rows == Aarr->rows);
assert(xarr->cols == Barr->cols);
svCopy(Barr, xarr, 0);
FLT *a_ws = SV_MATRIX_ALLOC(mat_size_bytes(Aarr));
memcpy(a_ws, SV_RAW_PTR(Aarr), mat_size_bytes(Aarr));
lapack_int brows = xarr->rows;
lapack_int bcols = xarr->cols;
lapack_int ldb = bcols; // Barr->step / sizeof(double);
lapack_int *ipiv = SV_MATRIX_ALLOC(sizeof(lapack_int) * MIN(Aarr->rows, Aarr->cols));
inf = LAPACKE_getrf(LAPACK_ROW_MAJOR, arows, acols, (a_ws), lda, ipiv);
assert(inf >= 0);
if (inf > 0) {
printf("Warning: Singular matrix: \n");
// print_mat(a_ws);
}
#ifdef DEBUG_PRINT
printf("Solve A * x = B:\n");
// print_mat(a_ws);
print_mat(Barr);
#endif
inf = LAPACKE_getrs(LAPACK_ROW_MAJOR, CblasNoTrans, arows, bcols, (a_ws), lda, ipiv, SV_RAW_PTR(xarr), ldb);
assert(inf == 0);
SV_MATRIX_FREE(a_ws);
SV_MATRIX_FREE(ipiv);
return 0;
}
static inline int svSolve_SVD(const SvMat *Aarr, const SvMat *Barr, SvMat *xarr) {
lapack_int arows = Aarr->rows;
lapack_int acols = Aarr->cols;
lapack_int xcols = Barr->cols;
bool xLargerThanB = Barr->rows > acols;
SvMat *xCpy = 0;
if (xLargerThanB) {
SV_CLONE_MAT_ALLOCA(xCpyStack, Barr);
xCpy = xCpyStack;
} else {
xCpy = xarr;
memcpy(SV_RAW_PTR(xarr), SV_RAW_PTR(Barr), mat_size_bytes(Barr));
}
// SvMat *aCpy = svCloneMat(Aarr);
FLT *aCpy = SV_MATRIX_ALLOC(mat_size_bytes(Aarr));
memcpy(aCpy, SV_RAW_PTR(Aarr), mat_size_bytes(Aarr));
FLT *S = SV_MATRIX_ALLOC(sizeof(FLT) * MIN(arows, acols));
// FLT *S = malloc(sizeof(FLT) * MIN(arows, acols));
FLT rcond = -1;
lapack_int *rank = SV_MATRIX_ALLOC(sizeof(lapack_int) * MIN(arows, acols));
lapack_int inf =
LAPACKE_gelss(LAPACK_ROW_MAJOR, arows, acols, xcols, (aCpy), acols, SV_RAW_PTR(xCpy), xcols, S, rcond, rank);
assert(xarr->rows == acols);
assert(xarr->cols == xCpy->cols);
if (xLargerThanB) {
xCpy->rows = acols;
svCopy(xCpy, xarr, 0);
// svReleaseMat(&xCpy);
}
SV_MATRIX_FREE(rank);
SV_MATRIX_FREE(aCpy);
SV_MATRIX_FREE(S);
if (xLargerThanB) {
SV_MAT_ALLOCA_FREE(xCpy);
}
assert(inf == 0);
if (inf != 0)
return inf;
return 0;
}
SURVIVE_LOCAL_ONLY int svSolve(const SvMat *Aarr, const SvMat *Barr, SvMat *xarr, enum svInvertMethod method) {
if (method == SV_INVERT_METHOD_LU) {
return svSolve_LU(Aarr, Barr, xarr);
} else if (method == SV_INVERT_METHOD_SVD || method == SV_INVERT_METHOD_QR) {
return svSolve_SVD(Aarr, Barr, xarr);
} else {
assert("Unknown method to solve" && 0);
}
return -1;
}
SURVIVE_LOCAL_ONLY void svTranspose(const SvMat *M, SvMat *dst) {
bool inPlace = M == dst || SV_RAW_PTR(M) == SV_RAW_PTR(dst);
FLT *src = SV_RAW_PTR(M);
if (inPlace) {
src = alloca(mat_size_bytes(M));
memcpy(src, SV_RAW_PTR(M), mat_size_bytes(M));
} else {
assert(M->rows == dst->cols);
assert(M->cols == dst->rows);
}
for (unsigned i = 0; i < M->rows; i++) {
for (unsigned j = 0; j < M->cols; j++) {
SV_RAW_PTR(dst)[j * M->rows + i] = src[i * M->cols + j];
}
}
}
#if defined(__has_feature)
#if __has_feature(memory_sanitizer)
#define MEMORY_SANITIZER_IGNORE __attribute__((no_sanitize("memory")))
#endif
#endif
#ifndef MEMORY_SANITIZER_IGNORE
#define MEMORY_SANITIZER_IGNORE
#endif
#define CALLOCA(size) memset(alloca(size), 0, size)
SURVIVE_LOCAL_ONLY void svSVD(SvMat *aarr, SvMat *warr, SvMat *uarr, SvMat *varr, enum svSVDFlags flags) {
char jobu = 'A';
char jobvt = 'A';
lapack_int inf;
if ((flags & SV_SVD_MODIFY_A) == 0) {
aarr = svCloneMat(aarr);
}
if (uarr == 0)
jobu = 'N';
if (varr == 0)
jobvt = 'N';
lapack_int arows = aarr->rows, acols = aarr->cols;
FLT *pw = warr ? SV_RAW_PTR(warr) : (FLT *)CALLOCA(sizeof(FLT) * arows * acols);
FLT *pu = uarr ? SV_RAW_PTR(uarr) : (FLT *)CALLOCA(sizeof(FLT) * arows * arows);
FLT *pv = varr ? SV_RAW_PTR(varr) : (FLT *)CALLOCA(sizeof(FLT) * acols * acols);
lapack_int ulda = uarr ? uarr->cols : acols;
lapack_int plda = varr ? varr->cols : acols;
FLT *superb = CALLOCA(sizeof(FLT) * MIN(arows, acols));
inf = LAPACKE_gesvd_static_alloc(LAPACK_ROW_MAJOR, jobu, jobvt, arows, acols, SV_RAW_PTR(aarr), acols, pw, pu, ulda,
pv, plda, superb);
switch (inf) {
case -6:
assert(false && "matrix has NaNs");
break;
case 0:
break;
default:
assert(inf == 0);
}
if (uarr && (flags & SV_SVD_U_T)) {
svTranspose(uarr, uarr);
}
if (varr && (flags & SV_SVD_V_T) == 0) {
svTranspose(varr, varr);
}
if ((flags & SV_SVD_MODIFY_A) == 0) {
svReleaseMat(&aarr);
}
}
SURVIVE_LOCAL_ONLY double svDet(const SvMat *M) {
assert(M->rows == M->cols);
assert(M->rows <= 3 && "svDet unimplemented for matrices >3");
FLT *m = SV_RAW_PTR(M);
switch (M->rows) {
case 1:
return m[0];
case 2: {
return m[0] * m[3] - m[1] * m[2];
}
case 3: {
FLT m00 = m[0], m01 = m[1], m02 = m[2], m10 = m[3], m11 = m[4], m12 = m[5], m20 = m[6], m21 = m[7], m22 = m[8];
return m00 * (m11 * m22 - m12 * m21) - m01 * (m10 * m22 - m12 * m20) + m02 * (m10 * m21 - m11 * m20);
}
default:
abort();
}
}
| {
"alphanum_fraction": 0.6495795415,
"avg_line_length": 30.5131810193,
"ext": "c",
"hexsha": "c2303661b45f9b374897a1cbb20a43d74ffcd829",
"lang": "C",
"max_forks_count": 52,
"max_forks_repo_forks_event_max_datetime": "2022-03-21T07:50:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-03-26T09:09:18.000Z",
"max_forks_repo_head_hexsha": "3dc35a3c5195724998cbb9e3b486e41ce6b1110d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jdavidberger/libsurvive",
"max_forks_repo_path": "redist/sv_matrix.blas.c",
"max_issues_count": 100,
"max_issues_repo_head_hexsha": "3dc35a3c5195724998cbb9e3b486e41ce6b1110d",
"max_issues_repo_issues_event_max_datetime": "2022-03-26T13:41:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-02-12T02:42:52.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jdavidberger/libsurvive",
"max_issues_repo_path": "redist/sv_matrix.blas.c",
"max_line_length": 120,
"max_stars_count": 208,
"max_stars_repo_head_hexsha": "3dc35a3c5195724998cbb9e3b486e41ce6b1110d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jdavidberger/libsurvive",
"max_stars_repo_path": "redist/sv_matrix.blas.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T14:06:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-02-18T18:48:39.000Z",
"num_tokens": 5731,
"size": 17362
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.