Search is not available for this dataset
text string | meta dict |
|---|---|
#ifndef __INC_MULTIMODELSTRUCT__
#define __INC_MULTIMODELSTRUCT__
#include "modelstruct.h"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
struct modelstruct;
/**
* \struct multimodelstruct
* handle a model with t-variate output i.e y_m = {y_1, ..., y_t}^{T}
*
* this contains some r <= t modelstructs representing the emulators in the PCA projected
* space
*/
typedef struct multi_modelstruct{
int nt; // number of observables in OBSERVED space
int nr; // number of pca-observables kept in the ROTATED space
int nparams; // number of dimensions in the PARAMETER SPACE
int nmodel_points; // number of points in the design
int cov_fn_index;
int regression_order;
/**
* the design (rows:nmodel_points) (cols:nparams)
*/
gsl_matrix *xmodel;
/**
* the full training set in the original space
* (rows:nmodel_points) (cols:nt)
*/
gsl_matrix *training_matrix;
/**
* a t length vector of the the mean values of the cols of training_matrix
*/
gsl_vector *training_mean;
/** array of (r) pca decomposed models
*
* pointers from this back to xmodel, is this bad?
*/
modelstruct** pca_model_array;
/**
* the eigenvalues and vectors from the pca decomp (t xt) , not saved for now...
*/
//gsl_vector *pca_eigenvalues;
//gsl_matrix *pca_eigenvectors;
gsl_vector *pca_evals_r; /** just the first r evals */
gsl_matrix *pca_evecs_r; /** the first r evecs (t x nr)*/
/**
* an (r x nmodel_points) matrix of the pca-transformed training points, these are
* used to init each of the r entries of pca_model_array */
gsl_matrix *pca_zmatrix; /** z <- (1/sqrt(pca_evals_r)) %*% t(pca_evecs_r) %*% (training_matrix - training_mean) */
} multi_modelstruct;
multi_modelstruct* alloc_multimodelstruct(gsl_matrix *xmodel_in, gsl_matrix *training_matrix_in,
int cov_fn_index, int regression_order, double varfrac);
void gen_pca_decomp(multi_modelstruct *m, double vfrac);
void gen_pca_model_array(multi_modelstruct *m);
void dump_multi_modelstruct(FILE* fptr, multi_modelstruct *m );
multi_modelstruct *load_multi_modelstruct(FILE* fptr);
double vector_elt_sum(gsl_vector* vec, int nstop);
void free_multimodelstruct(multi_modelstruct *m);
#endif
| {
"alphanum_fraction": 0.7264995524,
"avg_line_length": 28.641025641,
"ext": "h",
"hexsha": "38d90c2182d4e4ffa0cc5f3f81264c44136f42b3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MADAI/MADAIEmulator",
"max_forks_repo_path": "src/multi_modelstruct.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MADAI/MADAIEmulator",
"max_issues_repo_path": "src/multi_modelstruct.h",
"max_line_length": 116,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jackdawjackdaw/emulator",
"max_stars_repo_path": "src/multi_modelstruct.h",
"max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z",
"num_tokens": 620,
"size": 2234
} |
/*
* 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 mesh_7c5c4ae5_0f3e_4a2d_936e_0447239ac3a7_h
#define mesh_7c5c4ae5_0f3e_4a2d_936e_0447239ac3a7_h
#include <gslib/type.h>
#include <gslib/std.h>
#include <ariel/type.h>
__ariel_begin__
struct mesh_uv_set;
struct mesh_tangent_set;
typedef vector<vec3> mesh_points;
typedef vector<vec3> mesh_normals;
typedef vector<vec3> mesh_tangents;
typedef vector<vec3> mesh_colors;
typedef vector<vec2> mesh_uv_coords;
typedef vector<int32> mesh_faces;
typedef vector<mesh_uv_set> mesh_uv_sets;
typedef vector<mesh_tangent_set> mesh_tangent_sets;
struct mesh_uv_set
{
string name;
mesh_uv_coords coords;
};
struct mesh_tangent_set
{
string name;
mesh_tangents tangents;
};
class mesh:
public res_node
{
friend class mesh_io;
public:
mesh();
virtual ~mesh() {}
virtual res_type get_type() const override { return res_mesh; }
bool has_indices() const { return !_faces.empty(); }
bool has_points() const { return !_points.empty(); }
bool has_normals() const { return !_normals.empty(); }
bool has_colors() const { return !_vcolors.empty(); }
bool has_uvs() const { return !_uvsets.empty(); }
bool has_tangents() const { return !_tangentsets.empty(); }
int32 num_uv_sets() const { return (int32)_uvsets.size(); }
int32 num_tangent_sets() const { return (int32)_tangentsets.size(); }
int32 num_points() const { return (int32)_points.size(); }
int32 num_indices() const { return (int32)_faces.size(); }
const mesh_points& get_const_points() const { return _points; }
const mesh_faces& get_const_indices() const { return _faces; }
const mesh_normals& get_const_normals() const { return _normals; }
const mesh_colors& get_const_colors() const { return _vcolors; }
protected:
mesh_points _points;
mesh_normals _normals;
mesh_colors _vcolors;
mesh_uv_sets _uvsets;
mesh_tangent_sets _tangentsets;
mesh_faces _faces;
matrix _transforms;
public:
/*
* Caution:
* If there were splited vertices in the mesh, the normals & tangents could be incorrect,
* in such situations, you should always trust the data from exporter.
*/
void calc_normals();
};
__ariel_end__
#endif
| {
"alphanum_fraction": 0.6962372974,
"avg_line_length": 34.3490566038,
"ext": "h",
"hexsha": "30443879dbb7d04d863d236cbf30b14296b7ce4b",
"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/mesh.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/mesh.h",
"max_line_length": 94,
"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/mesh.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": 881,
"size": 3641
} |
#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 "mex.h" | {
"alphanum_fraction": 0.7192982456,
"avg_line_length": 21.375,
"ext": "h",
"hexsha": "32267a0d48b9f1ac8b4adf4ba31504b3621abc57",
"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_matlab/IBPsampler.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_matlab/IBPsampler.h",
"max_line_length": 28,
"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_matlab/IBPsampler.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": 114,
"size": 342
} |
/* statistics/test_nist.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Jim Davies, 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.
*/
/* These tests are based on the NIST Statistical Reference Datasets
See http://www.nist.gov/itl/div898/strd/index.html for more
information. */
#include <config.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_ieee_utils.h>
int
test_nist (void)
{
size_t i ;
const size_t nlew = 200 ;
const double lew[200] = {
-213, -564, -35, -15, 141, 115, -420, -360, 203, -338, -431, 194,
-220, -513, 154, -125, -559, 92, -21, -579, -52, 99, -543, -175,
162, -457, -346, 204, -300, -474, 164, -107, -572, -8, 83, -541,
-224, 180, -420, -374, 201, -236, -531, 83, 27, -564, -112, 131,
-507, -254, 199, -311, -495, 143, -46, -579, -90, 136, -472, -338,
202, -287, -477, 169, -124, -568, 17, 48, -568, -135, 162, -430,
-422, 172, -74, -577, -13, 92, -534, -243, 194, -355, -465, 156,
-81, -578, -64, 139, -449, -384, 193, -198, -538, 110, -44, -577,
-6, 66, -552, -164, 161, -460, -344, 205, -281, -504, 134, -28,
-576, -118, 156, -437, -381, 200, -220, -540, 83, 11, -568, -160,
172, -414, -408, 188, -125, -572, -32, 139, -492, -321, 205, -262,
-504, 142, -83, -574, 0, 48, -571, -106, 137, -501, -266, 190,
-391, -406, 194, -186, -553, 83, -13, -577, -49, 103, -515, -280,
201, 300, -506, 131, -45, -578, -80, 138, -462, -361, 201, -211,
-554, 32, 74, -533, -235, 187, -372, -442, 182, -147, -566, 25,
68, -535, -244, 194, -351, -463, 174, -125, -570, 15, 72, -550,
-190, 172, -424, -385, 198, -218, -536, 96 } ;
const size_t nlottery = 218 ;
const double lottery[218] = {
162, 671, 933, 414, 788, 730, 817, 33, 536, 875, 670, 236, 473, 167,
877, 980, 316, 950, 456, 92, 517, 557, 956, 954, 104, 178, 794, 278,
147, 773, 437, 435, 502, 610, 582, 780, 689, 562, 964, 791, 28, 97,
848, 281, 858, 538, 660, 972, 671, 613, 867, 448, 738, 966, 139, 636,
847, 659, 754, 243, 122, 455, 195, 968, 793, 59, 730, 361, 574, 522,
97, 762, 431, 158, 429, 414, 22, 629, 788, 999, 187, 215, 810, 782,
47, 34, 108, 986, 25, 644, 829, 630, 315, 567, 919, 331, 207, 412,
242, 607, 668, 944, 749, 168, 864, 442, 533, 805, 372, 63, 458, 777,
416, 340, 436, 140, 919, 350, 510, 572, 905, 900, 85, 389, 473, 758,
444, 169, 625, 692, 140, 897, 672, 288, 312, 860, 724, 226, 884, 508,
976, 741, 476, 417, 831, 15, 318, 432, 241, 114, 799, 955, 833, 358,
935, 146, 630, 830, 440, 642, 356, 373, 271, 715, 367, 393, 190, 669,
8, 861, 108, 795, 269, 590, 326, 866, 64, 523, 862, 840, 219, 382,
998, 4, 628, 305, 747, 247, 34, 747, 729, 645, 856, 974, 24, 568, 24,
694, 608, 480, 410, 729, 947, 293, 53, 930, 223, 203, 677, 227, 62,
455, 387, 318, 562, 242, 428, 968 } ;
const size_t nmavro = 50 ;
const double mavro[50] = {
2.00180, 2.00170, 2.00180, 2.00190, 2.00180, 2.00170, 2.00150,
2.00140, 2.00150, 2.00150, 2.00170, 2.00180, 2.00180, 2.00190,
2.00190, 2.00210, 2.00200, 2.00160, 2.00140, 2.00130, 2.00130,
2.00150, 2.00150, 2.00160, 2.00150, 2.00140, 2.00130, 2.00140,
2.00150, 2.00140, 2.00150, 2.00160, 2.00150, 2.00160, 2.00190,
2.00200, 2.00200, 2.00210, 2.00220, 2.00230, 2.00240, 2.00250,
2.00270, 2.00260, 2.00260, 2.00260, 2.00270, 2.00260, 2.00250,
2.00240 } ;
const size_t nmichelson = 100 ;
const double michelson [100] = {
299.85, 299.74, 299.90, 300.07, 299.93, 299.85, 299.95, 299.98,
299.98, 299.88, 300.00, 299.98, 299.93, 299.65, 299.76, 299.81,
300.00, 300.00, 299.96, 299.96, 299.96, 299.94, 299.96, 299.94,
299.88, 299.80, 299.85, 299.88, 299.90, 299.84, 299.83, 299.79,
299.81, 299.88, 299.88, 299.83, 299.80, 299.79, 299.76, 299.80,
299.88, 299.88, 299.88, 299.86, 299.72, 299.72, 299.62, 299.86,
299.97, 299.95, 299.88, 299.91, 299.85, 299.87, 299.84, 299.84,
299.85, 299.84, 299.84, 299.84, 299.89, 299.81, 299.81, 299.82,
299.80, 299.77, 299.76, 299.74, 299.75, 299.76, 299.91, 299.92,
299.89, 299.86, 299.88, 299.72, 299.84, 299.85, 299.85, 299.78,
299.89, 299.84, 299.78, 299.81, 299.76, 299.81, 299.79, 299.81,
299.82, 299.85, 299.87, 299.87, 299.81, 299.74, 299.81, 299.94,
299.95, 299.80, 299.81, 299.87 } ;
const size_t npidigits = 5000 ;
const double pidigits [5000] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8,
9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6, 4, 3, 3, 8, 3, 2, 7, 9, 5, 0, 2,
8, 8, 4, 1, 9, 7, 1, 6, 9, 3, 9, 9, 3, 7, 5, 1, 0, 5, 8, 2, 0, 9,
7, 4, 9, 4, 4, 5, 9, 2, 3, 0, 7, 8, 1, 6, 4, 0, 6, 2, 8, 6, 2, 0,
8, 9, 9, 8, 6, 2, 8, 0, 3, 4, 8, 2, 5, 3, 4, 2, 1, 1, 7, 0, 6, 7,
9, 8, 2, 1, 4, 8, 0, 8, 6, 5, 1, 3, 2, 8, 2, 3, 0, 6, 6, 4, 7, 0,
9, 3, 8, 4, 4, 6, 0, 9, 5, 5, 0, 5, 8, 2, 2, 3, 1, 7, 2, 5, 3, 5,
9, 4, 0, 8, 1, 2, 8, 4, 8, 1, 1, 1, 7, 4, 5, 0, 2, 8, 4, 1, 0, 2,
7, 0, 1, 9, 3, 8, 5, 2, 1, 1, 0, 5, 5, 5, 9, 6, 4, 4, 6, 2, 2, 9,
4, 8, 9, 5, 4, 9, 3, 0, 3, 8, 1, 9, 6, 4, 4, 2, 8, 8, 1, 0, 9, 7,
5, 6, 6, 5, 9, 3, 3, 4, 4, 6, 1, 2, 8, 4, 7, 5, 6, 4, 8, 2, 3, 3,
7, 8, 6, 7, 8, 3, 1, 6, 5, 2, 7, 1, 2, 0, 1, 9, 0, 9, 1, 4, 5, 6,
4, 8, 5, 6, 6, 9, 2, 3, 4, 6, 0, 3, 4, 8, 6, 1, 0, 4, 5, 4, 3, 2,
6, 6, 4, 8, 2, 1, 3, 3, 9, 3, 6, 0, 7, 2, 6, 0, 2, 4, 9, 1, 4, 1,
2, 7, 3, 7, 2, 4, 5, 8, 7, 0, 0, 6, 6, 0, 6, 3, 1, 5, 5, 8, 8, 1,
7, 4, 8, 8, 1, 5, 2, 0, 9, 2, 0, 9, 6, 2, 8, 2, 9, 2, 5, 4, 0, 9,
1, 7, 1, 5, 3, 6, 4, 3, 6, 7, 8, 9, 2, 5, 9, 0, 3, 6, 0, 0, 1, 1,
3, 3, 0, 5, 3, 0, 5, 4, 8, 8, 2, 0, 4, 6, 6, 5, 2, 1, 3, 8, 4, 1,
4, 6, 9, 5, 1, 9, 4, 1, 5, 1, 1, 6, 0, 9, 4, 3, 3, 0, 5, 7, 2, 7,
0, 3, 6, 5, 7, 5, 9, 5, 9, 1, 9, 5, 3, 0, 9, 2, 1, 8, 6, 1, 1, 7,
3, 8, 1, 9, 3, 2, 6, 1, 1, 7, 9, 3, 1, 0, 5, 1, 1, 8, 5, 4, 8, 0,
7, 4, 4, 6, 2, 3, 7, 9, 9, 6, 2, 7, 4, 9, 5, 6, 7, 3, 5, 1, 8, 8,
5, 7, 5, 2, 7, 2, 4, 8, 9, 1, 2, 2, 7, 9, 3, 8, 1, 8, 3, 0, 1, 1,
9, 4, 9, 1, 2, 9, 8, 3, 3, 6, 7, 3, 3, 6, 2, 4, 4, 0, 6, 5, 6, 6,
4, 3, 0, 8, 6, 0, 2, 1, 3, 9, 4, 9, 4, 6, 3, 9, 5, 2, 2, 4, 7, 3,
7, 1, 9, 0, 7, 0, 2, 1, 7, 9, 8, 6, 0, 9, 4, 3, 7, 0, 2, 7, 7, 0,
5, 3, 9, 2, 1, 7, 1, 7, 6, 2, 9, 3, 1, 7, 6, 7, 5, 2, 3, 8, 4, 6,
7, 4, 8, 1, 8, 4, 6, 7, 6, 6, 9, 4, 0, 5, 1, 3, 2, 0, 0, 0, 5, 6,
8, 1, 2, 7, 1, 4, 5, 2, 6, 3, 5, 6, 0, 8, 2, 7, 7, 8, 5, 7, 7, 1,
3, 4, 2, 7, 5, 7, 7, 8, 9, 6, 0, 9, 1, 7, 3, 6, 3, 7, 1, 7, 8, 7,
2, 1, 4, 6, 8, 4, 4, 0, 9, 0, 1, 2, 2, 4, 9, 5, 3, 4, 3, 0, 1, 4,
6, 5, 4, 9, 5, 8, 5, 3, 7, 1, 0, 5, 0, 7, 9, 2, 2, 7, 9, 6, 8, 9,
2, 5, 8, 9, 2, 3, 5, 4, 2, 0, 1, 9, 9, 5, 6, 1, 1, 2, 1, 2, 9, 0,
2, 1, 9, 6, 0, 8, 6, 4, 0, 3, 4, 4, 1, 8, 1, 5, 9, 8, 1, 3, 6, 2,
9, 7, 7, 4, 7, 7, 1, 3, 0, 9, 9, 6, 0, 5, 1, 8, 7, 0, 7, 2, 1, 1,
3, 4, 9, 9, 9, 9, 9, 9, 8, 3, 7, 2, 9, 7, 8, 0, 4, 9, 9, 5, 1, 0,
5, 9, 7, 3, 1, 7, 3, 2, 8, 1, 6, 0, 9, 6, 3, 1, 8, 5, 9, 5, 0, 2,
4, 4, 5, 9, 4, 5, 5, 3, 4, 6, 9, 0, 8, 3, 0, 2, 6, 4, 2, 5, 2, 2,
3, 0, 8, 2, 5, 3, 3, 4, 4, 6, 8, 5, 0, 3, 5, 2, 6, 1, 9, 3, 1, 1,
8, 8, 1, 7, 1, 0, 1, 0, 0, 0, 3, 1, 3, 7, 8, 3, 8, 7, 5, 2, 8, 8,
6, 5, 8, 7, 5, 3, 3, 2, 0, 8, 3, 8, 1, 4, 2, 0, 6, 1, 7, 1, 7, 7,
6, 6, 9, 1, 4, 7, 3, 0, 3, 5, 9, 8, 2, 5, 3, 4, 9, 0, 4, 2, 8, 7,
5, 5, 4, 6, 8, 7, 3, 1, 1, 5, 9, 5, 6, 2, 8, 6, 3, 8, 8, 2, 3, 5,
3, 7, 8, 7, 5, 9, 3, 7, 5, 1, 9, 5, 7, 7, 8, 1, 8, 5, 7, 7, 3, 0,
5, 3, 2, 1, 7, 1, 2, 2, 6, 8, 0, 6, 6, 1, 3, 0, 0, 1, 9, 2, 7, 8,
7, 6, 6, 1, 1, 1, 9, 5, 9, 0, 9, 2, 1, 6, 4, 2, 0, 1, 9, 8, 9, 3,
8, 0, 9, 5, 2, 5, 7, 2, 0, 1, 0, 6, 5, 4, 8, 5, 8, 6, 3, 2, 7, 8,
8, 6, 5, 9, 3, 6, 1, 5, 3, 3, 8, 1, 8, 2, 7, 9, 6, 8, 2, 3, 0, 3,
0, 1, 9, 5, 2, 0, 3, 5, 3, 0, 1, 8, 5, 2, 9, 6, 8, 9, 9, 5, 7, 7,
3, 6, 2, 2, 5, 9, 9, 4, 1, 3, 8, 9, 1, 2, 4, 9, 7, 2, 1, 7, 7, 5,
2, 8, 3, 4, 7, 9, 1, 3, 1, 5, 1, 5, 5, 7, 4, 8, 5, 7, 2, 4, 2, 4,
5, 4, 1, 5, 0, 6, 9, 5, 9, 5, 0, 8, 2, 9, 5, 3, 3, 1, 1, 6, 8, 6,
1, 7, 2, 7, 8, 5, 5, 8, 8, 9, 0, 7, 5, 0, 9, 8, 3, 8, 1, 7, 5, 4,
6, 3, 7, 4, 6, 4, 9, 3, 9, 3, 1, 9, 2, 5, 5, 0, 6, 0, 4, 0, 0, 9,
2, 7, 7, 0, 1, 6, 7, 1, 1, 3, 9, 0, 0, 9, 8, 4, 8, 8, 2, 4, 0, 1,
2, 8, 5, 8, 3, 6, 1, 6, 0, 3, 5, 6, 3, 7, 0, 7, 6, 6, 0, 1, 0, 4,
7, 1, 0, 1, 8, 1, 9, 4, 2, 9, 5, 5, 5, 9, 6, 1, 9, 8, 9, 4, 6, 7,
6, 7, 8, 3, 7, 4, 4, 9, 4, 4, 8, 2, 5, 5, 3, 7, 9, 7, 7, 4, 7, 2,
6, 8, 4, 7, 1, 0, 4, 0, 4, 7, 5, 3, 4, 6, 4, 6, 2, 0, 8, 0, 4, 6,
6, 8, 4, 2, 5, 9, 0, 6, 9, 4, 9, 1, 2, 9, 3, 3, 1, 3, 6, 7, 7, 0,
2, 8, 9, 8, 9, 1, 5, 2, 1, 0, 4, 7, 5, 2, 1, 6, 2, 0, 5, 6, 9, 6,
6, 0, 2, 4, 0, 5, 8, 0, 3, 8, 1, 5, 0, 1, 9, 3, 5, 1, 1, 2, 5, 3,
3, 8, 2, 4, 3, 0, 0, 3, 5, 5, 8, 7, 6, 4, 0, 2, 4, 7, 4, 9, 6, 4,
7, 3, 2, 6, 3, 9, 1, 4, 1, 9, 9, 2, 7, 2, 6, 0, 4, 2, 6, 9, 9, 2,
2, 7, 9, 6, 7, 8, 2, 3, 5, 4, 7, 8, 1, 6, 3, 6, 0, 0, 9, 3, 4, 1,
7, 2, 1, 6, 4, 1, 2, 1, 9, 9, 2, 4, 5, 8, 6, 3, 1, 5, 0, 3, 0, 2,
8, 6, 1, 8, 2, 9, 7, 4, 5, 5, 5, 7, 0, 6, 7, 4, 9, 8, 3, 8, 5, 0,
5, 4, 9, 4, 5, 8, 8, 5, 8, 6, 9, 2, 6, 9, 9, 5, 6, 9, 0, 9, 2, 7,
2, 1, 0, 7, 9, 7, 5, 0, 9, 3, 0, 2, 9, 5, 5, 3, 2, 1, 1, 6, 5, 3,
4, 4, 9, 8, 7, 2, 0, 2, 7, 5, 5, 9, 6, 0, 2, 3, 6, 4, 8, 0, 6, 6,
5, 4, 9, 9, 1, 1, 9, 8, 8, 1, 8, 3, 4, 7, 9, 7, 7, 5, 3, 5, 6, 6,
3, 6, 9, 8, 0, 7, 4, 2, 6, 5, 4, 2, 5, 2, 7, 8, 6, 2, 5, 5, 1, 8,
1, 8, 4, 1, 7, 5, 7, 4, 6, 7, 2, 8, 9, 0, 9, 7, 7, 7, 7, 2, 7, 9,
3, 8, 0, 0, 0, 8, 1, 6, 4, 7, 0, 6, 0, 0, 1, 6, 1, 4, 5, 2, 4, 9,
1, 9, 2, 1, 7, 3, 2, 1, 7, 2, 1, 4, 7, 7, 2, 3, 5, 0, 1, 4, 1, 4,
4, 1, 9, 7, 3, 5, 6, 8, 5, 4, 8, 1, 6, 1, 3, 6, 1, 1, 5, 7, 3, 5,
2, 5, 5, 2, 1, 3, 3, 4, 7, 5, 7, 4, 1, 8, 4, 9, 4, 6, 8, 4, 3, 8,
5, 2, 3, 3, 2, 3, 9, 0, 7, 3, 9, 4, 1, 4, 3, 3, 3, 4, 5, 4, 7, 7,
6, 2, 4, 1, 6, 8, 6, 2, 5, 1, 8, 9, 8, 3, 5, 6, 9, 4, 8, 5, 5, 6,
2, 0, 9, 9, 2, 1, 9, 2, 2, 2, 1, 8, 4, 2, 7, 2, 5, 5, 0, 2, 5, 4,
2, 5, 6, 8, 8, 7, 6, 7, 1, 7, 9, 0, 4, 9, 4, 6, 0, 1, 6, 5, 3, 4,
6, 6, 8, 0, 4, 9, 8, 8, 6, 2, 7, 2, 3, 2, 7, 9, 1, 7, 8, 6, 0, 8,
5, 7, 8, 4, 3, 8, 3, 8, 2, 7, 9, 6, 7, 9, 7, 6, 6, 8, 1, 4, 5, 4,
1, 0, 0, 9, 5, 3, 8, 8, 3, 7, 8, 6, 3, 6, 0, 9, 5, 0, 6, 8, 0, 0,
6, 4, 2, 2, 5, 1, 2, 5, 2, 0, 5, 1, 1, 7, 3, 9, 2, 9, 8, 4, 8, 9,
6, 0, 8, 4, 1, 2, 8, 4, 8, 8, 6, 2, 6, 9, 4, 5, 6, 0, 4, 2, 4, 1,
9, 6, 5, 2, 8, 5, 0, 2, 2, 2, 1, 0, 6, 6, 1, 1, 8, 6, 3, 0, 6, 7,
4, 4, 2, 7, 8, 6, 2, 2, 0, 3, 9, 1, 9, 4, 9, 4, 5, 0, 4, 7, 1, 2,
3, 7, 1, 3, 7, 8, 6, 9, 6, 0, 9, 5, 6, 3, 6, 4, 3, 7, 1, 9, 1, 7,
2, 8, 7, 4, 6, 7, 7, 6, 4, 6, 5, 7, 5, 7, 3, 9, 6, 2, 4, 1, 3, 8,
9, 0, 8, 6, 5, 8, 3, 2, 6, 4, 5, 9, 9, 5, 8, 1, 3, 3, 9, 0, 4, 7,
8, 0, 2, 7, 5, 9, 0, 0, 9, 9, 4, 6, 5, 7, 6, 4, 0, 7, 8, 9, 5, 1,
2, 6, 9, 4, 6, 8, 3, 9, 8, 3, 5, 2, 5, 9, 5, 7, 0, 9, 8, 2, 5, 8,
2, 2, 6, 2, 0, 5, 2, 2, 4, 8, 9, 4, 0, 7, 7, 2, 6, 7, 1, 9, 4, 7,
8, 2, 6, 8, 4, 8, 2, 6, 0, 1, 4, 7, 6, 9, 9, 0, 9, 0, 2, 6, 4, 0,
1, 3, 6, 3, 9, 4, 4, 3, 7, 4, 5, 5, 3, 0, 5, 0, 6, 8, 2, 0, 3, 4,
9, 6, 2, 5, 2, 4, 5, 1, 7, 4, 9, 3, 9, 9, 6, 5, 1, 4, 3, 1, 4, 2,
9, 8, 0, 9, 1, 9, 0, 6, 5, 9, 2, 5, 0, 9, 3, 7, 2, 2, 1, 6, 9, 6,
4, 6, 1, 5, 1, 5, 7, 0, 9, 8, 5, 8, 3, 8, 7, 4, 1, 0, 5, 9, 7, 8,
8, 5, 9, 5, 9, 7, 7, 2, 9, 7, 5, 4, 9, 8, 9, 3, 0, 1, 6, 1, 7, 5,
3, 9, 2, 8, 4, 6, 8, 1, 3, 8, 2, 6, 8, 6, 8, 3, 8, 6, 8, 9, 4, 2,
7, 7, 4, 1, 5, 5, 9, 9, 1, 8, 5, 5, 9, 2, 5, 2, 4, 5, 9, 5, 3, 9,
5, 9, 4, 3, 1, 0, 4, 9, 9, 7, 2, 5, 2, 4, 6, 8, 0, 8, 4, 5, 9, 8,
7, 2, 7, 3, 6, 4, 4, 6, 9, 5, 8, 4, 8, 6, 5, 3, 8, 3, 6, 7, 3, 6,
2, 2, 2, 6, 2, 6, 0, 9, 9, 1, 2, 4, 6, 0, 8, 0, 5, 1, 2, 4, 3, 8,
8, 4, 3, 9, 0, 4, 5, 1, 2, 4, 4, 1, 3, 6, 5, 4, 9, 7, 6, 2, 7, 8,
0, 7, 9, 7, 7, 1, 5, 6, 9, 1, 4, 3, 5, 9, 9, 7, 7, 0, 0, 1, 2, 9,
6, 1, 6, 0, 8, 9, 4, 4, 1, 6, 9, 4, 8, 6, 8, 5, 5, 5, 8, 4, 8, 4,
0, 6, 3, 5, 3, 4, 2, 2, 0, 7, 2, 2, 2, 5, 8, 2, 8, 4, 8, 8, 6, 4,
8, 1, 5, 8, 4, 5, 6, 0, 2, 8, 5, 0, 6, 0, 1, 6, 8, 4, 2, 7, 3, 9,
4, 5, 2, 2, 6, 7, 4, 6, 7, 6, 7, 8, 8, 9, 5, 2, 5, 2, 1, 3, 8, 5,
2, 2, 5, 4, 9, 9, 5, 4, 6, 6, 6, 7, 2, 7, 8, 2, 3, 9, 8, 6, 4, 5,
6, 5, 9, 6, 1, 1, 6, 3, 5, 4, 8, 8, 6, 2, 3, 0, 5, 7, 7, 4, 5, 6,
4, 9, 8, 0, 3, 5, 5, 9, 3, 6, 3, 4, 5, 6, 8, 1, 7, 4, 3, 2, 4, 1,
1, 2, 5, 1, 5, 0, 7, 6, 0, 6, 9, 4, 7, 9, 4, 5, 1, 0, 9, 6, 5, 9,
6, 0, 9, 4, 0, 2, 5, 2, 2, 8, 8, 7, 9, 7, 1, 0, 8, 9, 3, 1, 4, 5,
6, 6, 9, 1, 3, 6, 8, 6, 7, 2, 2, 8, 7, 4, 8, 9, 4, 0, 5, 6, 0, 1,
0, 1, 5, 0, 3, 3, 0, 8, 6, 1, 7, 9, 2, 8, 6, 8, 0, 9, 2, 0, 8, 7,
4, 7, 6, 0, 9, 1, 7, 8, 2, 4, 9, 3, 8, 5, 8, 9, 0, 0, 9, 7, 1, 4,
9, 0, 9, 6, 7, 5, 9, 8, 5, 2, 6, 1, 3, 6, 5, 5, 4, 9, 7, 8, 1, 8,
9, 3, 1, 2, 9, 7, 8, 4, 8, 2, 1, 6, 8, 2, 9, 9, 8, 9, 4, 8, 7, 2,
2, 6, 5, 8, 8, 0, 4, 8, 5, 7, 5, 6, 4, 0, 1, 4, 2, 7, 0, 4, 7, 7,
5, 5, 5, 1, 3, 2, 3, 7, 9, 6, 4, 1, 4, 5, 1, 5, 2, 3, 7, 4, 6, 2,
3, 4, 3, 6, 4, 5, 4, 2, 8, 5, 8, 4, 4, 4, 7, 9, 5, 2, 6, 5, 8, 6,
7, 8, 2, 1, 0, 5, 1, 1, 4, 1, 3, 5, 4, 7, 3, 5, 7, 3, 9, 5, 2, 3,
1, 1, 3, 4, 2, 7, 1, 6, 6, 1, 0, 2, 1, 3, 5, 9, 6, 9, 5, 3, 6, 2,
3, 1, 4, 4, 2, 9, 5, 2, 4, 8, 4, 9, 3, 7, 1, 8, 7, 1, 1, 0, 1, 4,
5, 7, 6, 5, 4, 0, 3, 5, 9, 0, 2, 7, 9, 9, 3, 4, 4, 0, 3, 7, 4, 2,
0, 0, 7, 3, 1, 0, 5, 7, 8, 5, 3, 9, 0, 6, 2, 1, 9, 8, 3, 8, 7, 4,
4, 7, 8, 0, 8, 4, 7, 8, 4, 8, 9, 6, 8, 3, 3, 2, 1, 4, 4, 5, 7, 1,
3, 8, 6, 8, 7, 5, 1, 9, 4, 3, 5, 0, 6, 4, 3, 0, 2, 1, 8, 4, 5, 3,
1, 9, 1, 0, 4, 8, 4, 8, 1, 0, 0, 5, 3, 7, 0, 6, 1, 4, 6, 8, 0, 6,
7, 4, 9, 1, 9, 2, 7, 8, 1, 9, 1, 1, 9, 7, 9, 3, 9, 9, 5, 2, 0, 6,
1, 4, 1, 9, 6, 6, 3, 4, 2, 8, 7, 5, 4, 4, 4, 0, 6, 4, 3, 7, 4, 5,
1, 2, 3, 7, 1, 8, 1, 9, 2, 1, 7, 9, 9, 9, 8, 3, 9, 1, 0, 1, 5, 9,
1, 9, 5, 6, 1, 8, 1, 4, 6, 7, 5, 1, 4, 2, 6, 9, 1, 2, 3, 9, 7, 4,
8, 9, 4, 0, 9, 0, 7, 1, 8, 6, 4, 9, 4, 2, 3, 1, 9, 6, 1, 5, 6, 7,
9, 4, 5, 2, 0, 8, 0, 9, 5, 1, 4, 6, 5, 5, 0, 2, 2, 5, 2, 3, 1, 6,
0, 3, 8, 8, 1, 9, 3, 0, 1, 4, 2, 0, 9, 3, 7, 6, 2, 1, 3, 7, 8, 5,
5, 9, 5, 6, 6, 3, 8, 9, 3, 7, 7, 8, 7, 0, 8, 3, 0, 3, 9, 0, 6, 9,
7, 9, 2, 0, 7, 7, 3, 4, 6, 7, 2, 2, 1, 8, 2, 5, 6, 2, 5, 9, 9, 6,
6, 1, 5, 0, 1, 4, 2, 1, 5, 0, 3, 0, 6, 8, 0, 3, 8, 4, 4, 7, 7, 3,
4, 5, 4, 9, 2, 0, 2, 6, 0, 5, 4, 1, 4, 6, 6, 5, 9, 2, 5, 2, 0, 1,
4, 9, 7, 4, 4, 2, 8, 5, 0, 7, 3, 2, 5, 1, 8, 6, 6, 6, 0, 0, 2, 1,
3, 2, 4, 3, 4, 0, 8, 8, 1, 9, 0, 7, 1, 0, 4, 8, 6, 3, 3, 1, 7, 3,
4, 6, 4, 9, 6, 5, 1, 4, 5, 3, 9, 0, 5, 7, 9, 6, 2, 6, 8, 5, 6, 1,
0, 0, 5, 5, 0, 8, 1, 0, 6, 6, 5, 8, 7, 9, 6, 9, 9, 8, 1, 6, 3, 5,
7, 4, 7, 3, 6, 3, 8, 4, 0, 5, 2, 5, 7, 1, 4, 5, 9, 1, 0, 2, 8, 9,
7, 0, 6, 4, 1, 4, 0, 1, 1, 0, 9, 7, 1, 2, 0, 6, 2, 8, 0, 4, 3, 9,
0, 3, 9, 7, 5, 9, 5, 1, 5, 6, 7, 7, 1, 5, 7, 7, 0, 0, 4, 2, 0, 3,
3, 7, 8, 6, 9, 9, 3, 6, 0, 0, 7, 2, 3, 0, 5, 5, 8, 7, 6, 3, 1, 7,
6, 3, 5, 9, 4, 2, 1, 8, 7, 3, 1, 2, 5, 1, 4, 7, 1, 2, 0, 5, 3, 2,
9, 2, 8, 1, 9, 1, 8, 2, 6, 1, 8, 6, 1, 2, 5, 8, 6, 7, 3, 2, 1, 5,
7, 9, 1, 9, 8, 4, 1, 4, 8, 4, 8, 8, 2, 9, 1, 6, 4, 4, 7, 0, 6, 0,
9, 5, 7, 5, 2, 7, 0, 6, 9, 5, 7, 2, 2, 0, 9, 1, 7, 5, 6, 7, 1, 1,
6, 7, 2, 2, 9, 1, 0, 9, 8, 1, 6, 9, 0, 9, 1, 5, 2, 8, 0, 1, 7, 3,
5, 0, 6, 7, 1, 2, 7, 4, 8, 5, 8, 3, 2, 2, 2, 8, 7, 1, 8, 3, 5, 2,
0, 9, 3, 5, 3, 9, 6, 5, 7, 2, 5, 1, 2, 1, 0, 8, 3, 5, 7, 9, 1, 5,
1, 3, 6, 9, 8, 8, 2, 0, 9, 1, 4, 4, 4, 2, 1, 0, 0, 6, 7, 5, 1, 0,
3, 3, 4, 6, 7, 1, 1, 0, 3, 1, 4, 1, 2, 6, 7, 1, 1, 1, 3, 6, 9, 9,
0, 8, 6, 5, 8, 5, 1, 6, 3, 9, 8, 3, 1, 5, 0, 1, 9, 7, 0, 1, 6, 5,
1, 5, 1, 1, 6, 8, 5, 1, 7, 1, 4, 3, 7, 6, 5, 7, 6, 1, 8, 3, 5, 1,
5, 5, 6, 5, 0, 8, 8, 4, 9, 0, 9, 9, 8, 9, 8, 5, 9, 9, 8, 2, 3, 8,
7, 3, 4, 5, 5, 2, 8, 3, 3, 1, 6, 3, 5, 5, 0, 7, 6, 4, 7, 9, 1, 8,
5, 3, 5, 8, 9, 3, 2, 2, 6, 1, 8, 5, 4, 8, 9, 6, 3, 2, 1, 3, 2, 9,
3, 3, 0, 8, 9, 8, 5, 7, 0, 6, 4, 2, 0, 4, 6, 7, 5, 2, 5, 9, 0, 7,
0, 9, 1, 5, 4, 8, 1, 4, 1, 6, 5, 4, 9, 8, 5, 9, 4, 6, 1, 6, 3, 7,
1, 8, 0, 2, 7, 0, 9, 8, 1, 9, 9, 4, 3, 0, 9, 9, 2, 4, 4, 8, 8, 9,
5, 7, 5, 7, 1, 2, 8, 2, 8, 9, 0, 5, 9, 2, 3, 2, 3, 3, 2, 6, 0, 9,
7, 2, 9, 9, 7, 1, 2, 0, 8, 4, 4, 3, 3, 5, 7, 3, 2, 6, 5, 4, 8, 9,
3, 8, 2, 3, 9, 1, 1, 9, 3, 2, 5, 9, 7, 4, 6, 3, 6, 6, 7, 3, 0, 5,
8, 3, 6, 0, 4, 1, 4, 2, 8, 1, 3, 8, 8, 3, 0, 3, 2, 0, 3, 8, 2, 4,
9, 0, 3, 7, 5, 8, 9, 8, 5, 2, 4, 3, 7, 4, 4, 1, 7, 0, 2, 9, 1, 3,
2, 7, 6, 5, 6, 1, 8, 0, 9, 3, 7, 7, 3, 4, 4, 4, 0, 3, 0, 7, 0, 7,
4, 6, 9, 2, 1, 1, 2, 0, 1, 9, 1, 3, 0, 2, 0, 3, 3, 0, 3, 8, 0, 1,
9, 7, 6, 2, 1, 1, 0, 1, 1, 0, 0, 4, 4, 9, 2, 9, 3, 2, 1, 5, 1, 6,
0, 8, 4, 2, 4, 4, 4, 8, 5, 9, 6, 3, 7, 6, 6, 9, 8, 3, 8, 9, 5, 2,
2, 8, 6, 8, 4, 7, 8, 3, 1, 2, 3, 5, 5, 2, 6, 5, 8, 2, 1, 3, 1, 4,
4, 9, 5, 7, 6, 8, 5, 7, 2, 6, 2, 4, 3, 3, 4, 4, 1, 8, 9, 3, 0, 3,
9, 6, 8, 6, 4, 2, 6, 2, 4, 3, 4, 1, 0, 7, 7, 3, 2, 2, 6, 9, 7, 8,
0, 2, 8, 0, 7, 3, 1, 8, 9, 1, 5, 4, 4, 1, 1, 0, 1, 0, 4, 4, 6, 8,
2, 3, 2, 5, 2, 7, 1, 6, 2, 0, 1, 0, 5, 2, 6, 5, 2, 2, 7, 2, 1, 1,
1, 6, 6, 0, 3, 9, 6, 6, 6, 5, 5, 7, 3, 0, 9, 2, 5, 4, 7, 1, 1, 0,
5, 5, 7, 8, 5, 3, 7, 6, 3, 4, 6, 6, 8, 2, 0, 6, 5, 3, 1, 0, 9, 8,
9, 6, 5, 2, 6, 9, 1, 8, 6, 2, 0, 5, 6, 4, 7, 6, 9, 3, 1, 2, 5, 7,
0, 5, 8, 6, 3, 5, 6, 6, 2, 0, 1, 8, 5, 5, 8, 1, 0, 0, 7, 2, 9, 3,
6, 0, 6, 5, 9, 8, 7, 6, 4, 8, 6, 1, 1, 7, 9, 1, 0, 4, 5, 3, 3, 4,
8, 8, 5, 0, 3, 4, 6, 1, 1, 3, 6, 5, 7, 6, 8, 6, 7, 5, 3, 2, 4, 9,
4, 4, 1, 6, 6, 8, 0, 3, 9, 6, 2, 6, 5, 7, 9, 7, 8, 7, 7, 1, 8, 5,
5, 6, 0, 8, 4, 5, 5, 2, 9, 6, 5, 4, 1, 2, 6, 6, 5, 4, 0, 8, 5, 3,
0, 6, 1, 4, 3, 4, 4, 4, 3, 1, 8, 5, 8, 6, 7, 6, 9, 7, 5, 1, 4, 5,
6, 6, 1, 4, 0, 6, 8, 0, 0, 7, 0, 0, 2, 3, 7, 8, 7, 7, 6, 5, 9, 1,
3, 4, 4, 0, 1, 7, 1, 2, 7, 4, 9, 4, 7, 0, 4, 2, 0, 5, 6, 2, 2, 3,
0, 5, 3, 8, 9, 9, 4, 5, 6, 1, 3, 1, 4, 0, 7, 1, 1, 2, 7, 0, 0, 0,
4, 0, 7, 8, 5, 4, 7, 3, 3, 2, 6, 9, 9, 3, 9, 0, 8, 1, 4, 5, 4, 6,
6, 4, 6, 4, 5, 8, 8, 0, 7, 9, 7, 2, 7, 0, 8, 2, 6, 6, 8, 3, 0, 6,
3, 4, 3, 2, 8, 5, 8, 7, 8, 5, 6, 9, 8, 3, 0, 5, 2, 3, 5, 8, 0, 8,
9, 3, 3, 0, 6, 5, 7, 5, 7, 4, 0, 6, 7, 9, 5, 4, 5, 7, 1, 6, 3, 7,
7, 5, 2, 5, 4, 2, 0, 2, 1, 1, 4, 9, 5, 5, 7, 6, 1, 5, 8, 1, 4, 0,
0, 2, 5, 0, 1, 2, 6, 2, 2, 8, 5, 9, 4, 1, 3, 0, 2, 1, 6, 4, 7, 1,
5, 5, 0, 9, 7, 9, 2, 5, 9, 2, 3, 0, 9, 9, 0, 7, 9, 6, 5, 4, 7, 3,
7, 6, 1, 2, 5, 5, 1, 7, 6, 5, 6, 7, 5, 1, 3, 5, 7, 5, 1, 7, 8, 2,
9, 6, 6, 6, 4, 5, 4, 7, 7, 9, 1, 7, 4, 5, 0, 1, 1, 2, 9, 9, 6, 1,
4, 8, 9, 0, 3, 0, 4, 6, 3, 9, 9, 4, 7, 1, 3, 2, 9, 6, 2, 1, 0, 7,
3, 4, 0, 4, 3, 7, 5, 1, 8, 9, 5, 7, 3, 5, 9, 6, 1, 4, 5, 8, 9, 0,
1, 9, 3, 8, 9, 7, 1, 3, 1, 1, 1, 7, 9, 0, 4, 2, 9, 7, 8, 2, 8, 5,
6, 4, 7, 5, 0, 3, 2, 0, 3, 1, 9, 8, 6, 9, 1, 5, 1, 4, 0, 2, 8, 7,
0, 8, 0, 8, 5, 9, 9, 0, 4, 8, 0, 1, 0, 9, 4, 1, 2, 1, 4, 7, 2, 2,
1, 3, 1, 7, 9, 4, 7, 6, 4, 7, 7, 7, 2, 6, 2, 2, 4, 1, 4, 2, 5, 4,
8, 5, 4, 5, 4, 0, 3, 3, 2, 1, 5, 7, 1, 8, 5, 3, 0, 6, 1, 4, 2, 2,
8, 8, 1, 3, 7, 5, 8, 5, 0, 4, 3, 0, 6, 3, 3, 2, 1, 7, 5, 1, 8, 2,
9, 7, 9, 8, 6, 6, 2, 2, 3, 7, 1, 7, 2, 1, 5, 9, 1, 6, 0, 7, 7, 1,
6, 6, 9, 2, 5, 4, 7, 4, 8, 7, 3, 8, 9, 8, 6, 6, 5, 4, 9, 4, 9, 4,
5, 0, 1, 1, 4, 6, 5, 4, 0, 6, 2, 8, 4, 3, 3, 6, 6, 3, 9, 3, 7, 9,
0, 0, 3, 9, 7, 6, 9, 2, 6, 5, 6, 7, 2, 1, 4, 6, 3, 8, 5, 3, 0, 6,
7, 3, 6, 0, 9, 6, 5, 7, 1, 2, 0, 9, 1, 8, 0, 7, 6, 3, 8, 3, 2, 7,
1, 6, 6, 4, 1, 6, 2, 7, 4, 8, 8, 8, 8, 0, 0, 7, 8, 6, 9, 2, 5, 6,
0, 2, 9, 0, 2, 2, 8, 4, 7, 2, 1, 0, 4, 0, 3, 1, 7, 2, 1, 1, 8, 6,
0, 8, 2, 0, 4, 1, 9, 0, 0, 0, 4, 2, 2, 9, 6, 6, 1, 7, 1, 1, 9, 6,
3, 7, 7, 9, 2, 1, 3, 3, 7, 5, 7, 5, 1, 1, 4, 9, 5, 9, 5, 0, 1, 5,
6, 6, 0, 4, 9, 6, 3, 1, 8, 6, 2, 9, 4, 7, 2, 6, 5, 4, 7, 3, 6, 4,
2, 5, 2, 3, 0, 8, 1, 7, 7, 0, 3, 6, 7, 5, 1, 5, 9, 0, 6, 7, 3, 5,
0, 2, 3, 5, 0, 7, 2, 8, 3, 5, 4, 0, 5, 6, 7, 0, 4, 0, 3, 8, 6, 7,
4, 3, 5, 1, 3, 6, 2, 2, 2, 2, 4, 7, 7, 1, 5, 8, 9, 1, 5, 0, 4, 9,
5, 3, 0, 9, 8, 4, 4, 4, 8, 9, 3, 3, 3, 0, 9, 6, 3, 4, 0, 8, 7, 8,
0, 7, 6, 9, 3, 2, 5, 9, 9, 3, 9, 7, 8, 0, 5, 4, 1, 9, 3, 4, 1, 4,
4, 7, 3, 7, 7, 4, 4, 1, 8, 4, 2, 6, 3, 1, 2, 9, 8, 6, 0, 8, 0, 9,
9, 8, 8, 8, 6, 8, 7, 4, 1, 3, 2, 6, 0, 4, 7, 2 } ;
const size_t nacc1 = 3 ;
const double numacc1[3] = { 10000001, 10000003, 10000002 } ;
const size_t nacc2 = 1001 ;
double numacc2[1001] ;
const size_t nacc3 = 1001 ;
double numacc3[1001] ;
const size_t nacc4 = 1001 ;
double numacc4[1001] ;
numacc2[0] = 1.2 ;
numacc3[0] = 1000000.2 ;
numacc4[0] = 10000000.2 ;
for (i = 1 ; i < 1000 ; i += 2)
{
numacc2[i] = 1.1 ;
numacc2[i+1] = 1.3 ;
numacc3[i] = 1000000.1 ;
numacc3[i+1] = 1000000.3 ;
numacc4[i] = 10000000.1 ;
numacc4[i+1] = 10000000.3 ;
}
gsl_ieee_env_setup ();
{
double mean = gsl_stats_mean (lew, 1, nlew);
double sd = gsl_stats_sd (lew, 1, nlew);
double lag1 = gsl_stats_lag1_autocorrelation (lew, 1, nlew);
double expected_mean = -177.435000000000;
double expected_sd = 277.332168044316;
double expected_lag1 = -0.307304800605679;
gsl_test_rel (mean, expected_mean, 1e-15, "lew gsl_stats_mean") ;
gsl_test_rel (sd, expected_sd, 1e-15, "lew gsl_stats_sd") ;
gsl_test_rel (lag1, expected_lag1, 1e-14, "lew autocorrelation") ;
}
{
double mean = gsl_stats_mean (lottery, 1, nlottery);
double sd = gsl_stats_sd (lottery, 1, nlottery);
double lag1 = gsl_stats_lag1_autocorrelation (lottery, 1, nlottery);
double expected_mean = 518.958715596330;
double expected_sd = 291.699727470969;
double expected_lag1 = -0.120948622967393;
gsl_test_rel (mean, expected_mean, 1e-15, "lottery gsl_stats_mean") ;
gsl_test_rel (sd, expected_sd, 1e-15, "lottery gsl_stats_sd") ;
gsl_test_rel (lag1, expected_lag1, 1e-14, "lottery autocorrelation") ;
}
{
double mean = gsl_stats_mean (mavro, 1, nmavro);
double sd = gsl_stats_sd (mavro, 1, nmavro);
double lag1 = gsl_stats_lag1_autocorrelation (mavro, 1, nmavro);
double expected_mean = 2.00185600000000;
double expected_sd = 0.000429123454003053;
double expected_lag1 = 0.937989183438248;
gsl_test_rel (mean, expected_mean, 1e-15, "mavro gsl_stats_mean") ;
gsl_test_rel (sd, expected_sd, 1e-13, "mavro gsl_stats_sd") ;
gsl_test_rel (lag1, expected_lag1, 1e-13, "mavro autocorrelation") ;
}
{
double mean = gsl_stats_mean (michelson, 1, nmichelson);
double sd = gsl_stats_sd (michelson, 1, nmichelson);
double lag1 = gsl_stats_lag1_autocorrelation (michelson, 1, nmichelson);
double expected_mean = 299.852400000000;
double expected_sd = 0.0790105478190518;
double expected_lag1 = 0.535199668621283;
gsl_test_rel (mean, expected_mean, 1e-15, "michelson gsl_stats_mean") ;
gsl_test_rel (sd, expected_sd, 1e-13, "michelson gsl_stats_sd") ;
gsl_test_rel (lag1, expected_lag1, 1e-13, "michelson autocorrelation") ;
}
{
double mean = gsl_stats_mean (pidigits, 1, npidigits);
double sd = gsl_stats_sd (pidigits, 1, npidigits);
double lag1 = gsl_stats_lag1_autocorrelation (pidigits, 1, npidigits);
double expected_mean = 4.53480000000000;
double expected_sd = 2.86733906028871;
double expected_lag1 = -0.00355099287237972;
gsl_test_rel (mean, expected_mean, 1e-14, "pidigits gsl_stats_mean") ;
gsl_test_rel (sd, expected_sd, 1e-15, "pidigits gsl_stats_sd") ;
gsl_test_rel (lag1, expected_lag1, 1e-14, "pidigits autocorrelation") ;
}
{
double mean = gsl_stats_mean (numacc1, 1, nacc1);
double sd = gsl_stats_sd (numacc1, 1, nacc1);
double lag1 = gsl_stats_lag1_autocorrelation (numacc1, 1, nacc1);
double expected_mean = 10000002;
double expected_sd = 1;
double expected_lag1 = -0.5;
gsl_test_rel (mean, expected_mean, 1e-15, "acc1 gsl_stats_mean") ;
gsl_test_rel (sd, expected_sd, 1e-15, "acc1 gsl_stats_sd") ;
gsl_test_rel (lag1, expected_lag1, 1e-15, "acc1 autocorrelation") ;
}
{
double mean = gsl_stats_mean (numacc2, 1, nacc2);
double sd = gsl_stats_sd (numacc2, 1, nacc2);
double lag1 = gsl_stats_lag1_autocorrelation (numacc2, 1, nacc2);
double expected_mean = 1.2;
double expected_sd = 0.1;
double expected_lag1 = -0.999;
gsl_test_rel (mean, expected_mean, 1e-15, "acc2 gsl_stats_mean") ;
gsl_test_rel (sd, expected_sd, 1e-15, "acc2 gsl_stats_sd") ;
gsl_test_rel (lag1, expected_lag1, 1e-10, "acc2 autocorrelation") ;
}
{
double mean = gsl_stats_mean (numacc3, 1, nacc3);
double sd = gsl_stats_sd (numacc3, 1, nacc3);
double lag1 = gsl_stats_lag1_autocorrelation (numacc3, 1, nacc3);
double expected_mean = 1000000.2;
double expected_sd = 0.1;
double expected_lag1 = -0.999;
gsl_test_rel (mean, expected_mean, 1e-15, "acc3 gsl_stats_mean") ;
gsl_test_rel (sd, expected_sd, 1e-9, "acc3 gsl_stats_sd") ;
gsl_test_rel (lag1, expected_lag1, 1e-10, "acc3 autocorrelation") ;
}
{
double mean = gsl_stats_mean (numacc4, 1, nacc4);
double sd = gsl_stats_sd (numacc4, 1, nacc4);
double lag1 = gsl_stats_lag1_autocorrelation (numacc4, 1, nacc4);
double expected_mean = 10000000.2;
double expected_sd = 0.1;
double expected_lag1 = -0.999;
gsl_test_rel (mean, expected_mean, 1e-15, "acc4 gsl_stats_mean") ;
gsl_test_rel (sd, expected_sd, 1e-7, "acc4 gsl_stats_sd") ;
gsl_test_rel (lag1, expected_lag1, 1e-10, "acc4 autocorrelation") ;
}
return 0;
}
| {
"alphanum_fraction": 0.441190917,
"avg_line_length": 52.5138888889,
"ext": "c",
"hexsha": "30b8ecc5647ce9eb19722adf8423d1b75775bb7e",
"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/statistics/test_nist.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/statistics/test_nist.c",
"max_line_length": 81,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/statistics/test_nist.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": 19739,
"size": 26467
} |
/*
Copyright (c) 2015, Patrick Weltevrede
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.
*/
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "psrsalsa.h"
#include <gsl/gsl_linalg.h>
int linalg_solve_matrix_eq_gauss_jordan(double *matrixa, double *matrixb, int n, int m, verbose_definition verbose)
{
int *orig_pivot_row, *orig_pivot_column, *pivot_column_done;
int pivotnr, pivot_col, pivot_row, rowi, coli, i;
double *ptr1, *ptr2, tmpvalue;
double largest_element_value;
int currow;
orig_pivot_row = malloc(n*sizeof(int));
orig_pivot_column = malloc(n*sizeof(int));
pivot_column_done = malloc(n*sizeof(int));
if(orig_pivot_row == NULL || orig_pivot_column == NULL || pivot_column_done == NULL) {
printerror(verbose.debug, "ERROR linalg_solve_matrix_eq_gauss_jordan: Memory allocation error.");
return 1;
}
for(coli = 0; coli < n; coli++)
pivot_column_done[coli] = 0;
for(pivotnr = 0; pivotnr < n; pivotnr++) {
largest_element_value = -1.0;
for(rowi = 0; rowi < n; rowi++) {
if(pivot_column_done[rowi] != 1) {
for(coli = 0; coli < n; coli++) {
if(pivot_column_done[coli] == 0) {
tmpvalue = matrixa[rowi*n+coli];
if(fabs(tmpvalue) >= largest_element_value) {
largest_element_value = fabs(tmpvalue);
pivot_row=rowi;
pivot_col=coli;
}
}else if(pivot_column_done[coli] > 1) {
printerror(verbose.debug, "ERROR linalg_solve_matrix_eq_gauss_jordan: The matrix equation is singular, no solution can be determined.");
return 2;
}
}
}
}
if(largest_element_value <= 0.0) {
printerror(verbose.debug, "ERROR linalg_solve_matrix_eq_gauss_jordan: The matrix equation is singular, no solution can be determined.");
return 2;
}
pivot_column_done[pivot_col] += 1;
if(pivot_row != pivot_col) {
ptr1 = matrixa + pivot_row*n;
ptr2 = matrixa + pivot_col*n;
for(i = 0; i < n; i++) {
tmpvalue = *ptr1;
*ptr1 = *ptr2;
*ptr2 = tmpvalue;
}
ptr1 = matrixb + pivot_row*n;
ptr2 = matrixb + pivot_col*n;
for(i = 0; i < n; i++) {
tmpvalue = *ptr1;
*ptr1 = *ptr2;
*ptr2 = tmpvalue;
}
}
orig_pivot_row[pivotnr] = pivot_row;
orig_pivot_column[pivotnr] = pivot_col;
matrixa[pivot_col*n+pivot_col]=1.0;
ptr1 = matrixa + pivot_col*n;
for(i = 0; i < n; i++) {
*ptr1 /= largest_element_value;
ptr1 += 1;
}
ptr1 = matrixb + pivot_col*m;
for(i = 0; i < m; i++) {
*ptr1 /= largest_element_value;
ptr1 += 1;
}
for(currow = 0; currow < n; currow++) {
if(currow != pivot_col) {
i = currow*n+pivot_col;
tmpvalue = matrixa[i];
matrixa[i] = 0.0;
ptr1 = matrixa + n*currow;
ptr2 = matrixa + n*pivot_col;
for(i=1; i <= n; i++) {
*ptr1 -= (*ptr2)*tmpvalue;
ptr1++;
ptr2++;
}
ptr1 = matrixb + currow*m;
ptr2 = matrixb + pivot_col*m;
for(i = 0; i < m; i++) {
*ptr1 -= (*ptr2)*tmpvalue;
ptr1++;
ptr2++;
}
}
}
}
for(coli = n-1; coli >= 0; coli--) {
if(orig_pivot_row[coli] != orig_pivot_column[coli]) {
for(rowi = 0; rowi <= n; rowi++) {
tmpvalue = matrixa[rowi*n+orig_pivot_row[coli]];
matrixa[rowi*n+orig_pivot_row[coli]] = matrixa[rowi*n+orig_pivot_column[coli]];
matrixa[rowi*n+orig_pivot_column[coli]] = tmpvalue;
}
}
}
free(pivot_column_done);
free(orig_pivot_row);
free(orig_pivot_column);
return 0;
}
| {
"alphanum_fraction": 0.6838723051,
"avg_line_length": 38.2857142857,
"ext": "c",
"hexsha": "552a49f006895308b6cdec9cbbcd7e24f7780ab1",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z",
"max_forks_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "David-McKenna/psrsalsa",
"max_forks_repo_path": "src/lib/linalg.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9",
"max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "David-McKenna/psrsalsa",
"max_issues_repo_path": "src/lib/linalg.c",
"max_line_length": 755,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "David-McKenna/psrsalsa",
"max_stars_repo_path": "src/lib/linalg.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z",
"num_tokens": 1333,
"size": 4824
} |
/* multilarge_nlinear/nielsen.c
*
* Copyright (C) 2016 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* This module contains routines for updating the Levenberg-Marquardt
* damping parameter on each iteration using Nielsen's method:
*
* [1] H. B. Nielsen, K. Madsen, Introduction to Optimization and
* Data Fitting, Informatics and Mathematical Modeling,
* Technical University of Denmark (DTU), 2010.
*
* 3 routines are needed to implement the update procedure:
*
* 1. init - initialize parameter prior to iteration
* 2. accept - update parameter after a step has been accepted
* 3. reject - update parameter after a step has been rejected
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_blas.h>
#define LM_ONE_THIRD (0.333333333333333)
static int nielsen_init(const gsl_matrix * JTJ, const gsl_vector * diag,
double * mu, long * nu);
static int nielsen_accept(const double rho, double * mu, long * nu);
static int nielsen_reject(double * mu, long * nu);
static int
nielsen_init(const gsl_matrix * JTJ, const gsl_vector * diag,
double * mu, long * nu)
{
const double mu0 = 1.0e-3;
size_t i;
double max = -1.0;
*nu = 2;
if (JTJ == NULL)
{
/* not using cholesky solver */
*mu = mu0;
return GSL_SUCCESS;
}
/* set mu = mu0 * max(diag(J~^T J~)), with J~ = J D^{-1} */
for (i = 0; i < JTJ->size1; ++i)
{
double JTJi = gsl_matrix_get(JTJ, i, i);
double di = gsl_vector_get(diag, i);
double val = JTJi / (di * di);
max = GSL_MAX(max, val);
}
*mu = mu0 * max;
return GSL_SUCCESS;
}
static int
nielsen_accept(const double rho, double * mu, long * nu)
{
double b;
/* reset nu */
*nu = 2;
b = 2.0 * rho - 1.0;
b = 1.0 - b*b*b;
*mu *= GSL_MAX(LM_ONE_THIRD, b);
return GSL_SUCCESS;
}
static int
nielsen_reject(double * mu, long * nu)
{
*mu *= (double) *nu;
/* nu := 2*nu */
*nu <<= 1;
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6584845251,
"avg_line_length": 26.2710280374,
"ext": "c",
"hexsha": "215d081766501685d781799f2bf035cc4264fad3",
"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/multilarge_nlinear/nielsen.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/multilarge_nlinear/nielsen.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/multilarge_nlinear/nielsen.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": 805,
"size": 2811
} |
/*
* Copyright 2020 Makani Technologies LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SIM_PHYSICS_DELTA_COEFF_AERO_DATABASE_H_
#define SIM_PHYSICS_DELTA_COEFF_AERO_DATABASE_H_
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <stdint.h>
#include <string>
#include "common/c_math/linalg.h"
#include "common/c_math/vec3.h"
#include "common/macros.h"
#include "sim/sim_params.h"
#include "sim/sim_types.h"
#include "system/labels.h"
class DeltaCoeffAeroDatabase {
friend class AeroTest;
public:
explicit DeltaCoeffAeroDatabase(const std::string &filename);
~DeltaCoeffAeroDatabase();
// Returns the nominal force-moment coefficient after adjusting for
// delta coefficients.
void AdjustForceMomentCoeff(double alpha, const Vec &flaps,
ForceMoment *force_moment_coeff) const;
private:
// Returns true if the database passes basic sign checks.
bool IsValid() const;
bool applicable_flaps_[kNumFlaps];
double reynolds_number_;
gsl_vector *alphads_, *deltads_;
gsl_matrix *CX_[kNumFlaps];
gsl_matrix *CY_[kNumFlaps];
gsl_matrix *CZ_[kNumFlaps];
gsl_matrix *CL_[kNumFlaps];
gsl_matrix *CM_[kNumFlaps];
gsl_matrix *CN_[kNumFlaps];
DISALLOW_COPY_AND_ASSIGN(DeltaCoeffAeroDatabase);
};
#endif // SIM_PHYSICS_DELTA_COEFF_AERO_DATABASE_H_
| {
"alphanum_fraction": 0.7518878101,
"avg_line_length": 28.0909090909,
"ext": "h",
"hexsha": "68ad83eb45a13d57050b87182b49ad2630f46a00",
"lang": "C",
"max_forks_count": 107,
"max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z",
"max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "leozz37/makani",
"max_forks_repo_path": "sim/physics/delta_coeff_aero_database.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b",
"max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "leozz37/makani",
"max_issues_repo_path": "sim/physics/delta_coeff_aero_database.h",
"max_line_length": 75,
"max_stars_count": 1178,
"max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "leozz37/makani",
"max_stars_repo_path": "sim/physics/delta_coeff_aero_database.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z",
"num_tokens": 458,
"size": 1854
} |
//
// Author : github.com/luncliff (luncliff@gmail.com)
// License : CC BY 4.0
//
// Note
// Test framework adapter
//
#pragma once
#include <gsl/gsl>
void _require_(bool expr);
void _require_(bool expr, gsl::czstring<> file, size_t line);
void _println_(gsl::czstring<> message);
void _fail_now_(gsl::czstring<> message, //
gsl::czstring<> file = __FILE__, size_t line = __LINE__);
| {
"alphanum_fraction": 0.6569343066,
"avg_line_length": 22.8333333333,
"ext": "h",
"hexsha": "7fa3cbb660e56f7baa3f0ac7ac9fdab8d6b7de87",
"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": "cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "Farwaykorse/coroutine",
"max_forks_repo_path": "test/test.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "Farwaykorse/coroutine",
"max_issues_repo_path": "test/test.h",
"max_line_length": 73,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cfe7f0ca5ab4670e539a9f4d6c69d85ba4cb18f7",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "Farwaykorse/coroutine",
"max_stars_repo_path": "test/test.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 122,
"size": 411
} |
/* poly/zsolve_init.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_poly.h>
#include <gsl/gsl_errno.h>
gsl_poly_complex_workspace *
gsl_poly_complex_workspace_alloc (size_t n)
{
size_t nc ;
gsl_poly_complex_workspace * w ;
if (n == 0)
{
GSL_ERROR_VAL ("matrix size n must be positive integer", GSL_EDOM, 0);
}
w = (gsl_poly_complex_workspace *)
malloc (sizeof(gsl_poly_complex_workspace));
if (w == 0)
{
GSL_ERROR_VAL ("failed to allocate space for struct", GSL_ENOMEM, 0);
}
nc = n - 1;
w->nc = nc;
w->matrix = (double *) malloc (nc * nc * sizeof(double));
if (w->matrix == 0)
{
free (w) ; /* error in constructor, avoid memory leak */
GSL_ERROR_VAL ("failed to allocate space for workspace matrix",
GSL_ENOMEM, 0);
}
return w ;
}
void
gsl_poly_complex_workspace_free (gsl_poly_complex_workspace * w)
{
free(w->matrix) ;
free(w);
}
| {
"alphanum_fraction": 0.6724137931,
"avg_line_length": 25.6857142857,
"ext": "c",
"hexsha": "a93fba452e016309bf5ba58b770e96ec591cafb0",
"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/poly/zsolve_init.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/poly/zsolve_init.c",
"max_line_length": 76,
"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/poly/zsolve_init.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": 481,
"size": 1798
} |
#pragma once
#include <Manager.h>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <limits>
#include <vector>
#include "../types/def.h"
#include <gsl\gsl>
#include "SFML/Window.hpp"
#include <utility>
#include <../_entity/Entity.h>
#include <../_entity/EntityManager.h>
#include "../_component/components/TransformComponent.h"
#include "../_component/components/CollisionComponent.h"
class ChunkManager : public Manager<ChunkManager> {
public:
friend class CRSP<ChunkManager>;
using ChunkMap = std::unordered_map<Chunk, EntityIdSet, PairIntIntHash>;
using EntityMap = std::unordered_map<EntityId, ChunkSet>;
using PositionCache = std::unordered_map<EntityId, std::pair<sf::Vector2f, sf::Vector2f>>;
using ChunkLengthType = float;
using GroupedEntities = std::unordered_map<Chunk, std::set<Entity*>, PairIntIntHash>;
private:
ChunkManager();
~ChunkManager();
public:
void start_up() override;
void shut_down() override;
std::vector<Chunk> get_relevant_chunks() const;
ChunkSet get_chunks_of(EntityId id) const;
ChunkSet calculate_chunks(Entity* entity) const;
Chunk get_chunk_from_position(float x, float y) const;
bool share_chunks(EntityId a, EntityId b) const;
void update_entity_chunks();
void update_single_entity(Entity* entity);
void clear();
/*
There are not const because it might require to generate vectors for new chunks without entities
*/
void draw_debug_chunks();
void draw_debug_chunk_configuration();
const EntityIdSet& get_entities_of_chunk(Chunk chunk);
const std::set<Entity*>& get_colliding_entities_of_chunk(Chunk chunk);
/**
Returns a vector of vectors with the entities grouped by chunks, that is, in each vector
we have all the entities that are in a particular chunk, entities can be repeated in more
than one vector.
*/
template<typename... T>
GroupedEntities get_grouped_entities_with_components() {
auto general = GroupedEntities{};
for (auto & c : m_chunk_map) {
if (c.second.size() == 0) continue;
auto& entity_set = c.second;
auto entities_in_chunk = std::vector<Entity*>{};
for (auto& e : entity_set) {
auto entity = EntityManager::get().get_entity(e);
if (!entity->is_in_relevant_chunk()) continue;
auto checks = { entity->has_component<T>()... };
if (std::all_of(checks.begin(), checks.end(), [](bool i) {return i; })) {
entities_in_chunk.push_back(entity);
}
}
general[c.first] = (std::move(entities_in_chunk));
}
return general;
}
/*
Specific version of this function for the elements with a collision component
that returns an internal member that we calculate on our "update_entity_chunks" instead
of calculating it on request like we are doing in the function above.
*/
template<>
GroupedEntities get_grouped_entities_with_components<TransformComponent, CollisionComponent>() {
return m_collision_components_cache;
}
private:
/**
The length of the side of each square chunk
*/
ChunkLengthType m_chunk_size{ 16 };
/**
Number of chunks outside the visible screen that we still consider relevant
*/
unsigned int m_chunk_threshold{ 1 };
/**
This is used in case an entity enters a chunk exactly in the frame that we have to check
something in that new chunk, we register the entity as being in the chunks that it
really is plus "m_safe_threshold" more in each direction.
*/
unsigned int m_safe_threshold{ 1 };
ChunkMap m_chunk_map{};
EntityMap m_entity_map{};
PositionCache m_location_cache{};
Chunk m_min_relevant_chunk{};
Chunk m_max_relevant_chunk{};
GroupedEntities m_collision_components_cache{};
sf::Vector2f camera_previous_center{ std::numeric_limits<float>::infinity(),std::numeric_limits<float>::infinity() };
sf::Vector2f camera_previous_size{ std::numeric_limits<float>::infinity(),std::numeric_limits<float>::infinity() };
bool m_camera_changed{ true };
}; | {
"alphanum_fraction": 0.68309361,
"avg_line_length": 29.4513888889,
"ext": "h",
"hexsha": "1914165587b970072bb2d6f88f9740267072f517",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-05-14T14:57:31.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-07T12:53:44.000Z",
"max_forks_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "osor-io/NGene",
"max_forks_repo_path": "NGene/src/physics/ChunkManager.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655",
"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": "osor-io/NGene",
"max_issues_repo_path": "NGene/src/physics/ChunkManager.h",
"max_line_length": 121,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "c28887f233d3485b9e95fa3882a0333e4180c655",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "osor-io/NGene",
"max_stars_repo_path": "NGene/src/physics/ChunkManager.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-05T04:00:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-14T14:57:30.000Z",
"num_tokens": 935,
"size": 4241
} |
//IN method.
//Bilinear transformation (3D tensor of weights, 1D vector of biases)
//of Ni1 inputs from X1 and Ni2 inputs from X2 to No outputs in Y.
//This version uses CBLAS.
//Input X1 has Ni1 neurons, X2 has Ni2 neurons, and output Y has No neurons.
//If col-major: Y[o,l] = X1[:,l]' * W[:,:,o] * X2[:,l] + B[o]
//where:
//X1 has size Ni1 x L
//X2 has size Ni2 x L
//Y has size No x L
//W has size Ni1 x Ni2 x No
//B has size No x 1
//If row-major: Y[l,o] = X1[l,:] * W[o,:,:] * X2[l,:]' + B[o]
//X1 has size L x Ni1
//X2 has size L x Ni2
//Y has size L x No
//W has size No x Ni2 x Ni1
//B has size 1 x No
//This is equal to the outer product of X1 and X2 at each l (time point),
//and then take the weighted sum by each of the No matrices within W,
//producing No scalars, one for each output neuron in Y.
//I retain the for loop through L for compatibility with real-time streaming.
//This CBLAS version not working yet!!
#include <stdio.h>
#include <stdlib.h>
#include <cblas.h>
#ifdef __cplusplus
namespace codee {
extern "C" {
#endif
int bilinear_cblas_s (float *Y, const float *X1, const float *X2, const float *W, const float *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L);
int bilinear_cblas_d (double *Y, const double *X1, const double *X2, const double *W, const double *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L);
int bilinear_cblas_c (float *Y, const float *X1, const float *X2, const float *W, const float *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L);
int bilinear_cblas_z (double *Y, const double *X1, const double *X2, const double *W, const double *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L);
int bilinear_cblas_s (float *Y, const float *X1, const float *X2, const float *W, const float *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L)
{
const size_t N12 = Ni1*Ni2, Nw = N12*No;
float *outer_prod;
outer_prod = (float *)malloc(N12*sizeof(float));
if (!outer_prod) { fprintf(stderr,"error in bilinear_cblas_s: problem with malloc. "); perror("malloc"); return 1; }
for (size_t l=L; l>0u; --l, X1+=Ni1, X2+=Ni2, B-=No, W-=Nw)
{
//Re-zero outer_prod
for (size_t n=N12; n>0u; --n) { outer_prod[n] = 0.0f; }
//Outer product of X1, X2
cblas_sger(CblasRowMajor,(int)Ni1,(int)Ni2,1.0f,X1,1,X2,1,outer_prod,(int)Ni2);
//Weight by W for each output
for (size_t o=No; o>0u; --o, ++B, ++Y, W+=N12)
{
*Y = *B + cblas_sdot((int)N12,W,1,outer_prod,1);
//*Y = cblas_sdsdot((int)N12,*B,W,1,outer_prod,1);
}
}
free(outer_prod);
return 0;
}
int bilinear_cblas_d (double *Y, const double *X1, const double *X2, const double *W, const double *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L)
{
const size_t N12 = Ni1*Ni2, Nw = N12*No;
double *outer_prod;
outer_prod = (double *)malloc(N12*sizeof(double));
if (!outer_prod) { fprintf(stderr,"error in bilinear_cblas_d: problem with malloc. "); perror("malloc"); return 1; }
for (size_t l=L; l>0u; --l, X1+=Ni1, X2+=Ni2, B-=No, W-=Nw)
{
//Re-zero outer_prod
for (size_t n=N12; n>0u; --n) { outer_prod[n] = 0.0; }
//Outer product of X1, X2
cblas_dger(CblasRowMajor,(int)Ni1,(int)Ni2,1.0,X1,1,X2,1,outer_prod,(int)Ni2);
//Weight by W for each output
for (size_t o=No; o>0u; --o, ++B, ++Y, W+=N12)
{
*Y = *B + cblas_ddot((int)N12,W,1,outer_prod,1);
}
}
free(outer_prod);
return 0;
}
int bilinear_cblas_c (float *Y, const float *X1, const float *X2, const float *W, const float *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L)
{
const size_t N12 = 2u*Ni1*Ni2, Nw = N12*No;
const float oz[2] = {1.0f,0.0f};
float *outer_prod;
outer_prod = (float *)malloc(N12*sizeof(float));
if (!outer_prod) { fprintf(stderr,"error in bilinear_cblas_c: problem with malloc. "); perror("malloc"); return 1; }
for (size_t l=L; l>0u; --l, X1+=2u*Ni1, X2+=2u*Ni2, B-=2u*No, W-=Nw)
{
//Re-zero outer_prod
for (size_t n=N12; n>0u; --n) { outer_prod[n] = 0.0f; }
//Outer product of X1, X2
cblas_cgeru(CblasRowMajor,(int)Ni1,(int)Ni2,oz,X1,1,X2,1,outer_prod,(int)Ni2);
//Weight by W for each output
for (size_t o=No; o>0u; --o, W+=N12)
{
cblas_cdotu_sub((int)N12,W,1,outer_prod,1,Y);
*Y++ += *B++; *Y++ += *B++;
}
}
free(outer_prod);
return 0;
}
int bilinear_cblas_z (double *Y, const double *X1, const double *X2, const double *W, const double *B, const size_t Ni1, const size_t Ni2, const size_t No, const size_t L)
{
const size_t N12 = 2u*Ni1*Ni2, Nw = N12*No;
const double oz[2] = {1.0,0.0};
double *outer_prod;
outer_prod = (double *)malloc(N12*sizeof(double));
if (!outer_prod) { fprintf(stderr,"error in bilinear_cblas_z: problem with malloc. "); perror("malloc"); return 1; }
for (size_t l=L; l>0u; --l, X1+=2u*Ni1, X2+=2u*Ni2, B-=2u*No, W-=Nw)
{
//Re-zero outer_prod
for (size_t n=N12; n>0u; --n) { outer_prod[n] = 0.0; }
//Outer product of X1, X2
cblas_zgeru(CblasRowMajor,(int)Ni1,(int)Ni2,oz,X1,1,X2,1,outer_prod,(int)Ni2);
//Weight by W for each output
for (size_t o=No; o>0u; --o, W+=N12)
{
cblas_zdotu_sub((int)N12,W,1,outer_prod,1,Y);
*Y++ += *B++; *Y++ += *B++;
}
}
free(outer_prod);
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.6134365107,
"avg_line_length": 33.2514619883,
"ext": "c",
"hexsha": "a81c21c912722f74b34d20a72ab999e10d5a937d",
"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": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/nn",
"max_forks_repo_path": "c/bilinear.cblas.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/nn",
"max_issues_repo_path": "c/bilinear.cblas.c",
"max_line_length": 172,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c4b8317a38a72a16fd0bf905791b6c19e49c0aa7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/nn",
"max_stars_repo_path": "c/bilinear.cblas.c",
"max_stars_repo_stars_event_max_datetime": "2020-08-26T09:28:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-26T09:28:40.000Z",
"num_tokens": 2012,
"size": 5686
} |
#ifndef _BLAS_UTIL_H_
#define _BLAS_UTIL_H_
#ifdef __BLAS_LEGACY__
#include <math.h>
#include "utils/cblas.h"
//#include <lapacke.h> //! hasn't used
#define _D2_MALLOC_SCALAR(x) (SCALAR *) malloc( (x) *sizeof(SCALAR))
#define _D2_MALLOC_INT(x) (int *) malloc( (x) *sizeof(int))
#define _D2_MALLOC_SIZE_T(x) (size_t *) malloc( (x) *sizeof(size_t))
#define _D2_CALLOC_SCALAR(x) (SCALAR *) calloc( (x) , sizeof(SCALAR))
#define _D2_CALLOC_INT(x) (int *) calloc( (x) , sizeof(int))
#define _D2_CALLOC_SIZE_T(x) (size_t *) calloc( (x) , sizeof(size_t))
#define _D2_FREE(x) free(x)
#elif defined __APPLE__
#include <Accelerate/Accelerate.h>
#define _D2_MALLOC_SCALAR(x) (SCALAR *) malloc( (x) *sizeof(SCALAR))
#define _D2_MALLOC_INT(x) (int *) malloc( (x) *sizeof(int))
#define _D2_MALLOC_SIZE_T(x) (size_t *) malloc( (x) *sizeof(size_t))
#define _D2_CALLOC_SCALAR(x) (SCALAR *) calloc( (x) , sizeof(SCALAR))
#define _D2_CALLOC_INT(x) (int *) calloc( (x) , sizeof(int))
#define _D2_CALLOC_SIZE_T(x) (size_t *) calloc( (x) , sizeof(size_t))
#define _D2_FREE(x) free(x)
#elif defined __USE_MKL__
#include <mkl.h>
#define _D2_MALLOC_SCALAR(x) (SCALAR *) mkl_malloc( (x) *sizeof(SCALAR), 16)
#define _D2_MALLOC_INT(x) (int *) mkl_malloc( (x) *sizeof(int), 16)
#define _D2_MALLOC_SIZE_T(x) (size_t *) mkl_malloc( (x) *sizeof(size_t), 16)
#define _D2_CALLOC_SCALAR(x) (SCALAR *) mkl_calloc( (x) , sizeof(SCALAR), 16)
#define _D2_CALLOC_INT(x) (int *) mkl_calloc( (x) , sizeof(int), 16)
#define _D2_CALLOC_SIZE_T(x) (size_t *) mkl_calloc( (x) , sizeof(size_t), 16)
#define _D2_FREE(x) mkl_free(x)
#endif
#endif /* _BLAS_UTIL_H_ */
| {
"alphanum_fraction": 0.6488939308,
"avg_line_length": 43,
"ext": "h",
"hexsha": "8be083fb3818a73af31fd807df0dc6f8dbb45fbb",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-06-13T20:23:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-01-11T16:55:13.000Z",
"max_forks_repo_head_hexsha": "7290657e1f6f95e633653172500a2b54d13e02be",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "bobye/d2_kmeans",
"max_forks_repo_path": "include/utils/blas_util.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7290657e1f6f95e633653172500a2b54d13e02be",
"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": "bobye/d2_kmeans",
"max_issues_repo_path": "include/utils/blas_util.h",
"max_line_length": 84,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "7290657e1f6f95e633653172500a2b54d13e02be",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "bobye/d2_kmeans",
"max_stars_repo_path": "include/utils/blas_util.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-09T12:53:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-20T18:10:54.000Z",
"num_tokens": 583,
"size": 1763
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <gsl/gsl_rng.h>
#include <assert.h>
#include "core_allvars.h"
#include "core_proto.h"
void init_galaxy(int p, int halonr)
{
int j, step;
assert(halonr == Halo[halonr].FirstHaloInFOFgroup);
Gal[p].Type = 0;
Gal[p].GalaxyNr = GalaxyCounter;
GalaxyCounter++;
Gal[p].HaloNr = halonr;
Gal[p].MostBoundID = Halo[halonr].MostBoundID;
Gal[p].SnapNum = Halo[halonr].SnapNum - 1;
Gal[p].mergeType = 0;
Gal[p].mergeIntoID = -1;
Gal[p].mergeIntoSnapNum = -1;
Gal[p].dT = -1.0;
for(j = 0; j < 3; j++)
{
Gal[p].Pos[j] = Halo[halonr].Pos[j];
Gal[p].Vel[j] = Halo[halonr].Vel[j];
}
Gal[p].Len = Halo[halonr].Len;
Gal[p].Vmax = Halo[halonr].Vmax;
Gal[p].Vvir = get_virial_velocity(halonr);
Gal[p].Mvir = get_virial_mass(halonr);
Gal[p].Rvir = get_virial_radius(halonr);
Gal[p].deltaMvir = 0.0;
Gal[p].ColdGas = 0.0;
Gal[p].StellarMass = 0.0;
Gal[p].BulgeMass = 0.0;
Gal[p].HotGas = 0.0;
Gal[p].EjectedMass = 0.0;
Gal[p].BlackHoleMass = 0.0;
Gal[p].ICS = 0.0;
Gal[p].MetalsColdGas = 0.0;
Gal[p].MetalsStellarMass = 0.0;
Gal[p].MetalsBulgeMass = 0.0;
Gal[p].MetalsHotGas = 0.0;
Gal[p].MetalsEjectedMass = 0.0;
Gal[p].MetalsICS = 0.0;
for(step = 0; step < STEPS; step++)
{
Gal[p].SfrDisk[step] = 0.0;
Gal[p].SfrBulge[step] = 0.0;
Gal[p].SfrDiskColdGas[step] = 0.0;
Gal[p].SfrDiskColdGasMetals[step] = 0.0;
Gal[p].SfrBulgeColdGas[step] = 0.0;
Gal[p].SfrBulgeColdGasMetals[step] = 0.0;
}
Gal[p].DiskScaleRadius = get_disk_radius(halonr, p);
Gal[p].MergTime = 999.9;
Gal[p].Cooling = 0.0;
Gal[p].Heating = 0.0;
Gal[p].r_heat = 0.0;
Gal[p].QuasarModeBHaccretionMass = 0.0;
Gal[p].TimeSinceMajorMerger = -1.0;
Gal[p].TimeSinceMinorMerger = -1.0;
Gal[p].OutflowRate = 0.0;
Gal[p].TotalSatelliteBaryons = 0.0;
// infall properties
Gal[p].infallMvir = -1.0;
Gal[p].infallVvir = -1.0;
Gal[p].infallVmax = -1.0;
//Raouf New things add to code
Gal[p].Qjet = 0.0;
Gal[p].Rcocoon = 0.0;
Gal[p].Rshocked = 0.0;
Gal[p].t_AGN_returne = 0.0;
Gal[p].t_AGN_on = 0.0;
Gal[p].Tshocked = 0.0;
Gal[p].Mshocked = 0.0;
for(j = 0; j < 7; j++)
{
Gal[p].RadioLuminosity[j] = 0.0;
}
for(j = 0; j < 600; j++)
{
Gal[p].RadioLuminosity_lifetime[j] = -999.0;
}
for(j = 0; j < 600; j++)
{
Gal[p].Rshocked_lifetime[j] = -999.0;
}
Gal[p].RadioAGNaccretionRate = 0.0;
Gal[p].rho_zero_Makino = 0.0;
Gal[p].rho_zero_Capelo = 0.0;
Gal[p].rho_zero_iso = 0.0;
Gal[p].b_gas = 0.0;
Gal[p].Rs = 0.0;
Gal[p].concentration = 0.0;
Gal[p].Temp_Gas = 0.0;
Gal[p].Lx_bol = 0.0;
Gal[p].R_index = 0.0;
Gal[p].Q_index = 0.0;
Gal[p].R_cool = 0.0;
Gal[p].fcool = 0.0;
Gal[p].t_static = 0.0;
Gal[p].t_AGN_off = 0.0;
Gal[p].time_to_next_on = 0.0;
Gal[p].delta = 0.0;
Gal[p].t_cool_Makino = 0.0;
}
double get_disk_radius(int halonr, int p)
{
double SpinMagnitude, SpinParameter;
if(Gal[p].Vvir > 0.0 && Gal[p].Rvir > 0.0)
{
// See Mo, Shude & White (1998) eq12, and using a Bullock style lambda.
SpinMagnitude = sqrt(Halo[halonr].Spin[0] * Halo[halonr].Spin[0] +
Halo[halonr].Spin[1] * Halo[halonr].Spin[1] + Halo[halonr].Spin[2] * Halo[halonr].Spin[2]);
// trim the extreme tail of the spin distribution for more a realistic r_s
if(SpinMagnitude > 1.5)
SpinMagnitude = 1.5;
SpinParameter = SpinMagnitude / (1.414 * Gal[p].Vvir * Gal[p].Rvir);
return (SpinParameter / 1.414) * Gal[p].Rvir;
}
else
return 0.1 * Gal[p].Rvir;
}
double get_metallicity(double gas, double metals)
{
double metallicity;
if(gas > 0.0 && metals > 0.0)
{
metallicity = metals / gas;
if(metallicity < 1.0)
return metallicity;
else
return 1.0;
}
else
return 0.0;
}
double dmax(double x, double y)
{
if(x > y)
return x;
else
return y;
}
double get_virial_mass(int halonr)
{
if(halonr == Halo[halonr].FirstHaloInFOFgroup && Halo[halonr].Mvir >= 0.0)
return Halo[halonr].Mvir; /* take spherical overdensity mass estimate */
else
return Halo[halonr].Len * PartMass;
}
double get_virial_velocity(int halonr)
{
double Rvir;
Rvir = get_virial_radius(halonr);
if(Rvir > 0.0)
return sqrt(G * get_virial_mass(halonr) / Rvir);
else
return 0.0;
}
double get_virial_radius(int halonr)
{
// return Halo[halonr].Rvir; // Used for Bolshoi
double zplus1, hubble_of_z_sq, rhocrit, fac;
zplus1 = 1 + ZZ[Halo[halonr].SnapNum];
hubble_of_z_sq =
Hubble * Hubble *(Omega * zplus1 * zplus1 * zplus1 + (1 - Omega - OmegaLambda) * zplus1 * zplus1 +
OmegaLambda);
rhocrit = 3 * hubble_of_z_sq / (8 * M_PI * G);
fac = 1 / (200 * 4 * M_PI / 3.0 * rhocrit);
return cbrt(get_virial_mass(halonr) * fac);
}
| {
"alphanum_fraction": 0.6151645207,
"avg_line_length": 21.5550660793,
"ext": "c",
"hexsha": "838a987537b911e683a5877c4d1a48e55c8a1c64",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-02-10T10:43:27.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-10T10:43:27.000Z",
"max_forks_repo_head_hexsha": "0a45aeb42c0a62290e97783c0c8ceb32446d1b0e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mojtabaraouf/sage",
"max_forks_repo_path": "code/model_misc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0a45aeb42c0a62290e97783c0c8ceb32446d1b0e",
"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": "mojtabaraouf/sage",
"max_issues_repo_path": "code/model_misc.c",
"max_line_length": 102,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "0a45aeb42c0a62290e97783c0c8ceb32446d1b0e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mojtabaraouf/sage",
"max_stars_repo_path": "code/model_misc.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-21T12:57:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-01-25T06:16:19.000Z",
"num_tokens": 1998,
"size": 4893
} |
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <gsl/gsl_rng.h>
#include "allvars.h"
#include "proto.h"
#ifdef COSMIC_RAYS
#include "cosmic_rays.h"
#endif
#ifdef CS_MODEL
#include "cs_metals.h"
#endif
/*! \file begrun.c
* \brief initial set-up of a simulation run
*
* This file contains various functions to initialize a simulation run. In
* particular, the parameterfile is read in and parsed, the initial
* conditions or restart files are read, and global variables are initialized
* to their proper values.
*/
/*! This function performs the initial set-up of the simulation. First, the
* parameterfile is set, then routines for setting units, reading
* ICs/restart-files are called, auxialiary memory is allocated, etc.
*/
void begrun(void)
{
struct global_data_all_processes all;
if(ThisTask == 0)
{
/* printf("\nThis is P-Gadget, version `%s', svn-revision `%s'.\n", GADGETVERSION, svn_version()); */
printf("\nThis is P-Gadget, version %s.\n", GADGETVERSION);
printf("\nRunning on %d processors.\n", NTask);
printf("\nCode was compiled with settings:\n %s\n\n", COMPILETIMESETTINGS);
}
#if defined(X86FIX) && defined(SOFTDOUBLEDOUBLE)
x86_fix(); /* disable 80bit treatment of internal FPU registers in favour of proper IEEE 64bit double precision arithmetic */
#endif
#ifdef PEDANTIC_MEMORY_HANDLER
mymalloc_init();
#endif
read_parameter_file(ParameterFile); /* ... read in parameters for this run */
#ifdef DEBUG
write_pid_file();
enable_core_dumps_and_fpu_exceptions();
#endif
#ifdef DARKENERGY
#ifdef TIMEDEPDE
fwa_init();
#endif
#endif
set_units();
#ifdef COOLING
All.Time = All.TimeBegin;
InitCool();
#endif
#ifdef CHEMISTRY
InitChem();
#endif
#if defined(SFR)
init_clouds();
#endif
#ifdef PERIODIC
ewald_init();
#endif
#ifdef PERIODIC
boxSize = All.BoxSize;
boxHalf = 0.5 * All.BoxSize;
#ifdef LONG_X
boxHalf_X = boxHalf * LONG_X;
boxSize_X = boxSize * LONG_X;
#endif
#ifdef LONG_Y
boxHalf_Y = boxHalf * LONG_Y;
boxSize_Y = boxSize * LONG_Y;
#endif
#ifdef LONG_Z
boxHalf_Z = boxHalf * LONG_Z;
boxSize_Z = boxSize * LONG_Z;
#endif
#endif
#ifdef TIME_DEP_ART_VISC
All.ViscSource = All.ViscSource0 / log((GAMMA + 1) / (GAMMA - 1));
All.DecayTime = 1 / All.DecayLength * sqrt((GAMMA - 1) / 2 * GAMMA);
#endif
random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);
gsl_rng_set(random_generator, 42); /* start-up seed */
#ifdef PMGRID
if(RestartFlag != 3 && RestartFlag != 4)
long_range_init();
#endif
#ifdef SUBFIND
GrNr = -1;
#endif
#ifdef EOS_DEGENERATE
eos_init();
#endif
All.TimeLastRestartFile = CPUThisRun;
if(RestartFlag == 0 || RestartFlag == 2 || RestartFlag == 3 || RestartFlag == 4)
{
set_random_numbers();
init(); /* ... read in initial model */
}
else
{
all = All; /* save global variables. (will be read from restart file) */
restart(RestartFlag); /* ... read restart file. Note: This also resets
all variables in the struct `All'.
However, during the run, some variables in the parameter
file are allowed to be changed, if desired. These need to
copied in the way below.
Note: All.PartAllocFactor is treated in restart() separately.
*/
All.MinSizeTimestep = all.MinSizeTimestep;
All.MaxSizeTimestep = all.MaxSizeTimestep;
All.BufferSize = all.BufferSize;
All.TimeLimitCPU = all.TimeLimitCPU;
All.ResubmitOn = all.ResubmitOn;
All.TimeBetSnapshot = all.TimeBetSnapshot;
All.TimeBetStatistics = all.TimeBetStatistics;
All.CpuTimeBetRestartFile = all.CpuTimeBetRestartFile;
All.ErrTolIntAccuracy = all.ErrTolIntAccuracy;
All.MaxRMSDisplacementFac = all.MaxRMSDisplacementFac;
All.ErrTolForceAcc = all.ErrTolForceAcc;
All.TypeOfTimestepCriterion = all.TypeOfTimestepCriterion;
All.TypeOfOpeningCriterion = all.TypeOfOpeningCriterion;
All.NumFilesWrittenInParallel = all.NumFilesWrittenInParallel;
All.TreeDomainUpdateFrequency = all.TreeDomainUpdateFrequency;
All.OutputListOn = all.OutputListOn;
All.CourantFac = all.CourantFac;
All.OutputListLength = all.OutputListLength;
memcpy(All.OutputListTimes, all.OutputListTimes, sizeof(double) * All.OutputListLength);
memcpy(All.OutputListFlag, all.OutputListFlag, sizeof(char) * All.OutputListLength);
#ifdef TIME_DEP_ART_VISC
All.ViscSource = all.ViscSource;
All.ViscSource0 = all.ViscSource0;
All.DecayTime = all.DecayTime;
All.DecayLength = all.DecayLength;
All.AlphaMin = all.AlphaMin;
#endif
#ifdef MAGNETIC_DISSIPATION
All.ArtMagDispConst = all.ArtMagDispConst;
#ifdef TIME_DEP_MAGN_DISP
All.ArtMagDispMin = all.ArtMagDispMin;
All.ArtMagDispSource = all.ArtMagDispSource;
All.ArtMagDispTime = all.ArtMagDispTime;
#endif
#endif
#ifdef DIVBCLEANING_DEDNER
All.DivBcleanParabolicSigma = all.DivBcleanParabolicSigma;
All.DivBcleanHyperbolicSigma = all.DivBcleanHyperbolicSigma;
#endif
#ifdef DARKENERGY
All.DarkEnergyParam = all.DarkEnergyParam;
#endif
strcpy(All.ResubmitCommand, all.ResubmitCommand);
strcpy(All.OutputListFilename, all.OutputListFilename);
strcpy(All.OutputDir, all.OutputDir);
strcpy(All.RestartFile, all.RestartFile);
strcpy(All.EnergyFile, all.EnergyFile);
strcpy(All.InfoFile, all.InfoFile);
strcpy(All.CpuFile, all.CpuFile);
strcpy(All.TimingsFile, all.TimingsFile);
strcpy(All.SnapshotFileBase, all.SnapshotFileBase);
#ifdef EOS_DEGENERATE
strcpy(All.EosTable, all.EosTable);
#endif
if(All.TimeMax != all.TimeMax)
readjust_timebase(All.TimeMax, all.TimeMax);
#ifdef NO_TREEDATA_IN_RESTART
/* if this is not activated, the tree was stored in the restart-files,
which also allocated the storage for it already */
/* ensures that domain reconstruction will be done and new tree will be constructed */
All.NumForcesSinceLastDomainDecomp = (long long) (1 + All.TotNumPart * All.TreeDomainUpdateFrequency);
#endif
}
open_outputfiles();
#ifdef PMGRID
long_range_init_regionsize();
#endif
reconstruct_timebins();
#ifdef COSMIC_RAYS
int CRpop;
for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)
CR_initialize_beta_tabs(All.CR_Alpha[CRpop], CRpop);
CR_Tab_Initialize();
#ifdef COSMIC_RAY_TEST
CR_test_routine();
#endif
#endif
#ifdef TWODIMS
int i;
for(i = 0; i < NumPart; i++)
{
P[i].Pos[2] = 0;
P[i].Vel[2] = 0;
}
#endif
if(All.ComovingIntegrationOn)
init_drift_table();
if(RestartFlag == 2)
All.Ti_nextoutput = find_next_outputtime(All.Ti_Current + 100);
else
All.Ti_nextoutput = find_next_outputtime(All.Ti_Current);
All.TimeLastRestartFile = CPUThisRun;
}
/*! Computes conversion factors between internal code units and the
* cgs-system.
*/
void set_units(void)
{
double meanweight;
#ifdef CONDUCTION
#ifndef CONDUCTION_CONSTANT
double coulomb_log;
#endif
#endif
#ifdef STATICNFW
double Mtot;
#endif
All.UnitTime_in_s = All.UnitLength_in_cm / All.UnitVelocity_in_cm_per_s;
All.UnitTime_in_Megayears = All.UnitTime_in_s / SEC_PER_MEGAYEAR;
if(All.GravityConstantInternal == 0)
All.G = GRAVITY / pow(All.UnitLength_in_cm, 3) * All.UnitMass_in_g * pow(All.UnitTime_in_s, 2);
else
All.G = All.GravityConstantInternal;
#ifdef TIMEDEPGRAV
All.Gini = All.G;
All.G = All.Gini * dGfak(All.TimeBegin);
#endif
All.UnitDensity_in_cgs = All.UnitMass_in_g / pow(All.UnitLength_in_cm, 3);
All.UnitPressure_in_cgs = All.UnitMass_in_g / All.UnitLength_in_cm / pow(All.UnitTime_in_s, 2);
All.UnitCoolingRate_in_cgs = All.UnitPressure_in_cgs / All.UnitTime_in_s;
All.UnitEnergy_in_cgs = All.UnitMass_in_g * pow(All.UnitLength_in_cm, 2) / pow(All.UnitTime_in_s, 2);
#ifdef ANNIHILATION_RADIATION
/* 5.609589206e23 is the factor to convert from g to GeV/c^2, the rest comes from All.UnitDensity_in_cgs */
All.UnitDensity_in_Gev_per_cm3 = 5.609589206e23 / pow(All.UnitLength_in_cm, 3) * All.UnitMass_in_g;
#endif
/* convert some physical input parameters to internal units */
All.Hubble = HUBBLE * All.UnitTime_in_s;
if(ThisTask == 0)
{
printf("\nHubble (internal units) = %g\n", All.Hubble);
printf("G (internal units) = %g\n", All.G);
printf("UnitMass_in_g = %g \n", All.UnitMass_in_g);
printf("UnitTime_in_s = %g \n", All.UnitTime_in_s);
printf("UnitVelocity_in_cm_per_s = %g \n", All.UnitVelocity_in_cm_per_s);
printf("UnitDensity_in_cgs = %g \n", All.UnitDensity_in_cgs);
printf("UnitEnergy_in_cgs = %g \n", All.UnitEnergy_in_cgs);
#ifdef ANNIHILATION_RADIATION
printf("Annihilation radiation units:\n");
printf("UnitDensity_in_Gev_per_cm3 = %g\n",All.UnitDensity_in_Gev_per_cm3);
#endif
printf("\n");
}
meanweight = 4.0 / (1 + 3 * HYDROGEN_MASSFRAC); /* note: assuming NEUTRAL GAS */
All.MinEgySpec = 1 / meanweight * (1.0 / GAMMA_MINUS1) * (BOLTZMANN / PROTONMASS) * All.MinGasTemp;
All.MinEgySpec *= All.UnitMass_in_g / All.UnitEnergy_in_cgs;
#if defined(SFR)
set_units_sfr();
#endif
#define cm (All.HubbleParam/All.UnitLength_in_cm)
#define g (All.HubbleParam/All.UnitMass_in_g)
#define s (All.HubbleParam/All.UnitTime_in_s)
#define erg (g*cm*cm/(s*s))
#define keV (1.602e-9*erg)
#define deg 1.0
#define m_p (PROTONMASS * g)
#define k_B (BOLTZMANN * erg / deg)
#ifdef NAVIERSTOKES
/* Braginskii-Spitzer shear viscosity parametrization */
/* mu = 0.406 * m_p^0.5 * (k_b* T)^(5/2) / e^4 / logLambda [g/cm/s] */
/* eta = frac * mu */
meanweight = 4.0 / (8 - 5 * (1 - HYDROGEN_MASSFRAC)); /* assuming full ionization */
#ifdef NAVIERSTOKES_CONSTANT
All.NavierStokes_ShearViscosity = All.FractionSpitzerViscosity * 0.406 * pow(PROTONMASS, 0.5) * pow(BOLTZMANN * All.ShearViscosityTemperature, 5. / 2.) / pow(ELECTRONCHARGE, 4) / LOG_LAMBDA; /*in cgs units */
if(ThisTask == 0)
printf("Constant shear viscosity in cgs units: eta = %g\n", All.NavierStokes_ShearViscosity);
All.NavierStokes_ShearViscosity *= All.UnitTime_in_s * All.UnitLength_in_cm / All.UnitMass_in_g / All.HubbleParam; /* in internal code units */
if(ThisTask == 0)
printf("Constant shear viscosity in internal code units: eta = %g\n", All.NavierStokes_ShearViscosity);
#else
All.NavierStokes_ShearViscosity = All.FractionSpitzerViscosity * 0.406 * pow(PROTONMASS, 0.5) * pow((meanweight * PROTONMASS * GAMMA_MINUS1), 5. / 2.) / pow(ELECTRONCHARGE, 4) / LOG_LAMBDA; /*in cgs units */
/*T = mu*m_p*(gamma-1)/k_b * E * UnitEnergy/UnitMass */
All.NavierStokes_ShearViscosity *= pow((All.UnitEnergy_in_cgs / All.UnitMass_in_g), 5. / 2.); /* now energy can be multiplied later in the internal code units */
All.NavierStokes_ShearViscosity *= All.UnitTime_in_s * All.UnitLength_in_cm / All.UnitMass_in_g / All.HubbleParam; /* in internal code units */
if(ThisTask == 0)
printf("Variable shear viscosity in internal code units: eta = %g\n", All.NavierStokes_ShearViscosity);
#endif
#ifdef NAVIERSTOKES_BULK
if(ThisTask == 0)
printf("Costant bulk viscosity in internal code units: zeta = %g\n", All.NavierStokes_BulkViscosity);
#endif
#ifdef VISCOSITY_SATURATION
/* calculate ion mean free path assuming complete ionization:
ion mean free path for hydrogen is similar to that of helium,
thus we calculate only for hydrogen */
/* l_i = 3^(3/2)*(k*T)^2 / (4*\pi^(1/2)*ni*(Z*e)^4*lnL) */
All.IonMeanFreePath = pow(3.0, 1.5) / (4.0 * sqrt(M_PI) * pow(ELECTRONCHARGE, 4) * LOG_LAMBDA);
All.IonMeanFreePath *= pow(meanweight * PROTONMASS * GAMMA_MINUS1, 2) * pow((All.UnitEnergy_in_cgs / All.UnitMass_in_g), 2); /*kT -> u */
All.IonMeanFreePath /= (HYDROGEN_MASSFRAC / PROTONMASS) *
(All.UnitDensity_in_cgs * All.HubbleParam * All.HubbleParam);
/* n_H = rho * Hfr / mp *//* now is cgs units *///changed / to * in front of the unitdensity
All.IonMeanFreePath *= All.HubbleParam / All.UnitLength_in_cm;
/* in internal code units */
#endif
#endif
#ifdef CONDUCTION
#ifndef CONDUCTION_CONSTANT
meanweight = m_p * 4.0 / (8 - 5 * (1 - HYDROGEN_MASSFRAC));
/* assuming full ionization */
coulomb_log = 37.8;
/* accordin1g to Sarazin's book */
All.ConductionCoeff *=
(1.84e-5 / coulomb_log * pow(meanweight / k_B * GAMMA_MINUS1, 2.5) * erg / (s * deg * cm));
/* Kappa_Spitzer definition taken from Zakamska & Narayan 2003
* ( ApJ 582:162-169, Eq. (5) )
*/
/* Note: Because we replace \nabla(T) in the conduction equation with
* \nable(u), our conduction coefficient is not the usual kappa, but
* rather kappa*(gamma-1)*mu/kB. We therefore need to multiply with
* another factor of (meanweight / k_B * GAMMA_MINUS1).
*/
All.ConductionCoeff *= meanweight / k_B * GAMMA_MINUS1;
/* The conversion of ConductionCoeff between internal units and cgs
* units involves one factor of 'h'. We take care of this here.
*/
All.ConductionCoeff /= All.HubbleParam;
#ifdef CONDUCTION_SATURATION
All.ElectronFreePathFactor = 8 * pow(3.0, 1.5) * pow(GAMMA_MINUS1, 2) / pow(3 + 5 * HYDROGEN_MASSFRAC, 2)
/ (1 + HYDROGEN_MASSFRAC) / sqrt(M_PI) / coulomb_log * pow(PROTONMASS, 3) / pow(ELECTRONCHARGE, 4)
/ (All.UnitDensity_in_cgs * All.HubbleParam * All.HubbleParam)
* pow(All.UnitPressure_in_cgs / All.UnitDensity_in_cgs, 2);
/* If the above value is multiplied with u^2/rho in code units (with rho being the physical density), then
* one gets the electrong mean free path in centimeter. Since we want to compare this with another length
* scale in code units, we now add an additional factor to convert back to code units.
*/
All.ElectronFreePathFactor *= All.HubbleParam / All.UnitLength_in_cm;
#endif
#endif /* CONDUCTION_CONSTANT */
#endif /* CONDUCTION */
#if defined(CR_DIFFUSION)
if(All.CR_DiffusionDensZero == 0.0)
{
/* Set reference density for CR Diffusion to rhocrit at z=0 */
All.CR_DiffusionDensZero = 3.0 * All.Hubble * All.Hubble / (8 * M_PI * All.G);
}
if(All.CR_DiffusionEntropyZero == 0.0)
{
All.CR_DiffusionEntropyZero = 1.0e4;
}
/* Set reference entropic function to correspond to
Reference Temperature @ ReferenceDensity */
if(ThisTask == 0)
{
printf("CR Diffusion: T0 = %g\n", All.CR_DiffusionEntropyZero);
}
/* convert Temperature value in Kelvin to thermal energy per unit mass
in internal units, and then to entropy */
All.CR_DiffusionEntropyZero *=
BOLTZMANN / (4.0 * PROTONMASS / (3.0 * HYDROGEN_MASSFRAC + 1.0)) *
All.UnitMass_in_g / All.UnitEnergy_in_cgs / pow(All.CR_DiffusionDensZero, GAMMA_MINUS1);
/* Change the density scaling, so that the temp scaling is mapped
onto an entropy scaling that is numerically less expensive */
All.CR_DiffusionDensScaling += GAMMA_MINUS1 * All.CR_DiffusionEntropyScaling;
if(ThisTask == 0)
{
printf("CR Diffusion: Rho0 = %g -- A0 = %g\n", All.CR_DiffusionDensZero, All.CR_DiffusionEntropyZero);
}
#endif /* CR_DIFFUSION */
#ifdef STATICNFW
R200 = pow(NFW_M200 * All.G / (100 * All.Hubble * All.Hubble), 1.0 / 3);
Rs = R200 / NFW_C;
Dc = 200.0 / 3 * NFW_C * NFW_C * NFW_C / (log(1 + NFW_C) - NFW_C / (1 + NFW_C));
RhoCrit = 3 * All.Hubble * All.Hubble / (8 * M_PI * All.G);
V200 = 10 * All.Hubble * R200;
if(ThisTask == 0)
printf("V200= %g\n", V200);
fac = 1.0;
Mtot = enclosed_mass(R200);
if(ThisTask == 0)
printf("M200= %g\n", Mtot);
/* fac = M200 / Mtot */
fac = V200 * V200 * V200 / (10 * All.G * All.Hubble) / Mtot;
Mtot = enclosed_mass(R200);
if(ThisTask == 0)
printf("M200= %g\n", Mtot);
#endif
}
#ifdef STATICNFW
/*! auxiliary function for static NFW potential
*/
double enclosed_mass(double R)
{
/* Eps is in units of Rs !!!! */
/* use unsoftened NFW if NFW_Eps=0 */
if(NFW_Eps > 0.0)
if(R > Rs * NFW_C)
R = Rs * NFW_C;
if(NFW_Eps > 0.0)
{
return fac * 4 * M_PI * RhoCrit * Dc *
(-
(Rs * Rs * Rs *
(1 - NFW_Eps + log(Rs) - 2 * NFW_Eps * log(Rs) +
NFW_Eps * NFW_Eps * log(NFW_Eps * Rs))) / ((NFW_Eps - 1) * (NFW_Eps - 1)) + (Rs * Rs * Rs * (Rs -
NFW_Eps
* Rs -
(2 *
NFW_Eps
-
1) *
(R +
Rs) *
log(R
+
Rs)
+
NFW_Eps
*
NFW_Eps
* (R +
Rs)
*
log(R
+
NFW_Eps
*
Rs)))
/ ((NFW_Eps - 1) * (NFW_Eps - 1) * (R + Rs)));
}
else /* analytic NFW */
{
return fac * 4 * M_PI * RhoCrit * Dc *
(-(Rs * Rs * Rs * (1 + log(Rs))) + Rs * Rs * Rs * (Rs + (R + Rs) * log(R + Rs)) / (R + Rs));
}
}
#endif
/*! This function opens various log-files that report on the status and
* performance of the simulstion. On restart from restart-files
* (start-option 1), the code will append to these files.
*/
void open_outputfiles(void)
{
char mode[2], buf[200];
if(RestartFlag == 0)
strcpy(mode, "w");
else
strcpy(mode, "a");
#ifdef BLACK_HOLES
/* Note: This is done by everyone */
sprintf(buf, "%sblackhole_details_%d.txt", All.OutputDir, ThisTask);
if(!(FdBlackHolesDetails = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#ifdef CS_FEEDBACK
sprintf(buf, "%spromotion_%d.txt", All.OutputDir, ThisTask);
if(!(FdPromotion = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#ifdef DISTORTIONTENSORPS
/* create caustic log file */
sprintf(buf, "%scaustics_%d.txt", All.OutputDir, ThisTask);
if(!(FdCaustics = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
if(ThisTask != 0) /* only the root processors writes to the log files */
return;
sprintf(buf, "%s%s", All.OutputDir, All.CpuFile);
if(!(FdCPU = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
sprintf(buf, "%s%s", All.OutputDir, All.InfoFile);
if(!(FdInfo = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
sprintf(buf, "%s%s", All.OutputDir, All.EnergyFile);
if(!(FdEnergy = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
sprintf(buf, "%s%s", All.OutputDir, All.TimingsFile);
if(!(FdTimings = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
sprintf(buf, "%s%s", All.OutputDir, "balance.txt");
if(!(FdBalance = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
fprintf(FdBalance, "\n");
fprintf(FdBalance, "Treewalk1 = '%c' / '%c'\n", CPU_Symbol[CPU_TREEWALK1],
CPU_SymbolImbalance[CPU_TREEWALK1]);
fprintf(FdBalance, "Treewalk2 = '%c' / '%c'\n", CPU_Symbol[CPU_TREEWALK2],
CPU_SymbolImbalance[CPU_TREEWALK2]);
fprintf(FdBalance, "Treewait1 = '%c' / '%c'\n", CPU_Symbol[CPU_TREEWAIT1],
CPU_SymbolImbalance[CPU_TREEWAIT1]);
fprintf(FdBalance, "Treewait2 = '%c' / '%c'\n", CPU_Symbol[CPU_TREEWAIT2],
CPU_SymbolImbalance[CPU_TREEWAIT2]);
fprintf(FdBalance, "Treesend = '%c' / '%c'\n", CPU_Symbol[CPU_TREESEND],
CPU_SymbolImbalance[CPU_TREESEND]);
fprintf(FdBalance, "Treerecv = '%c' / '%c'\n", CPU_Symbol[CPU_TREERECV],
CPU_SymbolImbalance[CPU_TREERECV]);
fprintf(FdBalance, "Treebuild = '%c' / '%c'\n", CPU_Symbol[CPU_TREEBUILD],
CPU_SymbolImbalance[CPU_TREEBUILD]);
fprintf(FdBalance, "Treeupdate = '%c' / '%c'\n", CPU_Symbol[CPU_TREEUPDATE],
CPU_SymbolImbalance[CPU_TREEUPDATE]);
fprintf(FdBalance, "Treehmaxupdate = '%c' / '%c'\n", CPU_Symbol[CPU_TREEHMAXUPDATE],
CPU_SymbolImbalance[CPU_TREEHMAXUPDATE]);
fprintf(FdBalance, "Treemisc = '%c' / '%c'\n", CPU_Symbol[CPU_TREEMISC],
CPU_SymbolImbalance[CPU_TREEMISC]);
fprintf(FdBalance, "Domain decomp = '%c' / '%c'\n", CPU_Symbol[CPU_DOMAIN],
CPU_SymbolImbalance[CPU_DOMAIN]);
fprintf(FdBalance, "Density compute= '%c' / '%c'\n", CPU_Symbol[CPU_DENSCOMPUTE],
CPU_SymbolImbalance[CPU_DENSCOMPUTE]);
fprintf(FdBalance, "Density imbal = '%c' / '%c'\n", CPU_Symbol[CPU_DENSWAIT],
CPU_SymbolImbalance[CPU_DENSWAIT]);
fprintf(FdBalance, "Density commu = '%c' / '%c'\n", CPU_Symbol[CPU_DENSCOMM],
CPU_SymbolImbalance[CPU_DENSCOMM]);
fprintf(FdBalance, "Density misc = '%c' / '%c'\n", CPU_Symbol[CPU_DENSMISC],
CPU_SymbolImbalance[CPU_DENSMISC]);
fprintf(FdBalance, "Hydro compute = '%c' / '%c'\n", CPU_Symbol[CPU_HYDCOMPUTE],
CPU_SymbolImbalance[CPU_HYDCOMPUTE]);
fprintf(FdBalance, "Hydro imbalance= '%c' / '%c'\n", CPU_Symbol[CPU_HYDWAIT],
CPU_SymbolImbalance[CPU_HYDWAIT]);
fprintf(FdBalance, "Hydro comm = '%c' / '%c'\n", CPU_Symbol[CPU_HYDCOMM],
CPU_SymbolImbalance[CPU_HYDCOMM]);
fprintf(FdBalance, "Hydro misc = '%c' / '%c'\n", CPU_Symbol[CPU_HYDMISC],
CPU_SymbolImbalance[CPU_HYDMISC]);
fprintf(FdBalance, "Drifts = '%c' / '%c'\n", CPU_Symbol[CPU_DRIFT], CPU_SymbolImbalance[CPU_DRIFT]);
fprintf(FdBalance, "Blackhole = '%c' / '%c'\n", CPU_Symbol[CPU_BLACKHOLES],
CPU_SymbolImbalance[CPU_BLACKHOLES]);
fprintf(FdBalance, "Kicks = '%c' / '%c'\n", CPU_Symbol[CPU_TIMELINE],
CPU_SymbolImbalance[CPU_TIMELINE]);
fprintf(FdBalance, "Potential = '%c' / '%c'\n", CPU_Symbol[CPU_POTENTIAL],
CPU_SymbolImbalance[CPU_POTENTIAL]);
fprintf(FdBalance, "PM = '%c' / '%c'\n", CPU_Symbol[CPU_MESH], CPU_SymbolImbalance[CPU_MESH]);
fprintf(FdBalance, "Peano-Hilbert = '%c' / '%c'\n", CPU_Symbol[CPU_PEANO], CPU_SymbolImbalance[CPU_PEANO]);
fprintf(FdBalance, "Cooling & SFR = '%c' / '%c'\n", CPU_Symbol[CPU_COOLINGSFR],
CPU_SymbolImbalance[CPU_COOLINGSFR]);
fprintf(FdBalance, "Snapshot dump = '%c' / '%c'\n", CPU_Symbol[CPU_SNAPSHOT],
CPU_SymbolImbalance[CPU_SNAPSHOT]);
fprintf(FdBalance, "FoF = '%c' / '%c'\n", CPU_Symbol[CPU_FOF], CPU_SymbolImbalance[CPU_FOF]);
fprintf(FdBalance, "Miscellaneous = '%c' / '%c'\n", CPU_Symbol[CPU_MISC], CPU_SymbolImbalance[CPU_MISC]);
fprintf(FdBalance, "\n");
#ifdef SFR
sprintf(buf, "%s%s", All.OutputDir, "sfr.txt");
if(!(FdSfr = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#ifdef BLACK_HOLES
sprintf(buf, "%s%s", All.OutputDir, "blackholes.txt");
if(!(FdBlackHoles = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#ifdef CS_MODEL
#ifdef CS_TESTS
sprintf(buf, "%s%s", All.OutputDir, "energy_test.txt");
if(!(FdEgyTest = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
sprintf(buf, "%s%s", All.OutputDir, "promotion_test.txt");
if(!(FdPromTest = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
sprintf(buf, "%s%s", All.OutputDir, "SN_test.txt");
if(!(FdSNTest = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#if defined(CS_SNI) || defined(CS_SNII)
sprintf(buf, "%s%s", All.OutputDir, "SN.txt");
if(!(FdSN = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
#endif
#endif
#ifdef FORCETEST
if(RestartFlag == 0)
{
sprintf(buf, "%s%s", All.OutputDir, "forcetest.txt");
if(!(FdForceTest = fopen(buf, "w")))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
fclose(FdForceTest);
}
#endif
#ifdef XXLINFO
sprintf(buf, "%s%s", All.OutputDir, "xxl.txt");
if(!(FdXXL = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
else
{
if(RestartFlag == 0)
{
fprintf(FdXXL, "nstep time ");
#ifdef MAGNETIC
fprintf(FdXXL, "<|B|> ");
#ifdef TRACEDIVB
fprintf(FdXXL, "max(divB) ");
#endif
#endif
#ifdef TIME_DEP_ART_VISC
fprintf(FdXXL, "<alpha> ");
#endif
fprintf(FdXXL, "\n");
fflush(FdXXL);
}
}
#endif
#ifdef DARKENERGY
sprintf(buf, "%s%s", All.OutputDir, "darkenergy.txt");
if(!(FdDE = fopen(buf, mode)))
{
printf("error in opening file '%s'\n", buf);
endrun(1);
}
else
{
if(RestartFlag == 0)
{
fprintf(FdDE, "nstep time H(a) ");
#ifndef TIMEDEPDE
fprintf(FdDE, "w0 Omega_L ");
#else
fprintf(FdDE, "w(a) Omega_L ");
#endif
#ifdef TIMEDEPGRAV
fprintf(FdDE, "dH dG ");
#endif
fprintf(FdDE, "\n");
fflush(FdDE);
}
}
#endif
}
/*! This function closes the global log-files.
*/
void close_outputfiles(void)
{
#ifdef BLACK_HOLES
fclose(FdBlackHolesDetails); /* needs to be done by everyone */
#endif
#ifdef CAUSTIC_FINDER
fclose(FdCaustics); /* needs to be done by everyone */
#endif
if(ThisTask != 0) /* only the root processors writes to the log files */
return;
fclose(FdCPU);
fclose(FdInfo);
fclose(FdEnergy);
fclose(FdTimings);
fclose(FdBalance);
#ifdef SFR
fclose(FdSfr);
#endif
#ifdef BLACK_HOLES
fclose(FdBlackHoles);
#endif
#ifdef XXLINFO
fclose(FdXXL);
#endif
#ifdef DARKENERGY
fclose(FdDE);
#endif
#ifdef CS_FEEDBACK
fclose(FdPromotion);
#endif
#ifdef CS_MODEL
#ifdef CS_TESTS
fclose(FdEgyTest);
fclose(FdPromTest);
fclose(FdSNTest);
#endif
#if defined(CS_SNI) || defined(CS_SNII)
fclose(FdSN);
#endif
#endif
#ifdef CS_FEEDBACK
fclose(FdPromotion);
#endif
}
/*! This function parses the parameterfile in a simple way. Each paramater is
* defined by a keyword (`tag'), and can be either of type douple, int, or
* character string. The routine makes sure that each parameter appears
* exactly once in the parameterfile, otherwise error messages are
* produced that complain about the missing parameters.
*/
void read_parameter_file(char *fname)
{
#define REAL 1
#define STRING 2
#define INT 3
#define MAXTAGS 300
FILE *fd, *fdout;
char buf[200], buf1[200], buf2[200], buf3[400];
int i, j, nt;
int id[MAXTAGS];
void *addr[MAXTAGS];
char tag[MAXTAGS][50];
int pnum, errorFlag = 0;
All.StarformationOn = 0; /* defaults */
#ifdef COSMIC_RAYS
char tempBuf[20];
int CRpop, x;
double tempAlpha;
#endif
if(sizeof(long long) != 8)
{
if(ThisTask == 0)
printf("\nType `long long' is not 64 bit on this platform. Stopping.\n\n");
endrun(0);
}
if(sizeof(int) != 4)
{
if(ThisTask == 0)
printf("\nType `int' is not 32 bit on this platform. Stopping.\n\n");
endrun(0);
}
if(sizeof(float) != 4)
{
if(ThisTask == 0)
printf("\nType `float' is not 32 bit on this platform. Stopping.\n\n");
endrun(0);
}
if(sizeof(double) != 8)
{
if(ThisTask == 0)
printf("\nType `double' is not 64 bit on this platform. Stopping.\n\n");
endrun(0);
}
if(ThisTask == 0) /* read parameter file on process 0 */
{
nt = 0;
strcpy(tag[nt], "InitCondFile");
addr[nt] = All.InitCondFile;
id[nt++] = STRING;
strcpy(tag[nt], "OutputDir");
addr[nt] = All.OutputDir;
id[nt++] = STRING;
strcpy(tag[nt], "SnapshotFileBase");
addr[nt] = All.SnapshotFileBase;
id[nt++] = STRING;
strcpy(tag[nt], "EnergyFile");
addr[nt] = All.EnergyFile;
id[nt++] = STRING;
strcpy(tag[nt], "CpuFile");
addr[nt] = All.CpuFile;
id[nt++] = STRING;
strcpy(tag[nt], "InfoFile");
addr[nt] = All.InfoFile;
id[nt++] = STRING;
strcpy(tag[nt], "TimingsFile");
addr[nt] = All.TimingsFile;
id[nt++] = STRING;
strcpy(tag[nt], "RestartFile");
addr[nt] = All.RestartFile;
id[nt++] = STRING;
strcpy(tag[nt], "ResubmitCommand");
addr[nt] = All.ResubmitCommand;
id[nt++] = STRING;
strcpy(tag[nt], "OutputListFilename");
addr[nt] = All.OutputListFilename;
id[nt++] = STRING;
strcpy(tag[nt], "OutputListOn");
addr[nt] = &All.OutputListOn;
id[nt++] = INT;
strcpy(tag[nt], "Omega0");
addr[nt] = &All.Omega0;
id[nt++] = REAL;
strcpy(tag[nt], "OmegaBaryon");
addr[nt] = &All.OmegaBaryon;
id[nt++] = REAL;
strcpy(tag[nt], "OmegaLambda");
addr[nt] = &All.OmegaLambda;
id[nt++] = REAL;
strcpy(tag[nt], "HubbleParam");
addr[nt] = &All.HubbleParam;
id[nt++] = REAL;
strcpy(tag[nt], "BoxSize");
addr[nt] = &All.BoxSize;
id[nt++] = REAL;
strcpy(tag[nt], "PeriodicBoundariesOn");
addr[nt] = &All.PeriodicBoundariesOn;
id[nt++] = INT;
strcpy(tag[nt], "TimeOfFirstSnapshot");
addr[nt] = &All.TimeOfFirstSnapshot;
id[nt++] = REAL;
strcpy(tag[nt], "CpuTimeBetRestartFile");
addr[nt] = &All.CpuTimeBetRestartFile;
id[nt++] = REAL;
strcpy(tag[nt], "TimeBetStatistics");
addr[nt] = &All.TimeBetStatistics;
id[nt++] = REAL;
strcpy(tag[nt], "TimeBegin");
addr[nt] = &All.TimeBegin;
id[nt++] = REAL;
strcpy(tag[nt], "TimeMax");
addr[nt] = &All.TimeMax;
id[nt++] = REAL;
strcpy(tag[nt], "TimeBetSnapshot");
addr[nt] = &All.TimeBetSnapshot;
id[nt++] = REAL;
strcpy(tag[nt], "UnitVelocity_in_cm_per_s");
addr[nt] = &All.UnitVelocity_in_cm_per_s;
id[nt++] = REAL;
strcpy(tag[nt], "UnitLength_in_cm");
addr[nt] = &All.UnitLength_in_cm;
id[nt++] = REAL;
strcpy(tag[nt], "UnitMass_in_g");
addr[nt] = &All.UnitMass_in_g;
id[nt++] = REAL;
strcpy(tag[nt], "TreeDomainUpdateFrequency");
addr[nt] = &All.TreeDomainUpdateFrequency;
id[nt++] = REAL;
strcpy(tag[nt], "ErrTolIntAccuracy");
addr[nt] = &All.ErrTolIntAccuracy;
id[nt++] = REAL;
strcpy(tag[nt], "ErrTolTheta");
addr[nt] = &All.ErrTolTheta;
id[nt++] = REAL;
#ifdef SUBFIND
strcpy(tag[nt], "ErrTolThetaSubfind");
addr[nt] = &All.ErrTolThetaSubfind;
id[nt++] = REAL;
#endif
strcpy(tag[nt], "ErrTolForceAcc");
addr[nt] = &All.ErrTolForceAcc;
id[nt++] = REAL;
strcpy(tag[nt], "MinGasHsmlFractional");
addr[nt] = &All.MinGasHsmlFractional;
id[nt++] = REAL;
strcpy(tag[nt], "MaxSizeTimestep");
addr[nt] = &All.MaxSizeTimestep;
id[nt++] = REAL;
strcpy(tag[nt], "MinSizeTimestep");
addr[nt] = &All.MinSizeTimestep;
id[nt++] = REAL;
strcpy(tag[nt], "MaxRMSDisplacementFac");
addr[nt] = &All.MaxRMSDisplacementFac;
id[nt++] = REAL;
strcpy(tag[nt], "ArtBulkViscConst");
addr[nt] = &All.ArtBulkViscConst;
id[nt++] = REAL;
strcpy(tag[nt], "CourantFac");
addr[nt] = &All.CourantFac;
id[nt++] = REAL;
strcpy(tag[nt], "DesNumNgb");
addr[nt] = &All.DesNumNgb;
id[nt++] = INT;
#ifdef SUBFIND
strcpy(tag[nt], "DesLinkNgb");
addr[nt] = &All.DesLinkNgb;
id[nt++] = INT;
#endif
strcpy(tag[nt], "MaxNumNgbDeviation");
addr[nt] = &All.MaxNumNgbDeviation;
id[nt++] = REAL;
#ifdef START_WITH_EXTRA_NGBDEV
strcpy(tag[nt], "MaxNumNgbDeviationStart");
addr[nt] = &All.MaxNumNgbDeviationStart;
id[nt++] = REAL;
#endif
strcpy(tag[nt], "ComovingIntegrationOn");
addr[nt] = &All.ComovingIntegrationOn;
id[nt++] = INT;
strcpy(tag[nt], "ICFormat");
addr[nt] = &All.ICFormat;
id[nt++] = INT;
strcpy(tag[nt], "SnapFormat");
addr[nt] = &All.SnapFormat;
id[nt++] = INT;
strcpy(tag[nt], "NumFilesPerSnapshot");
addr[nt] = &All.NumFilesPerSnapshot;
id[nt++] = INT;
strcpy(tag[nt], "NumFilesWrittenInParallel");
addr[nt] = &All.NumFilesWrittenInParallel;
id[nt++] = INT;
strcpy(tag[nt], "ResubmitOn");
addr[nt] = &All.ResubmitOn;
id[nt++] = INT;
strcpy(tag[nt], "CoolingOn");
addr[nt] = &All.CoolingOn;
id[nt++] = INT;
strcpy(tag[nt], "StarformationOn");
addr[nt] = &All.StarformationOn;
id[nt++] = INT;
strcpy(tag[nt], "TypeOfTimestepCriterion");
addr[nt] = &All.TypeOfTimestepCriterion;
id[nt++] = INT;
strcpy(tag[nt], "TypeOfOpeningCriterion");
addr[nt] = &All.TypeOfOpeningCriterion;
id[nt++] = INT;
strcpy(tag[nt], "TimeLimitCPU");
addr[nt] = &All.TimeLimitCPU;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningHalo");
addr[nt] = &All.SofteningHalo;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningDisk");
addr[nt] = &All.SofteningDisk;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningBulge");
addr[nt] = &All.SofteningBulge;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningGas");
addr[nt] = &All.SofteningGas;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningStars");
addr[nt] = &All.SofteningStars;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningBndry");
addr[nt] = &All.SofteningBndry;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningHaloMaxPhys");
addr[nt] = &All.SofteningHaloMaxPhys;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningDiskMaxPhys");
addr[nt] = &All.SofteningDiskMaxPhys;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningBulgeMaxPhys");
addr[nt] = &All.SofteningBulgeMaxPhys;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningGasMaxPhys");
addr[nt] = &All.SofteningGasMaxPhys;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningStarsMaxPhys");
addr[nt] = &All.SofteningStarsMaxPhys;
id[nt++] = REAL;
strcpy(tag[nt], "SofteningBndryMaxPhys");
addr[nt] = &All.SofteningBndryMaxPhys;
id[nt++] = REAL;
strcpy(tag[nt], "BufferSize");
addr[nt] = &All.BufferSize;
id[nt++] = INT;
strcpy(tag[nt], "PartAllocFactor");
addr[nt] = &All.PartAllocFactor;
id[nt++] = REAL;
strcpy(tag[nt], "GravityConstantInternal");
addr[nt] = &All.GravityConstantInternal;
id[nt++] = REAL;
strcpy(tag[nt], "InitGasTemp");
addr[nt] = &All.InitGasTemp;
id[nt++] = REAL;
strcpy(tag[nt], "MinGasTemp");
addr[nt] = &All.MinGasTemp;
id[nt++] = REAL;
#ifdef DISTORTIONTENSORPS
#ifdef ANNIHILATION_RADIATION
strcpy(tag[nt], "DM_velocity_dispersion");
addr[nt] = &All.DM_velocity_dispersion;
id[nt++] = REAL;
#endif
#endif
#ifdef SCALARFIELD
strcpy(tag[nt], "ScalarBeta");
addr[nt] = &All.ScalarBeta;
id[nt++] = REAL;
strcpy(tag[nt], "ScalarScreeningLength");
addr[nt] = &All.ScalarScreeningLength;
id[nt++] = REAL;
#endif
#ifdef OUTPUTLINEOFSIGHT
strcpy(tag[nt], "TimeFirstLineOfSight");
addr[nt] = &All.TimeFirstLineOfSight;
id[nt++] = REAL;
#endif
#if defined(ADAPTIVE_GRAVSOFT_FORGAS) && !defined(ADAPTIVE_GRAVSOFT_FORGAS_HSML)
strcpy(tag[nt], "ReferenceGasMass");
addr[nt] = &All.ReferenceGasMass;
id[nt++] = REAL;
#endif
#ifdef NAVIERSTOKES
strcpy(tag[nt], "FractionSpitzerViscosity");
addr[nt] = &All.FractionSpitzerViscosity;
id[nt++] = REAL;
#endif
#ifdef NAVIERSTOKES_CONSTANT
strcpy(tag[nt], "ShearViscosityTemperature");
addr[nt] = &All.ShearViscosityTemperature;
id[nt++] = REAL;
#endif
#ifdef NAVIERSTOKES_BULK
strcpy(tag[nt], "NavierStokes_BulkViscosity");
addr[nt] = &All.NavierStokes_BulkViscosity;
id[nt++] = REAL;
#endif
#ifdef CHEMISTRY
strcpy(tag[nt], "Epsilon");
addr[nt] = &All.Epsilon;
id[nt++] = REAL;
#endif
#ifdef CONDUCTION
strcpy(tag[nt], "ConductionEfficiency");
addr[nt] = &All.ConductionCoeff;
id[nt++] = REAL;
strcpy(tag[nt], "MaxSizeConductionStep");
addr[nt] = &All.MaxSizeConductionStep;
id[nt++] = REAL;
#endif
#if defined(BUBBLES) || defined(MULTI_BUBBLES)
strcpy(tag[nt], "BubbleDistance");
addr[nt] = &All.BubbleDistance;
id[nt++] = REAL;
strcpy(tag[nt], "BubbleRadius");
addr[nt] = &All.BubbleRadius;
id[nt++] = REAL;
strcpy(tag[nt], "BubbleTimeInterval");
addr[nt] = &All.BubbleTimeInterval;
id[nt++] = REAL;
strcpy(tag[nt], "BubbleEnergy");
addr[nt] = &All.BubbleEnergy;
id[nt++] = REAL;
strcpy(tag[nt], "FirstBubbleRedshift");
addr[nt] = &All.FirstBubbleRedshift;
id[nt++] = REAL;
#endif
#ifdef MULTI_BUBBLES
strcpy(tag[nt], "MinFoFMassForNewSeed");
addr[nt] = &All.MinFoFMassForNewSeed;
id[nt++] = REAL;
strcpy(tag[nt], "ClusterMass200");
addr[nt] = &All.ClusterMass200;
id[nt++] = REAL;
strcpy(tag[nt], "massDMpart");
addr[nt] = &All.massDMpart;
id[nt++] = REAL;
#endif
#ifdef BH_BUBBLES
strcpy(tag[nt], "BubbleDistance");
addr[nt] = &All.BubbleDistance;
id[nt++] = REAL;
strcpy(tag[nt], "BubbleRadius");
addr[nt] = &All.BubbleRadius;
id[nt++] = REAL;
strcpy(tag[nt], "BubbleEnergy");
addr[nt] = &All.BubbleEnergy;
id[nt++] = REAL;
strcpy(tag[nt], "BlackHoleRadioTriggeringFactor");
addr[nt] = &All.BlackHoleRadioTriggeringFactor;
id[nt++] = REAL;
strcpy(tag[nt], "DefaultICMDensity");
addr[nt] = &All.DefaultICMDensity;
id[nt++] = REAL;
strcpy(tag[nt], "RadioFeedbackFactor");
addr[nt] = &All.RadioFeedbackFactor;
id[nt++] = REAL;
#ifdef UNIFIED_FEEDBACK
strcpy(tag[nt], "RadioThreshold");
addr[nt] = &All.RadioThreshold;
id[nt++] = REAL;
#endif
#endif
#ifdef COSMIC_RAYS
for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)
{
sprintf(tempBuf, "CR_SpectralIndex_%i", CRpop);
strcpy(tag[nt], tempBuf);
addr[nt] = &All.CR_Alpha[CRpop];
id[nt++] = REAL;
}
/* sort the All.CR_Alpha[CRpop] array in assending order */
if (NUMCRPOP > 1)
for (x=0; x < NUMCRPOP-1; x++)
for (CRpop=0; CRpop < NUMCRPOP-x-1; CRpop++)
if (All.CR_Alpha[CRpop] > All.CR_Alpha[CRpop+1])
{
tempAlpha=All.CR_Alpha[CRpop];
All.CR_Alpha[CRpop]=All.CR_Alpha[CRpop+1];
All.CR_Alpha[CRpop+1]=tempAlpha;
}
strcpy(tag[nt], "CR_SupernovaEfficiency");
addr[nt] = &All.CR_SNEff;
id[nt++] = REAL;
strcpy(tag[nt], "CR_SupernovaSpectralIndex");
addr[nt] = &All.CR_SNAlpha;
id[nt++] = REAL;
#if defined(CR_DIFFUSION)
strcpy(tag[nt], "CR_DiffusionCoeff");
addr[nt] = &All.CR_DiffusionCoeff;
id[nt++] = REAL;
strcpy(tag[nt], "CR_DiffusionDensityScaling");
addr[nt] = &All.CR_DiffusionDensScaling;
id[nt++] = REAL;
/* CR Diffusion scaling: reference density rho_0.
If value is 0, then rho_crit @ z=0 is used. */
strcpy(tag[nt], "CR_DiffusionReferenceDensity");
addr[nt] = &All.CR_DiffusionDensZero;
id[nt++] = REAL;
strcpy(tag[nt], "CR_DiffusionTemperatureScaling");
addr[nt] = &All.CR_DiffusionEntropyScaling;
id[nt++] = REAL;
strcpy(tag[nt], "CR_DiffusionReferenceTemperature");
addr[nt] = &All.CR_DiffusionEntropyZero;
id[nt++] = REAL;
strcpy(tag[nt], "CR_DiffusionMaxSizeTimestep");
addr[nt] = &All.CR_DiffusionMaxSizeTimestep;
id[nt++] = REAL;
#endif /* CR_DIFFUSION */
#ifdef CR_SHOCK
strcpy(tag[nt], "CR_ShockEfficiency");
addr[nt] = &All.CR_ShockEfficiency;
id[nt++] = REAL;
#if ( CR_SHOCK == 1 ) /* Constant Spectral Index method */
strcpy(tag[nt], "CR_ShockSpectralIndex");
addr[nt] = &All.CR_ShockAlpha;
id[nt++] = REAL;
#else /* Mach-Number - Dependent method */
strcpy(tag[nt], "CR_ShockCutoffFac");
addr[nt] = &All.CR_ShockCutoff;
id[nt++] = REAL;
#endif
#endif /* CR_SHOCK */
#ifdef FIX_QINJ
strcpy(tag[nt], "Shock_Fix_Qinj");
addr[nt] = &All.Shock_Fix_Qinj;
id[nt++] = REAL;
#endif
#ifdef CR_BUBBLES
strcpy(tag[nt], "CR_AGNEff");
addr[nt] = &All.CR_AGNEff;
id[nt++] = REAL;
#endif
#endif /* COSMIC_RAYS */
#ifdef MACHNUM
strcpy(tag[nt], "Shock_LengthScale");
addr[nt] = &All.Shock_Length;
id[nt++] = REAL;
strcpy(tag[nt], "Shock_DeltaDecayTimeMax");
addr[nt] = &All.Shock_DeltaDecayTimeMax;
id[nt++] = REAL;
#endif
#ifdef BLACK_HOLES
strcpy(tag[nt], "TimeBetBlackHoleSearch");
addr[nt] = &All.TimeBetBlackHoleSearch;
id[nt++] = REAL;
strcpy(tag[nt], "BlackHoleAccretionFactor");
addr[nt] = &All.BlackHoleAccretionFactor;
id[nt++] = REAL;
strcpy(tag[nt], "BlackHoleFeedbackFactor");
addr[nt] = &All.BlackHoleFeedbackFactor;
id[nt++] = REAL;
strcpy(tag[nt], "BlackHoleEddingtonFactor");
addr[nt] = &All.BlackHoleEddingtonFactor;
id[nt++] = REAL;
strcpy(tag[nt], "SeedBlackHoleMass");
addr[nt] = &All.SeedBlackHoleMass;
id[nt++] = REAL;
strcpy(tag[nt], "MinFoFMassForNewSeed");
addr[nt] = &All.MinFoFMassForNewSeed;
id[nt++] = REAL;
strcpy(tag[nt], "BlackHoleNgbFactor");
addr[nt] = &All.BlackHoleNgbFactor;
id[nt++] = REAL;
strcpy(tag[nt], "BlackHoleMaxAccretionRadius");
addr[nt] = &All.BlackHoleMaxAccretionRadius;
id[nt++] = REAL;
#ifdef FOF
strcpy(tag[nt], "massDMpart");
addr[nt] = &All.massDMpart;
id[nt++] = REAL;
#endif
#endif
#ifdef SFR
strcpy(tag[nt], "CritOverDensity");
addr[nt] = &All.CritOverDensity;
id[nt++] = REAL;
strcpy(tag[nt], "CritPhysDensity");
addr[nt] = &All.CritPhysDensity;
id[nt++] = REAL;
strcpy(tag[nt], "FactorSN");
addr[nt] = &All.FactorSN;
id[nt++] = REAL;
strcpy(tag[nt], "FactorEVP");
addr[nt] = &All.FactorEVP;
id[nt++] = REAL;
strcpy(tag[nt], "TempSupernova");
addr[nt] = &All.TempSupernova;
id[nt++] = REAL;
strcpy(tag[nt], "TempClouds");
addr[nt] = &All.TempClouds;
id[nt++] = REAL;
strcpy(tag[nt], "MaxSfrTimescale");
addr[nt] = &All.MaxSfrTimescale;
id[nt++] = REAL;
strcpy(tag[nt], "WindEfficiency");
addr[nt] = &All.WindEfficiency;
id[nt++] = REAL;
strcpy(tag[nt], "WindEnergyFraction");
addr[nt] = &All.WindEnergyFraction;
id[nt++] = REAL;
strcpy(tag[nt], "WindFreeTravelLength");
addr[nt] = &All.WindFreeTravelLength;
id[nt++] = REAL;
strcpy(tag[nt], "WindFreeTravelDensFac");
addr[nt] = &All.WindFreeTravelDensFac;
id[nt++] = REAL;
#endif
#if defined(SNIA_HEATING)
strcpy(tag[nt], "SnIaHeatingRate");
addr[nt] = &All.SnIaHeatingRate;
id[nt++] = REAL;
#endif
#ifdef CS_MODEL
strcpy(tag[nt], "FactorSFR");
addr[nt] = &All.FactorSFR;
id[nt++] = REAL;
strcpy(tag[nt], "DecouplingParam");
addr[nt] = &All.DecouplingParam;
id[nt++] = REAL;
strcpy(tag[nt], "TlifeSNII");
addr[nt] = &All.TlifeSNII;
id[nt++] = REAL;
strcpy(tag[nt], "Raiteri_TlifeSNII");
addr[nt] = &All.Raiteri_TlifeSNII;
id[nt++] = INT;
strcpy(tag[nt], "MinTlifeSNI");
addr[nt] = &All.MinTlifeSNI;
id[nt++] = REAL;
strcpy(tag[nt], "MaxTlifeSNI");
addr[nt] = &All.MaxTlifeSNI;
id[nt++] = REAL;
strcpy(tag[nt], "RateSNI");
addr[nt] = &All.RateSNI;
id[nt++] = REAL;
strcpy(tag[nt], "SN_Energy_cgs");
addr[nt] = &All.SN_Energy_cgs;
id[nt++] = REAL;
strcpy(tag[nt], "Tcrit_Phase");
addr[nt] = &All.Tcrit_Phase;
id[nt++] = REAL;
strcpy(tag[nt], "DensFrac_Phase");
addr[nt] = &All.DensFrac_Phase;
id[nt++] = REAL;
strcpy(tag[nt], "SN_Energy_frac_cold");
addr[nt] = &All.SN_Energy_frac_cold;
id[nt++] = REAL;
strcpy(tag[nt], "MaxHotHsmlParam");
addr[nt] = &All.MaxHotHsmlParam;
id[nt++] = REAL;
strcpy(tag[nt], "InitialHotHsmlFactor");
addr[nt] = &All.InitialHotHsmlFactor;
id[nt++] = REAL;
strcpy(tag[nt], "MaxNumHotNgbDeviation");
addr[nt] = &All.MaxNumHotNgbDeviation;
id[nt++] = REAL;
#endif
#ifdef SOFTEREQS
strcpy(tag[nt], "FactorForSofterEQS");
addr[nt] = &All.FactorForSofterEQS;
id[nt++] = REAL;
#endif
#ifdef DARKENERGY
#ifndef TIMEDEPDE
strcpy(tag[nt], "DarkEnergyParam");
addr[nt] = &All.DarkEnergyParam;
id[nt++] = REAL;
#endif
#endif
#ifdef RESCALEVINI
strcpy(tag[nt], "VelIniScale");
addr[nt] = &All.VelIniScale;
id[nt++] = REAL;
#endif
#ifdef DARKENERGY
#ifdef TIMEDEPDE
strcpy(tag[nt], "DarkEnergyFile");
addr[nt] = All.DarkEnergyFile;
id[nt++] = STRING;
#endif
#endif
#ifdef TIME_DEP_ART_VISC
strcpy(tag[nt], "ViscositySourceScaling");
addr[nt] = &All.ViscSource0;
id[nt++] = REAL;
strcpy(tag[nt], "ViscosityDecayLength");
addr[nt] = &All.DecayLength;
id[nt++] = REAL;
strcpy(tag[nt], "ViscosityAlphaMin");
addr[nt] = &All.AlphaMin;
id[nt++] = REAL;
#endif
#ifdef MAGNETIC_DISSIPATION
strcpy(tag[nt], "ArtificialMagneticDissipationConstant");
addr[nt] = &All.ArtMagDispConst;
id[nt++] = REAL;
#ifdef TIME_DEP_MAGN_DISP
strcpy(tag[nt], "ArtificialMagneticDissipationMin");
addr[nt] = &All.ArtMagDispMin;
id[nt++] = REAL;
strcpy(tag[nt], "ArtificialMagneticDissipationSource");
addr[nt] = &All.ArtMagDispSource;
id[nt++] = REAL;
strcpy(tag[nt], "ArtificialMagneticDissipationDecaytime");
addr[nt] = &All.ArtMagDispTime;
id[nt++] = REAL;
#endif
#endif
#ifdef DIVBCLEANING_DEDNER
strcpy(tag[nt], "DivBcleaningParabolicSigma");
addr[nt] = &All.DivBcleanParabolicSigma;
id[nt++] = REAL;
strcpy(tag[nt], "DivBcleaningHyperbolicSigma");
addr[nt] = &All.DivBcleanHyperbolicSigma;
id[nt++] = REAL;
#endif
#ifdef MAGNETIC
#ifdef BINISET
strcpy(tag[nt], "BiniX");
addr[nt] = &All.BiniX;
id[nt++] = REAL;
strcpy(tag[nt], "BiniY");
addr[nt] = &All.BiniY;
id[nt++] = REAL;
strcpy(tag[nt], "BiniZ");
addr[nt] = &All.BiniZ;
id[nt++] = REAL;
#endif
#ifdef BSMOOTH
strcpy(tag[nt], "BSmoothInt");
addr[nt] = &All.BSmoothInt;
id[nt++] = INT;
strcpy(tag[nt], "BSmoothFrac");
addr[nt] = &All.BSmoothFrac;
id[nt++] = REAL;
#ifdef SETMAINTIMESTEPCOUNT
strcpy(tag[nt], "MainTimestepCount");
addr[nt] = &All.MainTimestepCountIni;
id[nt++] = INT;
#endif
#endif
#ifdef MAGNETIC_DIFFUSION
strcpy(tag[nt], "MagneticEta");
addr[nt] = &All.MagneticEta;
id[nt++] = REAL;
#endif
#endif
#ifdef EOS_DEGENERATE
strcpy(tag[nt], "EosTable");
addr[nt] = All.EosTable;
id[nt++] = STRING;
#endif
#ifdef RADTRANSFER
strcpy(tag[nt], "IonizingLumPerSolarMass");
addr[nt] = &All.IonizingLumPerSolarMass;
id[nt++] = REAL;
strcpy(tag[nt], "IonizingLumPerSFR");
addr[nt] = &All.IonizingLumPerSFR;
id[nt++] = REAL;
#endif
if((fd = fopen(fname, "r")))
{
sprintf(buf, "%s%s", fname, "-usedvalues");
if(!(fdout = fopen(buf, "w")))
{
printf("error opening file '%s' \n", buf);
errorFlag = 1;
}
else
{
printf("Obtaining parameters from file '%s':\n", fname);
while(!feof(fd))
{
char *ret;
*buf = 0;
ret = fgets(buf, 200, fd);
if(sscanf(buf, "%s%s%s", buf1, buf2, buf3) < 2)
continue;
if(buf1[0] == '%')
continue;
for(i = 0, j = -1; i < nt; i++)
if(strcmp(buf1, tag[i]) == 0)
{
j = i;
tag[i][0] = 0;
break;
}
if(j >= 0)
{
switch (id[j])
{
case REAL:
*((double *) addr[j]) = atof(buf2);
fprintf(fdout, "%-35s%g\n", buf1, *((double *) addr[j]));
fprintf(stdout, "%-35s%g\n", buf1, *((double *) addr[j]));
break;
case STRING:
strcpy((char *) addr[j], buf2);
fprintf(fdout, "%-35s%s\n", buf1, buf2);
fprintf(stdout, "%-35s%s\n", buf1, buf2);
break;
case INT:
*((int *) addr[j]) = atoi(buf2);
fprintf(fdout, "%-35s%d\n", buf1, *((int *) addr[j]));
fprintf(stdout, "%-35s%d\n", buf1, *((int *) addr[j]));
break;
}
}
else
{
#ifdef ALLOWEXTRAPARAMS
fprintf(stdout, "WARNING from file %s: Tag '%s' ignored !\n", fname, buf1);
#else
fprintf(stdout, "Error in file %s: Tag '%s' not allowed or multiple defined.\n",
fname, buf1);
errorFlag = 1;
#endif
}
}
fclose(fd);
fclose(fdout);
printf("\n");
i = strlen(All.OutputDir);
if(i > 0)
if(All.OutputDir[i - 1] != '/')
strcat(All.OutputDir, "/");
#ifdef INVARIANCETEST
i = strlen(All.OutputDir);
All.OutputDir[i - 1] = 0;
strcat(All.OutputDir, "/run0");
i = strlen(All.OutputDir);
All.OutputDir[i - 1] += Color;
mkdir(All.OutputDir, 02755);
strcat(All.OutputDir, "/");
sprintf(buf1, "%s%s", All.OutputDir, "logfile.txt");
printf("stdout will now appear in the file '%s'\n", buf1);
fflush(stdout);
freopen(buf1, "w", stdout);
#endif
sprintf(buf1, "%s%s", fname, "-usedvalues");
sprintf(buf2, "%s%s", All.OutputDir, "parameters-usedvalues");
sprintf(buf3, "cp %s %s", buf1, buf2);
#ifndef NOCALLSOFSYSTEM
int ret;
ret = system(buf3);
#endif
}
}
else
{
printf("Parameter file %s not found.\n", fname);
errorFlag = 1;
}
// Counts number of CR populations in parameter file
/*
#ifdef COSMIC_RAYS
CRpop=0;
while ((All.CR_Alpha[CRpop] != 0.0 ) && ( CRpop < MaxNumCRpop ))
CRpop++;
NUMCRPOP = CRpop;
#else
NUMCRPOP = 1;
#endif
*/
printf(" NUMCRPOP = %i \n", NUMCRPOP);
for(i = 0; i < nt; i++)
{
if(*tag[i])
{
printf("Error. I miss a value for tag '%s' in parameter file '%s'.\n", tag[i], fname);
errorFlag = 1;
}
}
if(All.OutputListOn && errorFlag == 0)
errorFlag += read_outputlist(All.OutputListFilename);
else
All.OutputListLength = 0;
}
MPI_Bcast(&errorFlag, 1, MPI_INT, 0, MPI_COMM_WORLD);
if(errorFlag)
{
MPI_Finalize();
exit(0);
}
/* now communicate the relevant parameters to the other processes */
MPI_Bcast(&All, sizeof(struct global_data_all_processes), MPI_BYTE, 0, MPI_COMM_WORLD);
for(pnum = 0; All.NumFilesWrittenInParallel > (1 << pnum); pnum++);
if(All.NumFilesWrittenInParallel != (1 << pnum))
{
if(ThisTask == 0)
printf("NumFilesWrittenInParallel MUST be a power of 2\n");
endrun(0);
}
if(All.NumFilesWrittenInParallel > NTask)
{
if(ThisTask == 0)
printf("NumFilesWrittenInParallel MUST be smaller than number of processors\n");
endrun(0);
}
#ifdef PERIODIC
if(All.PeriodicBoundariesOn == 0)
{
if(ThisTask == 0)
{
printf("Code was compiled with periodic boundary conditions switched on.\n");
printf("You must set `PeriodicBoundariesOn=1', or recompile the code.\n");
}
endrun(0);
}
#else
if(All.PeriodicBoundariesOn == 1)
{
if(ThisTask == 0)
{
printf("Code was compiled with periodic boundary conditions switched off.\n");
printf("You must set `PeriodicBoundariesOn=0', or recompile the code.\n");
}
endrun(0);
}
#endif
#if defined(VORONOI) && !defined(PERIODIC)
if(ThisTask == 0)
{
printf("Voronoi code requires periodic boundaries.\n");
}
endrun(0);
#endif
#ifdef COOLING
if(All.CoolingOn == 0)
{
if(ThisTask == 0)
{
printf("Code was compiled with cooling switched on.\n");
printf("You must set `CoolingOn=1', or recompile the code.\n");
}
endrun(0);
}
#else
if(All.CoolingOn == 1)
{
if(ThisTask == 0)
{
printf("Code was compiled with cooling switched off.\n");
printf("You must set `CoolingOn=0', or recompile the code.\n");
}
endrun(0);
}
#endif
if(All.TypeOfTimestepCriterion >= 3)
{
if(ThisTask == 0)
{
printf("The specified timestep criterion\n");
printf("is not valid\n");
}
endrun(0);
}
#if defined(LONG_X) || defined(LONG_Y) || defined(LONG_Z)
#ifndef NOGRAVITY
if(ThisTask == 0)
{
printf("Code was compiled with LONG_X/Y/Z, but not with NOGRAVITY.\n");
printf("Stretched periodic boxes are not implemented for gravity yet.\n");
}
endrun(0);
#endif
#endif
#ifdef SFR
#ifndef MOREPARAMS
if(ThisTask == 0)
{
printf("Code was compiled with SFR, but not with MOREPARAMS.\n");
printf("This is not allowed.\n");
}
endrun(0);
#endif
if(All.StarformationOn == 0)
{
if(ThisTask == 0)
{
printf("Code was compiled with star formation switched on.\n");
printf("You must set `StarformationOn=1', or recompile the code.\n");
}
endrun(0);
}
if(All.CoolingOn == 0)
{
if(ThisTask == 0)
{
printf("You try to use the code with star formation enabled,\n");
printf("but you did not switch on cooling.\nThis mode is not supported.\n");
}
endrun(0);
}
#else
if(All.StarformationOn == 1)
{
if(ThisTask == 0)
{
printf("Code was compiled with star formation switched off.\n");
printf("You must set `StarformationOn=0', or recompile the code.\n");
}
endrun(0);
}
#endif
#ifdef METALS
#ifndef SFR
if(ThisTask == 0)
{
printf("Code was compiled with METALS, but not with SFR.\n");
printf("This is not allowed.\n");
}
endrun(0);
#endif
#endif
#ifndef MOREPARAMS
#ifdef TIME_DEP_ART_VISC
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with TIME_DEP_ART_VISC, but not with MOREPARAMS.\n");
fprintf(stdout, "This is not allowed.\n");
}
endrun(0);
#endif
#ifdef DARKENERGY
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with DARKENERGY, but not with MOREPARAMS.\n");
fprintf(stdout, "This is not allowed.\n");
}
endrun(0);
#endif
#ifdef TIMEDEPDE
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with TIMEDEPDE, but not with MOREPARAMS.\n");
fprintf(stdout, "This is not allowed.\n");
}
endrun(0);
#endif
#endif
#ifdef TIMEDEPDE
#ifndef DARKENERGY
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with TIMEDEPDE, but not with DARKENERGY.\n");
fprintf(stdout, "This is not allowed.\n");
}
endrun(0);
#endif
#endif
#ifndef MAGNETIC
#ifdef TRACEDIVB
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with TRACEDIVB, but not with MAGNETIC.\n");
fprintf(stdout, "This is not allowed.\n");
}
endrun(0);
#endif
#ifdef DBOUTPUT
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with DBOUTPUT, but not with MAGNETIC.\n");
fprintf(stdout, "This is not allowed.\n");
}
endrun(0);
#endif
#ifdef MAGFORCE
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with MAGFORCE, but not with MAGNETIC.\n");
fprintf(stdout, "This is not allowed.\n");
}
endrun(0);
#endif
#ifdef BSMOOTH
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with BSMOOTH, but not with MAGNETIC.\n");
fprintf(stdout, "This is not allowed.\n");
}
endrun(0);
#endif
#ifdef BFROMROTA
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with BFROMROTA, but not with MAGNETIC.\n");
fprintf(stdout, "This is not allowed.\n");
}
endrun(0);
#endif
#ifdef MU0_UNITY
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with MU0_UNITY, but not with MAGNETIC.\n");
fprintf(stdout, "This makes no sense.\n");
}
endrun(0);
#endif
#ifdef MAGNETIC_DISSIPATION
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with MAGNETIC_DISSIPATION, but not with MAGNETIC.\n");
fprintf(stdout, "This makes no sense.\n");
}
endrun(0);
#endif
#ifdef TIME_DEP_MAGN_DISP
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with TIME_DEP_MAGN_DISP, but not with MAGNETIC.\n");
fprintf(stdout, "This makes no sense.\n");
}
endrun(0);
#endif
#ifdef DIVBCLEANING_DEDNER
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with DIVBCLEANING_DEDNER, but not with MAGNETIC.\n");
fprintf(stdout, "This makes no sense.\n");
}
endrun(0);
#endif
#endif
#if defined(NOWINDTIMESTEPPING) && defined(MAGNETIC)
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with NOWINDTIMESTEPPING and with MAGNETIC.\n");
fprintf(stdout, "This is not allowed, as it leads to inconsitent MHD for wind particles.\n");
}
endrun(0);
#endif
#ifndef MAGFORCE
#ifdef DIVBFORCE
if(ThisTask == 0)
{
fprintf(stdout, "Code was compiled with DIVBFORCE, but not with MAGFORCE.\n");
fprintf(stdout, "This is not allowed.\n");
}
endrun(0);
#endif
#endif
#ifdef BH_BUBBLES
#ifndef BLACK_HOLES
if(ThisTask == 0)
{
printf("Code was compiled with BH_BUBBLES, but not with BLACK_HOLES.\n");
printf("This is not allowed.\n");
}
endrun(0);
#endif
#if defined(BUBBLES) || defined(MULTI_BUBBLES) || defined(EBUB_PROPTO_BHAR)
if(ThisTask == 0)
{
printf
("If the code is compiled with BH_BUBBLES, then BUBBLES, MULTI_BUBBLES or EBUB_PROPTO_BHAR options cannot be used.\n");
printf("This is not allowed.\n");
}
endrun(0);
#endif
#endif
#undef REAL
#undef STRING
#undef INT
#undef MAXTAGS
#ifdef COSMIC_RAYS
if(ThisTask == 0)
{
printf("CR SN Efficiency: %g\n", All.CR_SNEff);
}
#endif
}
/*! this function reads a table with a list of desired output times. The table
* does not have to be ordered in any way, but may not contain more than
* MAXLEN_OUTPUTLIST entries.
*/
int read_outputlist(char *fname)
{
FILE *fd;
int count, flag;
char buf[512];
if(!(fd = fopen(fname, "r")))
{
printf("can't read output list in file '%s'\n", fname);
return 1;
}
All.OutputListLength = 0;
while(1)
{
if(fgets(buf, 500, fd) != buf)
break;
count = sscanf(buf, " %lg %d ", &All.OutputListTimes[All.OutputListLength], &flag);
if(count == 1)
flag = 1;
if(count == 1 || count == 2)
{
if(All.OutputListLength >= MAXLEN_OUTPUTLIST)
{
if(ThisTask == 0)
printf("\ntoo many entries in output-list. You should increase MAXLEN_OUTPUTLIST=%d.\n",
(int) MAXLEN_OUTPUTLIST);
endrun(13);
}
All.OutputListFlag[All.OutputListLength] = flag;
All.OutputListLength++;
}
}
fclose(fd);
printf("\nfound %d times in output-list.\n", All.OutputListLength);
return 0;
}
/*! If a restart from restart-files is carried out where the TimeMax variable
* is increased, then the integer timeline needs to be adjusted. The approach
* taken here is to reduce the resolution of the integer timeline by factors
* of 2 until the new final time can be reached within TIMEBASE.
*/
void readjust_timebase(double TimeMax_old, double TimeMax_new)
{
int i;
long long ti_end;
if(sizeof(long long) != 8)
{
if(ThisTask == 0)
printf("\nType 'long long' is not 64 bit on this platform\n\n");
endrun(555);
}
if(ThisTask == 0)
{
printf("\nAll.TimeMax has been changed in the parameterfile\n");
printf("Need to adjust integer timeline\n\n\n");
}
if(TimeMax_new < TimeMax_old)
{
if(ThisTask == 0)
printf("\nIt is not allowed to reduce All.TimeMax\n\n");
endrun(556);
}
if(All.ComovingIntegrationOn)
ti_end = (long long) (log(TimeMax_new / All.TimeBegin) / All.Timebase_interval);
else
ti_end = (long long) ((TimeMax_new - All.TimeBegin) / All.Timebase_interval);
while(ti_end > TIMEBASE)
{
All.Timebase_interval *= 2.0;
ti_end /= 2;
All.Ti_Current /= 2;
#ifdef PMGRID
All.PM_Ti_begstep /= 2;
All.PM_Ti_endstep /= 2;
#endif
#ifdef CONDUCTION
All.Conduction_Ti_begstep /= 2;
All.Conduction_Ti_endstep /= 2;
#endif
#ifdef CR_DIFFUSION
All.CR_Diffusion_Ti_begstep /= 2;
All.CR_Diffusion_Ti_endstep /= 2;
#endif
for(i = 0; i < NumPart; i++)
{
P[i].Ti_begstep /= 2;
P[i].Ti_current /= 2;
if(P[i].TimeBin > 0)
{
P[i].TimeBin--;
if(P[i].TimeBin <= 0)
{
printf("Error in readjust_timebase(). Minimum Timebin for particle %d reached.\n", i);
endrun(8765);
}
}
}
All.Ti_nextlineofsight /= 2;
}
All.TimeMax = TimeMax_new;
}
| {
"alphanum_fraction": 0.6197502093,
"avg_line_length": 26.1506437768,
"ext": "c",
"hexsha": "15f62ce84e2e75f132d9e5c58220d40a0cf2daaa",
"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/begrun.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/begrun.c",
"max_line_length": 210,
"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/begrun.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 18947,
"size": 60931
} |
#include <viaio/Vlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_combination.h>
/* binomial coefficient, n choose k */
double binom (int n,int k)
{
double prod,ix,nx,kx;
int i;
nx = (double)n;
kx = (double)k;
prod = ix = 1;
for (i=1; i<=k; i++) {
prod *= (nx-kx+ix)/ix;
ix++;
}
return prod;
}
char **randomCombinations(long maxiter,int n,unsigned long int seed)
{
size_t iter,i,j,k;
size_t znum,maxnum=90000;
/* ini random */
fprintf(stderr," random shuffle\n");
gsl_rng_env_setup();
const gsl_rng_type *T = gsl_rng_default;
gsl_rng *rx = gsl_rng_alloc(T);
gsl_rng_set(rx,(unsigned long int)seed);
/* ini data structs */
int *src = (int *) calloc(n,sizeof(int));
char *tmp = (char *)calloc(n,sizeof(char));
for (i=0; i<n; i++) src[i] = i;
char **table = (char **)calloc(maxiter,sizeof(char *));
for (i=0; i<maxiter; i++)
table[i] = (char *)calloc(n,sizeof(char));
/* generate permutation table */
for (iter=0; iter<maxiter; iter++) {
znum = 0;
skip:
if (znum >= maxnum) VError(" znum %d",znum);
k = n/2;
if (n%2 == 1 && iter%2 == 0) k++; /* for odd number of images */
gsl_ran_shuffle (rx,src,n,sizeof(int));
memset(tmp,'0',n*sizeof(char));
for (j=0; j<k; j++) tmp[src[j]] = '1';
/* check if already there */
for (j=0; j<iter; j++) {
if (memcmp(tmp,table[j],(size_t)n) == 0 && znum < maxnum) {
znum++;
goto skip;
}
}
memcpy(table[iter],tmp,(size_t)n);
}
return table;
}
char **XXrandomCombinations(long maxiter,int n,unsigned long int seed)
{
size_t iter,i,j;
double p=0.5;
/* ini random */
gsl_rng_env_setup();
const gsl_rng_type *T = gsl_rng_default;
gsl_rng *rx = gsl_rng_alloc(T);
gsl_rng_set(rx,(unsigned long int)seed);
/* ini data structs */
char *tmp = (char *)calloc(n,sizeof(char));
char **table = (char **)calloc(maxiter,sizeof(char *));
for (i=0; i<maxiter; i++)
table[i] = (char *)calloc(n,sizeof(char));
/* generate permutation table */
iter = 0;
while (iter < maxiter) {
memset(tmp,'0',n*sizeof(char));
int ic=0;
for (j=0; j<n; j++) {
if (gsl_ran_bernoulli(rx,p) > 0) {
tmp[j] = '1';
ic++;
}
}
for (j=0; j<iter; j++) { /* check if already there */
if (memcmp(tmp,table[j],n) == 0) goto skip;
}
memcpy(table[iter],tmp,(size_t)n);
iter++;
skip: ;
}
return table;
}
char **allCombinations(long maxiter,int n,int iskip)
{
size_t iter,i,j,num,b;
/* ini data structs */
char *tmp = (char *)calloc(n,sizeof(char));
char **table = (char **)calloc(maxiter,sizeof(char *));
for (i=0; i<maxiter; i++)
table[i] = (char *)calloc(n,sizeof(char));
size_t xmax = (size_t) gsl_pow_int(2.0,(int)n);
iter = 0;
for (i=0; i<xmax; i+=iskip) {
/* decimal to binary */
memset(tmp,'0',n*sizeof(char));
j=0;
num = i;
while(num > 0) {
b=num%2;
if (b == 1) tmp[j] = '1';
num=num/2;
j++;
}
/* fprintf(stderr," iter: %5d %s\n",iter,tmp); */
memcpy(table[iter],tmp,(size_t)n);
iter++;
if (iter >= maxiter) return table;
}
return table;
}
| {
"alphanum_fraction": 0.5737704918,
"avg_line_length": 22.3666666667,
"ext": "c",
"hexsha": "8908ddbd76d65a8d85e7aa329cf026bf8aae182a",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/stats/utils/genCombinations.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/stats/utils/genCombinations.c",
"max_line_length": 70,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/stats/utils/genCombinations.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": 1104,
"size": 3355
} |
static char help[] =
"DMPlex mesh test suggested by Matt Knepley on petsc-users 11/9/21.\n"
"Shows DMPlex is more capable at the command line than I thought.\n\n";
/*
running with the -dm_view hdf5 seems to require a library I don't have:
mpiexec -n 2 ./meshtest -dm_plex_shape sphere -dm_refine_pre 3 -dm_extrude 5 -dm_plex_transform_extrude_thickness 0.1 -dm_distribute -dm_view hdf5:mesh.h5
this runs without complaint:
mpiexec -n 2 ./meshtest -dm_plex_shape sphere -dm_refine_pre 3 -dm_extrude 5 -dm_plex_transform_extrude_thickness 0.1 -dm_distribute -dm_view
*/
#include <petsc.h>
int main(int argc, char **argv)
{
DM dm;
PetscErrorCode ierr;
ierr = PetscInitialize(&argc, &argv, NULL, help); if (ierr) return ierr;
ierr = DMCreate(PETSC_COMM_WORLD, &dm); CHKERRQ(ierr);
ierr = DMSetType(dm, DMPLEX); CHKERRQ(ierr);
ierr = DMSetFromOptions(dm); CHKERRQ(ierr);
ierr = DMViewFromOptions(dm, NULL, "-dm_view"); CHKERRQ(ierr);
ierr = DMDestroy(&dm);CHKERRQ(ierr);
return PetscFinalize();
} | {
"alphanum_fraction": 0.7322297955,
"avg_line_length": 38.037037037,
"ext": "c",
"hexsha": "4f8a5f1ed0483fcb25c93bddb3945e2d4848ca28",
"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": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bueler/p4pdes-next",
"max_forks_repo_path": "c/dmplex/meshtest.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "bueler/p4pdes-next",
"max_issues_repo_path": "c/dmplex/meshtest.c",
"max_line_length": 154,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bueler/p4pdes-next",
"max_stars_repo_path": "c/dmplex/meshtest.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 317,
"size": 1027
} |
/**
* Simple and fast kmeans-implementation making use of multithreading.
*
* Author: Anders Bennehag
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Anders Bennehag
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <pthread.h>
#include <assert.h>
#include <gsl/gsl_rng.h>
#include "fastkmeans/fastkmeans.h"
typedef enum {
SUCCESS=0,
ALLOCATION_ERROR,
} fkm_error;
typedef enum {
WAIT,
RELEASED,
EXIT,
} barrier_status;
typedef struct {
const gsl_matrix* points;
gsl_matrix* clusters;
const size_t num_points;
const size_t dim;
const size_t k;
unsigned* owner_of;
} targs;
typedef struct {
pthread_mutex_t lock;
pthread_cond_t cond;
int count;
int goal;
barrier_status status;
} tbarrier;
typedef struct {
targs* args;
size_t thread_id;
pthread_t pthread_id;
size_t num_threads;
tbarrier* bar_start;
tbarrier* bar_finish;
} thread_meta;
typedef struct {
thread_meta* threads;
const size_t num_threads;
tbarrier bar_start;
tbarrier bar_finish;
} thread_pool;
int fkm_clusters_assignment(const thread_pool* tpool);
double fkm_clusters_update(const targs* args);
double fkm_matrix_diff(gsl_matrix* a, gsl_matrix* b);
int fkm_threads_init(thread_pool* tpool);
int fkm_threads_join(thread_pool* tpool);
int barrier_finish(tbarrier* bar);
int fkm_kmeans(const gsl_matrix* points, gsl_matrix* clusters,
size_t max_iter, int num_threads) {
if (num_threads<0) {
printf("Invalid number of threads\n");
return 1;
}
size_t num_points = points->size1;
unsigned owner_of[num_points];
targs args = {
.points=points,
.clusters=clusters,
.num_points=num_points,
.dim=points->size2,
.k=clusters->size1,
.owner_of=owner_of,
};
thread_meta tmeta[num_threads];
thread_pool tpool = {
.num_threads=num_threads,
.threads=tmeta,
.bar_start={
.lock=PTHREAD_MUTEX_INITIALIZER,
.cond=PTHREAD_COND_INITIALIZER,
.goal=num_threads+1,
},
.bar_finish={
.lock=PTHREAD_MUTEX_INITIALIZER,
.cond=PTHREAD_COND_INITIALIZER,
.goal=num_threads+1,
},
};
for (int i=0; i<num_threads; ++i) {
tmeta[i].args = &args;
tmeta[i].pthread_id = 0;
tmeta[i].thread_id = i;
tmeta[i].num_threads = num_threads;
tmeta[i].bar_start=&tpool.bar_start;
tmeta[i].bar_finish=&tpool.bar_finish;
}
fkm_threads_init(&tpool);
gsl_rng* rng = gsl_rng_alloc(gsl_rng_mt19937);
gsl_rng_set(rng, time(NULL));
// Randomize which center each point belongs to
for (size_t p=0; p < args.num_points; ++p) {
// TODO: Make sure every cluster gets assigned
owner_of[p] = gsl_rng_uniform_int(rng, args.k);
/*FKM_DEBUGFMT("Made %u owner of %lu", owner_of[p], p);*/
}
// Initiate clusters to random point in input
for (size_t m=0; m<args.k; m++) {
size_t rand_p = gsl_rng_uniform_int(rng, args.num_points);
for (size_t j=0; j<args.dim; ++j) {
double val = gsl_matrix_get(points,
rand_p,
j);
gsl_matrix_set(clusters, m, j, val);
}
}
for (size_t it=0; it<max_iter; ++it) {
FKM_DEBUGFMT("iter %lu num_points %lu dim %lu, k %lu num_threads %i",
it, args.num_points, args.dim, args.k, num_threads);
/*for (size_t p=0; p<num_points;++p) {*/
/*printf("%lu:%u ", p, owner_of[p]);*/
/*}*/
/*printf("\n");*/
fkm_clusters_assignment(&tpool);
double diff = fkm_clusters_update(&args);
FKM_DEBUGFMT("Diff: %f", diff);
if (fabs(diff) < 1e-10) {
FKM_DEBUG("Break since no progress");
break;
}
}
barrier_finish(&tpool.bar_start);
int err = fkm_threads_join(&tpool);
return 0;
}
int barrier_wait(tbarrier* bar) {
pthread_mutex_lock(&bar->lock);
FKM_DEBUGFMT("barrier_wait: count:%i goal:%i status:%i", bar->count,
bar->goal,
bar->status);
assert(bar->goal > 0);
bar->count += 1;
if (bar->goal == bar->count) {
bar->status = RELEASED;
bar->count = 0;
FKM_DEBUG("Goal reached in barrier, broadcasting release");
pthread_cond_broadcast(&bar->cond);
pthread_mutex_unlock(&bar->lock);
return 0;
}
pthread_mutex_unlock(&bar->lock);
for (;;) {
pthread_cond_wait(&bar->cond, &bar->lock);
if (bar->status == RELEASED) {
FKM_DEBUG("Barrier released");
pthread_mutex_unlock(&bar->lock);
return 0;
} else if (bar->status == EXIT) {
FKM_DEBUG("Barrier signals FINISHED");
pthread_mutex_unlock(&bar->lock);
return 1;
} else {
// Spurious wakeup
FKM_DEBUG("Spurious wakeup");
}
}
}
int barrier_finish(tbarrier* bar) {
int err = pthread_mutex_lock(&bar->lock);
if (err) {
FKM_ERROR("Could not acquire mutex");
return 1;
}
bar->status = EXIT;
err = pthread_mutex_unlock(&bar->lock);
if (err) {
FKM_ERROR("Could not release mutex");
return 1;
}
err = pthread_cond_broadcast(&bar->cond);
if (err) {
FKM_ERROR("Could not broadcast cond-variable");
return 1;
}
return 0;
}
int fkm_clusters_assignment_single(targs* args,
size_t offset,
size_t stride);
void* fkm_thread_manage(void* data) {
thread_meta* tmeta = data;
targs* args = tmeta->args;
int stop=0;
for (;;) {
stop = barrier_wait(tmeta->bar_start);
if (stop) {
return 0;
}
fkm_clusters_assignment_single(args,
tmeta->thread_id,
tmeta->num_threads);
stop = barrier_wait(tmeta->bar_finish);
if (stop) {
return 0;
}
}
}
int fkm_clusters_assignment_single(targs* args,
size_t offset,
size_t stride) {
for (size_t p=offset; p<args->num_points; p+=stride) {
double min_err = 1e308;
for (size_t m=0; m<args->k; ++m) {
double err = 0;
for (size_t j=0; j<args->dim; ++j) {
double a = fabs(gsl_matrix_get(args->clusters, m, j)
- gsl_matrix_get(args->points, p, j));
err += a*a;
}
if (err < min_err) {
min_err = err;
args->owner_of[p] = m;
}
}
}
return 0;
}
int fkm_threads_init(thread_pool* tpool) {
for (size_t thr=0; thr<tpool->num_threads;++thr) {
thread_meta* tdata = &tpool->threads[thr];
int err = pthread_create(&tdata->pthread_id,
NULL,
&fkm_thread_manage,
tdata);
if (err) {
FKM_ERRORFMT("pthread_create-error %i", err);
return 1;
}
}
return 0;
}
int fkm_threads_join(thread_pool* tpool) {
for (size_t thr=0; thr<tpool->num_threads;++thr) {
thread_meta* tdata = &tpool->threads[thr];
int err = pthread_join(tdata->pthread_id, NULL);
if (err) {
FKM_ERRORFMT("pthread_join-error %i", err);
}
return 1;
}
return 0;
}
int fkm_clusters_assignment(const thread_pool* tpool) {
tbarrier* bar_start = tpool->threads[0].bar_start;
FKM_DEBUGFMT("bar_start: count:%i goal:%i status:%i", bar_start->count,
bar_start->goal,
bar_start->status);
int err = barrier_wait(bar_start);
if (err) {
FKM_ERROR("barrier_wait failed");
return 1;
}
tbarrier* bar_finish = tpool->threads[0].bar_finish;
FKM_DEBUGFMT("bar_finish: count:%i goal:%i status:%i", bar_finish->count,
bar_finish->goal,
bar_finish->status);
err = barrier_wait(tpool->threads[0].bar_finish);
if (err) {
FKM_ERROR("barrier_wait failed");
return 1;
}
return 0;
}
/**
* Update clusters.
*
*
*/
double fkm_clusters_update(const targs* args) {
/*printf("DEBUG: num_points %lu dim %lu, k %lu\n", num_points, dim, k);*/
unsigned cluster_size[args->k];
for (size_t m=0; m<args->k; ++m) {
cluster_size[m] = 0;
}
gsl_matrix* mean_sums = gsl_matrix_calloc(args->k, args->dim);
for (size_t p=0; p<args->num_points; ++p) {
unsigned m = args->owner_of[p];
assert(m < args->k);
cluster_size[m] += 1;
/*LOGFMT("p:%lu belongs to %u. Children %u", p, m, cluster_size[m]);*/
for (size_t j=0; j<args->dim; ++j) {
double val = gsl_matrix_get(mean_sums, m, j)
+ gsl_matrix_get(args->points, p, j);
gsl_matrix_set(mean_sums, m, j, val);
}
}
double diff = 0;
for (size_t m=0; m<args->k; ++m) {
/*printf("Updating cluster %lu to", m);*/
for (size_t j=0; j<args->dim; ++j) {
double val = gsl_matrix_get(mean_sums, m, j);
val /= cluster_size[m];
diff += val - gsl_matrix_get(args->clusters, m, j);
gsl_matrix_set(args->clusters, m, j, val);
/*printf(" %u %f", cluster_size[m], val);*/
}
/*printf("\n");*/
}
gsl_matrix_free(mean_sums);
return diff;
}
typedef double (*elem_func)(double, double);
double fkm_matrix_elem_func(gsl_matrix* a, gsl_matrix* b, elem_func f) {
double v = 0;
for (size_t i=0; i<a->block->size; ++i) {
v += f(a->block->data[i], b->block->data[i]);
}
return v;
}
double diff(double a, double b) {
return fabs(a - b);
}
double fkm_matrix_diff(gsl_matrix* a, gsl_matrix* b) {
return fkm_matrix_elem_func(a, b, diff);
}
void print_matrix(gsl_matrix* a) {
for (size_t i=0; i<5 && i<a->block->size; ++i) {
printf("%lu: %f\n", i, a->block->data[i]);
}
}
gsl_matrix* fkm_matrix_load(FILE* fin) {
size_t rows, cols;
int err = fscanf(fin, "%lu %lu", &rows, &cols);
if (err == EOF) {
printf("ERROR: Could not parse matrix dimensions\n");
return 0;
}
gsl_matrix* mat = gsl_matrix_alloc(rows, cols);
err = gsl_matrix_fscanf(fin, mat);
if (err) {
printf("ERROR: Could not parse matrix data\n");
return 0;
}
printf("Loaded %lu rows, %lu columns matrix\n", rows, cols);
return mat;
}
int fkm_matrix_save(FILE* fout, gsl_matrix* mat) {
int err = 0;
fprintf(fout, "%zu %zu\n", mat->size1, mat->size2);
for (size_t i=0; i<mat->block->size; ++i) {
if (i && i % mat->size2 == 0) {
err = fprintf(fout, "\n");
if (err<0) {
FKM_ERRORFMT("fprintf returned %i", err);
}
}
int err = fprintf(fout, "%f ", mat->block->data[i]);
if (err<0) {
FKM_ERRORFMT("fprintf returned %i", err);
}
}
return err;
}
| {
"alphanum_fraction": 0.5416774194,
"avg_line_length": 29.0625,
"ext": "c",
"hexsha": "e0b39292c9e4758e3edad4c0e329928f0811eb62",
"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": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "PureW/fast-kmeans",
"max_forks_repo_path": "src/fastkmeans/fastkmeans.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd",
"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": "PureW/fast-kmeans",
"max_issues_repo_path": "src/fastkmeans/fastkmeans.c",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "25e1a923ec08c1f3f7c15cf4f4c6b9f616ab14dd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "PureW/fast-kmeans",
"max_stars_repo_path": "src/fastkmeans/fastkmeans.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3056,
"size": 11625
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <mcbp/protocol/opcode.h>
#include <mcbp/protocol/request.h>
#include <mcbp/protocol/response.h>
#include <mcbp/protocol/status.h>
#include <gsl/gsl>
namespace cb {
namespace mcbp {
/**
* FrameBuilder allows you to build up a request / response frame in
* a provided memory area. It provides helper methods which makes sure
* that the fields is formatted in the correct byte order etc.
*/
template <typename T>
class FrameBuilder {
public:
FrameBuilder(cb::byte_buffer backing) : buffer(backing) {
checkSize(sizeof(T));
std::fill(backing.begin(), backing.begin() + sizeof(T), 0);
}
T* getFrame() {
return reinterpret_cast<T*>(buffer.data());
}
void setMagic(Magic magic) {
getFrame()->setMagic(magic);
}
void setOpcode(ClientOpcode opcode) {
getFrame()->setOpcode(opcode);
}
void setOpcode(ServerOpcode opcode) {
getFrame()->setOpcode(opcode);
}
void setDatatype(Datatype datatype) {
getFrame()->setDatatype(datatype);
}
void setVBucket(Vbid value) {
getFrame()->setVBucket(value);
}
void setOpaque(uint32_t opaque) {
getFrame()->setOpaque(opaque);
}
void setCas(uint64_t val) {
getFrame()->setCas(val);
}
/**
* Insert the provided extras in the appropriate location (right after
* the header) and updates the extlen and bodylen field.
*
* @param extras the extra field to insert
*/
void setExtras(cb::const_byte_buffer extras) {
auto* req = getFrame();
// can we fit the extras?
checkSize(req->getExtlen(), extras.size());
// Start by moving key and body to where it belongs
const auto old_body_size = req->getBodylen() - req->getExtlen();
auto* start = buffer.data() + sizeof(*req);
uint8_t* old_start = start + req->getExtlen();
uint8_t* new_start = start + extras.size();
memmove(new_start, old_start, old_body_size);
// Insert the new extras:
std::copy(extras.begin(), extras.end(), start);
req->setExtlen(uint8_t(extras.size()));
req->setBodylen(gsl::narrow<uint32_t>(old_body_size + extras.size()));
}
/**
* Insert the provided key in the appropriate location (right after
* the extras field) and updates the keylen and bodylen field.
*
* @param key the key field to insert
*/
void setKey(cb::const_byte_buffer key) {
auto* req = getFrame();
checkSize(req->getKeylen(), key.size());
// Start by moving the body to where it belongs
const auto old_body_size =
req->getBodylen() - req->getKeylen() - req->getExtlen();
auto* start = buffer.data() + sizeof(*req) + req->getExtlen();
uint8_t* old_start = start + req->getKeylen();
uint8_t* new_start = start + key.size();
memmove(new_start, old_start, old_body_size);
// Insert the new key:
std::copy(key.begin(), key.end(), start);
req->setKeylen(uint16_t(key.size()));
req->setBodylen(gsl::narrow<uint32_t>(old_body_size + req->getExtlen() +
key.size()));
}
/**
* Insert the provided value in the appropriate location (right after
* the key field) and update the bodylen field.
*
* @param value the value to insert into the body
*/
void setValue(cb::const_byte_buffer value) {
auto* req = getFrame();
const auto old_size =
req->getBodylen() - req->getKeylen() - req->getExtlen();
checkSize(old_size, value.size());
auto* start = buffer.data() + sizeof(*req) + req->getExtlen() +
req->getKeylen();
std::copy(value.begin(), value.end(), start);
req->setBodylen(gsl::narrow<uint32_t>(value.size() + req->getKeylen() +
req->getExtlen()));
}
/**
* Try to validate the underlying packet
*/
void validate() {
getFrame()->isValid();
}
protected:
/**
* check that the requested size fits into the buffer
*
* @param size The total requested size (including header)
*/
void checkSize(size_t size) {
if (size > buffer.size()) {
throw std::logic_error(
"FrameBuilder::checkSize: too big to fit in buffer");
}
}
/**
* check if there is room in the buffer to replace the field with
* one with a different size
*
* @param oldfield
* @param newfield
*/
void checkSize(size_t oldfield, size_t newfield) {
checkSize(sizeof(T) + getFrame()->getBodylen() - oldfield + newfield);
}
cb::byte_buffer buffer;
};
/**
* Specialized class to build a Request
*/
class RequestBuilder : public FrameBuilder<Request> {
public:
RequestBuilder(cb::byte_buffer backing) : FrameBuilder<Request>(backing) {
}
void setVbucket(Vbid vbucket) {
getFrame()->setVBucket(vbucket);
}
};
/**
* Specialized class to build a response
*/
class ResponseBuilder : public FrameBuilder<Response> {
public:
ResponseBuilder(cb::byte_buffer backing) : FrameBuilder<Response>(backing) {
}
void setStatus(Status status) {
getFrame()->setStatus(status);
}
};
} // namespace mcbp
} // namespace cb
| {
"alphanum_fraction": 0.6117012584,
"avg_line_length": 29.9950980392,
"ext": "h",
"hexsha": "b0485ef0ea4119f4052b71d541de7263e1ef172d",
"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": "24d4546220f3181678d7eadedc68b4ea088d3538",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "t3rm1n4l/kv_engine",
"max_forks_repo_path": "include/mcbp/protocol/framebuilder.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538",
"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": "t3rm1n4l/kv_engine",
"max_issues_repo_path": "include/mcbp/protocol/framebuilder.h",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "24d4546220f3181678d7eadedc68b4ea088d3538",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "t3rm1n4l/kv_engine",
"max_stars_repo_path": "include/mcbp/protocol/framebuilder.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1457,
"size": 6119
} |
/* gsl_math.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATH_H__
#define __GSL_MATH_H__
#include <math.h>
#include <gsl/gsl_sys.h>
#include <gsl/gsl_machine.h>
#include <gsl/gsl_precision.h>
#include <gsl/gsl_nan.h>
#include <gsl/gsl_pow_int.h>
#ifndef M_E
#define M_E 2.71828182845904523536028747135 /* e */
#endif
#ifndef M_LOG2E
#define M_LOG2E 1.44269504088896340735992468100 /* log_2 (e) */
#endif
#ifndef M_LOG10E
#define M_LOG10E 0.43429448190325182765112891892 /* log_10 (e) */
#endif
#ifndef M_SQRT2
#define M_SQRT2 1.41421356237309504880168872421 /* sqrt(2) */
#endif
#ifndef M_SQRT1_2
#define M_SQRT1_2 0.70710678118654752440084436210 /* sqrt(1/2) */
#endif
#ifndef M_SQRT3
#define M_SQRT3 1.73205080756887729352744634151 /* sqrt(3) */
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846264338328 /* pi */
#endif
#ifndef M_PI_2
#define M_PI_2 1.57079632679489661923132169164 /* pi/2 */
#endif
#ifndef M_PI_4
#define M_PI_4 0.78539816339744830961566084582 /* pi/4 */
#endif
#ifndef M_SQRTPI
#define M_SQRTPI 1.77245385090551602729816748334 /* sqrt(pi) */
#endif
#ifndef M_2_SQRTPI
#define M_2_SQRTPI 1.12837916709551257389615890312 /* 2/sqrt(pi) */
#endif
#ifndef M_1_PI
#define M_1_PI 0.31830988618379067153776752675 /* 1/pi */
#endif
#ifndef M_2_PI
#define M_2_PI 0.63661977236758134307553505349 /* 2/pi */
#endif
#ifndef M_LN10
#define M_LN10 2.30258509299404568401799145468 /* ln(10) */
#endif
#ifndef M_LN2
#define M_LN2 0.69314718055994530941723212146 /* ln(2) */
#endif
#ifndef M_LNPI
#define M_LNPI 1.14472988584940017414342735135 /* ln(pi) */
#endif
#ifndef M_EULER
#define M_EULER 0.57721566490153286060651209008 /* Euler constant */
#endif
#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
/* other needlessly compulsive abstractions */
#define GSL_IS_ODD(n) ((n) & 1)
#define GSL_IS_EVEN(n) (!(GSL_IS_ODD(n)))
#define GSL_SIGN(x) ((x) >= 0.0 ? 1 : -1)
/* Return nonzero if x is a real number, i.e. non NaN or infinite. */
#define GSL_IS_REAL(x) (gsl_finite(x))
/* Define MAX and MIN macros/functions if they don't exist. */
/* plain old macros for general use */
#define GSL_MAX(a,b) ((a) > (b) ? (a) : (b))
#define GSL_MIN(a,b) ((a) < (b) ? (a) : (b))
/* function versions of the above, in case they are needed */
double gsl_max (double a, double b);
double gsl_min (double a, double b);
/* inline-friendly strongly typed versions */
#ifdef HAVE_INLINE
extern inline int GSL_MAX_INT (int a, int b);
extern inline int GSL_MIN_INT (int a, int b);
extern inline double GSL_MAX_DBL (double a, double b);
extern inline double GSL_MIN_DBL (double a, double b);
extern inline long double GSL_MAX_LDBL (long double a, long double b);
extern inline long double GSL_MIN_LDBL (long double a, long double b);
extern inline int
GSL_MAX_INT (int a, int b)
{
return GSL_MAX (a, b);
}
extern inline int
GSL_MIN_INT (int a, int b)
{
return GSL_MIN (a, b);
}
extern inline double
GSL_MAX_DBL (double a, double b)
{
return GSL_MAX (a, b);
}
extern inline double
GSL_MIN_DBL (double a, double b)
{
return GSL_MIN (a, b);
}
extern inline long double
GSL_MAX_LDBL (long double a, long double b)
{
return GSL_MAX (a, b);
}
extern inline long double
GSL_MIN_LDBL (long double a, long double b)
{
return GSL_MIN (a, b);
}
#else
#define GSL_MAX_INT(a,b) GSL_MAX(a,b)
#define GSL_MIN_INT(a,b) GSL_MIN(a,b)
#define GSL_MAX_DBL(a,b) GSL_MAX(a,b)
#define GSL_MIN_DBL(a,b) GSL_MIN(a,b)
#define GSL_MAX_LDBL(a,b) GSL_MAX(a,b)
#define GSL_MIN_LDBL(a,b) GSL_MIN(a,b)
#endif /* HAVE_INLINE */
/* Definition of an arbitrary function with parameters */
struct gsl_function_struct
{
double (* function) (double x, void * params);
void * params;
};
typedef struct gsl_function_struct gsl_function ;
#define GSL_FN_EVAL(F,x) (*((F)->function))(x,(F)->params)
/* Definition of an arbitrary function returning two values, r1, r2 */
struct gsl_function_fdf_struct
{
double (* f) (double x, void * params);
double (* df) (double x, void * params);
void (* fdf) (double x, void * params, double * f, double * df);
void * params;
};
typedef struct gsl_function_fdf_struct gsl_function_fdf ;
#define GSL_FN_FDF_EVAL_F(FDF,x) (*((FDF)->f))(x,(FDF)->params)
#define GSL_FN_FDF_EVAL_DF(FDF,x) (*((FDF)->df))(x,(FDF)->params)
#define GSL_FN_FDF_EVAL_F_DF(FDF,x,y,dy) (*((FDF)->fdf))(x,(FDF)->params,(y),(dy))
/* Definition of an arbitrary vector-valued function with parameters */
struct gsl_function_vec_struct
{
int (* function) (double x, double y[], void * params);
void * params;
};
typedef struct gsl_function_vec_struct gsl_function_vec ;
#define GSL_FN_VEC_EVAL(F,x,y) (*((F)->function))(x,y,(F)->params)
__END_DECLS
#endif /* __GSL_MATH_H__ */
| {
"alphanum_fraction": 0.7043343653,
"avg_line_length": 25.6123348018,
"ext": "h",
"hexsha": "7f9a39150fcdbcfab4f091440a0cbef95f264a3f",
"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/gsl_math.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/gsl_math.h",
"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/gsl_math.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 1772,
"size": 5814
} |
/*
* GENANN - Minimal C Artificial Neural Network
*
* Copyright (c) 2015-2018 Lewis Van Winkle
*
* http://CodePlea.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgement in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
*/
#include "genann.h"
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cblas.h>
#ifndef genann_act
#define genann_act_hidden genann_act_hidden_indirect
#define genann_act_output genann_act_output_indirect
#else
#define genann_act_hidden genann_act
#define genann_act_output genann_act
#endif
#define LOOKUP_SIZE 4096
double genann_act_hidden_indirect(const struct genann *ann, double a) {
return ann->activation_hidden(ann, a);
}
double genann_act_output_indirect(const struct genann *ann, double a) {
return ann->activation_output(ann, a);
}
const double sigmoid_dom_min = -15.0;
const double sigmoid_dom_max = 15.0;
double interval;
double lookup[LOOKUP_SIZE];
#ifdef __GNUC__
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#define unused __attribute__((unused))
#else
#define likely(x) x
#define unlikely(x) x
#define unused
#pragma warning(disable : 4996) /* For fscanf */
#endif
double genann_act_sigmoid(const genann *ann unused, double a) {
if (a < -45.0) return 0;
if (a > 45.0) return 1;
return 1.0 / (1 + exp(-a));
}
void genann_init_sigmoid_lookup(const genann *ann) {
const double f = (sigmoid_dom_max - sigmoid_dom_min) / LOOKUP_SIZE;
int i;
interval = LOOKUP_SIZE / (sigmoid_dom_max - sigmoid_dom_min);
for (i = 0; i < LOOKUP_SIZE; ++i) {
lookup[i] = genann_act_sigmoid(ann, sigmoid_dom_min + f * i);
}
}
double genann_act_sigmoid_cached(const genann *ann unused, double a) {
assert(!isnan(a));
if (a < sigmoid_dom_min) return lookup[0];
if (a >= sigmoid_dom_max) return lookup[LOOKUP_SIZE - 1];
size_t j = (size_t)((a-sigmoid_dom_min)*interval+0.5);
/* Because doubleing point... */
if (unlikely(j >= LOOKUP_SIZE)) return lookup[LOOKUP_SIZE - 1];
return lookup[j];
}
double genann_act_linear(const struct genann *ann unused, double a) {
return a;
}
double genann_act_threshold(const struct genann *ann unused, double a) {
return a > 0;
}
genann *genann_init(int inputs, int hidden_layers, int hidden, int outputs) {
if (hidden_layers < 0) return 0;
if (inputs < 1) return 0;
if (outputs < 1) return 0;
if (hidden_layers > 0 && hidden < 1) return 0;
const int hidden_weights = hidden_layers ? (inputs+1) * hidden + (hidden_layers-1) * (hidden+1) * hidden : 0;
const int output_weights = (hidden_layers ? (hidden+1) : (inputs+1)) * outputs;
const int total_weights = (hidden_weights + output_weights);
const int total_neurons = (inputs + hidden * hidden_layers + outputs);
/* Allocate extra size for weights, outputs, and deltas. */
const int size = sizeof(genann) + sizeof(double) * (total_weights + total_neurons + (total_neurons - inputs));
genann *ret = malloc(size);
if (!ret) return 0;
ret->inputs = inputs;
ret->hidden_layers = hidden_layers;
ret->hidden = hidden;
ret->outputs = outputs;
ret->total_weights = total_weights;
ret->total_neurons = total_neurons;
/* Set pointers. */
ret->weight = (double*)((char*)ret + sizeof(genann));
ret->output = ret->weight + ret->total_weights;
ret->delta = ret->output + ret->total_neurons;
genann_randomize(ret);
ret->activation_hidden = genann_act_sigmoid_cached;
ret->activation_output = genann_act_sigmoid_cached;
genann_init_sigmoid_lookup(ret);
return ret;
}
genann *genann_read(FILE *in) {
int inputs, hidden_layers, hidden, outputs;
int rc;
errno = 0;
rc = fscanf(in, "%d %d %d %d", &inputs, &hidden_layers, &hidden, &outputs);
if (rc < 4 || errno != 0) {
perror("fscanf");
return NULL;
}
genann *ann = genann_init(inputs, hidden_layers, hidden, outputs);
int i;
for (i = 0; i < ann->total_weights; ++i) {
errno = 0;
rc = fscanf(in, " %le", ann->weight + i);
if (rc < 1 || errno != 0) {
perror("fscanf");
genann_free(ann);
return NULL;
}
}
return ann;
}
genann *genann_copy(genann const *ann) {
const int size = sizeof(genann) + sizeof(double) * (ann->total_weights + ann->total_neurons + (ann->total_neurons - ann->inputs));
genann *ret = malloc(size);
if (!ret) return 0;
memcpy(ret, ann, size);
/* Set pointers. */
ret->weight = (double*)((char*)ret + sizeof(genann));
ret->output = ret->weight + ret->total_weights;
ret->delta = ret->output + ret->total_neurons;
return ret;
}
void genann_randomize(genann *ann) {
int i;
for (i = 0; i < ann->total_weights; ++i) {
double r = GENANN_RANDOM();
/* Sets weights from -0.5 to 0.5. */
ann->weight[i] = r - 0.5;
}
}
void genann_free(genann *ann) {
/* The weight, output, and delta pointers go to the same buffer. */
free(ann);
}
double const *genann_run(genann const *ann, double const *inputs) {
//Copy the weights into a more convenient variable
double const *w = ann->weight;
//Initialize the output vector to point at the second layer of neurons
double *o = ann->output + ann->inputs;
//Initialize the input vector to point at the first layer of neurons
double const *i = ann->output;
/* Copy the inputs to the scratch area, where we also store each neuron's
* output, for consistency. This way the first layer isn't a special case. */
memcpy(ann->output, inputs, sizeof(double) * ann->inputs);
int h, j, k;
if (!ann->hidden_layers) {
double *ret = o;
for (j = 0; j < ann->outputs; ++j) {
double sum = *w++ * -1.0;
for (k = 0; k < ann->inputs; ++k) {
sum += *w++ * i[k];
}
*o++ = genann_act_output(ann, sum);
}
return ret;
}
/* Figure input layer */
for (j = 0; j < ann->hidden; ++j) {
double sum = *w++ * -1.0;
for (k = 0; k < ann->inputs; ++k) {
sum += *w++ * i[k];
}
*o++ = genann_act_hidden(ann, sum);
}
i += ann->inputs;
/////////////////////////////////
// TODO: 1 GEMV using BLAS //
/////////////////////////////////
/*
Function description:
Activates each neuron in the input layer based on an input vector.
Propagates these activations through the network.
Variables:
ann: The neural network
ann->weights: The edge and neuron weights for all layers
ann->inputs: The number of neurons in the input layer
ann->hidden: The number of neurons in the hidden layers
ann->hidden_layers: The number of hidden layers in the network
ann->output: The neuron activations for the whole network, incluing input, hidden and final layer.
inputs: The input vector
w: Points at ann->weights
o: Points at the layer of ann->output we are currently writing to
i: Points to the layer of ann->output we are currently using as input.
i.e. the previous layer.
When the function returns, ann->output contains the final result.
*/
/* Comment from original source: Figure hidden layers, if any. */
//These are the dimensions of the square weight matrix
int m = ann->hidden;
int n = ann->hidden;
//In addition to n edge weights, each neuron has one value (bias) associated with it.
//This value is *also* saved in w, meaning the complete matrix has (n+1)*m elements.
//This value is always multiplied by -1, which we make room for in a copy of the input vector.
double* temp_i = malloc( (ann->hidden+1) * sizeof(double) );
double* sums = calloc((ann->hidden+1), sizeof(double));
for (h = 1; h < ann->hidden_layers; ++h) {
//Copyyng the input vector and setting the first value to -1 as described above.
temp_i[0] = -1.0;
memcpy(temp_i+1, i, n*sizeof(double));
////////////////////////////////////////////////////////////
// Decompose and replace this double for loop with GEMV call
for (j = 0; j < ann->hidden; ++j) {
for (k = 0; k < ann->hidden+1; ++k) {
sums[j] += w[k + j*(ann->hidden+1)] * temp_i[k];
}
o[j] = genann_act_hidden(ann, sums[j]);
}
////////////////////////////////////////////////////////////
w += (n + 1) * m;
o += m;
i += m;
}
free(temp_i);
free(sums);
/////////////////////////////////
// TODO 1 END //
/////////////////////////////////
double const *ret = o;
/* Figure output layer. */
for (j = 0; j < ann->outputs; ++j) {
double sum = *w++ * -1.0;
for (k = 0; k < ann->hidden; ++k) {
sum += *w++ * i[k];
}
*o++ = genann_act_output(ann, sum);
}
/* Sanity check that we used all weights and wrote all outputs. */
assert(w - ann->weight == ann->total_weights);
assert(o - ann->output == ann->total_neurons);
return ret;
}
void genann_train(genann const *ann, double const *inputs, double const *desired_outputs, double learning_rate) {
/* To begin with, we must run the network forward. */
genann_run(ann, inputs);
int h, j, k;
/*
TDT4200 comment: This lonesome curly bracket starts a new scope.
That means no variables declared within will be
visible outside outside it (that is, o, d and t).
That also means the names can safely be re-used later.
*/
{ /* First set the output layer deltas. */
double const *o = ann->output + ann->inputs + ann->hidden * ann->hidden_layers; /* First output. */
double *d = ann->delta + ann->hidden * ann->hidden_layers; /* First delta. */
double const *t = desired_outputs; /* First desired output. */
/* Set output layer deltas. */
if (genann_act_output == genann_act_linear ||
ann->activation_output == genann_act_linear) {
for (j = 0; j < ann->outputs; ++j) {
*d++ = *t++ - *o++;
}
} else {
for (j = 0; j < ann->outputs; ++j) {
*d++ = (*t - *o) * *o * (1.0 - *o);
++o; ++t;
}
}
}
/* Set hidden layer deltas, start on last layer and work backwards. */
/* Note that loop is skipped in the case of hidden_layers == 0. */
for (h = ann->hidden_layers - 1; h >= 0; --h) {
/* Find first output and delta in this layer. */
double const *o = ann->output + ann->inputs + (h * ann->hidden);
double *d = ann->delta + (h * ann->hidden);
/* Find first delta in following layer (which may be hidden or output). */
double const * const dd = ann->delta + ((h+1) * ann->hidden);
/* Find first weight in following layer (which may be hidden or output). */
double const * const ww = ann->weight + ((ann->inputs+1) * ann->hidden) + ((ann->hidden+1) * ann->hidden * (h));
/////////////////////////////////
// TODO: 2 GEMV using BLAS //
/////////////////////////////////
/*
Function description:
First, run an input through the network (see TODO 1).
Then, starting at the output layer and running backwards, determine the
deltas, the differences between the desired activation and actual
activation of each neuron.
Variables:
ann: The artificial neural network, same as in TODO 1. \
ann->delta: An area of memory as big as ann->output.
When function returns, stores difference between desired
output and actual output.
h: The index of the current layer. Starting at the output layer and
going backwards.
o: The actual output of the current layer, produced by TODO 1 function.
d: The delta vector of the current layer, this is what we're calculating
dd: The delta vector of the *previous* layer, at index (h+1).
ww: The edge weights going from the previous layer and the current one.
Note 1: We're playing fast and loose with the term "difference" here.
It is not strictly a [desired]-[actual] calculation, but can be
conceptually thought of as a difference.
Note 2: We say "previous" layer meaning the layer involved in the
previous calculation. Because we are going backwards, this is,
strictly speaking, the "following" layer, which is what it is
called in the source code comments.
*/
// TODO 2.a: Define the m and n dimension of the delta matrix
// Hint: Look at the double for loop
int m = 0;
int n = 0;
//A temporary vector to store the propagated delta from the previuos layer.
double* delta = calloc(ann->hidden, sizeof(double));
// TODO 2.b: Decompose and implement GEMV BLAS call for the code
// Hint: Think about how ww is offset from its original address.
// You will need pointer arithmetic for the BLAS call
for (j = 0; j < ann->hidden; ++j) {
//We iterate up to the value ann->outputs if we are on the output layer,
//h == ann->hidden_layers-1, and to ann->hidden otherwise.
for (k = 0; k < (h == ann->hidden_layers-1 ? ann->outputs : ann->hidden); ++k) {
//Similarly to TODO 1, we add 1 to ann->hidden and j here as a
//consequence of how bias for each neuron is stored.
const int windex = k * (ann->hidden + 1) + (j + 1);
//Propagate the deltas from the previous layer backwards
//Using the weights between the layers and storing the result in "delta"
delta[j] += dd[k] * ww[windex];
}
//Calculate the actual new deltas for this layer
d[j] = o[j] * (1.0-o[j]) * delta[j];
}
free(delta);
/////////////////////////////////
// TODO 2 END //
/////////////////////////////////
}
/* Train the outputs. */
{
/* Find first output delta. */
double const *d = ann->delta + ann->hidden * ann->hidden_layers; /* First output delta. */
/* Find first weight to first output delta. */
double *w = ann->weight + (ann->hidden_layers
? ((ann->inputs+1) * ann->hidden + (ann->hidden+1) * ann->hidden * (ann->hidden_layers-1))
: (0));
/* Find first output in previous layer. */
double const * const i = ann->output + (ann->hidden_layers
? (ann->inputs + (ann->hidden) * (ann->hidden_layers-1))
: 0);
/* Set output layer weights. */
for (j = 0; j < ann->outputs; ++j) {
*w++ += *d * learning_rate * -1.0;
for (k = 1; k < (ann->hidden_layers ? ann->hidden : ann->inputs) + 1; ++k) {
*w++ += *d * learning_rate * i[k-1];
}
++d;
}
assert(w - ann->weight == ann->total_weights);
}
/* Train the hidden layers. */
for (h = ann->hidden_layers - 1; h >= 0; --h) {
/* Find first delta in this layer. */
double const *d = ann->delta + (h * ann->hidden);
/* Find first input to this layer. */
double const *i = ann->output + (h
? (ann->inputs + ann->hidden * (h-1))
: 0);
/* Find first weight to this layer. */
double *w = ann->weight + (h
? ((ann->inputs+1) * ann->hidden + (ann->hidden+1) * (ann->hidden) * (h-1))
: 0);
/////////////////////////////////
// TODO: 3 (Optional) Optimize //
/////////////////////////////////
for (j = 0; j < ann->hidden; ++j) {
*w++ += *d * learning_rate * -1.0;
for (k = 1; k < (h == 0 ? ann->inputs : ann->hidden) + 1; ++k) {
*w++ += *d * learning_rate * i[k-1];
}
++d;
}
/////////////////////////////////
// TODO 3 END //
/////////////////////////////////
}
}
void genann_write(genann const *ann, FILE *out) {
fprintf(out, "%d %d %d %d", ann->inputs, ann->hidden_layers, ann->hidden, ann->outputs);
int i;
for (i = 0; i < ann->total_weights; ++i) {
fprintf(out, " %.20e", ann->weight[i]);
}
}
| {
"alphanum_fraction": 0.5623373685,
"avg_line_length": 33.9961538462,
"ext": "c",
"hexsha": "3d3b31083b764800ca9cf0466cecef3e85fb71ec",
"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": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jorgstei/Datateknologi",
"max_forks_repo_path": "TDT4200/A3/genann.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e",
"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": "jorgstei/Datateknologi",
"max_issues_repo_path": "TDT4200/A3/genann.c",
"max_line_length": 134,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6fea7bf2c557cd93981c6996c7f4cca02f343d9e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jorgstei/Datateknologi",
"max_stars_repo_path": "TDT4200/A3/genann.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4526,
"size": 17678
} |
/* randist/poisson.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 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 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* The poisson distribution has the form
p(n) = (mu^n / n!) exp(-mu)
for n = 0, 1, 2, ... . The method used here is the one from Knuth. */
unsigned int
gsl_ran_poisson (const gsl_rng * r, double mu)
{
double emu;
double prod = 1.0;
unsigned int k = 0;
while (mu > 10)
{
unsigned int m = mu * (7.0 / 8.0);
double X = gsl_ran_gamma_int (r, m);
if (X >= mu)
{
return k + gsl_ran_binomial (r, mu / X, m - 1);
}
else
{
k += m;
mu -= X;
}
}
/* This following method works well when mu is small */
emu = exp (-mu);
do
{
prod *= gsl_rng_uniform (r);
k++;
}
while (prod > emu);
return k - 1;
}
void
gsl_ran_poisson_array (const gsl_rng * r, size_t n, unsigned int array[],
double mu)
{
size_t i;
for (i = 0; i < n; i++)
{
array[i] = gsl_ran_poisson (r, mu);
}
return;
}
double
gsl_ran_poisson_pdf (const unsigned int k, const double mu)
{
double p;
double lf = gsl_sf_lnfact (k);
p = exp (log (mu) * k - lf - mu);
return p;
}
| {
"alphanum_fraction": 0.6125301205,
"avg_line_length": 22.0744680851,
"ext": "c",
"hexsha": "34501f844d7b43ddfd52bddace0f132c8829233b",
"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/randist/poisson.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/randist/poisson.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/randist/poisson.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": 623,
"size": 2075
} |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "Bow\BaseBow.h"
#include "Tracking\TrackLocalMap.h"
#include "Image\AnalyzedImage.h"
#include <gsl\gsl>
#include <memory>
#include <vector>
namespace mage
{
// VI-C : LOCAL MAPPING - NEW MAP POINT CREATION
// create new map points for keyframe by triangulate ORB from connected keyframes KC in covisibility graph
void NewMapPointsCreation(
const BaseBow& bagOfWords,
const KeyframeProxy& Ki,
const PerCameraSettings& cameraSettings,
const NewMapPointsCreationSettings& newMapPointSettings,
const float scale,
thread_memory memory,
gsl::span<MappingKeyframe> Kcs,
std::vector<MapPointKeyframeAssociations>& newMapPoints);
// Carries the state, arguments, and cached computations through the NewMapPointsCreation operation.
// Because this struct carries the state, operations that use its contents may depend on prior
// operations to populate that content; in other words, any method that takes a NewMapPointsCreationState
// is expected to modify the state in such a way that it is ready for the next call.
// used internally by new map points creation
struct NewMapPointsCreationState
{
const BaseBow& BagOfWords;
const KeyframeProxy& Ki; // new keyframe
const MappingKeyframe* Kc; // connected keyframe
size_t KcKeypointDescriptorIdx; // index into the Kc analyzed image's keypoints/descriptors
size_t KiKeypointDescriptorIdx; // index into the Ki analyzed image's keypoints/descriptors
cv::Matx33f FundamentalMatrixKcToKi; // fundamental matrix Kc to Ki
cv::Matx33f FundamentalMatrixKiToKc; // fundamental matrix Ki to Kc
cv::Matx34f KiViewMatrix; // new keyframe matrix
cv::Matx33f KiCameraMatrix; // Camera Calibration for Ki
cv::Matx44f KiInverseViewMatrix; // new keyframe world matrix
cv::Matx34f KcViewMatrix; // connected keyframe matrix
cv::Matx33f KcCameraMatrix; // Camera Calibration for Kc
cv::Matx44f KcInverseViewMatrix; // connected keyframe world matrix
std::set<size_t> KiAssociatedDescriptors; // new keyframe associated descriptors
const float KiPyramidScale; // Pyramid Scale used when features were extracted of Ki
const float KiImageBorder; // Image Border for which no keypoints could have been extracted
const size_t KiNumLevels; // Number of levels used to extract features in Ki
const PerCameraSettings& CameraSettings;
const NewMapPointsCreationSettings& NewMapPointsCreationSettings;
const float CosMinParallax;
const float MapScale;
NewMapPointsCreationState(const BaseBow& bagofWords, const KeyframeProxy& keyFrameId, const PerCameraSettings& cameraSettings, const mage::NewMapPointsCreationSettings& newMapPointsCreationSettings, const float scale);
void SetKc(const MappingKeyframe& kc)
{
Kc = &kc;
KcInverseViewMatrix = Kc->GetPose().GetInverseViewMatrix();
KcViewMatrix = Kc->GetPose().GetViewMatrix();
KcCameraMatrix = Kc->GetAnalyzedImage()->GetUndistortedCalibration().GetCameraMatrix();
}
};
// tests whether a match should be turned into a mappoint, if so creates the new map point
// used internally by new map points creation
bool TryCreateNewAssociatedMapPointForMatch(
NewMapPointsCreationState& state,
std::vector<MapPointKeyframeAssociations>& keyframeAssociations);
// For each new map point created in CreateInitialAssociations()
// For each covisible keyframe that isn't already associated with this map point, attempt to
// match one of the unassociated descriptors of the keyframe with the map point. If you succeed,
// Create the association.
//
// This method modifies NewMapPointsCreationState and keyframeAssociations.
void LocallyAssociateNewAssociations(
NewMapPointsCreationState& state,
gsl::span<MappingKeyframe> covisibleKeyframes,
thread_memory memory,
std::vector<MapPointKeyframeAssociations>& keyframeAssociations);
// For each covisible keyframe, match all the unassociated descriptors in that keyframe
// to the unassociated descriptors in the current keyframe.
// For each resulting match (after confirming that the new keyframe descriptor involved
// has not been associated by a previous iteration), try to create a map point for the
// match.
//
// This method modifies the NewMapPointsCreationState and should leave it ready to be passed
// into LocallyAssociateNewAssociations(). It also modifies newMapPoints and
// keyframeAssociations.
void CreateInitialAssociations(
NewMapPointsCreationState& state,
gsl::span<MappingKeyframe> covisibleKeyframes,
std::vector<MapPointKeyframeAssociations>& newMapPoints,
int maxHammingDist,
int minHammingDifference,
ptrdiff_t maxFrameToSearch,
thread_memory memory);
bool VerifyProjectInFront(
const cv::Matx34f& viewMatrix,
const cv::Matx33f& cameraCalibration,
const cv::Point3f& triangulatedPoint);
}
| {
"alphanum_fraction": 0.6835465529,
"avg_line_length": 50.7027027027,
"ext": "h",
"hexsha": "92d6cf1980d7f1ba23763162729055fe124d0d8f",
"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": "Core/MAGESLAM/Source/Mapping/NewMapPointsCreation.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": "Core/MAGESLAM/Source/Mapping/NewMapPointsCreation.h",
"max_line_length": 226,
"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": "Core/MAGESLAM/Source/Mapping/NewMapPointsCreation.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": 1239,
"size": 5628
} |
/**
* tlibs2
* (container-agnostic) math library
* @author Tobias Weber <tobias.weber@tum.de>, <tweber@ill.fr>
* @date 2017-2021
* @license GPLv3, see 'LICENSE' file
*
* @note The present version was forked on 8-Nov-2018 from my privately developed "magtools" project (https://github.com/t-weber/magtools).
* @note Additional functions forked on 7-Nov-2018 from my privately and TUM-PhD-developed "tlibs" project (https://github.com/t-weber/tlibs).
* @note Further functions and updates forked on 1-Feb-2021 and 19-Apr-2021 from my privately developed "geo" and "misc" projects (https://github.com/t-weber/geo and https://github.com/t-weber/misc).
*
* @desc for the references, see the 'LITERATURE' file
*
* ----------------------------------------------------------------------------
* tlibs
* Copyright (C) 2017-2021 Tobias WEBER (Institut Laue-Langevin (ILL),
* Grenoble, France).
* Copyright (C) 2015-2017 Tobias WEBER (Technische Universitaet Muenchen
* (TUM), Garching, Germany).
* "magtools", "geo", and "misc" projects
* Copyright (C) 2017-2021 Tobias WEBER (privately developed).
*
* 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, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ----------------------------------------------------------------------------
*/
#ifndef __TLIBS2_CXX20_MATH_ALGOS_H__
#define __TLIBS2_CXX20_MATH_ALGOS_H__
//#define USE_LAPACK
#define __TLIBS2_QR_METHOD 0
#include <cstddef>
#include <cstdint>
#include <cassert>
#include <cmath>
#include <complex>
#include <tuple>
#include <unordered_map>
#include <vector>
#include <initializer_list>
#include <limits>
#include <algorithm>
#include <functional>
#include <iterator>
#include <numeric>
#include <random>
#include <utility>
#include <optional>
#include <memory>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <stdexcept>
#if __has_include(<numbers>)
#include <numbers>
#define __TLIBS2_USE_NUMBERS__
#endif
#include <boost/algorithm/string.hpp>
#include <boost/math/special_functions/factorials.hpp>
#include <boost/math/special_functions/spherical_harmonic.hpp>
#include <boost/algorithm/minmax_element.hpp>
#include "log.h"
#include "str.h"
#include "bits.h"
#include "traits.h"
#if __has_include(<lapacke.h>) && USE_LAPACK
extern "C"
{
#define lapack_complex_double std::complex<double>
#define lapack_complex_double_real(z) (z.real())
#define lapack_complex_double_imag(z) (z.imag())
#define lapack_complex_float std::complex<float>
#define lapack_complex_float_real(z) (z.real())
#define lapack_complex_float_imag(z) (z.imag())
#include <lapacke.h>
}
#define __TLIBS2_USE_LAPACK__
#else
#pragma message("tlibs2: Disabling Lapack(e) library (not found).")
#endif
#if __has_include(<Faddeeva.hh>)
#include <Faddeeva.hh>
using t_real_fadd = double;
#define __TLIBS2_USE_FADDEEVA__
#else
#pragma message("tlibs2: Disabling Faddeeva library (not found).")
#endif
#if __has_include(<Qhull.h>)
#include <Qhull.h>
#include <QhullFacetList.h>
#include <QhullVertexSet.h>
#define __TLIBS2_USE_QHULL__
#else
#pragma message("tlibs2: Disabling QHull library (not found).")
#endif
// separator tokens
#define TL2_COLSEP ';'
#define TL2_ROWSEP '|'
namespace tl2 {
// ----------------------------------------------------------------------------
// forward declarations
// ----------------------------------------------------------------------------
template<class t_mat>
t_mat prod(const t_mat& mat1, const t_mat& mat2, bool assert_sizes=true)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>;
template<class t_mat>
t_mat zero(std::size_t N1, std::size_t N2)
requires is_basic_mat<t_mat>;
template<class t_vec>
t_vec zero(std::size_t N=0)
requires is_basic_vec<t_vec>;
template<class t_mat, class t_vec>
std::tuple<bool, t_mat, t_mat> qr(const t_mat& mat)
requires is_mat<t_mat> && is_vec<t_vec>;
template<class t_mat>
std::tuple<t_mat, bool> inv(const t_mat& mat)
requires is_mat<t_mat>;
template<class t_mat>
typename t_mat::value_type det(const t_mat& mat)
requires is_mat<t_mat>;
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// helpers and constants
// ----------------------------------------------------------------------------
// constants
#ifdef __TLIBS2_USE_NUMBERS__
template<typename T=double> constexpr T golden{std::numbers::phi_v<T>};
template<typename T=double> constexpr T pi{std::numbers::pi_v<T>};
#else
// see: https://en.wikipedia.org/wiki/Golden_ratio
template<typename T=double> constexpr T golden{1.618033988749895};
template<typename T=double> constexpr T pi{M_PI};
#endif
// constant calculated using scipy:
// import scipy.constants as co
// E_to_k2 = 2.*co.neutron_mass/(co.Planck/co.elementary_charge*1000./2./co.pi)**2. / co.elementary_charge*1000. * 1e-20
template<typename T=double> constexpr T E_to_k2 = 0.482596423544;
template<typename INT=int> bool is_even(INT i) { return (i%2 == 0); }
template<typename INT=int> bool is_odd(INT i) { return !is_even<INT>(i); }
template<class T=double> constexpr T r2d(T rad) { return rad/pi<T>*T(180); } // rad -> deg
template<class T=double> constexpr T d2r(T deg) { return deg/T(180)*pi<T>; } // deg -> rad
template<class T=double> constexpr T r2m(T rad) { return rad/pi<T>*T(180*60); } // rad -> min
template<class T=double> constexpr T m2r(T min) { return min/T(180*60)*pi<T>; } // min -> rad
/**
* Gaussian around 0: f(x) = exp(-1/2 * (x/sig)^2)
* at hwhm: f(x_hwhm) = 1/2
* exp(-1/2 * (x_hwhm/sig)^2) = 1/2
* -1/2 * (x_hwhm/sig)^2 = ln(1/2)
* (x_hwhm/sig)^2 = -2*ln(1/2)
* x_hwhm^2 = sig^2 * 2*ln(2)
*/
template<class T=double> static constexpr T SIGMA2FWHM = T(2)*std::sqrt(T(2)*std::log(T(2)));
template<class T=double> static constexpr T SIGMA2HWHM = std::sqrt(T(2)*std::log(T(2)));
template<class T=double> static constexpr T FWHM2SIGMA = T(1)/SIGMA2FWHM<T>;
template<class T=double> static constexpr T HWHM2SIGMA = T(1)/SIGMA2HWHM<T>;
template<typename T> T sign(T t)
{
if(t<0.) return -T(1);
return T(1);
}
template<typename T> T cot(T t)
{
return std::tan(T(0.5)*pi<T> - t);
}
template<typename T> T coth(T t)
{
return T(1) / std::tanh(t);
}
template<typename T=double>
T log(T tbase, T tval)
{
return T(std::log(tval)/std::log(tbase));
}
template<typename T=double>
T nextpow(T tbase, T tval)
{
return T(std::pow(tbase, std::ceil(log(tbase, tval))));
}
template<class T, typename REAL=double>
T lerp(const T& a, const T& b, REAL val)
{
return a + T((b-a)*val);
}
/**
* unsigned angle between two vectors
* <q1|q2> / (|q1| |q2|) = cos(alpha)
*/
template<class t_vec>
typename t_vec::value_type angle_unsigned(const t_vec& q1, const t_vec& q2)
requires is_basic_vec<t_vec>
{
using t_real = typename t_vec::value_type;
if(q1.size() != q2.size())
return t_real(0);
t_real dot = t_real(0);
t_real len1 = t_real(0);
t_real len2 = t_real(0);
for(std::size_t i=0; i<q1.size(); ++i)
{
dot += q1[i]*q2[i];
len1 += q1[i]*q1[i];
len2 += q2[i]*q2[i];
}
len1 = std::sqrt(len1);
len2 = std::sqrt(len2);
dot /= len1;
dot /= len2;
return std::acos(dot);
}
/**
* unsigned angle between two quaternions
* <q1|q2> / (|q1| |q2|) = cos(alpha)
*/
template<class t_quat>
typename t_quat::value_type angle_unsigned(const t_quat& q1, const t_quat& q2)
requires is_quat<t_quat>
{
using t_real = typename t_quat::value_type;
t_real dot = q1.R_component_1() * q2.R_component_1() +
q1.R_component_2() * q2.R_component_2() +
q1.R_component_3() * q2.R_component_3() +
q1.R_component_4() * q2.R_component_4();
t_real len1 = q1.R_component_1() * q1.R_component_1() +
q1.R_component_2() * q1.R_component_2() +
q1.R_component_3() * q1.R_component_3() +
q1.R_component_4() * q1.R_component_4();
t_real len2 = q2.R_component_1() * q2.R_component_1() +
q2.R_component_2() * q2.R_component_2() +
q2.R_component_3() * q2.R_component_3() +
q2.R_component_4() * q2.R_component_4();
len1 = std::sqrt(len1);
len2 = std::sqrt(len2);
dot /= len1;
dot /= len2;
return std::acos(dot);
}
/**
* slerp
* @see K. Shoemake, "Animating rotation with quaternion curves", http://dx.doi.org/10.1145/325334.325242
* @see (Desktop Bronstein 2008), formula 4.207
* @see (Bronstein 2008), p. 306, formula 4.155
*/
template<class T>
T slerp(const T& q1, const T& q2, typename T::value_type t)
{
using t_real = typename T::value_type;
t_real angle = angle_unsigned<T>(q1, q2);
T q = std::sin((t_real(1)-t)*angle)/std::sin(angle) * q1 +
std::sin(t*angle)/std::sin(angle) * q2;
return q;
}
/**
* x = 0..1
*/
template<typename T=double>
T linear_interp(T x0, T x1, T x)
{
return lerp<T,T>(x0, x1, x);
}
/**
* x = 0..1, y = 0..1
*/
template<typename T=double>
T bilinear_interp(T x0y0, T x1y0, T x0y1, T x1y1, T x, T y)
{
T top = linear_interp<T>(x0y1, x1y1, x);
T bottom = linear_interp<T>(x0y0, x1y0, x);
return linear_interp<T>(bottom, top, y);
}
template<typename T=double, typename REAL=double,
template<class...> class t_vec = std::vector>
t_vec<T> linspace(const T& tmin, const T& tmax, std::size_t iNum)
{
t_vec<T> vec;
vec.reserve(iNum);
for(std::size_t i=0; i<iNum; ++i)
vec.push_back(lerp<T,REAL>(tmin, tmax, REAL(i)/REAL(iNum-1)));
return vec;
}
template<typename T=double, typename REAL=double,
template<class...> class t_vec = std::vector>
t_vec<T> logspace(const T& tmin, const T& tmax, std::size_t iNum, T tBase=T(10))
{
t_vec<T> vec = linspace<T, REAL>(tmin, tmax, iNum);
for(T& t : vec)
t = std::pow(tBase, t);
return vec;
}
template<typename T>
T clamp(T t, T min, T max)
{
if(t < min) t = min;
if(t > max) t = max;
return t;
}
template<class T>
bool is_in_range(T val, T centre, T pm)
{
pm = std::abs(pm);
if(val < centre-pm) return false;
if(val > centre+pm) return false;
return true;
}
/**
* point contained in linear range?
*/
template<class T = double>
bool is_in_linear_range(T dStart, T dStop, T dPoint)
{
if(dStop < dStart)
std::swap(dStart, dStop);
return (dPoint >= dStart) && (dPoint <= dStop);
}
/**
* angle contained in angular range?
*/
template<class T = double>
bool is_in_angular_range(T dStart, T dRange, T dAngle)
{
if(dStart < T(0)) dStart += T(2)*pi<T>;
if(dAngle < T(0)) dAngle += T(2)*pi<T>;
dStart = std::fmod(dStart, T(2)*pi<T>);
dAngle = std::fmod(dAngle, T(2)*pi<T>);
T dStop = dStart + dRange;
// if the end point is contained in the circular range
if(dStop < T(2)*pi<T>)
{
return is_in_linear_range<T>(dStart, dStop, dAngle);
}
// else end point wraps around
else
{
return is_in_linear_range<T>(dStart, T(2)*pi<T>, dAngle) ||
is_in_linear_range<T>(T(0), dRange-(T(2)*pi<T>-dStart), dAngle);
}
}
/**
* converts a string to a scalar value
*/
template<class t_scalar=double, class t_str=std::string>
t_scalar stoval(const t_str& str)
{
if constexpr(std::is_same_v<t_scalar, float>)
return std::stof(str);
else if constexpr(std::is_same_v<t_scalar, double>)
return std::stod(str);
else if constexpr(std::is_same_v<t_scalar, long double>)
return std::stold(str);
else if constexpr(std::is_same_v<t_scalar, int>)
return std::stoi(str);
// else if constexpr(std::is_same_v<t_scalar, unsigned int>)
// return std::stoui(str);
else if constexpr(std::is_same_v<t_scalar, long>)
return std::stol(str);
else if constexpr(std::is_same_v<t_scalar, unsigned long>)
return std::stoul(str);
else if constexpr(std::is_same_v<t_scalar, long long>)
return std::stoll(str);
else if constexpr(std::is_same_v<t_scalar, unsigned long long>)
return std::stoull(str);
else
{
t_scalar val{};
std::istringstream{str} >> val;
return val;
}
}
template<class t_num>
t_num get_rand(t_num min=1, t_num max=-1)
{
static std::mt19937 rng{std::random_device{}()};
if(max <= min)
{
min = std::numeric_limits<t_num>::lowest() / 10.;
max = std::numeric_limits<t_num>::max() / 10.;
}
if constexpr(std::is_integral_v<t_num>)
return std::uniform_int_distribution<t_num>(min, max)(rng);
else
return std::uniform_real_distribution<t_num>(min, max)(rng);
}
// ----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// peak model functions
// -----------------------------------------------------------------------------
/**
* gaussian
* @see https://en.wikipedia.org/wiki/Gaussian_function
*/
template<class T=double>
T gauss_model(T x, T x0, T sigma, T amp, T offs)
{
T norm = T(1)/(std::sqrt(T(2)*pi<T>) * sigma);
return amp * norm * std::exp(-0.5 * ((x-x0)/sigma)*((x-x0)/sigma)) + offs;
}
template<class T=double>
T gauss_model_amp(T x, T x0, T sigma, T amp, T offs)
{
return amp * std::exp(-0.5 * ((x-x0)/sigma)*((x-x0)/sigma)) + offs;
}
template<class T=double>
T gauss_model_amp_slope(T x, T x0, T sigma, T amp, T offs, T slope)
{
return amp * std::exp(-0.5 * ((x-x0)/sigma)*((x-x0)/sigma)) + (x-x0)*slope + offs;
}
/**
* lorentzian
* @see https://en.wikipedia.org/wiki/Cauchy_distribution
*/
template<class T=double>
T lorentz_model_amp(T x, T x0, T hwhm, T amp, T offs)
{
return amp*hwhm*hwhm / ((x-x0)*(x-x0) + hwhm*hwhm) + offs;
}
template<class T=double>
T lorentz_model_amp_slope(T x, T x0, T hwhm, T amp, T offs, T slope)
{
return amp*hwhm*hwhm / ((x-x0)*(x-x0) + hwhm*hwhm) + (x-x0)*slope + offs;
}
template<class T=double>
T parabola_model(T x, T x0, T amp, T offs)
{
return amp*(x-x0)*(x-x0) + offs;
}
template<class T=double>
T parabola_model_slope(T x, T x0, T amp, T offs, T slope)
{
return amp*(x-x0)*(x-x0) + (x-x0)*slope + offs;
}
// -----------------------------------------------------------------------------
template<class t_real_to, class t_real_from,
bool bIsEqu = std::is_same<t_real_from, t_real_to>::value>
struct complex_cast
{
const std::complex<t_real_to>& operator()(const std::complex<t_real_from>& c) const
{ return c; }
};
template<class t_real_to, class t_real_from>
struct complex_cast<t_real_to, t_real_from, 0>
{
std::complex<t_real_to> operator()(const std::complex<t_real_from>& c) const
{ return std::complex<t_real_to>(t_real_to(c.real()), t_real_to(c.imag())); }
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Faddeeva function
// -----------------------------------------------------------------------------
#ifdef __TLIBS2_USE_FADDEEVA__
/**
* Complex error function
*/
template<class T=double>
std::complex<T> erf(const std::complex<T>& z)
{
complex_cast<t_real_fadd, T> cst;
complex_cast<T, t_real_fadd> inv_cst;
return inv_cst(::Faddeeva::erf(cst(z)));
}
/**
* Complex complementary error function
*/
template<class T=double>
std::complex<T> erfc(const std::complex<T>& z)
{
complex_cast<t_real_fadd, T> cst;
complex_cast<T, t_real_fadd> inv_cst;
return inv_cst(::Faddeeva::erfc(cst(z)));
}
/**
* Faddeeva function
* @see https://en.wikipedia.org/wiki/Faddeeva_function
*/
template<class T=double>
std::complex<T> faddeeva(const std::complex<T>& z)
{
std::complex<T> i(0, 1.);
return std::exp(-z*z) * erfc(-i*z);
}
/**
* Voigt profile
* @see https://en.wikipedia.org/wiki/Voigt_profile
*/
template<class T=double>
T voigt_model(T x, T x0, T sigma, T gamma, T amp, T offs)
{
T norm = T(1)/(std::sqrt(T(2)*pi<T>) * sigma);
std::complex<T> z = std::complex<T>(x-x0, gamma) / (sigma * std::sqrt(T(2)));
return amp*norm * faddeeva<T>(z).real() + offs;
}
template<class T=double>
T voigt_model_amp(T x, T x0, T sigma, T gamma, T amp, T offs)
{
std::complex<T> z = std::complex<T>(x-x0, gamma) / (sigma * std::sqrt(T(2)));
return amp * faddeeva<T>(z).real() + offs;
}
template<class T=double>
T voigt_model_amp_slope(T x, T x0, T sigma, T gamma, T amp, T offs, T slope)
{
std::complex<T> z = std::complex<T>(x-x0, gamma) / (sigma * std::sqrt(T(2)));
return amp * faddeeva<T>(z).real() + (x-x0)*slope + offs;
}
#endif
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// physics-related functions
// -----------------------------------------------------------------------------
/**
* wrapper for boost's Y function
*/
template<class T=double>
std::complex<T> Ylm(int l /*0..i*/, int m /*-l..l*/, T th /*0..pi*/, T ph /*0..2pi*/)
{
return boost::math::spherical_harmonic<T,T>(l,m, th, ph);
}
/**
* CG coefficients
* @see (Arfken 2013), p. 790 for the formula
*
* e.g. two e- spins: s1 = s2 = 0.5, ms[1,2] = 0.5 (up) or -0.5 (down), S = 0 (sing.) or 1 (trip.)
*/
template<class T = double>
T CG_coeff(T S, T s1, T s2, T ms1, T ms2)
{
T (*fak)(T) = [](T t) -> T { return boost::math::factorial<T>(t); };
T tCG = fak(S + s1 - s2)*fak(S - s1 + s2)*fak(-S + s1 + s2);
tCG *= (T(2)*S + T(1));
tCG *= fak(S + ms1 + ms2) * fak(S - (ms1 + ms2));
tCG *= fak(s1 + ms1) * fak(s1 - ms1);
tCG *= fak(s2 + ms2) * fak(s2 - ms2);
tCG /= fak(S + s1 + s2 + T(1));
tCG = std::sqrt(tCG);
auto k_fkt = [&](T k) -> T
{
T t = std::pow(T(-1), k);
t /= fak(k);
t /= fak(-S + s1 + s2 - k)*fak(S - s1 - ms2 + k)*fak(S - s2 + ms1 + k);
t /= fak(s2 + ms2 - k)*fak(s1 - ms1 - k);
return t;
};
auto k_minmax = [&]() -> std::pair<T,T>
{
T kmax = s1 - ms1;
kmax = std::min(kmax, s2 + ms2);
kmax = std::min(kmax, -S + s1 + s2);
T kmin = -(S - s1 - ms2);
kmin = std::max(kmin, -(S - s2 + ms1));
kmin = std::max(kmin, T(0));
return std::make_pair(kmin, kmax);
};
T kmin, kmax;
std::tie(kmin, kmax) = k_minmax();
T kfact = T(0);
for(T k=kmin; k<=kmax; k+=T(1))
kfact += k_fkt(k);
tCG *= kfact;
return tCG;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// coordinate trafos
// -----------------------------------------------------------------------------
/**
* cartesian -> spherical
* @see https://en.wikipedia.org/wiki/Spherical_coordinate_system
*/
template<class T = double>
std::tuple<T,T,T> cart_to_sph(T x, T y, T z)
{
T rho = std::sqrt(x*x + y*y + z*z);
T phi = std::atan2(y, x);
T theta = std::acos(z/rho);
return std::make_tuple(rho, phi, theta);
}
/**
* spherical -> cartesian
* @see https://en.wikipedia.org/wiki/Spherical_coordinate_system
*/
template<class T = double>
std::tuple<T,T,T> sph_to_cart(T rho, T phi, T theta)
{
T x = rho * std::cos(phi)*std::sin(theta);
T y = rho * std::sin(phi)*std::sin(theta);
T z = rho * std::cos(theta);
return std::make_tuple(x, y, z);
}
/**
* cylindrical -> spherical
* @see https://en.wikipedia.org/wiki/Spherical_coordinate_system
*/
template<class T = double>
std::tuple<T,T,T> cyl_to_sph(T rho_cyl, T phi_cyl, T z_cyl)
{
T rho = std::sqrt(rho_cyl*rho_cyl + z_cyl*z_cyl);
T theta = std::acos(z_cyl/rho);
return std::make_tuple(rho, phi_cyl, theta);
}
/**
* spherical -> cylindrical
* @see https://en.wikipedia.org/wiki/Spherical_coordinate_system
*/
template<class T = double>
std::tuple<T,T,T> sph_to_cyl(T rho_sph, T phi_sph, T theta_sph)
{
T rho = rho_sph * std::sin(theta_sph);
T z = rho_sph * std::cos(theta_sph);
return std::make_tuple(rho, phi_sph, z);
}
/**
* cylindrical -> cartesian
* @see https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
*/
template<class T = double>
std::tuple<T,T,T> cyl_to_cart(T rho, T phi, T z)
{
T x = rho * std::cos(phi);
T y = rho * std::sin(phi);
return std::make_tuple(x, y, z);
}
/**
* cartesian -> cylindrical
* @see https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
*/
template<class T = double>
std::tuple<T,T,T> cart_to_cyl(T x, T y, T z)
{
T rho = std::sqrt(x*x + y*y);
T phi = std::atan2(y, x);
return std::make_tuple(rho, phi, z);
}
template<class T = double>
std::tuple<T,T> crys_to_sph(T twophi_crys, T twotheta_crys)
{
// converts the out-of-plane scattering angle '2theta' to the spherical theta
T theta_sph = pi<T>/T(2) - twotheta_crys;
// converts in-plane scattering angle '2phi' to the spherical phi
T phi_sph = twophi_crys - pi<T>/T(2);
return std::make_tuple(phi_sph, theta_sph);
}
template<class T = double>
std::tuple<T,T> sph_to_crys(T phi, T theta)
{
return crys_to_sph<T>(phi, theta);
}
/**
* gnomonic projection (similar to perspective projection with fov=90°)
* @return [x,y]
* @see see http://mathworld.wolfram.com/GnomonicProjection.html
*/
template<class T = double>
std::tuple<T,T> gnomonic_proj(T twophi_crys, T twotheta_crys)
{
T x = -std::tan(twophi_crys);
T y = std::tan(twotheta_crys) / std::cos(twophi_crys);
return std::make_tuple(x, y);
}
/**
* stereographic projection
* @return [x,y]
* @see http://mathworld.wolfram.com/StereographicProjection.html
*/
template<class T = double>
std::tuple<T,T> stereographic_proj(T twophi_crys, T twotheta_crys, T rad)
{
const T sth = std::sin(twotheta_crys);
const T cth = std::cos(twotheta_crys);
const T sph = std::sin(twophi_crys);
const T cph = std::cos(twophi_crys);
T x = -T(2) * rad * sph * cth / (T(1) + cth*cph);
T y = T(2) * rad * sth / (T(1) + cth*cph);
return std::make_tuple(x, y);
}
// -----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// adapters
// ----------------------------------------------------------------------------
template<typename size_t, size_t N, typename T, template<size_t, size_t, class...> class t_mat_base>
class qvec_adapter : public t_mat_base<1, N, T>
{
public:
// types
using base_type = t_mat_base<1, N, T>;
using size_type = size_t;
using value_type = T;
// constructors
using base_type::base_type;
qvec_adapter(const base_type& vec) : base_type{vec} {}
static constexpr size_t size() { return N; }
T& operator[](size_t i) { return base_type::operator()(i,0); }
const T operator[](size_t i) const { return base_type::operator()(i,0); }
};
template<typename size_t, size_t ROWS, size_t COLS, typename T, template<size_t, size_t, class...> class t_mat_base>
class qmat_adapter : public t_mat_base<COLS, ROWS, T>
{
public:
// types
using base_type = t_mat_base<COLS, ROWS, T>;
using size_type = size_t;
using value_type = T;
// constructors
using base_type::base_type;
qmat_adapter(const base_type& mat) : base_type{mat} {}
static constexpr size_t size1() { return ROWS; }
static constexpr size_t size2() { return COLS; }
};
template<typename size_t, size_t N, typename T, class t_vec_base>
class qvecN_adapter : public t_vec_base
{
public:
// types
using base_type = t_vec_base;
using size_type = size_t;
using value_type = T;
// constructors
using base_type::base_type;
qvecN_adapter(const base_type& vec) : base_type{vec} {}
static constexpr size_t size() { return N; }
T& operator[](size_t i) { return static_cast<base_type&>(*this)[i]; }
const T operator[](size_t i) const { return static_cast<const base_type&>(*this)[i]; }
};
template<typename size_t, size_t ROWS, size_t COLS, typename T, class t_mat_base>
class qmatNN_adapter : public t_mat_base
{
public:
// types
using base_type = t_mat_base;
using size_type = size_t;
using value_type = T;
// constructors
using base_type::base_type;
qmatNN_adapter(const base_type& mat) : base_type{mat} {}
// convert from a different matrix type
template<class t_matOther> qmatNN_adapter(const t_matOther& matOther)
requires is_basic_mat<t_matOther>
{
const std::size_t minRows = std::min(static_cast<std::size_t>(size1()), static_cast<std::size_t>(matOther.size1()));
const std::size_t minCols = std::min(static_cast<std::size_t>(size2()), static_cast<std::size_t>(matOther.size2()));
for(std::size_t i=0; i<minRows; ++i)
for(std::size_t j=0; j<minCols; ++j)
(*this)(i,j) = static_cast<value_type>(matOther(i,j));
}
static constexpr size_t size1() { return ROWS; }
static constexpr size_t size2() { return COLS; }
};
// ----------------------------------------------------------------------------
}
namespace tl2_ops {
// ----------------------------------------------------------------------------
// vector operators
// ----------------------------------------------------------------------------
/**
* unary +
*/
template<class t_vec>
const t_vec& operator+(const t_vec& vec1)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
return vec1;
}
/**
* unary -
*/
template<class t_vec>
t_vec operator-(const t_vec& vec1)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
t_vec vec(vec1.size());
for(std::size_t i=0; i<vec1.size(); ++i)
vec[i] = -vec1[i];
return vec;
}
/**
* binary +
*/
template<class t_vec>
t_vec operator+(const t_vec& vec1, const t_vec& vec2)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
if constexpr(tl2::is_dyn_vec<t_vec>)
assert((vec1.size() == vec2.size()));
t_vec vec(vec1.size());
for(std::size_t i=0; i<vec1.size(); ++i)
vec[i] = vec1[i] + vec2[i];
return vec;
}
/**
* binary -
*/
template<class t_vec>
t_vec operator-(const t_vec& vec1, const t_vec& vec2)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
return vec1 + (-vec2);
}
/**
* vector * scalar
*/
template<class t_vec>
t_vec operator*(const t_vec& vec1, typename t_vec::value_type d)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
t_vec vec(vec1.size());
for(std::size_t i=0; i<vec1.size(); ++i)
vec[i] = vec1[i] * d;
return vec;
}
/**
* scalar * vector
*/
template<class t_vec>
t_vec operator*(typename t_vec::value_type d, const t_vec& vec)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
//&& !tl2::is_basic_mat<typename t_vec::value_type> // hack!
{
return vec * d;
}
/**
* vector / scalar
*/
template<class t_vec>
t_vec operator/(const t_vec& vec1, typename t_vec::value_type d)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
t_vec vec(vec1.size());
for(std::size_t i=0; i<vec1.size(); ++i)
vec[i] = vec1[i] / d;
return vec;
}
/**
* vector += vector
*/
template<class t_vec>
t_vec& operator+=(t_vec& vec1, const t_vec& vec2)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
vec1 = vec1 + vec2;
return vec1;
}
/**
* vector -= vector
*/
template<class t_vec>
t_vec& operator-=(t_vec& vec1, const t_vec& vec2)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
vec1 = vec1 - vec2;
return vec1;
}
/**
* vector *= scalar
*/
template<class t_vec>
t_vec& operator*=(t_vec& vec1, typename t_vec::value_type d)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
vec1 = vec1 * d;
return vec1;
}
/**
* vector /= scalar
*/
template<class t_vec>
t_vec& operator/=(t_vec& vec1, typename t_vec::value_type d)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
vec1 = vec1 / d;
return vec1;
}
/**
* operator <<
*/
template<class t_vec>
std::ostream& operator<<(std::ostream& ostr, const t_vec& vec)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
const std::size_t N = vec.size();
for(std::size_t i=0; i<N; ++i)
{
ostr << vec[i];
if(i < N-1)
ostr << TL2_COLSEP << " ";
}
return ostr;
}
/**
* operator >>
*/
template<class t_vec>
std::istream& operator>>(std::istream& istr, t_vec& vec)
requires tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
vec.clear();
std::string str;
std::getline(istr, str);
std::vector<std::string> vecstr;
boost::split(vecstr, str, [](auto c)->bool { return c==TL2_COLSEP; }, boost::token_compress_on);
for(auto& tok : vecstr)
{
boost::trim(tok);
typename t_vec::value_type c = tl2::stoval<typename t_vec::value_type>(tok);
vec.emplace_back(std::move(c));
}
return istr;
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// matrix operators
// ----------------------------------------------------------------------------
/**
* unary +
*/
template<class t_mat>
const t_mat& operator+(const t_mat& mat1)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
return mat1;
}
/**
* unary -
*/
template<class t_mat>
t_mat operator-(const t_mat& mat1)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
t_mat mat(mat1.size1(), mat1.size2());
for(std::size_t i=0; i<mat1.size1(); ++i)
for(std::size_t j=0; j<mat1.size2(); ++j)
mat(i,j) = -mat1(i,j);
return mat;
}
/**
* binary +
*/
template<class t_mat>
t_mat operator+(const t_mat& mat1, const t_mat& mat2)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
if constexpr(tl2::is_dyn_mat<t_mat>)
assert((mat1.size1() == mat2.size1() && mat1.size2() == mat2.size2()));
t_mat mat(mat1.size1(), mat1.size2());
for(std::size_t i=0; i<mat1.size1(); ++i)
for(std::size_t j=0; j<mat1.size2(); ++j)
mat(i,j) = mat1(i,j) + mat2(i,j);
return mat;
}
/**
* binary -
*/
template<class t_mat>
t_mat operator-(const t_mat& mat1, const t_mat& mat2)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
return mat1 + (-mat2);
}
/**
* matrix * scalar
*/
template<class t_mat>
t_mat operator*(const t_mat& mat1, typename t_mat::value_type d)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
t_mat mat(mat1.size1(), mat1.size2());
for(std::size_t i=0; i<mat1.size1(); ++i)
for(std::size_t j=0; j<mat1.size2(); ++j)
mat(i,j) = mat1(i,j) * d;
return mat;
}
/**
* scalar * matrix
*/
template<class t_mat>
t_mat operator*(typename t_mat::value_type d, const t_mat& mat)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
return mat * d;
}
/**
* matrix / scalar
*/
template<class t_mat>
t_mat operator/(const t_mat& mat, typename t_mat::value_type d)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
using T = typename t_mat::value_type;
return mat * (T(1)/d);
}
/**
* matrix-matrix product
*/
template<class t_mat>
t_mat operator*(const t_mat& mat1, const t_mat& mat2)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
return tl2::prod<t_mat>(mat1, mat2);
}
/**
* matrix *= scalar
*/
template<class t_mat>
t_mat& operator*=(t_mat& mat1, typename t_mat::value_type d)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
mat1 = mat1 * d;
return mat1;
}
/**
* matrix *= matrix
*/
template<class t_mat>
t_mat& operator*=(t_mat& mat1, const t_mat& mat2)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
mat1 = mat1 * mat2;
return mat1;
}
/**
* matrix += matrix
*/
template<class t_mat>
t_mat& operator+=(t_mat& mat1, const t_mat& mat2)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
mat1 = mat1 + mat2;
return mat1;
}
/**
* matrix /= scalar
*/
template<class t_mat>
t_mat& operator/=(t_mat& mat1, typename t_mat::value_type d)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
mat1 = mat1 / d;
return mat1;
}
/**
* operator <<
*/
template<class t_mat>
std::ostream& operator<<(std::ostream& ostr, const t_mat& mat)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
const std::size_t ROWS = mat.size1();
const std::size_t COLS = mat.size2();
for(std::size_t row=0; row<ROWS; ++row)
{
for(std::size_t col=0; col<COLS; ++col)
{
ostr << mat(row, col);
if(col < COLS-1)
ostr << TL2_COLSEP << " ";
}
if(row < ROWS-1)
ostr << TL2_ROWSEP << " ";
}
return ostr;
}
/**
* prints matrix in nicely formatted form
*/
template<class t_mat>
std::ostream& niceprint(std::ostream& ostr, const t_mat& mat)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
const std::size_t ROWS = mat.size1();
const std::size_t COLS = mat.size2();
for(std::size_t i=0; i<ROWS; ++i)
{
ostr << "(";
for(std::size_t j=0; j<COLS; ++j)
ostr << std::setw(ostr.precision()*1.5) << std::right << mat(i,j);
ostr << ")";
if(i < ROWS-1)
ostr << "\n";
}
return ostr;
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// mixed operators
// ----------------------------------------------------------------------------
/**
* matrix-vector product: c_i = a_ij b_j
*/
template<class t_mat, class t_vec>
t_vec operator*(const t_mat& mat, const t_vec& vec)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
&& tl2::is_basic_vec<t_vec> && tl2::is_dyn_vec<t_vec>
{
if constexpr(tl2::is_dyn_mat<t_mat>)
assert((mat.size2() == vec.size()));
else
static_assert(t_mat::size2() == t_vec::size());
t_vec vecRet(mat.size1());
for(std::size_t row=0; row<mat.size1(); ++row)
{
vecRet[row] = typename t_vec::value_type{/*0*/};
for(std::size_t col=0; col<mat.size2(); ++col)
{
auto elem = mat(row, col) * vec[col];
vecRet[row] = vecRet[row] + elem;
}
}
return vecRet;
}
// ----------------------------------------------------------------------------
}
namespace tl2 {
// ----------------------------------------------------------------------------
// vector and matrix containers
// ----------------------------------------------------------------------------
template<class T = double, template<class...> class t_cont = std::vector>
requires is_basic_vec<t_cont<T>> && is_dyn_vec<t_cont<T>>
class vec : public t_cont<T>
{
public:
using value_type = T;
using container_type = t_cont<T>;
using container_type::container_type;
using container_type::size;
using container_type::operator[];
using typename container_type::iterator;
using typename container_type::const_iterator;
using typename container_type::size_type;
using typename container_type::difference_type;
using typename container_type::allocator_type;
~vec() = default;
vec(const vec<T, t_cont>& other) : container_type{other}
{}
template<class T_other, template<class...> class t_cont_other>
vec(const vec<T_other, t_cont_other>& other)
{
this->operator=<T_other, t_cont_other>(other);
}
vec<T, t_cont>& operator=(const vec<T, t_cont>& other)
{
*static_cast<container_type*>(this) = other;
return *this;
}
const vec<T, t_cont>& operator=(const vec<T, t_cont>& other) const
{
*static_cast<container_type*>(this) = other;
return *this;
}
template<class T_other, template<class...> class t_cont_other>
vec<T, t_cont>& operator=(const vec<T_other, t_cont_other>& other)
{
*this = convert<vec<T, t_cont>, vec<T_other, t_cont_other>>(other);
return *this;
}
template<class T_other, template<class...> class t_cont_other>
const vec<T, t_cont>& operator=(const vec<T_other, t_cont_other>& other) const
{
*this = convert<vec<T, t_cont>, vec<T_other, t_cont_other>>(other);
return *this;
}
vec(std::size_t SIZE, const T* arr = nullptr) : container_type(SIZE)
{
if(arr)
from_array(arr);
}
const value_type& operator()(std::size_t i) const { return this->operator[](i); }
value_type& operator()(std::size_t i) { return this->operator[](i); }
void from_array(const T* arr)
{
// initialise from given array data
for(std::size_t i=0; i<size(); ++i)
this->operator[](i) = arr[i];
}
void to_array(T* arr) const
{
// write elements to array
for(std::size_t i=0; i<size(); ++i)
arr[i] = this->operator[](i);
}
friend vec operator+(const vec& vec1, const vec& vec2) { return tl2_ops::operator+(vec1, vec2); }
friend vec operator-(const vec& vec1, const vec& vec2) { return tl2_ops::operator-(vec1, vec2); }
friend const vec& operator+(const vec& vec1) { return tl2_ops::operator+(vec1); }
friend vec operator-(const vec& vec1) { return tl2_ops::operator-(vec1); }
friend vec operator*(value_type d, const vec& vec1) { return tl2_ops::operator*(d, vec1); }
friend vec operator*(const vec& vec1, value_type d) { return tl2_ops::operator*(vec1, d); }
friend vec operator/(const vec& vec1, value_type d) { return tl2_ops::operator/(vec1, d); }
vec& operator*=(const vec& vec2) { return tl2_ops::operator*=(*this, vec2); }
vec& operator+=(const vec& vec2) { return tl2_ops::operator+=(*this, vec2); }
vec& operator-=(const vec& vec2) { return tl2_ops::operator-=(*this, vec2); }
vec& operator*=(value_type d) { return tl2_ops::operator*=(*this, d); }
vec& operator/=(value_type d) { return tl2_ops::operator/=(*this, d); }
};
template<class T=double, template<class...> class t_cont = std::vector>
requires is_basic_vec<t_cont<T>> && is_dyn_vec<t_cont<T>>
class mat
{
public:
using value_type = T;
using container_type = t_cont<T>;
mat() = default;
~mat() = default;
mat(std::size_t ROWS, std::size_t COLS, const T* arr = nullptr)
: m_data(ROWS*COLS), m_rowsize{ROWS}, m_colsize{COLS}
{
if(arr)
from_array(arr);
}
template<class T_other, template<class...> class t_cont_other>
mat(const mat<T_other, t_cont_other>& other)
{
this->operator=<T_other, t_cont_other>(other);
}
template<class T_other, template<class...> class t_cont_other>
mat<T, t_cont>& operator=(const vec<T_other, t_cont_other>& other)
{
*this = convert<mat<T, t_cont>, mat<T_other, t_cont_other>>(other);
this->m_rowsize = other.m_rowsize;
this->m_colsize = other.m_colsize;
return *this;
}
template<class T_other, template<class...> class t_cont_other>
const mat<T, t_cont>& operator=(const vec<T_other, t_cont_other>& other) const
{
*this = convert<mat<T, t_cont>, mat<T_other, t_cont_other>>(other);
this->m_rowsize = other.m_rowsize;
this->m_colsize = other.m_colsize;
return *this;
}
std::size_t size1() const { return m_rowsize; }
std::size_t size2() const { return m_colsize; }
// element access
const T& operator()(std::size_t row, std::size_t col) const { return m_data[row*m_colsize + col]; }
T& operator()(std::size_t row, std::size_t col) { return m_data[row*m_colsize + col]; }
void from_array(const T* arr)
{
// initialise from given array data
for(std::size_t i=0; i<m_rowsize; ++i)
for(std::size_t j=0; j<m_colsize; ++j)
this->operator()(i,j) = arr[i*m_colsize + j];
}
void to_array(T* arr) const
{
// write elements to array
for(std::size_t i=0; i<m_rowsize; ++i)
for(std::size_t j=0; j<m_colsize; ++j)
arr[i*m_colsize + j] = this->operator()(i,j);
}
friend mat operator+(const mat& mat1, const mat& mat2) { return tl2_ops::operator+(mat1, mat2); }
friend mat operator-(const mat& mat1, const mat& mat2) { return tl2_ops::operator-(mat1, mat2); }
friend const mat& operator+(const mat& mat1) { return tl2_ops::operator+(mat1); }
friend mat operator-(const mat& mat1) { return tl2_ops::operator-(mat1); }
friend mat operator*(const mat& mat1, const mat& mat2) { return tl2_ops::operator*(mat1, mat2); }
friend mat operator*(const mat& mat1, value_type d) { return tl2_ops::operator*(mat1, d); }
friend mat operator*(value_type d, const mat& mat1) { return tl2_ops::operator*(d, mat1); }
friend mat operator/(const mat& mat1, value_type d) { return tl2_ops::operator/(mat1, d); }
template<class t_vec> requires is_basic_vec<t_cont<T>> && is_dyn_vec<t_cont<T>>
friend t_vec operator*(const mat& mat1, const t_vec& vec2) { return tl2_ops::operator*(mat1, vec2); }
mat& operator*=(const mat& mat2) { return tl2_ops::operator*=(*this, mat2); }
mat& operator+=(const mat& mat2) { return tl2_ops::operator+=(*this, mat2); }
mat& operator-=(const mat& mat2) { return tl2_ops::operator-=(*this, mat2); }
mat& operator*=(value_type d) { return tl2_ops::operator*=(*this, d); }
mat& operator/=(value_type d) { return tl2_ops::operator/=(*this, d); }
private:
container_type m_data{};
std::size_t m_rowsize{0};
std::size_t m_colsize{0};
};
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// scalar algos
// ----------------------------------------------------------------------------
/**
* are two scalars equal within an epsilon range?
*/
template<class T>
bool equals(T t1, T t2, T eps = std::numeric_limits<T>::epsilon())
requires is_scalar<T>
{
return std::abs(t1 - t2) <= eps;
}
/**
* get next multiple of the given granularity
*/
template<typename t_num = unsigned int>
t_num next_multiple(t_num num, t_num granularity)
requires is_scalar<t_num>
{
t_num div = num / granularity;
bool rest_is_0 = 1;
if constexpr(std::is_floating_point_v<t_num>)
{
div = std::floor(div);
t_num rest = std::fmod(num, granularity);
rest_is_0 = equals(rest, t_num{0});
}
else
{
t_num rest = num % granularity;
rest_is_0 = (rest==0);
}
return rest_is_0 ? num : (div+1) * granularity;
}
/**
* mod operation, keeping result positive
*/
template<class t_real>
t_real mod_pos(t_real val, t_real tomod=t_real{2}*pi<t_real>)
requires is_scalar<t_real>
{
val = std::fmod(val, tomod);
if(val < t_real(0))
val += tomod;
return val;
}
/**
* are two angles equal within an epsilon range?
*/
template<class T>
bool angle_equals(T t1, T t2, T eps = std::numeric_limits<T>::epsilon(), T tomod=T{2}*pi<T>)
requires is_scalar<T>
{
t1 = mod_pos<T>(t1, tomod);
t2 = mod_pos<T>(t2, tomod);
return std::abs(t1 - t2) <= eps;
}
/**
* are two complex numbers equal within an epsilon range?
*/
template<class T>
bool equals(const T& t1, const T& t2,
typename T::value_type eps = std::numeric_limits<typename T::value_type>::epsilon())
requires is_complex<T>
{
return (std::abs(t1.real() - t2.real()) <= eps) &&
(std::abs(t1.imag() - t2.imag()) <= eps);
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// n-dim algos
// ----------------------------------------------------------------------------
/**
* are two vectors equal within an epsilon range?
*/
template<class t_vec, class t_real = typename t_vec::value_type>
bool equals(const t_vec& vec1, const t_vec& vec2,
t_real eps = std::numeric_limits<t_real>::epsilon(),
int _maxSize = -1)
requires is_basic_vec<t_vec>
{
// size has to be equal
if(vec1.size() != vec2.size())
return false;
std::size_t maxSize = vec1.size();
if(_maxSize >= 0)
maxSize = std::min(std::size_t(_maxSize), maxSize);
// check each element
for(std::size_t i=0; i<maxSize; ++i)
{
if constexpr(tl2::is_complex<t_real>)
{
if(!equals<t_real>(vec1[i], vec2[i], eps.real()))
return false;
}
else
{
if(!equals<t_real>(vec1[i], vec2[i], eps))
return false;
}
}
return true;
}
/**
* are two matrices equal within an epsilon range?
*/
template<class t_mat, class t_real>
bool equals(const t_mat& mat1, const t_mat& mat2,
t_real eps = std::numeric_limits<t_real>::epsilon(),
int _maxSize = -1)
requires is_mat<t_mat>
{
using T = typename t_mat::value_type;
if(mat1.size1() != mat2.size1() || mat1.size2() != mat2.size2())
return false;
std::size_t maxSize1 = mat1.size1();
std::size_t maxSize2 = mat1.size2();
if(_maxSize >= 0)
{
maxSize1 = std::min(std::size_t(_maxSize), maxSize1);
maxSize2 = std::min(std::size_t(_maxSize), maxSize2);
}
for(std::size_t i=0; i<maxSize1; ++i)
{
for(std::size_t j=0; j<maxSize2; ++j)
{
if constexpr(is_complex<decltype(eps)>)
{
if(!equals<T>(mat1(i,j), mat2(i,j), eps.real()))
return false;
}
else
{
if(!equals<T>(mat1(i,j), mat2(i,j), eps))
return false;
}
}
}
return true;
}
/**
* check if two collections of matrices or vectors are equal
*/
template<class t_obj, template<class...> class t_vec = std::vector>
bool equals_all(const t_vec<t_obj>& vec1, const t_vec<t_obj>& _vec2,
typename t_obj::value_type eps = std::numeric_limits<typename t_obj::value_type>::epsilon(),
int maxSize=-1)
{
auto vec2 = _vec2;
if(vec1.size() != vec2.size())
return false;
for(const auto& obj1 : vec1)
{
// find obj1 in vec2
auto iter = std::find_if(vec2.crbegin(), vec2.crend(),
[&obj1, eps, maxSize](const t_obj& obj2) -> bool
{
return tl2::equals<t_obj>(obj1, obj2, eps, maxSize);
});
// not found
if(iter == vec2.crend())
return false;
// remove already checked element
vec2.erase(iter.base()-1);
}
return true;
}
/**
* remove duplicate vectors or matrices in the container
*/
template<class t_obj, template<class...> class t_cont = std::vector>
t_cont<t_obj> remove_duplicates(const t_cont<t_obj>& objs,
typename t_obj::value_type eps = std::numeric_limits<typename t_obj::value_type>::epsilon())
{
t_cont<t_obj> newobjs = objs;
for(const auto& elem : objs)
{
// find obj in container
auto iter = std::find_if(newobjs.cbegin(), newobjs.cend(),
[&elem, eps](const t_obj& elem2) -> bool
{
return tl2::equals<t_obj>(elem, elem2, eps);
});
// not found
if(iter == newobjs.cend())
newobjs.push_back(elem);
}
return newobjs;
}
/**
* set submatrix to unit
*/
template<class t_mat>
void unit(t_mat& mat, std::size_t rows_begin, std::size_t cols_begin, std::size_t rows_end, std::size_t cols_end)
requires is_basic_mat<t_mat>
{
for(std::size_t i=rows_begin; i<rows_end; ++i)
for(std::size_t j=cols_begin; j<cols_end; ++j)
mat(i,j) = (i==j ? 1 : 0);
}
/**
* unit matrix
*/
template<class t_mat>
t_mat unit(std::size_t N1, std::size_t N2)
requires is_basic_mat<t_mat>
{
t_mat mat;
if constexpr(is_dyn_mat<t_mat>)
mat = t_mat(N1, N2);
unit<t_mat>(mat, 0,0, mat.size1(),mat.size2());
return mat;
}
/**
* unit matrix
*/
template<class t_mat>
t_mat unit(std::size_t N=0)
requires is_basic_mat<t_mat>
{
return unit<t_mat>(N,N);
}
/**
* zero matrix
*/
template<class t_mat>
t_mat zero(std::size_t N1, std::size_t N2)
requires is_basic_mat<t_mat>
{
t_mat mat;
if constexpr(is_dyn_mat<t_mat>)
mat = t_mat(N1, N2);
for(std::size_t i=0; i<mat.size1(); ++i)
for(std::size_t j=0; j<mat.size2(); ++j)
mat(i,j) = 0;
return mat;
}
/**
* zero matrix
*/
template<class t_mat>
t_mat zero(std::size_t N=0)
requires is_basic_mat<t_mat>
{
return zero<t_mat>(N, N);
}
/**
* zero vector
*/
template<class t_vec>
t_vec zero(std::size_t N /* = 0*/)
requires is_basic_vec<t_vec>
{
using size_t = decltype(t_vec{}.size());
t_vec vec;
if constexpr(is_dyn_vec<t_vec>)
vec = t_vec(N);
for(size_t i=0; i<vec.size(); ++i)
vec[i] = 0;
return vec;
}
/**
* row permutation matrix
*/
template<class t_mat>
t_mat perm(std::size_t N1, std::size_t N2, std::size_t from, std::size_t to)
requires is_basic_mat<t_mat>
{
t_mat mat;
if constexpr(is_dyn_mat<t_mat>)
mat = t_mat(N1, N2);
unit<t_mat>(mat, 0,0, mat.size1(),mat.size2());
mat(from, from) = mat(to, to) = 0;
mat(from, to) = mat(to, from) = 1;
return mat;
}
/**
* diagonal matrix
*/
template<class t_mat, class t_vec = std::vector<typename t_mat::value_type>>
t_mat diag(const t_vec& vals)
requires is_basic_mat<t_mat> && is_basic_vec<t_vec>
{
const std::size_t N = vals.size();
t_mat mat = zero<t_mat>(N);
// static matrix does not necessarily have the required size!
if constexpr(!tl2::is_dyn_mat<t_mat>)
assert(mat.size1() == mat.size1() && mat.size1() == N);
for(std::size_t i=0; i<std::min(mat.size1(), N); ++i)
mat(i,i) = vals[i];
return mat;
}
/**
* vector of diagonal matrix elements
*/
template<class t_vec, class t_mat>
t_vec diag_vec(const t_mat& mat)
requires is_vec<t_vec> && is_mat<t_mat>
{
std::size_t N = std::min(mat.size1(), mat.size2());
t_vec vec = zero<t_vec>(N);
for(std::size_t i=0; i<N; ++i)
vec[i] = mat(i,i);
return vec;
}
/**
* tests for zero scalar
*/
template<class t_real>
bool equals_0(t_real val, t_real eps = std::numeric_limits<t_real>::epsilon())
requires is_scalar<t_real>
{
return equals<t_real>(val, t_real(0), eps);
}
/**
* tests for zero vector
*/
template<class t_vec>
bool equals_0(const t_vec& vec,
typename t_vec::value_type eps = std::numeric_limits<typename t_vec::value_type>::epsilon())
requires is_basic_vec<t_vec>
{
return equals<t_vec>(vec, zero<t_vec>(vec.size()), eps);
}
/**
* tests for zero matrix
*/
template<class t_mat>
bool equals_0(const t_mat& mat,
typename t_mat::value_type eps = std::numeric_limits<typename t_mat::value_type>::epsilon())
requires is_mat<t_mat>
{
return equals<t_mat>(mat, zero<t_mat>(mat.size1(), mat.size2()), eps);
}
/**
* tests for symmetric or hermitian matrix
*/
template<class t_mat>
bool is_symm_or_herm(const t_mat& mat,
typename t_mat::value_type eps = std::numeric_limits<typename t_mat::value_type>::epsilon())
requires is_mat<t_mat>
{
using t_elem = typename t_mat::value_type;
if(mat.size1() != mat.size2())
return false;
for(std::size_t i=0; i<mat.size1(); ++i)
{
for(std::size_t j=i+1; j<mat.size2(); ++j)
{
if constexpr(is_complex<t_elem>)
{
// not hermitian?
if(!equals<t_elem>(mat(i,j), std::conj(mat(j,i)), eps))
return false;
}
else
{
// not symmetric?
if(!equals<t_elem>(mat(i,j), mat(j,i), eps))
return false;
}
}
}
return true;
}
/**
* transpose matrix
* WARNING: not possible for static non-square matrix!
*/
template<class t_mat>
t_mat trans(const t_mat& mat)
requires is_mat<t_mat>
{
using t_idxtype = decltype(mat.size1());
t_mat mat2;
if constexpr(is_dyn_mat<t_mat>)
mat2 = t_mat(mat.size2(), mat.size1());
for(t_idxtype i=0; i<mat.size1(); ++i)
for(t_idxtype j=0; j<mat.size2(); ++j)
mat2(j,i) = mat(i,j);
return mat2;
}
// -----------------------------------------------------------------------------
/**
* set values lower than epsilon to zero
* scalar version
*/
template<typename t_real>
void set_eps_0(t_real& d, t_real eps = std::numeric_limits<t_real>::epsilon())
requires is_scalar<t_real>
{
if(std::abs(d) < eps)
d = t_real(0);
};
/**
* set values lower than epsilon to zero
* vector version
*/
template<typename t_vec, typename t_real = typename t_vec::value_type>
void set_eps_0(t_vec& vec, t_real eps = std::numeric_limits<t_real>::epsilon())
requires is_basic_vec<t_vec>
{
for(t_real& d : vec)
set_eps_0<t_real>(d, eps);
};
/**
* set values lower than epsilon to zero
* matrix version
*/
template<typename t_mat, typename t_real = typename t_mat::value_type>
void set_eps_0(t_mat& mat, t_real eps = std::numeric_limits<t_real>::epsilon())
requires is_basic_mat<t_mat>
{
for(std::size_t i=0; i<mat.size1(); ++i)
for(std::size_t j=0; j<mat.size2(); ++j)
set_eps_0<t_real>(mat(i,j), eps);
};
// -----------------------------------------------------------------------------
/**
* create a vector with given size if it is dynamic
*/
template<class t_vec>
t_vec create(std::size_t size=3)
requires is_basic_vec<t_vec>
{
t_vec vec;
if constexpr(is_dyn_vec<t_vec>)
vec = t_vec(size);
return vec;
}
/**
* create a matrix with given sizes if it is dynamic
*/
template<class t_mat>
t_mat create(std::size_t size1, std::size_t size2)
requires is_basic_mat<t_mat>
{
t_mat mat;
if constexpr(is_dyn_mat<t_mat>)
mat = t_mat{size1, size2};
return mat;
}
/**
* create vector from initializer_list
*/
template<class t_vec, template<class...> class t_cont = std::initializer_list>
t_vec create(const t_cont<typename t_vec::value_type>& lst)
requires is_basic_vec<t_vec>
{
t_vec vec;
if constexpr(is_dyn_vec<t_vec>)
vec = t_vec(lst.size());
auto iterLst = lst.begin();
auto size = vec.size();
using local_size_t = std::decay_t<decltype(size)>;
for(local_size_t i=0; i<size; ++i)
{
if(iterLst != lst.end())
{
vec[i] = *iterLst;
std::advance(iterLst, 1);
}
else // vector larger than given list?
{
vec[i] = 0;
}
}
return vec;
}
/**
* create matrix from nested initializer_lists in columns/rows order
*/
template<class t_mat,
template<class...> class t_cont_outer = std::initializer_list,
template<class...> class t_cont = std::initializer_list>
t_mat create_mat(const t_cont_outer<t_cont<typename t_mat::value_type>>& lst)
requires is_mat<t_mat>
{
const std::size_t iCols = lst.size();
const std::size_t iRows = lst.begin()->size();
t_mat mat = unit<t_mat>(iRows, iCols);
auto iterCol = lst.begin();
for(std::size_t iCol=0; iCol<iCols; ++iCol)
{
auto iterRow = iterCol->begin();
for(std::size_t iRow=0; iRow<iRows; ++iRow)
{
mat(iRow, iCol) = *iterRow;
std::advance(iterRow, 1);
}
std::advance(iterCol, 1);
}
return mat;
}
/**
* create matrix from nested initializer_lists in columns/rows order
*/
template<class t_mat,
template<class...> class t_cont_outer = std::initializer_list,
template<class...> class t_cont = std::initializer_list>
t_mat create(const t_cont_outer<t_cont<typename t_mat::value_type>>& lst)
requires is_mat<t_mat>
{
return create_mat<t_mat, t_cont_outer, t_cont>(lst);
}
/**
* create matrix from column (or row) vectors
*/
template<class t_mat, class t_vec, template<class...> class t_cont_outer = std::initializer_list>
t_mat create(const t_cont_outer<t_vec>& lst, bool bRow = false)
requires is_mat<t_mat> && is_basic_vec<t_vec>
{
const std::size_t iCols = lst.size();
const std::size_t iRows = lst.begin()->size();
t_mat mat = unit<t_mat>(iRows, iCols);
auto iterCol = lst.begin();
for(std::size_t iCol=0; iCol<iCols; ++iCol)
{
for(std::size_t iRow=0; iRow<iRows; ++iRow)
mat(iRow, iCol) = (*iterCol)[iRow];
std::advance(iterCol, 1);
}
if(bRow) mat = trans<t_mat>(mat);
return mat;
}
/**
* create matrix from initializer_list in column/row order
*/
template<class t_mat>
t_mat create_mat(const std::initializer_list<typename t_mat::value_type>& lst)
requires is_mat<t_mat>
{
const std::size_t N = std::sqrt(lst.size());
t_mat mat = unit<t_mat>(N, N);
auto iter = lst.begin();
for(std::size_t iRow=0; iRow<N; ++iRow)
{
for(std::size_t iCol=0; iCol<N; ++iCol)
{
mat(iRow, iCol) = *iter;
std::advance(iter, 1);
}
}
return mat;
}
/**
* create matrix from initializer_list in column/row order
*/
template<class t_mat>
t_mat create(const std::initializer_list<typename t_mat::value_type>& lst)
requires is_mat<t_mat>
{
return create_mat<t_mat>(lst);
}
/**
* linearise a matrix to a vector container
*/
template<class t_vec, class t_mat>
t_vec convert(const t_mat& mat)
requires is_basic_vec<t_vec> && is_mat<t_mat>
{
using T_dst = typename t_vec::value_type;
using t_idx = decltype(mat.size1());
t_vec vec;
vec.reserve(mat.size1()*mat.size2());
for(t_idx iRow=0; iRow<mat.size1(); ++iRow)
for(t_idx iCol=0; iCol<mat.size2(); ++iCol)
vec.push_back(T_dst(mat(iRow, iCol)));
return vec;
}
/**
* converts matrix containers of different value types
*/
template<class t_mat_dst, class t_mat_src>
t_mat_dst convert(const t_mat_src& mat)
requires is_mat<t_mat_dst> && is_mat<t_mat_src>
{
using T_dst = typename t_mat_dst::value_type;
using t_idx = decltype(mat.size1());
// in case the static size of the destination vector is larger than the source's
t_idx maxRows = std::max(mat.size1(), t_idx(t_mat_dst{}.size1()));
t_idx maxCols = std::max(mat.size2(), t_idx(t_mat_dst{}.size2()));
t_mat_dst matdst = unit<t_mat_dst>(maxRows, maxCols);
for(t_idx iRow=0; iRow<mat.size1(); ++iRow)
for(t_idx iCol=0; iCol<mat.size2(); ++iCol)
matdst(iRow, iCol) = T_dst(mat(iRow, iCol));
return matdst;
}
/**
* converts vector containers of different value types
*/
template<class t_vec_dst, class t_vec_src>
t_vec_dst convert(const t_vec_src& vec)
requires is_vec<t_vec_dst> && is_vec<t_vec_src>
{
using T_dst = typename t_vec_dst::value_type;
using t_idx = decltype(vec.size());
t_vec_dst vecdst = create<t_vec_dst>(vec.size());
for(t_idx i=0; i<vec.size(); ++i)
vecdst[i] = T_dst(vec[i]);
return vecdst;
}
/**
* converts a container of objects
*/
template<class t_obj_dst, class t_obj_src, template<class...> class t_cont>
t_cont<t_obj_dst> convert(const t_cont<t_obj_src>& src_objs)
requires (is_vec<t_obj_dst> || is_mat<t_obj_dst>) && (is_vec<t_obj_src> || is_mat<t_obj_src>)
{
t_cont<t_obj_dst> dst_objs;
dst_objs.reserve(src_objs.size());
for(const t_obj_src& src_obj : src_objs)
dst_objs.emplace_back(convert<t_obj_dst, t_obj_src>(src_obj));
return dst_objs;
}
/**
* get a column vector from a matrix
*/
template<class t_mat, class t_vec>
t_vec col(const t_mat& mat, std::size_t col)
requires is_mat<t_mat> && is_basic_vec<t_vec>
{
t_vec vec;
if constexpr(is_dyn_vec<t_vec>)
vec = t_vec(mat.size1());
for(std::size_t i=0; i<mat.size1(); ++i)
vec[i] = mat(i, col);
return vec;
}
/**
* get a row vector from a matrix
*/
template<class t_mat, class t_vec>
t_vec row(const t_mat& mat, std::size_t row)
requires is_mat<t_mat> && is_basic_vec<t_vec>
{
t_vec vec;
if constexpr(is_dyn_vec<t_vec>)
vec = t_vec(mat.size2());
for(std::size_t i=0; i<mat.size2(); ++i)
vec[i] = mat(row, i);
return vec;
}
/**
* set a column vector in a matrix
*/
template<class t_mat, class t_vec>
void set_col(t_mat& mat, const t_vec& vec, std::size_t col)
requires is_mat<t_mat> && is_basic_vec<t_vec>
{
for(std::size_t i=0; i<std::min<std::size_t>(mat.size1(), vec.size()); ++i)
mat(i, col) = vec[i];
}
/**
* set a row vector in a matrix
*/
template<class t_mat, class t_vec>
void set_row(t_mat& mat, const t_vec& vec, std::size_t row)
requires is_mat<t_mat> && is_basic_vec<t_vec>
{
for(std::size_t i=0; i<std::min<std::size_t>(mat.size1(), vec.size()); ++i)
mat(row, i) = vec[i];
}
/**
* inner product <vec1|vec2>
*/
template<class t_vec>
typename t_vec::value_type inner(const t_vec& vec1, const t_vec& vec2)
requires is_basic_vec<t_vec>
{
typename t_vec::value_type val{0};
auto size = vec1.size();
using local_size_t = std::decay_t<decltype(size)>;
for(local_size_t i=0; i<size; ++i)
{
if constexpr(is_complex<typename t_vec::value_type>)
val += std::conj(vec1[i]) * vec2[i];
else
val += vec1[i] * vec2[i];
}
return val;
}
/**
* inner product between two vectors of different type
*/
template<class t_vec1, class t_vec2>
typename t_vec1::value_type inner(const t_vec1& vec1, const t_vec2& vec2)
requires is_basic_vec<t_vec1> && is_basic_vec<t_vec2>
{
if(vec1.size()==0 || vec2.size()==0)
return typename t_vec1::value_type{};
// first element
auto val = vec1[0]*vec2[0];
// remaining elements
for(std::size_t i=1; i<std::min(vec1.size(), vec2.size()); ++i)
{
if constexpr(is_complex<typename t_vec1::value_type>)
{
auto prod = std::conj(vec1[i]) * vec2[i];
val = val + prod;
}
else
{
auto prod = vec1[i]*vec2[i];
val = val + prod;
}
}
return val;
}
/**
* matrix-matrix product: c_ij = a_ik b_kj
*/
template<class t_mat>
t_mat prod(const t_mat& mat1, const t_mat& mat2, bool assert_sizes/*=true*/)
requires tl2::is_basic_mat<t_mat> && tl2::is_dyn_mat<t_mat>
{
// if not asserting sizes, the inner size will use the minimum of the two matrix sizes
if(assert_sizes)
{
if constexpr(tl2::is_dyn_mat<t_mat>)
assert((mat1.size2() == mat2.size1()));
else
static_assert(t_mat::size2() == t_mat::size1());
}
t_mat matRet(mat1.size1(), mat2.size2());
const std::size_t innersize = std::min(mat1.size2(), mat2.size1());
for(std::size_t row=0; row<matRet.size1(); ++row)
{
for(std::size_t col=0; col<matRet.size2(); ++col)
{
matRet(row, col) = 0;
for(std::size_t i=0; i<innersize; ++i)
matRet(row, col) += mat1(row, i) * mat2(i, col);
}
}
return matRet;
}
/**
* element-wise division
*/
template<class t_mat>
t_mat div_perelem(const t_mat& mat1, const t_mat& mat2, bool assert_sizes=true)
requires tl2::is_basic_mat<t_mat>
{
if(assert_sizes)
{
if constexpr(tl2::is_dyn_mat<t_mat>)
assert(mat1.size1() == mat2.size1() && mat1.size2() == mat2.size2());
}
t_mat matRet = zero<t_mat>(mat1.size1(), mat1.size2());
for(std::size_t row=0; row<matRet.size1(); ++row)
for(std::size_t col=0; col<matRet.size2(); ++col)
matRet(row, col) = mat1(row, col) / mat2(row,col);
return matRet;
}
/**
* 2-norm
*/
template<class t_vec, class t_real = typename t_vec::value_type>
t_real norm(const t_vec& vec)
requires is_basic_vec<t_vec>
{
t_real d = static_cast<t_real>(inner<t_vec>(vec, vec));
return std::sqrt(d);
}
/**
* n-norm
*/
template<class t_vec, class t_real = typename t_vec::value_type>
typename t_vec::value_type norm(const t_vec& vec, t_real n)
requires is_basic_vec<t_vec>
{
t_real d = t_real{0};
for(std::size_t i=0; i<vec.size(); ++i)
d += std::pow(std::abs(vec[i]), n);
return std::pow(d, t_real(1)/n);
}
/**
* outer product
*/
template<class t_mat, class t_vec>
t_mat outer(const t_vec& vec1, const t_vec& vec2)
requires is_basic_vec<t_vec> && is_mat<t_mat>
{
const std::size_t N1 = vec1.size();
const std::size_t N2 = vec2.size();
t_mat mat;
if constexpr(is_dyn_mat<t_mat>)
mat = t_mat(N1, N2);
for(std::size_t n1=0; n1<N1; ++n1)
{
for(std::size_t n2=0; n2<N2; ++n2)
{
if constexpr(is_complex<typename t_vec::value_type>)
mat(n1, n2) = std::conj(vec1[n1]) * vec2[n2];
else
mat(n1, n2) = vec1[n1]*vec2[n2];
}
}
return mat;
}
// ----------------------------------------------------------------------------
// operations with metric
// ----------------------------------------------------------------------------
/**
* covariant metric tensor: g_{i,j} = e_i * e_j
* @see (Arens 2015), p. 808
*/
template<class t_mat, class t_vec, template<class...> class t_cont=std::initializer_list>
t_mat metric(const t_cont<t_vec>& basis_co)
requires is_basic_mat<t_mat> && is_basic_vec<t_vec>
{
const std::size_t N = basis_co.size();
t_mat g_co;
if constexpr(is_dyn_mat<t_mat>)
g_co = t_mat(N, N);
auto iter_i = basis_co.begin();
for(std::size_t i=0; i<N; ++i)
{
auto iter_j = basis_co.begin();
for(std::size_t j=0; j<N; ++j)
{
g_co(i,j) = inner<t_vec>(*iter_i, *iter_j);
std::advance(iter_j, 1);
}
std::advance(iter_i, 1);
}
return g_co;
}
/**
* covariant metric tensor: g_{i,j} = e_i * e_j
* @see (Arens 2015), p. 815
*/
template<class t_mat>
t_mat metric(const t_mat& basis_co)
requires is_basic_mat<t_mat>
{
t_mat basis_trans = trans(basis_co);
return basis_trans * basis_co;
}
/**
* get levi-civita symbol in fractional coordinates
* @see (Arens 2015), p. 815
*/
template<class t_mat>
typename t_mat::value_type levi(const t_mat& basis_co,
const std::initializer_list<std::size_t>& indices)
requires is_basic_mat<t_mat>
{
using size_t = decltype(basis_co.size1());
using t_vec = vec<typename t_mat::value_type>;
t_mat mat = create<t_mat>(basis_co.size1(), basis_co.size2());
auto iter = indices.begin();
size_t maxcols = std::min(indices.size(), basis_co.size2());
for(size_t i=0; i<maxcols; ++i)
{
set_col<t_mat, t_vec>(
mat, col<t_mat, t_vec>(basis_co, *iter), i);
std::advance(iter, 1);
}
return det<t_mat>(mat);
}
/**
* cross product in fractional coordinates: c^l = eps_ijk g^li a^j b^k
* @see (Arens 2015), p. 815
*/
template<class t_mat, class t_vec>
t_vec cross(const t_mat& B, const t_vec& a, const t_vec& b)
requires is_basic_mat<t_mat> && is_basic_vec<t_vec>
{
using size_t = decltype(B.size1());
using t_real = typename t_mat::value_type;
// metric and its inverse
auto G = metric<t_mat>(B);
auto [G_inv, ok] = inv(G);
// maximum indices
const size_t i_max = G_inv.size1();
const size_t j_max = a.size();
const size_t k_max = b.size();
const size_t l_max = G_inv.size2();
// cross product result vector
t_vec c = zero<t_vec>(l_max);
for(size_t i=0; i<i_max; ++i)
{
for(size_t j=0; j<j_max; ++j)
{
for(size_t k=0; k<k_max; ++k)
{
t_real eps = levi<t_mat>(B, {i,j,k});
for(size_t l=0; l<l_max; ++l)
c[l] += eps * G_inv(l,i) * a[j] * b[k];
}
}
}
return c;
}
/**
* lower index using metric
* @see (Arens 2015), p. 808
*/
template<class t_mat, class t_vec>
t_vec lower_index(const t_mat& metric_co, const t_vec& vec_contra)
requires is_basic_mat<t_mat> && is_basic_vec<t_vec>
{
const std::size_t N = vec_contra.size();
t_vec vec_co = zero<t_vec>(N);
for(std::size_t i=0; i<N; ++i)
for(std::size_t j=0; j<N; ++j)
vec_co[i] += metric_co(i,j) * vec_contra[j];
return vec_co;
}
/**
* raise index using metric
* @see (Arens 2015), p. 808
*/
template<class t_mat, class t_vec>
t_vec raise_index(const t_mat& metric_contra, const t_vec& vec_co)
requires is_basic_mat<t_mat> && is_basic_vec<t_vec>
{
const std::size_t N = vec_co.size();
t_vec vec_contra = zero<t_vec>(N);
for(std::size_t i=0; i<N; ++i)
for(std::size_t j=0; j<N; ++j)
vec_contra[i] += metric_contra(i,j) * vec_co[j];
return vec_contra;
}
/**
* inner product using metric
* @see (Arens 2015), p. 808
*/
template<class t_mat, class t_vec>
typename t_vec::value_type inner(const t_mat& metric_co,
const t_vec& vec1_contra, const t_vec& vec2_contra)
requires is_basic_mat<t_mat> && is_basic_vec<t_vec>
{
t_vec vec2_co = lower_index<t_mat, t_vec>(metric_co, vec2_contra);
return inner<t_vec>(vec1_contra, vec2_co);
}
/**
* 2-norm using metric
* @see (Arens 2015), p. 808
*/
template<class t_mat, class t_vec>
typename t_vec::value_type norm(const t_mat& metric_co, const t_vec& vec_contra)
requires is_basic_vec<t_vec>
{
return std::sqrt(inner<t_mat, t_vec>(metric_co, vec_contra, vec_contra));
}
/**
* angle between vectors under a given metric
* @see (Arens 2015), p. 808
*/
template<class t_mat, class t_vec>
typename t_vec::value_type angle(const t_mat& metric_co,
const t_vec& vec1_contra, const t_vec& vec2_contra)
requires is_basic_mat<t_mat> && is_basic_vec<t_vec>
{
using t_real = typename t_mat::value_type;
t_real len1 = norm<t_mat, t_vec>(metric_co, vec1_contra);
t_real len2 = norm<t_mat, t_vec>(metric_co, vec2_contra);
t_real c = inner<t_mat, t_vec>(metric_co, vec1_contra, vec2_contra);
c /= len1 * len2;
c = clamp<t_real>(c, -1, 1);
return std::acos(c);
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// tas calculations
// @see M. D. Lumsden, J. L. Robertson, and M. Yethiraj, J. Appl. Crystallogr. 38(3), pp. 405–411 (2005), doi: 10.1107/S0021889805004875.
// @see (Shirane 2002)
// ----------------------------------------------------------------------------
/**
* angle between ki and kf in the scattering triangle
* @returns nullopt if the angle can't be reached
*
* |Q> = |ki> - |kf>
* Q^2 = ki^2 + kf^2 - 2*<ki|kf>
* 2*<ki|kf> = ki^2 + kf^2 - Q^2
* cos phi = (ki^2 + kf^2 - Q^2) / (2 ki*kf)
*/
template<typename t_real>
std::optional<t_real> calc_tas_angle_ki_kf(
t_real ki, t_real kf, t_real Q, t_real sense=1)
{
t_real c = (ki*ki + kf*kf - Q*Q) / (t_real(2)*ki*kf);
if(std::abs(c) > t_real(1))
return std::nullopt;
return sense*std::acos(c);
}
/**
* angle between ki and Q in the scattering triangle
* @returns nullopt if the angle can't be reached
*
* |Q> = |ki> - |kf>
* |kf> = |ki> + |Q>
* kf^2 = ki^2 + Q^2 - 2*<ki|Q>
* 2*<ki|Q> = ki^2 + Q^2 - kf^2
* cos phi = (ki^2 + Q^2 - kf^2) / (2 ki*Q)
*/
template<typename t_real>
std::optional<t_real> calc_tas_angle_ki_Q(
t_real ki, t_real kf, t_real Q, t_real sense=1)
{
t_real c = (ki*ki + Q*Q - kf*kf) / (t_real(2)*ki*Q);
if(std::abs(c) > t_real(1))
return std::nullopt;
return sense*std::acos(c);
}
/**
* get length of Q
* |Q> = |ki> - |kf>
* Q^2 = ki^2 + kf^2 - 2*<ki|kf>
* Q^2 = ki^2 + kf^2 - 2*ki*kf*cos(a4)
*/
template<typename t_real>
t_real calc_tas_Q_len(t_real ki, t_real kf, t_real a4)
{
t_real Qsq = ki*ki + kf*kf - t_real(2)*ki*kf*std::cos(a4);
return std::sqrt(Qsq);
}
/**
* get tas a3 and a4 angles
* @return [a3, a4, distance of Q to the scattering plane]
// @see M. D. Lumsden, et al., doi: 10.1107/S0021889805004875.
*/
template<class t_mat, class t_vec, class t_real = typename t_mat::value_type>
std::tuple<bool, t_real, t_real, t_real> calc_tas_a3a4(
const t_mat& B, t_real ki_lab, t_real kf_lab,
const t_vec& Q_rlu, const t_vec& orient_rlu, const t_vec& orient_up_rlu,
t_real sample_sense = 1, t_real a3_offs = pi<t_real>)
requires is_basic_mat<t_mat> && is_basic_vec<t_vec>
{
// metric from crystal B matrix
t_mat G = tl2::metric<t_mat>(B);
// length of Q vector
t_real Q_len_lab = norm<t_mat, t_vec>(G, Q_rlu);
// angle xi between Q and orientation reflex
t_real xi = angle<t_mat, t_vec>(G, Q_rlu, orient_rlu);
// sign/direction of xi
t_vec xivec = cross<t_mat, t_vec>(G, orient_rlu, Q_rlu);
t_real xidir = inner<t_mat, t_vec>(G, xivec, orient_up_rlu);
if(xidir < t_real(0))
xi = -xi;
// angle psi between ki and Q
std::optional<t_real> psi =
calc_tas_angle_ki_Q<t_real>(ki_lab, kf_lab, Q_len_lab, sample_sense);
if(!psi)
return std::make_tuple(false, 0, 0, 0);
// crystal and scattering angle
t_real a3 = - *psi - xi + a3_offs;
std::optional<t_real> a4 =
calc_tas_angle_ki_kf<t_real>(ki_lab, kf_lab, Q_len_lab);
if(!a4)
return std::make_tuple(false, a3, 0, 0);
*a4 *= sample_sense;
// distance of Q to the scattering plane
t_real dist_Q_plane = inner<t_mat, t_vec>(G, Q_rlu, orient_up_rlu);
dist_Q_plane /= norm<t_mat, t_vec>(G, orient_up_rlu);
return std::make_tuple(true, a3, *a4, dist_Q_plane);
}
/**
* get hkl position of a tas
* @return Q_rlu
// @see M. D. Lumsden, et al., doi: 10.1107/S0021889805004875.
*/
template<class t_mat, class t_vec, class t_real = typename t_mat::value_type>
std::optional<t_vec> calc_tas_hkl(
const t_mat& B, t_real ki_lab, t_real kf_lab, t_real Q_len_lab, t_real a3,
const t_vec& orient_rlu, const t_vec& orient_up_rlu,
t_real sample_sense = 1, t_real a3_offs = pi<t_real>)
requires is_basic_mat<t_mat> && is_basic_vec<t_vec>
{
auto [Binv, ok] = inv<t_mat>(B);
if(!ok)
return std::nullopt;
// angle psi between ki and Q
std::optional<t_real> psi =
calc_tas_angle_ki_Q<t_real>(ki_lab, kf_lab, Q_len_lab, sample_sense);
if(!psi)
return std::nullopt;
// angle xi between Q and orientation reflex
t_real xi = a3_offs - a3 - *psi;
t_vec rotaxis_lab = B * orient_up_rlu;
t_mat rotmat = rotation<t_mat, t_vec>(rotaxis_lab, xi, false);
t_vec orient_lab = B * orient_rlu;
t_vec Q_lab = rotmat * orient_lab;
Q_lab /= norm<t_vec>(Q_lab);
Q_lab *= Q_len_lab;
t_vec Q_rlu = Binv * Q_lab;
return Q_rlu;
}
/**
* get a1 or a5 angle
* @returns nullopt of the angle can't be reached
* @see https://en.wikipedia.org/wiki/Bragg's_law
*
* Bragg: n lam = 2d sin(theta)
* n 2pi / k = 2d sin(theta)
* n pi / k = d sin(theta)
* theta = asin(n pi / (k d))
*/
template<class t_real>
std::optional<t_real> calc_tas_a1(t_real k, t_real d)
{
t_real sintheta = pi<t_real> / (k*d);
if(std::abs(sintheta) > t_real(1))
return std::nullopt;
return std::asin(sintheta);
}
/**
* get k from crystal angle
* @see https://en.wikipedia.org/wiki/Bragg's_law
*
* k = n pi / (d sin(theta))
*/
template<class t_real>
t_real calc_tas_k(t_real theta, t_real d)
{
t_real sintheta = std::abs(std::sin(theta));
return pi<t_real> / (d * sintheta);
}
/**
* get ki from kf and energy transfer
*/
template<class t_real>
t_real calc_tas_ki(t_real kf, t_real E)
{
return std::sqrt(kf*kf + E_to_k2<t_real>*E);
}
/**
* get kf from ki and energy transfer
*/
template<class t_real>
t_real calc_tas_kf(t_real ki, t_real E)
{
return std::sqrt(ki*ki - E_to_k2<t_real>*E);
}
/**
* get energy transfer from ki and kf
*/
template<class t_real>
t_real calc_tas_E(t_real ki, t_real kf)
{
return (ki*ki - kf*kf) / E_to_k2<t_real>;
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// projection operators
// ----------------------------------------------------------------------------
/**
* matrix to project onto vector: P = |v><v|
* from: |x'> = <v|x> * |v> = |v><v|x> = |v><v| * |x>
* @see (Arens 2015), p. 814 for the projection tensor
*/
template<class t_mat, class t_vec>
t_mat projector(const t_vec& vec, bool bIsNormalised = true)
requires is_vec<t_vec> && is_mat<t_mat>
{
if(bIsNormalised)
{
return outer<t_mat, t_vec>(vec, vec);
}
else
{
const auto len = norm<t_vec>(vec);
t_vec _vec = vec / len;
return outer<t_mat, t_vec>(_vec, _vec);
}
}
/**
* project vec1 onto vec2
*
* proj_op = |vec2><vec2¦/ len(vec2)^2, len(vec2) = sqrt(<vec2|vec2>)
* proj = proj_op * vec1 = |vec2> * <vec2|vec1> / <vec2|vec2>
*
* @see (Arens 2015), p. 814 for the projection tensor
*/
template<class t_vec>
t_vec project(const t_vec& vec, const t_vec& vecProj, bool bIsNormalised = true)
requires is_vec<t_vec>
{
if(bIsNormalised)
{
return inner<t_vec>(vec, vecProj) * vecProj;
}
else
{
const auto len = norm<t_vec>(vecProj);
const t_vec _vecProj = vecProj / len;
return inner<t_vec>(vec, _vecProj) * _vecProj;
}
}
/**
* project vector vec onto another vector vecProj
* don't multiply with direction vector
*
* @see (Arens 2015), p. 814 for the projection tensor
*/
template<class t_vec, class t_real = typename t_vec::value_type>
t_real project_scalar(const t_vec& vec, const t_vec& vecProj, bool bIsNormalised = true)
requires is_vec<t_vec>
{
if(bIsNormalised)
{
return inner<t_vec>(vec, vecProj);
}
else
{
const auto len = norm<t_vec>(vecProj);
const t_vec _vecProj = vecProj / len;
return inner<t_vec>(vec, _vecProj);
}
}
/**
* project vector vec onto the line lineOrigin + lam*lineDir
* (shifts line to go through origin, calculate projection and shift back)
* @returns [closest point, distance, projection parameter]
*
* @see https://de.wikipedia.org/wiki/Lot_(Mathematik)
*/
template<class t_vec, class t_real = typename t_vec::value_type>
std::tuple<t_vec, t_real, t_real> project_line(const t_vec& vec,
const t_vec& lineOrigin, const t_vec& _lineDir, bool bIsNormalised = true)
requires is_vec<t_vec>
{
const t_real lenDir = bIsNormalised ? 1 : norm<t_vec>(_lineDir);
const t_vec lineDir = _lineDir / lenDir;
const t_vec ptShifted = vec - lineOrigin;
const t_real paramProj = project_scalar<t_vec, t_real>(ptShifted, lineDir, true);
const t_vec ptProj = paramProj * lineDir;
const t_vec ptNearest = lineOrigin + ptProj;
const t_real dist = norm<t_vec>(vec - ptNearest);
return std::make_tuple(ptNearest, dist, paramProj);
}
/**
* distance between point and line
* @see (Arens 2015), p. 711
*/
template<class t_vec, class t_real = typename t_vec::value_type>
t_real dist_pt_line(const t_vec& pt,
const t_vec& linePt1, const t_vec& linePt2,
bool bLineIsInfinite = true)
requires is_vec<t_vec>
{
const std::size_t dim = linePt1.size();
const t_vec lineDir = linePt2 - linePt1;
const auto [nearestPt, dist, paramProj] =
project_line<t_vec>(pt, linePt1, lineDir, false);
// get point component with max. difference
t_real diff = -1.;
std::size_t compidx = 0;
for(std::size_t i=0; i<dim; ++i)
{
t_real newdiff = std::abs(linePt2[i] - linePt1[i]);
if(newdiff > diff)
{
diff = newdiff;
compidx = i;
}
}
t_real t = (nearestPt[compidx]-linePt1[compidx]) / (linePt2[compidx]-linePt1[compidx]);
if(bLineIsInfinite || (t>=t_real{0} && t<=t_real{1}))
{
// projection is on line -> use distance between point and projection
return dist;
}
else
{
// projection is not on line -> use distance between point and closest line end point
if(std::abs(t-t_real{0}) < std::abs(t-t_real{1}))
return norm<t_vec>(linePt1 - pt);
else
return norm<t_vec>(linePt2 - pt);
}
}
/**
* matrix to project onto orthogonal complement (plane perpendicular to vector): P = 1-|v><v|
* from completeness relation: 1 = sum_i |v_i><v_i| = |x><x| + |y><y| + |z><z|
*
* @see (Arens 2015), p. 814 for the projection tensor
*/
template<class t_mat, class t_vec>
t_mat ortho_projector(const t_vec& vec, bool bIsNormalised = true)
requires is_vec<t_vec> && is_mat<t_mat>
{
const std::size_t iSize = vec.size();
return unit<t_mat>(iSize) -
projector<t_mat, t_vec>(vec, bIsNormalised);
}
/**
* matrix to mirror on plane perpendicular to vector: P = 1 - 2*|v><v|
* subtracts twice its projection onto the plane normal from the vector
*
* @see (Arens 2015), p. 710
*/
template<class t_mat, class t_vec>
t_mat ortho_mirror_op(const t_vec& vec, bool bIsNormalised = true)
requires is_vec<t_vec> && is_mat<t_mat>
{
using T = typename t_vec::value_type;
const std::size_t iSize = vec.size();
return unit<t_mat>(iSize) -
T(2)*projector<t_mat, t_vec>(vec, bIsNormalised);
}
/**
* matrix to mirror [a, b, c, ...] into, e.g., [a, b', 0, 0]
* @see (Scarpino 2011), p. 268
*/
template<class t_mat, class t_vec>
t_mat ortho_mirror_zero_op(const t_vec& vec, std::size_t row)
requires is_vec<t_vec> && is_mat<t_mat>
{
using T = typename t_vec::value_type;
const std::size_t N = vec.size();
t_vec vecSub = zero<t_vec>(N);
for(std::size_t i=0; i<row; ++i)
vecSub[i] = vec[i];
// norm of rest vector
T n = T(0);
for(std::size_t i=row; i<N; ++i)
n += vec[i]*vec[i];
vecSub[row] = std::sqrt(n);
const t_vec vecOp = vec - vecSub;
// nothing to do -> return unit matrix
if(equals_0<t_vec>(vecOp))
return unit<t_mat>(vecOp.size(), vecOp.size());
return ortho_mirror_op<t_mat, t_vec>(vecOp, false);
}
/**
* project vector vec onto plane through the origin and perpendicular to vector vecNorm
* (e.g. used to calculate magnetic interaction vector M_perp)
*/
template<class t_vec>
t_vec ortho_project(const t_vec& vec, const t_vec& vecNorm, bool bIsNormalised = true)
requires is_vec<t_vec>
{
return vec - project<t_vec>(vec, vecNorm, bIsNormalised);
}
/**
* project vector vec onto plane perpendicular to vector vecNorm with distance d
* vecNorm has to be normalised and plane in Hessian form: x*vecNorm = d
*/
template<class t_vec>
t_vec ortho_project_plane(const t_vec& vec,
const t_vec& vecNorm, typename t_vec::value_type d)
requires is_vec<t_vec>
{
// project onto plane through origin
t_vec vecProj0 = ortho_project<t_vec>(vec, vecNorm, 1);
// add distance of plane to origin
return vecProj0 + d*vecNorm;
}
/**
* mirror a vector on a plane perpendicular to vector vecNorm with distance d
* vecNorm has to be normalised and plane in Hessian form: x*vecNorm = d
* @see (Arens 2015), p. 710
*/
template<class t_vec>
t_vec ortho_mirror_plane(const t_vec& vec,
const t_vec& vecNorm, typename t_vec::value_type d)
requires is_vec<t_vec>
{
using T = typename t_vec::value_type;
t_vec vecProj = ortho_project_plane<t_vec>(vec, vecNorm, d);
return vec - T(2)*(vec - vecProj);
}
/**
* find orthonormal substitute basis for vector space (Gram-Schmidt algo)
* remove orthogonal projections to all other base vectors: |i'> = (1 - sum_{j<i} |j><j|) |i>
*
* @see https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process
* @see (Arens 2015), p. 744
*/
template<class t_vec,
template<class...> class t_cont_in = std::initializer_list,
template<class...> class t_cont_out = std::vector>
t_cont_out<t_vec> orthonorm_sys(const t_cont_in<t_vec>& sys)
requires is_vec<t_vec>
{
t_cont_out<t_vec> newsys;
newsys.reserve(sys.size());
for(const t_vec& vecSys : sys)
{
t_vec vecOrthoProj = vecSys;
// subtract projections to other basis vectors
for(const t_vec& vecNewSys : newsys)
vecOrthoProj -= project<t_vec>(vecSys, vecNewSys, true);
// normalise
vecOrthoProj /= norm<t_vec>(vecOrthoProj);
newsys.emplace_back(std::move(vecOrthoProj));
}
return newsys;
}
// ----------------------------------------------------------------------------
/**
* submatrix removing a column/row from a matrix stored in a vector container
*/
template<class t_vec>
t_vec flat_submat(const t_vec& mat,
std::size_t iNumRows, std::size_t iNumCols,
std::size_t iRemRow, std::size_t iRemCol)
requires is_basic_vec<t_vec>
{
t_vec vec;
vec.reserve(mat.size());
for(std::size_t iRow=0; iRow<iNumRows; ++iRow)
{
if(iRow == iRemRow)
continue;
for(std::size_t iCol=0; iCol<iNumCols; ++iCol)
{
if(iCol == iRemCol)
continue;
vec.push_back(mat[iRow*iNumCols + iCol]);
}
}
return vec;
}
/**
* submatrix removing a column/row from a matrix
*/
template<class t_mat>
t_mat submat(const t_mat& mat, decltype(mat.size1()) iRemRow, decltype(mat.size2()) iRemCol)
requires is_basic_mat<t_mat> && is_dyn_mat<t_mat>
{
using size_t = decltype(mat.size1());
t_mat matRet = create<t_mat>(mat.size1()-1, mat.size2()-1);
size_t iResRow = 0;
for(size_t iRow=0; iRow<mat.size1(); ++iRow)
{
if(iRow == iRemRow)
continue;
size_t iResCol = 0;
for(size_t iCol=0; iCol<mat.size2(); ++iCol)
{
if(iCol == iRemCol)
continue;
matRet(iResRow, iResCol) = mat(iRow, iCol);
++iResCol;
}
++iResRow;
}
return matRet;
}
/**
* determinant from a square matrix stored in a vector container
* @see (Merziger 2006), p. 185
*/
template<class t_vec>
typename t_vec::value_type flat_det(const t_vec& mat, std::size_t iN)
requires is_basic_vec<t_vec>
{
using T = typename t_vec::value_type;
// special cases
if(iN == 0)
return 0;
else if(iN == 1)
return mat[0];
else if(iN == 2)
return mat[0]*mat[3] - mat[1]*mat[2];
// recursively expand determiant along a row
T fullDet = T(0);
std::size_t iRow = 0;
// get row with maximum number of zeros
std::size_t iMaxNumZeros = 0;
for(std::size_t iCurRow=0; iCurRow<iN; ++iCurRow)
{
std::size_t iNumZeros = 0;
for(std::size_t iCurCol=0; iCurCol<iN; ++iCurCol)
{
if(equals<T>(mat[iCurRow*iN + iCurCol], T(0)))
++iNumZeros;
}
if(iNumZeros > iMaxNumZeros)
{
iRow = iCurRow;
iMaxNumZeros = iNumZeros;
}
}
for(std::size_t iCol=0; iCol<iN; ++iCol)
{
const T elem = mat[iRow*iN + iCol];
if(equals<T>(elem, 0))
continue;
const T sgn = ((iRow+iCol) % 2) == 0 ? T(1) : T(-1);
const t_vec subMat = flat_submat<t_vec>(mat, iN, iN, iRow, iCol);
const T subDet = flat_det<t_vec>(subMat, iN-1) * sgn;
fullDet += elem * subDet;
}
return fullDet;
}
/**
* trace
*/
template<class t_mat>
typename t_mat::value_type trace(const t_mat& mat)
requires is_mat<t_mat>
{
using T = typename t_mat::value_type;
T _tr = T(0);
std::size_t N = std::min(mat.size1(), mat.size2());
for(std::size_t i=0; i<N; ++i)
_tr += mat(i,i);
return _tr;
}
/**
* gets reciprocal basis vectors |b_i> from real basis vectors |a_i> (and vice versa)
* c: multiplicative constant (c=2*pi for physical lattices, c=1 for mathematics)
*
* Def.: <b_i | a_j> = c * delta(i,j) =>
*
* e.g. 2d case:
* ( a_1x a_2x )
* ( a_1y a_2y )
*
* ( b_1x b_1y ) ( 1 0 )
* ( b_2x b_2y ) ( 0 1 )
*
* B^t * A = I
* A = B^(-t)
*/
template<class t_mat, class t_vec,
template<class...> class t_cont_in = std::initializer_list,
template<class...> class t_cont_out = std::vector>
t_cont_out<t_vec> recip(const t_cont_in<t_vec>& lstReal, typename t_vec::value_type c=1)
requires is_mat<t_mat> && is_basic_vec<t_vec>
{
const t_mat basis = create<t_mat, t_vec, t_cont_in>(lstReal);
auto [basis_inv, bOk] = inv<t_mat>(basis);
basis_inv *= c;
t_cont_out<t_vec> lstRecip;
lstRecip.reserve(basis_inv.size1());
for(std::size_t currow=0; currow<basis_inv.size1(); ++currow)
{
const t_vec rowvec = row<t_mat, t_vec>(basis_inv, currow);
lstRecip.emplace_back(std::move(rowvec));
}
return lstRecip;
}
/**
* general n-dim cross product using determinant definition
*/
template<class t_vec, template<class...> class t_cont = std::initializer_list>
t_vec cross(const t_cont<t_vec>& vecs)
requires is_basic_vec<t_vec>
{
using T = typename t_vec::value_type;
// N also has to be equal to the vector size!
const std::size_t N = vecs.size()+1;
t_vec vec = zero<t_vec>(N);
for(std::size_t iComp=0; iComp<N; ++iComp)
{
std::vector<T> mat = zero<std::vector<T>>(N*N);
mat[0*N + iComp] = T(1);
std::size_t iRow = 0;
for(const t_vec& vec : vecs)
{
for(std::size_t iCol=0; iCol<N; ++iCol)
mat[(iRow+1)*N + iCol] = vec[iCol];
++iRow;
}
vec[iComp] = flat_det<decltype(mat)>(mat, N);
}
return vec;
}
/**
* intersection of plane <x|n> = d and line |org> + lam*|dir>
* @returns [position of intersection, 0: no intersection, 1: intersection, 2: line on plane, line parameter lambda]
*
* insert |x> = |org> + lam*|dir> in plane equation:
* <org|n> + lam*<dir|n> = d
* lam = (d - <org|n>) / <dir|n>
*
* @see http://mathworld.wolfram.com/Line-PlaneIntersection.html
*/
template<class t_vec>
std::tuple<t_vec, int, typename t_vec::value_type>
intersect_line_plane(
const t_vec& lineOrg, const t_vec& lineDir,
const t_vec& planeNorm, typename t_vec::value_type plane_d)
requires is_vec<t_vec>
{
using T = typename t_vec::value_type;
// are line and plane parallel?
const T dir_n = inner<t_vec>(lineDir, planeNorm);
if(equals<T>(dir_n, 0))
{
const T org_n = inner<t_vec>(lineOrg, planeNorm);
// line on plane?
if(equals<T>(org_n, plane_d))
return std::make_tuple(t_vec(), 2, T(0));
// no intersection
return std::make_tuple(t_vec(), 0, T(0));
}
const T org_n = inner<t_vec>(lineOrg, planeNorm);
const T lam = (plane_d - org_n) / dir_n;
const t_vec vecInters = lineOrg + lam*lineDir;
return std::make_tuple(vecInters, 1, lam);
}
/**
* intersection of a sphere and a line |org> + lam*|dir>
* @returns vector of intersections
* insert |x> = |org> + lam*|dir> in sphere equation <x-mid | x-mid> = r^2
*
* @see https://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection for the solution.
*/
template<class t_vec, template<class...> class t_cont = std::vector>
requires is_vec<t_vec>
t_cont<t_vec> intersect_line_sphere(
const t_vec& lineOrg, const t_vec& _lineDir,
const t_vec& sphereOrg, typename t_vec::value_type sphereRad,
bool linedir_normalised = false, bool only_segment = false,
typename t_vec::value_type eps = std::numeric_limits<typename t_vec::value_type>::epsilon())
{
using T = typename t_vec::value_type;
t_vec lineDir = _lineDir;
T lenDir = linedir_normalised ? T(1) : norm<t_vec>(lineDir);
if(!linedir_normalised)
lineDir /= lenDir;
auto vecDiff = sphereOrg - lineOrg;
auto proj = project_scalar<t_vec>(vecDiff, lineDir, true);
auto rt = proj*proj + sphereRad*sphereRad - inner<t_vec>(vecDiff, vecDiff);
// no intersection
if(rt < T(0))
return t_cont<t_vec>{};
// one intersection
if(equals(rt, T(0), eps))
{
T lam = proj/lenDir;
if(!only_segment || (only_segment && lam >= T(0) && lam < T(1)))
return t_cont<t_vec>{{ lineOrg + proj*lineDir }};
return t_cont<t_vec>{};
}
// two intersections
auto val = std::sqrt(rt);
t_cont<t_vec> inters;
inters.reserve(2);
T lam1 = (proj + val)/lenDir;
T lam2 = (proj - val)/lenDir;
if(!only_segment || (only_segment && lam1 >= T(0) && lam1 < T(1)))
inters.emplace_back(lineOrg + (proj + val)*lineDir);
if(!only_segment || (only_segment && lam2 >= T(0) && lam2 < T(1)))
inters.emplace_back(lineOrg + (proj - val)*lineDir);
// sort intersections by x
std::sort(inters.begin(), inters.end(),
[](const t_vec& vec1, const t_vec& vec2) -> bool
{ return vec1[0] < vec2[0]; });
return inters;
}
/**
* average vector or matrix
*/
template<class ty, template<class...> class t_cont = std::vector>
ty avg(const t_cont<ty>& vecs)
requires is_vec<ty> || is_mat<ty>
{
if(vecs.size() == 0)
return ty();
typename ty::value_type num = 1;
ty vec = *vecs.begin();
auto iter = vecs.begin();
std::advance(iter, 1);
for(; iter!=vecs.end(); std::advance(iter, 1))
{
vec += *iter;
++num;
}
vec /= num;
return vec;
}
/**
* intersection of a polygon and a line
* @returns [position of intersection, intersects?, line parameter lambda]
*/
template<class t_vec, template<class ...> class t_cont = std::vector>
std::tuple<t_vec, bool, typename t_vec::value_type>
intersect_line_poly(
const t_vec& lineOrg, const t_vec& lineDir,
const t_cont<t_vec>& poly)
requires is_vec<t_vec>
{
using T = typename t_vec::value_type;
// middle point
const t_vec mid = avg<t_vec, t_cont>(poly);
// calculate polygon plane
const t_vec vec0 = poly[0] - mid;
const t_vec vec1 = poly[1] - mid;
t_vec planeNorm = cross<t_vec>({vec0, vec1});
planeNorm /= norm<t_vec>(planeNorm);
const T planeD = inner<t_vec>(poly[0], planeNorm);
// intersection with plane
auto [vec, intersects, lam] =
intersect_line_plane<t_vec>(lineOrg, lineDir, planeNorm, planeD);
if(intersects != 1)
return std::make_tuple(t_vec(), false, T(0));
// is intersection point contained in polygon?
const t_vec* vecFirst = &(*poly.rbegin());
for(auto iter=poly.begin(); iter!=poly.end(); std::advance(iter, 1))
{
const t_vec* vecSecond = &(*iter);
const t_vec edge = *vecSecond - *vecFirst;
// plane through edge
t_vec edgeNorm = cross<t_vec>({edge, planeNorm});
edgeNorm /= norm<t_vec>(edgeNorm);
const T edgePlaneD = inner<t_vec>(*vecFirst, edgeNorm);
// side of intersection
const T ptEdgeD = inner<t_vec>(vec, edgeNorm);
// outside polygon?
if(ptEdgeD > edgePlaneD)
return std::make_tuple(t_vec(), false, T(0));
vecFirst = vecSecond;
}
// intersects with polygon
return std::make_tuple(vec, true, lam);
}
/**
* intersection of a polygon (transformed with a matrix) and a line
* @returns [position of intersection, intersects?, line parameter lambda]
*/
template<class t_vec, class t_mat, template<class ...> class t_cont = std::vector>
std::tuple<t_vec, bool, typename t_vec::value_type>
intersect_line_poly(
const t_vec& lineOrg, const t_vec& lineDir,
const t_cont<t_vec>& _poly, const t_mat& mat)
requires is_vec<t_vec> && is_mat<t_mat>
{
auto poly = _poly;
// transform each vertex of the polygon
// TODO: check for homogeneous coordinates!
for(t_vec& vec : poly)
vec = mat * vec;
return intersect_line_poly<t_vec, t_cont>(lineOrg, lineDir, poly);
}
/**
* intersection or closest points of lines |org1> + lam1*|dir1> and |org2> + lam2*|dir2>
* @returns [nearest position 1, nearest position 2, dist, valid?, line parameter 1, line parameter 2]
*
* |org1> + lam1*|dir1> = |org2> + lam2*|dir2>
* |org1> - |org2> = lam2*|dir2> - lam1*|dir1>
* |org1> - |org2> = (dir2 | -dir1) * |lam2 lam1>
* (dir2 | -dir1)^T * (|org1> - |org2>) = (dir2 | -dir1)^T * (dir2 | -dir1) * |lam2 lam1>
* |lam2 lam1> = ((dir2 | -dir1)^T * (dir2 | -dir1))^(-1) * (dir2 | -dir1)^T * (|org1> - |org2>)
*
* @see https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
*/
template<class t_vec, class t_real = typename t_vec::value_type>
std::tuple<t_vec, t_vec, bool, t_real, t_real, t_real>
intersect_line_line(
const t_vec& line1Org, const t_vec& line1Dir,
const t_vec& line2Org, const t_vec& line2Dir,
t_real eps = std::numeric_limits<t_real>::epsilon())
requires is_vec<t_vec>
{
const t_vec orgdiff = line1Org - line2Org;
// direction matrix (symmetric)
const t_real d11 = inner<t_vec>(line2Dir, line2Dir);
const t_real d12 = -inner<t_vec>(line2Dir, line1Dir);
const t_real d22 = inner<t_vec>(line1Dir, line1Dir);
const t_real d_det = d11*d22 - d12*d12;
// check if matrix is invertible
if(equals<t_real>(d_det, 0, eps))
return std::make_tuple(t_vec(), t_vec(), false, 0, 0, 0);
// inverse (symmetric)
const t_real d11_i = d22 / d_det;
const t_real d12_i = -d12 / d_det;
const t_real d22_i = d11 / d_det;
const t_vec v1 = d11_i*line2Dir - d12_i*line1Dir;
const t_vec v2 = d12_i*line2Dir - d22_i*line1Dir;
const t_real lam2 = inner<t_vec>(v1, orgdiff);
const t_real lam1 = inner<t_vec>(v2, orgdiff);
const t_vec pos1 = line1Org + lam1*line1Dir;
const t_vec pos2 = line2Org + lam2*line2Dir;
const t_real dist = norm<t_vec>(pos2 - pos1);
return std::make_tuple(pos1, pos2, true, dist, lam1, lam2);
}
/**
* intersection of planes <x|n1> = d1 and <x|n2> = d2
* @returns line [org, dir, 0: no intersection, 1: intersection, 2: planes coincide]
*
* @see http://mathworld.wolfram.com/Plane-PlaneIntersection.html
*/
template<class t_vec>
std::tuple<t_vec, t_vec, int>
intersect_plane_plane(
const t_vec& plane1Norm, typename t_vec::value_type plane1_d,
const t_vec& plane2Norm, typename t_vec::value_type plane2_d)
requires is_vec<t_vec>
{
using T = typename t_vec::value_type;
t_vec lineDir = cross<t_vec>({plane1Norm, plane2Norm});
const T lenCross = norm<t_vec>(lineDir);
// planes parallel or coinciding
if(equals<T>(lenCross, 0))
{
const bool bCoincide = equals<T>(plane1_d, plane2_d);
return std::make_tuple(t_vec(), t_vec(), bCoincide ? 2 : 0);
}
lineDir /= lenCross;
t_vec lineOrg = - cross<t_vec>({plane1Norm, lineDir}) * plane2_d
+ cross<t_vec>({plane2Norm, lineDir}) * plane1_d;
lineOrg /= lenCross;
return std::make_tuple(lineOrg, lineDir, 1);
}
/**
* uv coordinates of a point inside a polygon defined by three vertices
*/
template<class t_vec>
t_vec poly_uv_ortho(const t_vec& vert1, const t_vec& vert2, const t_vec& vert3,
const t_vec& uv1, const t_vec& uv2, const t_vec& uv3,
const t_vec& _pt)
requires is_vec<t_vec>
{
using T = typename t_vec::value_type;
t_vec vec12 = vert2 - vert1;
t_vec vec13 = vert3 - vert1;
t_vec uv12 = uv2 - uv1;
t_vec uv13 = uv3 - uv1;
// ----------------------------------------------------
// orthonormalisation
const T len12 = norm<t_vec>(vec12);
const T len13 = norm<t_vec>(vec13);
const T lenuv12 = norm<t_vec>(uv12);
const T lenuv13 = norm<t_vec>(uv13);
auto vecBasis = orthonorm_sys<t_vec, std::initializer_list, std::vector>({vec12, vec13});
auto uvBasis = orthonorm_sys<t_vec, std::initializer_list, std::vector>({uv12, uv13});
vec12 = vecBasis[0]*len12; vec13 = vecBasis[1]*len13;
uv12 = uvBasis[0]*lenuv12; uv13 = uvBasis[1]*lenuv13;
// ----------------------------------------------------
const t_vec pt = _pt - vert1;
// project a point onto a vector and return the fraction along that vector
auto project_lam = [](const t_vec& vec, const t_vec& vecProj) -> T
{
const T len = norm<t_vec>(vecProj);
const t_vec _vecProj = vecProj / len;
T lam = inner<t_vec>(vec, _vecProj);
return lam / len;
};
T lam12 = project_lam(pt, vec12);
T lam13 = project_lam(pt, vec13);
// uv coordinates at specified point
const t_vec uv_pt = uv1 + lam12*uv12 + lam13*uv13;
return uv_pt;
}
/**
* uv coordinates of a point inside a polygon defined by three vertices
* (more general version than poly_uv_ortho)
*/
template<class t_mat, class t_vec>
t_vec poly_uv(const t_vec& vert1, const t_vec& vert2, const t_vec& vert3,
const t_vec& uv1, const t_vec& uv2, const t_vec& uv3,
const t_vec& _pt)
requires is_mat<t_mat> && is_vec<t_vec>
{
t_vec vec12 = vert2 - vert1;
t_vec vec13 = vert3 - vert1;
t_vec vecnorm = cross<t_vec>({vec12, vec13});
// basis
const t_mat basis = create<t_mat, t_vec>({vec12, vec13, vecnorm}, false);
// reciprocal basis, RECI = REAL^(-T)
const auto [basisInv, bOk] = inv<t_mat>(basis);
if(!bOk) return zero<t_vec>(uv1.size());
t_vec pt = _pt - vert1; // real pt
pt = basisInv * pt; // reciprocal pt
// uv coordinates at specified point
t_vec uv12 = uv2 - uv1;
t_vec uv13 = uv3 - uv1;
// pt has components in common reciprocal basis
// assumes that both vector and uv coordinates have the same reciprocal basis
return uv1 + pt[0]*uv12 + pt[1]*uv13;
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Statistical functions
// ----------------------------------------------------------------------------
/**
* mean value
*/
template<class t_elem, template<class...> class t_cont = std::vector>
t_elem mean(const t_cont<t_elem>& vec)
requires is_basic_vec<t_cont<t_elem>>
{
if(vec.size()==0) return t_elem{};
else if(vec.size()==1) return *vec.begin();
using namespace tl2_ops;
//t_elem meanvec = std::accumulate(std::next(vec.begin(), 1), vec.end(), *vec.begin());
t_elem meanvec = *vec.begin();
auto iter = std::next(vec.begin(), 1);
for(; iter!=vec.end(); iter=std::next(iter, 1))
meanvec += *iter;
meanvec /= vec.size();
return meanvec;
}
/**
* mean value with given probability
*/
template<class t_vec_prob, class t_vec>
typename t_vec::value_type mean(const t_vec_prob& vecP, const t_vec& vec)
requires is_basic_vec<t_vec> && is_basic_vec<t_vec_prob>
{
typedef typename t_vec::value_type T;
typedef typename t_vec_prob::value_type Tprob;
std::size_t iSize = std::min(vecP.size(), vec.size());
if(iSize==0) return T(0);
T tMean = vecP[0]*vec[0];
Tprob tProbTotal = vecP[0];
for(std::size_t i=1; i<iSize; ++i)
{
tMean += vecP[i]*vec[i];
tProbTotal += vecP[i];
}
tMean /= tProbTotal;
return tMean;
}
/**
* standard deviation of mean value, with correction factor
* @see https://en.wikipedia.org/wiki/Bessel%27s_correction
*/
template<class t_vec>
typename t_vec::value_type std_dev(const t_vec& vec, bool bCorr=1)
requires is_basic_vec<t_vec>
{
typedef typename t_vec::value_type T;
if(vec.size()<=1) return T(0);
T tProb = T(vec.size());
if(bCorr) tProb -= T(1);
T tMean = mean(vec);
T t = T(0);
for(const T& tval : vec)
t += (tval-tMean) * (tval-tMean);
t /= tProb;
return std::sqrt(t);
}
/**
* standard deviation with given probability
* @see https://en.wikipedia.org/wiki/Standard_deviation
*/
template<class t_vec_prob, class t_vec>
typename t_vec::value_type std_dev(const t_vec_prob& vecP, const t_vec& vec)
requires is_basic_vec<t_vec> && is_basic_vec<t_vec_prob>
{
typedef typename t_vec::value_type T;
std::size_t iSize = std::min(vecP.size(), vec.size());
if(iSize<=1) return T(0);
T tMean = mean<t_vec_prob, t_vec>(vecP, vec);
T t = T(0);
T tProbTotal = T(0);
for(std::size_t iIdx = 0; iIdx<iSize; ++iIdx)
{
t += (vec[iIdx]-tMean)*(vec[iIdx]-tMean) * vecP[iIdx];
tProbTotal += vecP[iIdx];
}
t /= tProbTotal;
return std::sqrt(t);
}
/**
* calculates minimum and maximum components of a collection of vectors
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_vec, t_vec> minmax(const t_cont<t_vec>& verts)
requires is_vec<t_vec>
{
using namespace tl2_ops;
using t_real = typename t_vec::value_type;
if(!verts.size())
return std::make_tuple(t_vec{}, t_vec{});
// set to limit values
t_vec vecmin = zero<t_vec>(verts.begin()->size());
t_vec vecmax = zero<t_vec>(verts.begin()->size());
for(std::size_t i=0; i<vecmin.size(); ++i)
{
vecmin[i] = std::numeric_limits<t_real>::max();
vecmax[i] = -std::numeric_limits<t_real>::max();
}
// iterate components
for(std::size_t i=0; i<vecmin.size(); ++i)
{
// iterate vectors
for(const t_vec& vec : verts)
{
vecmin[i] = std::min(vecmin[i], vec[i]);
vecmax[i] = std::max(vecmax[i], vec[i]);
}
}
return std::make_tuple(vecmin, vecmax);
}
/**
* calculates the covariance and the correlation matrices
* covariance: C_ij = cov(X_i, X_j) = < (X_i - <X_i>) * (X_j - <X_j>) >
* correlation: K_ij = C_ij / (sigma_i sigma_j)
*
* @see http://www.itl.nist.gov/div898/handbook/pmc/section5/pmc541.htm
* @see (Arfken 2013) pp. 1142-1144
* @see (Arens 2015), p. 795 and p. 1372
*/
template<class t_mat, class t_vec, class T=typename t_vec::value_type>
std::tuple<t_mat, t_mat>
covariance(const std::vector<t_vec>& vecVals, const std::vector<T>* pProb = 0)
requires is_mat<t_mat> && is_vec<t_vec>
{
using t_vecvec = typename std::remove_reference<decltype(vecVals)>::type;
using t_innervec_org = decltype(vecVals[0]);
using t_innervec = typename std::remove_const<
typename std::remove_reference<t_innervec_org>::type>::type;
if(vecVals.size() == 0)
return std::make_tuple(t_mat(), t_mat());
// mean vector <X_i>
t_innervec vecMean;
if(pProb)
vecMean = mean<std::vector<T>, t_vecvec>(*pProb, vecVals);
else
vecMean = mean<t_vec>(vecVals);
t_mat matCov = zero<t_mat>(vecVals[0].size(), vecVals[0].size());
T tSum = T{0};
const std::size_t N = vecVals.size();
for(std::size_t i=0; i<N; ++i)
{
T tprob = T{1};
// X_i - <X_i>
t_innervec vec = vecVals[i] - vecMean;
// matrix elements, AA^t
t_mat matOuter = outer<t_mat, t_vec>(vec, vec);
// probabilities for final averaging, <...>
if(pProb)
{
tprob = (*pProb)[i];
matOuter *= tprob;
}
matCov += matOuter;
tSum += tprob;
}
// average, sometimes defined as C /= (N-1)
matCov /= tSum /*-T(1)*/;
// --------------------------------------------------------------------------------
// correlation matrix
t_innervec vecVar = diag_vec<t_vec, t_mat>(matCov);
t_innervec vecStdDev(vecVar.size());
std::transform(vecVar.begin(), vecVar.end(), vecStdDev.begin(),
[](typename t_innervec::value_type d) -> typename t_innervec::value_type
{ return std::sqrt(d); });
t_mat matStdDev = outer<t_mat, t_vec>(vecStdDev, vecStdDev);
t_mat matCorr = div_perelem<t_mat>(matCov, matStdDev);
// --------------------------------------------------------------------------------
return std::make_tuple(matCov, matCorr);
}
/**
* calculates chi^2 distance of a function model to data points
* chi^2 = sum( (y_i - f(x_i))^2 / sigma_i^2 )
*
* @see (Arfken 2013), p. 1170
*/
template<class T, class t_func, class t_iter_dat=T*>
T chi2(const t_func& func, std::size_t N,
const t_iter_dat x, const t_iter_dat y, const t_iter_dat dy)
{
using t_dat = typename std::remove_pointer<t_iter_dat>::type;
T tchi2 = T{0};
for(std::size_t i=0; i<N; ++i)
{
T td = T(y[i]) - func(T(x[i]));
T tdy = dy ? T(dy[i]) : T(0.1*td); // 10% error if none given
if(std::abs(tdy) < std::numeric_limits<t_dat>::min())
tdy = std::numeric_limits<t_dat>::min();
T tchi = T(td) / T(tdy);
tchi2 += tchi*tchi;
}
return tchi2;
}
/**
* chi^2 for vector types
*
* @see (Merziger 2006), p. 185
*/
template<class t_vec, class t_func>
typename t_vec::value_type chi2(const t_func& func,
const t_vec& x, const t_vec& y, const t_vec& dy)
requires is_vec<t_vec>
{
using T = typename t_vec::value_type;
return chi2<T, t_func, T*>(func, x.size(), x.data(), y.data(),
dy.size() ? dy.data() : nullptr);
}
/**
* chi^2 which doesn't use an x value, but an index instead: y[idx] - func(idx)
* @see (Arfken 2013), p. 1170
*/
template<class T, class t_func, class t_iter_dat=T*>
T chi2_idx(const t_func& func, std::size_t N, const t_iter_dat y, const t_iter_dat dy)
{
using t_dat = typename std::remove_pointer<t_iter_dat>::type;
T tchi2 = T(0);
for(std::size_t i=0; i<N; ++i)
{
T td = T(y[i]) - func(i);
T tdy = dy ? T(dy[i]) : T(0.1*td); // 10% error if none given
if(std::abs(tdy) < std::numeric_limits<t_dat>::min())
tdy = std::numeric_limits<t_dat>::min();
T tchi = T(td) / T(tdy);
tchi2 += tchi*tchi;
}
return tchi2;
}
/**
* direct chi^2 calculation with a model array instead of a model function
* @see (Arfken 2013), p. 1170
*/
template<class T, class t_iter_dat=T*>
T chi2_direct(std::size_t N, const t_iter_dat func_y, const t_iter_dat y, const t_iter_dat dy)
{
using t_dat = typename std::remove_pointer<t_iter_dat>::type;
T tchi2 = T(0);
for(std::size_t i=0; i<N; ++i)
{
T td = T(y[i]) - T(func_y[i]);
T tdy = dy ? T(dy[i]) : T(0.1*td); // 10% error if none given
if(std::abs(tdy) < std::numeric_limits<t_dat>::min())
tdy = std::numeric_limits<t_dat>::min();
T tchi = T(td) / T(tdy);
tchi2 += tchi*tchi;
}
return tchi2;
}
/**
* multi-dimensional chi^2 function
* @see (Arfken 2013), p. 1170
*/
template<class T, class T_dat, class t_func, template<class...> class t_vec=std::vector>
T chi2_nd(const t_func& func,
const t_vec<t_vec<T_dat>>& vecvecX, const t_vec<T_dat>& vecY, const t_vec<T_dat>& vecDY)
{
T tchi2 = T(0);
for(std::size_t i=0; i<vecvecX.size(); ++i)
{
T td = T(vecY[i]) - func(vecvecX[i]);
T tdy = vecDY[i];
if(std::abs(tdy) < std::numeric_limits<T_dat>::min())
tdy = std::numeric_limits<T_dat>::min();
T tchi = T(td) / T(tdy);
tchi2 += tchi*tchi;
}
return tchi2;
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// 3-dim algos
// ----------------------------------------------------------------------------
/**
* 3-dim cross product
*/
template<class t_vec>
t_vec cross(const t_vec& vec1, const t_vec& vec2)
requires is_basic_vec<t_vec>
{
t_vec vec;
// only valid for 3-vectors -> use first three components
if(vec1.size() < 3 || vec2.size() < 3)
return vec;
if constexpr(is_dyn_vec<t_vec>)
vec = t_vec(3);
for(int i=0; i<3; ++i)
vec[i] = vec1[(i+1)%3]*vec2[(i+2)%3] - vec1[(i+2)%3]*vec2[(i+1)%3];
return vec;
}
/**
* cross product matrix (3x3)
* @see https://en.wikipedia.org/wiki/Skew-symmetric_matrix
*/
template<class t_mat, class t_vec>
t_mat skewsymmetric(const t_vec& vec)
requires is_basic_vec<t_vec> && is_mat<t_mat>
{
t_mat mat;
if constexpr(is_dyn_mat<t_mat>)
mat = t_mat(3,3);
// if static matrix is larger than 3x3 (e.g. for homogeneous coordinates), initialise as identity
if(mat.size1() > 3 || mat.size2() > 3)
mat = unit<t_mat>(mat.size1(), mat.size2());
mat(0,0) = 0; mat(0,1) = -vec[2]; mat(0,2) = vec[1];
mat(1,0) = vec[2]; mat(1,1) = 0; mat(1,2) = -vec[0];
mat(2,0) = -vec[1]; mat(2,1) = vec[0]; mat(2,2) = 0;
return mat;
}
/**
* SO(2) rotation matrix
*/
template<class t_mat>
t_mat rotation_2d(const typename t_mat::value_type angle)
requires tl2::is_mat<t_mat>
{
using t_real = typename t_mat::value_type;
const t_real c = std::cos(angle);
const t_real s = std::sin(angle);
return create<t_mat>({{c,s}, {-s,c}});
}
/**
* SO(3) matrix to rotate around an axis (Rodrigues' formula)
* @see (Arens 2015), p. 718 and p. 816
* @see (Merziger 2006), p. 208
* @see https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula
*/
template<class t_mat, class t_vec>
t_mat rotation(const t_vec& axis, const typename t_vec::value_type angle, bool bIsNormalised=1)
requires is_vec<t_vec> && is_mat<t_mat>
{
using t_real = typename t_vec::value_type;
const t_real c = std::cos(angle);
const t_real s = std::sin(angle);
t_real len = 1;
if(!bIsNormalised)
len = norm<t_vec>(axis);
// ----------------------------------------------------
// special cases: rotations around [100], [010], [001]
if(equals(axis, create<t_vec>({ len, 0, 0 })))
return create<t_mat>({{1,0,0}, {0,c,s}, {0,-s,c}});
else if(equals(axis, create<t_vec>({ 0, len, 0 })))
return create<t_mat>({{c,0,-s}, {0,1,0}, {s,0,c}});
else if(equals(axis, create<t_vec>({ 0, 0, len })))
return create<t_mat>({{c,s,0}, {-s,c,0}, {0,0,1}});
// ----------------------------------------------------
// general case
// project along rotation axis
t_mat matProj1 = projector<t_mat, t_vec>(axis, bIsNormalised);
// project along axis 2 in plane perpendicular to rotation axis
t_mat matProj2 = ortho_projector<t_mat, t_vec>(axis, bIsNormalised) * c;
// project along axis 3 in plane perpendicular to rotation axis and axis 2
t_mat matProj3 = skewsymmetric<t_mat, t_vec>(axis/len) * s;
//std::cout << matProj1(3,3) << " " << matProj2(3,3) << " " << matProj3(3,3) << std::endl;
t_mat matProj = matProj1 + matProj2 + matProj3;
// if matrix is larger than 3x3 (e.g. for homogeneous cooridnates), fill up with identity
unit<t_mat>(matProj, 3,3, matProj.size1(), matProj.size2());
return matProj;
}
/**
* matrix to rotate vector vec1 into vec2
*/
template<class t_mat, class t_vec>
t_mat rotation(const t_vec& vec1, const t_vec& vec2,
const t_vec& normal_vec = create<t_vec>({0, 0, 1}))
requires is_vec<t_vec> && is_mat<t_mat>
{
using t_real = typename t_vec::value_type;
constexpr t_real eps = 1e-6;
// get rotation axis from cross product
t_vec axis = cross<t_vec>({ vec1, vec2 });
t_real lenaxis = norm<t_vec>(axis);
// rotation angle
const t_real angle = std::atan2(lenaxis, inner<t_vec>(vec1, vec2));
// collinear vectors?
if(equals<t_real>(angle, 0, eps))
return unit<t_mat>(vec1.size());
// antiparallel vectors?
if(equals<t_real>(std::abs(angle), pi<t_real>, eps))
{
axis = normal_vec;
lenaxis = norm<t_vec>(axis);
}
axis /= lenaxis;
t_mat mat = rotation<t_mat, t_vec>(axis, angle, true);
return mat;
}
/**
* extracts lines from polygon object, takes input from e.g. create_cube()
* @returns [point pairs]
*/
template<class t_vec, template<class...> class t_cont = std::vector>
t_cont<t_vec> create_lines(const t_cont<t_vec>& vertices, const t_cont<t_cont<std::size_t>>& faces)
requires is_vec<t_vec>
{
t_cont<t_vec> lineverts;
auto line_already_seen = [&lineverts](const t_vec& vec1, const t_vec& vec2) -> bool
{
auto iter = lineverts.begin();
while(1)
{
const t_vec& linevec1 = *iter;
std::advance(iter, 1); if(iter == lineverts.end()) break;
const t_vec& linevec2 = *iter;
if(equals<t_vec>(vec1, linevec1) && equals<t_vec>(vec2, linevec2))
return true;
if(equals<t_vec>(vec1, linevec2) && equals<t_vec>(vec2, linevec1))
return true;
std::advance(iter, 1); if(iter == lineverts.end()) break;
}
return false;
};
for(const auto& face : faces)
{
// iterator to last point
auto iter1 = face.begin();
std::advance(iter1, face.size()-1);
for(auto iter2 = face.begin(); iter2 != face.end(); std::advance(iter2, 1))
{
const t_vec& vec1 = vertices[*iter1];
const t_vec& vec2 = vertices[*iter2];
//if(!line_already_seen(vec1, vec2))
{
lineverts.push_back(vec1);
lineverts.push_back(vec2);
}
iter1 = iter2;
}
}
return lineverts;
}
/**
* triangulates polygon object, takes input from e.g. create_cube()
* @returns [triangles, face normals, vertex uvs]
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_vec>, t_cont<t_vec>>
create_triangles(const std::tuple<t_cont<t_vec>, t_cont<t_cont<std::size_t>>,
t_cont<t_vec>, t_cont<t_cont<t_vec>>>& tup)
requires is_vec<t_vec>
{
const t_cont<t_vec>& vertices = std::get<0>(tup);
const t_cont<t_cont<std::size_t>>& faces = std::get<1>(tup);
const t_cont<t_vec>& normals = std::get<2>(tup);
const t_cont<t_cont<t_vec>>& uvs = std::get<3>(tup);
t_cont<t_vec> triangles;
t_cont<t_vec> triag_normals;
t_cont<t_vec> vert_uvs;
auto iterFaces = faces.begin();
auto iterNorms = normals.begin();
auto iterUVs = uvs.begin();
// iterate over faces
while(iterFaces != faces.end())
{
// triangulate faces
auto iterFaceVertIdx = iterFaces->begin();
std::size_t vert1Idx = *iterFaceVertIdx;
std::advance(iterFaceVertIdx, 1);
std::size_t vert2Idx = *iterFaceVertIdx;
const t_vec *puv1 = nullptr;
const t_vec *puv2 = nullptr;
const t_vec *puv3 = nullptr;
typename t_cont<t_vec>::const_iterator iterFaceUVIdx;
if(iterUVs != uvs.end() && iterFaceUVIdx != iterUVs->end())
{
iterFaceUVIdx = iterUVs->begin();
puv1 = &(*iterFaceUVIdx);
std::advance(iterFaceUVIdx, 1);
puv2 = &(*iterFaceUVIdx);
}
// iterate over face vertices
while(1)
{
std::advance(iterFaceVertIdx, 1);
if(iterFaceVertIdx == iterFaces->end())
break;
std::size_t vert3Idx = *iterFaceVertIdx;
if(iterUVs != uvs.end() && iterFaceUVIdx != iterUVs->end())
{
std::advance(iterFaceUVIdx, 1);
puv3 = &(*iterFaceUVIdx);
}
// create triangle
triangles.push_back(vertices[vert1Idx]);
triangles.push_back(vertices[vert2Idx]);
triangles.push_back(vertices[vert3Idx]);
// triangle normal
triag_normals.push_back(*iterNorms);
//triag_normals.push_back(*iterNorms);
//triag_normals.push_back(*iterNorms);
// triangle vertex uvs
if(puv1 && puv2 && puv3)
{
vert_uvs.push_back(*puv1);
vert_uvs.push_back(*puv2);
vert_uvs.push_back(*puv3);
}
// next vertex
vert2Idx = vert3Idx;
puv2 = puv3;
}
std::advance(iterFaces, 1);
if(iterNorms != normals.end()) std::advance(iterNorms, 1);
if(iterUVs != uvs.end()) std::advance(iterUVs, 1);
}
return std::make_tuple(triangles, triag_normals, vert_uvs);
}
/**
* subdivides triangles
* input: [triangle vertices, normals, uvs]
* @returns [triangles, face normals, vertex uvs]
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_vec>, t_cont<t_vec>>
subdivide_triangles(const std::tuple<t_cont<t_vec>, t_cont<t_vec>, t_cont<t_vec>>& tup)
requires is_vec<t_vec>
{
const t_cont<t_vec>& vertices = std::get<0>(tup);
const t_cont<t_vec>& normals = std::get<1>(tup);
const t_cont<t_vec>& uvs = std::get<2>(tup);
t_cont<t_vec> vertices_new;
t_cont<t_vec> normals_new;
t_cont<t_vec> uvs_new;
// iterate over triplets forming triangles
auto itervert = vertices.begin();
auto iternorm = normals.begin();
auto iteruv = uvs.begin();
while(itervert != vertices.end())
{
const t_vec& vec1 = *itervert;
std::advance(itervert, 1); if(itervert == vertices.end()) break;
const t_vec& vec2 = *itervert;
std::advance(itervert, 1); if(itervert == vertices.end()) break;
const t_vec& vec3 = *itervert;
std::advance(itervert, 1);
const t_vec vec12mid = avg<t_vec>({ vec1, vec2 });
const t_vec vec23mid = avg<t_vec>({ vec2, vec3 });
const t_vec vec31mid = avg<t_vec>({ vec3, vec1 });
// triangle 1
vertices_new.push_back(vec1);
vertices_new.push_back(vec12mid);
vertices_new.push_back(vec31mid);
// triangle 2
vertices_new.push_back(vec12mid);
vertices_new.push_back(vec2);
vertices_new.push_back(vec23mid);
// triangle 3
vertices_new.push_back(vec31mid);
vertices_new.push_back(vec23mid);
vertices_new.push_back(vec3);
// triangle 4
vertices_new.push_back(vec12mid);
vertices_new.push_back(vec23mid);
vertices_new.push_back(vec31mid);
// duplicate normals for the four sub-triangles
if(iternorm != normals.end())
{
normals_new.push_back(*iternorm);
normals_new.push_back(*iternorm);
normals_new.push_back(*iternorm);
normals_new.push_back(*iternorm);
std::advance(iternorm, 1);
}
// uv coords
if(iteruv != uvs.end())
{
// uv coords at vertices
const t_vec& uv1 = *iteruv;
std::advance(iteruv, 1); if(iteruv == uvs.end()) break;
const t_vec& uv2 = *iteruv;
std::advance(iteruv, 1); if(iteruv == uvs.end()) break;
const t_vec& uv3 = *iteruv;
std::advance(iteruv, 1);
const t_vec uv12mid = avg<t_vec>({ uv1, uv2 });
const t_vec uv23mid = avg<t_vec>({ uv2, uv3 });
const t_vec uv31mid = avg<t_vec>({ uv3, uv1 });
// uvs of triangle 1
uvs_new.push_back(uv1);
uvs_new.push_back(uv12mid);
uvs_new.push_back(uv31mid);
// uvs of triangle 2
uvs_new.push_back(uv12mid);
uvs_new.push_back(uv2);
uvs_new.push_back(uv23mid);
// uvs of triangle 3
uvs_new.push_back(uv31mid);
uvs_new.push_back(uv23mid);
uvs_new.push_back(uv3);
// uvs of triangle 4
uvs_new.push_back(uv12mid);
uvs_new.push_back(uv23mid);
uvs_new.push_back(uv31mid);
}
}
return std::make_tuple(vertices_new, normals_new, uvs_new);
}
/**
* subdivides triangles (with specified number of iterations)
* input: [triangle vertices, normals, uvs]
* @returns [triangles, face normals, vertex uvs]
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_vec>, t_cont<t_vec>>
subdivide_triangles(const std::tuple<t_cont<t_vec>, t_cont<t_vec>, t_cont<t_vec>>& tup, std::size_t iters)
requires is_vec<t_vec>
{
auto tupDiv = tup;
for(std::size_t i=0; i<iters; ++i)
tupDiv = subdivide_triangles<t_vec, t_cont>(tupDiv);
return tupDiv;
}
/**
* create the faces of a sphere
* input: [triangle vertices, normals, uvs] (like subdivide_triangles)
* @returns [triangles, face normals, vertex uvs]
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_vec>, t_cont<t_vec>>
spherify(const std::tuple<t_cont<t_vec>, t_cont<t_vec>, t_cont<t_vec>>& tup,
typename t_vec::value_type rad = 1)
requires is_vec<t_vec>
{
const t_cont<t_vec>& vertices = std::get<0>(tup);
//const t_cont<t_vec>& normals = std::get<1>(tup);
const t_cont<t_vec>& uvs = std::get<2>(tup);
t_cont<t_vec> vertices_new;
t_cont<t_vec> normals_new;
vertices_new.reserve(vertices.size());
normals_new.reserve(vertices.size());
// vertices
for(t_vec vec : vertices)
{
vec /= norm<t_vec>(vec);
vec *= rad;
vertices_new.emplace_back(std::move(vec));
}
// face normals
auto itervert = vertices.begin();
// iterate over triplets forming triangles
while(itervert != vertices.end())
{
const t_vec& vec1 = *itervert;
std::advance(itervert, 1); if(itervert == vertices.end()) break;
const t_vec& vec2 = *itervert;
std::advance(itervert, 1); if(itervert == vertices.end()) break;
const t_vec& vec3 = *itervert;
std::advance(itervert, 1);
t_vec vecmid = avg<t_vec>({ vec1, vec2, vec3 });
vecmid /= norm<t_vec>(vecmid);
normals_new.emplace_back(std::move(vecmid));
}
return std::make_tuple(vertices_new, normals_new, uvs);
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// 3-dim solids
// ----------------------------------------------------------------------------
/**
* transforms vertices and normals using a matrix
*/
template<class t_mat, class t_vec, template<class...> class t_cont = std::vector>
void transform_obj(t_cont<t_vec>& verts, t_cont<t_vec>& norms, const t_mat& mat, bool is_3dhom=false)
requires is_vec<t_vec> && is_mat<t_mat>
{
using size_t = decltype(mat.size1());
// make sure a 3-vector and a 4-matrix are handled correctly in homogeneous coordinates
if(is_3dhom && mat.size1()==4)
{
t_mat mat3 = mat;
for(size_t i=0; i<3; ++i)
{
mat3(3,i) = 0;
mat3(i,3) = 0;
}
mat3(3,3) = 1;
for(auto& vert : verts)
{
vert = mat3 * vert;
// add translation and normalise
for(size_t i=0; i<3; ++i)
{
vert[i] += mat(i,3);
vert[i] /= mat(3,3);
}
}
for(auto& norm : norms)
norm = mat3 * norm;
}
// standard case: just multiply
else
{
for(auto& vert : verts)
vert = mat * vert;
for(auto& norm : norms)
norm = mat * norm;
}
}
/**
* create a plane
* @returns [vertices, face vertex indices, face normals, face uvs]
*/
template<class t_mat, class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_cont<std::size_t>>, t_cont<t_vec>, t_cont<t_cont<t_vec>>>
create_plane(const t_vec& norm, typename t_vec::value_type lx=1, typename t_vec::value_type ly=1)
requires is_vec<t_vec>
{
t_vec norm_old = create<t_vec>({ 0, 0, -1 });
t_vec rot_vec = create<t_vec>({ 1, 0, 0 });
t_mat rot = rotation<t_mat, t_vec>(norm_old, norm, rot_vec);
t_cont<t_vec> vertices =
{
create<t_vec>({ -lx, -ly, 0. }), // vertex 0
create<t_vec>({ -lx, +ly, 0. }), // vertex 1
create<t_vec>({ +lx, +ly, 0. }), // vertex 2
create<t_vec>({ +lx, -ly, 0. }), // vertex 3
};
// rotate according to given normal
for(t_vec& vec : vertices)
vec = rot * vec;
t_cont<t_cont<std::size_t>> faces = { { 0, 1, 2, 3 } };
t_cont<t_vec> normals = { norm };
t_cont<t_cont<t_vec>> uvs =
{{
create<t_vec>({0, 0}),
create<t_vec>({0, 1}),
create<t_vec>({1, 1}),
create<t_vec>({1, 0}),
}};
return std::make_tuple(vertices, faces, normals, uvs);
}
/**
* create a disk
* @returns [vertices, face vertex indices, face normals, face uvs]
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_cont<std::size_t>>, t_cont<t_vec>, t_cont<t_cont<t_vec>>>
create_disk(typename t_vec::value_type r = 1, std::size_t num_points=32)
requires is_vec<t_vec>
{
using t_real = typename t_vec::value_type;
// vertices
t_cont<t_vec> vertices;
vertices.reserve(num_points);
// inner vertex
for(std::size_t pt=0; pt<num_points; ++pt)
{
const t_real phi = t_real(pt)/t_real(num_points) * t_real(2)*pi<t_real>;
const t_real c = std::cos(phi);
const t_real s = std::sin(phi);
// outer vertices
t_vec vert = create<t_vec>({ r*c, r*s, 0 });
vertices.emplace_back(std::move(vert));
}
// faces, normals & uvs
t_cont<t_cont<std::size_t>> faces;
t_cont<t_vec> normals;
t_cont<t_cont<t_vec>> uvs; // TODO
t_cont<std::size_t> face(num_points);
std::iota(face.begin(), face.end(), 0);
faces.push_back(face);
normals.push_back(create<t_vec>({0,0,1}));
return std::make_tuple(vertices, faces, normals, uvs);
}
/**
* create a cone
* @returns [vertices, face vertex indices, face normals, face uvs]
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_cont<std::size_t>>, t_cont<t_vec>, t_cont<t_cont<t_vec>>>
create_cone(typename t_vec::value_type r = 1, typename t_vec::value_type h = 1,
bool bWithCap = true, std::size_t num_points = 32)
requires is_vec<t_vec>
{
using t_real = typename t_vec::value_type;
// vertices
t_cont<t_vec> vertices;
// inner vertex
vertices.push_back(create<t_vec>({ 0, 0, h }));
for(std::size_t pt=0; pt<num_points; ++pt)
{
const t_real phi = t_real(pt)/t_real(num_points) * t_real(2)*pi<t_real>;
const t_real c = std::cos(phi);
const t_real s = std::sin(phi);
// outer vertices
t_vec vert = create<t_vec>({ r*c, r*s, 0 });
vertices.emplace_back(std::move(vert));
}
// faces, normals & uvs
t_cont<t_cont<std::size_t>> faces;
t_cont<t_vec> normals;
t_cont<t_cont<t_vec>> uvs; // TODO
for(std::size_t face=0; face<num_points; ++face)
{
std::size_t idx0 = face + 1; // outer 1
std::size_t idx1 = (face == num_points-1 ? 1 : face + 2); // outer 2
std::size_t idx2 = 0; // inner
faces.push_back({ idx0, idx1, idx2 });
t_vec n = cross<t_vec>({vertices[idx2]-vertices[idx0], vertices[idx1]-vertices[idx0]});
n /= norm<t_vec>(n);
normals.push_back(n);
}
if(bWithCap)
{
const auto [disk_vertices, disk_faces, disk_normals, disk_uvs] = create_disk<t_vec, t_cont>(r, num_points);
// vertex indices have to be adapted for merging
const std::size_t vert_start_idx = vertices.size();
vertices.insert(vertices.end(), disk_vertices.begin(), disk_vertices.end());
auto disk_faces_bottom = disk_faces;
for(auto& disk_face : disk_faces_bottom)
{
for(auto& disk_face_idx : disk_face)
disk_face_idx += vert_start_idx;
std::reverse(disk_face.begin(), disk_face.end());
}
faces.insert(faces.end(), disk_faces_bottom.begin(), disk_faces_bottom.end());
for(const auto& normal : disk_normals)
normals.push_back(-normal);
uvs.insert(uvs.end(), disk_uvs.begin(), disk_uvs.end());
}
return std::make_tuple(vertices, faces, normals, uvs);
}
/**
* create a cylinder
* cyltype: 0 (no caps), 1 (with caps), 2 (arrow)
* @returns [vertices, face vertex indices, face normals, face uvs]
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_cont<std::size_t>>, t_cont<t_vec>, t_cont<t_cont<t_vec>>>
create_cylinder(typename t_vec::value_type r = 1, typename t_vec::value_type h = 1,
int cyltype = 0, std::size_t num_points = 32,
typename t_vec::value_type arrow_r = 1.5, typename t_vec::value_type arrow_h = 0.5)
requires is_vec<t_vec>
{
using t_real = typename t_vec::value_type;
// vertices
t_cont<t_vec> vertices;
t_cont<t_real> vertices_u;
for(std::size_t pt=0; pt<num_points; ++pt)
{
const t_real u = t_real(pt)/t_real(num_points);
const t_real phi = u * t_real(2)*pi<t_real>;
const t_real c = std::cos(phi);
const t_real s = std::sin(phi);
t_vec top = create<t_vec>({ r*c, r*s, h*t_real(0.5) });
t_vec bottom = create<t_vec>({ r*c, r*s, -h*t_real(0.5) });
vertices.emplace_back(std::move(top));
vertices.emplace_back(std::move(bottom));
vertices_u.push_back(u);
}
// faces, normals & uvs
t_cont<t_cont<std::size_t>> faces;
t_cont<t_vec> normals;
t_cont<t_cont<t_vec>> uvs;
for(std::size_t face=0; face<num_points; ++face)
{
std::size_t idx0 = face*2 + 0; // top 1
std::size_t idx1 = face*2 + 1; // bottom 1
std::size_t idx2 = (face >= num_points-1 ? 1 : face*2 + 3); // bottom 2
std::size_t idx3 = (face >= num_points-1 ? 0 : face*2 + 2); // top 2
t_vec n = cross<t_vec>({vertices[idx1]-vertices[idx0], vertices[idx3]-vertices[idx0]});
n /= norm<t_vec>(n);
faces.push_back({ idx0, idx1, idx2, idx3 });
normals.emplace_back(std::move(n));
t_real u1 = vertices_u[idx0];
t_real u2 = (face >= num_points-1 ? 1 : vertices_u[idx3]);
uvs.push_back({ create<t_vec>({u1,1}), create<t_vec>({u1,0}),
create<t_vec>({u2,0}), create<t_vec>({u2,1}) });
}
if(cyltype > 0)
{
const auto [disk_vertices, disk_faces, disk_normals, disk_uvs] = create_disk<t_vec, t_cont>(r, num_points);
// bottom lid
// vertex indices have to be adapted for merging
std::size_t vert_start_idx = vertices.size();
const t_vec top = create<t_vec>({ 0, 0, h*t_real(0.5) });
for(const auto& disk_vert : disk_vertices)
vertices.push_back(disk_vert - top);
auto disk_faces_bottom = disk_faces;
for(auto& disk_face : disk_faces_bottom)
{
for(auto& disk_face_idx : disk_face)
disk_face_idx += vert_start_idx;
std::reverse(disk_face.begin(), disk_face.end());
}
faces.insert(faces.end(), disk_faces_bottom.begin(), disk_faces_bottom.end());
for(const auto& normal : disk_normals)
normals.push_back(-normal);
uvs.insert(uvs.end(), disk_uvs.begin(), disk_uvs.end());
vert_start_idx = vertices.size();
if(cyltype == 1) // top lid
{
for(const auto& disk_vert : disk_vertices)
vertices.push_back(disk_vert + top);
auto disk_faces_top = disk_faces;
for(auto& disk_face : disk_faces_top)
for(auto& disk_face_idx : disk_face)
disk_face_idx += vert_start_idx;
faces.insert(faces.end(), disk_faces_top.begin(), disk_faces_top.end());
for(const auto& normal : disk_normals)
normals.push_back(normal);
uvs.insert(uvs.end(), disk_uvs.begin(), disk_uvs.end());
}
else if(cyltype == 2) // arrow top
{
// no need to cap the arrow if the radii are equal
bool bConeCap = !equals<t_real>(r, arrow_r);
const auto [cone_vertices, cone_faces, cone_normals, cone_uvs] =
create_cone<t_vec, t_cont>(arrow_r, arrow_h, bConeCap, num_points);
for(const auto& cone_vert : cone_vertices)
vertices.push_back(cone_vert + top);
auto cone_faces_top = cone_faces;
for(auto& cone_face : cone_faces_top)
for(auto& cone_face_idx : cone_face)
cone_face_idx += vert_start_idx;
faces.insert(faces.end(), cone_faces_top.begin(), cone_faces_top.end());
for(const auto& normal : cone_normals)
normals.push_back(normal);
uvs.insert(uvs.end(), cone_uvs.begin(), cone_uvs.end());
}
}
return std::make_tuple(vertices, faces, normals, uvs);
}
/**
* create the faces of a cuboid
* @returns [vertices, face vertex indices, face normals, face uvs]
* @see https://en.wikipedia.org/wiki/Platonic_solid
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_cont<std::size_t>>, t_cont<t_vec>, t_cont<t_cont<t_vec>>>
create_cuboid(typename t_vec::value_type lx=1, typename t_vec::value_type ly=1, typename t_vec::value_type lz=1)
requires is_vec<t_vec>
{
t_cont<t_vec> vertices =
{
create<t_vec>({ +lx, -ly, -lz }), // vertex 0
create<t_vec>({ -lx, -ly, -lz }), // vertex 1
create<t_vec>({ -lx, +ly, -lz }), // vertex 2
create<t_vec>({ +lx, +ly, -lz }), // vertex 3
create<t_vec>({ -lx, -ly, +lz }), // vertex 4
create<t_vec>({ +lx, -ly, +lz }), // vertex 5
create<t_vec>({ +lx, +ly, +lz }), // vertex 6
create<t_vec>({ -lx, +ly, +lz }), // vertex 7
};
t_cont<t_cont<std::size_t>> faces =
{
{ 0, 1, 2, 3 }, // -z face
{ 4, 5, 6, 7 }, // +z face
{ 1, 0, 5, 4 }, // -y face
{ 7, 6, 3, 2 }, // +y face
{ 1, 4, 7, 2 }, // -x face
{ 5, 0, 3, 6 }, // +x face
};
t_cont<t_vec> normals =
{
create<t_vec>({ 0, 0, -1 }), // -z face
create<t_vec>({ 0, 0, +1 }), // +z face
create<t_vec>({ 0, -1, 0 }), // -y face
create<t_vec>({ 0, +1, 0 }), // +y face
create<t_vec>({ -1, 0, 0 }), // -x face
create<t_vec>({ +1, 0, 0 }), // +x face
};
t_cont<t_cont<t_vec>> uvs =
{
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({1,1}), create<t_vec>({0,1}) }, // -z face
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({1,1}), create<t_vec>({0,1}) }, // +z face
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({1,1}), create<t_vec>({0,1}) }, // -y face
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({1,1}), create<t_vec>({0,1}) }, // +y face
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({1,1}), create<t_vec>({0,1}) }, // -x face
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({1,1}), create<t_vec>({0,1}) }, // +x face
};
return std::make_tuple(vertices, faces, normals, uvs);
}
/**
* create the faces of a cube
* @returns [vertices, face vertex indices, face normals, face uvs]
* @see https://en.wikipedia.org/wiki/Platonic_solid
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_cont<std::size_t>>, t_cont<t_vec>, t_cont<t_cont<t_vec>>>
create_cube(typename t_vec::value_type l = 1)
requires is_vec<t_vec>
{
return create_cuboid<t_vec, t_cont>(l, l, l);
}
/**
* create the faces of a icosahedron
* @returns [vertices, face vertex indices, face normals, face uvs]
* @see https://en.wikipedia.org/wiki/Platonic_solid
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_cont<std::size_t>>, t_cont<t_vec>, t_cont<t_cont<t_vec>>>
create_icosahedron(typename t_vec::value_type l = 1)
requires is_vec<t_vec>
{
using T = typename t_vec::value_type;
const T g = golden<T>;
t_cont<t_vec> vertices =
{
create<t_vec>({ 0, -l, -g*l }), create<t_vec>({ 0, -l, +g*l }),
create<t_vec>({ 0, +l, -g*l }), create<t_vec>({ 0, +l, +g*l }),
create<t_vec>({ -g*l, 0, -l }), create<t_vec>({ -g*l, 0, +l }),
create<t_vec>({ +g*l, 0, -l }), create<t_vec>({ +g*l, 0, +l }),
create<t_vec>({ -l, -g*l, 0 }), create<t_vec>({ -l, +g*l, 0 }),
create<t_vec>({ +l, -g*l, 0 }), create<t_vec>({ +l, +g*l, 0 }),
};
t_cont<t_cont<std::size_t>> faces =
{
{ 4, 2, 0 }, { 0, 6, 10 }, { 10, 7, 1 }, { 1, 3, 5 }, { 5, 9, 4 },
{ 7, 10, 6 }, { 6, 0, 2 }, { 2, 4, 9 }, { 9, 5, 3 }, { 3, 1, 7 },
{ 0, 10, 8 }, { 10, 1, 8 }, { 1, 5, 8 }, { 5, 4, 8 }, { 4, 0, 8 },
{ 3, 7, 11 }, { 7, 6, 11 }, { 6, 2, 11 }, { 2, 9, 11 }, { 9, 3, 11 },
};
t_cont<t_vec> normals;
normals.reserve(faces.size());
for(const auto& face : faces)
{
auto iter = face.begin();
const t_vec& vec1 = *(vertices.begin() + *iter); std::advance(iter,1);
const t_vec& vec2 = *(vertices.begin() + *iter); std::advance(iter,1);
const t_vec& vec3 = *(vertices.begin() + *iter);
const t_vec vec12 = vec2 - vec1;
const t_vec vec13 = vec3 - vec1;
t_vec n = cross<t_vec>({vec12, vec13});
n /= norm<t_vec>(n);
normals.emplace_back(std::move(n));
}
// TODO
t_cont<t_cont<t_vec>> uvs =
{
};
return std::make_tuple(vertices, faces, normals, uvs);
}
/**
* create the faces of a dodecahedron
* @returns [vertices, face vertex indices, face normals, face uvs]
* @see https://en.wikipedia.org/wiki/Platonic_solid
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_cont<std::size_t>>, t_cont<t_vec>, t_cont<t_cont<t_vec>>>
create_dodecahedron(typename t_vec::value_type l = 1)
requires is_vec<t_vec>
{
using T = typename t_vec::value_type;
const T g = golden<T>;
t_cont<t_vec> vertices =
{
create<t_vec>({ l, l, l }), create<t_vec>({ l, l, -l }),
create<t_vec>({ l, -l, l }), create<t_vec>({ l, -l, -l }),
create<t_vec>({ -l, l, l }), create<t_vec>({ -l, l, -l }),
create<t_vec>({ -l, -l, l }), create<t_vec>({ -l, -l, -l }),
create<t_vec>({ 0, T{l}/g, g }), create<t_vec>({ 0, T{l}/g, -g }),
create<t_vec>({ 0, -T{l}/g, g }), create<t_vec>({ 0, -T{l}/g, -g }),
create<t_vec>({ g, 0, T{l}/g }), create<t_vec>({ g, 0, -T{l}/g }),
create<t_vec>({ -g, 0, T{l}/g }), create<t_vec>({ -g, 0, -T{l}/g }),
create<t_vec>({ T{l}/g, g, 0 }), create<t_vec>({ T{l}/g, -g, 0 }),
create<t_vec>({ -T{l}/g, g, 0 }), create<t_vec>({ -T{l}/g, -g, 0 }),
};
t_cont<t_cont<std::size_t>> faces =
{
{ 0, 16, 18, 4, 8 }, { 0, 8, 10, 2, 12 }, { 0, 12, 13, 1, 16 },
{ 1, 9, 5, 18, 16 }, { 1, 13, 3, 11, 9 }, { 2, 17, 3, 13, 12 },
{ 3, 17, 19, 7, 11 }, { 2, 10, 6, 19, 17 }, { 4, 14, 6, 10, 8 },
{ 4, 18, 5, 15, 14 }, { 5, 9, 11, 7, 15 }, { 6, 14, 15, 7, 19 },
};
t_cont<t_vec> normals;
normals.reserve(faces.size());
for(const auto& face : faces)
{
auto iter = face.begin();
const t_vec& vec1 = *(vertices.begin() + *iter); std::advance(iter,1);
const t_vec& vec2 = *(vertices.begin() + *iter); std::advance(iter,1);
const t_vec& vec3 = *(vertices.begin() + *iter);
const t_vec vec12 = vec2 - vec1;
const t_vec vec13 = vec3 - vec1;
t_vec n = cross<t_vec>({vec12, vec13});
n /= norm<t_vec>(n);
normals.emplace_back(std::move(n));
}
// TODO
t_cont<t_cont<t_vec>> uvs =
{
};
return std::make_tuple(vertices, faces, normals, uvs);
}
/**
* create the faces of a octahedron
* @returns [vertices, face vertex indices, face normals, face uvs]
* @see https://en.wikipedia.org/wiki/Platonic_solid
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_cont<std::size_t>>, t_cont<t_vec>, t_cont<t_cont<t_vec>>>
create_octahedron(typename t_vec::value_type l = 1)
requires is_vec<t_vec>
{
using T = typename t_vec::value_type;
t_cont<t_vec> vertices =
{
create<t_vec>({ +l, 0, 0 }), // vertex 0
create<t_vec>({ 0, +l, 0 }), // vertex 1
create<t_vec>({ 0, 0, +l }), // vertex 2
create<t_vec>({ -l, 0, 0 }), // vertex 3
create<t_vec>({ 0, -l, 0 }), // vertex 4
create<t_vec>({ 0, 0, -l }), // vertex 5
};
t_cont<t_cont<std::size_t>> faces =
{
{ 2, 0, 1 }, { 0, 5, 1 }, { 5, 3, 1 }, { 3, 2, 1 }, // upper half
{ 0, 2, 4 }, { 5, 0, 4 }, { 3, 5, 4 }, { 2, 3, 4 }, // lower half
};
const T len = std::sqrt(3);
t_cont<t_vec> normals =
{
create<t_vec>({ +1/len, +1/len, +1/len }),
create<t_vec>({ +1/len, +1/len, -1/len }),
create<t_vec>({ -1/len, +1/len, -1/len }),
create<t_vec>({ -1/len, +1/len, +1/len }),
create<t_vec>({ +1/len, -1/len, +1/len }),
create<t_vec>({ +1/len, -1/len, -1/len }),
create<t_vec>({ -1/len, -1/len, -1/len }),
create<t_vec>({ -1/len, -1/len, +1/len }),
};
t_cont<t_cont<t_vec>> uvs =
{
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
};
return std::make_tuple(vertices, faces, normals, uvs);
}
/**
* create the faces of a tetrahedron
* @returns [vertices, face vertex indices, face normals, face uvs]
* @see https://en.wikipedia.org/wiki/Platonic_solid
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_vec>, t_cont<t_cont<std::size_t>>, t_cont<t_vec>, t_cont<t_cont<t_vec>>>
create_tetrahedron(typename t_vec::value_type l = 1)
requires is_vec<t_vec>
{
using T = typename t_vec::value_type;
t_cont<t_vec> vertices =
{
create<t_vec>({ -l, -l, +l }), // vertex 0
create<t_vec>({ +l, +l, +l }), // vertex 1
create<t_vec>({ -l, +l, -l }), // vertex 2
create<t_vec>({ +l, -l, -l }), // vertex 3
};
t_cont<t_cont<std::size_t>> faces =
{
{ 1, 2, 0 }, { 2, 1, 3 }, // connected to upper edge
{ 0, 3, 1 }, { 3, 0, 2 }, // connected to lower edge
};
const T len = std::sqrt(3);
t_cont<t_vec> normals =
{
create<t_vec>({ -1/len, +1/len, +1/len }),
create<t_vec>({ +1/len, +1/len, -1/len }),
create<t_vec>({ +1/len, -1/len, +1/len }),
create<t_vec>({ -1/len, -1/len, -1/len }),
};
t_cont<t_cont<t_vec>> uvs =
{
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
{ create<t_vec>({0,0}), create<t_vec>({1,0}), create<t_vec>({0.5,1}) },
};
return std::make_tuple(vertices, faces, normals, uvs);
}
/**
* calculates the bounding sphere of a collection of vertices
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_vec, typename t_vec::value_type> bounding_sphere(
const t_cont<t_vec>& verts)
requires is_vec<t_vec>
{
using t_real = typename t_vec::value_type;
t_real rad{};
t_vec center = mean<t_vec, t_cont>(verts);
for(const t_vec& vec : verts)
{
t_vec vecCur = vec-center;
t_real dot = inner<t_vec>(vecCur, vecCur);
rad = std::max(rad, dot);
}
rad = std::sqrt(rad);
return std::make_tuple(center, rad);
}
/**
* calculates the bounding box of a collection of vertices
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_vec, t_vec> bounding_box(
const t_cont<t_vec>& verts,
const t_vec* oldmin = nullptr, const t_vec* oldmax = nullptr)
requires is_vec<t_vec>
{
if(verts.size() == 0)
return std::make_tuple(t_vec{}, t_vec{});
using t_real = typename t_vec::value_type;
const std::size_t dim = verts[0].size();
if(dim == 0)
return std::make_tuple(t_vec{}, t_vec{});
t_vec min, max;
if(oldmin && oldmax)
{
min = *oldmin;
max = *oldmax;
}
else
{
min = create<t_vec>(dim);
for(std::size_t i=0; i<dim; ++i)
min[i] = std::numeric_limits<t_real>::max();
max = -min;
}
for(const t_vec& vert : verts)
{
for(std::size_t i=0; i<dim; ++i)
{
min[i] = std::min(min[i], vert[i]);
max[i] = std::max(max[i], vert[i]);
}
}
return std::make_tuple(min, max);
}
/**
* calculates the bounding box of a collection of vertices
* @see https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_collision_detection
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_vec, t_vec> bounding_box(
const t_cont<t_cont<t_vec>>& allverts, std::size_t dim = 3)
requires is_vec<t_vec>
{
using t_real = typename t_vec::value_type;
t_vec min, max;
min = create<t_vec>(dim);
for(std::size_t i=0; i<dim; ++i)
min[i] = std::numeric_limits<t_real>::max();
max = -min;
for(const t_cont<t_vec>& verts : allverts)
std::tie(min, max) = bounding_box<t_vec, t_cont>(verts, &min, &max);
return std::make_tuple(min, max);
}
/**
* calculates the bounding box of a sphere
*/
template<class t_vec, class t_real=typename t_vec::value_type> requires is_vec<t_vec>
std::tuple<t_vec, t_vec> sphere_bounding_box(const t_vec& pos, t_real rad)
{
const std::size_t dim = pos.size();
if(dim == 0)
return std::make_tuple(t_vec{}, t_vec{});
t_vec min = create<t_vec>(dim);
t_vec max = create<t_vec>(dim);
for(std::size_t i=0; i<dim; ++i)
{
min[i] = pos[i] - rad;
max[i] = pos[i] + rad;
}
return std::make_tuple(min, max);
}
/**
* calculates the bounding box of a collection of spheres
*/
template<class t_vec, template<class...> class t_cont = std::vector,
class t_real = typename t_vec::value_type>
std::tuple<t_vec, t_vec> sphere_bounding_box(
const t_cont<std::tuple<t_vec, t_real>>& spheres, std::size_t dim = 3)
requires is_vec<t_vec>
{
t_vec min = create<t_vec>(dim);
for(std::size_t i=0; i<dim; ++i)
min[i] = std::numeric_limits<t_real>::max();
t_vec max = -min;
for(const auto& sphere : spheres)
{
auto [spheremin, spheremax] = sphere_bounding_box<t_vec, t_real>(
std::get<0>(sphere), std::get<1>(sphere));
for(std::size_t i=0; i<dim; ++i)
{
min[i] = std::min(min[i], spheremin[i]);
max[i] = std::max(max[i], spheremax[i]);
}
}
return std::make_tuple(min, max);
}
/**
* checks if a point is inside a bounding box
* @see https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_collision_detection
*/
template<class t_vec> requires is_vec<t_vec>
bool in_bounding_box(
const t_vec& pt, const std::tuple<t_vec, t_vec>& bb)
{
const std::size_t dim = pt.size();
const t_vec& min = std::get<0>(bb);
const t_vec& max = std::get<1>(bb);
for(std::size_t i=0; i<dim; ++i)
{
if(pt[i] < min[i] || pt[i] > max[i])
return false;
}
return true;
}
/**
* checks for bounding box intersection
* @see https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_collision_detection
*/
template<class t_vec> requires is_vec<t_vec>
bool collide_bounding_boxes(
const std::tuple<t_vec, t_vec>& bb1,
const std::tuple<t_vec, t_vec>& bb2)
{
// invalid bounding boxes?
if(std::get<0>(bb1).size()==0 || std::get<1>(bb1).size()==0 ||
std::get<0>(bb2).size()==0 || std::get<1>(bb2).size()==0)
return false;
const std::size_t dim = std::min(std::get<0>(bb1).size(), std::get<0>(bb2).size());
for(std::size_t i=0; i<dim; ++i)
{
if(std::get<0>(bb1)[i] > std::get<1>(bb2)[i])
return false;
if(std::get<0>(bb2)[i] > std::get<1>(bb1)[i])
return false;
}
return true;
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// 3-dim algos in homogeneous coordinates
// ----------------------------------------------------------------------------
/**
* project a homogeneous vector to screen coordinates
* @returns [vecPersp, vecScreen]
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluProject.xml
*/
template<class t_mat, class t_vec>
std::tuple<t_vec, t_vec> hom_to_screen_coords(const t_vec& vec4,
const t_mat& matModelView, const t_mat& matProj, const t_mat& matViewport,
bool bFlipY = false, bool bFlipX = false)
requires is_vec<t_vec> && is_mat<t_mat>
{
// perspective trafo and divide
t_vec vecPersp = matProj * matModelView * vec4;
vecPersp /= vecPersp[3];
// viewport trafo
t_vec vec = matViewport * vecPersp;
// flip y coordinate
if(bFlipY) vec[1] = matViewport(1,1)*2 - vec[1];
// flip x coordinate
if(bFlipX) vec[0] = matViewport(0,0)*2 - vec[0];
return std::make_tuple(vecPersp, vec);
}
/**
* calculate world coordinates from screen coordinates
* (vary zPlane to get the points of the z-line at constant (x,y))
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluUnProject.xml
*/
template<class t_mat, class t_vec>
t_vec hom_from_screen_coords(
typename t_vec::value_type xScreen, typename t_vec::value_type yScreen, typename t_vec::value_type zPlane,
const t_mat& matModelView_inv, const t_mat& matProj_inv, const t_mat& matViewport_inv,
const t_mat* pmatViewport = nullptr, bool bFlipY = false, bool bFlipX = false)
requires is_vec<t_vec> && is_mat<t_mat>
{
t_vec vecScreen = create<t_vec>({xScreen, yScreen, zPlane, 1.});
// flip y coordinate
if(pmatViewport && bFlipY) vecScreen[1] = (*pmatViewport)(1,1)*2 - vecScreen[1];
// flip x coordinate
if(pmatViewport && bFlipX) vecScreen[0] = (*pmatViewport)(0,0)*2 - vecScreen[0];
t_vec vecWorld = matModelView_inv * matProj_inv * matViewport_inv * vecScreen;
vecWorld /= vecWorld[3];
return vecWorld;
}
/**
* calculate line from screen coordinates
* @returns [pos, dir]
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluUnProject.xml
*/
template<class t_mat, class t_vec>
std::tuple<t_vec, t_vec> hom_line_from_screen_coords(
typename t_vec::value_type xScreen, typename t_vec::value_type yScreen,
typename t_vec::value_type z1, typename t_vec::value_type z2,
const t_mat& matModelView_inv, const t_mat& matProj_inv, const t_mat& matViewport_inv,
const t_mat* pmatViewport = nullptr, bool bFlipY = false, bool bFlipX = false)
requires is_vec<t_vec> && is_mat<t_mat>
{
const t_vec lineOrg = hom_from_screen_coords<t_mat, t_vec>(xScreen, yScreen, z1, matModelView_inv, matProj_inv,
matViewport_inv, pmatViewport, bFlipY, bFlipX);
const t_vec linePos2 = hom_from_screen_coords<t_mat, t_vec>(xScreen, yScreen, z2, matModelView_inv, matProj_inv,
matViewport_inv, pmatViewport, bFlipY, bFlipX);
t_vec lineDir = linePos2 - lineOrg;
lineDir /= norm<t_vec>(lineDir);
return std::make_tuple(lineOrg, lineDir);
}
/**
* perspective matrix (homogeneous 4x4)
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluPerspective.xml
*/
template<class t_mat, typename t_scalar=typename t_mat::value_type>
t_mat hom_perspective(
t_scalar n = 0.01, t_scalar f = 100.,
t_scalar fov = 0.5*pi<typename t_mat::value_type>, t_scalar ratio = 3./4.,
bool bLHS = true, bool bZ01 = false)
requires is_mat<t_mat>
{
const t_scalar c = 1./std::tan(0.5 * fov);
const t_scalar n0 = bZ01 ? t_scalar{0} : n;
const t_scalar sc = bZ01 ? t_scalar{1} : t_scalar{2};
const t_scalar zs = bLHS ? t_scalar{-1} : t_scalar{1};
const t_scalar range_nf = std::abs(f-n);
// ( x*c*r ) ( -x*c*r/z )
// ( y*c ) ( -y*c/z )
// P * x = ( z*(n0+f)/(n-f) + w*sc*n*f/(n-f) ) => ( -(n0+f)/(n-f) - w/z*sc*n*f/(n-f) )
// ( -z ) ( 1 )
return create<t_mat>({
c*ratio, 0., 0., 0.,
0, c, 0., 0.,
0., 0., zs*(n0+f)/range_nf, -sc*n*f/range_nf,
0., 0., zs, 0.
});
}
/**
* orthographic projection matrix (homogeneous 4x4)
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glOrtho.xml
* @see https://en.wikipedia.org/wiki/Orthographic_projection
*/
template<class t_mat, typename t_scalar=typename t_mat::value_type>
t_mat hom_ortho_sym(
t_scalar n = 0.01, t_scalar f = 100.,
t_scalar range_lr = 2., t_scalar range_bt = 2.,
bool bLHS = true, bool bMap05 = false)
requires is_mat<t_mat>
{
// map ranges into [-0.5, 0.5] or [-1, 1] else
const t_scalar sc = bMap05 ? t_scalar{1} : t_scalar{2};
const t_scalar zs = bLHS ? t_scalar{-1} : t_scalar{1};
const t_scalar range_nf = std::abs(f) + std::abs(n);
// centring
const t_scalar tr_z = sc*t_scalar{0.5} * (n+f) / range_nf;
// ( sc_x*x )
// ( sc_y*y )
// P * x = ( sc_z*z - tr_z )
// ( 1 )
return create<t_mat>({
sc/range_lr, 0., 0., 0.,
0., sc/range_bt, 0., 0.,
0., 0., zs*sc/range_nf, zs*tr_z,
0., 0., 0., 1.
});
}
/**
* orthographic projection matrix (homogeneous 4x4)
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glOrtho.xml
* @see https://en.wikipedia.org/wiki/Orthographic_projection
*/
template<class t_mat, typename t_scalar=typename t_mat::value_type>
t_mat hom_ortho(
t_scalar n = 0.01, t_scalar f = 100.,
t_scalar l = -1., t_scalar r = 1.,
t_scalar b = -1., t_scalar t = 1.,
bool bLHS = true, bool bMap05 = false)
requires is_mat<t_mat>
{
// map ranges into [-0.5, 0.5] or [-1, 1] else
const t_scalar sc = bMap05 ? t_scalar{1} : t_scalar{2};
const t_scalar zs = bLHS ? t_scalar{-1} : t_scalar{1};
const t_scalar range_lr = r - l;
const t_scalar range_bt = t - b;
const t_scalar range_nf = f - n;
// centring
const t_scalar tr_x = sc*t_scalar{0.5} * (l+r) / range_lr;
const t_scalar tr_y = sc*t_scalar{0.5} * (b+t) / range_bt;
const t_scalar tr_z = sc*t_scalar{0.5} * (n+f) / range_nf;
// ( sc_x*x - tr_x )
// ( sc_y*y - tr_y )
// P * x = ( sc_z*z - tr_z )
// ( 1 )
return create<t_mat>({
sc/range_lr, 0., 0., -tr_x,
0., sc/range_bt, 0., -tr_y,
0., 0., zs*sc/range_nf, zs*tr_z,
0., 0., 0., 1.
});
}
/**
* viewport matrix (homogeneous 4x4)
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glViewport.xml
*/
template<class t_mat, typename t_scalar=typename t_mat::value_type>
t_mat hom_viewport(t_scalar w, t_scalar h, t_scalar n = 0, t_scalar f = 1)
requires is_mat<t_mat>
{
t_scalar sc{0.5};
return create<t_mat>({
sc*w, 0., 0., sc*w,
0, sc*h, 0., sc*h,
0., 0., sc*(f-n), sc*(f+n),
0., 0., 0., 1.
});
}
/**
* translation matrix in homogeneous coordinates
*/
template<class t_mat, class t_real = typename t_mat::value_type>
t_mat hom_translation(t_real x, t_real y, t_real z)
requires is_mat<t_mat>
{
return create<t_mat>({
1., 0., 0., x,
0., 1., 0., y,
0., 0., 1., z,
0., 0., 0., 1.
});
}
/**
* scaling matrix in homogeneous coordinates
*/
template<class t_mat, class t_real = typename t_mat::value_type>
t_mat hom_scaling(t_real x, t_real y, t_real z)
requires is_mat<t_mat>
{
return create<t_mat>({
x, 0., 0., 0.,
0., y, 0., 0.,
0., 0., z, 0.,
0., 0., 0., 1.
});
}
/**
* "look at" matrix in homogeneous coordinates
* @see (Sellers 2014), pp. 78-79
* @see https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/gluLookAt.xml
*/
template<class t_mat, class t_vec>
t_mat hom_lookat(const t_vec& pos, const t_vec& target, const t_vec& _up)
requires is_vec<t_vec> && is_mat<t_mat>
{
using t_real = typename t_mat::value_type;
// create orthonormal system
t_vec dir = -(target - pos);
dir = dir / norm<t_vec>(dir);
t_vec side = cross<t_vec>({_up, dir});
side = side / norm<t_vec>(side);
t_vec up = cross<t_vec>({dir, side});
//up = up / norm<t_vec>(up);
// inverted/transposed rotation matrix
t_mat rot_inv = unit<t_mat>(4);
set_row<t_mat, t_vec>(rot_inv, side, 0);
set_row<t_mat, t_vec>(rot_inv, up, 1);
set_row<t_mat, t_vec>(rot_inv, dir, 2);
// inverted translation matrix
t_mat trans_inv = hom_translation<t_mat, t_real>(
-pos[0], -pos[1], -pos[2]);
return rot_inv * trans_inv;
}
/**
* shear matrix
* @see https://en.wikipedia.org/wiki/Shear_matrix
*/
template<class t_mat, class t_real = typename t_mat::value_type>
t_mat shear(std::size_t ROWS, std::size_t COLS, std::size_t i, std::size_t j, t_real s)
requires is_mat<t_mat>
{
t_mat mat = unit<t_mat>(ROWS, COLS);
mat(i,j) = s;
return mat;
}
/**
* rotation matrix in homogeneous coordinates
*/
template<class t_mat, class t_vec>
t_mat hom_rotation(const t_vec& vec1, const t_vec& vec2,
const t_vec& vec_normal = create<t_vec>({0, 0, 1}))
requires is_vec<t_vec> && is_mat<t_mat>
{
t_mat rot = rotation<t_mat, t_vec>(vec1, vec2, vec_normal);
return create<t_mat>({
rot(0,0), rot(0,1), rot(0,2), 0.,
rot(1,0), rot(1,1), rot(1,2), 0.,
rot(2,0), rot(2,1), rot(2,2), 0.,
0., 0., 0., 1.
});
}
/**
* rotation matrix in homogeneous coordinates
*/
template<class t_mat, class t_vec>
t_mat hom_rotation(const t_vec& axis, typename t_vec::value_type angle, bool bIsNormalised=1)
requires is_vec<t_vec> && is_mat<t_mat>
{
t_mat rot = rotation<t_mat, t_vec>(axis, angle, bIsNormalised);
return create<t_mat>({
rot(0,0), rot(0,1), rot(0,2), 0.,
rot(1,0), rot(1,1), rot(1,2), 0.,
rot(2,0), rot(2,1), rot(2,2), 0.,
0., 0., 0., 1.
});
}
// ----------------------------------------------------------------------------
/**
* arrow matrix
*/
template<class t_vec, class t_mat, class t_real = typename t_vec::value_type>
t_mat get_arrow_matrix(
const t_vec& vecTo,
t_real postscale = 1, const t_vec& vecPostTrans = create<t_vec>({0,0,0.5}),
const t_vec& vecFrom = create<t_vec>({0,0,1}),
t_real prescale = 1, const t_vec& vecPreTrans = create<t_vec>({0,0,0}),
const t_vec& vecNormal = create<t_vec>({0,0,1}))
requires is_vec<t_vec> && is_mat<t_mat>
{
t_mat mat = unit<t_mat>(4);
mat *= hom_translation<t_mat>(vecPreTrans[0], vecPreTrans[1], vecPreTrans[2]);
mat *= hom_scaling<t_mat>(prescale, prescale, prescale);
mat *= hom_rotation<t_mat, t_vec>(vecFrom, vecTo, vecNormal);
mat *= hom_scaling<t_mat>(postscale, postscale, postscale);
mat *= hom_translation<t_mat>(vecPostTrans[0], vecPostTrans[1], vecPostTrans[2]);
return mat;
}
// ----------------------------------------------------------------------------
// complex algos
// ----------------------------------------------------------------------------
/**
* split a complex vector into two vectors with the real and imag parts
*/
template<class t_vec_cplx, class t_vec_real>
std::tuple<t_vec_real, t_vec_real> split_cplx(const t_vec_cplx& vec)
requires is_complex<typename t_vec_cplx::value_type> && is_vec<t_vec_cplx> && is_vec<t_vec_real>
{
using t_real = typename t_vec_real::value_type;
t_vec_real vecRe = zero<t_vec_real>(vec.size());
t_vec_real vecIm = zero<t_vec_real>(vec.size());
auto iter = vec.begin();
auto iterRe = vecRe.begin();
auto iterIm = vecIm.begin();
for(; iter!=vec.end(); )
{
*iterRe = t_real{iter->real()};
*iterIm = t_real{iter->imag()};
std::advance(iter, 1);
std::advance(iterRe, 1);
std::advance(iterIm, 1);
}
return std::make_tuple(vecRe, vecIm);
}
/**
* split a complex matrix into two matrices with the real and imag parts
*/
template<class t_mat_cplx, class t_mat_real>
std::tuple<t_mat_real, t_mat_real> split_cplx(const t_mat_cplx& mat)
requires is_complex<typename t_mat_cplx::value_type> && is_mat<t_mat_cplx> && is_mat<t_mat_real>
{
t_mat_real matRe = zero<t_mat_real>(mat.size1(), mat.size2());
t_mat_real matIm = zero<t_mat_real>(mat.size1(), mat.size2());
for(std::size_t i=0; i<mat.size1(); ++i)
{
for(std::size_t j=0; j<mat.size2(); ++j)
{
matRe(i,j) = mat(i,j).real();
matIm(i,j) = mat(i,j).imag();
}
}
return std::make_tuple(matRe, matIm);
}
/**
* SU(2) generators, pauli matrices sig_i = 2*S_i
* @see (Arfken 2013), p. 110
*/
template<class t_mat>
const t_mat& su2_matrix(std::size_t which)
requires is_mat<t_mat> && is_complex<typename t_mat::value_type>
{
using t_cplx = typename t_mat::value_type;
constexpr t_cplx c0(0,0);
constexpr t_cplx c1(1,0);
constexpr t_cplx cI(0,1);
static const t_mat mat[] =
{
create<t_mat>({{c0, c1}, { c1, c0}}), // x
create<t_mat>({{c0, cI}, {-cI, c0}}), // y
create<t_mat>({{c1, c0}, { c0, -c1}}), // z
};
return mat[which];
}
/**
* get a vector of pauli matrices
* @see (Arfken 2013), p. 110
*/
template<class t_vec>
t_vec su2_matrices(bool bIncludeUnit = false)
requires is_basic_vec<t_vec> && is_mat<typename t_vec::value_type>
&& is_complex<typename t_vec::value_type::value_type>
{
using t_mat = typename t_vec::value_type;
t_vec vec;
vec.reserve(4);
if(bIncludeUnit)
vec.emplace_back(unit<t_mat>(2));
for(std::size_t i=0; i<3; ++i)
vec.emplace_back(su2_matrix<t_mat>(i));
return vec;
}
/**
* project the vector of SU(2) matrices onto a vector
* proj = <sigma|vec>
*/
template<class t_vec, class t_mat>
t_mat proj_su2(const t_vec& vec, bool bIsNormalised=1)
requires is_vec<t_vec> && is_mat<t_mat>
{
typename t_vec::value_type len = 1;
if(!bIsNormalised)
len = norm<t_vec>(vec);
const auto sigma = su2_matrices<std::vector<t_mat>>(false);
return inner<std::vector<t_mat>, t_vec>(sigma, vec);
}
/**
* SU(2) ladders
* @see https://en.wikipedia.org/wiki/Ladder_operator
*/
template<class t_mat>
const t_mat& su2_ladder(std::size_t which)
requires is_mat<t_mat> && is_complex<typename t_mat::value_type>
{
using t_cplx = typename t_mat::value_type;
constexpr t_cplx cI(0,1);
constexpr t_cplx c05(0.5, 0);
static const t_mat mat[] =
{
c05*su2_matrix<t_mat>(0) + c05*cI*su2_matrix<t_mat>(1), // up
c05*su2_matrix<t_mat>(0) - c05*cI*su2_matrix<t_mat>(1), // down
};
return mat[which];
}
/**
* SU(3) generators, Gell-Mann matrices
* @see https://de.wikipedia.org/wiki/Gell-Mann-Matrizen
*/
template<class t_mat>
const t_mat& su3_matrix(std::size_t which)
requires is_mat<t_mat> && is_complex<typename t_mat::value_type>
{
using t_cplx = typename t_mat::value_type;
using t_real = typename t_cplx::value_type;
constexpr t_cplx c0(0,0);
constexpr t_cplx c1(1,0);
constexpr t_cplx c2(2,0);
constexpr t_cplx cI(0,1);
constexpr t_real s3 = std::sqrt(3.);
static const t_mat mat[] =
{
create<t_mat>({{c0,c1,c0}, {c1,c0,c0}, {c0,c0,c0}}), // 1
create<t_mat>({{c0,cI,c0}, {-cI,c0,c0}, {c0,c0,c0}}), // 2
create<t_mat>({{c1,c0,c0}, {c0,-c1,c0}, {c0,c0,c0}}), // 3
create<t_mat>({{c0,c0,c1}, {c0,c0,c0}, {c1,c0,c0}}), // 4
create<t_mat>({{c0,c0,cI}, {c0,c0,c0}, {-cI,c0,c0}}), // 5
create<t_mat>({{c0,c0,c0}, {c0,c0,c1}, {c0,c1,c0}}), // 6
create<t_mat>({{c0,c0,c0}, {c0,c0,cI}, {c0,-cI,c0}}), // 7
create<t_mat>({{c1/s3,c0,c0}, {c0,c1/s3,c0}, {c0,c0,-c2/s3*c1}}), // 8
};
return mat[which];
}
/**
* real crystallographic A matrix
* @see https://en.wikipedia.org/wiki/Fractional_coordinates
*/
template<class t_mat, class t_real = typename t_mat::value_type>
t_mat A_matrix(t_real a, t_real b, t_real c, t_real _aa, t_real _bb, t_real _cc)
requires is_mat<t_mat>
{
const t_real ca = std::cos(_aa);
const t_real cb = std::cos(_bb);
const t_real cc = std::cos(_cc);
const t_real sc = std::sin(_cc);
const t_real sb = std::sin(_bb);
return create<t_mat>({
a, b*cc, c*cb,
t_real{0}, b*sc, c*(ca - cc*cb)/sc,
t_real{0}, t_real{0}, c*std::sqrt(sb*sb - std::pow((ca - cc*cb)/sc, t_real{2}))
});
}
/**
* reciprocal crystallographic B matrix, B = 2pi * A^(-T)
* @see https://en.wikipedia.org/wiki/Fractional_coordinates
*/
template<class t_mat, class t_real = typename t_mat::value_type>
t_mat B_matrix(t_real a, t_real b, t_real c, t_real _aa, t_real _bb, t_real _cc)
requires is_mat<t_mat>
{
const t_real sc = std::sin(_cc);
const t_real ca = std::cos(_aa);
const t_real cb = std::cos(_bb);
const t_real cc = std::cos(_cc);
const t_real rr = std::sqrt(1. + 2.*ca*cb*cc - (ca*ca + cb*cb + cc*cc));
return t_real{2}*pi<t_real> * create<t_mat>({
t_real{1}/a, t_real{0}, t_real{0},
-t_real{1}/a * cc/sc, t_real{1}/b * t_real{1}/sc, t_real{0},
(cc*ca - cb)/(a*sc*rr), (cb*cc-ca)/(b*sc*rr), sc/(c*rr)
});
}
/**
* UB orientation matrix
* @see https://dx.doi.org/10.1107/S0021889805004875
*/
template<class t_mat, class t_vec>
t_mat UB_matrix(const t_mat& B,
const t_vec& vec1_rlu, const t_vec& vec2_rlu, const t_vec& vec3_rlu)
requires is_mat<t_mat> && is_vec<t_vec>
{
t_vec vec1_lab = B * vec1_rlu;
t_vec vec2_lab = B * vec2_rlu;
t_vec vec3_lab = B * vec3_rlu;
vec1_lab /= norm<t_vec>(vec1_lab);
vec2_lab /= norm<t_vec>(vec2_lab);
vec3_lab /= norm<t_vec>(vec3_lab);
t_mat U_lab = unit<t_mat>(B.size1(), B.size2());
set_row<t_mat, t_vec>(U_lab, vec1_lab, 0);
set_row<t_mat, t_vec>(U_lab, vec2_lab, 1);
set_row<t_mat, t_vec>(U_lab, vec3_lab, 2);
return U_lab * B;
}
/**
* get correct distance in unit cell, considering wrapping-around
*/
template<class t_mat, class t_vec, class t_real = typename t_mat::value_type>
t_real get_dist_uc(const t_mat& matA, const t_vec& vec1, const t_vec& vec2)
requires is_mat<t_mat> && is_vec<t_vec>
{
t_vec vec1A = matA * vec1;
// all supercell position to try
std::vector<t_vec> vecSCs
{{
create<t_vec>({0, 0, 0}),
create<t_vec>({+1, 0, 0}), create<t_vec>({ 0, +1, 0}), create<t_vec>({ 0, 0, +1}),
create<t_vec>({ 0, +1, +1}), create<t_vec>({ 0, +1, -1}),
create<t_vec>({+1, 0, +1}), create<t_vec>({+1, 0, -1}),
create<t_vec>({+1, +1, 0}), create<t_vec>({+1, -1, 0}),
create<t_vec>({+1, +1, +1}), create<t_vec>({+1, +1, -1}),
create<t_vec>({+1, -1, +1}), create<t_vec>({+1, -1, -1}),
}};
t_real thedist = std::numeric_limits<t_real>::max();
for(const t_vec& _vecSC : vecSCs)
{
for(const t_vec& vecSC : { _vecSC, -_vecSC, t_real{2}*_vecSC, t_real{-2}*_vecSC })
{
t_vec vec2A = matA * (vec2 + vecSC);
t_real dist = norm(vec1A - vec2A);
thedist = std::min(thedist, dist);
}
}
return thedist;
}
/**
* general structure factor calculation
* e.g. type T as vector (complex number) for magnetic (nuclear) structure factor
* Ms_or_bs:
- nuclear scattering lengths for nuclear neutron scattering or
- atomic form factors for x-ray scattering
- magnetisation (* magnetic form factor) for magnetic neutron scattering
* Rs: atomic positions
* Q: scattering vector G for nuclear scattering or G+k for magnetic scattering with propagation vector k
* fs: optional magnetic form factors
*
* @see (Shirane 2002), p. 25, equ. 2.26 for nuclear structure factor
* @see (Shirane 2002), p. 40, equ. 2.81 for magnetic structure factor
* @see https://doi.org/10.1016/B978-044451050-1/50002-1
*/
template<class t_vec, class T = t_vec, template<class...> class t_cont = std::vector,
class t_cplx = std::complex<double>>
T structure_factor(const t_cont<T>& Ms_or_bs, const t_cont<t_vec>& Rs, const t_vec& Q, const t_vec* fs=nullptr)
requires is_basic_vec<t_vec>
{
using t_real = typename t_cplx::value_type;
constexpr t_cplx cI{0,1};
constexpr t_real twopi = pi<t_real> * t_real{2};
constexpr t_real expsign = -1;
T F{};
if(Rs.size() == 0)
return F;
if constexpr(is_vec<T>)
F = zero<T>(Rs.begin()->size()); // always 3 dims...
else if constexpr(is_complex<T>)
F = T(0);
auto iterM_or_b = Ms_or_bs.begin();
auto iterR = Rs.begin();
typename t_vec::const_iterator iterf;
if(fs) iterf = fs->begin();
while(iterM_or_b != Ms_or_bs.end() && iterR != Rs.end())
{
// if form factors are given, use them, otherwise set to 1
t_real f = t_real(1);
if(fs)
{
auto fval = *iterf;
if constexpr(is_complex<decltype(fval)>)
f = fval.real();
else
f = fval;
}
// structure factor
F += (*iterM_or_b) * f * std::exp(expsign * cI * twopi * inner<t_vec>(Q, *iterR));
// next M or b if available (otherwise keep current)
auto iterM_or_b_next = std::next(iterM_or_b, 1);
if(iterM_or_b_next != Ms_or_bs.end())
iterM_or_b = iterM_or_b_next;
if(fs)
{
// next form factor if available (otherwise keep current)
auto iterf_next = std::next(iterf, 1);
if(iterf_next != fs->end())
iterf = iterf_next;
}
// next atomic position
std::advance(iterR, 1);
}
return F;
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
/**
* wrap atom positions back to unit cell
*/
template<class t_vec, class t_real = typename t_vec::value_type>
t_vec keep_atom_in_uc(const t_vec& _atom)
requires is_vec<t_vec>
{
auto newatom = _atom;
for(std::size_t i=0; i<newatom.size(); ++i)
{
newatom[i] = std::fmod(newatom[i], t_real{1});
if(newatom[i] < t_real{-0.5})
newatom[i] += std::abs(std::floor(newatom[i]));
if(newatom[i] >= t_real{0.5})
newatom[i] -= std::abs(std::ceil(newatom[i]));
}
return newatom;
}
/**
* wrap collection of atom positions back to unit cell
*/
template<class t_vec, class t_real = typename t_vec::value_type,
template<class...> class t_cont = std::vector>
t_cont<t_vec> keep_atoms_in_uc(const t_cont<t_vec>& _atoms)
requires is_vec<t_vec>
{
t_cont<t_vec> newatoms;
newatoms.reserve(_atoms.size());
for(const auto& _atom : _atoms)
newatoms.emplace_back(keep_atom_in_uc<t_vec, t_real>(_atom));
return newatoms;
}
/**
* create positions using the given symmetry operations
*/
template<class t_vec, class t_mat, class t_real = typename t_vec::value_type,
template<class...> class t_cont = std::vector>
t_cont<t_vec> apply_ops_hom(const t_vec& _atom, const t_cont<t_mat>& ops,
t_real eps=std::numeric_limits<t_real>::epsilon(), bool bKeepInUnitCell=true)
requires is_vec<t_vec> && is_mat<t_mat>
{
// in homogeneous coordinates
t_vec atom = _atom;
if(atom.size() == 3)
atom = create<t_vec>({atom[0], atom[1], atom[2], 1});
t_cont<t_vec> newatoms;
newatoms.reserve(ops.size());
for(const auto& op : ops)
{
auto newatom = op*atom;
newatom.resize(3);
if(bKeepInUnitCell)
newatom = keep_atom_in_uc<t_vec>(newatom);
// position already occupied?
if(std::find_if(newatoms.begin(), newatoms.end(), [&newatom, eps](const t_vec& vec)->bool
{
return tl2::equals<t_vec>(vec, newatom, eps);
}) == newatoms.end())
{
newatoms.emplace_back(std::move(newatom));
}
}
return newatoms;
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// polarisation
// ----------------------------------------------------------------------------
/**
* conjugate complex vector
*/
template<class t_vec>
t_vec conj(const t_vec& vec)
requires is_basic_vec<t_vec>
{
const std::size_t N = vec.size();
t_vec vecConj = zero<t_vec>(N);
for(std::size_t iComp=0; iComp<N; ++iComp)
{
if constexpr(is_complex<typename t_vec::value_type>)
vecConj[iComp] = std::conj(vec[iComp]);
else // simply copy non-complex vector
vecConj[iComp] = vec[iComp];
}
return vecConj;
}
/**
* hermitian conjugate complex matrix
*/
template<class t_mat>
t_mat herm(const t_mat& mat)
requires is_basic_mat<t_mat>
{
t_mat mat2;
if constexpr(is_dyn_mat<t_mat>)
mat2 = t_mat(mat.size2(), mat.size1());
for(std::size_t i=0; i<mat.size1(); ++i)
{
for(std::size_t j=0; j<mat.size2(); ++j)
{
if constexpr(is_complex<typename t_mat::value_type>)
mat2(j,i) = std::conj(mat(i,j));
else // simply transpose non-complex matrix
mat2(j,i) = mat(i,j);
}
}
return mat2;
}
/**
* polarisation density matrix
* (based on a proof from a lecture by P. J. Brown, 2006)
*
* eigenvector expansion of a state: |psi> = a_i |xi_i>
* mean value of operator with mixed states:
* <A> = p_i * <a_i|A|a_i>
* <A> = tr( A * p_i * |a_i><a_i| )
* <A> = tr( A * rho )
* polarisation density matrix: rho = 0.5 * (1 + <P|sigma>)
*
* @see https://doi.org/10.1016/B978-044451050-1/50006-9
* @see (Desktop Bronstein 2008), Ch. 21 (Zusatzkapitel.pdf), pp. 11-12 and p. 24
*/
template<class t_vec, class t_mat>
t_mat pol_density_mat(const t_vec& P, typename t_vec::value_type c=0.5)
requires is_vec<t_vec> && is_mat<t_mat>
{
return (unit<t_mat>(2,2) + proj_su2<t_vec, t_mat>(P, true)) * c;
}
/**
* Blume-Maleev equation
* @returns scattering intensity and final polarisation vector
*
* @see https://doi.org/10.1016/B978-044451050-1/50006-9 - p. 225-226
*/
template<class t_vec, typename t_cplx = typename t_vec::value_type>
std::tuple<t_cplx, t_vec> blume_maleev(const t_vec& P_i, const t_vec& Mperp, const t_cplx& N)
requires is_vec<t_vec>
{
const t_vec MperpConj = conj(Mperp);
const t_cplx NConj = std::conj(N);
constexpr t_cplx imag(0, 1);
// ------------------------------------------------------------------------
// intensity
// nuclear
t_cplx I = NConj*N;
// nuclear-magnetic
I += NConj*inner<t_vec>(P_i, Mperp);
I += N*inner<t_vec>(Mperp, P_i);
// magnetic, non-chiral
I += inner<t_vec>(Mperp, Mperp);
// magnetic, chiral
I += imag * inner<t_vec>(P_i, cross<t_vec>({ MperpConj, Mperp }));
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// polarisation vector
// nuclear
t_vec P_f = P_i * N*NConj;
// nuclear-magnetic
P_f += NConj * Mperp;
P_f += N * MperpConj;
P_f += imag * N * cross<t_vec>({ P_i, MperpConj });
P_f += -imag * NConj * cross<t_vec>({ P_i, Mperp });
// magnetic, non-chiral
P_f += Mperp * inner<t_vec>(Mperp, P_i);
P_f += MperpConj * inner<t_vec>(P_i, Mperp);
P_f += -P_i * inner<t_vec>(Mperp, Mperp);
// magnetic, chiral
P_f += imag * cross<t_vec>({ Mperp, MperpConj });
// ------------------------------------------------------------------------
return std::make_tuple(I, P_f/I);
}
/**
* Blume-Maleev equation
* calculate equation indirectly with density matrix
* (based on a proof from a lecture by P. J. Brown, 2006)
*
* V = N*1 + <Mperp|sigma>
* I = tr( <V|V> rho )
* P_f = tr( <V|sigma|V> rho ) / I
*
* @returns scattering intensity and final polarisation vector
*
* @see https://doi.org/10.1016/B978-044451050-1/50006-9 - p. 225-226
*/
template<class t_mat, class t_vec, typename t_cplx = typename t_vec::value_type>
std::tuple<t_cplx, t_vec> blume_maleev_indir(const t_vec& P_i, const t_vec& Mperp, const t_cplx& N)
requires is_mat<t_mat> && is_vec<t_vec>
{
// spin-1/2
constexpr t_cplx c = 0.5;
// vector of pauli matrices
const auto sigma = su2_matrices<std::vector<t_mat>>(false);
// density matrix
const auto density = pol_density_mat<t_vec, t_mat>(P_i, c);
// potential
const auto V_mag = proj_su2<t_vec, t_mat>(Mperp, true);
const auto V_nuc = N * unit<t_mat>(2);
const auto V = V_nuc + V_mag;
const auto VConj = herm(V);
// scattering intensity
t_cplx I = trace(VConj*V * density);
// ------------------------------------------------------------------------
// scattered polarisation vector
const auto m0 = (VConj * sigma[0]) * V * density;
const auto m1 = (VConj * sigma[1]) * V * density;
const auto m2 = (VConj * sigma[2]) * V * density;
t_vec P_f = create<t_vec>({ trace(m0), trace(m1), trace(m2) });
// ------------------------------------------------------------------------
return std::make_tuple(I, P_f/I);
}
// ----------------------------------------------------------------------------
}
// ----------------------------------------------------------------------------
// lapack wrappers
// ----------------------------------------------------------------------------
#ifdef __TLIBS2_USE_LAPACK__
namespace tl2_la {
/**
* LU decomposition of a matrix, mat = P * L * U, returning raw results
* @returns [ok, LU, perm]
* @see http://www.math.utah.edu/software/lapack/lapack-d/dgetrf.html
*/
template<class t_mat, template<class...> class t_vec = std::vector>
std::tuple<bool, t_vec<typename t_mat::value_type>, t_vec<lapack_int>> _lu_raw(const t_mat& mat)
requires tl2::is_mat<t_mat>
{
using namespace tl2_ops;
using t_scalar = typename t_mat::value_type;
using t_real = tl2::underlying_value_type<t_scalar>;
const std::size_t rows = mat.size1();
const std::size_t cols = mat.size2();
const std::size_t minor = std::min(rows, cols);
t_vec<t_scalar> outmat(rows*cols);
t_vec<lapack_int> outpivots(minor);
for(std::size_t i=0; i<rows; ++i)
for(std::size_t j=0; j<cols; ++j)
outmat[i*cols + j] = mat(i, j);
int err = -1;
if constexpr(tl2::is_complex<t_scalar>)
{
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_cgetrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outpivots.data());
else if constexpr(std::is_same_v<t_real, double>)
err = LAPACKE_zgetrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outpivots.data());
}
else
{
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_sgetrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outpivots.data());
else if constexpr(std::is_same_v<t_real, double>)
err = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outpivots.data());
}
return std::make_tuple(err == 0, outmat, outpivots);
}
/**
* LU decomposition of a matrix, mat = P * L * U
* @returns [ok, P, L, U]
* @see http://www.math.utah.edu/software/lapack/lapack-d/dgetrf.html
*/
template<class t_mat, template<class...> class t_vec = std::vector>
std::tuple<bool, t_mat, t_mat, t_mat> lu(const t_mat& mat)
requires tl2::is_mat<t_mat>
{
using namespace tl2_ops;
const std::size_t rows = mat.size1();
const std::size_t cols = mat.size2();
auto [ ok, lumat, pivots ] = _lu_raw<t_mat, t_vec>(mat);
t_mat P = tl2::unit<t_mat>(rows, cols);
t_mat L = tl2::unit<t_mat>(rows, cols);
t_mat U = tl2::unit<t_mat>(rows, cols);
// L and U
for(std::size_t i=0; i<rows; ++i)
{
for(std::size_t j=0; j<cols; ++j)
{
if(j>=i)
U(i, j) = lumat[i*cols + j];
else
L(i, j) = lumat[i*cols + j];
}
}
// permutation matrix P
for(std::size_t i=0; i<pivots.size(); ++i)
P = tl2::prod<t_mat>(P, tl2::perm<t_mat>(rows, cols, i, pivots[i]-1));
return std::make_tuple(ok, P, L, U);
}
/**
* inverted matrix
*/
template<class t_mat>
std::tuple<t_mat, bool> inv(const t_mat& mat)
requires tl2::is_mat<t_mat>
{
// fail if matrix is not square
if constexpr(tl2::is_dyn_mat<t_mat>)
assert((mat.size1() == mat.size2()));
else
static_assert(t_mat::size1() == t_mat::size2());
using t_scalar = typename t_mat::value_type;
using t_real = tl2::underlying_value_type<t_scalar>;
const std::size_t rows = mat.size1();
const std::size_t cols = mat.size2();
t_mat I = tl2::unit<t_mat>(rows, cols);
// lu factorisation
auto [ ok, lumat, pivots ] = _lu_raw<t_mat, std::vector>(mat);
if(!ok)
return std::make_tuple(I, false);
// inversion
int err = -1;
if constexpr(tl2::is_complex<t_scalar>)
{
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_cgetri(LAPACK_ROW_MAJOR, rows, lumat.data(), rows, pivots.data());
else if constexpr(std::is_same_v<t_real, double>)
err = LAPACKE_zgetri(LAPACK_ROW_MAJOR, rows, lumat.data(), rows, pivots.data());
}
else
{
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_sgetri(LAPACK_ROW_MAJOR, rows, lumat.data(), rows, pivots.data());
else if constexpr(std::is_same_v<t_real, double>)
err = LAPACKE_dgetri(LAPACK_ROW_MAJOR, rows, lumat.data(), rows, pivots.data());
}
for(std::size_t i=0; i<rows; ++i)
for(std::size_t j=0; j<cols; ++j)
I(i, j) = lumat[i*cols + j];
return std::make_tuple(I, err == 0);
}
/**
* QR decomposition of a matrix, mat = QR
* @returns [ok, Q, R]
* @see http://www.math.utah.edu/software/lapack/lapack-d/dgeqrf.html
*/
template<class t_mat, class t_vec = std::vector<typename t_mat::value_type>>
std::tuple<bool, t_mat, t_mat> qr(const t_mat& mat)
requires tl2::is_mat<t_mat>
{
using namespace tl2_ops;
using t_scalar = typename t_mat::value_type;
using t_real = tl2::underlying_value_type<t_scalar>;
const std::size_t rows = mat.size1();
const std::size_t cols = mat.size2();
const std::size_t minor = std::min(rows, cols);
const t_mat I = tl2::unit<t_mat>(minor);
t_mat Q = I, R = mat;
t_vec outmat(rows*cols), outvec(minor);
for(std::size_t i=0; i<rows; ++i)
for(std::size_t j=0; j<cols; ++j)
outmat[i*cols + j] = mat(i, j);
int err = -1;
if constexpr(tl2::is_complex<t_scalar>)
{
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_cgeqrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outvec.data());
else if constexpr(std::is_same_v<t_real, double>)
err = LAPACKE_zgeqrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outvec.data());
}
else
{
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_sgeqrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outvec.data());
else if constexpr(std::is_same_v<t_real, double>)
err = LAPACKE_dgeqrf(LAPACK_ROW_MAJOR, rows, cols, outmat.data(), cols, outvec.data());
}
for(std::size_t i=0; i<rows; ++i)
for(std::size_t j=0; j<cols; ++j)
R(i, j) = (j>=i ? outmat[i*cols + j] : t_real{0});
t_vec v = tl2::zero<t_vec>(minor);
for(std::size_t k=1; k<=minor; ++k)
{
for(std::size_t i=1; i<=k-1; ++i)
v[i-1] = t_real{0};
v[k-1] = t_real{1};
for(std::size_t i=k+1; i<=minor; ++i)
v[i-1] = outmat[(i-1)*cols + (k-1)];
Q = Q * (I - outvec[k-1]*tl2::outer<t_mat, t_vec>(v, v));
}
return std::make_tuple(err == 0, Q, R);
}
/**
* eigenvectors and -values of a complex matrix
* @returns [ok, evals, evecs]
*/
template<class t_mat_cplx, class t_vec_cplx, class t_cplx = typename t_mat_cplx::value_type,
class t_real = typename t_cplx::value_type>
std::tuple<bool, std::vector<t_cplx>, std::vector<t_vec_cplx>>
eigenvec(const t_mat_cplx& mat, bool only_evals=false, bool is_hermitian=false, bool normalise=false,
t_real mineval=-1, t_real maxeval=-2, t_real eps=-1)
requires tl2::is_mat<t_mat_cplx> && tl2::is_vec<t_vec_cplx> && tl2::is_complex<t_cplx>
{
bool only_selected_evals = (mineval <= maxeval);
bool use_selective_func = only_selected_evals;
//use_selective_func = true;
std::vector<t_cplx> evals;
std::vector<t_vec_cplx> evecs;
if(mat.size1() != mat.size2() || mat.size1() == 0)
return std::make_tuple(0, evals, evecs);
const std::size_t N = mat.size1();
evals.resize(N);
if(!only_evals)
evecs.resize(N, tl2::zero<t_vec_cplx>(N));
std::vector<t_cplx> inmat(N*N, t_cplx{0,0}),
outevecs(only_evals ? 0 : N*N, t_cplx{0,0});
for(std::size_t i=0; i<N; ++i)
{
for(std::size_t j=0; j<N; ++j)
{
if(is_hermitian)
inmat[i*N + j] = (j>=i ? mat(j,i) : t_real{0});
else
inmat[i*N + j] = mat(j,i);
}
}
int err = -1;
if(is_hermitian)
{
// evals of hermitian matrix are purely real
std::vector<t_real> outevals_real(N, t_real{0});
// all eigenvalues
if(!use_selective_func)
{
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_cheev(LAPACK_COL_MAJOR, only_evals ? 'N' : 'V', 'L', N, inmat.data(), N, outevals_real.data());
else if constexpr(std::is_same_v<t_real, double>)
err = LAPACKE_zheev(LAPACK_COL_MAJOR, only_evals ? 'N' : 'V', 'L', N, inmat.data(), N, outevals_real.data());
else
throw std::domain_error("Invalid real type.");
}
// only selected eigenvalues
else
{
int minidx = 1, maxidx = N;
int iNumFound = 0;
std::unique_ptr<int, std::default_delete<int[]>>
uptrIdxArr(new int[2*N]);
// use maximum precision if none given
if(eps < t_real{0})
{
if constexpr(std::is_same_v<t_real, float>)
eps = LAPACKE_slamch('S');
else if constexpr(std::is_same_v<t_real, double>)
eps = LAPACKE_dlamch('S');
else
throw std::domain_error("Invalid real type.");
}
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_cheevr(LAPACK_COL_MAJOR, (only_evals ? 'N' : 'V'), (only_selected_evals?'V':'A'), 'L',
N, inmat.data(), N, mineval, maxeval, minidx, maxidx,
eps, &iNumFound, outevals_real.data(), outevecs.data(), N, uptrIdxArr.get());
else if constexpr(std::is_same_v<t_real, double>)
err = LAPACKE_zheevr(LAPACK_COL_MAJOR, (only_evals ? 'N' : 'V'), (only_selected_evals?'V':'A'), 'L',
N, inmat.data(), N, mineval, maxeval, minidx, maxidx,
eps, &iNumFound, outevals_real.data(), outevecs.data(), N, uptrIdxArr.get());
else
throw std::domain_error("Invalid real type.");
// resize to actual number of eigenvalues and -vectors
if(std::size_t(iNumFound) != N)
{
evals.resize(iNumFound, t_real{0});
evecs.resize(iNumFound, tl2::zero<t_vec_cplx>(N));
}
}
// copy to complex output vector
for(std::size_t i=0; i<evals.size(); ++i)
evals[i] = outevals_real[i];
}
else
{
if constexpr(std::is_same_v<t_real, float>)
{
err = LAPACKE_cgeev(LAPACK_COL_MAJOR, 'N', only_evals ? 'N' : 'V', N,
inmat.data(), N, evals.data(), nullptr, N,
only_evals ? nullptr : outevecs.data(), N);
}
else if constexpr(std::is_same_v<t_real, double>)
{
err = LAPACKE_zgeev(LAPACK_COL_MAJOR, 'N', only_evals ? 'N' : 'V', N,
inmat.data(), N, evals.data(), nullptr, N,
only_evals ? nullptr : outevecs.data(), N);
}
else
{
throw std::domain_error("Invalid real type.");
}
}
if(!only_evals)
{
for(std::size_t i=0; i<evecs.size(); ++i)
{
// hermitian algo overwrites original matrix!
for(std::size_t j=0; j<N; ++j)
evecs[i][j] = (is_hermitian && !use_selective_func) ? inmat[i*N + j] : outevecs[i*N + j];
if(normalise && (err == 0))
{
t_cplx n = tl2::norm(evecs[i]);
if(!tl2::equals<t_cplx>(n, t_cplx{0,0}))
evecs[i] /= n;
}
}
}
return std::make_tuple(err == 0, evals, evecs);
}
/**
* eigenvectors and -values of a real matrix
* @returns [ok, evals_re, evals_im, evecs_re, evecs_im]
*/
template<class t_mat, class t_vec, class t_real = typename t_mat::value_type>
std::tuple<bool, std::vector<t_real>, std::vector<t_real>, std::vector<t_vec>, std::vector<t_vec>>
eigenvec(const t_mat& mat, bool only_evals=false, bool is_symmetric=false, bool normalise=false,
t_real mineval=-1, t_real maxeval=-2, t_real eps=-1)
requires (tl2::is_mat<t_mat> && tl2::is_vec<t_vec> && !tl2::is_complex<t_real>)
{
bool only_selected_evals = (mineval <= maxeval);
bool use_selective_func = only_selected_evals;
//use_selective_func = true;
std::vector<t_real> evals_re, evals_im;
std::vector<t_vec> evecs_re, evecs_im;
if(mat.size1() != mat.size2() || mat.size1() == 0)
return std::make_tuple(false, evals_re, evals_im, evecs_re, evecs_im);
const std::size_t N = mat.size1();
evals_re.resize(N, t_real{0});
evals_im.resize(N, t_real{0});
if(!only_evals)
{
evecs_re.resize(N, tl2::zero<t_vec>(N));
evecs_im.resize(N, tl2::zero<t_vec>(N));
}
std::vector<t_real> inmat(N*N, t_real{0}),
outevecs(only_evals ? 0 : N*N, t_real{0});
for(std::size_t i=0; i<N; ++i)
{
for(std::size_t j=0; j<N; ++j)
{
if(is_symmetric)
inmat[i*N + j] = (j>=i ? mat(j,i) : t_real{0});
else
inmat[i*N + j] = mat(j,i);
}
}
int err = -1;
if(is_symmetric)
{
// all eigenvalues
if(!use_selective_func)
{
// evals of symmetric matrix are purely real
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_ssyev(LAPACK_COL_MAJOR, (only_evals ? 'N' : 'V'), 'L', N, inmat.data(), N, evals_re.data());
else if constexpr(std::is_same_v<t_real, double>)
err = LAPACKE_dsyev(LAPACK_COL_MAJOR, (only_evals ? 'N' : 'V'), 'L', N, inmat.data(), N, evals_re.data());
else
throw std::domain_error("Invalid real type.");
}
// only selected eigenvalues
else
{
int minidx = 1, maxidx = N;
int iNumFound = 0;
std::unique_ptr<int, std::default_delete<int[]>>
uptrIdxArr(new int[2*N]);
// use maximum precision if none given
if(eps < t_real{0})
{
if constexpr(std::is_same_v<t_real, float>)
eps = LAPACKE_slamch('S');
else if constexpr(std::is_same_v<t_real, double>)
eps = LAPACKE_dlamch('S');
else
throw std::domain_error("Invalid real type.");
}
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_ssyevr(LAPACK_COL_MAJOR, (only_evals?'N':'V'), (only_selected_evals?'V':'A'), 'L',
N, inmat.data(), N, mineval, maxeval, minidx, maxidx,
eps, &iNumFound, evals_re.data(), outevecs.data(), N, uptrIdxArr.get());
else if constexpr(std::is_same_v<t_real, double>)
err = LAPACKE_dsyevr(LAPACK_COL_MAJOR, (only_evals?'N':'V'), (only_selected_evals?'V':'A'), 'L',
N, inmat.data(), N, mineval, maxeval, minidx, maxidx,
eps, &iNumFound, evals_re.data(), outevecs.data(), N, uptrIdxArr.get());
else
throw std::domain_error("Invalid real type.");
// resize to actual number of eigenvalues and -vectors
if(std::size_t(iNumFound) != N)
{
evals_re.resize(iNumFound, t_real{0});
evals_im.resize(iNumFound, t_real{0});
evecs_re.resize(iNumFound, tl2::zero<t_vec>(N));
evecs_im.resize(iNumFound, tl2::zero<t_vec>(N));
}
}
}
else
{
if constexpr(std::is_same_v<t_real, float>)
{
err = LAPACKE_sgeev(LAPACK_COL_MAJOR, 'N', (only_evals ? 'N' : 'V'), N,
inmat.data(), N, evals_re.data(), evals_im.data(), nullptr, N,
only_evals ? nullptr : outevecs.data(), N);
}
else if constexpr(std::is_same_v<t_real, double>)
{
err = LAPACKE_dgeev(LAPACK_COL_MAJOR, 'N', (only_evals ? 'N' : 'V'), N,
inmat.data(), N, evals_re.data(), evals_im.data(), nullptr, N,
only_evals ? nullptr : outevecs.data(), N);
}
else
{
throw std::domain_error("Invalid real type.");
}
}
// evecs
if(!only_evals)
{
if((is_symmetric && !use_selective_func))
{
for(std::size_t i=0; i<evals_re.size(); ++i)
{
// symmetric algo overwrites original matrix!
for(std::size_t j=0; j<N; ++j)
evecs_re[i][j] = inmat[i*N + j];
}
}
else
{
for(std::size_t i=0; i<evals_re.size(); ++i)
{
if(tl2::equals<t_real>(evals_im[i], 0))
{
for(std::size_t j=0; j<N; ++j)
{
evecs_re[i][j] = outevecs[i*N + j];
evecs_im[i][j] = 0;
}
}
else
{
for(std::size_t j=0; j<N; ++j)
{
evecs_re[i][j] = outevecs[i*N + j];
evecs_im[i][j] = outevecs[(i+1)*N + j]; // imag part of evec follows next in array
evecs_re[i+1][j] = evecs_re[i][j]; // next evec is the conjugated one
evecs_im[i+1][j] = -evecs_im[i][j];
}
++i; // already used two values in array
}
}
}
if(normalise && (err == 0))
{
for(std::size_t i=0; i<evecs_re.size(); ++i)
{
t_real sum{0};
for(std::size_t j=0; j<N; ++j)
sum += std::norm(std::complex(evecs_re[i][j], evecs_im[i][j]));
sum = std::sqrt(sum);
if(!tl2::equals<t_real>(sum, 0))
{
evecs_re[i] /= sum;
evecs_im[i] /= sum;
}
}
}
}
return std::make_tuple(err == 0, evals_re, evals_im, evecs_re, evecs_im);
}
/**
* singular values of a real or complex matrix mat = U * diag{vals} * V^h
* @returns [ ok, U, Vh, vals ]
*/
template<class t_mat, class t_scalar = typename t_mat::value_type, class t_real = tl2::underlying_value_type<t_scalar>>
std::tuple<bool, t_mat, t_mat, std::vector<t_real>>
singval(const t_mat& mat)
requires tl2::is_mat<t_mat>
{
const std::size_t rows = mat.size1();
const std::size_t cols = mat.size2();
const auto [Nmin, Nmax] = std::minmax(rows, cols);
std::vector<t_scalar> inmat(rows*cols), outU(rows*rows), outVh(cols*cols);
std::vector<t_real> vals(Nmin);
std::vector<t_real> _tmp(Nmax * Nmax * 2);
for(std::size_t i=0; i<rows; ++i)
for(std::size_t j=0; j<cols; ++j)
inmat[i*cols + j] = mat(i,j);
int err = -1;
if constexpr(tl2::is_complex<t_scalar>)
{
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_cgesvd(LAPACK_ROW_MAJOR, 'A', 'A', rows, cols, inmat.data(), cols,
vals.data(), outU.data(), rows, outVh.data(), cols, _tmp.data());
else
err = LAPACKE_zgesvd(LAPACK_ROW_MAJOR, 'A', 'A', rows, cols, inmat.data(), cols,
vals.data(), outU.data(), rows, outVh.data(), cols, _tmp.data());
}
else
{
if constexpr(std::is_same_v<t_real, float>)
err = LAPACKE_sgesvd(LAPACK_ROW_MAJOR, 'A', 'A', rows, cols, inmat.data(), cols,
vals.data(), outU.data(), rows, outVh.data(), cols, _tmp.data());
else
err = LAPACKE_dgesvd(LAPACK_ROW_MAJOR, 'A', 'A', rows, cols, inmat.data(), cols,
vals.data(), outU.data(), rows, outVh.data(), cols, _tmp.data());
}
t_mat U = tl2::unit<t_mat>(rows);
t_mat Vh = tl2::unit<t_mat>(cols);
for(std::size_t i=0; i<Nmax; ++i)
{
for(std::size_t j=0; j<Nmax; ++j)
{
if(i<U.size1() && j<U.size2()) U(i,j) = outU[i*cols + j];
if(i<Vh.size1() && j<Vh.size2()) Vh(i,j) = outVh[i*cols + j];
}
}
return std::make_tuple(err==0, U, Vh, vals);
}
/**
* pseudoinverse M+ of a matrix
* @see https://de.wikipedia.org/wiki/Pseudoinverse#Berechnung
* @see (Arens 2015), pp. 788-792
*
* M = U D (V*)^h
* M+ = V D+ (U*)^h
*/
template<class t_mat>
std::tuple<t_mat, bool> pseudoinv(const t_mat& mat)
requires tl2::is_mat<t_mat>
{
using t_scalar = typename t_mat::value_type;
using t_real = tl2::underlying_value_type<t_scalar>;
auto [ ok, U, Vh, vals ] = singval<t_mat>(mat);
auto V = tl2::herm(Vh);
auto Uh = tl2::herm(U);
for(t_real& d : vals)
{
if(!tl2::equals<t_real>(d, t_real(0)))
d = t_real(1)/d;
}
auto diag = tl2::diag<t_mat>(vals);
return std::make_tuple(tl2::prod<t_mat>(V, tl2::prod(diag, Uh)), ok);
}
// ----------------------------------------------------------------------------
// equation solvers
// ----------------------------------------------------------------------------
/**
* system of ODEs with constant coefficients C
* @see (Arens 2015), pp. 1049-1051
*
* f'(x) = C f(x) and f(x0) = f0
* => f(x) = f0 * exp(C(x-x0)) = sum_i norm_i * evec_i * exp(eval_i * (x-x0))
* norm = (evec_i)^(-1) * f0
*/
template<class t_mat, class t_vec, class t_val = typename t_vec::value_type>
std::tuple<bool, t_vec>
odesys_const(const t_mat& C, const t_val& x, const t_val& x0, const t_vec& f0)
requires (tl2::is_mat<t_mat> && tl2::is_vec<t_vec>)
{
const std::size_t rows = C.size1();
const std::size_t cols = C.size2();
if(rows != cols)
return std::make_tuple(false, t_vec{});
const auto [ok, evals, evecs] = eigenvec<t_mat, t_vec, t_val>(C);
if(!ok)
return std::make_tuple(false, t_vec{});
//for(std::size_t i=0; i<evals.size(); ++i)
// std::cout << "eval: " << evals[i] << ", evec: " << evecs[i] << std::endl;
const t_mat basis = tl2::create<t_mat, t_vec, std::vector>(evecs, false);
const auto [basis_inv, invok] = tl2::inv<t_mat>(basis);
if(!invok)
return std::make_tuple(false, t_vec{});
const t_vec norm = basis_inv * f0;
t_vec f = tl2::zero<t_vec>(cols);
for(std::size_t i=0; i<cols; ++i)
f += norm[i] * evecs[i] * std::exp(evals[i]*(x-x0));
return std::make_tuple(true, f);
}
/**
* system of difference equations with constant coefficients C
*/
template<class t_mat, class t_vec, class t_val = typename t_vec::value_type>
std::tuple<bool, t_vec>
diffsys_const(const t_mat& C, const t_val& n, const t_val& n0, const t_vec& f0)
requires (tl2::is_mat<t_mat> && tl2::is_vec<t_vec>)
{
const std::size_t rows = C.size1();
const std::size_t cols = C.size2();
if(rows != cols)
return std::make_tuple(false, t_vec{});
const auto [ok, evals, evecs] = eigenvec<t_mat, t_vec, t_val>(C);
if(!ok)
return std::make_tuple(false, t_vec{});
//for(std::size_t i=0; i<evals.size(); ++i)
// std::cout << "eval: " << evals[i] << ", evec: " << evecs[i] << std::endl;
const t_mat basis = tl2::create<t_mat, t_vec, std::vector>(evecs, false);
const auto [basis_inv, invok] = tl2::inv<t_mat>(basis);
if(!invok)
return std::make_tuple(false, t_vec{});
const t_vec norm = basis_inv * f0;
t_vec f = tl2::zero<t_vec>(cols);
for(std::size_t i=0; i<cols; ++i)
f += norm[i] * evecs[i] * std::pow(evals[i], n-n0);
return std::make_tuple(true, f);
}
// ----------------------------------------------------------------------------
}
#endif // __TLIBS2_USE_LAPACK__
namespace tl2 {
/**
* QR decomposition of a matrix
* @returns [ok, Q, R]
* @see (Scarpino 2011), pp. 269-272
*/
template<class t_mat, class t_vec>
std::tuple<bool, t_mat, t_mat> qr(const t_mat& mat)
requires is_mat<t_mat> && is_vec<t_vec>
{
#ifdef __TLIBS2_USE_LAPACK__
return tl2_la::qr<t_mat, t_vec>(mat);
#else
const std::size_t rows = mat.size1();
const std::size_t cols = mat.size2();
const std::size_t N = std::min(cols, rows);
#if __TLIBS2_QR_METHOD == 0
t_mat R = mat;
t_mat Q = unit<t_mat>(N, N);
for(std::size_t icol=0; icol<N-1; ++icol)
{
t_vec vecCol = col<t_mat, t_vec>(R, icol);
t_mat matMirror = ortho_mirror_zero_op<t_mat, t_vec>(vecCol, icol);
Q = prod(Q, matMirror, false);
R = prod(matMirror, R);
}
#elif __TLIBS2_QR_METHOD == 1
std::vector<t_vec> sysM;
sysM.reserve(mat.size2());
for(std::size_t i=0; i<mat.size2(); ++i)
sysM.push_back(col<t_mat, t_vec>(mat, i));
std::vector<t_vec> Qsys = orthonorm_sys<t_vec, std::vector, std::vector>(sysM);
t_mat Q = create<t_mat>(Qsys, false);
t_mat R = prod(trans(Q), mat);
#endif
return std::make_tuple(true, Q, R);
#endif
}
/**
* inverted matrix
* @see https://en.wikipedia.org/wiki/Invertible_matrix#In_relation_to_its_adjugate
* @see https://en.wikipedia.org/wiki/Adjugate_matrix
*/
template<class t_mat>
std::tuple<t_mat, bool> inv(const t_mat& mat)
requires is_mat<t_mat>
{
// fails if matrix is not square, TODO: fix
if constexpr(tl2::is_dyn_mat<t_mat>)
assert((mat.size1() == mat.size2()));
else
static_assert(t_mat::size1() == t_mat::size2());
#ifdef __TLIBS2_USE_LAPACK__
return tl2_la::inv<t_mat>(mat);
#else
using T = typename t_mat::value_type;
using t_vec = std::vector<T>;
const std::size_t N = mat.size1();
const t_vec matFlat = convert<t_vec, t_mat>(mat);
const T fullDet = flat_det<t_vec>(matFlat, N);
// fail if determinant is zero
if(equals<T>(fullDet, 0))
{
//std::cerr << "det == 0" << std::endl;
return std::make_tuple(t_mat(), false);
}
t_mat matInv;
if constexpr(is_dyn_mat<t_mat>)
matInv = t_mat(N, N);
for(std::size_t i=0; i<N; ++i)
{
for(std::size_t j=0; j<N; ++j)
{
const T sgn = ((i+j) % 2) == 0 ? T(1) : T(-1);
const t_vec subMat = flat_submat<t_vec>(matFlat, N, N, i, j);
matInv(j,i) = sgn * flat_det<t_vec>(subMat, N-1);
}
}
matInv = matInv / fullDet;
return std::make_tuple(matInv, true);
#endif
}
/**
* determinant
*
* M v = l v
* M = V^-1 L V
* det(M) = det(V^-1 L V) = det(V V^-1 L) = det(L) = l_1*...*l_n
*/
template<class t_mat>
typename t_mat::value_type det(const t_mat& mat)
requires is_mat<t_mat>
{
using T = typename t_mat::value_type;
if(mat.size1() != mat.size2())
return 0;
#ifdef __TLIBS2_USE_LAPACK__
using t_vec = vec<T>;
if constexpr(tl2::is_complex<typename t_mat::value_type>)
{
const auto [ok, evals, evecs] =
tl2_la::eigenvec<t_mat, t_vec, T>(mat, true, false, false);
T detval{1, 0};
for(const auto& eval : evals)
detval *= eval;
return detval;
}
else
{
const auto [ok, evalsRe, evalsIm, evecsRe, evecsIm] =
tl2_la::eigenvec<t_mat, t_vec, T>(mat, true, false, false);
std::complex<T> detval{1, 0};
for(std::size_t i=0; i<evalsRe.size(); ++i)
detval *= std::complex<T>{evalsRe[i], evalsIm[i]};
return detval.real();
}
#else
std::vector<T> matFlat = convert<std::vector<T>, t_mat>(mat);
return flat_det<std::vector<T>>(matFlat, mat.size1());
#endif
}
/**
* matrix power
*/
template<class t_mat>
std::tuple<t_mat, bool> pow(const t_mat& mat, int ipow)
requires is_mat<t_mat>
{
t_mat themat;
if(mat.size1() != mat.size2())
return std::make_tuple(themat, false);
bool ok = true;
int ipow_pos = ipow<0 ? -ipow : ipow;
themat = unit<t_mat>(mat.size1());
for(int i=0; i<ipow_pos; ++i)
themat = themat*mat;
if(ipow < 0)
std::tie(themat, ok) = tl2::inv<t_mat>(themat);
return std::make_tuple(themat, ok);
}
/**
* least-squares regression, solves for parameters v
* @see https://en.wikipedia.org/wiki/Least_squares
* @see (Arens 2015), p. 793
*
* exact equation:
* X v = y
*
* approx. equation (normal equation):
* X^t X v = X^t y
* v = inv(X^t X) X^t y
*
* (QR)^t QR v = X^t y
* R^tQ^t QR v = X^t y
* R^tR v = X^t y
* v = inv(R^tR) X^t y
*/
template<class t_vec, class t_mat = mat<typename t_vec::value_type, std::vector>>
std::tuple<t_vec, bool> leastsq(const t_vec& x, const t_vec& y, std::size_t order,
bool use_qr=true, bool use_pseudoinv=false)
requires is_vec<t_vec> && is_dyn_mat<t_mat>
{
// check array sizes, TODO: fix
if constexpr(tl2::is_dyn_vec<t_vec>)
assert((x.size() == y.size()));
using namespace tl2_ops;
using T = typename t_vec::value_type;
const std::size_t N = x.size();
t_mat X{N, order+1};
for(std::size_t j=0; j<=order; ++j)
for(std::size_t i=0; i<N; ++i)
X(i,j) = std::pow(x[i], static_cast<T>(j));
t_mat XtX;
if(use_qr)
{
auto [ok_qr, Q, R] = qr<t_mat, t_vec>(X);
if(!ok_qr)
return std::make_tuple(t_vec{}, false);
XtX = trans<t_mat>(R) * R;
}
else
{
XtX = trans<t_mat>(X) * X;
}
t_vec Xty = trans<t_mat>(X) * y;
t_mat Y;
bool ok = false;
if(use_pseudoinv)
{
#ifdef __TLIBS2_USE_LAPACK__
std::tie(Y, ok) = tl2_la::pseudoinv<t_mat>(XtX);
#else
#pragma message("leastsq: Pseudo-inverse is not available, using standard inverse instead.")
std::tie(Y, ok) = inv<t_mat>(XtX);
#endif
}
else
{
std::tie(Y, ok) = inv<t_mat>(XtX);
}
t_vec v = Y * Xty;
return std::make_tuple(v, ok);
}
/**
* signed angle between two vectors
*/
template<typename t_vec>
typename t_vec::value_type angle(const t_vec& vec0,
const t_vec& vec1, const t_vec* pvec_norm=nullptr)
requires is_vec<t_vec>
{
using namespace tl2_ops;
using t_real = typename t_vec::value_type;
if(vec0.size() != vec1.size())
throw std::runtime_error("angle: vector sizes do not match.");
if(vec0.size() == 2)
{
// signed angles wrt basis
t_real angle0 = std::atan2(vec0[1], vec0[0]);
t_real angle1 = std::atan2(vec1[1], vec1[0]);
return angle1 - angle0;
}
if(vec0.size() == 3)
{
// cross product gives sine
t_vec veccross = cross<t_vec>({vec0, vec1});
t_real dS = norm(veccross);
// dot product gives cosine
t_real dC = inner(vec0, vec1);
t_real dAngle = std::atan2(dS, dC);
// get signed angle
if(pvec_norm)
{
// see if the cross product points along the direction
// of the given normal
if(inner(veccross, *pvec_norm) < t_real{0})
dAngle = -dAngle;
}
return dAngle;
}
throw std::runtime_error("angle: only implemented for size == 2 and size == 3.");
}
/**
* get the normal vector to a polygon
*/
template<class t_vec, template<class...> class t_cont = std::vector>
t_vec get_poly_normal(t_cont<t_vec>& vecPoly)
requires is_vec<t_vec>
{
using namespace tl2_ops;
using t_real = typename t_vec::value_type;
// line from centre to vertex
const t_vec vecCentre = mean(vecPoly);
// face normal
t_vec vecNormBest = zero<t_vec>(vecCentre.size());
t_real tBestCross = t_real(0);
// find non-collinear vectors
for(std::size_t iVecPoly=1; iVecPoly<vecPoly.size(); ++iVecPoly)
{
t_vec vecNorm = cross<t_vec>({vecPoly[0]-vecCentre, vecPoly[1]-vecCentre});
t_real tCross = norm(vecNorm);
if(tCross > tBestCross)
{
tBestCross = tCross;
vecNormBest = vecNorm;
}
}
// nothing found
if(vecNormBest.size() < vecCentre.size())
return t_vec{};
return vecNormBest;
}
/**
* sort vertices in a convex polygon
*/
template<class t_vec, template<class...> class t_cont = std::vector>
void sort_poly_verts_norm(t_cont<t_vec>& vecPoly, const t_vec& _vecNorm)
requires is_vec<t_vec>
{
using namespace tl2_ops;
if(vecPoly.size() <= 1)
return;
// line from centre to vertex
const t_vec vecCentre = mean(vecPoly);
const t_vec vecNorm = _vecNorm / norm(_vecNorm);
t_vec vec0 = vecPoly[0] - vecCentre;
std::stable_sort(vecPoly.begin(), vecPoly.end(),
[&vecCentre, &vec0, &vecNorm](const t_vec& vertex1, const t_vec& vertex2) -> bool
{
t_vec vec1 = vertex1 - vecCentre;
t_vec vec2 = vertex2 - vecCentre;
return angle(vec0, vec1, &vecNorm) < angle(vec0, vec2, &vecNorm);
});
}
/**
* sort vertices in a convex polygon using an absolute centre for determining the normal
* @returns normal
*/
template<class t_vec, template<class...> class t_cont = std::vector>
t_vec sort_poly_verts(t_cont<t_vec>& vecPoly, const t_vec& vecAbsCentre, bool make_norm_perp_to_poly=false)
requires is_vec<t_vec>
{
using namespace tl2_ops;
if(vecPoly.size() <= 1)
return t_vec{};
// line from centre to vertex
const t_vec vecCentre = mean(vecPoly);
// face normal
t_vec vecNorm = vecCentre - vecAbsCentre;
sort_poly_verts_norm<t_vec, t_cont>(vecPoly, vecNorm);
if(make_norm_perp_to_poly)
{
t_vec normal = get_poly_normal<t_vec, t_cont>(vecPoly);
// do they point in the same direction?
if(inner(normal, vecNorm) < 0.)
normal = -normal;
vecNorm = normal;
}
vecNorm /= norm(vecNorm);
return vecNorm;
}
/**
* sort vertices in a convex polygon determining normal
* @returns normal
*/
template<class t_vec, template<class...> class t_cont = std::vector>
t_vec sort_poly_verts(t_cont<t_vec>& vecPoly)
requires is_vec<t_vec>
{
using namespace tl2_ops;
if(vecPoly.size() <= 1)
return;
t_vec vecNorm = get_poly_normal<t_vec, t_cont>(vecPoly);
sort_poly_verts_norm<t_vec, t_cont>(vecPoly, vecNorm, true);
vecNorm /= norm(vecNorm);
return vecNorm;
}
}
#ifdef __TLIBS2_USE_QHULL__
namespace tl2_qh {
/**
* calculates the convex hull
* @see https://github.com/t-weber/misc/blob/master/geo/qhulltst.cpp
*/
template<class t_vec, template<class...> class t_cont = std::vector>
std::tuple<t_cont<t_cont<t_vec>>, t_cont<t_vec>, t_cont<typename t_vec::value_type>>
get_convexhull(const t_cont<t_vec>& vecVerts)
requires tl2::is_vec<t_vec>
{
using namespace tl2_ops;
using t_real = typename t_vec::value_type;
using t_real_qh = double;
using t_facetlist_iter = typename orgQhull::QhullLinkedList<orgQhull::QhullFacet>::iterator;
using t_vertexset_iter = typename orgQhull::QhullSet<orgQhull::QhullVertex>::iterator;
// copy vertices
int dim = vecVerts[0].size();
std::size_t len = vecVerts.size()*dim;
std::unique_ptr<t_real_qh[]> mem{new t_real_qh[len]};
std::size_t i=0;
for(const t_vec& vert : vecVerts)
{
for(int d=0; d<dim; ++d)
{
mem[i] = t_real_qh(vert[d]);
++i;
}
}
orgQhull::Qhull qhull{"tlibs2", dim, int(vecVerts.size()), mem.get(), "Qt"};
orgQhull::QhullFacetList facets = qhull.facetList();
t_cont<t_cont<t_vec>> vecPolys;
t_cont<t_vec> vecNormals;
t_cont<t_real> vecDists;
vecPolys.reserve(facets.size());
vecNormals.reserve(facets.size());
vecDists.reserve(facets.size());
//const t_vec vecCentre = tl2::mean(vecVerts);
for(t_facetlist_iter iter=facets.begin(); iter!=facets.end(); ++iter)
{
// triangulable?
if(iter->isUpperDelaunay())
continue;
orgQhull::QhullVertexSet vertices = iter->vertices();
t_cont<t_vec> vecPoly;
vecPoly.reserve(vertices.size());
for(t_vertexset_iter iterVertex=vertices.begin(); iterVertex!=vertices.end(); ++iterVertex)
{
orgQhull::QhullPoint point = (*iterVertex).point();
t_vec vecPoint(dim);
for(int i=0; i<dim; ++i)
vecPoint[i] = t_real(point[i]);
vecPoly.emplace_back(std::move(vecPoint));
}
t_vec vecNormal; //= tl2::sort_poly_verts<t_vec, t_cont>(vecPoly, vecCentre, true);
vecNormal.resize(dim);
orgQhull::QhullHyperplane plane = iter->hyperplane();
const t_real_qh* planenorm = plane.coordinates();
const t_real_qh planedist = plane.offset();
for(int i=0; i<dim; ++i)
vecNormal[i] = t_real(planenorm[i]);
vecPolys.emplace_back(std::move(vecPoly));
vecNormals.emplace_back(std::move(vecNormal));
vecDists.emplace_back(planedist);
}
// too few polygons => remove polyhedron
if(vecPolys.size() < 3)
vecPolys = decltype(vecPolys){};
return std::make_tuple(vecPolys, vecNormals, vecDists);
}
}
#endif
namespace tl2 {
// ----------------------------------------------------------------------------
// Quaternions
// @see (Kuipers 2002) for infos
// ----------------------------------------------------------------------------
template<class t_quat> t_quat unit_quat() requires is_quat<t_quat>
{
return t_quat(1, 0,0,0);
}
/**
* calculates the quaternion inverse
* @see (Bronstein 2008), Ch. 4
* @see (Kuipers 2002), p. 112
* @see https://en.wikipedia.org/wiki/Quaternion#Conjugation,_the_norm,_and_reciprocal
*/
template<class t_quat> t_quat inv(const t_quat& q) requires is_quat<t_quat>
{
t_quat qc{q.R_component_1(), -q.R_component_2(), -q.R_component_3(), -q.R_component_4()};
return qc / (q*qc);
}
/**
* quaternion product
* @see (Kuipers 2002), pp. 106-110
* @see https://en.wikipedia.org/wiki/Quaternion#Scalar_and_vector_parts
*/
template<class t_quat, class t_vec>
t_quat prod(const t_quat& q1, const t_quat& q2)
requires is_quat<t_quat> && is_vec<t_vec>
{
using T = typename t_quat::value_type;
T r1 = q1.R_component_1();
T r2 = q2.R_component_1();
t_vec vec1 = create<t_vec>({q1.R_component_2(), q1.R_component_3(), q1.R_component_4()});
t_vec vec2 = create<t_vec>({q2.R_component_2(), q2.R_component_3(), q2.R_component_4()});
T r = r1*r2 - inner<t_vec>(vec1, vec2);
t_vec vec = r1*vec2 + r2*vec1 + cross<t_vec>({vec1, vec2});;
return t_quat(r, vec[0], vec[1], vec[2]);
}
/**
* 3x3 matrix -> quat
* @desc algo from: http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q55
*/
template<class t_mat, class t_quat>
t_quat rot3_to_quat(const t_mat& rot)
requires is_quat<t_quat> && is_mat<t_mat>
{
using T = typename t_quat::value_type;
const T tr = trace<t_mat>(rot);
T v[3], w;
if(tr > T(0)) // scalar component is largest
{
w = T(0.5) * std::sqrt(tr+T(1));
v[0] = (rot(2,1) - rot(1,2)) / (T(4)*w);
v[1] = (rot(0,2) - rot(2,0)) / (T(4)*w);
v[2] = (rot(1,0) - rot(0,1)) / (T(4)*w);
}
else
{
for(std::size_t iComp=0; iComp<3; ++iComp) // find largest vector component
{
const std::size_t iM = iComp; // major comp.
const std::size_t im1 = (iComp+1)%3; // minor comp. 1
const std::size_t im2 = (iComp+2)%3; // minor comp. 2
if(rot(iM,iM)>=rot(im1,im1) && rot(iM,iM)>=rot(im2,im2))
{
v[iM] = T(0.5) * std::sqrt(T(1) + rot(iM,iM) - rot(im1,im1) - rot(im2,im2));
v[im1] = (rot(im1, iM) + rot(iM, im1)) / (v[iM]*T(4));
v[im2] = (rot(iM, im2) + rot(im2, iM)) / (v[iM]*T(4));
w = (rot(im2,im1) - rot(im1,im2)) / (v[iM]*T(4));
break;
}
if(iComp>=2)
throw std::runtime_error("rot3_to_quat: invalid condition.");
}
}
t_quat quatRet{w, v[0],v[1],v[2]};
T norm_eucl = std::sqrt(w*w + v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
return quatRet / norm_eucl;
}
/**
* quat -> 3x3 matrix
* @see (Desktop Bronstein 2008), formulas (4.162a/b)
* @see (Bronstein 2008), p. 296, formulas (4.109a/b)
*/
template<class t_quat, class t_mat>
t_mat quat_to_rot3(const t_quat& quat)
requires is_quat<t_quat> && is_mat<t_mat>
{
t_quat qc{quat.R_component_1(), -quat.R_component_2(), -quat.R_component_3(), -quat.R_component_4()};
const t_quat i{0,1,0,0}, j{0,0,1,0}, k{0,0,0,1};
const t_quat cols[] = { quat*i*qc, quat*j*qc, quat*k*qc };
t_mat mat = unit<t_mat>(3);
for(std::size_t icol=0; icol<3; ++icol)
{
mat(0, icol) = cols[icol].R_component_2();
mat(1, icol) = cols[icol].R_component_3();
mat(2, icol) = cols[icol].R_component_4();
}
return mat;
}
/**
* vector -> quat
* @see (Kuipers 2002), p. 114
*/
template<class t_vec, class t_quat>
t_quat vec3_to_quat(const t_vec& vec)
requires is_quat<t_quat> && is_vec<t_vec>
{
using T = typename t_vec::value_type;
return t_quat{T(0), vec[0], vec[1], vec[2]};
}
/**
* quat, vector product
* @see (Kuipers 2002), p. 127
*/
template<class t_quat, class t_vec>
t_vec quat_vec_prod(const t_quat& q, const t_vec& v)
requires is_quat<t_quat> && is_vec<t_vec>
{
t_quat qv = vec3_to_quat<t_vec, t_quat>(v);
t_quat qc{q.R_component_1(), -q.R_component_2(), -q.R_component_3(), -q.R_component_4()};
t_quat qvq = q * qv * qc;
return create<t_vec>({ qvq.R_component_2(), qvq.R_component_3(), qvq.R_component_4() });
}
/**
* quat -> complex 2x2 matrix
* @see (Scherer 2010), p.173
* @see (DesktopBronstein08), ch. 4, equations (4.163a) and (4.163b)
* @see (Bronstein08), ch. 4, p. 296, equation (4.110a) and (4.110b)
*/
template<class t_mat, class t_mat_cplx, class t_quat>
t_mat_cplx quat_to_cmat(const t_quat& quat)
requires is_quat<t_quat> && is_mat<t_mat> && is_mat<t_mat_cplx>
{
using t_cplx = typename t_mat_cplx::value_type;
const auto matI = unit<t_mat_cplx>(2);
t_mat_cplx mat =
t_cplx(quat.R_component_1()) * matI +
t_cplx(quat.R_component_2()) * su2_matrix<t_mat_cplx>(0) +
t_cplx(quat.R_component_3()) * su2_matrix<t_mat_cplx>(1) +
t_cplx(quat.R_component_4()) * su2_matrix<t_mat_cplx>(2);
return mat;
}
/**
* rotation angle
* @see https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix
*/
template<class t_quat>
typename t_quat::value_type rotation_angle(const t_quat& quat)
requires is_quat<t_quat>
{
using t_real = typename t_quat::value_type;
return t_real{2}*std::acos(quat.R_component_1());
}
/**
* quat -> rotation axis
* @see (Bronstein 2008), Ch. 4, pp. 301-302
* @see https://en.wikipedia.org/wiki/Quaternion#Exponential,_logarithm,_and_power_functions
* @see https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
*/
template<class t_quat, class t_vec>
std::pair<t_vec, typename t_vec::value_type> rotation_axis(const t_quat& quat)
requires is_quat<t_quat> && is_vec<t_vec>
{
using T = typename t_vec::value_type;
t_vec vec = create<t_vec>({
quat.R_component_2(),
quat.R_component_3(),
quat.R_component_4()
});
T angle = rotation_angle(quat);
vec /= std::sin(T{0.5}*angle);
return std::make_pair(vec, angle);
}
/**
* rotation axis -> quat
* @see (Desktop Bronstein 2008), formula (4.193)
* @see (Bronstein 2008), ch. 4, pp. 301-302
* @see https://en.wikipedia.org/wiki/Quaternion#Exponential,_logarithm,_and_power_functions
* @see https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation
*/
template<class t_vec, class t_quat>
t_quat rotation_quat(const t_vec& vec, typename t_vec::value_type angle)
requires is_quat<t_quat> && is_vec<t_vec>
{
using T = typename t_vec::value_type;
const T s = std::sin(T(0.5)*angle);
const T c = std::cos(T(0.5)*angle);
const T n = norm<t_vec>(vec);
const T x = s * vec[0] / n;
const T y = s * vec[1] / n;
const T z = s * vec[2] / n;
const T r = c;
return t_quat{r, x,y,z};
}
/**
* quaternion to rotate vec0 into vec1
*/
template<class t_vec, class t_quat>
t_quat rotation_quat(const t_vec& _vec0, const t_vec& _vec1)
requires is_quat<t_quat> && is_vec<t_vec>
{
using T = typename t_vec::value_type;
t_vec vec0 = _vec0 / norm<t_vec>(_vec0);
t_vec vec1 = _vec1 / norm<t_vec>(_vec1);
// parallel vectors -> do nothing
if(equals<t_vec>(vec0, vec1))
{
return unit_quat<t_quat>();
}
// antiparallel vectors -> rotate about any perpendicular axis
else if(equals<t_vec>(vec0, -vec1))
{
t_vec vecPerp = create<t_vec>({ vec0[2], T{0}, -vec0[0] });
return rotation_quat<t_quat, t_vec, T>(vecPerp, pi<T>);
}
// rotation axis from cross product
t_vec vecaxis = cross<t_vec>({vec0, vec1});
T dC = inner<t_vec>(vec0, vec1);
T dS = norm<t_vec>(vecaxis);
// rotation angle
T dAngle = std::atan2(dS, dC);
return rotation_quat<t_vec, t_quat>(vecaxis, dAngle);
}
template<class t_quat>
t_quat rotation_quat_x(typename t_quat::value_type angle)
requires is_quat<t_quat>
{
using T = typename t_quat::value_type;
return t_quat{std::cos(T(0.5)*angle), std::sin(T(0.5)*angle), T(0), T(0)};
}
template<class t_quat>
t_quat rotation_quat_y(typename t_quat::value_type angle)
requires is_quat<t_quat>
{
using T = typename t_quat::value_type;
return t_quat{std::cos(T(0.5)*angle), T(0), std::sin(T(0.5)*angle), T(0)};
}
template<class t_quat>
t_quat rotation_quat_z(typename t_quat::value_type angle)
requires is_quat<t_quat>
{
using T = typename t_quat::value_type;
return t_quat{std::cos(T(0.5)*angle), T(0), T(0), std::sin(T(0.5)*angle)};
}
/**
* XYZ euler angles -> quat
* @see (Kuipers 2002), pp. 166-167
*/
template<class t_quat>
t_quat euler_to_quat_xyz(
typename t_quat::value_type phi, typename t_quat::value_type theta, typename t_quat::value_type psi)
requires is_quat<t_quat>
{
t_quat q1 = rotation_quat_x<t_quat>(phi);
t_quat q2 = rotation_quat_y<t_quat>(theta);
t_quat q3 = rotation_quat_z<t_quat>(psi);
return q3 * q2 * q1;
}
/**
* ZXZ euler angles -> quat
* @see (Kuipers 2002), pp. 166-167
*/
template<class t_quat>
t_quat euler_to_quat_zxz(
typename t_quat::value_type phi, typename t_quat::value_type theta, typename t_quat::value_type psi)
requires is_quat<t_quat>
{
t_quat q1 = rotation_quat_z<t_quat>(phi);
t_quat q2 = rotation_quat_x<t_quat>(theta);
t_quat q3 = rotation_quat_z<t_quat>(psi);
return q3 * q2 * q1;
}
/**
* quat -> XYZ euler angles
* @see http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
*/
template<class t_quat>
std::vector<typename t_quat::value_type>
quat_to_euler_xyz(const t_quat& quat)
requires is_quat<t_quat>
{
using T = typename t_quat::value_type;
T q[] = { quat.R_component_1(), quat.R_component_2(),
quat.R_component_3(), quat.R_component_4() };
// formulas from:
// http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
T phi = std::atan2(T(2)*(q[0]*q[1] + q[2]*q[3]), T(1)-T(2)*(q[1]*q[1] + q[2]*q[2]));
T theta = std::asin(T(2)*(q[0]*q[2] - q[3]*q[1]));
T psi = std::atan2(T(2)*(q[0]*q[3] + q[1]*q[2]), T(1)-T(2)*(q[2]*q[2] + q[3]*q[3]));
return std::vector<T>({ phi, theta, psi });
}
/**
* @see (Desktop Bronstein 2008), formula (4.217)
* @see (Bronstein 2008), p. 308, formula (4.165)
*/
template<class t_quat>
t_quat stereo_proj(const t_quat& quat)
requires is_quat<t_quat>
{
using T = typename t_quat::value_type;
return (T{1}+quat) / (T{1}-quat);
}
/**
* @see (Desktop Bronstein 2008), formula (4.217)
* @see (Bronstein 2008), p. 308, formula (4.165)
*/
template<class t_quat>
t_quat stereo_proj_inv(const t_quat& quat)
requires is_quat<t_quat>
{
using T = typename t_quat::value_type;
return (T{1}-quat) / (T{1}+quat);
}
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Fourier transform
// @see (Scarpino 2011), ch. 14 for infos.
// ----------------------------------------------------------------------------
/**
* dft
* @see http://www.fftw.org/fftw3_doc/The-1d-Discrete-Fourier-Transform-_0028DFT_0029.html#The-1d-Discrete-Fourier-Transform-_0028DFT_0029
*/
template<typename T = double, class t_cplx = std::complex<T>,
template<class...> class t_cont = std::vector>
requires is_complex<t_cplx>
t_cplx dft_coeff(int k, const t_cont<t_cplx>& invec, bool bInv = false)
{
const std::size_t N = invec.size();
t_cplx imag(0., 1.);
t_cplx f(0., 0.);
for(std::size_t j=0; j<N; ++j)
{
T dv = T(-2)*pi<T>*T(j)*T(k)/T(N);
if(bInv) dv = -dv;
f += invec[j] * (std::cos(dv) + imag*std::sin(dv));
}
return f;
}
/**
* dft
* @see http://www.fftw.org/fftw3_doc/The-1d-Discrete-Fourier-Transform-_0028DFT_0029.html#The-1d-Discrete-Fourier-Transform-_0028DFT_0029
*/
template<typename T = double, class t_cplx = std::complex<T>,
template<class...> class t_cont = std::vector>
requires is_complex<t_cplx>
t_cont<t_cplx> dft(const t_cont<t_cplx>& invec,
bool bInv = false, bool bNorm = false)
{
const std::size_t N = invec.size();
t_cont<t_cplx> outvec;
outvec.resize(N);
for(std::size_t k=0; k<N; ++k)
{
outvec[k] = dft_coeff<T, t_cplx, t_cont>(k, invec, bInv);
if(bNorm && bInv)
outvec[k] /= N;
}
return outvec;
}
/**
* fft
* @see (Scarpino 2011), ch. 14.
*/
template<typename T = double, class t_cplx = std::complex<T>>
requires is_complex<t_cplx>
t_cplx fft_factor(T N, T k, bool bInv = false)
{
T ph = bInv ? -1 : 1.;
T c = std::cos(T(2)*pi<T>*k/N * ph);
T s = std::sin(T(2)*pi<T>*k/N * ph);
return t_cplx{c, -s};
}
/**
* fft
* @see (Scarpino 2011), ch. 14.
*/
template<typename T = double, class t_cplx = std::complex<T>,
template<class...> class t_cont = std::vector>
requires is_complex<t_cplx>
t_cont<t_cplx> fft_reorder(const t_cont<t_cplx>& vecIn)
{
t_cont<std::size_t> vecIdx =
bit_reverse_indices<std::size_t, t_cont>(vecIn.size());
t_cont<t_cplx> vecInRev;
vecInRev.reserve(vecIn.size());
for(std::size_t i=0; i<vecIn.size(); ++i)
vecInRev.push_back(vecIn[vecIdx[i]]);
return vecInRev;
}
/**
* fft
* @see (Scarpino 2011), ch. 14.
*/
template<typename T = double, class t_cplx = std::complex<T>,
template<class...> class t_cont = std::vector>
requires is_complex<t_cplx>
t_cont<t_cplx> fft_merge(const t_cont<t_cplx>& vecIn, bool bInv = false)
{
const std::size_t N = vecIn.size();
const std::size_t N2 = N/2;
if(N==0 || N==1)
return vecIn;
auto split_vec = [](const t_cont<t_cplx>& vec)
-> std::pair<t_cont<t_cplx>, t_cont<t_cplx>>
{
std::size_t N = vec.size();
t_cont<t_cplx> vec1, vec2;
vec1.reserve(N/2);
vec2.reserve(N/2);
for(std::size_t i=0; i<N/2; ++i)
{
vec1.push_back(vec[i]);
vec2.push_back(vec[N/2 + i]);
}
return std::make_pair(std::move(vec1), std::move(vec2));
};
auto pair = split_vec(vecIn);
t_cont<t_cplx> vec1 = fft_merge<T, t_cplx, t_cont>(pair.first, bInv);
t_cont<t_cplx> vec2 = fft_merge<T, t_cplx, t_cont>(pair.second, bInv);
t_cont<t_cplx> vecOut;
vecOut.resize(N);
for(std::size_t i=0; i<N2; ++i)
{
vecOut[i] = vec1[i] + vec2[i]*fft_factor<T, t_cplx>(N, i, bInv);
vecOut[N2+i] = vec1[i] + vec2[i]*fft_factor<T, t_cplx>(N, N2+i, bInv);
}
return vecOut;
}
/**
* fft
* @see (Scarpino 2011), ch. 14.
*/
template<typename T = double, class t_cplx = std::complex<T>,
template<class...> class t_cont = std::vector>
requires is_complex<t_cplx>
t_cont<t_cplx> fft(const t_cont<t_cplx>& vecIn,
bool bInv = false, bool bNorm = false)
{
const std::size_t n = vecIn.size();
t_cont<t_cplx> vecOut;
vecOut.resize(n);
vecOut = fft_reorder<T, t_cplx, t_cont>(vecIn);
vecOut = fft_merge<T, t_cplx, t_cont>(vecOut, bInv);
if(bInv && bNorm)
for(t_cplx& c : vecOut)
c /= n;
return vecOut;
}
// ----------------------------------------------------------------------------
}
// ----------------------------------------------------------------------------
#endif
| {
"alphanum_fraction": 0.6362540972,
"avg_line_length": 25.9537502995,
"ext": "h",
"hexsha": "77f0a002d863f7efdd4e59361607ae9f97fa4c3d",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-09-20T19:30:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-20T19:30:13.000Z",
"max_forks_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2",
"max_forks_repo_path": "libs/maths.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87",
"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": "tweber-ill/ill_mirror-takin2-tlibs2",
"max_issues_repo_path": "libs/maths.h",
"max_line_length": 199,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "669fd34c306625fd306da278a5b29fb6aae16a87",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "tweber-ill/ill_mirror-takin2-tlibs2",
"max_stars_repo_path": "libs/maths.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 68871,
"size": 216610
} |
// Copyright © Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root
// for more information.
#ifndef NOVELRT_INPUT_H
#define NOVELRT_INPUT_H
// Input Dependencies
#include "NovelRT/LoggingService.h"
#include "NovelRT/Maths/Maths.h"
#include "NovelRT/Timing/Timestamp.h"
#include <gsl/span>
#include <map>
#include <string>
/**
* @Brief The input plugin API.
*/
namespace NovelRT::Input
{
enum class KeyState;
class IInputDevice;
class NovelKey;
struct InputAction;
}
// clang-format off
// Input Types
#include "IInputDevice.h"
#include "KeyState.h"
#include "NovelKey.h"
#include "InputAction.h"
// clang-format on
#endif // NOVELRT_INPUT_H
| {
"alphanum_fraction": 0.7336122734,
"avg_line_length": 20.4857142857,
"ext": "h",
"hexsha": "c1c0e39b064c31ad047713fcf6015748ddbfb95b",
"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": "53e341a79db9e84b47f80e12e1d7049a6874811d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Shidesu/NovelRT",
"max_forks_repo_path": "include/NovelRT/Input/Input.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "53e341a79db9e84b47f80e12e1d7049a6874811d",
"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": "Shidesu/NovelRT",
"max_issues_repo_path": "include/NovelRT/Input/Input.h",
"max_line_length": 119,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "53e341a79db9e84b47f80e12e1d7049a6874811d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Shidesu/NovelRT",
"max_stars_repo_path": "include/NovelRT/Input/Input.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 182,
"size": 717
} |
//This takes univariate X, windows X with W, applies the 1D FFT to each frame,
//takes power, transforms with T mat to B cfs, and then compresses power.
//The output Y is power (real-valued), i.e. the FFT squared.
//The size of Y is BxC if dim==0, and RxB if dim==1.
//This is equivalent to stft -> apply_spectrogram_T_mat -> pow_compress.
#include <stdio.h>
#include <float.h>
#include <math.h>
#include <cblas.h>
#include <fftw3.h>
#ifdef __cplusplus
namespace codee {
extern "C" {
#endif
int spectrogram_s (float *Y, const float *X1, const float *X2, const float *X3, const size_t N, const size_t L, const size_t B, const size_t F, const int c0, const float stp, const int mn0, const float p, const float preg);
int spectrogram_s (float *Y, const int iscolmajor, const int R, const int C, const float *X, const int N, const float *W, const int L, const float *H, const int dim, const int c0, const float stp, const int mn0, const int nfft, const float p, const float preg);
int spectrogram_d (double *Y, const int iscolmajor, const int R, const int C, const double *X, const int N, const double *W, const int L, const double *H, const int dim, const int c0, const double stp, const int mn0, const int nfft, const double p, const double preg);
int spectrogram_s (float *Y, const int iscolmajor, const int R, const int C, const float *X, const int N, const float *W, const int L, const float *H, const int dim, const int c0, const float stp, const int mn0, const int nfft, const float p, const float preg)
{
const float z = 0.0f, o = 1.0f;
const int F = nfft/2 + 1; //num non-negative FFT freqs
const int Lpre = L/2; //nsamps before center samp
int ss = c0 - Lpre; //start samp of current frame
int r, c, f, n = 0;
float *X1, *Y1;
fftwf_plan plan;
//struct timespec tic, toc;
//Checks
if (N<1) { fprintf(stderr,"error in spectrogram_s: N (length X) must be positive\n"); return 1; }
if (R<1) { fprintf(stderr,"error in spectrogram_s: R (nrows Y) must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in spectrogram_s: C (ncols Y) must be positive\n"); return 1; }
if (L<1) { fprintf(stderr,"error in spectrogram_s: L (winlength) must be positive\n"); return 1; }
if (c0<0) { fprintf(stderr,"error in spectrogram_s: c0 (center samp of 1st frame) must be nonnegative\n"); return 1; }
if (c0>N-1) { fprintf(stderr,"error in spectrogram_s: c0 (center samp of 1st frame) must be < N (length X)\n"); return 1; }
if (L>=N) { fprintf(stderr,"error in spectrogram_s: L (winlength) must be < N (length X)\n"); return 1; }
if (stp<=0.0f) { fprintf(stderr,"error in spectrogram_s: stp (step size) must be positive\n"); return 1; }
if (nfft<L) { fprintf(stderr,"error in spectrogram_s: nfft must be >= L (winlength)\n"); return 1; }
if (p!=p || p<0.0f || p>1.0f) { fprintf(stderr,"error in spectrogram_s: p must be in [0.0 1.0]\n"); return 1; }
if (preg!=preg || preg<0.0f) { fprintf(stderr,"error in spectrogram_s: preg must be nonnegative\n"); return 1; }
//Initialize fftwf
X1 = fftwf_alloc_real((size_t)nfft);
Y1 = fftwf_alloc_real((size_t)nfft);
plan = fftwf_plan_r2r_1d(nfft,X1,Y1,FFTW_R2HC,FFTW_ESTIMATE);
if (!plan) { fprintf(stderr,"error in spectrogram_s: problem creating fftw plan\n"); return 1; }
cblas_scopy(nfft,&z,0,&X1[0],1); //zero-pad
//clock_gettime(CLOCK_REALTIME,&tic);
//Initialize Y to preg
cblas_scopy(R*C,&preg,0,&Y[0],1);
if (dim==0)
{
if (iscolmajor)
{
for (c=0; c<C; c++)
{
//Window
ss = (int)(roundf(c*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_scopy(-ss,&z,0,&X1[0],1);
cblas_ssbmv(CblasColMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_ssbmv(CblasColMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
}
else if (ss<N)
{
cblas_ssbmv(CblasColMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_scopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftwf_execute(plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_sgemv(CblasColMajor,CblasNoTrans,R,F,1.0f,&H[0],R,&Y1[0],1,1.0f,&Y[c*R],1);
//for (b=0; b<R; b++) { Y[b+c*R] += cblas_sdot(f2s[b],&H[b+f1s[b]*R],R,&Y1[f1s[b]],1); }
}
}
else
{
for (c=0; c<C; c++)
{
//Window
ss = (int)(roundf(c*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_scopy(-ss,&z,0,&X1[0],1);
cblas_ssbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_ssbmv(CblasRowMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
}
else if (ss<N)
{
cblas_ssbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_scopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftwf_execute(plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_sgemv(CblasRowMajor,CblasNoTrans,R,F,1.0f,&H[0],F,&Y1[0],1,1.0f,&Y[c],C);
}
}
}
else if (dim==1)
{
if (iscolmajor)
{
for (r=0; r<R; r++)
{
//Window
ss = (int)(roundf(r*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_scopy(-ss,&z,0,&X1[0],1);
cblas_ssbmv(CblasColMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_ssbmv(CblasColMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
}
else if (ss<N)
{
cblas_ssbmv(CblasColMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_scopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftwf_execute(plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_sgemv(CblasColMajor,CblasNoTrans,C,F,1.0f,&H[0],C,&Y1[0],1,1.0f,&Y[r],R);
}
}
else
{
for (r=0; r<R; r++)
{
//Window
ss = (int)(roundf(r*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_scopy(-ss,&z,0,&X1[0],1);
cblas_ssbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_ssbmv(CblasRowMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
}
else if (ss<N)
{
cblas_ssbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_scopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftwf_execute(plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_sgemv(CblasRowMajor,CblasNoTrans,C,F,1.0f,&H[0],F,&Y1[0],1,1.0f,&Y[r*C],1);
}
}
}
else
{
fprintf(stderr,"error in spectrogram_s: dim must be 0 or 1.\n"); return 1;
}
//clock_gettime(CLOCK_REALTIME,&toc); fprintf(stderr,"elapsed time = %f ms\n",(toc.tv_sec-tic.tv_sec)*1e3+(toc.tv_nsec-tic.tv_nsec)/1e6);
//Power compress
if (1.0f-p>FLT_EPSILON)
{
if (p>FLT_EPSILON)
{
if (fabsf(p-0.5f)<=FLT_EPSILON) { for (n=0; n<R*C; n++) { Y[n] = sqrtf(Y[n]+preg); } }
else if (fabsf(p-1.0f/3.0f)<=FLT_EPSILON) { for (n=0; n<R*C; n++) { Y[n] = cbrtf(Y[n]+preg); } }
else { for (n=0; n<R*C; n++) { Y[n] = powf(Y[n]+preg,p); } }
}
else { for (n=0; n<R*C; n++) { Y[n] = logf(Y[n]+preg); } }
}
else { for (n=0; n<R*C; n++) { Y[n] += preg; } }
//Exit
fftwf_destroy_plan(plan); fftwf_free(X1); fftwf_free(Y1);
return 0;
}
int spectrogram_d (double *Y, const int iscolmajor, const int R, const int C, const double *X, const int N, const double *W, const int L, const double *H, const int dim, const int c0, const double stp, const int mn0, const int nfft, const double p, const double preg)
{
const double z = 0.0, o = 1.0;
const int F = nfft/2 + 1; //num non-negative FFT freqs
const int Lpre = L/2; //nsamps before center samp
int ss = c0 - Lpre; //start samp of current frame
int r, c, f, n = 0;
double *X1, *Y1;
fftw_plan plan;
//Checks
if (N<1) { fprintf(stderr,"error in spectrogram_d: N (length X) must be positive\n"); return 1; }
if (R<1) { fprintf(stderr,"error in spectrogram_d: R (nrows Y) must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in spectrogram_d: C (ncols Y) must be positive\n"); return 1; }
if (L<1) { fprintf(stderr,"error in spectrogram_d: L (winlength) must be positive\n"); return 1; }
if (c0<0) { fprintf(stderr,"error in spectrogram_d: c0 (center samp of 1st frame) must be nonnegative\n"); return 1; }
if (c0>N-1) { fprintf(stderr,"error in spectrogram_d: c0 (center samp of 1st frame) must be < N (length X)\n"); return 1; }
if (L>=N) { fprintf(stderr,"error in spectrogram_d: L (winlength) must be < N (length X)\n"); return 1; }
if (stp<=0.0) { fprintf(stderr,"error in spectrogram_d: stp (step size) must be positive\n"); return 1; }
if (nfft<L) { fprintf(stderr,"error in spectrogram_d: nfft must be >= L (winlength)\n"); return 1; }
if (p!=p || p<0.0 || p>1.0) { fprintf(stderr,"error in spectrogram_d: p must be in [0.0 1.0]\n"); return 1; }
if (preg!=preg || preg<0.0) { fprintf(stderr,"error in spectrogram_d: preg must be nonnegative\n"); return 1; }
//Initialize fftw
X1 = fftw_alloc_real((size_t)nfft);
Y1 = fftw_alloc_real((size_t)nfft);
plan = fftw_plan_r2r_1d(nfft,X1,Y1,FFTW_R2HC,FFTW_ESTIMATE);
if (!plan) { fprintf(stderr,"error in spectrogram_d: problem creating fftw plan\n"); return 1; }
cblas_dcopy(nfft,&z,0,&X1[0],1); //zero-pad
//Initialize Y to preg
cblas_dcopy(R*C,&preg,0,&Y[0],1);
if (dim==0)
{
if (iscolmajor)
{
for (c=0; c<C; c++)
{
//Window
ss = (int)(round(c*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_dcopy(-ss,&z,0,&X1[0],1);
cblas_dsbmv(CblasColMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_dsbmv(CblasColMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
}
else if (ss<N)
{
cblas_dsbmv(CblasColMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_dcopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftw_execute(plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_dgemv(CblasColMajor,CblasNoTrans,R,F,1.0,&H[0],R,&Y1[0],1,1.0,&Y[c*R],1);
}
}
else
{
for (c=0; c<C; c++)
{
//Window
ss = (int)(round(c*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_dcopy(-ss,&z,0,&X1[0],1);
cblas_dsbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_dsbmv(CblasRowMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
}
else if (ss<N)
{
cblas_dsbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_dcopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftw_execute(plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_dgemv(CblasRowMajor,CblasNoTrans,R,F,1.0,&H[0],F,&Y1[0],1,1.0,&Y[c],C);
}
}
}
else if (dim==1)
{
if (iscolmajor)
{
for (r=0; r<R; r++)
{
//Window
ss = (int)(round(r*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_dcopy(-ss,&z,0,&X1[0],1);
cblas_dsbmv(CblasColMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_dsbmv(CblasColMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
}
else if (ss<N)
{
cblas_dsbmv(CblasColMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_dcopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftw_execute(plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_dgemv(CblasColMajor,CblasNoTrans,C,F,1.0,&H[0],C,&Y1[0],1,1.0,&Y[r],R);
}
}
else
{
for (r=0; r<R; r++)
{
//Window
ss = (int)(round(r*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_dcopy(-ss,&z,0,&X1[0],1);
cblas_dsbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_dsbmv(CblasRowMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
}
else if (ss<N)
{
cblas_dsbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_dcopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftw_execute(plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F-1+nfft%2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_dgemv(CblasRowMajor,CblasNoTrans,C,F,1.0,&H[0],F,&Y1[0],1,1.0,&Y[r*C],1);
}
}
}
else
{
fprintf(stderr,"error in spectrogram_d: dim must be 0 or 1.\n"); return 1;
}
//Power compress
if (1.0-p>DBL_EPSILON)
{
if (p>DBL_EPSILON)
{
if (fabs(p-0.5)<=DBL_EPSILON) { for (n=0; n<R*C; n++) { Y[n] = sqrt(Y[n]+preg); } }
else if (fabs(p-1.0/3.0)<=DBL_EPSILON) { for (n=0; n<R*C; n++) { Y[n] = cbrt(Y[n]+preg); } }
else { for (n=0; n<R*C; n++) { Y[n] = pow(Y[n]+preg,p); } }
}
else { for (n=0; n<R*C; n++) { Y[n] = log(Y[n]+preg); } }
}
else { for (n=0; n<R*C; n++) { Y[n] += preg; } }
//Exit
fftw_destroy_plan(plan); fftw_free(X1); fftw_free(Y1);
return 0;
}
#ifdef __cplusplus
}
}
#endif
// //Get Hb (banded H) //this worked to get banded matrix storage (but was slower!):
// if (!(Hb=(float *)calloc((size_t)((kl+ku+1)*B),sizeof(float)))) { fprintf(stderr,"error in spectrogram_s: problem with calloc for Hb. "); perror("calloc"); return 1; }
// if (iscolmajor)
// {
// for (r=0; r<kl+1+ku; r++)
// {
// if (r<ku) { b = 0; f = ku - r; }
// else { b = r - ku; f = 0; }
// while (b<B && f<F) { Hb[r+f*(kl+1+ku)] = H[b+f*B]; b++; f++; }
// }
// }
// else
// {
// for (c=0; c<kl+1+ku; c++)
// {
// if (c<kl) { b = kl - c; f = 0; }
// else { b = 0; f = c - kl; }
// while (b<B && f<F) { Hb[c+b*(kl+1+ku)] = H[f+b*F]; b++; f++; }
// }
// }
// ...
// cblas_sgbmv(CblasRowMajor,CblasNoTrans,B,F,kl,ku,1.0f,&Hb[0],kl+ku+1,&Y1[0],1,1.0f,&Y[c],C);
| {
"alphanum_fraction": 0.4547426034,
"avg_line_length": 38.967806841,
"ext": "c",
"hexsha": "7283b0531bf8d2706e2e32a44301171fd3cbaa1c",
"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": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/aud",
"max_forks_repo_path": "c/spectrogram.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/aud",
"max_issues_repo_path": "c/spectrogram.c",
"max_line_length": 268,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/aud",
"max_stars_repo_path": "c/spectrogram.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6564,
"size": 19367
} |
#ifndef COMMAND_UTILS_INCLUDE
#define COMMAND_UTILS_INCLUDE
#include <limits>
#include <string>
#include <vector>
#include <gsl/string_span>
#include "tmpFile.h"
namespace execHelper {
namespace test {
namespace baseUtils {
using ConfigFile = TmpFile;
const gsl::czstring<> EXEC_HELPER_BINARY = "exec-helper";
const gsl::czstring<> COMMAND_KEY = "commands";
const gsl::czstring<> COMMAND_LINE_COMMAND_KEY = "command-line-command";
const gsl::czstring<> COMMAND_LINE_COMMAND_LINE_KEY = "command-line";
using ReturnCode = int32_t;
static const ReturnCode SUCCESS = EXIT_SUCCESS;
static const ReturnCode RUNTIME_ERROR = std::numeric_limits<ReturnCode>::max();
} // namespace baseUtils
} // namespace test
} // namespace execHelper
#endif /* COMMAND_UTILS_INCLUDE */
| {
"alphanum_fraction": 0.774025974,
"avg_line_length": 25.6666666667,
"ext": "h",
"hexsha": "933dd85964978cbca2b985474beb76ee53b07013",
"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/commandUtils.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/commandUtils.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/commandUtils.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": 170,
"size": 770
} |
/* integration/qmomof.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
static void
compute_moments (double par, double * cheb);
static int
dgtsl (size_t n, double *c, double *d, double *e, double *b);
gsl_integration_qawo_table *
gsl_integration_qawo_table_alloc (double omega, double L,
enum gsl_integration_qawo_enum sine,
size_t n)
{
gsl_integration_qawo_table *t;
double * chebmo;
if (n == 0)
{
GSL_ERROR_VAL ("table length n must be positive integer",
GSL_EDOM, 0);
}
t = (gsl_integration_qawo_table *)
malloc (sizeof (gsl_integration_qawo_table));
if (t == 0)
{
GSL_ERROR_VAL ("failed to allocate space for qawo_table struct",
GSL_ENOMEM, 0);
}
chebmo = (double *) malloc (25 * n * sizeof (double));
if (chebmo == 0)
{
free (t);
GSL_ERROR_VAL ("failed to allocate space for chebmo block",
GSL_ENOMEM, 0);
}
t->n = n;
t->sine = sine;
t->omega = omega;
t->L = L;
t->par = 0.5 * omega * L;
t->chebmo = chebmo;
/* precompute the moments */
{
size_t i;
double scale = 1.0;
for (i = 0 ; i < t->n; i++)
{
compute_moments (t->par * scale, t->chebmo + 25*i);
scale *= 0.5;
}
}
return t;
}
int
gsl_integration_qawo_table_set (gsl_integration_qawo_table * t,
double omega, double L,
enum gsl_integration_qawo_enum sine)
{
t->omega = omega;
t->sine = sine;
t->L = L;
t->par = 0.5 * omega * L;
/* recompute the moments */
{
size_t i;
double scale = 1.0;
for (i = 0 ; i < t->n; i++)
{
compute_moments (t->par * scale, t->chebmo + 25*i);
scale *= 0.5;
}
}
return GSL_SUCCESS;
}
int
gsl_integration_qawo_table_set_length (gsl_integration_qawo_table * t,
double L)
{
/* return immediately if the length is the same as the old length */
if (L == t->L)
return GSL_SUCCESS;
/* otherwise reset the table and compute the new parameters */
t->L = L;
t->par = 0.5 * t->omega * L;
/* recompute the moments */
{
size_t i;
double scale = 1.0;
for (i = 0 ; i < t->n; i++)
{
compute_moments (t->par * scale, t->chebmo + 25*i);
scale *= 0.5;
}
}
return GSL_SUCCESS;
}
void
gsl_integration_qawo_table_free (gsl_integration_qawo_table * t)
{
RETURN_IF_NULL (t);
free (t->chebmo);
free (t);
}
static void
compute_moments (double par, double *chebmo)
{
double v[28], d[25], d1[25], d2[25];
const size_t noeq = 25;
const double par2 = par * par;
const double par4 = par2 * par2;
const double par22 = par2 + 2.0;
const double sinpar = sin (par);
const double cospar = cos (par);
size_t i;
/* compute the chebyschev moments with respect to cosine */
double ac = 8 * cospar;
double as = 24 * par * sinpar;
v[0] = 2 * sinpar / par;
v[1] = (8 * cospar + (2 * par2 - 8) * sinpar / par) / par2;
v[2] = (32 * (par2 - 12) * cospar
+ (2 * ((par2 - 80) * par2 + 192) * sinpar) / par) / par4;
if (fabs (par) <= 24)
{
/* compute the moments as the solution of a boundary value
problem using the asyptotic expansion as an endpoint */
double an2, ass, asap;
double an = 6;
size_t k;
for (k = 0; k < noeq - 1; k++)
{
an2 = an * an;
d[k] = -2 * (an2 - 4) * (par22 - 2 * an2);
d2[k] = (an - 1) * (an - 2) * par2;
d1[k + 1] = (an + 3) * (an + 4) * par2;
v[k + 3] = as - (an2 - 4) * ac;
an = an + 2.0;
}
an2 = an * an;
d[noeq - 1] = -2 * (an2 - 4) * (par22 - 2 * an2);
v[noeq + 2] = as - (an2 - 4) * ac;
v[3] = v[3] - 56 * par2 * v[2];
ass = par * sinpar;
asap = (((((210 * par2 - 1) * cospar - (105 * par2 - 63) * ass) / an2
- (1 - 15 * par2) * cospar + 15 * ass) / an2
- cospar + 3 * ass) / an2
- cospar) / an2;
v[noeq + 2] = v[noeq + 2] - 2 * asap * par2 * (an - 1) * (an - 2);
dgtsl (noeq, d1, d, d2, v + 3);
}
else
{
/* compute the moments by forward recursion */
size_t k;
double an = 4;
for (k = 3; k < 13; k++)
{
double an2 = an * an;
v[k] = ((an2 - 4) * (2 * (par22 - 2 * an2) * v[k - 1] - ac)
+ as - par2 * (an + 1) * (an + 2) * v[k - 2])
/ (par2 * (an - 1) * (an - 2));
an = an + 2.0;
}
}
for (i = 0; i < 13; i++)
{
chebmo[2 * i] = v[i];
}
/* compute the chebyschev moments with respect to sine */
v[0] = 2 * (sinpar - par * cospar) / par2;
v[1] = (18 - 48 / par2) * sinpar / par2 + (-2 + 48 / par2) * cospar / par;
ac = -24 * par * cospar;
as = -8 * sinpar;
if (fabs (par) <= 24)
{
/* compute the moments as the solution of a boundary value
problem using the asyptotic expansion as an endpoint */
size_t k;
double an2, ass, asap;
double an = 5;
for (k = 0; k < noeq - 1; k++)
{
an2 = an * an;
d[k] = -2 * (an2 - 4) * (par22 - 2 * an2);
d2[k] = (an - 1) * (an - 2) * par2;
d1[k + 1] = (an + 3) * (an + 4) * par2;
v[k + 2] = ac + (an2 - 4) * as;
an = an + 2.0;
}
an2 = an * an;
d[noeq - 1] = -2 * (an2 - 4) * (par22 - 2 * an2);
v[noeq + 1] = ac + (an2 - 4) * as;
v[2] = v[2] - 42 * par2 * v[1];
ass = par * cospar;
asap = (((((105 * par2 - 63) * ass - (210 * par2 - 1) * sinpar) / an2
+ (15 * par2 - 1) * sinpar
- 15 * ass) / an2 - sinpar - 3 * ass) / an2 - sinpar) / an2;
v[noeq + 1] = v[noeq + 1] - 2 * asap * par2 * (an - 1) * (an - 2);
dgtsl (noeq, d1, d, d2, v + 2);
}
else
{
/* compute the moments by forward recursion */
size_t k;
double an = 3;
for (k = 2; k < 12; k++)
{
double an2 = an * an;
v[k] = ((an2 - 4) * (2 * (par22 - 2 * an2) * v[k - 1] + as)
+ ac - par2 * (an + 1) * (an + 2) * v[k - 2])
/ (par2 * (an - 1) * (an - 2));
an = an + 2.0;
}
}
for (i = 0; i < 12; i++)
{
chebmo[2 * i + 1] = v[i];
}
}
static int
dgtsl (size_t n, double *c, double *d, double *e, double *b)
{
/* solves a tridiagonal matrix A x = b
c[1 .. n - 1] subdiagonal of the matrix A
d[0 .. n - 1] diagonal of the matrix A
e[0 .. n - 2] superdiagonal of the matrix A
b[0 .. n - 1] right hand side, replaced by the solution vector x */
size_t k;
c[0] = d[0];
if (n == 0)
{
return GSL_SUCCESS;
}
if (n == 1)
{
b[0] = b[0] / d[0] ;
return GSL_SUCCESS;
}
d[0] = e[0];
e[0] = 0;
e[n - 1] = 0;
for (k = 0; k < n - 1; k++)
{
size_t k1 = k + 1;
if (fabs (c[k1]) >= fabs (c[k]))
{
{
double t = c[k1];
c[k1] = c[k];
c[k] = t;
};
{
double t = d[k1];
d[k1] = d[k];
d[k] = t;
};
{
double t = e[k1];
e[k1] = e[k];
e[k] = t;
};
{
double t = b[k1];
b[k1] = b[k];
b[k] = t;
};
}
if (c[k] == 0)
{
return GSL_FAILURE ;
}
{
double t = -c[k1] / c[k];
c[k1] = d[k1] + t * d[k];
d[k1] = e[k1] + t * e[k];
e[k1] = 0;
b[k1] = b[k1] + t * b[k];
}
}
if (c[n - 1] == 0)
{
return GSL_FAILURE;
}
b[n - 1] = b[n - 1] / c[n - 1];
b[n - 2] = (b[n - 2] - d[n - 2] * b[n - 1]) / c[n - 2];
for (k = n ; k > 2; k--)
{
size_t kb = k - 3;
b[kb] = (b[kb] - d[kb] * b[kb + 1] - e[kb] * b[kb + 2]) / c[kb];
}
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.4628044034,
"avg_line_length": 23,
"ext": "c",
"hexsha": "802eaddffd62501e97cb4b79b35b666491a29548",
"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/integration/qmomof.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/integration/qmomof.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/integration/qmomof.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": 3189,
"size": 8993
} |
/* err/env.c
*
* Copyright (C) 2001, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#define STR_EQ(x,y) (strcmp((x),(y)) == 0)
void
gsl_err_env_setup (void)
{
const char * p = getenv("GSL_ERROR_MODE") ;
if (p == 0) /* GSL_ERROR_MODE environment variable is not set */
return ;
if (*p == '\0') /* GSL_ERROR_MODE environment variable is empty */
return ;
printf("GSL_ERROR_MODE=\"") ;
if (STR_EQ(p, "abort"))
{
gsl_set_error_handler (NULL);
printf("abort") ;
}
printf("\"\n") ;
}
| {
"alphanum_fraction": 0.6774193548,
"avg_line_length": 25.0384615385,
"ext": "c",
"hexsha": "f1b4203e8e0a8d066f15decf939f822cf871f62f",
"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/err/env.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/err/env.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/err/env.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": 340,
"size": 1302
} |
/* multiroots/fdfsolver.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_multiroots.h>
gsl_multiroot_fdfsolver *
gsl_multiroot_fdfsolver_alloc (const gsl_multiroot_fdfsolver_type * T,
size_t n)
{
int status;
gsl_multiroot_fdfsolver * s;
s = (gsl_multiroot_fdfsolver *) malloc (sizeof (gsl_multiroot_fdfsolver));
if (s == 0)
{
GSL_ERROR_VAL ("failed to allocate space for multiroot solver struct",
GSL_ENOMEM, 0);
}
s->x = gsl_vector_calloc (n);
if (s->x == 0)
{
free (s);
GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
}
s->f = gsl_vector_calloc (n);
if (s->f == 0)
{
gsl_vector_free (s->x);
free (s);
GSL_ERROR_VAL ("failed to allocate space for f", GSL_ENOMEM, 0);
}
s->J = gsl_matrix_calloc (n,n);
if (s->J == 0)
{
gsl_vector_free (s->x);
gsl_vector_free (s->f);
free (s);
GSL_ERROR_VAL ("failed to allocate space for g", GSL_ENOMEM, 0);
}
s->dx = gsl_vector_calloc (n);
if (s->dx == 0)
{
gsl_matrix_free (s->J);
gsl_vector_free (s->x);
gsl_vector_free (s->f);
free (s);
GSL_ERROR_VAL ("failed to allocate space for dx", GSL_ENOMEM, 0);
}
s->state = malloc (T->size);
if (s->state == 0)
{
gsl_vector_free (s->dx);
gsl_vector_free (s->x);
gsl_vector_free (s->f);
gsl_matrix_free (s->J);
free (s); /* exception in constructor, avoid memory leak */
GSL_ERROR_VAL ("failed to allocate space for multiroot solver state",
GSL_ENOMEM, 0);
}
s->type = T ;
status = (s->type->alloc)(s->state, n);
if (status != GSL_SUCCESS)
{
free (s->state);
gsl_vector_free (s->dx);
gsl_vector_free (s->x);
gsl_vector_free (s->f);
gsl_matrix_free (s->J);
free (s); /* exception in constructor, avoid memory leak */
GSL_ERROR_VAL ("failed to set solver", status, 0);
}
s->fdf = NULL;
return s;
}
int
gsl_multiroot_fdfsolver_set (gsl_multiroot_fdfsolver * s,
gsl_multiroot_function_fdf * f,
const gsl_vector * x)
{
if (s->x->size != f->n)
{
GSL_ERROR ("function incompatible with solver size", GSL_EBADLEN);
}
if (x->size != f->n)
{
GSL_ERROR ("vector length not compatible with function", GSL_EBADLEN);
}
s->fdf = f;
gsl_vector_memcpy(s->x,x);
return (s->type->set) (s->state, s->fdf, s->x, s->f, s->J, s->dx);
}
int
gsl_multiroot_fdfsolver_iterate (gsl_multiroot_fdfsolver * s)
{
return (s->type->iterate) (s->state, s->fdf, s->x, s->f, s->J, s->dx);
}
void
gsl_multiroot_fdfsolver_free (gsl_multiroot_fdfsolver * s)
{
RETURN_IF_NULL (s);
(s->type->free) (s->state);
free (s->state);
gsl_vector_free (s->dx);
gsl_vector_free (s->x);
gsl_vector_free (s->f);
gsl_matrix_free (s->J);
free (s);
}
const char *
gsl_multiroot_fdfsolver_name (const gsl_multiroot_fdfsolver * s)
{
return s->type->name;
}
gsl_vector *
gsl_multiroot_fdfsolver_root (const gsl_multiroot_fdfsolver * s)
{
return s->x;
}
gsl_vector *
gsl_multiroot_fdfsolver_dx (const gsl_multiroot_fdfsolver * s)
{
return s->dx;
}
gsl_vector *
gsl_multiroot_fdfsolver_f (const gsl_multiroot_fdfsolver * s)
{
return s->f;
}
| {
"alphanum_fraction": 0.6193367585,
"avg_line_length": 24.0561797753,
"ext": "c",
"hexsha": "82db3b46289fbd834ed708027af855f28e09e0c9",
"lang": "C",
"max_forks_count": 173,
"max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z",
"max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_forks_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_forks_repo_name": "juandesant/astrometry.net",
"max_forks_repo_path": "gsl-an/multiroots/fdfsolver.c",
"max_issues_count": 208,
"max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z",
"max_issues_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_issues_repo_name": "juandesant/astrometry.net",
"max_issues_repo_path": "gsl-an/multiroots/fdfsolver.c",
"max_line_length": 81,
"max_stars_count": 460,
"max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630",
"max_stars_repo_licenses": [
"Net-SNMP",
"Xnet"
],
"max_stars_repo_name": "juandesant/astrometry.net",
"max_stars_repo_path": "gsl-an/multiroots/fdfsolver.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z",
"num_tokens": 1266,
"size": 4282
} |
#pragma once
#include "schedule.h"
#include <gsl/gsl-lite.hpp>
#include <range/v3/view/span.hpp>
#include <vector>
namespace angonoka {
struct Configuration;
} // namespace angonoka
namespace angonoka::stun {
using ranges::span;
/**
Cache-friendly container of views into an array of ints.
*/
class Vector2D {
public:
/**
Default constructor.
*/
Vector2D() noexcept;
/**
Constructor.
@param data Array of ints
@param spans Array of spans
*/
Vector2D(
std::vector<int16>&& data,
std::vector<span<int16>>&& spans) noexcept;
/**
Construct from an array of span sizes.
@param data Array of ints
@param sizes Array of span sizes
*/
Vector2D(
std::vector<int16>&& data,
span<const int16> sizes) noexcept;
Vector2D(const Vector2D& other);
Vector2D& operator=(const Vector2D& other);
Vector2D(Vector2D&& other) noexcept;
Vector2D& operator=(Vector2D&& other) noexcept;
~Vector2D() noexcept;
/**
Get a span by index.
@param index Span index
@return A span of ints.
*/
template <typename T> decltype(auto) operator[](T&& index) const
{
Expects(!spans.empty());
return spans[std::forward<T>(index)];
}
/**
Clear the contents of the container.
*/
void clear() noexcept;
/**
Get size of the container.
@return Size of the container.
*/
[[nodiscard]] std::size_t size() const noexcept;
/**
Check if the container is empty.
@return True if the container is empty.
*/
[[nodiscard]] bool empty() const noexcept;
private:
std::vector<int16> data;
std::vector<span<int16>> spans;
};
/**
General, read-only information about the schedule.
@var agent_performance Agent's speed multipliers
@var task_duration Task durations in seconds
@var available_agents Which agents can perform each task
@var dependencies Task's dependent sub-tasks
@var duration_multiplier Multiply the makespan by this value
to get the duration in seconds
*/
struct ScheduleParams {
std::vector<float> agent_performance;
std::vector<float> task_duration;
Vector2D available_agents;
Vector2D dependencies;
float duration_multiplier;
};
/**
Construct a valid but naive schedule.
@param ScheduleParams An instance of ScheduleParams
@return A valid schedule
*/
std::vector<ScheduleItem>
initial_schedule(const ScheduleParams& params);
/**
Construct ScheduleParams from Configuration.
@param config An instance of Configuration
@return ScheduleParams
*/
ScheduleParams to_schedule_params(const Configuration& config);
} // namespace angonoka::stun
| {
"alphanum_fraction": 0.6369359916,
"avg_line_length": 22.872,
"ext": "h",
"hexsha": "4acef294b32dd86ca7853ece99c99ae9150a2cb7",
"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": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "coffee-lord/angonoka",
"max_forks_repo_path": "src/stun/schedule_params.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "coffee-lord/angonoka",
"max_issues_repo_path": "src/stun/schedule_params.h",
"max_line_length": 68,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "coffee-lord/angonoka",
"max_stars_repo_path": "src/stun/schedule_params.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z",
"num_tokens": 644,
"size": 2859
} |
/* FacSexNe.c
Simulation of tracking neutral mutation under facultative sex
To calculate Ne under different scenarios
Code based on that used in Agrawal and Hartfield 2016 (https://github.com/MattHartfield/BalSelSims).
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.
Run by executing:
./FacSexNe N sex gc reps
Where:
- N is the population size
- sex is the frequency of sex (a value between 0 = obligate asex, and 1 = obligate sex)
- gc is the frequency of mitotic gene conversion
- reps is how many times to introduce linked neutral allele
*/
/* Preprocessor statements */
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <stddef.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* Function prototypes */
void neutinit(double *geninit, unsigned int N);
void reproduction(double *geninit, double sex);
void gconv(double *geninit, double gc);
double ncheck(double *geninit);
/* Main program */
int main(int argc, char *argv[]){
unsigned int N = 0; /* Population size */
unsigned int g, i; /* Counters. Reps counter, geno counter */
unsigned int reps = 0; /* Length of simulation (no. of introductions of neutral site) */
double sex = 0; /* Frequency of sexual reproduction */
double gc = 0; /* Frequency of gene conversion */
double Acheck = 0; /* Frequency of derived neutral allele (A) after each reproduction */
double Hsum = 0; /* Summed heterozygosity over transit time of neutral allele */
char Hout[128]; /* String to hold filename in */
FILE *ofp_hs = NULL; /* Pointer for results output */
/* GSL random number definitions */
const gsl_rng_type * T;
gsl_rng * r;
/* This reads in data from command line. */
if(argc != 5){
fprintf(stderr,"Invalid number of input values.\n");
exit(1);
}
N = atoi(argv[1]);
sex = strtod(argv[2],NULL);
gc = strtod(argv[3],NULL);
reps = strtod(argv[4],NULL);
/* Arrays definition and memory assignment */
double *genotype = calloc(3,sizeof(double)); /* Genotype frequencies */
unsigned int *gensamp = calloc(3,sizeof(unsigned int)); /* New population samples */
/* 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);
/* Setting up neutral genotype */
neutinit(genotype,N);
/* Reintroducing neutral genotype, resetting hap sum */
Acheck = ncheck(genotype);
Hsum = Acheck*(1.0-Acheck);
/* Introduce and track neutral mutations 'reps' times */
g = 0;
while(g < reps){
/* Reproduction routine */
reproduction(genotype,sex);
/* Gene conversion routine */
gconv(genotype,gc);
/* Sampling based on new frequencies */
gsl_ran_multinomial(r,3,N,genotype,gensamp);
for(i = 0; i < 3; i++){
*(genotype + i) = (*(gensamp + i))/(1.0*N);
}
/* Checking state of haplotypes: if A fixed reset so can start fresh next time */
Acheck = ncheck(genotype);
Hsum += Acheck*(1.0-Acheck);
if(Acheck == 0 || Acheck == 1){
sprintf(Hout,"/scratch/mhartfield/CC_FSC_Ne/temp_s%.8lf_gc%.8lf.out",sex,gc);
if(g != 0){
ofp_hs = fopen(Hout,"a");
}else if(g == 0){
ofp_hs = fopen(Hout,"w");
}
fprintf(ofp_hs,"%.10lf\n",Hsum);
fclose(ofp_hs);
g++;
/* Reintroducing neutral genotype, resetting hap sum */
neutinit(genotype,N);
Acheck = ncheck(genotype);
Hsum = Acheck*(1-Acheck);
}
} /* End of simulation */
/* Freeing memory and wrapping up */
gsl_rng_free(r);
free(gensamp);
free(genotype);
return 0;
}
/* Setting up neutral polymorphism routine */
void neutinit(double *geninit, unsigned int N){
*(geninit + 0) = 1 - 1/(1.0*N);
*(geninit + 1) = 1/(1.0*N);
*(geninit + 2) = 0;
} /* End of neutral setup routine */
/* Reproduction routine */
void reproduction(double *geninit, double sex){
/* Fed-in genotype frequencies (for ease of programming) */
double gaas, gAas, gAAs;
/* Genotype frequencies after sex */
double gaaSX, gAaSX, gAASX;
/* Genotype frequencies after asex */
double gaaAS, gAaAS, gAAAS;
/* Initial definition of genotypes */
gaas = *(geninit + 0);
gAas = *(geninit + 1);
gAAs = *(geninit + 2);
/* Change in frequencies due to sex */
gaaSX = sex*(gaas + gAas/2.0)*(gaas + gAas/2.0);
gAaSX = sex*2.0*(gaas + gAas/2.0)*(gAAs + gAas/2.0);
gAASX = sex*(gAAs + gAas/2.0)*(gAAs + gAas/2.0);
/* Change in frequencies due to asex */
gaaAS = gaas*(1 - sex);
gAaAS = gAas*(1 - sex);
gAAAS = gAAs*(1 - sex);
/* Combining to give overall frequency change following reproduction */
*(geninit + 0) = gaaAS + gaaSX;
*(geninit + 1) = gAaAS + gAaSX;
*(geninit + 2) = gAAAS + gAASX;
} /* End of reproduction routine */
/* Gene conversion routine */
void gconv(double *geninit, double gc){
/* Fed-in genotype frequencies (for ease of programming) */
double gaar, gAar, gAAr;
/* Frequencies after gene conversion */
double gaagc, gAagc, gAAgc;
/* Initial definition of genotypes */
gaar = *(geninit + 0);
gAar = *(geninit + 1);
gAAr = *(geninit + 2);
/* Gene conversion equations */
gaagc = gaar + gAar*gc/2.0;
gAagc = gAar*(1.0-gc);
gAAgc = gAAr + gAar*gc/2.0;
/* Output */
*(geninit + 0) = gaagc;
*(geninit + 1) = gAagc;
*(geninit + 2) = gAAgc;
} /* End of gene conversion routine */
/* Has neutral allele fixed or not? Measuring its frequency */
double ncheck(double *geninit){
/* Fed-in genotype frequencies (for ease of programming) */
double gAas, gAAs;
double Atot = 0.0; /* Total frequency of A */
/* Initial definition of genotypes */
gAas = *(geninit + 1);
gAAs = *(geninit + 2);
/* Checking frequency of A */
Atot = gAAs + gAas/2.0;
return Atot;
} /* End of neutral check routine */
/* End of program */
| {
"alphanum_fraction": 0.6441727791,
"avg_line_length": 29.3540669856,
"ext": "c",
"hexsha": "4f7cac2913c83cd31e8d7c8d5f832b7523bb2d07",
"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": "02d5472f3d913c166c9107e3fe5ace9ea0643a78",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MattHartfield/FacSexNe",
"max_forks_repo_path": "FacSexNe.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "02d5472f3d913c166c9107e3fe5ace9ea0643a78",
"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/FacSexNe",
"max_issues_repo_path": "FacSexNe.c",
"max_line_length": 100,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "02d5472f3d913c166c9107e3fe5ace9ea0643a78",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MattHartfield/FacSexNe",
"max_stars_repo_path": "FacSexNe.c",
"max_stars_repo_stars_event_max_datetime": "2019-12-13T14:50:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-22T15:58:03.000Z",
"num_tokens": 1857,
"size": 6135
} |
/* sum/gsl_sum.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#ifndef __GSL_SUM_H__
#define __GSL_SUM_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Workspace for Levin U Transform with error estimation,
*
* size = number of terms the workspace can handle
* sum_plain = simple sum of series
* q_num = backward diagonal of numerator; length = size
* q_den = backward diagonal of denominator; length = size
* dq_num = table of numerator derivatives; length = size**2
* dq_den = table of denominator derivatives; length = size**2
* dsum = derivative of sum wrt term i; length = size
*/
typedef struct
{
size_t size;
size_t i; /* position in array */
size_t terms_used; /* number of calls */
double sum_plain;
double *q_num;
double *q_den;
double *dq_num;
double *dq_den;
double *dsum;
}
gsl_sum_levin_u_workspace;
GSL_EXPORT gsl_sum_levin_u_workspace *gsl_sum_levin_u_alloc (size_t n);
GSL_EXPORT void gsl_sum_levin_u_free (gsl_sum_levin_u_workspace * w);
/* Basic Levin-u acceleration method.
*
* array = array of series elements
* n = size of array
* sum_accel = result of summation acceleration
* err = estimated error
*
* See [Fessler et al., ACM TOMS 9, 346 (1983) and TOMS-602]
*/
GSL_EXPORT int gsl_sum_levin_u_accel (const double *array,
const size_t n,
gsl_sum_levin_u_workspace * w,
double *sum_accel, double *abserr);
/* Basic Levin-u acceleration method with constraints on the terms
* used,
*
* array = array of series elements
* n = size of array
* min_terms = minimum number of terms to sum
* max_terms = maximum number of terms to sum
* sum_accel = result of summation acceleration
* err = estimated error
*
* See [Fessler et al., ACM TOMS 9, 346 (1983) and TOMS-602]
*/
GSL_EXPORT int gsl_sum_levin_u_minmax (const double *array,
const size_t n,
const size_t min_terms,
const size_t max_terms,
gsl_sum_levin_u_workspace * w,
double *sum_accel, double *abserr);
/* Basic Levin-u step w/o reference to the array of terms.
* We only need to specify the value of the current term
* to execute the step. See TOMS-745.
*
* sum = t0 + ... + t_{n-1} + term; term = t_{n}
*
* term = value of the series term to be added
* n = position of term in series (starting from 0)
* sum_accel = result of summation acceleration
* sum_plain = simple sum of series
*/
GSL_EXPORT
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);
/* The following functions perform the same calculation without
estimating the errors. They require O(N) storage instead of O(N^2).
This may be useful for summing many similar series where the size
of the error has already been estimated reliably and is not
expected to change. */
typedef struct
{
size_t size;
size_t i; /* position in array */
size_t terms_used; /* number of calls */
double sum_plain;
double *q_num;
double *q_den;
double *dsum;
}
gsl_sum_levin_utrunc_workspace;
GSL_EXPORT gsl_sum_levin_utrunc_workspace *gsl_sum_levin_utrunc_alloc (size_t n);
GSL_EXPORT void gsl_sum_levin_utrunc_free (gsl_sum_levin_utrunc_workspace * w);
GSL_EXPORT int gsl_sum_levin_utrunc_accel (const double *array,
const size_t n,
gsl_sum_levin_utrunc_workspace * w,
double *sum_accel, double *abserr_trunc);
GSL_EXPORT int gsl_sum_levin_utrunc_minmax (const double *array,
const size_t n,
const size_t min_terms,
const size_t max_terms,
gsl_sum_levin_utrunc_workspace * w,
double *sum_accel, double *abserr_trunc);
GSL_EXPORT int gsl_sum_levin_utrunc_step (const double term,
const size_t n,
gsl_sum_levin_utrunc_workspace * w,
double *sum_accel);
__END_DECLS
#endif /* __GSL_SUM_H__ */
| {
"alphanum_fraction": 0.6041415013,
"avg_line_length": 35.1212121212,
"ext": "h",
"hexsha": "187192a095f7a5396aa3ef346a1fd6069338405d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "dynaryu/vaws",
"max_forks_repo_path": "src/core/gsl/include/gsl/gsl_sum.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "dynaryu/vaws",
"max_issues_repo_path": "src/core/gsl/include/gsl/gsl_sum.h",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "dynaryu/vaws",
"max_stars_repo_path": "src/core/gsl/include/gsl/gsl_sum.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1354,
"size": 5795
} |
/* randist/bernoulli.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* The bernoulli distribution has the form,
prob(0) = 1-p, prob(1) = p
*/
unsigned int
gsl_ran_bernoulli (const gsl_rng * r, double p)
{
double u = gsl_rng_uniform (r) ;
if (u < p)
{
return 1 ;
}
else
{
return 0 ;
}
}
double
gsl_ran_bernoulli_pdf (const unsigned int k, double p)
{
if (k == 0)
{
return 1 - p ;
}
else if (k == 1)
{
return p ;
}
else
{
return 0 ;
}
}
| {
"alphanum_fraction": 0.6563400576,
"avg_line_length": 22.3870967742,
"ext": "c",
"hexsha": "c10f5a49ae343d9ecdfb607da32a74873e2ede27",
"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/randist/bernoulli.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/randist/bernoulli.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/randist/bernoulli.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": 404,
"size": 1388
} |
#pragma once
#include <exception>
#include <iostream>
#include <cstdlib>
#include <functional>
#include <memory>
#include <vector>
#include <gsl/gsl>
#define VK_USE_PLATFORM_WIN32_KHR
#include <vulkan/vulkan.h>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#define GLFW_EXPOSE_NATIVE_WIN32
#include <GLFW/glfw3native.h>
#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif
/*
We define this in case we want to use VulkanMemoryAllocator's
allocators.
- https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator
Currently we are using the allocator by default so allocation of
buffers and images without VMA_USE_ALLOCATOR could not be fully supported.
*/
#define VMA_USE_ALLOCATOR
#include "../utils/Utils.h"
#include "./RenderUtils.h"
#include "../Configuration.h"
#include "RenderData.h"
/**
Used for managing all the rendering logic of the application.
Manages creation, destruction and use of all the resources necessary
to render to the screen using the Vulkan API.
*/
class Renderer
{
private:
using WindowPtr = std::unique_ptr<GLFWwindow, GLFWWindowDestroyer>;
public:
/**
Default Constructor.
Since we tie a lot of the resources to this instance and we need to
manage them only from here the copy and move functionalities are not allowed.
*/
[[gsl::suppress(26439)]] Renderer();
Renderer(const Renderer&) = delete;
Renderer& operator=(const Renderer&) = delete;
Renderer(Renderer&&) = delete;
Renderer& operator=(Renderer&&) = delete;
~Renderer();
/* --------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------- PUBLIC FUNCTION MEMBERS ---------------------------------------- */
/* --------------------------------------------------------------------------------------------------------- */
/**
Updates the uniform buffer for the object being rendered
@TODO: Reformat this function out of the renderer.
@see m_uniform_buffer
*/
auto updateRotateTestUniformBuffer() ->void;
/**
Sets up the beggining of a frame. Setting up the recording of a
one time command buffer to submit to the rendering queue.
*/
auto beginFrame() -> void;
/**
Finishes the rendering stages and submits all the necessary information
to the graphics card for rendering.
*/
auto endFrame() -> void;
/**
Returns true when we should close the application as far as the render manager
is concerned. Currently it deals with the user closing the window itself.
@return true if the window has been closed or we should end the application.
*/
auto shouldClose() const noexcept -> bool;
private:
/* ---------------------------------------------------------------------------------------------------------- */
/* ---------------------------------------- PRIVATE FUNCTION MEMBERS ---------------------------------------- */
/* ---------------------------------------------------------------------------------------------------------- */
/**
Initializes the physical window shown by the operating system
@see m_window
*/
auto initWindow() noexcept -> void;
/**
Initializes all the Vulkan related components necessary for rendering to
the screen.
*/
auto initVulkan() -> void;
/**
Recreates all the necessary members to create a new swap chain, for example
when resizing the window.
*/
auto recreateSwapChain() -> void;
/**
Cleans up all the resources that need to be explicitly cleaned up,
mostly related to the Vulkan API and its resources.
*/
auto cleanup() noexcept -> void;
/**
Cleans up all the resources related to the swap chain, this is useful when
recreating the swap chain to be sure we are not leaking memory and resources.
*/
auto cleanupSwapChain() noexcept -> void;
/**
Creates a Vulkan instance based on the current configuration parameters.
@see m_instance
@return A Valid Vulkan Instance
*/
auto createInstance()->VkInstance;
/**
Prints to standard output all the extension names of all the extensions provided.
@param a vector with the extensions you would like to print
*/
auto printInstanceExtensions(const std::vector<VkExtensionProperties>& extensions)
const -> void;
/**
Checks and prints if all the required extensions provided are available within the available ones.
@param The vector of the names of the required extensions
@param The vector of the struct with the properties of the available extensions
@return true if all the required extensions are within the available ones, false otherwise.
*/
[[gsl::suppress(bounds.3)]] auto checkInstanceExtensionsNamesAvailable(
const std::vector<const char*>& required_extensions,
const std::vector<VkExtensionProperties>& available_extensions)
const -> bool;
/**
Checks and prints if all the required validation layers in the conficuration are available.
@return true if all the required validation layers are within the available ones, false otherwise.
*/
[[gsl::suppress(bounds.3)]] auto checkValidationLayerSupport() const noexcept -> bool;
/**
Calculates and returns the necessary Vulkan extensions for this application based
on configuration.
@return A vector with the names of the required extensions
*/
auto getRequiredExtensions() const noexcept->std::vector<const char*>;
/**
Callback function called to receive messages from the validation layers when
enabled (in debug mode).
It follows the parameters of the vulkan PFN_vkDebugReportCallbackEXT function
@see PFN_vkDebugReportCallbackEXT
@return VK_FALSE to indicate that the Vulkan call should NOT be aborted.
*/
#pragma warning( push )
#pragma warning( disable : 4229)
auto static VKAPI_ATTR VKAPI_CALL debugReportCallback(
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT object_type,
uint64_t object,
size_t location,
int32_t msg_code,
const char* layer_prefix,
const char* msg,
void* user_data
)->VkBool32;
#pragma warning( pop )
/**
Sets up the callback function to receive debug information from
the debug report validation layer.
@see debugReportCallback
@see m_debug_callback
*/
auto setupDebugCallback() -> void;
/**
Creates the window surface to which we will render to.
@see m_surface
*/
auto createSurface() -> void;
/**
Interface to the vulkan function "vkCreateDebugReportCallbackEXT" to create
the debug function callback.
@see vkCreateDebugReportCallbackEXT
@return the result of vkCreateDebugReportCallbackEXT or VK_ERROR_EXTENSION_NOT_PRESENT if
we can't find the function pointer.
*/
auto createDebugReportCallbackEXT(
const VkInstance& instance,
const VkDebugReportCallbackCreateInfoEXT * create_info,
const VkAllocationCallbacks* allocator,
VkDebugReportCallbackEXT* callback
) noexcept->VkResult;
/**
Interface to the vulkan function "vkDestroyDebugReportCallbackEXT" to destroy
the debug function callback.
@see vkDestroyDebugReportCallbackEXT
*/
auto destroyDebugReportCallbackEXT(
const VkInstance& instance,
const VkDebugReportCallbackEXT& callback,
const VkAllocationCallbacks* allocator
) noexcept -> void;
/**
Iterates and picks the most suitable physical device
available on the system for this application.
@see m_physical_device
@see m_physical_device_properties
@see m_physical_device_features
*/
auto pickPhysicalDevice() -> void;
/**
Checks if the physical device is suitable for the application
and gives it a score based on how suitable it is based on configuration.
@param the physical device to rate
@return a tuple with a bool representing that is true when the device is valid
and an int representing the score, the higher the better.
*/
auto physicalDeviceSuitability(
const VkPhysicalDevice& device
) const noexcept->std::tuple<bool, int>;
/**
Checks the queue families supported by the provided device and returns the indices for the
required ones in the struct QueueFamilyIndices (graphics and present queues right now).
@see QueueFamilyIndices
@see m_queue_family_indices
@see PrintOptions
@param The physical device to retrieve the queue families from
@param The print options for the function to indicate the output desired to standard output
@return The struct with the family queue indices required or -1 if they haven't been found
*/
auto findQueueFamilies(
const VkPhysicalDevice& physical_device,
PrintOptions print_options
) const->QueueFamilyIndices;
/**
Creates the vulkan logical device we are going to use and retrieves the graphics and present
queues from it.
@see m_device
@see m_graphics_queue
@see m_present_queue
*/
auto createLogicalDevice() -> void;
/**
Creates the allocator used to reserve memory in vulkan
@see m_vma_allocator
*/
auto createAllocator() noexcept ->void;
/**
Checks if the physical device provided supports all the extensions required by our configuration
@param The physical device to check for extension support
@return true if all the extensions are supported, false otherwise
*/
[[gsl::suppress(bounds.3)]]
auto checkDeviceExtensionSupport(
const VkPhysicalDevice& device
) const -> bool;
/**
Checks and retrieves information about the swap chain capabilities of a physical device.
Fills up said information in the SwapChainSupportDetails struct
@see SwapChainSupportDetails
@param The physical device to check for swap chain support
@return A SwapChainSupportDetails filled with swap chain support information
*/
auto querySwapChainSupport(
const VkPhysicalDevice& device
) const->SwapChainSupportDetails;
/**
Checks and returns the best available surface chain format from the provided ones
prioritizing the ones that fit us best.
@param A vector with the surface formats to check
@return The best surface format for our application
*/
auto pickSurfaceChainFormat(
const std::vector<VkSurfaceFormatKHR>& available_formats
) const->VkSurfaceFormatKHR;
/**
Checks and returns the best available present mode from the provided ones
prioritizing the ones that fit us best.
@param A vector with the present modes to check
@return The best present mode for our application
*/
auto pickSurfacePresentMode(
const std::vector<VkPresentModeKHR>& available_modes
) const noexcept->VkPresentModeKHR;
/**
Checks and returns the best available extent for the images in the
swap chain based on its capabilities.
@param The capabilities of the surface
@return The best possible extent (width, height) for our application
*/
auto pickSwapExtent(
const VkSurfaceCapabilitiesKHR& capabilities
) const noexcept->VkExtent2D;
/**
Creates the vulkan swap chain required for rendering.
Prioritizes a triple buffering implementation if possible.
@see m_swap_chain
*/
auto createSwapChain() -> void;
/**
Creates an image view for each image in the swap chain so
we can use them as color targets later.
@see m_swap_chain_image_views
*/
auto createSwapChainImageViews() -> void;
/**
Creates the render pass that will be used to then create
the graphics pipeline.
@see m_render_pass
*/
auto createRenderPass() -> void;
/**
Creates the descriptor set layout that we will set in
the pipeline.
@see m_descriptor_set_layout;
*/
auto createDescriptorSetLayout() -> void;
/**
Creates the graphics pipeline (or pipelines) that will be used to render
our scene.
@see m_pipeline_layout
@see m_pipeline
*/
auto createGraphicsPipeline() -> void;
/**
Creates a shader module based on the code provided and wraps it up
in the VkShaderModule struct
@see VkShaderModule
@param An array of characters with the code for the shader
@return The shader module created based on the shader code
*/
auto createShaderModule(const std::vector<char>& code) const->VkShaderModule;
/**
Creates the framebuffersto draw to during render time
@see m_swap_chain_framebuffers
*/
auto createFramebuffers() -> void;
/**
Creates the command pool that contains the command buffers to
draw to during render time.
@see m_graphics_command_pool
*/
auto createGraphicsCommandPool() -> void;
/**
Creates the command pool that contains the command buffers to
execute transfer memory commands.
@see m_transfer_command_pool
*/
auto createTransferCommandPool() -> void;
/**
Helper function that creates a vulkan image in a general way
@param Width of the image
@param Height of the image
@param Vulkan Format of the image
@param Tiling Options for the image
@param Usage flags that the image will need
@param Usage type for allocation
@param Flags necessary for allocation
@param The image to be populated
@param The sharing mode for the image (Concurrent or exclusive)
@param The family indices when sharing mode is concurrent (or nullptr otherwise)
@param The sample count for the image, 1 sample by default (used on images meant for multisampling)
*/
auto createImage(
uint width,
uint height,
VkFormat format,
VkImageTiling tiling,
VkImageUsageFlags flags,
VmaMemoryUsage allocation_usage,
VmaAllocationCreateFlags allocation_flags,
AllocatedImage& image,
VkSharingMode sharing_mode,
const std::vector<uint>* queue_family_indices,
short samples = 1
) -> void;
/**
Destroys the image provided and frees its memory
@param The image to destroy
*/
auto destroyImage(AllocatedImage& image) noexcept -> void;
/**
Creates the necessary resources for the implementation
of a depth buffer
@ m_depth_image
@ m_depth_image_view
*/
auto createDepthResources() -> void;
/**
Creates a texture image with the data loaded from a file
@param the path of th texture
@return The allocated image with the texture
*/
auto createTextureImage(std::string path) -> AllocatedImage;
/**
Creates a texture image view into the texture image
@param The image to create the view from
@return An image view for the provided image.
*/
auto createTextureImageView(AllocatedImage image) -> VkImageView;
/**
Loads the scene with the provided object (.obj) and texture paths
@param The path to the .obj model
@param The path to the texture for the model
@see m_scene
*/
auto loadScene(std::string object_path, std::string texture_path) -> void;
/**
Creates a sampler to sample the textures
used in the rendering phase.
@see m_texture_sampler
*/
auto createTextureSampler() -> void;
/**
Helper function that creates a vulkan buffer in a general way.
@param The size of the memory to be allocated
@param The usage flags necessary for the memory we are allocating
@param The allocation usage that the buffer will have
@param The flags for the allocator to use during creating of the buffer.
@param The handle to the buffer to create
@param The sharing mode of the buffer (VK_SHARING_MODE_(EXCLUSIVE/CONCURRENT))
@param The family indices of the queues this buffer will be shared between if CONCURRENT, nullptr otherwise
*/
auto createBuffer(
VkDeviceSize size,
VkBufferUsageFlags usage,
#ifdef VMA_USE_ALLOCATOR
VmaMemoryUsage allocation_usage,
VmaAllocationCreateFlags allocation_flags,
#else
VkMemoryPropertyFlags properties,
#endif
AllocatedBuffer& allocated_buffer,
VkSharingMode sharing_mode,
const std::vector<uint>* queue_family_indices
) -> void;
/**
Destroys the buffer provided and frees its memory
@param The Buffer to destroy
*/
auto destroyBuffer(
AllocatedBuffer& allocated_buffer
) noexcept -> void;
/**
Creates the vertex buffer that will hold the vertices to render.
@see m_vertex_buffer
*/
auto createVertexBuffer() -> void;
/**
Creates the index buffer that will hold the indexes in order to render.
@see m_index_buffer
*/
auto createIndexBuffer() -> void;
/**
Creates the uniform buffer that will hold the object data to render.
@see m_uniform_buffer
*/
auto createUniformBuffer() -> void;
/**
Creates the descriptor pool that will hold the descriptors sets that will
be used during rendering.
@see m_descriptor_pool
*/
auto createDescriptorPool() -> void;
/**
Creates the descriptor set that will hold the descriptors
used during rendering.
@see m_descriptor_set
*/
auto createDescriptorSet() -> void;
/**
Helper function that finds the appropriate format for a depth attachment.
@return Format that supports usage as a depth attachment
*/
auto findDepthFormat()->VkFormat;
/**
Checks if a given format has a stencil component in it.
@param The format to check
@return True if it has a stencil component, false otherwise
*/
auto hasStencilComponent(VkFormat format) const noexcept -> bool;
/**
Helper function that finds the post appropriate format for an image given
the desired features and candidates.
@param The possible formats to choose from
@param The tiling options of the image
@param The features desired
@return The most appropriate format
*/
auto findSupportedFormat(
const std::vector<VkFormat>& candidates,
VkImageTiling tiling,
VkFormatFeatureFlags features
)->VkFormat;
/**
Helper function that calculates the required memory types given the input properties.
@param Flags that indicate the types of memories that we can consider
@param Properties of the memory we need
@param A reference to a boolean that will indicate if we have found an appropriate type
@return Appropriate flags of the memory we can use.
*/
auto findMemoryType(
uint type_filter,
VkMemoryPropertyFlags properties,
VkBool32 *found = nullptr
)->uint;
/**
Copies the contents from one VkBuffer to another.
@param The source buffer
@param The destination buffer
@param The size of the memory to be copied
*/
auto copyBuffer(
VkBuffer src,
VkBuffer dst,
VkDeviceSize size
) noexcept -> void;
/**
Creates the command buffers that contain the commands to
draw to during render time.
@see m_command_buffers
*/
auto createCommandBuffers() -> void;
/**
Creates the drawing commands into the command buffers
@see m_command_buffers
*/
auto recordCommandBuffers() -> void;
/**
Creates the semaphores and fences necessary for synchronization of
the rendering phase.
@see m_image_available_semaphores
@see m_render_finished_semaphores
@see m_command_buffer_fences
*/
auto createSemaphoresAndFences() -> void;
/**
Handles the event of resizing the window to set up the appropriate
rendering parameters accordingly.
@param Reference to the window that has been resized
@param New width of the window
@param New height of the window
*/
auto static onWindowsResized(
GLFWwindow * window,
int width,
int heigth) -> void;
/**
Creates a single use command buffer and starts recording to it
@param the type of commands that will be used (graphics also allows transfer)
@return The command buffer we are recording to
*/
auto beginSingleTimeCommands(
CommandType command_type = CommandType::graphics
) noexcept->WrappedCommandBuffer;
/**
End recording to a particulaar command buffer and submits it to the queue
@param The command buffer to submit to the queue
*/
auto endSingleTimeCommands(
WrappedCommandBuffer& command_buffer
) noexcept ->void;
/**
Helper function that changes the image layout to a new one
@param The image to change the layout to
@param The format of the image
@param The old layout of the image
@param The new layout for the image
*/
auto changeImageLayout(
VkImage& image,
VkFormat format,
VkImageLayout old_layout,
VkImageLayout new_layout)->void;
/**
Helper function that copies a buffer with image data into
a vulkan image structure.
@param The buffer to read the data from
@param The image to write de data into
@param Width of the image
@param Height of the image
*/
auto copyBufferToImage(
VkBuffer buffer,
VkImage image,
uint width,
uint heigth) noexcept -> void;
/**
Helped function that creates an image view to the
provided image.
@param The image to create a view from
@param The format of the view
@param The aspect mast to create the image view regarding its use
@return An image view into the provided image
*/
auto createImageView(
VkImage image,
VkFormat format,
VkImageAspectFlags aspect_flags
)->VkImageView;
/**
Helper function that calculates the required flags to
set up an especific amount of samples.
@param The number of samples required (power of 2 up to 64)
@return The required vulkan flag for the number of samples
*/
auto getSampleBits(short samples)->VkSampleCountFlagBits;
/**
Creates a render target for multisampling. This includes, the image,
its memory and a view to it.
@param Width of the render target
@param Height of the render target
@param Desired format of the render target
@param The usage flags for the render target
@param The aspect flags for the image view of the render target
@return The render target struct with all the relevant info
*/
auto createMultisampleRenderTarget(
uint width,
uint height,
VkFormat format,
VkImageUsageFlags usage,
VkImageAspectFlags aspect_mask)->WrappedRenderTarget;
/* ---------------------------------------------------------------------------------------------- */
/* ---------------------------------------- DATA MEMBERS ---------------------------------------- */
/* ---------------------------------------------------------------------------------------------- */
RenderConfiguration config{};
#ifdef VMA_USE_ALLOCATOR
VmaAllocator m_vma_allocator{};
#endif
WindowPtr m_window{};
VkInstance m_instance{};
VkDebugReportCallbackEXT m_debug_callback{};
VkSurfaceKHR m_surface{};
QueueFamilyIndices m_queue_family_indices{};
VkPhysicalDevice m_physical_device = VK_NULL_HANDLE;
VkPhysicalDeviceProperties m_physical_device_properties{};
VkPhysicalDeviceFeatures m_physical_device_features{};
VkDevice m_device{};
VkQueue m_graphics_queue{};
VkQueue m_present_queue{};
VkQueue m_transfer_queue{};
WrappedRenderTarget m_render_target{};
WrappedRenderTarget m_depth_target{};
VkFormat m_depth_format{};
VkSwapchainKHR m_swap_chain{};
uint m_current_swapchain_buffer{};
std::vector<VkImage> m_swap_chain_images{};
VkFormat m_swap_chain_image_format{};
VkExtent2D m_swap_chain_extent{};
std::vector<VkImageView> m_swap_chain_image_views{};
VkRenderPass m_render_pass{};
VkPipelineLayout m_pipeline_layout{};
SimpleObjScene m_scene{};
VkDescriptorSetLayout m_descriptor_set_layout{};
VkPipeline m_pipeline{};
std::vector<VkFramebuffer> m_swap_chain_framebuffers{};
VkCommandPool m_graphics_command_pool{};
VkCommandPool m_transfer_command_pool{};
AllocatedBuffer m_vertex_buffer{};
AllocatedBuffer m_index_buffer{};
AllocatedBuffer m_uniform_buffer{};
AllocatedImage m_depth_image{};
VkImageView m_depth_image_view{};
VkSampler m_texture_sampler{};
VkDescriptorPool m_descriptor_pool{};
VkDescriptorSet m_descriptor_set{};
std::vector<VkCommandBuffer> m_command_buffers{};
uint m_current_command_buffer{};
std::vector<bool> m_command_buffer_submitted{};
std::vector<VkSemaphore> m_image_available_semaphores{};
std::vector<VkSemaphore> m_render_finished_semaphores{};
std::vector<VkFence> m_command_buffer_fences{};
};
| {
"alphanum_fraction": 0.7294379712,
"avg_line_length": 26.987283237,
"ext": "h",
"hexsha": "ef4e68b0c8d03afce855feb2684c0defdb461364",
"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": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Jazzzy/VR_ButNotReally",
"max_forks_repo_path": "VR_ButNotReally/src/render/Renderer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414",
"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": "Jazzzy/VR_ButNotReally",
"max_issues_repo_path": "VR_ButNotReally/src/render/Renderer.h",
"max_line_length": 113,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "82e0335ee86cc9cc32d784c4b1b55ab884ae0414",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Jazzzy/VR_ButNotReally",
"max_stars_repo_path": "VR_ButNotReally/src/render/Renderer.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5145,
"size": 23344
} |
#pragma once
#include <gsl\gsl>
#include "Texture.h"
#include "Rectangle.h"
namespace Library
{
class Texture2D final : public Texture
{
RTTI_DECLARATIONS(Texture2D, Texture)
public:
Texture2D(const GLuint textureID, GLuint width, GLuint height);
Texture2D(const Texture2D&) = default;
Texture2D& operator=(const Texture2D&) = default;
Texture2D(Texture2D&&) = default;
Texture2D& operator=(Texture2D&&) = default;
~Texture2D() = default;
static std::shared_ptr<Texture2D> CreateTexture2D(GLuint width, GLuint height, GLint mipLevels = 1, GLenum colorFormat = GL_RGBA16F);
GLuint Width() const;
GLuint Height() const;
Rectangle Bounds() const;
private:
GLuint mWidth;
GLuint mHeight;
};
} | {
"alphanum_fraction": 0.7296551724,
"avg_line_length": 23.3870967742,
"ext": "h",
"hexsha": "b5a65909f1f44387f743ad856cb8fb780cb54ebf",
"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": "628e9aed116022175cc0c59c88ace7688309628c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "DakkyDaWolf/OpenGL",
"max_forks_repo_path": "source/Library.Shared/Texture2D.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c",
"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": "DakkyDaWolf/OpenGL",
"max_issues_repo_path": "source/Library.Shared/Texture2D.h",
"max_line_length": 135,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "DakkyDaWolf/OpenGL",
"max_stars_repo_path": "source/Library.Shared/Texture2D.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 200,
"size": 725
} |
/* linalg/test.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2005, 2006, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_linalg.h>
#define TEST_SVD_4X4 1
int check (double x, double actual, double eps);
gsl_matrix * create_hilbert_matrix(unsigned long size);
gsl_matrix * create_general_matrix(unsigned long size1, unsigned long size2);
gsl_matrix * create_vandermonde_matrix(unsigned long size);
gsl_matrix * create_moler_matrix(unsigned long size);
gsl_matrix * create_row_matrix(unsigned long size1, unsigned long size2);
gsl_matrix * create_2x2_matrix(double a11, double a12, double a21, double a22);
gsl_matrix * create_diagonal_matrix(double a[], unsigned long size);
int test_matmult(void);
int test_matmult_mod(void);
int test_LU_solve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_LU_solve(void);
int test_LUc_solve_dim(const gsl_matrix_complex * m, const double * actual, double eps);
int test_LUc_solve(void);
int test_QR_solve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_QR_solve(void);
int test_QR_QRsolve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_QR_QRsolve(void);
int test_QR_lssolve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_QR_lssolve(void);
int test_QR_decomp_dim(const gsl_matrix * m, double eps);
int test_QR_decomp(void);
int test_QRPT_solve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_QRPT_solve(void);
int test_QRPT_QRsolve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_QRPT_QRsolve(void);
int test_QRPT_decomp_dim(const gsl_matrix * m, double eps);
int test_QRPT_decomp(void);
int test_QR_update_dim(const gsl_matrix * m, double eps);
int test_QR_update(void);
int test_QRPT_update_dim(const gsl_matrix * m, double eps);
int test_QRPT_update(void);
int test_LQ_solve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_LQ_solve(void);
int test_LQ_LQsolve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_LQ_LQsolve(void);
int test_LQ_lssolve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_LQ_lssolve(void);
int test_LQ_decomp_dim(const gsl_matrix * m, double eps);
int test_LQ_decomp(void);
int test_PTLQ_solve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_PTLQ_solve(void);
int test_PTLQ_LQsolve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_PTLQ_LQsolve(void);
int test_PTLQ_decomp_dim(const gsl_matrix * m, double eps);
int test_PTLQ_decomp(void);
int test_LQ_update_dim(const gsl_matrix * m, double eps);
int test_LQ_update(void);
int test_SV_solve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_SV_solve(void);
int test_SV_decomp_dim(const gsl_matrix * m, double eps);
int test_SV_decomp(void);
int test_SV_decomp_mod_dim(const gsl_matrix * m, double eps);
int test_SV_decomp_mod(void);
int test_SV_decomp_jacobi_dim(const gsl_matrix * m, double eps);
int test_SV_decomp_jacobi(void);
int test_cholesky_solve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_cholesky_solve(void);
int test_cholesky_decomp_dim(const gsl_matrix * m, double eps);
int test_cholesky_decomp(void);
int test_cholesky_invert_dim(const gsl_matrix * m, double eps);
int test_cholesky_invert(void);
int test_HH_solve_dim(const gsl_matrix * m, const double * actual, double eps);
int test_HH_solve(void);
int test_TDS_solve_dim(unsigned long dim, double d, double od, const double * actual, double eps);
int test_TDS_solve(void);
int test_TDN_solve_dim(unsigned long dim, double d, double a, double b, const double * actual, double eps);
int test_TDN_solve(void);
int test_TDS_cyc_solve_one(const unsigned long dim, const double * d, const double * od, const double * r,
const double * actual, double eps);
int test_TDS_cyc_solve(void);
int test_TDN_cyc_solve_dim(unsigned long dim, double d, double a, double b, const double * actual, double eps);
int test_TDN_cyc_solve(void);
int test_bidiag_decomp_dim(const gsl_matrix * m, double eps);
int test_bidiag_decomp(void);
int
check (double x, double actual, double eps)
{
if (x == actual)
{
return 0;
}
else if (actual == 0)
{
return fabs(x) > eps;
}
else
{
return (fabs(x - actual)/fabs(actual)) > eps;
}
}
gsl_vector *
vector_alloc (size_t n)
{
size_t p[5] = {3, 5, 7, 11, 13};
static size_t k = 0;
size_t stride = p[k];
k = (k + 1) % 5;
{
gsl_block * b = gsl_block_alloc (n * stride);
gsl_vector * v = gsl_vector_alloc_from_block (b, 0, n, stride);
v->owner = 1;
return v;
}
}
void
vector_free (gsl_vector * v)
{
gsl_vector_free (v);
}
gsl_matrix *
create_hilbert_matrix(unsigned long size)
{
unsigned long i, j;
gsl_matrix * m = gsl_matrix_alloc(size, size);
for(i=0; i<size; i++) {
for(j=0; j<size; j++) {
gsl_matrix_set(m, i, j, 1.0/(i+j+1.0));
}
}
return m;
}
gsl_matrix *
create_general_matrix(unsigned long size1, unsigned long size2)
{
unsigned long i, j;
gsl_matrix * m = gsl_matrix_alloc(size1, size2);
for(i=0; i<size1; i++) {
for(j=0; j<size2; j++) {
gsl_matrix_set(m, i, j, 1.0/(i+j+1.0));
}
}
return m;
}
gsl_matrix *
create_singular_matrix(unsigned long size1, unsigned long size2)
{
unsigned long i, j;
gsl_matrix * m = gsl_matrix_alloc(size1, size2);
for(i=0; i<size1; i++) {
for(j=0; j<size2; j++) {
gsl_matrix_set(m, i, j, 1.0/(i+j+1.0));
}
}
/* zero the first column */
for(j = 0; j <size2; j++)
gsl_matrix_set(m,0,j,0.0);
return m;
}
gsl_matrix *
create_vandermonde_matrix(unsigned long size)
{
unsigned long i, j;
gsl_matrix * m = gsl_matrix_alloc(size, size);
for(i=0; i<size; i++) {
for(j=0; j<size; j++) {
gsl_matrix_set(m, i, j, pow(i + 1.0, size - j - 1.0));
}
}
return m;
}
gsl_matrix *
create_moler_matrix(unsigned long size)
{
unsigned long i, j;
gsl_matrix * m = gsl_matrix_alloc(size, size);
for(i=0; i<size; i++) {
for(j=0; j<size; j++) {
gsl_matrix_set(m, i, j, GSL_MIN(i+1,j+1)-2.0);
}
}
return m;
}
gsl_matrix_complex *
create_complex_matrix(unsigned long size)
{
unsigned long i, j;
gsl_matrix_complex * m = gsl_matrix_complex_alloc(size, size);
for(i=0; i<size; i++) {
for(j=0; j<size; j++) {
gsl_complex z = gsl_complex_rect(1.0/(i+j+1.0), 1/(i*i+j*j+0.5));
gsl_matrix_complex_set(m, i, j, z);
}
}
return m;
}
gsl_matrix *
create_row_matrix(unsigned long size1, unsigned long size2)
{
unsigned long i;
gsl_matrix * m = gsl_matrix_calloc(size1, size2);
for(i=0; i<size1; i++) {
gsl_matrix_set(m, i, 0, 1.0/(i+1.0));
}
return m;
}
gsl_matrix *
create_2x2_matrix(double a11, double a12, double a21, double a22)
{
gsl_matrix * m = gsl_matrix_alloc(2, 2);
gsl_matrix_set(m, 0, 0, a11);
gsl_matrix_set(m, 0, 1, a12);
gsl_matrix_set(m, 1, 0, a21);
gsl_matrix_set(m, 1, 1, a22);
return m;
}
gsl_matrix *
create_diagonal_matrix(double a[], unsigned long size)
{
unsigned long i;
gsl_matrix * m = gsl_matrix_calloc(size, size);
for(i=0; i<size; i++) {
gsl_matrix_set(m, i, i, a[i]);
}
return m;
}
gsl_matrix * m11;
gsl_matrix * m51;
gsl_matrix * m35;
gsl_matrix * m53;
gsl_matrix * m97;
gsl_matrix * s35;
gsl_matrix * s53;
gsl_matrix * hilb2;
gsl_matrix * hilb3;
gsl_matrix * hilb4;
gsl_matrix * hilb12;
gsl_matrix * row3;
gsl_matrix * row5;
gsl_matrix * row12;
gsl_matrix * A22;
gsl_matrix * A33;
gsl_matrix * A44;
gsl_matrix * A55;
gsl_matrix_complex * c7;
gsl_matrix * inf5; double inf5_data[] = {1.0, 0.0, -3.0, 0.0, -5.0};
gsl_matrix * nan5;
gsl_matrix * dblmin3, * dblmin5;
double m53_lssolution[] = {52.5992295702070, -337.7263113752073,
351.8823436427604};
double hilb2_solution[] = {-8.0, 18.0} ;
double hilb3_solution[] = {27.0, -192.0, 210.0};
double hilb4_solution[] = {-64.0, 900.0, -2520.0, 1820.0};
double hilb12_solution[] = {-1728.0, 245388.0, -8528520.0,
127026900.0, -1009008000.0, 4768571808.0,
-14202796608.0, 27336497760.0, -33921201600.0,
26189163000.0, -11437874448.0, 2157916488.0 };
double c7_solution[] = { 2.40717272023734e+01, -9.84612797621247e+00,
-2.69338853034031e+02, 8.75455232472528e+01,
2.96661356736296e+03, -1.02624473923993e+03,
-1.82073812124749e+04, 5.67384473042410e+03,
5.57693879019068e+04, -1.61540963210502e+04,
-7.88941207561151e+04, 1.95053812987858e+04,
3.95548551241728e+04, -7.76593696255317e+03 };
gsl_matrix * vander2;
gsl_matrix * vander3;
gsl_matrix * vander4;
gsl_matrix * vander12;
double vander2_solution[] = {1.0, 0.0};
double vander3_solution[] = {0.0, 1.0, 0.0};
double vander4_solution[] = {0.0, 0.0, 1.0, 0.0};
double vander12_solution[] = {0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0};
gsl_matrix * moler10;
/* matmult now obsolete */
#ifdef MATMULT
int
test_matmult(void)
{
int s = 0;
gsl_matrix * A = gsl_matrix_calloc(2, 2);
gsl_matrix * B = gsl_matrix_calloc(2, 3);
gsl_matrix * C = gsl_matrix_calloc(2, 3);
gsl_matrix_set(A, 0, 0, 10.0);
gsl_matrix_set(A, 0, 1, 5.0);
gsl_matrix_set(A, 1, 0, 1.0);
gsl_matrix_set(A, 1, 1, 20.0);
gsl_matrix_set(B, 0, 0, 10.0);
gsl_matrix_set(B, 0, 1, 5.0);
gsl_matrix_set(B, 0, 2, 2.0);
gsl_matrix_set(B, 1, 0, 1.0);
gsl_matrix_set(B, 1, 1, 3.0);
gsl_matrix_set(B, 1, 2, 2.0);
gsl_linalg_matmult(A, B, C);
s += ( fabs(gsl_matrix_get(C, 0, 0) - 105.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 1) - 65.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 2) - 30.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 0) - 30.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 1) - 65.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 2) - 42.0) > GSL_DBL_EPSILON );
gsl_matrix_free(A);
gsl_matrix_free(B);
gsl_matrix_free(C);
return s;
}
int
test_matmult_mod(void)
{
int s = 0;
gsl_matrix * A = gsl_matrix_calloc(3, 3);
gsl_matrix * B = gsl_matrix_calloc(3, 3);
gsl_matrix * C = gsl_matrix_calloc(3, 3);
gsl_matrix * D = gsl_matrix_calloc(2, 3);
gsl_matrix * E = gsl_matrix_calloc(2, 3);
gsl_matrix * F = gsl_matrix_calloc(2, 2);
gsl_matrix_set(A, 0, 0, 10.0);
gsl_matrix_set(A, 0, 1, 5.0);
gsl_matrix_set(A, 0, 2, 1.0);
gsl_matrix_set(A, 1, 0, 1.0);
gsl_matrix_set(A, 1, 1, 20.0);
gsl_matrix_set(A, 1, 2, 5.0);
gsl_matrix_set(A, 2, 0, 1.0);
gsl_matrix_set(A, 2, 1, 3.0);
gsl_matrix_set(A, 2, 2, 7.0);
gsl_matrix_set(B, 0, 0, 10.0);
gsl_matrix_set(B, 0, 1, 5.0);
gsl_matrix_set(B, 0, 2, 2.0);
gsl_matrix_set(B, 1, 0, 1.0);
gsl_matrix_set(B, 1, 1, 3.0);
gsl_matrix_set(B, 1, 2, 2.0);
gsl_matrix_set(B, 2, 0, 1.0);
gsl_matrix_set(B, 2, 1, 3.0);
gsl_matrix_set(B, 2, 2, 2.0);
gsl_matrix_set(D, 0, 0, 10.0);
gsl_matrix_set(D, 0, 1, 5.0);
gsl_matrix_set(D, 0, 2, 1.0);
gsl_matrix_set(D, 1, 0, 1.0);
gsl_matrix_set(D, 1, 1, 20.0);
gsl_matrix_set(D, 1, 2, 5.0);
gsl_matrix_set(E, 0, 0, 10.0);
gsl_matrix_set(E, 0, 1, 5.0);
gsl_matrix_set(E, 0, 2, 2.0);
gsl_matrix_set(E, 1, 0, 1.0);
gsl_matrix_set(E, 1, 1, 3.0);
gsl_matrix_set(E, 1, 2, 2.0);
gsl_linalg_matmult_mod(A, GSL_LINALG_MOD_NONE, B, GSL_LINALG_MOD_NONE, C);
s += ( fabs(gsl_matrix_get(C, 0, 0) - 106.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 1) - 68.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 2) - 32.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 0) - 35.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 1) - 80.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 2) - 52.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 0) - 20.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 1) - 35.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 2) - 22.0) > GSL_DBL_EPSILON );
gsl_linalg_matmult_mod(A, GSL_LINALG_MOD_TRANSPOSE, B, GSL_LINALG_MOD_NONE, C);
s += ( fabs(gsl_matrix_get(C, 0, 0) - 102.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 1) - 56.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 2) - 24.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 0) - 73.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 1) - 94.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 2) - 56.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 0) - 22.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 1) - 41.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 2) - 26.0) > GSL_DBL_EPSILON );
gsl_linalg_matmult_mod(A, GSL_LINALG_MOD_NONE, B, GSL_LINALG_MOD_TRANSPOSE, C);
s += ( fabs(gsl_matrix_get(C, 0, 0) - 127.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 1) - 27.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 2) - 27.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 0) - 120.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 1) - 71.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 2) - 71.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 0) - 39.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 1) - 24.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 2) - 24.0) > GSL_DBL_EPSILON );
gsl_linalg_matmult_mod(A, GSL_LINALG_MOD_TRANSPOSE, B, GSL_LINALG_MOD_TRANSPOSE, C);
s += ( fabs(gsl_matrix_get(C, 0, 0) - 107.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 1) - 15.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 2) - 15.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 0) - 156.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 1) - 71.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 2) - 71.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 0) - 49.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 1) - 30.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 2) - 30.0) > GSL_DBL_EPSILON );
/* now try for non-symmetric matrices */
gsl_linalg_matmult_mod(D, GSL_LINALG_MOD_TRANSPOSE, E, GSL_LINALG_MOD_NONE, C);
s += ( fabs(gsl_matrix_get(C, 0, 0) - 101.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 1) - 53.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 0, 2) - 22.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 0) - 70.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 1) - 85.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 1, 2) - 50.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 0) - 15.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 1) - 20.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(C, 2, 2) - 12.0) > GSL_DBL_EPSILON );
gsl_linalg_matmult_mod(D, GSL_LINALG_MOD_NONE, E, GSL_LINALG_MOD_TRANSPOSE, F);
s += ( fabs(gsl_matrix_get(F, 0, 0) - 127.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(F, 0, 1) - 27.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(F, 1, 0) - 120.0) > GSL_DBL_EPSILON );
s += ( fabs(gsl_matrix_get(F, 1, 1) - 71.0) > GSL_DBL_EPSILON );
gsl_matrix_free(A);
gsl_matrix_free(B);
gsl_matrix_free(C);
gsl_matrix_free(D);
gsl_matrix_free(E);
gsl_matrix_free(F);
return s;
}
#endif
int
test_LU_solve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
int signum;
unsigned long i, dim = m->size1;
gsl_permutation * perm = gsl_permutation_alloc(dim);
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * lu = gsl_matrix_alloc(dim,dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_vector * residual = gsl_vector_alloc(dim);
gsl_matrix_memcpy(lu,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_LU_decomp(lu, perm, &signum);
s += gsl_linalg_LU_solve(lu, perm, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i),actual[i],eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
s += gsl_linalg_LU_refine(m, lu, perm, rhs, x, residual);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i),actual[i],eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g (improved)\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(residual);
gsl_vector_free(x);
gsl_matrix_free(lu);
gsl_vector_free(rhs);
gsl_permutation_free(perm);
return s;
}
int test_LU_solve(void)
{
int f;
int s = 0;
f = test_LU_solve_dim(hilb2, hilb2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LU_solve hilbert(2)");
s += f;
f = test_LU_solve_dim(hilb3, hilb3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LU_solve hilbert(3)");
s += f;
f = test_LU_solve_dim(hilb4, hilb4_solution, 2048.0 * GSL_DBL_EPSILON);
gsl_test(f, " LU_solve hilbert(4)");
s += f;
f = test_LU_solve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " LU_solve hilbert(12)");
s += f;
f = test_LU_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LU_solve vander(2)");
s += f;
f = test_LU_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LU_solve vander(3)");
s += f;
f = test_LU_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LU_solve vander(4)");
s += f;
f = test_LU_solve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " LU_solve vander(12)");
s += f;
return s;
}
int
test_LUc_solve_dim(const gsl_matrix_complex * m, const double * actual, double eps)
{
int s = 0;
int signum;
unsigned long i, dim = m->size1;
gsl_permutation * perm = gsl_permutation_alloc(dim);
gsl_vector_complex * rhs = gsl_vector_complex_alloc(dim);
gsl_matrix_complex * lu = gsl_matrix_complex_alloc(dim,dim);
gsl_vector_complex * x = gsl_vector_complex_alloc(dim);
gsl_vector_complex * residual = gsl_vector_complex_alloc(dim);
gsl_matrix_complex_memcpy(lu,m);
for(i=0; i<dim; i++)
{
gsl_complex z = gsl_complex_rect (2.0*i+1.0, 2.0*i+2.0);
gsl_vector_complex_set(rhs, i, z);
}
s += gsl_linalg_complex_LU_decomp(lu, perm, &signum);
s += gsl_linalg_complex_LU_solve(lu, perm, rhs, x);
for(i=0; i<dim; i++) {
gsl_complex z = gsl_vector_complex_get(x, i);
int foo_r = check(GSL_REAL(z),actual[2*i],eps);
int foo_i = check(GSL_IMAG(z),actual[2*i+1],eps);
if(foo_r || foo_i) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, GSL_REAL(z), actual[2*i]);
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, GSL_IMAG(z), actual[2*i+1]);
}
s += foo_r + foo_i;
}
s += gsl_linalg_complex_LU_refine(m, lu, perm, rhs, x, residual);
for(i=0; i<dim; i++) {
gsl_complex z = gsl_vector_complex_get(x, i);
int foo_r = check(GSL_REAL(z),actual[2*i],eps);
int foo_i = check(GSL_IMAG(z),actual[2*i+1],eps);
if(foo_r || foo_i) {
printf("%3lu[%lu]: %22.18g %22.18g (improved)\n", dim, i, GSL_REAL(z), actual[2*i]);
printf("%3lu[%lu]: %22.18g %22.18g (improved)\n", dim, i, GSL_IMAG(z), actual[2*i+1]);
}
s += foo_r + foo_i;
}
gsl_vector_complex_free(residual);
gsl_vector_complex_free(x);
gsl_matrix_complex_free(lu);
gsl_vector_complex_free(rhs);
gsl_permutation_free(perm);
return s;
}
int test_LUc_solve(void)
{
int f;
int s = 0;
f = test_LUc_solve_dim(c7, c7_solution, 1024.0 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " complex_LU_solve complex(7)");
s += f;
return s;
}
int
test_QR_solve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, dim = m->size1;
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * qr = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_matrix_memcpy(qr,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_QR_decomp(qr, d);
s += gsl_linalg_QR_solve(qr, d, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(qr);
gsl_vector_free(rhs);
return s;
}
int test_QR_solve(void)
{
int f;
int s = 0;
f = test_QR_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_solve hilbert(2)");
s += f;
f = test_QR_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_solve hilbert(3)");
s += f;
f = test_QR_solve_dim(hilb4, hilb4_solution, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_solve hilbert(4)");
s += f;
f = test_QR_solve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " QR_solve hilbert(12)");
s += f;
f = test_QR_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_solve vander(2)");
s += f;
f = test_QR_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_solve vander(3)");
s += f;
f = test_QR_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_solve vander(4)");
s += f;
f = test_QR_solve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " QR_solve vander(12)");
s += f;
return s;
}
int
test_QR_QRsolve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, dim = m->size1;
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * qr = gsl_matrix_alloc(dim,dim);
gsl_matrix * q = gsl_matrix_alloc(dim,dim);
gsl_matrix * r = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_matrix_memcpy(qr,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_QR_decomp(qr, d);
s += gsl_linalg_QR_unpack(qr, d, q, r);
s += gsl_linalg_QR_QRsolve(q, r, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(qr);
gsl_matrix_free(q);
gsl_matrix_free(r);
gsl_vector_free(rhs);
return s;
}
int test_QR_QRsolve(void)
{
int f;
int s = 0;
f = test_QR_QRsolve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_QRsolve hilbert(2)");
s += f;
f = test_QR_QRsolve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_QRsolve hilbert(3)");
s += f;
f = test_QR_QRsolve_dim(hilb4, hilb4_solution, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_QRsolve hilbert(4)");
s += f;
f = test_QR_QRsolve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " QR_QRsolve hilbert(12)");
s += f;
f = test_QR_QRsolve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_QRsolve vander(2)");
s += f;
f = test_QR_QRsolve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_QRsolve vander(3)");
s += f;
f = test_QR_QRsolve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_QRsolve vander(4)");
s += f;
f = test_QR_QRsolve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " QR_QRsolve vander(12)");
s += f;
return s;
}
int
test_QR_lssolve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, M = m->size1, N = m->size2;
gsl_vector * rhs = gsl_vector_alloc(M);
gsl_matrix * qr = gsl_matrix_alloc(M,N);
gsl_vector * d = gsl_vector_alloc(N);
gsl_vector * x = gsl_vector_alloc(N);
gsl_vector * r = gsl_vector_alloc(M);
gsl_vector * res = gsl_vector_alloc(M);
gsl_matrix_memcpy(qr,m);
for(i=0; i<M; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_QR_decomp(qr, d);
s += gsl_linalg_QR_lssolve(qr, d, rhs, x, res);
for(i=0; i<N; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("(%3lu,%3lu)[%lu]: %22.18g %22.18g\n", M, N, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
/* compute residual r = b - m x */
if (M == N) {
gsl_vector_set_zero(r);
} else {
gsl_vector_memcpy(r, rhs);
gsl_blas_dgemv(CblasNoTrans, -1.0, m, x, 1.0, r);
};
for(i=0; i<N; i++) {
int foo = check(gsl_vector_get(res, i), gsl_vector_get(r,i), sqrt(eps));
if(foo) {
printf("(%3lu,%3lu)[%lu]: %22.18g %22.18g\n", M, N, i, gsl_vector_get(res, i), gsl_vector_get(r,i));
}
s += foo;
}
gsl_vector_free(r);
gsl_vector_free(res);
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(qr);
gsl_vector_free(rhs);
return s;
}
int test_QR_lssolve(void)
{
int f;
int s = 0;
f = test_QR_lssolve_dim(m53, m53_lssolution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_lssolve m(5,3)");
s += f;
f = test_QR_lssolve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_lssolve hilbert(2)");
s += f;
f = test_QR_lssolve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_lssolve hilbert(3)");
s += f;
f = test_QR_lssolve_dim(hilb4, hilb4_solution, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_lssolve hilbert(4)");
s += f;
f = test_QR_lssolve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " QR_lssolve hilbert(12)");
s += f;
f = test_QR_lssolve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_lssolve vander(2)");
s += f;
f = test_QR_lssolve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_lssolve vander(3)");
s += f;
f = test_QR_lssolve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_lssolve vander(4)");
s += f;
f = test_QR_lssolve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " QR_lssolve vander(12)");
s += f;
return s;
}
int
test_QR_decomp_dim(const gsl_matrix * m, double eps)
{
int s = 0;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * qr = gsl_matrix_alloc(M,N);
gsl_matrix * a = gsl_matrix_alloc(M,N);
gsl_matrix * q = gsl_matrix_alloc(M,M);
gsl_matrix * r = gsl_matrix_alloc(M,N);
gsl_vector * d = gsl_vector_alloc(GSL_MIN(M,N));
gsl_matrix_memcpy(qr,m);
s += gsl_linalg_QR_decomp(qr, d);
s += gsl_linalg_QR_unpack(qr, d, q, r);
/* compute a = q r */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, q, r, 0.0, a);
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, i, j);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_vector_free(d);
gsl_matrix_free(qr);
gsl_matrix_free(a);
gsl_matrix_free(q);
gsl_matrix_free(r);
return s;
}
int test_QR_decomp(void)
{
int f;
int s = 0;
f = test_QR_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp m(3,5)");
s += f;
f = test_QR_decomp_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp m(5,3)");
s += f;
f = test_QR_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp hilbert(2)");
s += f;
f = test_QR_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp hilbert(3)");
s += f;
f = test_QR_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp hilbert(4)");
s += f;
f = test_QR_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp hilbert(12)");
s += f;
f = test_QR_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp vander(2)");
s += f;
f = test_QR_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp vander(3)");
s += f;
f = test_QR_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_decomp vander(4)");
s += f;
f = test_QR_decomp_dim(vander12, 0.0005); /* FIXME: bad accuracy */
gsl_test(f, " QR_decomp vander(12)");
s += f;
return s;
}
int
test_QRPT_solve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
int signum;
unsigned long i, dim = m->size1;
gsl_permutation * perm = gsl_permutation_alloc(dim);
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * qr = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_vector * norm = gsl_vector_alloc(dim);
gsl_matrix_memcpy(qr,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_QRPT_decomp(qr, d, perm, &signum, norm);
s += gsl_linalg_QRPT_solve(qr, d, perm, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(norm);
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(qr);
gsl_vector_free(rhs);
gsl_permutation_free(perm);
return s;
}
int test_QRPT_solve(void)
{
int f;
int s = 0;
f = test_QRPT_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_solve hilbert(2)");
s += f;
f = test_QRPT_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_solve hilbert(3)");
s += f;
f = test_QRPT_solve_dim(hilb4, hilb4_solution, 2 * 2048.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_solve hilbert(4)");
s += f;
f = test_QRPT_solve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " QRPT_solve hilbert(12)");
s += f;
f = test_QRPT_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_solve vander(2)");
s += f;
f = test_QRPT_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_solve vander(3)");
s += f;
f = test_QRPT_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_solve vander(4)");
s += f;
f = test_QRPT_solve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " QRPT_solve vander(12)");
s += f;
return s;
}
int
test_QRPT_QRsolve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
int signum;
unsigned long i, dim = m->size1;
gsl_permutation * perm = gsl_permutation_alloc(dim);
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * qr = gsl_matrix_alloc(dim,dim);
gsl_matrix * q = gsl_matrix_alloc(dim,dim);
gsl_matrix * r = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_vector * norm = gsl_vector_alloc(dim);
gsl_matrix_memcpy(qr,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_QRPT_decomp2(qr, q, r, d, perm, &signum, norm);
s += gsl_linalg_QRPT_QRsolve(q, r, perm, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(norm);
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(qr);
gsl_matrix_free(q);
gsl_matrix_free(r);
gsl_vector_free(rhs);
gsl_permutation_free(perm);
return s;
}
int test_QRPT_QRsolve(void)
{
int f;
int s = 0;
f = test_QRPT_QRsolve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_QRsolve hilbert(2)");
s += f;
f = test_QRPT_QRsolve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_QRsolve hilbert(3)");
s += f;
f = test_QRPT_QRsolve_dim(hilb4, hilb4_solution, 2 * 2048.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_QRsolve hilbert(4)");
s += f;
f = test_QRPT_QRsolve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " QRPT_QRsolve hilbert(12)");
s += f;
f = test_QRPT_QRsolve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_QRsolve vander(2)");
s += f;
f = test_QRPT_QRsolve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_QRsolve vander(3)");
s += f;
f = test_QRPT_QRsolve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_QRsolve vander(4)");
s += f;
f = test_QRPT_QRsolve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " QRPT_QRsolve vander(12)");
s += f;
return s;
}
int
test_QRPT_decomp_dim(const gsl_matrix * m, double eps)
{
int s = 0, signum;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * qr = gsl_matrix_alloc(M,N);
gsl_matrix * a = gsl_matrix_alloc(M,N);
gsl_matrix * q = gsl_matrix_alloc(M,M);
gsl_matrix * r = gsl_matrix_alloc(M,N);
gsl_vector * d = gsl_vector_alloc(GSL_MIN(M,N));
gsl_vector * norm = gsl_vector_alloc(N);
gsl_permutation * perm = gsl_permutation_alloc(N);
gsl_matrix_memcpy(qr,m);
s += gsl_linalg_QRPT_decomp(qr, d, perm, &signum, norm);
s += gsl_linalg_QR_unpack(qr, d, q, r);
/* compute a = q r */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, q, r, 0.0, a);
/* Compute QR P^T by permuting the elements of the rows of QR */
for (i = 0; i < M; i++) {
gsl_vector_view row = gsl_matrix_row (a, i);
gsl_permute_vector_inverse (perm, &row.vector);
}
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, i, j);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_permutation_free (perm);
gsl_vector_free(norm);
gsl_vector_free(d);
gsl_matrix_free(qr);
gsl_matrix_free(a);
gsl_matrix_free(q);
gsl_matrix_free(r);
return s;
}
int test_QRPT_decomp(void)
{
int f;
int s = 0;
f = test_QRPT_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_decomp m(3,5)");
s += f;
f = test_QRPT_decomp_dim(m53, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_decomp m(5,3)");
s += f;
f = test_QRPT_decomp_dim(s35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_decomp s(3,5)");
s += f;
f = test_QRPT_decomp_dim(s53, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_decomp s(5,3)");
s += f;
f = test_QRPT_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_decomp hilbert(2)");
s += f;
f = test_QRPT_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_decomp hilbert(3)");
s += f;
f = test_QRPT_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_decomp hilbert(4)");
s += f;
f = test_QRPT_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_decomp hilbert(12)");
s += f;
f = test_QRPT_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_decomp vander(2)");
s += f;
f = test_QRPT_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_decomp vander(3)");
s += f;
f = test_QRPT_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_decomp vander(4)");
s += f;
f = test_QRPT_decomp_dim(vander12, 0.0005); /* FIXME: bad accuracy */
gsl_test(f, " QRPT_decomp vander(12)");
s += f;
return s;
}
int
test_QR_update_dim(const gsl_matrix * m, double eps)
{
int s = 0;
unsigned long i,j,k, M = m->size1, N = m->size2;
gsl_matrix * qr1 = gsl_matrix_alloc(M,N);
gsl_matrix * qr2 = gsl_matrix_alloc(M,N);
gsl_matrix * q1 = gsl_matrix_alloc(M,M);
gsl_matrix * r1 = gsl_matrix_alloc(M,N);
gsl_matrix * q2 = gsl_matrix_alloc(M,M);
gsl_matrix * r2 = gsl_matrix_alloc(M,N);
gsl_vector * d = gsl_vector_alloc(GSL_MIN(M,N));
gsl_vector * solution1 = gsl_vector_alloc(N);
gsl_vector * solution2 = gsl_vector_alloc(N);
gsl_vector * u = gsl_vector_alloc(M);
gsl_vector * v = gsl_vector_alloc(N);
gsl_vector * w = gsl_vector_alloc(M);
gsl_matrix_memcpy(qr1,m);
gsl_matrix_memcpy(qr2,m);
for(i=0; i<M; i++) gsl_vector_set(u, i, sin(i+1.0));
for(i=0; i<N; i++) gsl_vector_set(v, i, cos(i+2.0) + sin(i*i+3.0));
for(i=0; i<M; i++)
{
double ui = gsl_vector_get(u, i);
for(j=0; j<N; j++)
{
double vj = gsl_vector_get(v, j);
double qij = gsl_matrix_get(qr1, i, j);
gsl_matrix_set(qr1, i, j, qij + ui * vj);
}
}
s += gsl_linalg_QR_decomp(qr2, d);
s += gsl_linalg_QR_unpack(qr2, d, q2, r2);
/* compute w = Q^T u */
for (j = 0; j < M; j++)
{
double sum = 0;
for (i = 0; i < M; i++)
sum += gsl_matrix_get (q2, i, j) * gsl_vector_get (u, i);
gsl_vector_set (w, j, sum);
}
s += gsl_linalg_QR_update(q2, r2, w, v);
/* compute qr2 = q2 * r2 */
for (i = 0; i < M; i++)
{
for (j = 0; j< N; j++)
{
double sum = 0;
for (k = 0; k <= GSL_MIN(j,M-1); k++)
{
double qik = gsl_matrix_get(q2, i, k);
double rkj = gsl_matrix_get(r2, k, j);
sum += qik * rkj ;
}
gsl_matrix_set (qr2, i, j, sum);
}
}
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double s1 = gsl_matrix_get(qr1, i, j);
double s2 = gsl_matrix_get(qr2, i, j);
int foo = check(s1, s2, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, s1, s2);
}
s += foo;
}
}
gsl_vector_free(solution1);
gsl_vector_free(solution2);
gsl_vector_free(d);
gsl_vector_free(u);
gsl_vector_free(v);
gsl_vector_free(w);
gsl_matrix_free(qr1);
gsl_matrix_free(qr2);
gsl_matrix_free(q1);
gsl_matrix_free(r1);
gsl_matrix_free(q2);
gsl_matrix_free(r2);
return s;
}
int test_QR_update(void)
{
int f;
int s = 0;
f = test_QR_update_dim(m35, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_update m(3,5)");
s += f;
f = test_QR_update_dim(m53, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_update m(5,3)");
s += f;
f = test_QR_update_dim(hilb2, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_update hilbert(2)");
s += f;
f = test_QR_update_dim(hilb3, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_update hilbert(3)");
s += f;
f = test_QR_update_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_update hilbert(4)");
s += f;
f = test_QR_update_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_update hilbert(12)");
s += f;
f = test_QR_update_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_update vander(2)");
s += f;
f = test_QR_update_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_update vander(3)");
s += f;
f = test_QR_update_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QR_update vander(4)");
s += f;
f = test_QR_update_dim(vander12, 0.0005); /* FIXME: bad accuracy */
gsl_test(f, " QR_update vander(12)");
s += f;
return s;
}
int
test_QRPT_update_dim(const gsl_matrix * m, double eps)
{
int s = 0, signum;
unsigned long i,j,k, M = m->size1, N = m->size2;
gsl_matrix * qr1 = gsl_matrix_alloc(M,N);
gsl_matrix * qr2 = gsl_matrix_alloc(M,N);
gsl_matrix * q1 = gsl_matrix_alloc(M,M);
gsl_matrix * r1 = gsl_matrix_alloc(M,N);
gsl_matrix * q2 = gsl_matrix_alloc(M,M);
gsl_matrix * r2 = gsl_matrix_alloc(M,N);
gsl_vector * d = gsl_vector_alloc(GSL_MIN(M,N));
gsl_vector * u = gsl_vector_alloc(M);
gsl_vector * v = gsl_vector_alloc(N);
gsl_vector * w = gsl_vector_alloc(M);
gsl_vector * norm = gsl_vector_alloc(N);
gsl_permutation * perm = gsl_permutation_alloc(N);
gsl_matrix_memcpy(qr1,m);
gsl_matrix_memcpy(qr2,m);
for(i=0; i<M; i++) gsl_vector_set(u, i, sin(i+1.0));
for(i=0; i<N; i++) gsl_vector_set(v, i, cos(i+2.0) + sin(i*i+3.0));
for(i=0; i<M; i++)
{
double ui = gsl_vector_get(u, i);
for(j=0; j<N; j++)
{
double vj = gsl_vector_get(v, j);
double qij = gsl_matrix_get(qr1, i, j);
gsl_matrix_set(qr1, i, j, qij + ui * vj);
}
}
s += gsl_linalg_QRPT_decomp(qr2, d, perm, &signum, norm);
s += gsl_linalg_QR_unpack(qr2, d, q2, r2);
/* compute w = Q^T u */
for (j = 0; j < M; j++)
{
double sum = 0;
for (i = 0; i < M; i++)
sum += gsl_matrix_get (q2, i, j) * gsl_vector_get (u, i);
gsl_vector_set (w, j, sum);
}
s += gsl_linalg_QRPT_update(q2, r2, perm, w, v);
/* Now compute qr2 = q2 * r2 * p^T */
/* first multiply q2 * r2 */
for (i = 0; i < M; i++)
{
for (j = 0; j< N; j++)
{
double sum = 0;
for (k = 0; k <= GSL_MIN(j,M-1); k++)
{
double qik = gsl_matrix_get(q2, i, k);
double rkj = gsl_matrix_get(r2, k, j);
sum += qik * rkj ;
}
gsl_matrix_set (qr2, i, j, sum);
}
}
/* now apply permutation to get qr2 = q2 * r2 * p^T */
for (i = 0; i < M ; i++)
{
gsl_vector_view r_i = gsl_matrix_row(qr2, i);
gsl_permute_vector_inverse(perm, &r_i.vector);
}
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double s1 = gsl_matrix_get(qr1, i, j);
double s2 = gsl_matrix_get(qr2, i, j);
int foo = check(s1, s2, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, s1, s2);
}
s += foo;
}
}
gsl_permutation_free (perm);
gsl_vector_free(norm);
gsl_vector_free(d);
gsl_vector_free(u);
gsl_vector_free(v);
gsl_vector_free(w);
gsl_matrix_free(qr1);
gsl_matrix_free(qr2);
gsl_matrix_free(q1);
gsl_matrix_free(r1);
gsl_matrix_free(q2);
gsl_matrix_free(r2);
return s;
}
int test_QRPT_update(void)
{
int f;
int s = 0;
f = test_QRPT_update_dim(m35, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_update m(3,5)");
s += f;
f = test_QRPT_update_dim(m53, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_update m(5,3)");
s += f;
f = test_QRPT_update_dim(hilb2, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_update hilbert(2)");
s += f;
f = test_QRPT_update_dim(hilb3, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_update hilbert(3)");
s += f;
f = test_QRPT_update_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_update hilbert(4)");
s += f;
f = test_QRPT_update_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_update hilbert(12)");
s += f;
f = test_QRPT_update_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_update vander(2)");
s += f;
f = test_QRPT_update_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_update vander(3)");
s += f;
f = test_QRPT_update_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " QRPT_update vander(4)");
s += f;
f = test_QRPT_update_dim(vander12, 0.0005); /* FIXME: bad accuracy */
gsl_test(f, " QRPT_update vander(12)");
s += f;
return s;
}
int
test_LQ_solve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, dim = m->size1;
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * lq = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_matrix_transpose_memcpy(lq,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_LQ_decomp(lq, d);
s += gsl_linalg_LQ_solve_T(lq, d, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_vector_free(rhs);
return s;
}
int test_LQ_solve(void)
{
int f;
int s = 0;
f = test_LQ_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve hilbert(2)");
s += f;
f = test_LQ_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve hilbert(3)");
s += f;
f = test_LQ_solve_dim(hilb4, hilb4_solution, 4 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve hilbert(4)");
s += f;
f = test_LQ_solve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " LQ_solve hilbert(12)");
s += f;
f = test_LQ_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve vander(2)");
s += f;
f = test_LQ_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve vander(3)");
s += f;
f = test_LQ_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_solve vander(4)");
s += f;
f = test_LQ_solve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " LQ_solve vander(12)");
s += f;
return s;
}
int
test_LQ_LQsolve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, dim = m->size1;
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * lq = gsl_matrix_alloc(dim,dim);
gsl_matrix * q = gsl_matrix_alloc(dim,dim);
gsl_matrix * l = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_matrix_transpose_memcpy(lq,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_LQ_decomp(lq, d);
s += gsl_linalg_LQ_unpack(lq, d, q, l);
s += gsl_linalg_LQ_LQsolve(q, l, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_matrix_free(q);
gsl_matrix_free(l);
gsl_vector_free(rhs);
return s;
}
int test_LQ_LQsolve(void)
{
int f;
int s = 0;
f = test_LQ_LQsolve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve hilbert(2)");
s += f;
f = test_LQ_LQsolve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve hilbert(3)");
s += f;
f = test_LQ_LQsolve_dim(hilb4, hilb4_solution, 4 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve hilbert(4)");
s += f;
f = test_LQ_LQsolve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " LQ_LQsolve hilbert(12)");
s += f;
f = test_LQ_LQsolve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve vander(2)");
s += f;
f = test_LQ_LQsolve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve vander(3)");
s += f;
f = test_LQ_LQsolve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_LQsolve vander(4)");
s += f;
f = test_LQ_LQsolve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " LQ_LQsolve vander(12)");
s += f;
return s;
}
int
test_LQ_lssolve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, M = m->size1, N = m->size2;
gsl_vector * rhs = gsl_vector_alloc(M);
gsl_matrix * lq = gsl_matrix_alloc(N,M);
gsl_vector * d = gsl_vector_alloc(N);
gsl_vector * x = gsl_vector_alloc(N);
gsl_vector * r = gsl_vector_alloc(M);
gsl_vector * res = gsl_vector_alloc(M);
gsl_matrix_transpose_memcpy(lq,m);
for(i=0; i<M; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_LQ_decomp(lq, d);
s += gsl_linalg_LQ_lssolve_T(lq, d, rhs, x, res);
for(i=0; i<N; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("(%3lu,%3lu)[%lu]: %22.18g %22.18g\n", M, N, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
/* compute residual r = b - m x */
if (M == N) {
gsl_vector_set_zero(r);
} else {
gsl_vector_memcpy(r, rhs);
gsl_blas_dgemv(CblasNoTrans, -1.0, m, x, 1.0, r);
};
for(i=0; i<N; i++) {
int foo = check(gsl_vector_get(res, i), gsl_vector_get(r,i), sqrt(eps));
if(foo) {
printf("(%3lu,%3lu)[%lu]: %22.18g %22.18g\n", M, N, i, gsl_vector_get(res, i), gsl_vector_get(r,i));
}
s += foo;
}
gsl_vector_free(r);
gsl_vector_free(res);
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_vector_free(rhs);
return s;
}
int test_LQ_lssolve(void)
{
int f;
int s = 0;
f = test_LQ_lssolve_dim(m53, m53_lssolution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve m(5,3)");
s += f;
f = test_LQ_lssolve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve hilbert(2)");
s += f;
f = test_LQ_lssolve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve hilbert(3)");
s += f;
f = test_LQ_lssolve_dim(hilb4, hilb4_solution, 4 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve hilbert(4)");
s += f;
f = test_LQ_lssolve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " LQ_lssolve hilbert(12)");
s += f;
f = test_LQ_lssolve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve vander(2)");
s += f;
f = test_LQ_lssolve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve vander(3)");
s += f;
f = test_LQ_lssolve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_lssolve vander(4)");
s += f;
f = test_LQ_lssolve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " LQ_lssolve vander(12)");
s += f;
return s;
}
int
test_LQ_decomp_dim(const gsl_matrix * m, double eps)
{
int s = 0;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * lq = gsl_matrix_alloc(M,N);
gsl_matrix * a = gsl_matrix_alloc(M,N);
gsl_matrix * q = gsl_matrix_alloc(N,N);
gsl_matrix * l = gsl_matrix_alloc(M,N);
gsl_vector * d = gsl_vector_alloc(GSL_MIN(M,N));
gsl_matrix_memcpy(lq,m);
s += gsl_linalg_LQ_decomp(lq, d);
s += gsl_linalg_LQ_unpack(lq, d, q, l);
/* compute a = q r */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, l, q, 0.0, a);
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, i, j);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_matrix_free(a);
gsl_matrix_free(q);
gsl_matrix_free(l);
return s;
}
int test_LQ_decomp(void)
{
int f;
int s = 0;
f = test_LQ_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp m(3,5)");
s += f;
f = test_LQ_decomp_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp m(5,3)");
s += f;
f = test_LQ_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp hilbert(2)");
s += f;
f = test_LQ_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp hilbert(3)");
s += f;
f = test_LQ_decomp_dim(hilb4, 4 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp hilbert(4)");
s += f;
f = test_LQ_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp hilbert(12)");
s += f;
f = test_LQ_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp vander(2)");
s += f;
f = test_LQ_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp vander(3)");
s += f;
f = test_LQ_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_decomp vander(4)");
s += f;
f = test_LQ_decomp_dim(vander12, 0.0005); /* FIXME: bad accuracy */
gsl_test(f, " LQ_decomp vander(12)");
s += f;
return s;
}
int
test_PTLQ_solve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
int signum;
unsigned long i, dim = m->size1;
gsl_permutation * perm = gsl_permutation_alloc(dim);
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * lq = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_vector * norm = gsl_vector_alloc(dim);
gsl_matrix_transpose_memcpy(lq,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_PTLQ_decomp(lq, d, perm, &signum, norm);
s += gsl_linalg_PTLQ_solve_T(lq, d, perm, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(norm);
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_vector_free(rhs);
gsl_permutation_free(perm);
return s;
}
int test_PTLQ_solve(void)
{
int f;
int s = 0;
f = test_PTLQ_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve hilbert(2)");
s += f;
f = test_PTLQ_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve hilbert(3)");
s += f;
f = test_PTLQ_solve_dim(hilb4, hilb4_solution, 2 * 2048.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve hilbert(4)");
s += f;
f = test_PTLQ_solve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " PTLQ_solve hilbert(12)");
s += f;
f = test_PTLQ_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve vander(2)");
s += f;
f = test_PTLQ_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve vander(3)");
s += f;
f = test_PTLQ_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_solve vander(4)");
s += f;
f = test_PTLQ_solve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " PTLQ_solve vander(12)");
s += f;
return s;
}
int
test_PTLQ_LQsolve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
int signum;
unsigned long i, dim = m->size1;
gsl_permutation * perm = gsl_permutation_alloc(dim);
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * lq = gsl_matrix_alloc(dim,dim);
gsl_matrix * q = gsl_matrix_alloc(dim,dim);
gsl_matrix * l = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_vector * norm = gsl_vector_alloc(dim);
gsl_matrix_transpose_memcpy(lq,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_PTLQ_decomp2(lq, q, l, d, perm, &signum, norm);
s += gsl_linalg_PTLQ_LQsolve_T(q, l, perm, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(norm);
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_vector_free(rhs);
gsl_permutation_free(perm);
return s;
}
int test_PTLQ_LQsolve(void)
{
int f;
int s = 0;
f = test_PTLQ_LQsolve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve hilbert(2)");
s += f;
f = test_PTLQ_LQsolve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve hilbert(3)");
s += f;
f = test_PTLQ_LQsolve_dim(hilb4, hilb4_solution, 2 * 2048.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve hilbert(4)");
s += f;
f = test_PTLQ_LQsolve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " PTLQ_LQsolve hilbert(12)");
s += f;
f = test_PTLQ_LQsolve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve vander(2)");
s += f;
f = test_PTLQ_LQsolve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve vander(3)");
s += f;
f = test_PTLQ_LQsolve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_LQsolve vander(4)");
s += f;
f = test_PTLQ_LQsolve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " PTLQ_LQsolve vander(12)");
s += f;
return s;
}
int
test_PTLQ_decomp_dim(const gsl_matrix * m, double eps)
{
int s = 0, signum;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * lq = gsl_matrix_alloc(N,M);
gsl_matrix * a = gsl_matrix_alloc(N,M);
gsl_matrix * q = gsl_matrix_alloc(M,M);
gsl_matrix * l = gsl_matrix_alloc(N,M);
gsl_vector * d = gsl_vector_alloc(GSL_MIN(M,N));
gsl_vector * norm = gsl_vector_alloc(N);
gsl_permutation * perm = gsl_permutation_alloc(N);
gsl_matrix_transpose_memcpy(lq,m);
s += gsl_linalg_PTLQ_decomp(lq, d, perm, &signum, norm);
s += gsl_linalg_LQ_unpack(lq, d, q, l);
/* compute a = l q */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, l, q, 0.0, a);
/* Compute P LQ by permuting the rows of LQ */
for (i = 0; i < M; i++) {
gsl_vector_view col = gsl_matrix_column (a, i);
gsl_permute_vector_inverse (perm, &col.vector);
}
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, j, i);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_permutation_free (perm);
gsl_vector_free(norm);
gsl_vector_free(d);
gsl_matrix_free(lq);
gsl_matrix_free(a);
gsl_matrix_free(q);
gsl_matrix_free(l);
return s;
}
int test_PTLQ_decomp(void)
{
int f;
int s = 0;
f = test_PTLQ_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp m(3,5)");
s += f;
f = test_PTLQ_decomp_dim(m53, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp m(5,3)");
s += f;
f = test_PTLQ_decomp_dim(s35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp s(3,5)");
s += f;
f = test_PTLQ_decomp_dim(s53, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp s(5,3)");
s += f;
f = test_PTLQ_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp hilbert(2)");
s += f;
f = test_PTLQ_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp hilbert(3)");
s += f;
f = test_PTLQ_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp hilbert(4)");
s += f;
f = test_PTLQ_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp hilbert(12)");
s += f;
f = test_PTLQ_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp vander(2)");
s += f;
f = test_PTLQ_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp vander(3)");
s += f;
f = test_PTLQ_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " PTLQ_decomp vander(4)");
s += f;
f = test_PTLQ_decomp_dim(vander12, 0.0005); /* FIXME: bad accuracy */
gsl_test(f, " PTLQ_decomp vander(12)");
s += f;
return s;
}
int
test_LQ_update_dim(const gsl_matrix * m, double eps)
{
int s = 0;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * lq1 = gsl_matrix_alloc(N,M);
gsl_matrix * lq2 = gsl_matrix_alloc(N,M);
gsl_matrix * q1 = gsl_matrix_alloc(M,M);
gsl_matrix * l1 = gsl_matrix_alloc(N,M);
gsl_matrix * q2 = gsl_matrix_alloc(M,M);
gsl_matrix * l2 = gsl_matrix_alloc(N,M);
gsl_vector * d2 = gsl_vector_alloc(GSL_MIN(M,N));
gsl_vector * u = gsl_vector_alloc(M);
gsl_vector * v = gsl_vector_alloc(N);
gsl_vector * w = gsl_vector_alloc(M);
gsl_matrix_transpose_memcpy(lq1,m);
gsl_matrix_transpose_memcpy(lq2,m);
for(i=0; i<M; i++) gsl_vector_set(u, i, sin(i+1.0));
for(i=0; i<N; i++) gsl_vector_set(v, i, cos(i+2.0) + sin(i*i+3.0));
/* lq1 is updated */
gsl_blas_dger(1.0, v, u, lq1);
/* lq2 is first decomposed, updated later */
s += gsl_linalg_LQ_decomp(lq2, d2);
s += gsl_linalg_LQ_unpack(lq2, d2, q2, l2);
/* compute w = Q^T u */
gsl_blas_dgemv(CblasNoTrans, 1.0, q2, u, 0.0, w);
/* now lq2 is updated */
s += gsl_linalg_LQ_update(q2, l2, v, w);
/* multiply q2*l2 */
gsl_blas_dgemm(CblasNoTrans,CblasNoTrans,1.0,l2,q2,0.0,lq2);
/* check lq1==lq2 */
for(i=0; i<N; i++) {
for(j=0; j<M; j++) {
double s1 = gsl_matrix_get(lq1, i, j);
double s2 = gsl_matrix_get(lq2, i, j);
int foo = check(s1, s2, eps);
#if 0
if(foo) {
printf("LQ:(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, s1, s2);
}
#endif
s += foo;
}
}
gsl_vector_free(d2);
gsl_vector_free(u);
gsl_vector_free(v);
gsl_vector_free(w);
gsl_matrix_free(lq1);
gsl_matrix_free(lq2);
gsl_matrix_free(q1);
gsl_matrix_free(l1);
gsl_matrix_free(q2);
gsl_matrix_free(l2);
return s;
}
int test_LQ_update(void)
{
int f;
int s = 0;
f = test_LQ_update_dim(m35, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update m(3,5)");
s += f;
f = test_LQ_update_dim(m53, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update m(5,3)");
s += f;
f = test_LQ_update_dim(hilb2, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update hilbert(2)");
s += f;
f = test_LQ_update_dim(hilb3, 2 * 512.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update hilbert(3)");
s += f;
f = test_LQ_update_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update hilbert(4)");
s += f;
f = test_LQ_update_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update hilbert(12)");
s += f;
f = test_LQ_update_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update vander(2)");
s += f;
f = test_LQ_update_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update vander(3)");
s += f;
f = test_LQ_update_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " LQ_update vander(4)");
s += f;
f = test_LQ_update_dim(vander12, 0.0005); /* FIXME: bad accuracy */
gsl_test(f, " LQ_update vander(12)");
s += f;
return s;
}
int
test_SV_solve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, dim = m->size1;
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * u = gsl_matrix_alloc(dim,dim);
gsl_matrix * q = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_calloc(dim);
gsl_matrix_memcpy(u,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_SV_decomp(u, q, d, x);
s += gsl_linalg_SV_solve(u, q, d, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(u);
gsl_matrix_free(q);
gsl_vector_free(rhs);
return s;
}
int test_SV_solve(void)
{
int f;
int s = 0;
f = test_SV_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_solve hilbert(2)");
s += f;
f = test_SV_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_solve hilbert(3)");
s += f;
f = test_SV_solve_dim(hilb4, hilb4_solution, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_solve hilbert(4)");
s += f;
f = test_SV_solve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " SV_solve hilbert(12)");
s += f;
f = test_SV_solve_dim(vander2, vander2_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_solve vander(2)");
s += f;
f = test_SV_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_solve vander(3)");
s += f;
f = test_SV_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_solve vander(4)");
s += f;
f = test_SV_solve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " SV_solve vander(12)");
s += f;
return s;
}
int
test_SV_decomp_dim(const gsl_matrix * m, double eps)
{
int s = 0;
double di1;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * v = gsl_matrix_alloc(M,N);
gsl_matrix * a = gsl_matrix_alloc(M,N);
gsl_matrix * q = gsl_matrix_alloc(N,N);
gsl_matrix * dqt = gsl_matrix_alloc(N,N);
gsl_vector * d = gsl_vector_alloc(N);
gsl_vector * w = gsl_vector_alloc(N);
gsl_matrix_memcpy(v,m);
s += gsl_linalg_SV_decomp(v, q, d, w);
/* Check that singular values are non-negative and in non-decreasing
order */
di1 = 0.0;
for (i = 0; i < N; i++)
{
double di = gsl_vector_get (d, i);
if (gsl_isnan (di))
{
continue; /* skip NaNs */
}
if (di < 0) {
s++;
printf("singular value %lu = %22.18g < 0\n", i, di);
}
if(i > 0 && di > di1) {
s++;
printf("singular value %lu = %22.18g vs previous %22.18g\n", i, di, di1);
}
di1 = di;
}
/* Scale dqt = D Q^T */
for (i = 0; i < N ; i++)
{
double di = gsl_vector_get (d, i);
for (j = 0; j < N; j++)
{
double qji = gsl_matrix_get(q, j, i);
gsl_matrix_set (dqt, i, j, qji * di);
}
}
/* compute a = v dqt */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, v, dqt, 0.0, a);
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, i, j);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_vector_free(w);
gsl_vector_free(d);
gsl_matrix_free(v);
gsl_matrix_free(a);
gsl_matrix_free(q);
gsl_matrix_free(dqt);
return s;
}
int test_SV_decomp(void)
{
int f;
int s = 0;
f = test_SV_decomp_dim(m11, 2 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp m(1,1)");
s += f;
f = test_SV_decomp_dim(m51, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp m(5,1)");
s += f;
/* M<N not implemented yet */
#if 0
f = test_SV_decomp_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp m(3,5)");
s += f;
#endif
f = test_SV_decomp_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp m(5,3)");
s += f;
f = test_SV_decomp_dim(moler10, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp moler(10)");
s += f;
f = test_SV_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp hilbert(2)");
s += f;
f = test_SV_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp hilbert(3)");
s += f;
f = test_SV_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp hilbert(4)");
s += f;
f = test_SV_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp hilbert(12)");
s += f;
f = test_SV_decomp_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp vander(2)");
s += f;
f = test_SV_decomp_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp vander(3)");
s += f;
f = test_SV_decomp_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp vander(4)");
s += f;
f = test_SV_decomp_dim(vander12, 1e-4);
gsl_test(f, " SV_decomp vander(12)");
s += f;
f = test_SV_decomp_dim(row3, 10 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp row3");
s += f;
f = test_SV_decomp_dim(row5, 128 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp row5");
s += f;
f = test_SV_decomp_dim(row12, 1024 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp row12");
s += f;
f = test_SV_decomp_dim(inf5, 1024 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp inf5");
s += f;
f = test_SV_decomp_dim(nan5, 1024 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp nan5");
s += f;
f = test_SV_decomp_dim(dblmin3, 1024 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp dblmin3");
s += f;
f = test_SV_decomp_dim(dblmin5, 1024 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp dblmin5");
s += f;
{
double i1, i2, i3, i4;
double lower = -2, upper = 2;
for (i1 = lower; i1 <= upper; i1++)
{
for (i2 = lower; i2 <= upper; i2++)
{
for (i3 = lower; i3 <= upper; i3++)
{
for (i4 = lower; i4 <= upper; i4++)
{
gsl_matrix_set (A22, 0,0, i1);
gsl_matrix_set (A22, 0,1, i2);
gsl_matrix_set (A22, 1,0, i3);
gsl_matrix_set (A22, 1,1, i4);
f = test_SV_decomp_dim(A22, 16 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp (2x2) A=[%g, %g; %g, %g]", i1,i2,i3,i4);
s += f;
}
}
}
}
}
{
int i;
double carry = 0, lower = 0, upper = 1;
double *a = A33->data;
for (i=0; i<9; i++) {
a[i] = lower;
}
while (carry == 0.0) {
f = test_SV_decomp_dim(A33, 64 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp (3x3) A=[ %g, %g, %g; %g, %g, %g; %g, %g, %g]",
a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);
/* increment */
carry=1.0;
for (i=9; carry > 0.0 && i>0 && i--;)
{
double v=a[i]+carry;
carry = (v>upper) ? 1.0 : 0.0;
a[i] = (v>upper) ? lower : v;
}
}
}
#ifdef TEST_SVD_4X4
{
int i;
double carry = 0, lower = 0, upper = 1;
double *a = A44->data;
for (i=0; i<16; i++) {
a[i] = lower;
}
while (carry == 0.0) {
f = test_SV_decomp_dim(A44, 64 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp (4x4) A=[ %g, %g, %g, %g; %g, %g, %g, %g; %g, %g, %g, %g; %g, %g, %g, %g]",
a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9],
a[10], a[11], a[12], a[13], a[14], a[15]);
/* increment */
carry=1.0;
for (i=16; carry > 0.0 && i>0 && i--;)
{
double v=a[i]+carry;
carry = (v>upper) ? 1.0 : 0.0;
a[i] = (v>upper) ? lower : v;
}
}
}
#endif
return s;
}
int
test_SV_decomp_mod_dim(const gsl_matrix * m, double eps)
{
int s = 0;
double di1;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * v = gsl_matrix_alloc(M,N);
gsl_matrix * a = gsl_matrix_alloc(M,N);
gsl_matrix * q = gsl_matrix_alloc(N,N);
gsl_matrix * x = gsl_matrix_alloc(N,N);
gsl_matrix * dqt = gsl_matrix_alloc(N,N);
gsl_vector * d = gsl_vector_alloc(N);
gsl_vector * w = gsl_vector_alloc(N);
gsl_matrix_memcpy(v,m);
s += gsl_linalg_SV_decomp_mod(v, x, q, d, w);
/* Check that singular values are non-negative and in non-decreasing
order */
di1 = 0.0;
for (i = 0; i < N; i++)
{
double di = gsl_vector_get (d, i);
if (gsl_isnan (di))
{
continue; /* skip NaNs */
}
if (di < 0) {
s++;
printf("singular value %lu = %22.18g < 0\n", i, di);
}
if(i > 0 && di > di1) {
s++;
printf("singular value %lu = %22.18g vs previous %22.18g\n", i, di, di1);
}
di1 = di;
}
/* Scale dqt = D Q^T */
for (i = 0; i < N ; i++)
{
double di = gsl_vector_get (d, i);
for (j = 0; j < N; j++)
{
double qji = gsl_matrix_get(q, j, i);
gsl_matrix_set (dqt, i, j, qji * di);
}
}
/* compute a = v dqt */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, v, dqt, 0.0, a);
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, i, j);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_vector_free(w);
gsl_vector_free(d);
gsl_matrix_free(v);
gsl_matrix_free(a);
gsl_matrix_free(q);
gsl_matrix_free(dqt);
gsl_matrix_free (x);
return s;
}
int test_SV_decomp_mod(void)
{
int f;
int s = 0;
f = test_SV_decomp_mod_dim(m11, 2 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod m(1,1)");
s += f;
f = test_SV_decomp_mod_dim(m51, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod m(5,1)");
s += f;
/* M<N not implemented yet */
#if 0
f = test_SV_decomp_mod_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod m(3,5)");
s += f;
#endif
f = test_SV_decomp_mod_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod m(5,3)");
s += f;
f = test_SV_decomp_mod_dim(moler10, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod moler(10)");
s += f;
f = test_SV_decomp_mod_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod hilbert(2)");
s += f;
f = test_SV_decomp_mod_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod hilbert(3)");
s += f;
f = test_SV_decomp_mod_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod hilbert(4)");
s += f;
f = test_SV_decomp_mod_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod hilbert(12)");
s += f;
f = test_SV_decomp_mod_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod vander(2)");
s += f;
f = test_SV_decomp_mod_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod vander(3)");
s += f;
f = test_SV_decomp_mod_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod vander(4)");
s += f;
f = test_SV_decomp_mod_dim(vander12, 1e-4);
gsl_test(f, " SV_decomp_mod vander(12)");
s += f;
f = test_SV_decomp_mod_dim(row3, 10 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod row3");
s += f;
f = test_SV_decomp_mod_dim(row5, 128 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod row5");
s += f;
f = test_SV_decomp_mod_dim(row12, 1024 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod row12");
s += f;
f = test_SV_decomp_mod_dim(inf5, 1024 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod inf5");
s += f;
f = test_SV_decomp_mod_dim(nan5, 1024 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod nan5");
s += f;
{
double i1, i2, i3, i4;
double lower = -2, upper = 2;
for (i1 = lower; i1 <= upper; i1++)
{
for (i2 = lower; i2 <= upper; i2++)
{
for (i3 = lower; i3 <= upper; i3++)
{
for (i4 = lower; i4 <= upper; i4++)
{
gsl_matrix_set (A22, 0,0, i1);
gsl_matrix_set (A22, 0,1, i2);
gsl_matrix_set (A22, 1,0, i3);
gsl_matrix_set (A22, 1,1, i4);
f = test_SV_decomp_mod_dim(A22, 16 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod (2x2) A=[%g, %g; %g, %g]", i1,i2,i3,i4);
s += f;
}
}
}
}
}
{
int i;
double carry = 0, lower = 0, upper = 1;
double *a = A33->data;
for (i=0; i<9; i++) {
a[i] = lower;
}
while (carry == 0.0) {
f = test_SV_decomp_mod_dim(A33, 64 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod (3x3) A=[ %g, %g, %g; %g, %g, %g; %g, %g, %g]",
a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);
/* increment */
carry=1.0;
for (i=9; carry > 0.0 && i>0 && i--;)
{
double v=a[i]+carry;
carry = (v>upper) ? 1.0 : 0.0;
a[i] = (v>upper) ? lower : v;
}
}
}
#ifdef TEST_SVD_4X4
{
int i;
double carry = 0, lower = 0, upper = 1;
double *a = A44->data;
for (i=0; i<16; i++) {
a[i] = lower;
}
while (carry == 0.0) {
f = test_SV_decomp_mod_dim(A44, 64 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_mod (4x4) A=[ %g, %g, %g, %g; %g, %g, %g, %g; %g, %g, %g, %g; %g, %g, %g, %g]",
a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9],
a[10], a[11], a[12], a[13], a[14], a[15]);
/* increment */
carry=1.0;
for (i=16; carry>0.0 && i>0 && i--;)
{
double v=a[i]+carry;
carry = (v>upper) ? 1.0 : 0.0;
a[i] = (v>upper) ? lower : v;
}
}
}
#endif
return s;
}
int
test_SV_decomp_jacobi_dim(const gsl_matrix * m, double eps)
{
int s = 0;
double di1;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * v = gsl_matrix_alloc(M,N);
gsl_matrix * a = gsl_matrix_alloc(M,N);
gsl_matrix * q = gsl_matrix_alloc(N,N);
gsl_matrix * dqt = gsl_matrix_alloc(N,N);
gsl_vector * d = gsl_vector_alloc(N);
gsl_matrix_memcpy(v,m);
s += gsl_linalg_SV_decomp_jacobi(v, q, d);
if (s)
printf("call returned status = %d\n", s);
/* Check that singular values are non-negative and in non-decreasing
order */
di1 = 0.0;
for (i = 0; i < N; i++)
{
double di = gsl_vector_get (d, i);
if (gsl_isnan (di))
{
continue; /* skip NaNs */
}
if (di < 0) {
s++;
printf("singular value %lu = %22.18g < 0\n", i, di);
}
if(i > 0 && di > di1) {
s++;
printf("singular value %lu = %22.18g vs previous %22.18g\n", i, di, di1);
}
di1 = di;
}
/* Scale dqt = D Q^T */
for (i = 0; i < N ; i++)
{
double di = gsl_vector_get (d, i);
for (j = 0; j < N; j++)
{
double qji = gsl_matrix_get(q, j, i);
gsl_matrix_set (dqt, i, j, qji * di);
}
}
/* compute a = v dqt */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, v, dqt, 0.0, a);
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, i, j);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_vector_free(d);
gsl_matrix_free(v);
gsl_matrix_free(a);
gsl_matrix_free(q);
gsl_matrix_free(dqt);
return s;
}
int test_SV_decomp_jacobi(void)
{
int f;
int s = 0;
f = test_SV_decomp_jacobi_dim(m11, 2 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi m(1,1)");
s += f;
f = test_SV_decomp_jacobi_dim(m51, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi m(5,1)");
s += f;
/* M<N not implemented yet */
#if 0
f = test_SV_decomp_jacobi_dim(m35, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi m(3,5)");
s += f;
#endif
f = test_SV_decomp_jacobi_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi m(5,3)");
s += f;
f = test_SV_decomp_jacobi_dim(moler10, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi moler(10)");
s += f;
f = test_SV_decomp_jacobi_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi hilbert(2)");
s += f;
f = test_SV_decomp_jacobi_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi hilbert(3)");
s += f;
f = test_SV_decomp_jacobi_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi hilbert(4)");
s += f;
f = test_SV_decomp_jacobi_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi hilbert(12)");
s += f;
f = test_SV_decomp_jacobi_dim(vander2, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi vander(2)");
s += f;
f = test_SV_decomp_jacobi_dim(vander3, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi vander(3)");
s += f;
f = test_SV_decomp_jacobi_dim(vander4, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi vander(4)");
s += f;
f = test_SV_decomp_jacobi_dim(vander12, 1e-4);
gsl_test(f, " SV_decomp_jacobi vander(12)");
s += f;
f = test_SV_decomp_jacobi_dim(row3, 10 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi row3");
s += f;
f = test_SV_decomp_jacobi_dim(row5, 128 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi row5");
s += f;
f = test_SV_decomp_jacobi_dim(row12, 1024 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi row12");
s += f;
#ifdef TEST_JACOBI_INF
f = test_SV_decomp_jacobi_dim(inf5, 1024 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi inf5");
s += f;
f = test_SV_decomp_jacobi_dim(nan5, 1024 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi nan5");
s += f;
#endif
{
double i1, i2, i3, i4;
double lower = -2, upper = 2;
for (i1 = lower; i1 <= upper; i1++)
{
for (i2 = lower; i2 <= upper; i2++)
{
for (i3 = lower; i3 <= upper; i3++)
{
for (i4 = lower; i4 <= upper; i4++)
{
gsl_matrix_set (A22, 0,0, i1);
gsl_matrix_set (A22, 0,1, i2);
gsl_matrix_set (A22, 1,0, i3);
gsl_matrix_set (A22, 1,1, i4);
f = test_SV_decomp_jacobi_dim(A22, 16 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi (2x2) A=[%g, %g; %g, %g]", i1,i2,i3,i4);
s += f;
}
}
}
}
}
{
int i;
double carry = 0, lower = 0, upper = 1;
double *a = A33->data;
for (i=0; i<9; i++) {
a[i] = lower;
}
while (carry == 0.0) {
f = test_SV_decomp_jacobi_dim(A33, 64 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi (3x3) A=[ %g, %g, %g; %g, %g, %g; %g, %g, %g]",
a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);
/* increment */
carry=1.0;
for (i=9; carry > 0.0 && i>0 && i--;)
{
double v=a[i]+carry;
carry = (v>upper) ? 1.0 : 0.0;
a[i] = (v>upper) ? lower : v;
}
}
}
#ifdef TEST_SVD_4X4
{
int i;
unsigned long k = 0;
double carry = 0, lower = 0, upper = 1;
double *a = A44->data;
for (i=0; i<16; i++) {
a[i] = lower;
}
while (carry == 0.0) {
k++;
f = test_SV_decomp_jacobi_dim(A44, 64 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi (4x4) A=[ %g, %g, %g, %g; %g, %g, %g, %g; %g, %g, %g, %g; %g, %g, %g, %g] %lu",
a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9],
a[10], a[11], a[12], a[13], a[14], a[15], k);
/* increment */
carry=1.0;
for (i=16; carry > 0.0 && i>0 && i--;)
{
double v=a[i]+carry;
carry = (v>upper) ? 1.0 : 0.0;
a[i] = (v>upper) ? lower : v;
}
}
}
#endif
{
int i;
unsigned long k = 0;
double carry = 0, lower = 0, upper = 1;
double *a = A55->data;
for (i=0; i<25; i++) {
a[i] = lower;
}
while (carry == 0.0) {
k++;
if (k % 1001 == 0)
{
f = test_SV_decomp_jacobi_dim(A55, 64 * GSL_DBL_EPSILON);
gsl_test(f, " SV_decomp_jacobi (5x5) case=%lu",k);
}
/* increment */
carry=1.0;
for (i=25; carry >0.0 && i>0 && i--;)
{
double v=a[i]+carry;
carry = (v>upper) ? 1.0 : 0.0;
a[i] = (v>upper) ? lower : v;
}
}
}
return s;
}
int
test_cholesky_solve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, dim = m->size1;
gsl_vector * rhs = gsl_vector_alloc(dim);
gsl_matrix * u = gsl_matrix_alloc(dim,dim);
gsl_vector * x = gsl_vector_calloc(dim);
gsl_matrix_memcpy(u,m);
for(i=0; i<dim; i++) gsl_vector_set(rhs, i, i+1.0);
s += gsl_linalg_cholesky_decomp(u);
s += gsl_linalg_cholesky_solve(u, rhs, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i), actual[i], eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(x);
gsl_matrix_free(u);
gsl_vector_free(rhs);
return s;
}
int test_cholesky_solve(void)
{
int f;
int s = 0;
f = test_cholesky_solve_dim(hilb2, hilb2_solution, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_solve hilbert(2)");
s += f;
f = test_cholesky_solve_dim(hilb3, hilb3_solution, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_solve hilbert(3)");
s += f;
f = test_cholesky_solve_dim(hilb4, hilb4_solution, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_solve hilbert(4)");
s += f;
f = test_cholesky_solve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " cholesky_solve hilbert(12)");
s += f;
return s;
}
int
test_cholesky_decomp_dim(const gsl_matrix * m, double eps)
{
int s = 0;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix * v = gsl_matrix_alloc(M,N);
gsl_matrix * a = gsl_matrix_alloc(M,N);
gsl_matrix * l = gsl_matrix_alloc(M,N);
gsl_matrix * lt = gsl_matrix_alloc(N,N);
gsl_matrix_memcpy(v,m);
s += gsl_linalg_cholesky_decomp(v);
/* Compute L LT */
for (i = 0; i < N ; i++)
{
for (j = 0; j < N; j++)
{
double vij = gsl_matrix_get(v, i, j);
gsl_matrix_set (l, i, j, i>=j ? vij : 0);
gsl_matrix_set (lt, i, j, i<=j ? vij : 0);
}
}
/* compute a = l lt */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, l, lt, 0.0, a);
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, i, j);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_matrix_free(v);
gsl_matrix_free(a);
gsl_matrix_free(l);
gsl_matrix_free(lt);
return s;
}
int test_cholesky_decomp(void)
{
int f;
int s = 0;
f = test_cholesky_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_decomp hilbert(2)");
s += f;
f = test_cholesky_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_decomp hilbert(3)");
s += f;
f = test_cholesky_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_decomp hilbert(4)");
s += f;
f = test_cholesky_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_decomp hilbert(12)");
s += f;
return s;
}
int
test_cholesky_invert_dim(const gsl_matrix * m, double eps)
{
int s = 0;
unsigned long i, j, N = m->size1;
gsl_matrix * v = gsl_matrix_alloc(N, N);
gsl_matrix * c = gsl_matrix_alloc(N, N);
gsl_matrix_memcpy(v,m);
s += gsl_linalg_cholesky_decomp(v);
s += gsl_linalg_cholesky_invert(v);
gsl_blas_dsymm(CblasLeft, CblasUpper, 1.0, m, v, 0.0, c);
/* c should be the identity matrix */
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
int foo;
double cij = gsl_matrix_get(c, i, j);
double expected;
if (i == j)
expected = 1.0;
else
expected = 0.0;
foo = check(cij, expected, eps);
if (foo)
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", N, N, i,j, cij, expected);
s += foo;
}
}
gsl_matrix_free(v);
gsl_matrix_free(c);
return s;
}
int
test_cholesky_invert(void)
{
int f;
int s = 0;
f = test_cholesky_invert_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_invert hilbert(2)");
s += f;
f = test_cholesky_invert_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_invert hilbert(3)");
s += f;
f = test_cholesky_invert_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_invert hilbert(4)");
s += f;
return s;
}
int
test_cholesky_decomp_unit_dim(const gsl_matrix * m, double eps)
{
int s = 0;
const unsigned long M = m->size1;
const unsigned long N = m->size2;
unsigned long i,j;
gsl_matrix * v = gsl_matrix_alloc(M,N);
gsl_matrix * a = gsl_matrix_alloc(M,N);
gsl_matrix * l = gsl_matrix_alloc(M,N);
gsl_matrix * lt = gsl_matrix_alloc(N,N);
gsl_matrix * dm = gsl_matrix_alloc(M,N);
gsl_vector * dv = gsl_vector_alloc(M);
gsl_matrix_memcpy(v,m);
s += gsl_linalg_cholesky_decomp_unit(v, dv);
/*
for(i = 0; i < M; i++)
{
for(j = 0; j < N; j++)
{
printf("v[%lu,%lu]: %22.18e\n", i,j, gsl_matrix_get(v, i, j));
}
}
for(i = 0; i < M; i++)
{
printf("d[%lu]: %22.18e\n", i, gsl_vector_get(dv, i));
}
*/
/* put L and transpose(L) into separate matrices */
for(i = 0; i < N ; i++)
{
for(j = 0; j < N; j++)
{
const double vij = gsl_matrix_get(v, i, j);
gsl_matrix_set (l, i, j, i>=j ? vij : 0);
gsl_matrix_set (lt, i, j, i<=j ? vij : 0);
}
}
/* put D into its own matrix */
gsl_matrix_set_zero(dm);
for(i = 0; i < M; ++i) gsl_matrix_set(dm, i, i, gsl_vector_get(dv, i));
/* compute a = L * D * transpose(L); uses v for temp space */
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, dm, lt, 0.0, v);
gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, l, v, 0.0, a);
for(i = 0; i < M; i++)
{
for(j = 0; j < N; j++)
{
const double aij = gsl_matrix_get(a, i, j);
const double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo)
{
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_vector_free(dv);
gsl_matrix_free(dm);
gsl_matrix_free(lt);
gsl_matrix_free(l);
gsl_matrix_free(v);
gsl_matrix_free(a);
return s;
}
int test_cholesky_decomp_unit(void)
{
int f;
int s = 0;
f = test_cholesky_decomp_unit_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_decomp_unit hilbert(2)");
s += f;
f = test_cholesky_decomp_unit_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_decomp_unit hilbert(3)");
s += f;
f = test_cholesky_decomp_unit_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_decomp_unit hilbert(4)");
s += f;
f = test_cholesky_decomp_unit_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " cholesky_decomp_unit hilbert(12)");
s += f;
return s;
}
int
test_choleskyc_solve_dim(const gsl_matrix_complex * m, const gsl_vector_complex * actual, double eps)
{
int s = 0;
unsigned long i, dim = m->size1;
gsl_complex z;
gsl_vector_complex * rhs = gsl_vector_complex_alloc(dim);
gsl_matrix_complex * u = gsl_matrix_complex_alloc(dim,dim);
gsl_vector_complex * x = gsl_vector_complex_calloc(dim);
GSL_SET_IMAG(&z, 0.0);
gsl_matrix_complex_memcpy(u,m);
for(i=0; i<dim; i++)
{
GSL_SET_REAL(&z, i + 1.0);
gsl_vector_complex_set(rhs, i, z);
}
s += gsl_linalg_complex_cholesky_decomp(u);
s += gsl_linalg_complex_cholesky_solve(u, rhs, x);
for(i=0; i<dim; i++) {
gsl_complex y = gsl_vector_complex_get(x, i);
gsl_complex a = gsl_vector_complex_get(actual, i);
int foo = check(GSL_REAL(y), GSL_REAL(a), eps);
int foo2 = check(GSL_IMAG(y), GSL_IMAG(a), eps);
if(foo || foo2) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, GSL_REAL(y), GSL_REAL(a));
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, GSL_IMAG(y), GSL_IMAG(a));
}
s += foo + foo2;
}
gsl_vector_complex_free(x);
gsl_matrix_complex_free(u);
gsl_vector_complex_free(rhs);
return s;
} /* test_choleskyc_solve_dim() */
int
test_choleskyc_solve(void)
{
double data7[] = { 66,0, 0,64, 126,63, 124,-62, 61,-61, 60,60, 0,-59,
0,-64, 65,0, 62,-124, -61,-122, -60,-60, 59,-59, -58,0,
126,-63, 62,124, 308,0, 180,-240, 59,-177, 174,58, -57,-114,
124,62, -61,122, 180,240, 299,0, 174,-58, 57,171, 56,-112,
61,61, -60,60, 59,177, 174,58, 119,0, 0,112, 55,-55,
60,-60, 59,59, 174,-58, 57,-171, 0,-112, 116,0, -54,-54,
0,59, -58,0, -57,114, 56,112, 55,55, -54,54, 60,0 };
double data7_sol[] = { -0.524944196428570,0.209123883928571,
1.052873883928572,0.712444196428571,
0.117568824404762,0.443191964285714,
0.412862723214286,-0.356696428571429,
0.815931919642858,-0.265820312500000,
0.777929687500000,0.119484747023810,
1.058733258928571,-0.132087053571429 };
gsl_matrix_complex_view cp7 = gsl_matrix_complex_view_array(data7, 7, 7);
gsl_vector_complex_view cp7_sol = gsl_vector_complex_view_array(data7_sol, 7);
int f;
int s = 0;
f = test_choleskyc_solve_dim(&cp7.matrix, &cp7_sol.vector, 1024.0 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " complex_cholesky_solve complex(7)");
s += f;
return s;
} /* test_choleskyc_solve() */
int
test_choleskyc_decomp_dim(const gsl_matrix_complex * m, double eps)
{
int s = 0;
unsigned long i,j, M = m->size1, N = m->size2;
gsl_matrix_complex * v = gsl_matrix_complex_alloc(M,N);
gsl_matrix_complex * a = gsl_matrix_complex_alloc(M,N);
gsl_matrix_complex * l = gsl_matrix_complex_alloc(M,N);
gsl_matrix_complex * lh = gsl_matrix_complex_alloc(N,N);
gsl_matrix_complex_memcpy(v, m);
gsl_matrix_complex_set_zero(l);
gsl_matrix_complex_set_zero(lh);
s += gsl_linalg_complex_cholesky_decomp(v);
/* Compute L L^H */
for (i = 0; i < N ; i++)
{
for (j = 0; j <= i; j++)
{
gsl_complex vij = gsl_matrix_complex_get(v, i, j);
gsl_matrix_complex_set (l, i, j, vij);
gsl_matrix_complex_set (lh, j, i, gsl_complex_conjugate(vij));
}
}
/* compute a = l lh */
gsl_blas_zgemm (CblasNoTrans,
CblasNoTrans,
GSL_COMPLEX_ONE,
l,
lh,
GSL_COMPLEX_ZERO,
a);
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
gsl_complex aij = gsl_matrix_complex_get(a, i, j);
gsl_complex mij = gsl_matrix_complex_get(m, i, j);
int foo_r = check(GSL_REAL(aij), GSL_REAL(mij), eps);
int foo_i = check(GSL_IMAG(aij), GSL_IMAG(mij), eps);
if(foo_r || foo_i) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, GSL_REAL(aij), GSL_REAL(mij));
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, GSL_IMAG(aij), GSL_IMAG(mij));
}
s += foo_r + foo_i;
}
}
gsl_matrix_complex_free(v);
gsl_matrix_complex_free(a);
gsl_matrix_complex_free(l);
gsl_matrix_complex_free(lh);
return s;
}
int
test_choleskyc_decomp(void)
{
int f;
int s = 0;
double dat3[] = { 59.75,0, 49.25,172.25, 66.75,-162.75,
49.25,-172.25, 555.5,0, -429,-333.5,
66.75,162.75, -429,333.5, 536.5,0 };
gsl_matrix_complex_view p3 = gsl_matrix_complex_view_array(dat3, 3, 3);
f = test_choleskyc_decomp_dim(&p3.matrix, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " complex_cholesky_decomp complex(3)");
s += f;
return s;
}
int
test_HH_solve_dim(const gsl_matrix * m, const double * actual, double eps)
{
int s = 0;
unsigned long i, dim = m->size1;
gsl_permutation * perm = gsl_permutation_alloc(dim);
gsl_matrix * hh = gsl_matrix_alloc(dim,dim);
gsl_vector * d = gsl_vector_alloc(dim);
gsl_vector * x = gsl_vector_alloc(dim);
gsl_matrix_memcpy(hh,m);
for(i=0; i<dim; i++) gsl_vector_set(x, i, i+1.0);
s += gsl_linalg_HH_svx(hh, x);
for(i=0; i<dim; i++) {
int foo = check(gsl_vector_get(x, i),actual[i],eps);
if( foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
gsl_vector_free(x);
gsl_vector_free(d);
gsl_matrix_free(hh);
gsl_permutation_free(perm);
return s;
}
int test_HH_solve(void)
{
int f;
int s = 0;
f = test_HH_solve_dim(hilb2, hilb2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " HH_solve hilbert(2)");
s += f;
f = test_HH_solve_dim(hilb3, hilb3_solution, 128.0 * GSL_DBL_EPSILON);
gsl_test(f, " HH_solve hilbert(3)");
s += f;
f = test_HH_solve_dim(hilb4, hilb4_solution, 2.0 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " HH_solve hilbert(4)");
s += f;
f = test_HH_solve_dim(hilb12, hilb12_solution, 0.5);
gsl_test(f, " HH_solve hilbert(12)");
s += f;
f = test_HH_solve_dim(vander2, vander2_solution, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " HH_solve vander(2)");
s += f;
f = test_HH_solve_dim(vander3, vander3_solution, 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " HH_solve vander(3)");
s += f;
f = test_HH_solve_dim(vander4, vander4_solution, 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " HH_solve vander(4)");
s += f;
f = test_HH_solve_dim(vander12, vander12_solution, 0.05);
gsl_test(f, " HH_solve vander(12)");
s += f;
return s;
}
int
test_TDS_solve_dim(unsigned long dim, double d, double od, const double * actual, double eps)
{
int s = 0;
unsigned long i;
gsl_vector * offdiag = vector_alloc(dim-1);
gsl_vector * diag = vector_alloc(dim);
gsl_vector * rhs = vector_alloc(dim);
gsl_vector * x = vector_alloc(dim);
for(i=0; i<dim; i++) {
gsl_vector_set(diag, i, d);
gsl_vector_set(rhs, i, i + 1.0);
}
for(i=0; i<dim-1; i++) {
gsl_vector_set(offdiag, i, od);
}
s += gsl_linalg_solve_symm_tridiag(diag, offdiag, rhs, x);
for(i=0; i<dim; i++) {
double si = gsl_vector_get(x, i);
double ai = actual[i];
int foo = check(si, ai, eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
vector_free(x);
vector_free(rhs);
vector_free(diag);
vector_free(offdiag);
return s;
}
int test_TDS_solve(void)
{
int f;
int s = 0;
{
double actual[] = {0.0, 2.0};
f = test_TDS_solve_dim(2, 1.0, 0.5, actual, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDS dim=2 A");
s += f;
}
{
double actual[] = {3.0/8.0, 15.0/8.0};
f = test_TDS_solve_dim(2, 1.0, 1.0/3.0, actual, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDS dim=2 B");
s += f;
}
{
double actual[] = {5.0/8.0, 9.0/8.0, 2.0, 15.0/8.0, 35.0/8.0};
f = test_TDS_solve_dim(5, 1.0, 1.0/3.0, actual, 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDS dim=5");
s += f;
}
return s;
}
int
test_TDS_cyc_solve_one(const unsigned long dim,
const double * d, const double * od,
const double * r, const double * actual, double eps)
{
int s = 0;
unsigned long i;
gsl_vector * offdiag = vector_alloc(dim);
gsl_vector * diag = vector_alloc(dim);
gsl_vector * rhs = vector_alloc(dim);
gsl_vector * x = vector_alloc(dim);
for(i=0; i<dim; i++) {
gsl_vector_set(diag, i, d[i]);
gsl_vector_set(rhs, i, r[i]);
gsl_vector_set(offdiag, i, od[i]);
}
s += gsl_linalg_solve_symm_cyc_tridiag(diag, offdiag, rhs, x);
for(i=0; i<dim; i++) {
double si = gsl_vector_get(x, i);
double ai = actual[i];
int foo = check(si, ai, eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
vector_free(x);
vector_free(rhs);
vector_free(diag);
vector_free(offdiag);
return s;
}
int test_TDS_cyc_solve(void)
{
int f;
int s = 0;
#ifdef SUPPORT_UNDERSIZE_CYC
{
unsigned long dim = 1;
double diag[] = { 2 };
double offdiag[] = { 3 };
double rhs[] = { 7 };
double actual[] = { 3.5 };
f = test_TDS_cyc_solve_one(dim, diag, offdiag, rhs, actual, 28.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDS_cyc dim=%lu A", dim);
s += f;
}
{
unsigned long dim = 2;
double diag[] = { 1, 2 };
double offdiag[] = { 3, 4 };
double rhs[] = { 7, -7 };
double actual[] = { -5, 4 };
f = test_TDS_cyc_solve_one(dim, diag, offdiag, rhs, actual, 28.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDS_cyc dim=%lu A", dim);
s += f;
}
#endif
{
unsigned long dim = 3;
double diag[] = { 1, 1, 1 };
double offdiag[] = { 3, 3, 3 };
double rhs[] = { 7, -7, 7 };
double actual[] = { -2, 5, -2 };
f = test_TDS_cyc_solve_one(dim, diag, offdiag, rhs, actual, 28.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDS_cyc dim=%lu A", dim);
s += f;
}
{
unsigned long dim = 5;
double diag[] = { 4, 2, 1, 2, 4 };
double offdiag[] = { 1, 1, 1, 1, 1 };
double rhs[] = { 30, -24, 3, 21, -30 };
double actual[] = { 12, 3, -42, 42, -21 };
/* f = test_TDS_cyc_solve_one(dim, diag, offdiag, rhs, actual, 7.0 * GSL_DBL_EPSILON);
FIXME: bad accuracy */
f = test_TDS_cyc_solve_one(dim, diag, offdiag, rhs, actual, 40.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDS_cyc dim=%lu B", dim);
s += f;
}
return s;
}
int
test_TDN_solve_dim(unsigned long dim, double d, double a, double b, const double * actual, double eps)
{
int s = 0;
unsigned long i;
gsl_vector * abovediag = vector_alloc(dim-1);
gsl_vector * belowdiag = vector_alloc(dim-1);
gsl_vector * diag = vector_alloc(dim);
gsl_vector * rhs = vector_alloc(dim);
gsl_vector * x = vector_alloc(dim);
for(i=0; i<dim; i++) {
gsl_vector_set(diag, i, d);
gsl_vector_set(rhs, i, i + 1.0);
}
for(i=0; i<dim-1; i++) {
gsl_vector_set(abovediag, i, a);
gsl_vector_set(belowdiag, i, b);
}
s += gsl_linalg_solve_tridiag(diag, abovediag, belowdiag, rhs, x);
for(i=0; i<dim; i++) {
double si = gsl_vector_get(x, i);
double ai = actual[i];
int foo = check(si, ai, eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
vector_free(x);
vector_free(rhs);
vector_free(diag);
vector_free(abovediag);
vector_free(belowdiag);
return s;
}
int test_TDN_solve(void)
{
int f;
int s = 0;
double actual[16];
actual[0] = -7.0/3.0;
actual[1] = 5.0/3.0;
actual[2] = 4.0/3.0;
f = test_TDN_solve_dim(3, 1.0, 2.0, 1.0, actual, 2.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDN dim=2 A");
s += f;
actual[0] = 0.75;
actual[1] = 0.75;
actual[2] = 2.625;
f = test_TDN_solve_dim(3, 1.0, 1.0/3.0, 1.0/2.0, actual, 2.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDN dim=2 B");
s += f;
actual[0] = 99.0/140.0;
actual[1] = 41.0/35.0;
actual[2] = 19.0/10.0;
actual[3] = 72.0/35.0;
actual[4] = 139.0/35.0;
f = test_TDN_solve_dim(5, 1.0, 1.0/4.0, 1.0/2.0, actual, 35.0/8.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDN dim=5");
s += f;
return s;
}
int
test_TDN_cyc_solve_dim(unsigned long dim, double d, double a, double b, const double * actual, double eps)
{
int s = 0;
unsigned long i;
gsl_vector * abovediag = vector_alloc(dim);
gsl_vector * belowdiag = vector_alloc(dim);
gsl_vector * diag = vector_alloc(dim);
gsl_vector * rhs = vector_alloc(dim);
gsl_vector * x = vector_alloc(dim);
for(i=0; i<dim; i++) {
gsl_vector_set(diag, i, d);
gsl_vector_set(rhs, i, i + 1.0);
}
for(i=0; i<dim; i++) {
gsl_vector_set(abovediag, i, a);
gsl_vector_set(belowdiag, i, b);
}
s += gsl_linalg_solve_cyc_tridiag(diag, abovediag, belowdiag, rhs, x);
for(i=0; i<dim; i++) {
double si = gsl_vector_get(x, i);
double ai = actual[i];
int foo = check(si, ai, eps);
if(foo) {
printf("%3lu[%lu]: %22.18g %22.18g\n", dim, i, gsl_vector_get(x, i), actual[i]);
}
s += foo;
}
vector_free(x);
vector_free(rhs);
vector_free(diag);
vector_free(abovediag);
vector_free(belowdiag);
return s;
}
int test_TDN_cyc_solve(void)
{
int f;
int s = 0;
double actual[16];
actual[0] = 3.0/2.0;
actual[1] = -1.0/2.0;
actual[2] = 1.0/2.0;
f = test_TDN_cyc_solve_dim(3, 1.0, 2.0, 1.0, actual, 32.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDN_cyc dim=2 A");
s += f;
actual[0] = -5.0/22.0;
actual[1] = -3.0/22.0;
actual[2] = 29.0/22.0;
actual[3] = -9.0/22.0;
actual[4] = 43.0/22.0;
f = test_TDN_cyc_solve_dim(5, 3.0, 2.0, 1.0, actual, 66.0 * GSL_DBL_EPSILON);
gsl_test(f, " solve_TDN_cyc dim=5");
s += f;
return s;
}
int
test_bidiag_decomp_dim(const gsl_matrix * m, double eps)
{
int s = 0;
unsigned long i,j,k,r, M = m->size1, N = m->size2;
gsl_matrix * A = gsl_matrix_alloc(M,N);
gsl_matrix * a = gsl_matrix_alloc(M,N);
gsl_matrix * b = gsl_matrix_alloc(N,N);
gsl_matrix * u = gsl_matrix_alloc(M,N);
gsl_matrix * v = gsl_matrix_alloc(N,N);
gsl_vector * tau1 = gsl_vector_alloc(N);
gsl_vector * tau2 = gsl_vector_alloc(N-1);
gsl_vector * d = gsl_vector_alloc(N);
gsl_vector * sd = gsl_vector_alloc(N-1);
gsl_matrix_memcpy(A,m);
s += gsl_linalg_bidiag_decomp(A, tau1, tau2);
s += gsl_linalg_bidiag_unpack(A, tau1, u, tau2, v, d, sd);
gsl_matrix_set_zero(b);
for (i = 0; i < N; i++) gsl_matrix_set(b, i,i, gsl_vector_get(d,i));
for (i = 0; i < N-1; i++) gsl_matrix_set(b, i,i+1, gsl_vector_get(sd,i));
/* Compute A = U B V^T */
for (i = 0; i < M ; i++)
{
for (j = 0; j < N; j++)
{
double sum = 0;
for (k = 0; k < N; k++)
{
for (r = 0; r < N; r++)
{
sum += gsl_matrix_get(u, i, k) * gsl_matrix_get (b, k, r)
* gsl_matrix_get(v, j, r);
}
}
gsl_matrix_set (a, i, j, sum);
}
}
for(i=0; i<M; i++) {
for(j=0; j<N; j++) {
double aij = gsl_matrix_get(a, i, j);
double mij = gsl_matrix_get(m, i, j);
int foo = check(aij, mij, eps);
if(foo) {
printf("(%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n", M, N, i,j, aij, mij);
}
s += foo;
}
}
gsl_matrix_free(A);
gsl_matrix_free(a);
gsl_matrix_free(u);
gsl_matrix_free(v);
gsl_matrix_free(b);
gsl_vector_free(tau1);
gsl_vector_free(tau2);
gsl_vector_free(d);
gsl_vector_free(sd);
return s;
}
int test_bidiag_decomp(void)
{
int f;
int s = 0;
f = test_bidiag_decomp_dim(m53, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " bidiag_decomp m(5,3)");
s += f;
f = test_bidiag_decomp_dim(m97, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " bidiag_decomp m(9,7)");
s += f;
f = test_bidiag_decomp_dim(hilb2, 2 * 8.0 * GSL_DBL_EPSILON);
gsl_test(f, " bidiag_decomp hilbert(2)");
s += f;
f = test_bidiag_decomp_dim(hilb3, 2 * 64.0 * GSL_DBL_EPSILON);
gsl_test(f, " bidiag_decomp hilbert(3)");
s += f;
f = test_bidiag_decomp_dim(hilb4, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " bidiag_decomp hilbert(4)");
s += f;
f = test_bidiag_decomp_dim(hilb12, 2 * 1024.0 * GSL_DBL_EPSILON);
gsl_test(f, " bidiag_decomp hilbert(12)");
s += f;
return s;
}
void
my_error_handler (const char *reason, const char *file, int line, int err)
{
if (0) printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err) ;
}
int main(void)
{
gsl_ieee_env_setup ();
gsl_set_error_handler (&my_error_handler);
m11 = create_general_matrix(1,1);
m51 = create_general_matrix(5,1);
m35 = create_general_matrix(3,5);
m53 = create_general_matrix(5,3);
m97 = create_general_matrix(9,7);
s35 = create_singular_matrix(3,5);
s53 = create_singular_matrix(5,3);
hilb2 = create_hilbert_matrix(2);
hilb3 = create_hilbert_matrix(3);
hilb4 = create_hilbert_matrix(4);
hilb12 = create_hilbert_matrix(12);
vander2 = create_vandermonde_matrix(2);
vander3 = create_vandermonde_matrix(3);
vander4 = create_vandermonde_matrix(4);
vander12 = create_vandermonde_matrix(12);
moler10 = create_moler_matrix(10);
c7 = create_complex_matrix(7);
row3 = create_row_matrix(3,3);
row5 = create_row_matrix(5,5);
row12 = create_row_matrix(12,12);
A22 = create_2x2_matrix (0.0, 0.0, 0.0, 0.0);
A33 = gsl_matrix_alloc(3,3);
A44 = gsl_matrix_alloc(4,4);
A55 = gsl_matrix_alloc(5,5);
inf5 = create_diagonal_matrix (inf5_data, 5);
gsl_matrix_set(inf5, 3, 3, GSL_POSINF);
nan5 = create_diagonal_matrix (inf5_data, 5);
gsl_matrix_set(nan5, 3, 3, GSL_NAN);
dblmin3 = create_general_matrix (3, 3);
gsl_matrix_scale(dblmin3, GSL_DBL_MIN);
dblmin5 = create_general_matrix (5, 5);
gsl_matrix_scale(dblmin5, GSL_DBL_MIN);
/* Matmult now obsolete */
#ifdef MATMULT
gsl_test(test_matmult(), "Matrix Multiply");
gsl_test(test_matmult_mod(), "Matrix Multiply with Modification");
#endif
gsl_test(test_bidiag_decomp(), "Bidiagonal Decomposition");
gsl_test(test_LU_solve(), "LU Decomposition and Solve");
gsl_test(test_LUc_solve(), "Complex LU Decomposition and Solve");
gsl_test(test_QR_decomp(), "QR Decomposition");
gsl_test(test_QR_solve(), "QR Solve");
gsl_test(test_LQ_solve(), "LQ Solve");
gsl_test(test_PTLQ_solve(), "PTLQ Solve");
gsl_test(test_LQ_decomp(), "LQ Decomposition");
gsl_test(test_LQ_LQsolve(), "LQ LQ Solve");
gsl_test(test_LQ_lssolve(), "LQ LS Solve");
gsl_test(test_LQ_update(), "LQ Rank-1 Update");
gsl_test(test_QRPT_decomp(), "PTLQ Decomposition");
gsl_test(test_PTLQ_solve(), "PTLQ Solve");
gsl_test(test_QR_QRsolve(), "QR QR Solve");
gsl_test(test_QR_lssolve(), "QR LS Solve");
gsl_test(test_QR_update(), "QR Rank-1 Update");
gsl_test(test_QRPT_decomp(), "QRPT Decomposition");
gsl_test(test_QRPT_solve(), "QRPT Solve");
gsl_test(test_QRPT_QRsolve(), "QRPT QR Solve");
gsl_test(test_QRPT_update(), "QRPT Rank-1 Update");
gsl_test(test_SV_decomp(), "Singular Value Decomposition");
gsl_test(test_SV_decomp_jacobi(), "Singular Value Decomposition (Jacobi)");
gsl_test(test_SV_decomp_mod(), "Singular Value Decomposition (Mod)");
gsl_test(test_SV_solve(), "SVD Solve");
gsl_test(test_cholesky_decomp(), "Cholesky Decomposition");
gsl_test(test_cholesky_decomp_unit(), "Cholesky Decomposition [unit triangular]");
gsl_test(test_cholesky_solve(), "Cholesky Solve");
gsl_test(test_cholesky_invert(), "Cholesky Inverse");
gsl_test(test_choleskyc_decomp(), "Complex Cholesky Decomposition");
gsl_test(test_choleskyc_solve(), "Complex Cholesky Solve");
gsl_test(test_HH_solve(), "Householder solve");
gsl_test(test_TDS_solve(), "Tridiagonal symmetric solve");
gsl_test(test_TDS_cyc_solve(), "Tridiagonal symmetric cyclic solve");
gsl_test(test_TDN_solve(), "Tridiagonal nonsymmetric solve");
gsl_test(test_TDN_cyc_solve(), "Tridiagonal nonsymmetric cyclic solve");
gsl_matrix_free(m11);
gsl_matrix_free(m35);
gsl_matrix_free(m51);
gsl_matrix_free(m53);
gsl_matrix_free(m97);
gsl_matrix_free(s35);
gsl_matrix_free(s53);
gsl_matrix_free(hilb2);
gsl_matrix_free(hilb3);
gsl_matrix_free(hilb4);
gsl_matrix_free(hilb12);
gsl_matrix_free(vander2);
gsl_matrix_free(vander3);
gsl_matrix_free(vander4);
gsl_matrix_free(vander12);
gsl_matrix_free(moler10);
gsl_matrix_complex_free(c7);
gsl_matrix_free(row3);
gsl_matrix_free(row5);
gsl_matrix_free(row12);
gsl_matrix_free(A22);
gsl_matrix_free(A33);
gsl_matrix_free(A44);
gsl_matrix_free(A55);
gsl_matrix_free (inf5);
gsl_matrix_free (nan5);
gsl_matrix_free (dblmin3);
gsl_matrix_free (dblmin5);
exit (gsl_test_summary());
}
| {
"alphanum_fraction": 0.6081234884,
"avg_line_length": 26.7453032105,
"ext": "c",
"hexsha": "d098e22135bd4d1e69087899ba5e43cc5b3412ae",
"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/linalg/test.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/linalg/test.c",
"max_line_length": 117,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "0cb4635af7602f2a243a9b739e5ed757424ab2a7",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "mattjr/structured",
"max_stars_repo_path": "CMVS-PMVS/program/thirdParty/gsl-1.13/linalg/test.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": 41206,
"size": 112464
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//#include <nubspline.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
extern void* xcalloc(int NumPoints, int size);
/*void eval_NUBspline_1d_d(NUBspline_1d_d * restrict spline, double x,
double* restrict val);
void eval_NUBspline_1d_d_vg(NUBspline_1d_d * restrict spline, double x,
double* restrict val, double* restrict grad);
void eval_NUBspline_1d_d_vgl(NUBspline_1d_d * restrict spline, double x,
double* restrict val, double* restrict grad, double* restrict lapl);
void InterpolateWithSplines(int NumPointsToInterpolate, int NumPointsToEvaluate, double* x, double* y, double* NodalX, double* NodalY, double *func, double *NodalFunc, double* NodalDeriv)
{
double *s = xcalloc(NumPointsToInterpolate, sizeof(double));
double *NodalS = xcalloc(NumPointsToEvaluate, sizeof(double));
for (int j = 0; j < NumPointsToInterpolate; j++)
{
s[i] = sqrt(pow(x[j]-x[0],2)+pow(y[j]-y[0],2));
}
for(int j = 0; j < NumPointsToEvaluate, j++)
{
NodalS[i] = sqrt(pow(NodalX[j] -x[0],2) + pow(NodalY[j]-y[0],2));
}
NUgrid* myGrid = create_general_grid(s, NumPointsToInterpolate);
BCtype_d myBC;
myBC.lCode = NATURAL;
myBC.rCode = NATURAL;
NUBspline_1d_d *mySpline = create_NUBspline_1d_d(myGrid, myBC, func);
for(int i =0; i < NumPointsToEvaluate; i++)
{
if (NodalDeriv != NULL)
eval_NUBspline_1d_d_vg(mySpline, NodalS[i], &NodalFunc[i], &NodalDeriv[i]);
else
eval_NUBspline_1d_d(mySpline, NodalS[i], &NodalFunc[i]);
}
free(s);
free(NodalS);
}
*/
void InterpolateWithGSLSplines(int NumPointsToInterpolate, int NumPointsToEvaluate, double* x, double* y, double* NodalX, double* NodalY, double* func, double* NodalFunc, double* NodalDeriv)
{
double *s = xcalloc(NumPointsToInterpolate, sizeof(double));
double *NodalS = xcalloc(NumPointsToEvaluate, sizeof(double));
for (int j = 0; j < NumPointsToInterpolate; j++)
{
s[j] = sqrt(pow(x[j]-x[0],2)+pow(y[j]-y[0],2));
}
for(int j = 0; j < NumPointsToEvaluate; j++)
{
NodalS[j] = sqrt(pow(NodalX[j] -x[0],2) + pow(NodalY[j]-y[0],2));
}
gsl_interp_accel *acc = gsl_interp_accel_alloc();
gsl_spline* spline = gsl_spline_alloc(gsl_interp_cspline, NumPointsToInterpolate);
gsl_spline_init(spline, s, func, NumPointsToInterpolate);
for(int j = 0; j < NumPointsToEvaluate; j++)
{
NodalFunc[j] = gsl_spline_eval(spline, NodalS[j], acc);
if (NodalDeriv != NULL)
NodalDeriv[j] = gsl_spline_eval_deriv(spline, NodalS[j], acc);
}
gsl_interp_accel_free(acc);
gsl_spline_free(spline);
free(s);
free(NodalS);
}
| {
"alphanum_fraction": 0.7125145293,
"avg_line_length": 29.6666666667,
"ext": "c",
"hexsha": "e626c85af63af82620f11411651bedd19e36a6c1",
"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": "DGSHED/spline_interpolation.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": "DGSHED/spline_interpolation.c",
"max_line_length": 190,
"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": "DGSHED/spline_interpolation.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": 877,
"size": 2581
} |
/* eigen/schur.h
*
* Copyright (C) 2006 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_SCHUR_H__
#define __GSL_SCHUR_H__
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_complex.h>
/*
* Prototypes
*/
void gsl_schur_standardize(gsl_matrix *T, size_t row, gsl_complex *eval1,
gsl_complex *eval2, int update_t, gsl_matrix *Z);
#endif /* __GSL_SCHUR_H__ */
| {
"alphanum_fraction": 0.7244525547,
"avg_line_length": 32.2352941176,
"ext": "h",
"hexsha": "17d87a0e81d2487dbcf0c95d6bf376ba9c4501eb",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/eigen/schur.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/eigen/schur.h",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/eigen/schur.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 280,
"size": 1096
} |
#ifndef _POLIFITGSL_H
#define _POLIFITGSL_H
#include <gsl_multifit.h>
#include <stdbool.h>
#include <math.h>
bool polynomialfit(int obs, int degree,
double *dx, double *dy, double *store); /* n, p */
#endif
| {
"alphanum_fraction": 0.7089201878,
"avg_line_length": 23.6666666667,
"ext": "h",
"hexsha": "6fde4bc984fd66c4a6ce88fbf0372a38a69e6799",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-30T20:40:25.000Z",
"max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ruslankuzmin/julia",
"max_forks_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/polifitgsl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"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": "ruslankuzmin/julia",
"max_issues_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/polifitgsl.h",
"max_line_length": 55,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "oldjuila/juliakernel/ext_libraries/gsl/polifitgsl.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 67,
"size": 213
} |
#ifndef DART_POINTERS_H
#define DART_POINTERS_H
/*----- System Includes -----*/
#include <atomic>
#include <memory>
#include <gsl/gsl>
#include <stdint.h>
#include <functional>
#include <type_traits>
/*----- System Includes -----*/
#include "../refcount_traits.h"
/*----- Type Declarations -----*/
namespace dart {
namespace detail {
template <class T>
struct managed_ptr_deleter {
void operator ()(T ptr);
};
template <class T>
struct managed_ptr_deleter<T[]> {
void operator ()(std::remove_extent_t<T>* ptr);
};
// Type-erasure mechanism for counted_ptr_base.
template <class Counter>
struct managed_ptr {
managed_ptr(void* ptr, int64_t use_count) : ptr(ptr), use_count(use_count) {}
virtual ~managed_ptr() = default;
virtual void destroy() = 0;
void* ptr;
Counter use_count;
};
template <class Counter, class PtrType, class Deleter>
struct managed_ptr_eraser : managed_ptr<Counter> {
managed_ptr_eraser(void const* ptr, int64_t use_count) : managed_ptr<Counter>(const_cast<void*>(ptr), use_count) {}
managed_ptr_eraser(void const* ptr, int64_t use_count, Deleter const& deleter) :
managed_ptr<Counter>(const_cast<void*>(ptr), use_count),
deleter(deleter)
{}
managed_ptr_eraser(void const* ptr, int64_t use_count, Deleter&& deleter) :
managed_ptr<Counter>(const_cast<void*>(ptr), use_count),
deleter(std::move(deleter))
{}
virtual void destroy() override;
Deleter deleter;
};
template <class T, class Counter>
class counted_ptr_base {
public:
/*----- Public Types -----*/
using element_type = T;
using counter_type = Counter;
template <class U>
using ptr_type = std::conditional_t<std::is_array<U>::value, U, U*>;
/*----- Lifecycle Functions -----*/
counted_ptr_base() noexcept : value(nullptr) {}
counted_ptr_base(std::nullptr_t) noexcept : value(nullptr) {}
explicit counted_ptr_base(ptr_type<T> ptr) :
value(new managed_ptr_eraser<counter_type, ptr_type<T>, managed_ptr_deleter<ptr_type<T>>>(ptr, 1))
{}
template <class Deleter>
counted_ptr_base(ptr_type<T> ptr, Deleter&& deleter) :
value(new managed_ptr_eraser<counter_type, ptr_type<T>, Deleter>(ptr, 1, std::move(deleter)))
{}
template <class U, class EnableIf =
std::enable_if_t<
std::is_convertible<ptr_type<U>, ptr_type<T>>::value
>
>
counted_ptr_base(counted_ptr_base<U, counter_type> const& other) noexcept;
template <class U, class EnableIf =
std::enable_if_t<
std::is_convertible<ptr_type<U>, ptr_type<T>>::value
>
>
counted_ptr_base(counted_ptr_base<U, counter_type>&& other) noexcept;
template <class U, class Deleter, class EnableIf =
std::enable_if_t<
std::is_same<ptr_type<U>, ptr_type<T>>::value
||
std::is_convertible<ptr_type<U>, ptr_type<T>>::value
>
>
counted_ptr_base(std::unique_ptr<U, Deleter>&& ptr);
counted_ptr_base(counted_ptr_base const& other) noexcept;
counted_ptr_base(counted_ptr_base&& other) noexcept;
~counted_ptr_base() noexcept;
/*----- Operators -----*/
// Assignment.
template <class U, class EnableIf =
std::enable_if_t<
std::is_convertible<ptr_type<U>, ptr_type<T>>::value
>
>
counted_ptr_base& operator =(counted_ptr_base<U, counter_type> const& other) noexcept;
template <class U, class EnableIf =
std::enable_if_t<
std::is_convertible<ptr_type<U>, ptr_type<T>>::value
>
>
counted_ptr_base& operator =(counted_ptr_base<U, counter_type>&& other) noexcept;
counted_ptr_base& operator =(counted_ptr_base const& other) noexcept;
counted_ptr_base& operator =(counted_ptr_base&& other) noexcept;
template <class U, class Deleter, class EnableIf =
std::enable_if_t<
std::is_convertible<ptr_type<U>, ptr_type<T>>::value
>
>
counted_ptr_base& operator =(std::unique_ptr<U, Deleter>&& ptr)
noexcept(std::is_nothrow_move_constructible<Deleter>::value);
// Comparison.
bool operator ==(counted_ptr_base const& other) const noexcept;
bool operator !=(counted_ptr_base const& other) const noexcept;
bool operator <(counted_ptr_base const& other) const noexcept;
bool operator <=(counted_ptr_base const& other) const noexcept;
bool operator >(counted_ptr_base const& other) const noexcept;
bool operator >=(counted_ptr_base const& other) const noexcept;
// Conversion.
explicit operator bool() const noexcept;
/*----- Public API -----*/
// Accessors.
std::remove_extent_t<element_type>* get() const noexcept;
bool unique() const noexcept;
int64_t use_count() const noexcept;
// Mutators.
void reset() noexcept;
template <class U, class EnableIf =
std::enable_if_t<
std::is_convertible<U, ptr_type<T>>::value
>
>
void reset(U ptr);
template <class U, class Deleter, class EnableIf =
std::enable_if_t<
std::is_convertible<U, ptr_type<T>>::value
>
>
void reset(U ptr, Deleter&& deleter);
protected:
/*----- Protected Members -----*/
gsl::owner<managed_ptr<counter_type>*> value;
/*----- Friends -----*/
template <class U, class C>
friend class counted_ptr_base;
};
template <class T, class Counter>
struct counted_ptr_impl : counted_ptr_base<T, Counter> {
/*----- Types -----*/
using typename counted_ptr_base<T, Counter>::element_type;
/*----- Lifecycle Functions -----*/
using counted_ptr_base<T, Counter>::counted_ptr_base;
/*----- Operators -----*/
// Dereference.
auto operator *() const noexcept -> element_type&;
auto operator ->() const noexcept -> element_type*;
// Comparison.
using counted_ptr_base<T, Counter>::operator ==;
using counted_ptr_base<T, Counter>::operator !=;
using counted_ptr_base<T, Counter>::operator <;
using counted_ptr_base<T, Counter>::operator <=;
using counted_ptr_base<T, Counter>::operator >;
using counted_ptr_base<T, Counter>::operator >=;
using counted_ptr_base<T, Counter>::operator bool;
};
template <class T, class Counter>
struct counted_array_ptr_impl : counted_ptr_base<T, Counter> {
/*----- Types -----*/
using index_type = std::ptrdiff_t;
using element_type = std::remove_extent_t<typename counted_ptr_base<T, Counter>::element_type>;
/*----- Lifecycle Functions -----*/
using counted_ptr_base<T, Counter>::counted_ptr_base;
/*----- Operators -----*/
// Derefence.
element_type& operator [](index_type idx) const noexcept;
// Comparison.
using counted_ptr_base<T, Counter>::operator ==;
using counted_ptr_base<T, Counter>::operator !=;
using counted_ptr_base<T, Counter>::operator <;
using counted_ptr_base<T, Counter>::operator <=;
using counted_ptr_base<T, Counter>::operator >;
using counted_ptr_base<T, Counter>::operator >=;
using counted_ptr_base<T, Counter>::operator bool;
};
}
template <class T>
class shareable_ptr {
public:
/*----- Public Types -----*/
using value_type = T;
using element_type = typename refcount_traits<T>::element_type;
private:
struct is_nothrow_assignable :
meta::conjunction<
typename refcount_traits<T>::is_nothrow_copyable,
typename refcount_traits<T>::is_nothrow_moveable
>
{};
// XXX: MSVC gets confused if this is used directly in a noexcept specification.
struct is_nothrow_default_constructible :
std::integral_constant<bool,
refcount_traits<T>::template can_nothrow_take<element_type*, std::default_delete<element_type>>::value
>
{};
public:
/*----- Lifecycle Functions -----*/
// Converting constructors.
shareable_ptr(std::nullptr_t)
noexcept(is_nothrow_default_constructible::value) :
shareable_ptr()
{}
template <class U, class D, class EnableIf =
std::enable_if_t<
refcount::can_take<T, U*, D>::value
>
>
explicit shareable_ptr(std::unique_ptr<U, D>&& ptr)
noexcept(refcount_traits<T>::template can_nothrow_take<U*, D>::value);
shareable_ptr(T const& other) noexcept(refcount_traits<T>::is_nothrow_copyable::value);
shareable_ptr(T&& other) noexcept(refcount_traits<T>::is_nothrow_moveable::value);
// Ownership transfer constructors.
template <class U, class =
std::enable_if_t<
refcount::can_take<T, U*, std::default_delete<U>>::value
>
>
explicit shareable_ptr(U* owner)
noexcept(refcount_traits<T>::template can_nothrow_take<U*, std::default_delete<U>>::value) :
shareable_ptr(owner, std::default_delete<U> {})
{}
template <class U, class D, class EnableIf =
std::enable_if_t<
refcount::can_take<T, U*, D>::value
>
>
explicit shareable_ptr(U* owner, D&& del)
noexcept(refcount_traits<T>::template can_nothrow_take<U*, D>::value);
// Special Constructors.
shareable_ptr() noexcept(is_nothrow_default_constructible::value);
shareable_ptr(shareable_ptr const& other) noexcept(refcount_traits<T>::is_nothrow_copyable::value);
shareable_ptr(shareable_ptr&& other) noexcept(refcount_traits<T>::is_nothrow_moveable::value);
~shareable_ptr() noexcept;
/*----- Operators -----*/
// Assignment.
template <class U, class D, class EnableIf =
std::enable_if_t<
refcount::can_take<T, U*, D>::value
>
>
shareable_ptr& operator =(std::unique_ptr<U, D>&& ptr)
noexcept(refcount_traits<T>::template can_nothrow_take<U*, D>::value);
shareable_ptr& operator =(T const& other) noexcept(is_nothrow_assignable::value);
shareable_ptr& operator =(T&& other) noexcept;
shareable_ptr& operator =(std::nullptr_t) noexcept(is_nothrow_default_constructible::value);
shareable_ptr& operator =(shareable_ptr const& other) noexcept(is_nothrow_assignable::value);
shareable_ptr& operator =(shareable_ptr&& other) noexcept;
// Dereference.
auto operator *() const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value) -> element_type&;
auto operator ->() const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value) -> element_type*;
// Comparison.
bool operator ==(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);
bool operator !=(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);
bool operator <(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);
bool operator <=(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);
bool operator >(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);
bool operator >=(shareable_ptr const& other) const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);
// Conversion.
explicit operator bool() const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value);
/*----- Public API -----*/
// Accessors.
auto get() const noexcept(refcount_traits<T>::is_nothrow_unwrappable::value) -> element_type*;
bool unique() const noexcept(refcount_traits<T>::has_nothrow_use_count::value);
int64_t use_count() const noexcept(refcount_traits<T>::has_nothrow_use_count::value);
// Mutators.
void reset() noexcept(refcount_traits<T>::has_nothrow_reset::value);
// Extremely awkward "copy-constructor" that allows us to copy our
// wrapped value into a raw instance of T.
// Function has to be written this way since we can't assume T is copyable/moveable
// The only thing we can definitely do with T is pass it into dart::refcount_traits::copy.
void share(T& ptr) const noexcept(refcount_traits<T>::is_nothrow_copyable::value);
// Extremely awkward "move-constructor" that allows us to move our
// wrapped value into a raw instance of T.
// Function has to be written this way since we can't assume T is copyable/moveable
// The only thing we can definitely do with T is pass it into dart::refcount_traits::move.
void transfer(T& ptr) && noexcept(refcount_traits<T>::is_nothrow_moveable::value);
auto raw() noexcept -> value_type&;
auto raw() const noexcept -> value_type const&;
private:
/*----- Private Types -----*/
struct partial_construction_tag {};
/*----- Private Lifecycle Functions -----*/
shareable_ptr(partial_construction_tag) {}
/*----- Private Members -----*/
union {
value_type impl;
};
/*----- Friends -----*/
template <class U, class... Args>
friend shareable_ptr<U> make_shareable(Args&&...);
};
template <template <class> class RefCount>
struct view_ptr_context {
template <class T>
class view_ptr {
public:
/*----- Public Types -----*/
using refcount_type = RefCount<T>;
using is_nonowning = refcount_type;
using element_type = typename refcount_traits<refcount_type>::element_type;
// XXX: Necessary to make logic in refcount_traits work.
template <template <template <class> class> class Binder>
using refcount_rebind = Binder<RefCount>;
/*----- Lifecycle Functions -----*/
// Functions must exist for refcount concept, but will throw if called
// as view_ptr doesn't have ownership semantics
explicit view_ptr(T*);
template <class Del>
explicit view_ptr(T*, Del&&);
// I'm not currently disallowing construction from temporaries
// I can imagine scenarios where it could be useful, and generally,
// you'll need to know what you're doing to work with the view types
view_ptr(std::nullptr_t) noexcept : view_ptr() {}
view_ptr(refcount_type const& owner) noexcept : impl(&owner) {}
// Lifecycle functions mostly do nothing
view_ptr() noexcept : impl(nullptr) {}
view_ptr(view_ptr const&) = default;
view_ptr(view_ptr&& other) noexcept;
~view_ptr() = default;
/*----- Operators -----*/
auto operator =(refcount_type const& owner) noexcept -> view_ptr&;
auto operator =(view_ptr const&) -> view_ptr& = default;
auto operator =(view_ptr&& other) noexcept -> view_ptr&;
auto operator *() const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value) -> element_type&;
auto operator ->() const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value) -> element_type*;
bool operator ==(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);
bool operator !=(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);
bool operator <(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);
bool operator <=(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);
bool operator >(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);
bool operator >=(view_ptr const& other) const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);
explicit operator bool() const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value);
operator refcount_type const&() const;
/*----- Public API -----*/
auto get() const noexcept(refcount_traits<refcount_type>::is_nothrow_unwrappable::value) -> element_type*;
size_t use_count() const noexcept(refcount_traits<refcount_type>::has_nothrow_use_count::value);
void reset() noexcept;
auto raw() const noexcept -> refcount_type const&;
private:
/*----- Private Members -----*/
refcount_type const* impl;
};
};
template <class T>
using unsafe_ptr = std::conditional_t<
std::is_same<
std::remove_extent_t<T>,
T
>::value,
detail::counted_ptr_impl<T, int64_t>,
detail::counted_array_ptr_impl<T, int64_t>
>;
template <class T, class EnableIf =
std::enable_if_t<
std::is_array<T>::value
>
>
unsafe_ptr<T> make_unsafe(size_t idx);
template <class T, class... Args>
std::enable_if_t<!std::is_array<T>::value, unsafe_ptr<T>> make_unsafe(Args&&... the_args);
template <class T>
using skinny_ptr = std::conditional_t<
std::is_same<
std::remove_extent_t<T>,
T
>::value,
detail::counted_ptr_impl<T, std::atomic<int64_t>>,
detail::counted_array_ptr_impl<T, std::atomic<int64_t>>
>;
template <class T, class EnableIf =
std::enable_if_t<
std::is_array<T>::value
>
>
skinny_ptr<T> make_skinny(size_t idx);
template <class T, class... Args>
std::enable_if_t<!std::is_array<T>::value, skinny_ptr<T>> make_skinny(Args&&... the_args);
}
/*----- Template Implementations -----*/
#include "ptrs.tcc"
#endif
| {
"alphanum_fraction": 0.6442500557,
"avg_line_length": 35.3307086614,
"ext": "h",
"hexsha": "423d1744e39fcd1463354868d362c6c2fbc98d32",
"lang": "C",
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2020-06-11T11:05:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-11T08:05:10.000Z",
"max_forks_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Cfretz244/libdart",
"max_forks_repo_path": "include/dart/support/ptrs.h",
"max_issues_count": 10,
"max_issues_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25",
"max_issues_repo_issues_event_max_datetime": "2020-03-29T03:25:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-05-09T22:37:27.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Cfretz244/libdart",
"max_issues_repo_path": "include/dart/support/ptrs.h",
"max_line_length": 126,
"max_stars_count": 85,
"max_stars_repo_head_hexsha": "987b01aa1f11455ac6aaf89f8e60825e92e6ec25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Cfretz244/libdart",
"max_stars_repo_path": "include/dart/support/ptrs.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-07T16:31:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-09T19:12:25.000Z",
"num_tokens": 4171,
"size": 17948
} |
#ifndef COSMOLOGY_H
#define COSMOLOGY_H
#include <cmath>
//nbody code
#include <NBody.h>
#include <NBodyMath.h>
//gsl code
#include <gsl/gsl_integration.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_plain.h>
#include <gsl/gsl_monte_miser.h>
#include <gsl/gsl_monte_vegas.h>
using namespace std;
using namespace Math;
namespace Cosmology
{
//scale factor function
Double_t ScaleFactorFunc(const Double_t a, const Double_t om, const Double_t xla);
//{return 1/sqrt(1.+om*(1./a-1.)+xla*(pow(a,2.0)-1.));};
//Hubble expansion factor, omegak is diff omega m omegala
Double_t HubbleFunc(const Double_t a, const Double_t Ho, const Double_t om, const Double_t ola);
//Generalized Hubble expansion factor with omega_r=0 and omega_k specified
Double_t HubbleFunc(const Double_t a, const Double_t Ho, const Double_t om, const Double_t ode, const Double_t ok, Double_t alpha=0.0, Double_t wde=-1.0);
//wrapper for integration
/* Double_t HubbleIntFunc(Double_t a, void* params);
double HubbleIntFuncGSL(double a, void* params);
double HubbleIntFuncGSLMonte(double a, size_t dim, void* params);
//wrapper for integration of 1/aH for time calculation.
Double_t aHIntFunc(Double_t a, void* params);
double aHIntFuncGSL(double a, void* params);
double* aHIntFuncGSLMonte(double a, size_t dim, void* params);
*/
//Evaluates the time t (in units of t0) and Hubble parameter (units 1/t0)
//given the expansion factor a (=1 at t=1)
//for cosmological parameters omega0 and lambda0 (evaluated at t=1).
Double_t Timet(const Double_t a, const Double_t om, const Double_t ola);
Double_t Timeh(const Double_t a, const Double_t om, const Double_t ola);
//Growth factor
Double_t GrowthFunc(const Double_t a, const Double_t om, const Double_t ola);
Double_t GrowthFunc(const Double_t a, const Double_t Ho, const Double_t om, const Double_t ode, const Double_t ok, Double_t alpha=0.0, Double_t wde=-1.0);
//window function
Double_t WKR2(const Double_t k, const Double_t R);
//Power Spectra
Double_t PK(const Double_t k, const Double_t ns, const Double_t Amp);
//----Based on Bardeen et al 1986 BBKS
//qBBKS
Double_t qBBSK(const Double_t k, const Double_t ns, const Double_t Omegam, const Double_t h, const Double_t Omegab);
Double_t TBBKS(const Double_t k, const Double_t ns, const Double_t Omegam, const Double_t h, const Double_t Omegab);
//PBBSK here k is in Mpc^-1
Double_t PBBKS(const Double_t k, const Double_t ns, const Double_t Amp, const Double_t Omegam, const Double_t h, const Double_t Omegab=0.);
//----Based on Eisenstien and Hu 1998
//q98
Double_t qEH98(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);
//L98
Double_t LEH98(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);
//C98
Double_t CEH98(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);
//T98
Double_t TEH98(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);
//P98 here k is in Mpc^-1.
Double_t PEH98(const Double_t k, const Double_t ns, const Double_t deltaH, const Double_t clight, const Double_t Ho, const Double_t Omegam, const Double_t h, const Double_t Theta27);
//P98 here k is in Mpc^-1, but just pass amplitude in
Double_t PEH98(const Double_t k, const Double_t ns, const Double_t Amp, const Double_t Omegam, const Double_t h, const Double_t Theta27);
//----P98 with Warm Dark Matter dampenning like term, here k is in Mpc^-1.
Double_t PWDMEH98(const Double_t k, const Double_t ns, const Double_t AMP, const Double_t Omegam, const Double_t h, const Double_t Theta27, const Double_t Rd);
//effective index in k units of Mpc^-1. neff =dlnP/dlnk
//diff L98 by k
Double_t LEH98diff(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);
//diff C98 by k
Double_t CEH98diff(const Double_t k, const Double_t Omegam, const Double_t h, const Double_t Theta27);
Double_t neffEH98(const Double_t k, const Double_t ns, const Double_t Omegam, const Double_t h, const Double_t Theta27);
//----same as above but with Warm Dark Matter dampenning like term, here k is in Mpc^-1.
Double_t neffWDMEH98(const Double_t k, const Double_t ns, const Double_t Omegam, const Double_t h, const Double_t Theta27, const Double_t Rd);
//----Based on preprint of Green et al 04 for zeq>>z>zb and k>kb, zb=150 and kb~1e3 Mpc^-1.
Double_t PGreen04(const Double_t k, const Double_t Amp, const Double_t wm);
//----Based on data from a file not certain how to construct it yet (could use void * to store k and pk arrays.
Double_t PFromFile(const Double_t k, void* params);
// For integrals, void params has form of params[0]=ns;params[1]=Amp;params[2]=Omegam;params[3]=h;
// Must eventually alter so that Omega_Lambda is not assumed to be 1-Omegam
//integrate P(k)k^2dk*4pi/(2pi)^3
Double_t IntegralkkPower(int powerspectype, void *params, int itype=0, bool logint=true);
//integrate W^2(kR)P(k)k^2dk*4pi/(2pi)^3
Double_t IntegralSigma(int powerspectype, Double_t R, void *params, int itype=0, bool logint=true);
//-------------------------------------------------------------------
// Does open-ended romberg integration of the scale factor integral from a1 to a2
// Based on a Numerical Recipes routine
Double_t aintegral(const Double_t a1,const Double_t a2, const Double_t omega, const Double_t xlambda);
}
#endif
| {
"alphanum_fraction": 0.7388919364,
"avg_line_length": 49.7181818182,
"ext": "h",
"hexsha": "998d1c54be404773d948e8935d738e49b39e46b6",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2020-10-23T00:21:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-04-23T02:58:07.000Z",
"max_forks_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ICRAR/NBodylib",
"max_forks_repo_path": "src/Cosmology/Cosmology.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_issues_repo_issues_event_max_datetime": "2021-07-27T06:31:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-21T16:49:12.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ICRAR/NBodylib",
"max_issues_repo_path": "src/Cosmology/Cosmology.h",
"max_line_length": 183,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "10de78dde32d724b7a5ce323ce8ab093b15c61a8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ICRAR/NBodylib",
"max_stars_repo_path": "src/Cosmology/Cosmology.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1625,
"size": 5469
} |
#include <config.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_dft_complex.h>
#include <gsl/gsl_dft_complex_float.h>
#include "complex_internal.h"
#define BASE_DOUBLE
#include "templates_on.h"
#include "dft_source.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "dft_source.c"
#include "templates_off.h"
#undef BASE_FLOAT
| {
"alphanum_fraction": 0.7594936709,
"avg_line_length": 18.2307692308,
"ext": "c",
"hexsha": "26d32a5ae3a5b8aed002d18b6f2fb7d7cdb425b5",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/fft/dft.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/fft/dft.c",
"max_line_length": 38,
"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/fft/dft.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": 123,
"size": 474
} |
#include <errno.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <setjmp.h>
#include <glib.h>
#if GLIB_CHECK_VERSION (2, 6, 0)
# include <glib/gstdio.h>
#endif
#include <gsl/gsl_spline.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_math.h>
#include "asf.h"
#include "float_image.h"
#include "asf_endian.h"
#include "asf_jpeg.h"
#include "asf_view.h"
#ifndef linux
#ifndef darwin
#ifndef win32
static double
round (double arg)
{
return floor (arg + 0.5);
}
#endif // #ifndef win32
#endif // #ifndef darwin
#endif // #ifndef linux
#include "asf_glib.h"
// at 64MB tiles, this is ~1.5GB
static const int MAX_TILES = 24;
// quit blathering?
int quiet = FALSE;
static int data_size(CachedImage *self)
{
switch (self->data_type) {
case GREYSCALE_FLOAT:
return 4;
case RGB_BYTE:
return 3;
case GREYSCALE_BYTE:
return 1;
case RGB_FLOAT:
return 12;
default:
assert(FALSE);
return 0;
}
}
static void print_cache_size(CachedImage *self)
{
int i;
int size=0;
int ds = data_size(self);
for (i=0; i<self->n_tiles; ++i)
size += ds*self->rows_per_tile*self->ns;
asfPrintStatus("Cache size is %.1f megabytes.\n",
(float)size/1024./1024.);
}
static unsigned char *get_pixel(CachedImage *self, int line, int samp)
{
// check if outside the image
static unsigned char zero = 0;
if (line<0 || samp<0 || line >= self->nl || samp >= self->ns)
return &zero;
// size of each pixel
int ds = data_size(self);
int i;
for (i=0; i<self->n_tiles; ++i) {
int rs = self->rowstarts[i];
if (rs >= 0) {
if (line >= rs && line < rs+self->rows_per_tile) {
// found the right cache
assert(self->cache[i]);
// this probably won't ever happen, but here we go anyway
if (self->n_access > 1024*1024*1024) {
asfPrintStatus("Resetting n_access.\n");
for (i=0; i<self->n_tiles; ++i)
self->access_counts[i] = 0;
self->n_access = 1;
}
// mark this as the most recently accessed
self->access_counts[i] = self->n_access++;
// return pointer to the cached value
return &self->cache[i][((line-rs)*self->ns + samp)*ds];
}
}
}
int spot = 0;
if (!self->reached_max_tiles) {
assert(self->cache[self->n_tiles] == NULL);
unsigned char *data = malloc(ds*self->ns*self->rows_per_tile);
if (!data) {
// if this is the first tile -- abort, we are out of memory
if (self->n_tiles == 0)
asfPrintError("Failed to allocate cache of %ld bytes.\n"
"Out of memory.\n",
ds*self->ns*self->rows_per_tile);
// couldn't allocate the next tile -- must dump existing
if (!quiet)
asfPrintStatus("reached max # of tiles: %d\n", self->n_tiles);
print_cache_size(self);
self->reached_max_tiles = TRUE;
} else {
spot = self->n_tiles;
self->cache[spot] = data;
++self->n_tiles;
}
}
if (self->reached_max_tiles) {
// dump an existing cached tile
// not found in the cache -- find least used spot
int least_access_count = self->access_counts[0];
for (i=0; i<self->n_tiles; ++i) {
if (self->access_counts[i] < least_access_count) {
least_access_count = self->access_counts[i];
spot = i;
}
}
}
if (!self->reached_max_tiles && self->n_tiles == MAX_TILES) {
if (!quiet)
asfPrintStatus("Fully loaded with %d tiles.\n", self->n_tiles);
print_cache_size(self);
self->reached_max_tiles = TRUE;
}
// load info from file
assert(spot >= 0 && spot < self->n_tiles);
assert(self->cache[spot] != NULL);
// clear out the cache -- we may not fill up the tile, if
// we are near the end of the file, and we don't want old data
// to appear
int ns = self->ns;
memset(self->cache[spot], 0, ds*ns*self->rows_per_tile);
// update where this cache entry starts
int rs = (line / self->rows_per_tile) * self->rows_per_tile;
self->rowstarts[spot] = rs;
// mark this tile as the most recently accessed
self->access_counts[spot] = self->n_access++;
//printf("Updated entry #%d:\n"
// " row start: %d\n"
// " row end: %d\n"
// " access count: %d\n", spot,
// rs, rs+self->rows_per_tile-1, self->access_counts[spot]);
// ensure we don't read past the end of the file
int rows_to_get = self->rows_per_tile;
if (rs + self->rows_per_tile > self->nl)
rows_to_get = self->nl - rs;
if (!quiet) {
asfPrintStatus("Cache: loading into spot #%d: rows %d-%d\n",
spot, rs, rs+rows_to_get);
//print_cache_size(self);
}
self->client->read_fn(rs, rows_to_get, (void*)(self->cache[spot]),
self->client->read_client_info, self->meta, self->client->data_type);
assert((line-rs)*self->ns + samp <= self->ns*self->rows_per_tile);
return &self->cache[spot][((line-rs)*self->ns + samp)*ds];
}
void load_thumbnail_data(CachedImage *self, int thumb_size_x, int thumb_size_y,
void *dest_void)
{
if (self->entire_image_fits || !self->client->thumb_fn) {
// Either we don't have thumbnailing support from the client,
// or the image will fit entirely in memory. In both cases, we
// can just call get_pixel() on the subset necessary to show
// the image, which will load the entire image into cache.
// (... well, unless it is so huge that our tiles fit between
// the thumbnail grid ... but that's crazy talk)
int ds = data_size(self);
unsigned char *dest = (unsigned char*)dest_void;
// this will fill the cache with the image data
int sf = self->meta->general->line_count / thumb_size_y;
//assert(sf == self->meta->general->sample_count / thumb_size_x);
// supress the "populating cache" msgs when loading the whole thing
quiet=TRUE;
int i,j;
for (i=0; i<thumb_size_y; ++i) {
for (j=0; j<thumb_size_x; ++j) {
// make this independent of the data type
unsigned char *p = get_pixel(self,i*sf,j*sf);
memcpy(dest+(i*thumb_size_x+j)*ds, p, ds);
}
asfPercentMeter((float)i/(thumb_size_y-1));
}
quiet=FALSE;
} else {
self->client->thumb_fn(thumb_size_x, thumb_size_y,
self->meta, self->client->read_client_info, dest_void,
self->client->data_type);
}
}
CachedImage * cached_image_new_from_file(
const char *file, meta_parameters *meta, ClientInterface *client,
ImageStats *stats, ImageStatsRGB *stats_r, ImageStatsRGB *stats_g,
ImageStatsRGB *stats_b)
{
CachedImage *self = MALLOC(sizeof(CachedImage));
asfPrintStatus("Opening cache: %s\n", file);
self->data_type = client->data_type;
assert(self->data_type != UNDEFINED);
self->client = client; // take ownership of this
self->meta = meta; // do NOT take ownership of this
self->stats = stats; // do NOT take ownership of this
self->stats_r = stats_r; // do NOT take ownership of this
self->stats_g = stats_g; // do NOT take ownership of this
self->stats_b = stats_b; // do NOT take ownership of this
// line line_count may have been fudges, if we are multilooking
self->nl = meta->general->line_count;
self->ns = meta->general->sample_count;
asfPrintStatus("Image is %dx%d LxS\n", self->nl, self->ns);
if (client->require_full_load) {
// Use only 1 tile -- load entire image into it
// (client tells us we should do it this way)
// will it fit? Who knows. Assume it will, MALLOC will fail
// if it actually does not.
self->rows_per_tile = self->nl;
} else {
// how many rows per tile?
// We will use ~64 Meg tiles
self->rows_per_tile = 64*1024*1024 / (self->ns*data_size(self));
// test line -- uncomment this for very small tiles
//self->rows_per_tile = 2*1024*1024 / (self->ns*data_size(self));
}
asfPrintStatus("Using %d rows per tile.\n", self->rows_per_tile);
int n_tiles_required = (int)ceil((double)self->nl / self->rows_per_tile);
self->entire_image_fits = n_tiles_required <= MAX_TILES;
// self->entire_image_fits = FALSE; // uncomment to test thumb_fn
// at the beginning, we have no tiles
self->n_tiles = 0;
self->reached_max_tiles = FALSE;
int i;
self->rowstarts = MALLOC(sizeof(int)*MAX_TILES);
self->cache = MALLOC(sizeof(float*)*MAX_TILES);
self->access_counts = MALLOC(sizeof(int)*MAX_TILES);
for (i=0; i<MAX_TILES; ++i) {
self->rowstarts[i] = -1;
self->cache[i] = NULL;
self->access_counts[i] = 0;
}
self->n_access = 0;
asfPrintStatus("Number of tiles required for the entire image: %d\n",
n_tiles_required);
asfPrintStatus("Fits in memory: %s\n",
self->entire_image_fits ? "Yes" : "No");
return self;
}
float cached_image_get_pixel (CachedImage *self, int line, int samp)
{
if (self->data_type == GREYSCALE_FLOAT) {
return *((float*)get_pixel(self, line, samp));
}
else if (self->data_type == GREYSCALE_BYTE) {
return (float) *(get_pixel(self, line, samp));
}
else if (self->data_type == RGB_BYTE || self->data_type == RGB_FLOAT) {
unsigned char r, g, b;
cached_image_get_rgb(self, line, samp, &r, &g, &b);
return ((float)r + (float)g + (float)b)/3.;
}
// not reached
assert(0);
return 0;
}
void cached_image_get_rgb(CachedImage *self, int line, int samp,
unsigned char *r, unsigned char *g,
unsigned char *b)
{
if (self->data_type == GREYSCALE_FLOAT) {
float f = cached_image_get_pixel(self, line, samp);
if (have_lut()) {
// do not scale in the case of a lut
apply_lut((int)f, r, g, b);
} else {
*r = *g = *b =
(unsigned char)calc_scaled_pixel_value(self->stats, f);
}
}
else if (self->data_type == GREYSCALE_BYTE) {
if (have_lut()) {
apply_lut((int)(*(get_pixel(self, line, samp))), r, g, b);
}
else {
float f = (float) *(get_pixel(self, line, samp));
*r = *g = *b =
(unsigned char)calc_scaled_pixel_value(self->stats, f);
}
}
else if (self->data_type == RGB_BYTE) {
unsigned char *uc = get_pixel(self, line, samp);
*r = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_r,
(float)uc[0]);
*g = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_g,
(float)uc[1]);
*b = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_b,
(float)uc[2]);
}
else if (self->data_type == RGB_FLOAT) {
float *f = (float*)get_pixel(self, line, samp);
*r = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_r,f[0]);
*g = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_g,f[1]);
*b = (unsigned char)calc_rgb_scaled_pixel_value(self->stats_b,f[2]);
}
else {
// impossible!
assert(0);
*r = *g = *b = 0;
}
}
void cached_image_get_rgb_float(CachedImage *self, int line, int samp,
float *r, float *g, float *b)
{
if (self->data_type == GREYSCALE_FLOAT) {
float f = cached_image_get_pixel(self, line, samp);
*r = *g = *b = calc_scaled_pixel_value(self->stats, f);
}
else if (self->data_type == GREYSCALE_BYTE) {
*r = *g = *b = (float)(*(get_pixel(self, line, samp)));
}
else if (self->data_type == RGB_BYTE) {
unsigned char *uc = get_pixel(self, line, samp);
*r = (float)(uc[0]);
*g = (float)(uc[1]);
*b = (float)(uc[2]);
}
else if (self->data_type == RGB_FLOAT) {
float *f = (float*)get_pixel(self, line, samp);
*r = f[0];
*g = f[1];
*b = f[2];
}
else {
// impossible!
assert(0);
*r = *g = *b = 0.;
}
}
void cached_image_free (CachedImage *self)
{
int i;
for (i=0; i<self->n_tiles; ++i) {
if (self->cache[i])
free(self->cache[i]);
}
if (self->client->free_fn)
self->client->free_fn(self->client->read_client_info);
free(self->rowstarts);
free(self->access_counts);
free(self->cache);
free(self->client);
// we do not own the metadata -- don't free it!
free(self);
}
| {
"alphanum_fraction": 0.565158979,
"avg_line_length": 31.6737588652,
"ext": "c",
"hexsha": "d29956e480e1c791fcc599149eaf6f0f13ddf97e",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z",
"max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "glshort/MapReady",
"max_forks_repo_path": "src/asf_view/cache.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"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": "glshort/MapReady",
"max_issues_repo_path": "src/asf_view/cache.c",
"max_line_length": 79,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "glshort/MapReady",
"max_stars_repo_path": "src/asf_view/cache.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z",
"num_tokens": 3604,
"size": 13398
} |
/* addmatrix_gsl.c */
/*
Program to add two variable dimension matrices input by user
*/
// https://www.gnu.org/software/gsl/manual/html_node/Example-programs-for-matrices.html
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_matrix.h>
int main (void)
{
int i, j;
gsl_matrix * m = gsl_matrix_alloc(10, 3);
for (i = 0; i < 10; i++)
for (j = 0; j < 3; j++)
gsl_matrix_set(m, i, j, 0.23 + 100*i + j);
for (i = 0; i < 100; i++) /* OUT OF RANGE ERROR */
for (j = 0; j < 3; j++)
printf("m(%d, %d) = %g\n", i, j,
gsl_matrix_get(m, i, j));
gsl_matrix_free(m);
return 0;
}
| {
"alphanum_fraction": 0.5748792271,
"avg_line_length": 20.0322580645,
"ext": "c",
"hexsha": "08ca8c8d8c05f488dd471d31c0a1afe6614e739f",
"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": "CFitz/addmatrix_gsl.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": "CFitz/addmatrix_gsl.c",
"max_line_length": 87,
"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": "CFitz/addmatrix_gsl.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": 218,
"size": 621
} |
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2018-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#pragma once
#include <gsl/gsl-lite.hpp>
#include <platform/sized_buffer.h>
#include <array>
#include <optional>
#include <type_traits>
namespace cb::mcbp {
/**
* Helper code for encode and decode of LEB128 values.
* - mcbp encodes collection-ID as an unsigned LEB128
* - see https://en.wikipedia.org/wiki/LEB128
*/
// Empty, non specialised version of the decoder class
template <class T, class Enable = void>
class unsigned_leb128 {};
/**
* For encoding a unsigned T leb128, class constructs from a T value and
* provides a const_byte_buffer for access to the encoded
*/
template <class T>
class unsigned_leb128<
T,
typename std::enable_if<std::is_unsigned<T>::value>::type> {
public:
explicit unsigned_leb128(T in) {
while (in > 0) {
auto byte = gsl::narrow_cast<uint8_t>(in & 0x7full);
in >>= 7;
// In has more data?
if (in > 0) {
byte |= 0x80;
encodedData[encodedSize - 1] = byte;
// Increase the size
encodedSize++;
} else {
encodedData[encodedSize - 1] = byte;
}
}
}
cb::const_byte_buffer get() const {
return {encodedData.data(), encodedSize};
}
const uint8_t* begin() const {
return encodedData.data();
}
const uint8_t* end() const {
return encodedData.data() + encodedSize;
}
const uint8_t* data() const {
return encodedData.data();
}
size_t size() const {
return encodedSize;
}
constexpr static size_t getMaxSize() {
return maxSize;
}
/**
* decode returns the decoded T and a const_byte_buffer initialised with the
* data following the leb128 data.
*
* @param buf buffer containing a leb128 encoded value (of size T). This can
* be a prefix on some other data, the decode will only process
* up to the maximum number of bytes permitted for the type T.
* E.g. uint32_t use 5 bytes maximum. buf.size must be >= 1
*
* @returns A std::pair where first is the decoded value and second is a
* buffer initialised with the data following the leb128 data. Note
* if the input buf was 100% only a leb128, the returned buffer
* will point outside of the input buf, but size will be 0.
*
* @throws std::invalid_argument if the input is not a valid leb128, this
* means decode processed 'getMaxSize' bytes without a stop byte.
*/
static std::pair<T, cb::const_byte_buffer> decode(
cb::const_byte_buffer buf);
/**
* decodeCanonical returns the decoded value of type T and a
* const_byte_buffer initialised with the data following the leb128 data.
*
* This version does not throw an exception, but returns failure for two
* reasons.
* - no-stop byte found
* - non-canonical encoding was used, e.g. 0x81.00 instead of 0x01
*
* The caller will have to inspect the input to determine the error.
*
* @param buf buffer containing a leb128 encoded value (of size T). This can
* be a prefix on some other data, the decode will only process
* up to the maximum number of bytes permitted for the type T.
* E.g. uint32_t use 5 bytes maximum. buf.size must be >= 1
*
* @returns On error a std::pair where the second buffer has a nullptr and
* zero size, first is set to 0. On success a std::pair where first
* is the decoded value and second is a buffer initialised with the
* data following the leb128 data. Note if the input buf was 100%
* only a leb128, the returned buffer will point outside of the
* input buf, but size will be 0.
*/
static std::pair<T, cb::const_byte_buffer> decodeCanonical(
cb::const_byte_buffer buf);
/**
* decodeNoThrow returns the decoded value of type T and a const_byte_buffer
* initialised with the data following the leb128 data.
*
* This version does not throw an exception, but returns failure if no-stop
* is byte found.
*
* @param buf buffer containing a leb128 encoded value (of size T). This can
* be a prefix on some other data, the decode will only process
* up to the maximum number of bytes permitted for the type T.
* E.g. uint32_t use 5 bytes maximum. buf.size must be >= 1
*
* @returns On error a std::pair where the second buffer has a nullptr and
* zero size, first is set to 0. On success a std::pair where first
* is the decoded value and second is a buffer initialised with the
* data following the leb128 data. Note if the input buf was 100%
* only a leb128, the returned buffer will point outside of the
* input buf, but size will be 0.
*/
static std::pair<T, cb::const_byte_buffer> decodeNoThrow(
cb::const_byte_buffer buf);
protected:
struct NoThrow {};
/**
* decode returns the decoded value of type T and a const_byte_buffer
* initialised with the data following the leb128 data.
*
* This is the protected inner method used by the public decode, does not
* throw for bad input (allows public methods to decide error fate)
*/
static std::pair<T, cb::const_byte_buffer> decode(cb::const_byte_buffer buf,
NoThrow);
template <typename, typename>
friend class unsigned_leb128;
/**
* Test that a decoded value was encoded in the canonical format.
*
* The test works by examining the length and comparing against a constant.
* The constant is the maximum value that can be encoded as leb128 in
* 'encodedLength - 1' bytes.
*
* For example if the encodedLength was 2 and the value was less than or
* equal to 127, a non-canonical encoding was used, 127 and less can and
* must be encoded in only 1 byte.
*
* So the test when encoded length is 2 is that the value is greater than
* 127. If the encoded length is 3 the value must be greater than 16383 and
* so on.
*
* @param value The integer that was decoded
* @param encodedLength How many bytes the leb128 encoding used
*/
static inline bool is_canonical(uint64_t value, size_t encodedLength);
private:
// Larger T may need a larger array
static_assert(sizeof(T) <= 8, "Class is only valid for uint 8/16/64");
// value is large enough to store ~0 as leb128
static constexpr size_t maxSize = sizeof(T) + (((sizeof(T) + 1) / 8) + 1);
std::array<uint8_t, maxSize> encodedData{};
uint8_t encodedSize{1};
};
// Generate the maximum value that can be encoded in nbytes
#define MAX_LEB128(nbytes) \
((0x7full << ((nbytes - 1) * 7)) | ((1ull << ((nbytes - 1) * 7)) - 1ull))
template <>
inline bool unsigned_leb128<uint8_t>::is_canonical(uint64_t value,
size_t encodedLength) {
return (encodedLength == 2 && value > MAX_LEB128(1)) || encodedLength == 1;
}
template <>
inline bool unsigned_leb128<uint16_t>::is_canonical(uint64_t value,
size_t encodedLength) {
if (unsigned_leb128<uint8_t>::is_canonical(value, encodedLength)) {
return true;
}
return encodedLength == 3 && value > MAX_LEB128(2);
}
template <>
inline bool unsigned_leb128<uint32_t>::is_canonical(uint64_t value,
size_t encodedLength) {
if (unsigned_leb128<uint16_t>::is_canonical(value, encodedLength)) {
return true;
}
switch (encodedLength) {
case 4:
return value > MAX_LEB128(3);
case 5:
return value > MAX_LEB128(4);
}
return false;
}
template <>
inline bool unsigned_leb128<uint64_t>::is_canonical(uint64_t value,
size_t encodedLength) {
// We first have to ask if this is non-canonical for the lower size, e.g.
// u32. Each size asks the lower size first.
if (unsigned_leb128<uint32_t>::is_canonical(value, encodedLength)) {
return true;
}
switch (encodedLength) {
case 6:
return value > MAX_LEB128(5);
case 7:
return value > MAX_LEB128(6);
case 8:
return value > MAX_LEB128(7);
case 9:
return value > MAX_LEB128(8);
case 10:
return value > MAX_LEB128(9);
}
return false;
}
template <class T>
std::pair<T, cb::const_byte_buffer>
unsigned_leb128<T, typename std::enable_if<std::is_unsigned<T>::value>::type>::
decode(cb::const_byte_buffer buf, NoThrow) {
T rv = buf[0] & 0x7full;
size_t end = 0;
// Process up to the end of buf, or the max size for T, this ensures that
// bad input, e.g. no stop-byte avoids invalid shifts (where shift just
// keeps getting better). Primarily this gives us much better control over
// invalid input, e.g. 20 bytes of 0x80 with a stop byte, would of
// previously decoded to 0, but is really not valid input.
size_t size =
std::min(buf.size(), cb::mcbp::unsigned_leb128<T>::getMaxSize());
if ((buf[0] & 0x80) == 0x80ull) {
T shift = 7;
// shift in the remaining data
for (end = 1; end < size; end++) {
rv |= (buf[end] & 0x7full) << shift;
if ((buf[end] & 0x80ull) == 0) {
break; // no more
}
shift += 7;
}
// We should of stopped for a stop byte, not the end of the buffer or
// max encoding
if (end == size) {
return {0, cb::const_byte_buffer{}};
}
}
// Return the decoded value and a buffer for any remaining data
return {rv,
cb::const_byte_buffer{buf.data() + end + 1,
buf.size() - (end + 1)}};
}
template <class T>
std::pair<T, cb::const_byte_buffer>
unsigned_leb128<T, typename std::enable_if<std::is_unsigned<T>::value>::type>::
decode(cb::const_byte_buffer buf) {
if (buf.size() > 0) {
auto rv = unsigned_leb128<T>::decode(buf, NoThrow{});
if (rv.second.data()) {
return rv;
}
}
throw std::invalid_argument(
"`unsigned_leb128::decode invalid leb128 of size:" +
std::to_string(buf.size()));
}
template <class T>
std::pair<T, cb::const_byte_buffer>
unsigned_leb128<T, typename std::enable_if<std::is_unsigned<T>::value>::type>::
decodeCanonical(cb::const_byte_buffer buf) {
auto rv = unsigned_leb128<T>::decode(buf, NoThrow{});
if (rv.second.data() &&
!is_canonical(rv.first, size_t(rv.second.data() - buf.data()))) {
return {0, cb::const_byte_buffer{}};
}
return rv;
}
template <class T>
std::pair<T, cb::const_byte_buffer>
unsigned_leb128<T, typename std::enable_if<std::is_unsigned<T>::value>::type>::
decodeNoThrow(cb::const_byte_buffer buf) {
return unsigned_leb128<T>::decode(buf, NoThrow{});
}
/**
* @return a buffer to the data after the leb128 prefix
*/
template <class T>
typename std::enable_if<std::is_unsigned<T>::value, cb::const_byte_buffer>::type
skip_unsigned_leb128(cb::const_byte_buffer buf) {
return unsigned_leb128<T>::decode(buf).second;
}
/// @return the index of the stop byte within buf
static inline std::optional<size_t> unsigned_leb128_get_stop_byte_index(
cb::const_byte_buffer buf) {
// If buf does not contain a stop-byte, invalid
size_t stopByte = 0;
for (auto c : buf) {
if ((c & 0x80ull) == 0) {
return stopByte;
}
stopByte++;
}
return {};
}
} // namespace cb::mcbp
| {
"alphanum_fraction": 0.6142270862,
"avg_line_length": 35.5057142857,
"ext": "h",
"hexsha": "c17bc6032735c037ab7049fa1b90a6a3bc9d1a4b",
"lang": "C",
"max_forks_count": 71,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T10:34:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-05-22T20:41:59.000Z",
"max_forks_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_forks_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_forks_repo_name": "nawazish-couchbase/kv_engine",
"max_forks_repo_path": "include/mcbp/protocol/unsigned_leb128.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_issues_repo_issues_event_max_datetime": "2022-03-03T11:14:17.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-11-14T08:12:46.000Z",
"max_issues_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_issues_repo_name": "nawazish-couchbase/kv_engine",
"max_issues_repo_path": "include/mcbp/protocol/unsigned_leb128.h",
"max_line_length": 80,
"max_stars_count": 104,
"max_stars_repo_head_hexsha": "132f1bb04c9212bcac9e401d069aeee5f63ff1cd",
"max_stars_repo_licenses": [
"MIT",
"BSD-3-Clause"
],
"max_stars_repo_name": "nawazish-couchbase/kv_engine",
"max_stars_repo_path": "include/mcbp/protocol/unsigned_leb128.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T00:18:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-22T20:41:57.000Z",
"num_tokens": 3145,
"size": 12427
} |
/* ode-initval/gsl_odeiv.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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
*/
#ifndef __GSL_ODEIV_H__
#define __GSL_ODEIV_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* Description of a system of ODEs.
*
* y' = f(t,y) = dydt(t, y)
*
* The system is specified by giving the right-hand-side
* of the equation and possibly a jacobian function.
*
* Some methods require the jacobian function, which calculates
* the matrix dfdy and the vector dfdt. The matrix dfdy conforms
* to the GSL standard, being a continuous range of floating point
* values, in row-order.
*
* As with GSL function objects, user-supplied parameter
* data is also present.
*/
typedef struct
{
int (* function) (double t, const double y[], double dydt[], void * params);
int (* jacobian) (double t, const double y[], double * dfdy, double dfdt[], void * params);
size_t dimension;
void * params;
}
gsl_odeiv_system;
#define GSL_ODEIV_FN_EVAL(S,t,y,f) (*((S)->function))(t,y,f,(S)->params)
#define GSL_ODEIV_JA_EVAL(S,t,y,dfdy,dfdt) (*((S)->jacobian))(t,y,dfdy,dfdt,(S)->params)
/* General stepper object.
*
* Opaque object for stepping an ODE system from t to t+h.
* In general the object has some state which facilitates
* iterating the stepping operation.
*/
typedef struct
{
const char * name;
int can_use_dydt_in;
int gives_exact_dydt_out;
void * (*alloc) (size_t dim);
int (*apply) (void * state, size_t dim, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * dydt);
int (*reset) (void * state, size_t dim);
unsigned int (*order) (void * state);
void (*free) (void * state);
}
gsl_odeiv_step_type;
typedef struct {
const gsl_odeiv_step_type * type;
size_t dimension;
void * state;
}
gsl_odeiv_step;
/* Available stepper types.
*
* rk2 : embedded 2nd(3rd) Runge-Kutta
* rk4 : 4th order (classical) Runge-Kutta
* rkck : embedded 4th(5th) Runge-Kutta, Cash-Karp
* rk8pd : embedded 8th(9th) Runge-Kutta, Prince-Dormand
* rk2imp : implicit 2nd order Runge-Kutta at Gaussian points
* rk4imp : implicit 4th order Runge-Kutta at Gaussian points
* gear1 : M=1 implicit Gear method
* gear2 : M=2 implicit Gear method
*/
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk2;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk4;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rkf45;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rkck;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk8pd;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk2imp;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk2simp;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_rk4imp;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_bsimp;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_gear1;
GSL_VAR const gsl_odeiv_step_type *gsl_odeiv_step_gear2;
/* Constructor for specialized stepper objects.
*/
GSL_FUN gsl_odeiv_step * gsl_odeiv_step_alloc(const gsl_odeiv_step_type * T, size_t dim);
GSL_FUN int gsl_odeiv_step_reset(gsl_odeiv_step * s);
GSL_FUN void gsl_odeiv_step_free(gsl_odeiv_step * s);
/* General stepper object methods.
*/
GSL_FUN const char * gsl_odeiv_step_name(const gsl_odeiv_step * s);
GSL_FUN unsigned int gsl_odeiv_step_order(const gsl_odeiv_step * s);
GSL_FUN int gsl_odeiv_step_apply(gsl_odeiv_step * s, double t, double h, double y[], double yerr[], const double dydt_in[], double dydt_out[], const gsl_odeiv_system * dydt);
/* General step size control object.
*
* The hadjust() method controls the adjustment of
* step size given the result of a step and the error.
* Valid hadjust() methods must return one of the codes below.
*
* The general data can be used by specializations
* to store state and control their heuristics.
*/
typedef struct
{
const char * name;
void * (*alloc) (void);
int (*init) (void * state, double eps_abs, double eps_rel, double a_y, double a_dydt);
int (*hadjust) (void * state, size_t dim, unsigned int ord, const double y[], const double yerr[], const double yp[], double * h);
void (*free) (void * state);
}
gsl_odeiv_control_type;
typedef struct
{
const gsl_odeiv_control_type * type;
void * state;
}
gsl_odeiv_control;
/* Possible return values for an hadjust() evolution method.
*/
#define GSL_ODEIV_HADJ_INC 1 /* step was increased */
#define GSL_ODEIV_HADJ_NIL 0 /* step unchanged */
#define GSL_ODEIV_HADJ_DEC (-1) /* step decreased */
GSL_FUN gsl_odeiv_control * gsl_odeiv_control_alloc(const gsl_odeiv_control_type * T);
GSL_FUN int gsl_odeiv_control_init(gsl_odeiv_control * c, double eps_abs, double eps_rel, double a_y, double a_dydt);
GSL_FUN void gsl_odeiv_control_free(gsl_odeiv_control * c);
GSL_FUN int gsl_odeiv_control_hadjust (gsl_odeiv_control * c, gsl_odeiv_step * s, const double y[], const double yerr[], const double dydt[], double * h);
GSL_FUN const char * gsl_odeiv_control_name(const gsl_odeiv_control * c);
/* Available control object constructors.
*
* The standard control object is a four parameter heuristic
* defined as follows:
* D0 = eps_abs + eps_rel * (a_y |y| + a_dydt h |y'|)
* D1 = |yerr|
* q = consistency order of method (q=4 for 4(5) embedded RK)
* S = safety factor (0.9 say)
*
* / (D0/D1)^(1/(q+1)) D0 >= D1
* h_NEW = S h_OLD * |
* \ (D0/D1)^(1/q) D0 < D1
*
* This encompasses all the standard error scaling methods.
*
* The y method is the standard method with a_y=1, a_dydt=0.
* The yp method is the standard method with a_y=0, a_dydt=1.
*/
GSL_FUN gsl_odeiv_control * gsl_odeiv_control_standard_new(double eps_abs, double eps_rel, double a_y, double a_dydt);
GSL_FUN gsl_odeiv_control * gsl_odeiv_control_y_new(double eps_abs, double eps_rel);
GSL_FUN gsl_odeiv_control * gsl_odeiv_control_yp_new(double eps_abs, double eps_rel);
/* This controller computes errors using different absolute errors for
* each component
*
* D0 = eps_abs * scale_abs[i] + eps_rel * (a_y |y| + a_dydt h |y'|)
*/
GSL_FUN gsl_odeiv_control * gsl_odeiv_control_scaled_new(double eps_abs, double eps_rel, double a_y, double a_dydt, const double scale_abs[], size_t dim);
/* General evolution object.
*/
typedef struct {
size_t dimension;
double * y0;
double * yerr;
double * dydt_in;
double * dydt_out;
double last_step;
unsigned long int count;
unsigned long int failed_steps;
}
gsl_odeiv_evolve;
/* Evolution object methods.
*/
GSL_FUN gsl_odeiv_evolve * gsl_odeiv_evolve_alloc(size_t dim);
GSL_FUN int gsl_odeiv_evolve_apply(gsl_odeiv_evolve * e, gsl_odeiv_control * con, gsl_odeiv_step * step, const gsl_odeiv_system * dydt, double * t, double t1, double * h, double y[]);
GSL_FUN int gsl_odeiv_evolve_reset(gsl_odeiv_evolve * e);
GSL_FUN void gsl_odeiv_evolve_free(gsl_odeiv_evolve * e);
__END_DECLS
#endif /* __GSL_ODEIV_H__ */
| {
"alphanum_fraction": 0.7321055862,
"avg_line_length": 33.7966804979,
"ext": "h",
"hexsha": "0019c74d4f6f15e947cf6d45a9befb41486ef374",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_odeiv.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_odeiv.h",
"max_line_length": 183,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_odeiv.h",
"max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z",
"num_tokens": 2400,
"size": 8145
} |
/******************************************************************************
CosmoLike Configuration Space Covariances for Projected Galaxy 2-Point Statistics
https://github.com/CosmoLike/CosmoCov
by CosmoLike developers
******************************************************************************/
#include <math.h>
#include <stdlib.h>
#if !defined(__APPLE__)
#include <malloc.h>
#endif
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_erf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_legendre.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_sf_expint.h>
#include <gsl/gsl_deriv.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
#include <fftw3.h>
#include "../cosmolike_core/2dfftlog/twobessel.h"
#include "../cosmolike_core/2dfftlog/utils.h"
#include "../cosmolike_core/theory/basics.c"
#include "../cosmolike_core/theory/structs.c"
#include "../cosmolike_core/theory/recompute.c"
#include "../cosmolike_core/theory/cosmo3D.c"
#include "../cosmolike_core/theory/redshift_spline.c"
#include "../cosmolike_core/theory/halo.c"
#include "../cosmolike_core/theory/cosmo2D_fourier.c"
#include "../cosmolike_core/theory/covariances_3D.c"
#include "../cosmolike_core/theory/covariances_fourier.c"
#include "../cosmolike_core/theory/covariances_real_bin_fft.c"
#include "../cosmolike_core/theory/run_covariances_real_bin_fft.c"
#include "init.c"
#include "../cosmolike_core/2dfftlog/utils_complex.h"
#include <time.h>
int main(int argc, char** argv)
{
if (argc != 3){
fprintf(stderr, "Syntax: %s block_number config_file\n", argv[0]);
exit(1);
}
int hit=atoi(argv[1]);
char *inifile;
inifile = argv[2];
FILE *F1,*F2;
int i,l,m,n,o,s,p,output;
double ktmp;
char OUTFILE[400],filename[400];
// set this to one to output details about inputs for diagnostics
output = 0;
FILE *F;
set_cosmological_parameters(inifile,1);
set_survey_parameters(inifile,1);
set_cov_parameters(inifile,1);
init_source_sample(redshift.shear_REDSHIFT_FILE,tomo.shear_Nbin);
init_lens_sample(redshift.clustering_REDSHIFT_FILE,tomo.clustering_Nbin);
if (covparams.lin_bins){
printf("covariances_real_flat_fft does not support linear angular binning\nEXIT\n");exit(1);
}
if (covparams.full_tomo){
printf("covariances_real_flat_fft does not support full cross-zbins clustering yet\nEXIT\n");exit(1);
}
int NG, cNG;
if (covparams.ng==1){
NG = 1;
if (covparams.cng==1){
cNG = 1;
}
else{
cNG = 0;
}
}
else {
NG = 0;
cNG = 0;
}
printf("running multi_covariance_real with NG = %d, cNG = %d\n",NG, cNG);
like.Ntheta=covparams.ntheta;
like.vtmin = covparams.tmin;
like.vtmax = covparams.tmax;
int Ntheta = like.Ntheta;
double *thetamin,*dtheta,*theta;
thetamin=create_double_vector(0,Ntheta);
dtheta=create_double_vector(0,Ntheta-1);
theta=create_double_vector(0,Ntheta-1);
set_angular_binning(thetamin,dtheta);
for (i =0; i< Ntheta; i++){
theta[i] = 2./3.*(pow(thetamin[i+1],3.)-pow(thetamin[i],3.))/(pow(thetamin[i+1],2.)-pow(thetamin[i],2.));
}
int k=1;
if (strcmp(covparams.ss,"true")==0)
{
sprintf(OUTFILE,"%s_ssss_++_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin);
for (l=0;l<tomo.shear_Npowerspectra; l++){
for (m=l;m<tomo.shear_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
run_cov_shear_shear_real_binned(OUTFILE,covparams.outdir,theta,thetamin,dtheta,Ntheta,l,m,1,1,k);
}
k=k+1;
}
}
sprintf(OUTFILE,"%s_ssss_--_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin);
for (l=0;l<tomo.shear_Npowerspectra; l++){
for (m=l;m<tomo.shear_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
run_cov_shear_shear_real_binned(OUTFILE,covparams.outdir,theta,thetamin,dtheta,Ntheta,l,m,0,0,k);
}
k=k+1;
}
}
sprintf(OUTFILE,"%s_ssss_+-_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin);
for (l=0;l<tomo.shear_Npowerspectra; l++){
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
run_cov_shear_shear_real_binned(OUTFILE,covparams.outdir,theta,thetamin,dtheta,Ntheta,l,m,1,0,k);
}
k=k+1;
}
}
}
if (strcmp(covparams.ll,"true")==0)
{
sprintf(OUTFILE,"%s_llll_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Npowerspectra; l++){
for (m=l;m<tomo.clustering_Npowerspectra; m++){
if(k==hit){
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
run_cov_clustering_real_binned(OUTFILE,covparams.outdir,theta,thetamin,dtheta,Ntheta,l,m,k);
}
k=k+1;
}
}
}
if (strcmp(covparams.ls,"true")==0)
{
sprintf(OUTFILE,"%s_lsls_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin);
for (l=0;l<tomo.ggl_Npowerspectra; l++){
for (m=l;m<tomo.ggl_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
run_cov_ggl_real_binned(OUTFILE,covparams.outdir,theta,thetamin,dtheta,Ntheta,l,m,k);
}
k=k+1;
}
}
}
if (strcmp(covparams.ls,"true")==0 && strcmp(covparams.ss,"true")==0)
{
sprintf(OUTFILE,"%s_lsss_+_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin);
for (l=0;l<tomo.ggl_Npowerspectra; l++){
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
run_cov_ggl_shear_real_binned(OUTFILE,covparams.outdir,theta,thetamin,dtheta,Ntheta,l,m,1,k);
}
k=k+1;
}
}
sprintf(OUTFILE,"%s_lsss_-_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin);
for (l=0;l<tomo.ggl_Npowerspectra; l++){
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
run_cov_ggl_shear_real_binned(OUTFILE,covparams.outdir,theta,thetamin,dtheta,Ntheta,l,m,0,k);
}
k=k+1;
}
}
}
if (strcmp(covparams.ll,"true")==0 && strcmp(covparams.ss,"true")==0)
{
sprintf(OUTFILE,"%s_llss_+_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Npowerspectra; l++){
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
run_cov_clustering_shear_real_binned(OUTFILE,covparams.outdir,theta,thetamin,dtheta,Ntheta,l,m,1,k);
}
k=k+1;
}
}
sprintf(OUTFILE,"%s_llss_-_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Npowerspectra; l++){
for (m=0;m<tomo.shear_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
run_cov_clustering_shear_real_binned(OUTFILE,covparams.outdir,theta,thetamin,dtheta,Ntheta,l,m,0,k);
}
k=k+1;
}
}
}
if (strcmp(covparams.ll,"true")==0 && strcmp(covparams.ls,"true")==0)
{
sprintf(OUTFILE,"%s_llls_cov_Ntheta%d_Ntomo%d",covparams.filename,Ntheta,tomo.shear_Nbin);
for (l=0;l<tomo.clustering_Npowerspectra; l++){
for (m=0;m<tomo.ggl_Npowerspectra; m++){
if(k==hit) {
sprintf(filename,"%s%s_%d",covparams.outdir,OUTFILE,k);
run_cov_clustering_ggl_real_binned(OUTFILE,covparams.outdir,theta,thetamin,dtheta,Ntheta,l,m,k);
}
k=k+1;
}
}
}
if (hit==0)
{
sprintf(OUTFILE,"%s%s",covparams.outdir,covparams.filename);
// write_gglensing_zbins(OUTFILE);
sprintf(OUTFILE,"%s%s.blocks",covparams.outdir,covparams.filename);
F1 = fopen(OUTFILE,"w");
fprintf(F1,"%d\n",k-1);
fclose(F1);
}
printf("number of cov blocks for parallelization: %d\n",k-1);
printf("-----------------\n");
printf("PROGRAM EXECUTED\n");
printf("-----------------\n");
return 0;
}
| {
"alphanum_fraction": 0.6471709351,
"avg_line_length": 32.4131274131,
"ext": "c",
"hexsha": "dcce5b6bafbad9c207bcdf478726f888845e0592",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-01-27T11:30:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-04-21T20:17:05.000Z",
"max_forks_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "joezuntz/CosmoCov",
"max_forks_repo_path": "covs/compute_covariances_real_flat_fft.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5",
"max_issues_repo_issues_event_max_datetime": "2021-06-29T16:27:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-12T19:43:54.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "joezuntz/CosmoCov",
"max_issues_repo_path": "covs/compute_covariances_real_flat_fft.c",
"max_line_length": 110,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "a3ed2664573f0d47a192302b3326a2f6743c5ce5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "joezuntz/CosmoCov",
"max_stars_repo_path": "covs/compute_covariances_real_flat_fft.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-31T10:39:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-04-14T00:46:09.000Z",
"num_tokens": 2635,
"size": 8395
} |
#ifndef VERBOSITY_INCLUDE
#define VERBOSITY_INCLUDE
#include <iostream>
#include <gsl/string_span>
#include "config/fleetingOptionsInterface.h"
#include "config/variablesMap.h"
#include "core/task.h"
namespace execHelper {
namespace plugins {
using Verbosity = bool;
const gsl::czstring<> VERBOSITY_KEY = "verbose";
/**
* \brief Extends the functionality to include the _verbose_ config parameter and processes this parameter, using the --verbose flag
*/
struct VerbosityLong {
/*! @copydoc JobsLong::getVariables(config::VariablesMap&, const config::FleetingOptionsInterface&)
*/
static void
getVariables(config::VariablesMap& variables,
const config::FleetingOptionsInterface& options) noexcept;
/*! @copydoc JobsLong::apply(core::Task&, const config::VariablesMap&)
*/
inline static void apply(core::Task& task,
const config::VariablesMap& variables) noexcept {
if(*(variables.get<Verbosity>(VERBOSITY_KEY))) {
task.append("--verbose");
}
}
};
/**
* \brief Extends the functionality to include the _verbose_ config parameter and processes this parameter, using the --debug flag
*/
struct VerbosityDebug {
/*! @copydoc JobsLong::getVariables(config::VariablesMap&, const config::FleetingOptionsInterface&)
*/
inline static void
getVariables(config::VariablesMap& variables,
const config::FleetingOptionsInterface& options) noexcept {
VerbosityLong::getVariables(variables, options);
}
/*! @copydoc JobsLong::apply(core::Task&, const config::VariablesMap&)
*/
inline static void apply(core::Task& task,
const config::VariablesMap& variables) noexcept {
if(*(variables.get<Verbosity>(VERBOSITY_KEY))) {
task.append("--debug");
}
}
};
/**
* \brief Extends the functionality to include the _verbose_ config parameter and processes this parameter, using the -v flag
*/
struct VerbosityShort {
/*! @copydoc JobsLong::getVariables(config::VariablesMap&, const config::FleetingOptionsInterface&)
*/
inline static void
getVariables(config::VariablesMap& variables,
const config::FleetingOptionsInterface& options) noexcept {
VerbosityLong::getVariables(variables, options);
}
/*! @copydoc JobsLong::apply(core::Task&, const config::VariablesMap&)
*/
inline static void apply(core::Task& task,
const config::VariablesMap& variables) noexcept {
if(*(variables.get<Verbosity>(VERBOSITY_KEY))) {
task.append("-v");
}
}
};
} // namespace plugins
} // namespace execHelper
#endif /* VERBOSITY_INCLUDE */
| {
"alphanum_fraction": 0.6663039536,
"avg_line_length": 32.4352941176,
"ext": "h",
"hexsha": "b23ccf417796905976493fdd81f3a250e8c273ec",
"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": "src/plugins/include/plugins/verbosity.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": "src/plugins/include/plugins/verbosity.h",
"max_line_length": 132,
"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": "src/plugins/include/plugins/verbosity.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": 597,
"size": 2757
} |
#pragma once
#include <Python.h> // has to be the first included header
#ifdef HAVE_LAPACK
#include <lapacke.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
class SvdUtility
{
public:
static void getSVD(double input[], int rows, int cols, double leftSingVec[]);
static void getSVD(double input[], int rows, int cols, double leftSingVec[], double sigma[], double rightSingVecT[]);
static void getSVD(double _Complex input[], int rows, int cols, double _Complex leftSingVec[], double sigma[], double _Complex rightSingVecT[]);
static void reconstructSnapshots(int rows, int cols, double leftSingVec[], double sigma[], double rightSingVecT[], double output[]);
static void printMatrix(std::string name, double input[], int rows, int cols);
static vector<double> readCSV(string filename);
static vector<double> readCSV(string filename, int rows);
static void writeCSV(string filename, vector<double> values, int m, int n);
static void writeCSV(string filename, double values[], int m, int n, bool columnWise = false);
static int getCSVRowCount(string filename);
static int getCSVColumnCount(string filename);
};
| {
"alphanum_fraction": 0.7309269893,
"avg_line_length": 27.0888888889,
"ext": "h",
"hexsha": "b9ea0909c55f360705c083ee3973440ba68ee74b",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-05-28T13:24:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-17T12:18:10.000Z",
"max_forks_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "maierbn/opendihu",
"max_forks_repo_path": "core/src/utility/svd_utility.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0",
"max_issues_repo_issues_event_max_datetime": "2020-12-29T15:29:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-11-12T15:15:58.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "maierbn/opendihu",
"max_issues_repo_path": "core/src/utility/svd_utility.h",
"max_line_length": 146,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "maierbn/opendihu",
"max_stars_repo_path": "core/src/utility/svd_utility.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-20T04:46:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-25T19:29:34.000Z",
"num_tokens": 286,
"size": 1219
} |
#ifndef GSL_WRAPPERS_H
#define GSL_WRAPPERS_H
// #include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include <math.h>
#include <assert.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#define outlog(format, args...) \
fprintf(stderr, format, args); \
fprintf(stderr, "\n");
double safe_log(double);
double log_sum(double, double);
static inline double vget(const gsl_vector* v, int i)
{ return(gsl_vector_get(v, i)); };
static inline void vset(gsl_vector* v, int i, double x)
{ gsl_vector_set(v, i, x); };
// Increment a vector element by a double.
void vinc(gsl_vector*, int, double);
static inline double mget(const gsl_matrix* m, int i, int j)
{ return(gsl_matrix_get(m, i, j)); };
static inline void mset(gsl_matrix* m, int i, int j, double x)
{ gsl_matrix_set(m, i, j, x); };
void msetcol(gsl_matrix* m, int r, const gsl_vector* val);
// Increment a matrix element by a double.
void minc(gsl_matrix*, int, int, double);
void msetrow(gsl_matrix*, int, const gsl_vector*);
void col_sum(gsl_matrix*, gsl_vector*);
void vct_printf(const gsl_vector* v);
void mtx_printf(const gsl_matrix* m);
void vct_fscanf(const char*, gsl_vector* v);
void mtx_fscanf(const char*, gsl_matrix* m);
void vct_fprintf(const char* filename, gsl_vector* v);
void mtx_fprintf(const char* filename, const gsl_matrix* m);
double log_det(gsl_matrix*);
void matrix_inverse(gsl_matrix*, gsl_matrix*);
void sym_eigen(gsl_matrix*, gsl_vector*, gsl_matrix*);
double sum(const gsl_vector* v);
double norm(gsl_vector * v);
void vct_log(gsl_vector* v);
void vct_exp(gsl_vector* x);
void choose_k_from_n(int k, int n, int* result);
void log_normalize(gsl_vector* x);
void normalize(gsl_vector* x);
void optimize(int dim,
gsl_vector* x,
void* params,
void (*fdf)(const gsl_vector*, void*, double*, gsl_vector*),
void (*df)(const gsl_vector*, void*, gsl_vector*),
double (*f)(const gsl_vector*, void*));
void optimize_fdf(int dim,
gsl_vector* x,
void* params,
void (*fdf)(const gsl_vector*, void*, double*, gsl_vector*),
void (*df)(const gsl_vector*, void*, gsl_vector*),
double (*f)(const gsl_vector*, void*),
double* f_val,
double* conv_val,
int* niter);
void log_write(FILE* f, char* string);
int directory_exist(const char *dname);
void make_directory(char* name);
gsl_rng* new_random_number_generator();
#endif
| {
"alphanum_fraction": 0.6724875267,
"avg_line_length": 28.06,
"ext": "h",
"hexsha": "02956b0c5ea2da80c20b865be7b6e33c136ac6ba",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z",
"max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "iwangjian/topic-extractor",
"max_forks_repo_path": "scripts/lib/DTM/dtm/gsl-wrappers.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"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": "iwangjian/topic-extractor",
"max_issues_repo_path": "scripts/lib/DTM/dtm/gsl-wrappers.h",
"max_line_length": 78,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "iwangjian/dtm-lab",
"max_stars_repo_path": "scripts/lib/DTM/dtm/gsl-wrappers.h",
"max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z",
"num_tokens": 736,
"size": 2806
} |
// Based on code found in https://github.com/deeplearning4j/libnd4j/blob/master/blas/cpu/NativeBlas.cpp
#include <cblas.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <dlfcn.h>
#endif
static int maxThreads = -1;
static int vendor = 0;
static void blas_set_num_threads(int num) {
typedef void* (*void_int)(int);
typedef int* (*int_int)(int);
typedef int* (*int_int_int)(int, int);
maxThreads = num;
#ifdef __MKL
// if we're linked against mkl - just go for it
MKL_Set_Num_Threads(num);
MKL_Domain_Set_Num_Threads(num, 0); // MKL_DOMAIN_ALL
MKL_Domain_Set_Num_Threads(num, 1); // MKL_DOMAIN_BLAS
MKL_Set_Num_Threads_Local(num);
#elif __OPENBLAS
#ifdef _WIN32
// for win32 we just check for mkl_rt.dll
HMODULE handle = LoadLibrary("mkl_rt.dll");
if (handle != NULL) {
void_int mkl_global = (void_int) GetProcAddress(handle, "MKL_Set_Num_Threads");
if (mkl_global != NULL) {
mkl_global(num);
vendor = 3;
int_int_int mkl_domain = (int_int_int) GetProcAddress(handle, "MKL_Domain_Set_Num_Threads");
if (mkl_domain != NULL) {
mkl_domain(num, 0); // DOMAIN_ALL
mkl_domain(num, 1); // DOMAIN_BLAS
}
int_int mkl_local = (int_int) GetProcAddress(handle, "MKL_Set_Num_Threads_Local");
if (mkl_local != NULL) {
mkl_local(num);
}
} else {
printf("Unable to tune runtime. Please set OMP_NUM_THREADS manually.\n");
}
//FreeLibrary(handle);
} else {
// OpenBLAS path
handle = LoadLibrary("libopenblas.dll");
if (handle != NULL) {
void_int oblas = (void_int) GetProcAddress(handle, "openblas_set_num_threads");
if (oblas != NULL) {
vendor = 2;
oblas(num);
} else {
printf("Unable to tune runtime. Please set OMP_NUM_THREADS manually.\n");
}
//FreeLibrary(handle);
} else {
printf("Unable to guess runtime. Please set OMP_NUM_THREADS manually.\n");
}
}
#else
// it's possible to have MKL being loaded at runtime
void *handle = dlopen("libmkl_rt.so", RTLD_NOW|RTLD_GLOBAL);
if (handle == NULL) {
handle = dlopen("libmkl_rt.dylib", RTLD_NOW|RTLD_GLOBAL);
}
if (handle != NULL) {
// we call for openblas only if libmkl isn't loaded, and openblas_set_num_threads exists
void_int mkl_global = (void_int) dlsym(handle, "MKL_Set_Num_Threads");
if (mkl_global != NULL) {
// we're running against mkl
mkl_global((int) num);
vendor = 3;
int_int_int mkl_domain = (int_int_int) dlsym(handle, "MKL_Domain_Set_Num_Threads");
if (mkl_domain != NULL) {
mkl_domain(num, 0); // DOMAIN_ALL
mkl_domain(num, 1); // DOMAIN_BLAS
}
int_int mkl_local = (int_int) dlsym(handle, "MKL_Set_Num_Threads_Local");
if (mkl_local != NULL) {
mkl_local(num);
}
} else {
printf("Unable to tune runtime. Please set OMP_NUM_THREADS manually.\n");
}
dlclose(handle);
} else {
// we're falling back to bundled OpenBLAS opening libopenblas.so.0
handle = dlopen("libopenblas.so.0", RTLD_NOW|RTLD_GLOBAL);
if (handle == NULL) {
handle = dlopen("libopenblas.so", RTLD_NOW|RTLD_GLOBAL);
}
if (handle == NULL) {
handle = dlopen("libopenblas.dylib", RTLD_NOW|RTLD_GLOBAL);
}
if (handle != NULL) {
void_int oblas = (void_int) dlsym(handle, "openblas_set_num_threads");
if (oblas != NULL) {
vendor = 2;
// we're running against openblas
oblas((int) num);
} else {
printf("Unable to tune runtime. Please set OMP_NUM_THREADS manually.\n");
}
dlclose(handle);
} else printf("Unable to guess runtime. Please set OMP_NUM_THREADS manually.\n");
}
#endif
#else
printf("Unable to guess runtime. Please set OMP_NUM_THREADS or equivalent manually.\n");
#endif
fflush(stdout);
}
static int blas_get_num_threads() {
return maxThreads;
}
/**
* 0 - Unknown
* 1 - cuBLAS
* 2 - OpenBLAS
* 3 - MKL
*/
static int blas_get_vendor() {
return vendor;
}
| {
"alphanum_fraction": 0.589149032,
"avg_line_length": 31.2816901408,
"ext": "h",
"hexsha": "1708246ea9426fa329624b6de003194ba798ad80",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-03-25T06:48:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-25T06:48:42.000Z",
"max_forks_repo_head_hexsha": "20a13b5220d6be33e37b6c8ed6ea30a35361fafc",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "MaxKelsen/javacpp-presets",
"max_forks_repo_path": "openblas/src/main/resources/org/bytedeco/javacpp/include/blas_extra.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "20a13b5220d6be33e37b6c8ed6ea30a35361fafc",
"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": "MaxKelsen/javacpp-presets",
"max_issues_repo_path": "openblas/src/main/resources/org/bytedeco/javacpp/include/blas_extra.h",
"max_line_length": 104,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "20a13b5220d6be33e37b6c8ed6ea30a35361fafc",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "MaxKelsen/javacpp-presets",
"max_stars_repo_path": "openblas/src/main/resources/org/bytedeco/javacpp/include/blas_extra.h",
"max_stars_repo_stars_event_max_datetime": "2020-06-27T01:17:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-27T01:17:09.000Z",
"num_tokens": 1161,
"size": 4442
} |
/*
Project Name : OpenMEEG
© INRIA and ENPC (contributors: Geoffray ADDE, Maureen CLERC, Alexandre
GRAMFORT, Renaud KERIVEN, Jan KYBIC, Perrine LANDREAU, Théodore PAPADOPOULO,
Emmanuel OLIVI
Maureen.Clerc.AT.sophia.inria.fr, keriven.AT.certis.enpc.fr,
kybic.AT.fel.cvut.cz, papadop.AT.sophia.inria.fr)
The OpenMEEG software is a C++ package for solving the forward/inverse
problems of electroencephalography and magnetoencephalography.
This software is governed by the CeCILL-B license under French law and
abiding by the rules of distribution of free software. You can use,
modify and/ or redistribute the software under the terms of the CeCILL-B
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".
As a counterpart to the access to the source code and rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty and the software's authors, the holders of the
economic rights, and the successive licensors have only limited
liability.
In this respect, the user's attention is drawn to the risks associated
with loading, using, modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean that it is complicated to manipulate, and that also
therefore means that it is reserved for developers and experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and, more generally, to use and operate it in the
same conditions as regards security.
The fact that you are presently reading this means that you have had
knowledge of the CeCILL-B license and that you accept its terms.
*/
#pragma once
// cmake configuration.
#include <OpenMEEGConfigure.h>
#include <DLLDefinesOpenMEEGMaths.h>
#ifdef USE_MATIO
#include "matio.h"
#endif
#if !defined(USE_MKL)
#if defined (WIN32) || !defined(USE_ATLAS)
#define FC_GLOBAL(x,X) x ## _
#else
#include <FC.h>
#endif
#endif
//#define inline __forceinline
//#define inline __attribute__((always_inline))
//#define inline __attribute__((weak)) inline
#if WIN32
#pragma inline_recursion (on)
#pragma inline_depth (255)
#pragma warning( disable : 4530) //MSVC standard library can't be inlined
#pragma warning( disable : 4996) //MSVC warning C4996: declared deprecated
#endif
#ifdef USE_ATLAS
#ifdef __APPLE__
extern "C" {
#include <cblas.h>
#include <clapack.h>
}
#define BLAS(x,X) cblas_ ## x
#define LAPACK(x,X) x ## _
// #define LAPACK(x,X) FC_GLOBAL(x,X)
#else
extern "C" {
#include <cblas.h>
#include <clapack.h>
}
#define BLAS(x,X) cblas_ ## x
#define LAPACK(x,X) clapack_ ## x
#endif
#endif
#ifdef USE_MKL
// Hack to avoid the MKL declarations of Lapack Functions which do not use the power of C++ references
#define _MKL_LAPACK_H_
#include <mkl.h>
#define BLAS(x,X) cblas_ ## x
#define LAPACK(x,X) x
#define FC_GLOBAL(x,X) x
#endif
#ifdef USE_ACML
#include <acml.h>
// Those macros are not used yet
#define BLAS(x,X) x
#define LAPACK(x,X) FC_GLOBAL(x,X)
extern "C" void vrda_sin (int n, double *t, double *p);
extern "C" void vrda_cos (int n, double *t, double *p);
extern "C" void vrda_exp (int n, double *t, double *p);
extern "C" void vrda_log (int n, double *t, double *p);
#endif
#if defined(HAVE_BLAS) && !defined(USE_ATLAS) && !defined(USE_ACML)
#ifndef USE_MKL
#define CblasColMajor
#define CblasTrans 'T'
#define CblasNoTrans 'N'
#define CblasRight 'R'
#define CblasLeft 'L'
#define CblasUpper 'U'
#define BLAS(x,X) FC_GLOBAL(x,X)
#define LAPACK(x,X) FC_GLOBAL(x,X)
extern "C" {
void BLAS(dcopy,DCOPY)(const int&,const double*,const int&,double*,const int&);
void BLAS(daxpy,DAXPY)(const int&,const double&,const double*,const int&,double*,const int&);
double BLAS(ddot,DDOT)(const int&,const double*,const int&,const double*,const int&);
double BLAS(dnrm2,DNRM2)(const int&,const double*,const int&);
void BLAS(dscal,DSCAL)(const int&,const double&,double*,const int&);
void BLAS(dger,DGER)(const int&,const int&,const double&,const double*,const int&,const double*,const int&,double*,const int&);
void BLAS(dspmv,DSPMV)(const char&,const int&,const double&,const double*,const double*,const int&,const double&,double*,const int&);
void BLAS(dtpmv,DTPMV)(const char&,const char&,const char&,const int&,const double*,double*,const int&);
void BLAS(dsymm,DSYMM)(const char&,const char&,const int&,const int&,const double&,const double*,const int&,const double*,const int&, const double&,double*,const int&);
void BLAS(dgemm,DGEMM)(const char&,const char&,const int&,const int&,const int&,const double&,const double*,const int&,const double*,const int&,const double&,double*,const int&);
void BLAS(dtrmm,DTRMM)(const char&,const char&,const char&,const char&,const int&,const int&,const double&,const double*,const int&,const double*,const int&);
void BLAS(dgemv,DGEMV)(const char&,const int&,const int&,const double&,const double*,const int&,const double*,const int&,const double&,double*,const int&);
}
#endif
extern "C" {
void LAPACK(dgetrf,DGETRF)(const int&,const int&,double*,const int&,int*,int&);
void LAPACK(dgetri,DGETRI)(const int&,double*,const int&,int*,double*,const int&,int&);
}
#endif
#if defined(HAVE_LAPACK)
extern "C" {
void FC_GLOBAL(dgesdd,DGESDD)(const char&,const int&,const int&,double*,const int&,double*,double*,const int&,double*,const int&,double*,const int&,int*,int&);
void FC_GLOBAL(dpotf2,DPOTF2)(const char&,const int&,double*,const int&,int&);
double FC_GLOBAL(dlange,DLANGE)(const char&,const int&,const int&,const double*,const int&,double*);
void FC_GLOBAL(dsptrf,DSPTRF)(const char&,const int&,double*,int*,int&);
void FC_GLOBAL(dtptri,DTPTRI)(const char&,const char&,const int&,double*,int&,int&);
void FC_GLOBAL(dsptri,DSPTRI)(const char&,const int&,double*,int*,double*,int&);
void FC_GLOBAL(dpptrf,DPPTRF)(const char&,const int&,double*,int&);
void FC_GLOBAL(dpptri,DPPTRI)(const char&,const int&,double*,int&);
void FC_GLOBAL(dspevd,DSPEVD)(const char&,const char&,const int&,double*,double*,double*,const int&,double*,const int&,int*,const int&,int&);
void FC_GLOBAL(dsptrs,DSPTRS)(const char&,const int&,const int&,double*,int*,double*,const int&,int&);
}
#endif
#define DGESDD FC_GLOBAL(dgesdd,DGESDD)
#define DPOTF2 FC_GLOBAL(dpotf2,DPOTF2)
#define DLANGE FC_GLOBAL(dlange,DLANGE)
#define DSPTRF FC_GLOBAL(dsptrf,DSPTRF)
#define DTPTRI FC_GLOBAL(dtptri,DTPTRI)
#define DPPTRF FC_GLOBAL(dpptrf,DPPTRF)
#define DPPTRI FC_GLOBAL(dpptri,DPPTRI)
#define DSPEVD FC_GLOBAL(dspevd,DSPEVD)
#define DSPTRS FC_GLOBAL(dsptrs,DSPTRS)
#if defined(USE_ATLAS) || defined(USE_MKL)
#define DGER(X1,X2,X3,X4,X5,X6,X7,X8,X9) BLAS(dger,DGER)(CblasColMajor,X1,X2,X3,X4,X5,X6,X7,X8,X9)
#define DSPMV(X1,X2,X3,X4,X5,X6,X7,X8,X9) BLAS(dspmv,DSPMV)(CblasColMajor,X1,X2,X3,X4,X5,X6,X7,X8,X9)
#define DTPMV(X1,X2,X3,X4,X5,X6,X7) BLAS(dtpmv,DTPMV)(CblasColMajor,X1,X2,X3,X4,X5,X6,X7)
#define DSYMM(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12) BLAS(dsymm,DSYMM)(CblasColMajor,X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12)
#define DGEMV(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11) BLAS(dgemv,DGEMV)(CblasColMajor,X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11)
#define DGEMM(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,X13) BLAS(dgemm,DGEMM)(CblasColMajor,X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,X13)
#define DTRMM(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11) BLAS(dtrmm,DTRMM)(CblasColMajor,X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11)
#if defined(USE_ATLAS)
#ifdef __APPLE__
#define DGETRF(X1,X2,X3,X4,X5,X6) LAPACK(dgetrf,DGETRF)(&X1,&X2,X3,&X4,X5,&X6)
// #define DGETRF(X1,X2,X3,X4,X5,X6) LAPACK(dgetrf,DGETRF)(CblasColMajor,X1,X2,X3,X4,X5)
#define DGETRI(X1,X2,X3,X4,X5,X6,X7) LAPACK(dgetri,DGETRI)(&X1,X2,&X3,X4,X5,&X6,&X7)
// #define DGETRI(X1,X2,X3,X4,X5,X6,X7) LAPACK(dgetri,DGETRI)(CblasColMajor,X1,X2,X3,X4)
#else
#define DGETRF(X1,X2,X3,X4,X5) LAPACK(dgetrf,DGETRF)(CblasColMajor,X1,X2,X3,X4,X5)
#define DGETRI(X1,X2,X3,X4) LAPACK(dgetri,DGETRI)(CblasColMajor,X1,X2,X3,X4)
#endif
#else
#define DGETRF(X1,X2,X3,X4,X5,X6) LAPACK(dgetrf,DGETRF)(X1,X2,X3,X4,X5,X6)
#define DGETRI(X1,X2,X3,X4,X5,X6,X7) LAPACK(dgetri,DGETRI)(X1,X2,X3,X4,X5,X6,X7)
#endif
#define DSPTRI(X1,X2,X3,X4,X5,X6) FC_GLOBAL(dsptri,DSPTRI)(X1,X2,X3,X4,X5,X6)
#else
#define DGER(X1,X2,X3,X4,X5,X6,X7,X8,X9) BLAS(dger,DGER)(X1,X2,X3,X4,X5,X6,X7,X8,X9)
#define DSPMV(X1,X2,X3,X4,X5,X6,X7,X8,X9) BLAS(dspmv,DSPMV)(X1,X2,X3,X4,X5,X6,X7,X8,X9)
#define DTPMV(X1,X2,X3,X4,X5,X6,X7) BLAS(dtpmv,DTPMV)(X1,X2,X3,X4,X5,X6,X7)
#define DSYMM(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12) BLAS(dsymm,DSYMM)(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12)
#define DGEMV(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11) BLAS(dgemv,DGEMV)(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11)
#define DGEMM(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,X13) BLAS(dgemm,DGEMM)(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,X13)
#define DTRMM(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11) BLAS(dtrmm,DTRMM)(X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11)
#define DGETRF LAPACK(dgetrf,DGETRF)
#if defined(USE_ACML)
#define DGETRI(X1,X2,X3,X4,X5,X6,X7) LAPACK(dgetri,DGETRI)(X1,X2,X3,X4,X7)
#define DSPTRI(X1,X2,X3,X4,X5,X6) LAPACK(dsptri,DSPTRI)(X1,X2,X3,X4,X6)
#else
#define DGETRI(X1,X2,X3,X4,X5,X6,X7) LAPACK(dgetri,DGETRI)(X1,X2,X3,X4,X5,X6,X7)
#define DSPTRI(X1,X2,X3,X4,X5,X6) LAPACK(dsptri,DSPTRI)(X1,X2,X3,X4,X5,X6)
#endif
#endif
| {
"alphanum_fraction": 0.6957903098,
"avg_line_length": 48.1913875598,
"ext": "h",
"hexsha": "5d96711cfd5a1779093b38772d4823efc0c39390",
"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": "e4192e5884311215bb4f77cbc673106c0e90faa3",
"max_forks_repo_licenses": [
"Intel",
"CECILL-B"
],
"max_forks_repo_name": "neurodebian/openmeeg",
"max_forks_repo_path": "libs/OpenMEEGMaths/include/OpenMEEGMathsConfig.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e4192e5884311215bb4f77cbc673106c0e90faa3",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Intel",
"CECILL-B"
],
"max_issues_repo_name": "neurodebian/openmeeg",
"max_issues_repo_path": "libs/OpenMEEGMaths/include/OpenMEEGMathsConfig.h",
"max_line_length": 186,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e4192e5884311215bb4f77cbc673106c0e90faa3",
"max_stars_repo_licenses": [
"Intel",
"CECILL-B"
],
"max_stars_repo_name": "neurodebian/openmeeg",
"max_stars_repo_path": "libs/OpenMEEGMaths/include/OpenMEEGMathsConfig.h",
"max_stars_repo_stars_event_max_datetime": "2015-04-20T10:08:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-20T10:08:25.000Z",
"num_tokens": 3500,
"size": 10072
} |
#ifndef __TEST_MAIN_H__
#define __TEST_MAIN_H__
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stdlib.h>
#include <math.h>
#include <gsl_vector.h>
#include "common.h"
#include "svm_main.h"
#include "kernels.h"
// returns predictions and true values
PyObject* __test_t(PyObject* training, PyObject* testing, PyObject* alphas, double b, int rbf);
#endif /* __TEST_MAIN_H__ */ | {
"alphanum_fraction": 0.7584415584,
"avg_line_length": 24.0625,
"ext": "h",
"hexsha": "8759dc0e3776ce0ae5ef1f431d04011639c838ba",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "HARDIntegral/ADHD_Classifier",
"max_forks_repo_path": "Source/SVM/Include/test_main.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "HARDIntegral/ADHD_Classifier",
"max_issues_repo_path": "Source/SVM/Include/test_main.h",
"max_line_length": 95,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f86c8eafa78ca241919d12134afe796c665f8021",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "HARDIntegral/ADHD_Classifier",
"max_stars_repo_path": "Source/SVM/Include/test_main.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 99,
"size": 385
} |
#ifndef INCLUDED_BLAS_TRAITS_H
#define INCLUDED_BLAS_TRAITS_H
#include <cblas.h>
#include <type_traits>
namespace blas{
/*
Specialize to define the blas traits of an object. Should
be constructed from an instance of T
*/
template< typename T >
struct Traits {
};
template< typename T >
constexpr auto blas_cast( T&& x ){
return Traits<T>( std::forward<T>( x ) );
}
template< typename T >
constexpr CBLAS_ORDER layout( T&& traits ){
return (CBLAS_ORDER) traits.layout(); }
template< typename T >
constexpr CBLAS_TRANSPOSE trans( T&& traits ){
return (CBLAS_TRANSPOSE) traits.trans(); }
template< typename T >
constexpr CBLAS_UPLO uplo( T&& traits ){
return (CBLAS_UPLO) traits.uplo(); }
template< typename T >
constexpr auto nrows( T&& traits ){ return traits.nrows(); }
template< typename T >
constexpr auto ncols( T&& traits ){ return traits.ncols(); }
template< typename T >
constexpr auto array( T&& traits ){ return traits.array(); }
template< typename T >
constexpr auto ld( T&& traits ){ return traits.ld(); }
template< typename T >
struct MatrixTraits {
/*
using scalar_t = ...
static CBLAS_ORDER layout( const T& );
static CBLAS_TRANSPOSE trans( const T& );
static CBLAS_UPLO uplo( const T& ); --if symmetric
static std::size_t nrows( const T& );
static std::size_t ncols( const T& );
static scalar_t* array( T& );
static const scalar_t* array( const T& );
static std::size_t ld( const T& );
*/
};
template< typename T >
struct VectorTraits{
/*
using scalar_t = ...
static std::size_t length( const T& );
static std::size_t inc( const T& );
static scalar_t* array( T& );
static const scalar_t* array( const T& );
*/
};
template< typename T >
struct BlasCast : public std::false_type{
/*
When implemented - extend std::true_type (define ::value = true)
static _ blas_cast( T& );
static _ blas_cast( const T& );
*/
};
} //namespace blas
#endif
| {
"alphanum_fraction": 0.5913591359,
"avg_line_length": 27.775,
"ext": "h",
"hexsha": "fe16681418663ce606e9b631d07cc0b9290e381f",
"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/traits.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/traits.h",
"max_line_length": 72,
"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/traits.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 540,
"size": 2222
} |
/* multilarge.c
*
* Copyright (C) 2015 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_multilarge.h>
#include <gsl/gsl_blas.h>
gsl_multilarge_linear_workspace *
gsl_multilarge_linear_alloc(const gsl_multilarge_linear_type *T,
const size_t p)
{
gsl_multilarge_linear_workspace *w;
w = calloc(1, sizeof(gsl_multilarge_linear_workspace));
if (w == NULL)
{
GSL_ERROR_NULL("failed to allocate space for workspace",
GSL_ENOMEM);
}
w->type = T;
w->state = w->type->alloc(p);
if (w->state == NULL)
{
gsl_multilarge_linear_free(w);
GSL_ERROR_NULL("failed to allocate space for multilarge state",
GSL_ENOMEM);
}
w->p = p;
/* initialize newly allocated state */
gsl_multilarge_linear_reset(w);
return w;
}
void
gsl_multilarge_linear_free(gsl_multilarge_linear_workspace *w)
{
RETURN_IF_NULL(w);
if (w->state)
w->type->free(w->state);
free(w);
}
const char *
gsl_multilarge_linear_name(const gsl_multilarge_linear_workspace *w)
{
return w->type->name;
}
int
gsl_multilarge_linear_reset(gsl_multilarge_linear_workspace *w)
{
int status = w->type->reset(w->state);
return status;
}
int
gsl_multilarge_linear_accumulate(gsl_matrix * X, gsl_vector * y,
gsl_multilarge_linear_workspace * w)
{
int status = w->type->accumulate(X, y, w->state);
return status;
}
int
gsl_multilarge_linear_solve(const double lambda, gsl_vector * c,
double * rnorm, double * snorm,
gsl_multilarge_linear_workspace * w)
{
int status = w->type->solve(lambda, c, rnorm, snorm, w->state);
return status;
}
int
gsl_multilarge_linear_rcond(double *rcond, gsl_multilarge_linear_workspace * w)
{
int status = w->type->rcond(rcond, w->state);
return status;
}
int
gsl_multilarge_linear_lcurve(gsl_vector * reg_param, gsl_vector * rho,
gsl_vector * eta,
gsl_multilarge_linear_workspace * w)
{
const size_t len = reg_param->size;
if (len != rho->size)
{
GSL_ERROR ("reg_param and rho have different sizes", GSL_EBADLEN);
}
else if (len != eta->size)
{
GSL_ERROR ("reg_param and eta have different sizes", GSL_EBADLEN);
}
else
{
int status = w->type->lcurve(reg_param, rho, eta, w->state);
return status;
}
}
/*
gsl_multilarge_linear_wstdform1()
Using regularization matrix
L = diag(l_1,l_2,...,l_p), transform to Tikhonov standard form:
X~ = sqrt(W) X L^{-1}
y~ = sqrt(W) y
c~ = L c
Inputs: L - Tikhonov matrix as a vector of diagonal elements p-by-1;
or NULL for L = I
X - least squares matrix n-by-p
y - right hand side vector n-by-1
w - weight vector n-by-1; or NULL for W = I
Xs - least squares matrix in standard form X~ n-by-p
ys - right hand side vector in standard form y~ n-by-1
work - workspace
Return: success/error
Notes:
1) It is allowed for X = Xs and y = ys
*/
int
gsl_multilarge_linear_wstdform1 (const gsl_vector * L,
const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_multilarge_linear_workspace * work)
{
const size_t n = X->size1;
const size_t p = X->size2;
(void) work;
if (L != NULL && p != L->size)
{
GSL_ERROR("L vector does not match X", GSL_EBADLEN);
}
else if (n != y->size)
{
GSL_ERROR("y vector does not match X", GSL_EBADLEN);
}
else if (w != NULL && n != w->size)
{
GSL_ERROR("weight vector does not match X", GSL_EBADLEN);
}
else if (n != Xs->size1 || p != Xs->size2)
{
GSL_ERROR("Xs matrix dimensions do not match X", GSL_EBADLEN);
}
else if (n != ys->size)
{
GSL_ERROR("ys vector must be length n", GSL_EBADLEN);
}
else
{
int status = GSL_SUCCESS;
/* compute Xs = sqrt(W) X and ys = sqrt(W) y */
status = gsl_multifit_linear_applyW(X, w, y, Xs, ys);
if (status)
return status;
if (L != NULL)
{
size_t j;
/* construct X~ = sqrt(W) X * L^{-1} matrix */
for (j = 0; j < p; ++j)
{
gsl_vector_view Xj = gsl_matrix_column(Xs, j);
double lj = gsl_vector_get(L, j);
if (lj == 0.0)
{
GSL_ERROR("L matrix is singular", GSL_EDOM);
}
gsl_vector_scale(&Xj.vector, 1.0 / lj);
}
}
return status;
}
}
int
gsl_multilarge_linear_stdform1 (const gsl_vector * L,
const gsl_matrix * X,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_multilarge_linear_workspace * work)
{
int status;
status = gsl_multilarge_linear_wstdform1(L, X, NULL, y, Xs, ys, work);
return status;
}
int
gsl_multilarge_linear_L_decomp (gsl_matrix * L, gsl_vector * tau)
{
const size_t m = L->size1;
const size_t p = L->size2;
if (m < p)
{
GSL_ERROR("m < p not yet supported", GSL_EBADLEN);
}
else
{
int status;
status = gsl_multifit_linear_L_decomp(L, tau);
return status;
}
}
int
gsl_multilarge_linear_wstdform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_multilarge_linear_workspace * work)
{
const size_t m = LQR->size1;
const size_t n = X->size1;
const size_t p = X->size2;
(void) Ltau;
if (p != work->p)
{
GSL_ERROR("X has wrong number of columns", GSL_EBADLEN);
}
else if (p != LQR->size2)
{
GSL_ERROR("LQR and X matrices have different numbers of columns", GSL_EBADLEN);
}
else if (n != y->size)
{
GSL_ERROR("y vector does not match X", GSL_EBADLEN);
}
else if (w != NULL && n != w->size)
{
GSL_ERROR("weights vector must be length n", GSL_EBADLEN);
}
else if (m < p)
{
GSL_ERROR("m < p not yet supported", GSL_EBADLEN);
}
else if (n != Xs->size1 || p != Xs->size2)
{
GSL_ERROR("Xs matrix must be n-by-p", GSL_EBADLEN);
}
else if (n != ys->size)
{
GSL_ERROR("ys vector must have length n", GSL_EBADLEN);
}
else
{
int status;
size_t i;
gsl_matrix_const_view R = gsl_matrix_const_submatrix(LQR, 0, 0, p, p);
/* compute Xs = sqrt(W) X and ys = sqrt(W) y */
status = gsl_multifit_linear_applyW(X, w, y, Xs, ys);
if (status)
return status;
/* compute X~ = X R^{-1} using QR decomposition of L */
for (i = 0; i < n; ++i)
{
gsl_vector_view v = gsl_matrix_row(Xs, i);
/* solve: R^T y = X_i */
gsl_blas_dtrsv(CblasUpper, CblasTrans, CblasNonUnit, &R.matrix, &v.vector);
}
return GSL_SUCCESS;
}
}
int
gsl_multilarge_linear_stdform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_multilarge_linear_workspace * work)
{
int status;
status = gsl_multilarge_linear_wstdform2(LQR, Ltau, X, NULL, y, Xs, ys, work);
return status;
}
/*
gsl_multilarge_linear_genform1()
Backtransform regularized solution vector using matrix
L = diag(L)
*/
int
gsl_multilarge_linear_genform1 (const gsl_vector * L,
const gsl_vector * cs,
gsl_vector * c,
gsl_multilarge_linear_workspace * work)
{
if (L->size != work->p)
{
GSL_ERROR("L vector does not match workspace", GSL_EBADLEN);
}
else if (L->size != cs->size)
{
GSL_ERROR("cs vector does not match L", GSL_EBADLEN);
}
else if (L->size != c->size)
{
GSL_ERROR("c vector does not match L", GSL_EBADLEN);
}
else
{
/* compute true solution vector c = L^{-1} c~ */
gsl_vector_memcpy(c, cs);
gsl_vector_div(c, L);
return GSL_SUCCESS;
}
}
int
gsl_multilarge_linear_genform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_vector * cs,
gsl_vector * c,
gsl_multilarge_linear_workspace * work)
{
const size_t m = LQR->size1;
const size_t p = LQR->size2;
(void) Ltau;
(void) work;
if (p != c->size)
{
GSL_ERROR("c vector does not match LQR", GSL_EBADLEN);
}
else if (m < p)
{
GSL_ERROR("m < p not yet supported", GSL_EBADLEN);
}
else if (p != cs->size)
{
GSL_ERROR("cs vector size does not match c", GSL_EBADLEN);
}
else
{
int s;
gsl_matrix_const_view R = gsl_matrix_const_submatrix(LQR, 0, 0, p, p); /* R factor of L */
/* solve R c = cs for true solution c, using QR decomposition of L */
gsl_vector_memcpy(c, cs);
s = gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit, &R.matrix, c);
return s;
}
}
const gsl_matrix *
gsl_multilarge_linear_matrix_ptr (const gsl_multilarge_linear_workspace * work)
{
return work->type->matrix_ptr(work->state);
}
const gsl_vector *
gsl_multilarge_linear_rhs_ptr (const gsl_multilarge_linear_workspace * work)
{
return work->type->rhs_ptr(work->state);
}
| {
"alphanum_fraction": 0.5688557395,
"avg_line_length": 26.0521327014,
"ext": "c",
"hexsha": "eabe6220bb3c12a4c1a58d9b77f07e0ad0e13a1a",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/multilarge/multilarge.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/multilarge/multilarge.c",
"max_line_length": 96,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/multilarge/multilarge.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": 2902,
"size": 10994
} |
#if !defined(_MUSIC_GSL_)
#define _MUSIC_GSL_
#define WIN32
#include <gsl/gsl_combination.h>
#include <gsl/gsl_sf.h>
#endif | {
"alphanum_fraction": 0.7619047619,
"avg_line_length": 14,
"ext": "h",
"hexsha": "4d9ed9b22b7aa354d5037add788b9446b0d4cf15",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "berkus/music-cs",
"max_forks_repo_path": "src/Extensions/Classifiers/Barbedo/gsl.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "berkus/music-cs",
"max_issues_repo_path": "src/Extensions/Classifiers/Barbedo/gsl.h",
"max_line_length": 32,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "099b66cb1285d19955e953f916ec6c12c68f2242",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "berkus/music-cs",
"max_stars_repo_path": "src/Extensions/Classifiers/Barbedo/gsl.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 40,
"size": 126
} |
/* siman/gsl_siman.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Mark Galassi
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_SIMAN_H__
#define __GSL_SIMAN_H__
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* types for the function pointers passed to gsl_siman_solve */
typedef double (*gsl_siman_Efunc_t) (void *xp);
typedef void (*gsl_siman_step_t) (const gsl_rng *r, void *xp, double step_size);
typedef double (*gsl_siman_metric_t) (void *xp, void *yp);
typedef void (*gsl_siman_print_t) (void *xp);
typedef void (*gsl_siman_copy_t) (void *source, void *dest);
typedef void * (*gsl_siman_copy_construct_t) (void *xp);
typedef void (*gsl_siman_destroy_t) (void *xp);
/* this structure contains all the information needed to structure the
search, beyond the energy function, the step function and the
initial guess. */
typedef struct {
int n_tries; /* how many points to try for each step */
int iters_fixed_T; /* how many iterations at each temperature? */
double step_size; /* max step size in the random walk */
/* the following parameters are for the Boltzmann distribution */
double k, t_initial, mu_t, t_min;
} gsl_siman_params_t;
/* prototype for the workhorse function */
void gsl_siman_solve(const gsl_rng * r,
void *x0_p, gsl_siman_Efunc_t Ef,
gsl_siman_step_t take_step,
gsl_siman_metric_t distance,
gsl_siman_print_t print_position,
gsl_siman_copy_t copyfunc,
gsl_siman_copy_construct_t copy_constructor,
gsl_siman_destroy_t destructor,
size_t element_size,
gsl_siman_params_t params);
void
gsl_siman_solve_many (const gsl_rng * r, void *x0_p, gsl_siman_Efunc_t Ef,
gsl_siman_step_t take_step,
gsl_siman_metric_t distance,
gsl_siman_print_t print_position,
size_t element_size,
gsl_siman_params_t params);
__END_DECLS
#endif /* __GSL_SIMAN_H__ */
| {
"alphanum_fraction": 0.6855533466,
"avg_line_length": 36.3614457831,
"ext": "h",
"hexsha": "d04333a690b71ec80bd8e56e9d508f56b34b65e6",
"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/siman/gsl_siman.h",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/siman/gsl_siman.h",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/siman/gsl_siman.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z",
"num_tokens": 730,
"size": 3018
} |
static char help[] =
"Solves structured-grid Poisson problem in 1D, 2D, 3D. Option prefix fsh_.\n"
"Equation is\n"
" - cx u_xx - cy u_yy - cz u_zz = f,\n"
"subject to Dirichlet boundary conditions. Solves three different problems\n"
"where exact solution is known. Uses DMDA and SNES. Equation is put in form\n"
"F(u) = - grad^2 u - f. Call-backs fully-rediscretize for the supplied grid.\n"
"Defaults to 2D, a SNESType of KSPONLY, and a KSPType of CG.\n\n";
#include <petsc.h>
#include "poissonfunctions.h"
// exact solutions u(x,y), for boundary condition and error calculation
static double u_exact_1Dmanupoly(double x, double y, double z, void *ctx) {
return x*x * (1.0 - x*x);
}
static double u_exact_2Dmanupoly(double x, double y, double z, void *ctx) {
return x*x * (1.0 - x*x) * y*y *(y*y - 1.0);
}
static double u_exact_3Dmanupoly(double x, double y, double z, void *ctx) {
return x*x * (1.0 - x*x) * y*y * (y*y - 1.0) * z*z * (z*z - 1.0);
}
static double u_exact_1Dmanuexp(double x, double y, double z, void *ctx) {
return - exp(x);
}
static double u_exact_2Dmanuexp(double x, double y, double z, void *ctx) {
return - x * exp(y);
}
static double u_exact_3Dmanuexp(double x, double y, double z, void *ctx) {
return - x * exp(y + z);
}
static double zero(double x, double y, double z, void *ctx) {
return 0.0;
}
// right-hand-side functions f(x,y) = - laplacian u
static double f_rhs_1Dmanupoly(double x, double y, double z, void *ctx) {
PoissonCtx* user = (PoissonCtx*)ctx;
return user->cx * 12.0 * x*x - 2.0;
}
static double f_rhs_2Dmanupoly(double x, double y, double z, void *ctx) {
PoissonCtx* user = (PoissonCtx*)ctx;
double aa, bb, ddaa, ddbb;
aa = x*x * (1.0 - x*x);
bb = y*y * (y*y - 1.0);
ddaa = 2.0 * (1.0 - 6.0 * x*x);
ddbb = 2.0 * (6.0 * y*y - 1.0);
return - (user->cx * ddaa * bb + user->cy * aa * ddbb);
}
static double f_rhs_3Dmanupoly(double x, double y, double z, void *ctx) {
PoissonCtx* user = (PoissonCtx*)ctx;
double aa, bb, cc, ddaa, ddbb, ddcc;
aa = x*x * (1.0 - x*x);
bb = y*y * (y*y - 1.0);
cc = z*z * (z*z - 1.0);
ddaa = 2.0 * (1.0 - 6.0 * x*x);
ddbb = 2.0 * (6.0 * y*y - 1.0);
ddcc = 2.0 * (6.0 * z*z - 1.0);
return - (user->cx * ddaa * bb * cc + user->cy * aa * ddbb * cc + user->cz * aa * bb * ddcc);
}
static double f_rhs_1Dmanuexp(double x, double y, double z, void *ctx) {
return exp(x);
}
static double f_rhs_2Dmanuexp(double x, double y, double z, void *ctx) {
return x * exp(y); // note f = - (u_xx + u_yy) = - u
}
static double f_rhs_3Dmanuexp(double x, double y, double z, void *ctx) {
return 2.0 * x * exp(y + z); // note f = - laplacian u = - 2 u
}
// functions simply to put u_exact()=g_bdry() into a grid
// these are irritatingly-dimension-dependent inside ...
extern PetscErrorCode Form1DUExact(DMDALocalInfo*, Vec, PoissonCtx*);
extern PetscErrorCode Form2DUExact(DMDALocalInfo*, Vec, PoissonCtx*);
extern PetscErrorCode Form3DUExact(DMDALocalInfo*, Vec, PoissonCtx*);
//STARTPTRARRAYS
// arrays of pointers to functions: ..._ptr[DIMS]
static void* residual_ptr[3]
= {&Poisson1DFunctionLocal, &Poisson2DFunctionLocal, &Poisson3DFunctionLocal};
static void* jacobian_ptr[3]
= {&Poisson1DJacobianLocal, &Poisson2DJacobianLocal, &Poisson3DJacobianLocal};
static void* getuexact_ptr[3]
= {&Form1DUExact, &Form2DUExact, &Form3DUExact};
//ENDPTRARRAYS
typedef enum {MANUPOLY, MANUEXP, ZERO} ProblemType;
static const char* ProblemTypes[] = {"manupoly","manuexp","zero",
"ProblemType", "", NULL};
// more arrays of pointers to functions: ..._ptr[DIMS][PROBLEMS]
static void* g_bdry_ptr[3][3]
= {{&u_exact_1Dmanupoly, &u_exact_1Dmanuexp, &zero},
{&u_exact_2Dmanupoly, &u_exact_2Dmanuexp, &zero},
{&u_exact_3Dmanupoly, &u_exact_3Dmanuexp, &zero}};
static void* f_rhs_ptr[3][3]
= {{&f_rhs_1Dmanupoly, &f_rhs_1Dmanuexp, &zero},
{&f_rhs_2Dmanupoly, &f_rhs_2Dmanuexp, &zero},
{&f_rhs_3Dmanupoly, &f_rhs_3Dmanuexp, &zero}};
static const char* InitialTypes[] = {"zeros","random",
"InitialType", "", NULL};
int main(int argc,char **argv) {
PetscErrorCode ierr;
DM da, da_after;
SNES snes;
KSP ksp;
Vec u_initial, u, u_exact;
PoissonCtx user;
DMDALocalInfo info;
double errinf, normconst2h, err2h;
char gridstr[99];
PetscErrorCode (*getuexact)(DMDALocalInfo*,Vec,PoissonCtx*);
// fish defaults:
int dim = 2; // 2D
ProblemType problem = MANUEXP; // manufactured problem using exp()
InitialType initial = ZEROS; // set u=0 for initial iterate
PetscBool gonboundary = PETSC_TRUE; // initial iterate has u=g on boundary
// get options and configure context
user.Lx = 1.0;
user.Ly = 1.0;
user.Lz = 1.0;
user.cx = 1.0;
user.cy = 1.0;
user.cz = 1.0;
PetscInitialize(&argc,&argv,NULL,help);
ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"fsh_", "options for fish.c", ""); CHKERRQ(ierr);
ierr = PetscOptionsReal("-cx",
"set coefficient of x term u_xx in equation",
"fish.c",user.cx,&user.cx,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-cy",
"set coefficient of y term u_yy in equation",
"fish.c",user.cy,&user.cy,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-cz",
"set coefficient of z term u_zz in equation",
"fish.c",user.cz,&user.cz,NULL);CHKERRQ(ierr);
ierr = PetscOptionsInt("-dim",
"dimension of problem (=1,2,3 only)",
"fish.c",dim,&dim,NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-initial_gonboundary",
"set initial iterate to have correct boundary values",
"fish.c",gonboundary,&gonboundary,NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnum("-initial_type",
"type of initial iterate",
"fish.c",InitialTypes,(PetscEnum)initial,(PetscEnum*)&initial,NULL); CHKERRQ(ierr);
ierr = PetscOptionsReal("-Lx",
"set Lx in domain ([0,Lx] x [0,Ly] x [0,Lz], etc.)",
"fish.c",user.Lx,&user.Lx,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-Ly",
"set Ly in domain ([0,Lx] x [0,Ly] x [0,Lz], etc.)",
"fish.c",user.Ly,&user.Ly,NULL);CHKERRQ(ierr);
ierr = PetscOptionsReal("-Lz",
"set Ly in domain ([0,Lx] x [0,Ly] x [0,Lz], etc.)",
"fish.c",user.Lz,&user.Lz,NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnum("-problem",
"problem type; determines exact solution and RHS",
"fish.c",ProblemTypes,(PetscEnum)problem,(PetscEnum*)&problem,NULL); CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
user.g_bdry = g_bdry_ptr[dim-1][problem];
user.f_rhs = f_rhs_ptr[dim-1][problem];
if ( user.cx <= 0.0 || user.cy <= 0.0 || user.cz <= 0.0 ) {
SETERRQ(PETSC_COMM_WORLD,2,"positivity required for coefficients cx,cy,cz\n");
}
if ((problem == MANUEXP) && ( user.cx != 1.0 || user.cy != 1.0 || user.cz != 1.0)) {
SETERRQ(PETSC_COMM_WORLD,3,"cx=cy=cz=1 required for problem MANUEXP\n");
}
//STARTCREATE
// DMDA in chosen dimension
switch (dim) {
case 1:
ierr = DMDACreate1d(PETSC_COMM_WORLD,
DM_BOUNDARY_NONE,3,1,1, NULL, &da); CHKERRQ(ierr);
break;
case 2:
ierr = DMDACreate2d(PETSC_COMM_WORLD,
DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_STAR,
3,3,PETSC_DECIDE,PETSC_DECIDE,1,1,NULL,NULL,&da); CHKERRQ(ierr);
break;
case 3:
ierr = DMDACreate3d(PETSC_COMM_WORLD,
DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DM_BOUNDARY_NONE,
DMDA_STENCIL_STAR,
3,3,3,PETSC_DECIDE,PETSC_DECIDE,PETSC_DECIDE,
1,1,NULL,NULL,NULL,&da); CHKERRQ(ierr);
break;
default:
SETERRQ(PETSC_COMM_WORLD,1,"invalid dim for DMDA creation\n");
}
ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr);
ierr = DMSetFromOptions(da); CHKERRQ(ierr);
ierr = DMSetUp(da); CHKERRQ(ierr); // call BEFORE SetUniformCoordinates
ierr = DMDASetUniformCoordinates(da,0.0,user.Lx,0.0,user.Ly,0.0,user.Lz); CHKERRQ(ierr);
// create SNES supply call-backs
ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);
ierr = SNESSetDM(snes,da); CHKERRQ(ierr);
ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,
(DMDASNESFunction)(residual_ptr[dim-1]),&user); CHKERRQ(ierr);
ierr = DMDASNESSetJacobianLocal(da,
(DMDASNESJacobian)(jacobian_ptr[dim-1]),&user); CHKERRQ(ierr);
// default to KSPONLY+CG because problem is linear and SPD
ierr = SNESSetType(snes,SNESKSPONLY); CHKERRQ(ierr);
ierr = SNESGetKSP(snes,&ksp); CHKERRQ(ierr);
ierr = KSPSetType(ksp,KSPCG); CHKERRQ(ierr);
ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);
// initial iterate and solve
ierr = DMGetGlobalVector(da,&u_initial); CHKERRQ(ierr);
ierr = InitialState(da, initial, gonboundary, u_initial, &user); CHKERRQ(ierr);
ierr = SNESSolve(snes,NULL,u_initial); CHKERRQ(ierr);
//ENDCREATE
//STARTGETSOLUTION
// -snes_grid_sequence could change grid resolution
ierr = DMRestoreGlobalVector(da,&u_initial); CHKERRQ(ierr);
ierr = DMDestroy(&da); CHKERRQ(ierr);
// evaluate error and report
ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr); // SNES owns u; do not destroy it
ierr = VecDuplicate(u,&u_exact); CHKERRQ(ierr);
ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr); // SNES owns da_after; do not destroy it
ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr);
getuexact = getuexact_ptr[dim-1];
ierr = (*getuexact)(&info,u_exact,&user); CHKERRQ(ierr);
ierr = VecAXPY(u,-1.0,u_exact); CHKERRQ(ierr); // u <- u + (-1.0) uexact
ierr = VecDestroy(&u_exact); CHKERRQ(ierr); // no longer needed
ierr = VecNorm(u,NORM_INFINITY,&errinf); CHKERRQ(ierr);
ierr = VecNorm(u,NORM_2,&err2h); CHKERRQ(ierr);
//ENDGETSOLUTION
switch (dim) {
case 1:
normconst2h = PetscSqrtReal((double)(info.mx-1));
snprintf(gridstr,99,"%d point 1D",info.mx);
break;
case 2:
normconst2h = PetscSqrtReal((double)(info.mx-1)*(info.my-1));
snprintf(gridstr,99,"%d x %d point 2D",info.mx,info.my);
break;
case 3:
normconst2h = PetscSqrtReal((double)(info.mx-1)*(info.my-1)*(info.mz-1));
snprintf(gridstr,99,"%d x %d x %d point 3D",info.mx,info.my,info.mz);
break;
default:
SETERRQ(PETSC_COMM_WORLD,4,"invalid dim value in final report\n");
}
err2h /= normconst2h; // like continuous L2
ierr = PetscPrintf(PETSC_COMM_WORLD,
"problem %s on %s grid:\n"
" error |u-uexact|_inf = %.3e, |u-uexact|_h = %.3e\n",
ProblemTypes[problem],gridstr,errinf,err2h); CHKERRQ(ierr);
// destroy what we explicitly Created
ierr = SNESDestroy(&snes); CHKERRQ(ierr);
return PetscFinalize();
}
PetscErrorCode Form1DUExact(DMDALocalInfo *info, Vec u, PoissonCtx* user) {
PetscErrorCode ierr;
int i;
double xmax[1], xmin[1], hx, x, *au;
ierr = DMDAGetBoundingBox(info->da,xmin,xmax); CHKERRQ(ierr);
hx = (xmax[0] - xmin[0]) / (info->mx - 1);
ierr = DMDAVecGetArray(info->da, u, &au);CHKERRQ(ierr);
for (i=info->xs; i<info->xs+info->xm; i++) {
x = xmin[0] + i * hx;
au[i] = user->g_bdry(x,0.0,0.0,user);
}
ierr = DMDAVecRestoreArray(info->da, u, &au);CHKERRQ(ierr);
return 0;
}
PetscErrorCode Form2DUExact(DMDALocalInfo *info, Vec u, PoissonCtx* user) {
PetscErrorCode ierr;
int i, j;
double xymin[2], xymax[2], hx, hy, x, y, **au;
ierr = DMDAGetBoundingBox(info->da,xymin,xymax); CHKERRQ(ierr);
hx = (xymax[0] - xymin[0]) / (info->mx - 1);
hy = (xymax[1] - xymin[1]) / (info->my - 1);
ierr = DMDAVecGetArray(info->da, u, &au);CHKERRQ(ierr);
for (j=info->ys; j<info->ys+info->ym; j++) {
y = xymin[1] + j * hy;
for (i=info->xs; i<info->xs+info->xm; i++) {
x = xymin[0] + i * hx;
au[j][i] = user->g_bdry(x,y,0.0,user);
}
}
ierr = DMDAVecRestoreArray(info->da, u, &au);CHKERRQ(ierr);
return 0;
}
PetscErrorCode Form3DUExact(DMDALocalInfo *info, Vec u, PoissonCtx* user) {
PetscErrorCode ierr;
int i, j, k;
double xyzmin[3], xyzmax[3], hx, hy, hz, x, y, z, ***au;
ierr = DMDAGetBoundingBox(info->da,xyzmin,xyzmax); CHKERRQ(ierr);
hx = (xyzmax[0] - xyzmin[0]) / (info->mx - 1);
hy = (xyzmax[1] - xyzmin[1]) / (info->my - 1);
hz = (xyzmax[2] - xyzmin[2]) / (info->mz - 1);
ierr = DMDAVecGetArray(info->da, u, &au);CHKERRQ(ierr);
for (k=info->zs; k<info->zs+info->zm; k++) {
z = xyzmin[2] + k * hz;
for (j=info->ys; j<info->ys+info->ym; j++) {
y = xyzmin[1] + j * hy;
for (i=info->xs; i<info->xs+info->xm; i++) {
x = xyzmin[0] + i * hx;
au[k][j][i] = user->g_bdry(x,y,z,user);
}
}
}
ierr = DMDAVecRestoreArray(info->da, u, &au);CHKERRQ(ierr);
return 0;
}
| {
"alphanum_fraction": 0.6069320983,
"avg_line_length": 39.8422619048,
"ext": "c",
"hexsha": "7fe36007c28c45b140cff10c6ae37bba048c87c3",
"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/ch6/fish.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/ch6/fish.c",
"max_line_length": 97,
"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/ch6/fish.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4367,
"size": 13387
} |
#include <unistd.h>
#include "asf_sar.h"
#include "asf_raster.h"
#include "asf_nan.h"
#include "asf_complex.h"
#include <assert.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_eigen.h>
#define EPS 1.E-15
typedef struct {
int current_row;
int nrows; // # in held in memory, not total image rows
meta_parameters *meta;
float *amp; // HH amplitude data
quadPolS2Float *s2_data_buffer;
quadPolS2Float **s2_lines;
quadPolC3Float *c3_data_buffer;
quadPolC3Float **c3_lines;
quadPolT3Float *t3_data_buffer;
quadPolT3Float **t3_lines;
floatVector *pauli_buffer;
floatVector **pauli_lines;
complexMatrix **coh_buffer;
complexMatrix ***coh_lines;
int amp_band;
int hh_amp_band, hh_phase_band;
int hv_amp_band, hv_phase_band;
int vh_amp_band, vh_phase_band;
int vv_amp_band, vv_phase_band;
int c11_band, c12_real_band, c12_imag_band;
int c13_real_band, c13_imag_band, c22_band;
int c23_real_band, c23_imag_band, c33_band;
int t11_band, t12_real_band, t12_imag_band;
int t13_real_band, t13_imag_band, t22_band;
int t23_real_band, t23_imag_band, t33_band;
} PolarimetricImageRows;
//static complexFloat complex_new_gsl(gsl_complex c)
//{
// complexFloat ret;
// ret.real = GSL_REAL(c);
// ret.imag = GSL_IMAG(c);
// return ret;
//}
static quadPolS2Float qual_pol_s2_zero()
{
quadPolS2Float ret;
ret.hh = complex_zero();
ret.vh = complex_zero();
ret.hv = complex_zero();
ret.vv = complex_zero();
return ret;
}
static quadPolC3Float qual_pol_c3_zero()
{
quadPolC3Float ret;
ret.c11 = 0.0;
ret.c12_real = 0.0;
ret.c12_imag = 0.0;
ret.c13_real = 0.0;
ret.c13_imag = 0.0;
ret.c22 = 0.0;
ret.c23_real = 0.0;
ret.c23_imag = 0.0;
ret.c33 = 0.0;
return ret;
}
static quadPolT3Float qual_pol_t3_zero()
{
quadPolT3Float ret;
ret.t11 = 0.0;
ret.t12_real = 0.0;
ret.t12_imag = 0.0;
ret.t13_real = 0.0;
ret.t13_imag = 0.0;
ret.t22 = 0.0;
ret.t23_real = 0.0;
ret.t23_imag = 0.0;
ret.t33 = 0.0;
return ret;
}
static PolarimetricImageRows *
polarimetric_image_rows_new(meta_parameters *meta, int nrows, int multi)
{
PolarimetricImageRows *self = MALLOC(sizeof(PolarimetricImageRows));
self->nrows = nrows;
self->meta = meta;
// nrows must be odd
if (multi) {
self->current_row = 0;
}
else {
assert((self->nrows-1)%2==0);
self->current_row = -(nrows+1)/2;
}
int ns = meta->general->sample_count;
self->amp = CALLOC(ns, sizeof(float));
if (meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {
self->s2_data_buffer = CALLOC(nrows*ns, sizeof(quadPolS2Float));
self->s2_lines = CALLOC(nrows, sizeof(quadPolS2Float*));
}
else if (meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {
self->c3_data_buffer = CALLOC(nrows*ns, sizeof(quadPolC3Float));
self->c3_lines = CALLOC(nrows, sizeof(quadPolC3Float*));
}
// initially, the line pointers point at their natural locations in
// the buffer
int i;
if (meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {
for (i=0; i<nrows; ++i)
self->s2_lines[i] = &(self->s2_data_buffer[ns*i]);
}
if (meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {
for (i=0; i<nrows; ++i)
self->c3_lines[i] = &(self->c3_data_buffer[ns*i]);
}
// these guys are the pauli basis elements we've calculated for the
// loaded rows
self->pauli_buffer = CALLOC(nrows*ns, sizeof(floatVector));
self->pauli_lines = CALLOC(nrows, sizeof(floatVector*));
for (i=0; i<nrows; ++i)
self->pauli_lines[i] = &(self->pauli_buffer[ns*i]);
// coherency matrix elements for the loaded rows
self->coh_buffer = MALLOC(nrows*ns*sizeof(complexMatrix*));
for (i=0; i<nrows*ns; ++i)
self->coh_buffer[i] = complex_matrix_new(3,3);
self->coh_lines = MALLOC(nrows*sizeof(complexMatrix**));
for (i=0; i<nrows; ++i)
self->coh_lines[i] = &(self->coh_buffer[ns*i]);
// band numbers in the input file
self->amp_band = -1;
self->hh_amp_band = self->hh_phase_band = -1;
self->hv_amp_band = self->hv_phase_band = -1;
self->vh_amp_band = self->vh_phase_band = -1;
self->vv_amp_band = self->vv_phase_band = -1;
self->c11_band = -1;
self->c12_real_band = -1;
self->c12_imag_band = -1;
self->c13_real_band = -1;
self->c13_imag_band = -1;
self->c22_band = -1;
self->c23_real_band = -1;
self->c23_imag_band = -1;
self->c33_band = -1;
self->t11_band = -1;
self->t12_real_band = -1;
self->t12_imag_band = -1;
self->t13_real_band = -1;
self->t13_imag_band = -1;
self->t22_band = -1;
self->t23_real_band = -1;
self->t23_imag_band = -1;
self->t33_band = -1;
return self;
}
static int polarimetric_image_rows_get_bands(PolarimetricImageRows *self)
{
int ok=TRUE;
// "extra" amplitude band needs to be the first band
char *bands = self->meta->general->bands;
self->amp_band = strncmp_case(bands, "AMP", 3) == 0 ? 0 : -1;
// polarimetric bands
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {
self->hh_amp_band = find_band(self->meta, "AMP-HH", &ok);
self->hh_phase_band = find_band(self->meta, "PHASE-HH", &ok);
self->hv_amp_band = find_band(self->meta, "AMP-HV", &ok);
self->hv_phase_band = find_band(self->meta, "PHASE-HV", &ok);
self->vh_amp_band = find_band(self->meta, "AMP-VH", &ok);
self->vh_phase_band = find_band(self->meta, "PHASE-VH", &ok);
self->vv_amp_band = find_band(self->meta, "AMP-VV", &ok);
self->vv_phase_band = find_band(self->meta, "PHASE-VV", &ok);
}
else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {
self->c11_band = find_band(self->meta, "C11", &ok);
self->c12_real_band = find_band(self->meta, "C12_real", &ok);
self->c12_imag_band = find_band(self->meta, "C12_imag", &ok);
self->c13_real_band = find_band(self->meta, "C13_real", &ok);
self->c13_imag_band = find_band(self->meta, "C13_imag", &ok);
self->c22_band = find_band(self->meta, "C22", &ok);
self->c23_real_band = find_band(self->meta, "C23_real", &ok);
self->c23_imag_band = find_band(self->meta, "C23_imag", &ok);
self->c33_band = find_band(self->meta, "C33", &ok);
}
else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {
self->t11_band = find_band(self->meta, "T11", &ok);
self->t12_real_band = find_band(self->meta, "T12_real", &ok);
self->t12_imag_band = find_band(self->meta, "T12_imag", &ok);
self->t13_real_band = find_band(self->meta, "T13_real", &ok);
self->t13_imag_band = find_band(self->meta, "T13_imag", &ok);
self->t22_band = find_band(self->meta, "T22", &ok);
self->t23_real_band = find_band(self->meta, "T23_real", &ok);
self->t23_imag_band = find_band(self->meta, "T23_imag", &ok);
self->t33_band = find_band(self->meta, "T33", &ok);
}
return ok;
}
static void calculate_pauli_for_row(PolarimetricImageRows *self, int n)
{
int j, ns=self->meta->general->sample_count;
complexFloat cpx_a, cpx_b, cpx_c;
float value;
// HH-VV, HV+VH, HH+VV
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {
for (j=0; j<ns; ++j) {
quadPolS2Float q = self->s2_lines[n][j];
cpx_a = complex_sub(q.hh, q.vv);
cpx_b = complex_add(q.hv, q.vh);
cpx_c = complex_add(q.hh, q.vv);
self->pauli_lines[n][j].A = (float) hypot(cpx_a.real, cpx_a.imag);
self->pauli_lines[n][j].B = (float) hypot(cpx_b.real, cpx_b.imag);
self->pauli_lines[n][j].C = (float) hypot(cpx_c.real, cpx_c.imag);
}
}
else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {
for (j=0; j<ns; ++j) {
quadPolC3Float q = self->c3_lines[n][j];
value = fabs(q.c11 - 2.0*q.c13_real + q.c33) / 2.0;
if (ISNAN(value)) value = EPS;
if (value > 0)
value = 10 *log10(value);
self->pauli_lines[n][j].A = value;
value = fabs(q.c22);
if (ISNAN(value)) value = EPS;
if (value > 0)
value = 10 *log10(value);
self->pauli_lines[n][j].B = value;
value = fabs(q.c11 + 2.0*q.c13_real + q.c33) / 2.0;
if (ISNAN(value)) value = EPS;
if (value > 0)
value = 10 *log10(value);
self->pauli_lines[n][j].C = value;
}
}
else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {
for (j=0; j<ns; ++j) {
quadPolT3Float q = self->t3_lines[n][j];
self->pauli_lines[n][j].A = fabs(q.t22);
self->pauli_lines[n][j].B = fabs(q.t33);
self->pauli_lines[n][j].C = fabs(q.t11);
}
}
}
static void calculate_coherence_for_row(PolarimetricImageRows *self, int n)
{
// [ A*A B*A C*A ] A = HH + VV
// [ A*B B*B C*B ] B = HH - VV
// [ A*C B*C C*C ] C = 2*HV
int j, ns=self->meta->general->sample_count;
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {
for (j=0; j<ns; ++j) {
quadPolS2Float q = self->s2_lines[n][j];
complexVector v = //complex_vector_normalize(
complex_vector_new(
complex_add(q.hh, q.vv),
complex_sub(q.hh, q.vv),
complex_add(q.hv, q.vh))/*)*/;
complexVector vc = complex_vector_conj(v);
complexMatrix *m = self->coh_lines[n][j];
complex_matrix_set(m,0,0,complex_mul(vc.A, v.A));
complex_matrix_set(m,0,1,complex_mul(vc.A, v.B));
complex_matrix_set(m,0,2,complex_mul(vc.A, v.C));
complex_matrix_set(m,1,0,complex_mul(vc.B, v.A));
complex_matrix_set(m,1,1,complex_mul(vc.B, v.B));
complex_matrix_set(m,1,2,complex_mul(vc.B, v.C));
complex_matrix_set(m,2,0,complex_mul(vc.C, v.A));
complex_matrix_set(m,2,1,complex_mul(vc.C, v.B));
complex_matrix_set(m,2,2,complex_mul(vc.C, v.C));
//complex_matrix_scale(m,1./sqrt(2.0));
complex_matrix_scale(m,0.5);
}
}
}
static void polarimetric_image_rows_load_next_row(PolarimetricImageRows *self,
FILE *fin)
{
// we discard the top (0) row, slide all rows up one, then load
// the new row into the top position
// don't actually move any data -- update pointers into the
// buffers
// FIRST -- slide row pointers
int k;
for (k=0; k<self->nrows-1; ++k) {
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX)
self->s2_lines[k] = self->s2_lines[k+1];
else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX)
self->c3_lines[k] = self->c3_lines[k+1];
else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX)
self->t3_lines[k] = self->t3_lines[k+1];
self->pauli_lines[k] = self->pauli_lines[k+1];
}
// the next line to load will go into the spot we just dumped
int last = self->nrows - 1;
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX)
self->s2_lines[last] = self->s2_lines[0];
else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX)
self->c3_lines[last] = self->c3_lines[0];
else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX)
self->t3_lines[last] = self->t3_lines[0];
self->pauli_lines[last] = self->pauli_lines[0];
self->current_row++;
// NEXT, load in new row into the final row
// if we have moved off the top of the image, we will need to
// fill with zeros, instead of loading a row
int ns = self->meta->general->sample_count;
float *amp_buf=NULL, *phase_buf=NULL;
float *c11=NULL, *c12_real=NULL, *c12_imag=NULL, *c13_real=NULL;
float *c13_imag=NULL, *c22=NULL, *c23_real=NULL, *c23_imag=NULL, *c33=NULL;
float *t11=NULL, *t12_real=NULL, *t12_imag=NULL, *t13_real=NULL;
float *t13_imag=NULL, *t22=NULL, *t23_real=NULL, *t23_imag=NULL, *t33=NULL;
float C11, C12_real, C12_imag, C13_real, C13_imag;
float C22, C23_real, C23_imag, C33;
float phase, phase12, phase13, phase23;
amp_buf = MALLOC(sizeof(float)*ns);
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {
phase_buf = MALLOC(sizeof(float)*ns);
}
else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {
c11 = MALLOC(sizeof(float)*ns);
c12_real = MALLOC(sizeof(float)*ns);
c12_imag = MALLOC(sizeof(float)*ns);
c13_real = MALLOC(sizeof(float)*ns);
c13_imag = MALLOC(sizeof(float)*ns);
c22 = MALLOC(sizeof(float)*ns);
c23_real = MALLOC(sizeof(float)*ns);
c23_imag = MALLOC(sizeof(float)*ns);
c33 = MALLOC(sizeof(float)*ns);
}
else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {
t11 = MALLOC(sizeof(float)*ns);
t12_real = MALLOC(sizeof(float)*ns);
t12_imag = MALLOC(sizeof(float)*ns);
t13_real = MALLOC(sizeof(float)*ns);
t13_imag = MALLOC(sizeof(float)*ns);
t22 = MALLOC(sizeof(float)*ns);
t23_real = MALLOC(sizeof(float)*ns);
t23_imag = MALLOC(sizeof(float)*ns);
t33 = MALLOC(sizeof(float)*ns);
}
int row = self->current_row + (self->nrows-1)/2;
if (row < self->meta->general->line_count) {
// amplitude, we only store the current row
if (self->current_row >= 0 && self->amp_band >= 0)
get_band_float_line(fin, self->meta, self->amp_band,
self->current_row, self->amp);
// now the SLC rows
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {
get_band_float_line(fin, self->meta, self->hh_amp_band, row, amp_buf);
get_band_float_line(fin, self->meta, self->hh_phase_band, row, phase_buf);
for (k=0; k<ns; ++k)
self->s2_lines[last][k].hh = complex_new_polar(sqrt(amp_buf[k]),
phase_buf[k]);
get_band_float_line(fin, self->meta, self->hv_amp_band, row, amp_buf);
get_band_float_line(fin, self->meta, self->hv_phase_band, row, phase_buf);
for (k=0; k<ns; ++k)
self->s2_lines[last][k].hv = complex_new_polar(sqrt(amp_buf[k]),
phase_buf[k]);
get_band_float_line(fin, self->meta, self->vh_amp_band, row, amp_buf);
get_band_float_line(fin, self->meta, self->vh_phase_band, row, phase_buf);
for (k=0; k<ns; ++k)
self->s2_lines[last][k].vh = complex_new_polar(sqrt(amp_buf[k]),
phase_buf[k]);
get_band_float_line(fin, self->meta, self->vv_amp_band, row, amp_buf);
get_band_float_line(fin, self->meta, self->vv_phase_band, row, phase_buf);
for (k=0; k<ns; ++k)
self->s2_lines[last][k].vv = complex_new_polar(sqrt(amp_buf[k]),
phase_buf[k]);
}
else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {
get_band_float_line(fin, self->meta, self->c11_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[last][k].c11 = amp_buf[k];
get_band_float_line(fin, self->meta, self->c12_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[last][k].c12_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->c12_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[last][k].c12_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->c13_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[last][k].c13_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->c13_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[last][k].c13_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->c22_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[last][k].c22 = amp_buf[k];
get_band_float_line(fin, self->meta, self->c23_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[last][k].c23_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->c23_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[last][k].c23_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->c33_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[last][k].c33 = amp_buf[k];
}
else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {
get_band_float_line(fin, self->meta, self->t11_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[last][k].t11 = amp_buf[k];
get_band_float_line(fin, self->meta, self->t12_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[last][k].t12_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->t12_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[last][k].t12_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->t13_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[last][k].t13_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->t13_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[last][k].t13_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->t22_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[last][k].t22 = amp_buf[k];
get_band_float_line(fin, self->meta, self->t23_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[last][k].t23_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->t23_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[last][k].t23_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->t33_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[last][k].t33 = amp_buf[k];
}
calculate_pauli_for_row(self, last);
calculate_coherence_for_row(self, last);
}
else {
// window has scrolled off top of image -- fill with zeros
for (k=0; k<self->meta->general->sample_count; ++k) {
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX)
self->s2_lines[last][k] = qual_pol_s2_zero();
else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX)
self->c3_lines[last][k] = qual_pol_c3_zero();
else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX)
self->t3_lines[last][k] = qual_pol_t3_zero();
self->pauli_lines[last][k].A = 0.0;
self->pauli_lines[last][k].B = 0.0;
self->pauli_lines[last][k].C = 0.0;
}
}
free(amp_buf);
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX)
free(phase_buf);
if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {
free(c11);
free(c12_real);
free(c12_imag);
free(c13_real);
free(c13_imag);
free(c22);
free(c23_real);
free(c23_imag);
free(c33);
}
if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {
free(t11);
free(t12_real);
free(t12_imag);
free(t13_real);
free(t13_imag);
free(t22);
free(t23_real);
free(t23_imag);
free(t33);
}
}
static void polarimetric_image_rows_load_new_rows(PolarimetricImageRows *self,
FILE *fin)
{
int i,k,ns = self->meta->general->sample_count;
float *amp_buf=NULL, *phase_buf=NULL;
float *c11=NULL, *c12_real=NULL, *c12_imag=NULL, *c13_real=NULL;
float *c13_imag=NULL, *c22=NULL, *c23_real=NULL, *c23_imag=NULL, *c33=NULL;
float *t11=NULL, *t12_real=NULL, *t12_imag=NULL, *t13_real=NULL;
float *t13_imag=NULL, *t22=NULL, *t23_real=NULL, *t23_imag=NULL, *t33=NULL;
float phase, phase12, phase13, phase23;
float C11, C12_real, C12_imag, C13_real, C13_imag;
float C22, C23_real, C23_imag, C33;
amp_buf = MALLOC(sizeof(float)*ns);
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {
phase_buf = MALLOC(sizeof(float)*ns);
}
else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {
c11 = MALLOC(sizeof(float)*ns);
c12_real = MALLOC(sizeof(float)*ns);
c12_imag = MALLOC(sizeof(float)*ns);
c13_real = MALLOC(sizeof(float)*ns);
c13_imag = MALLOC(sizeof(float)*ns);
c22 = MALLOC(sizeof(float)*ns);
c23_real = MALLOC(sizeof(float)*ns);
c23_imag = MALLOC(sizeof(float)*ns);
c33 = MALLOC(sizeof(float)*ns);
}
else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {
t11 = MALLOC(sizeof(float)*ns);
t12_real = MALLOC(sizeof(float)*ns);
t12_imag = MALLOC(sizeof(float)*ns);
t13_real = MALLOC(sizeof(float)*ns);
t13_imag = MALLOC(sizeof(float)*ns);
t22 = MALLOC(sizeof(float)*ns);
t23_real = MALLOC(sizeof(float)*ns);
t23_imag = MALLOC(sizeof(float)*ns);
t33 = MALLOC(sizeof(float)*ns);
}
int amp_band = self->amp_band;
if (amp_band < 0)
amp_band = self->hh_amp_band;
// multilook the amplitude values as we go
for (k=0; k<ns; ++k)
self->amp[k] = 0.0;
for (i=0; i<self->nrows; ++i) {
int row = self->current_row + i;
get_band_float_line(fin, self->meta, amp_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->amp[k] += amp_buf[k];
// now the SLC rows
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {
get_band_float_line(fin, self->meta, self->hh_amp_band, row, amp_buf);
get_band_float_line(fin, self->meta, self->hh_phase_band, row, phase_buf);
for (k=0; k<ns; ++k)
self->s2_lines[i][k].hh = complex_new_polar(sqrt(amp_buf[k]),
phase_buf[k]);
get_band_float_line(fin, self->meta, self->hv_amp_band, row, amp_buf);
get_band_float_line(fin, self->meta, self->hv_phase_band, row, phase_buf);
for (k=0; k<ns; ++k)
self->s2_lines[i][k].hv = complex_new_polar(sqrt(amp_buf[k]),
phase_buf[k]);
get_band_float_line(fin, self->meta, self->vh_amp_band, row, amp_buf);
get_band_float_line(fin, self->meta, self->vh_phase_band, row, phase_buf);
for (k=0; k<ns; ++k)
self->s2_lines[i][k].vh = complex_new_polar(sqrt(amp_buf[k]),
phase_buf[k]);
get_band_float_line(fin, self->meta, self->vv_amp_band, row, amp_buf);
get_band_float_line(fin, self->meta, self->vv_phase_band, row, phase_buf);
for (k=0; k<ns; ++k)
self->s2_lines[i][k].vv = complex_new_polar(sqrt(amp_buf[k]),
phase_buf[k]);
}
else if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {
get_band_float_line(fin, self->meta, self->c11_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[i][k].c11 = amp_buf[k];
get_band_float_line(fin, self->meta, self->c12_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[i][k].c12_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->c12_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[i][k].c12_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->c13_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[i][k].c13_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->c13_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[i][k].c13_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->c22_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[i][k].c22 = amp_buf[k];
get_band_float_line(fin, self->meta, self->c23_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[i][k].c23_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->c23_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[i][k].c23_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->c33_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->c3_lines[i][k].c33 = amp_buf[k];
}
else if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {
for (k=0; k<ns; ++k)
self->t3_lines[i][k].t11 = amp_buf[k];
get_band_float_line(fin, self->meta, self->t12_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[i][k].t12_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->t12_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[i][k].t12_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->t13_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[i][k].t13_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->t13_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[i][k].t13_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->t22_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[i][k].t22 = amp_buf[k];
get_band_float_line(fin, self->meta, self->t23_real_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[i][k].t23_real = amp_buf[k];
get_band_float_line(fin, self->meta, self->t23_imag_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[i][k].t23_imag = amp_buf[k];
get_band_float_line(fin, self->meta, self->t33_band, row, amp_buf);
for (k=0; k<ns; ++k)
self->t3_lines[i][k].t33 = amp_buf[k];
}
calculate_pauli_for_row(self, i);
calculate_coherence_for_row(self, i);
}
// we multilook the amplitude data now, since we only keep one row
// around-- the rest of the stuff is not multilooked since it isn't
// the final result (all rows are kept in memory)
for (k=0; k<ns; ++k)
self->amp[k] /= self->nrows;
self->current_row += self->nrows;
free(amp_buf);
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX)
free(phase_buf);
if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {
free(c11);
free(c12_real);
free(c12_imag);
free(c13_real);
free(c13_imag);
free(c22);
free(c23_real);
free(c23_imag);
free(c33);
}
if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {
free(t11);
free(t12_real);
free(t12_imag);
free(t13_real);
free(t13_imag);
free(t22);
free(t23_real);
free(t23_imag);
free(t33);
}
}
static void polarimetric_image_rows_free(PolarimetricImageRows* self)
{
free(self->amp);
if (self->meta->general->image_data_type == POLARIMETRIC_S2_MATRIX) {
free(self->s2_data_buffer);
free(self->s2_lines);
}
if (self->meta->general->image_data_type == POLARIMETRIC_C3_MATRIX) {
free(self->c3_data_buffer);
free(self->c3_lines);
}
if (self->meta->general->image_data_type == POLARIMETRIC_T3_MATRIX) {
free(self->t3_data_buffer);
free(self->t3_lines);
}
free(self->pauli_buffer);
free(self->pauli_lines);
int i;
for (i=0; i<self->nrows*self->meta->general->sample_count; ++i)
complex_matrix_free(self->coh_buffer[i]);
free(self->coh_buffer);
free(self->coh_lines);
// do not free metadata pointer!
free(self);
}
static double log3(double v)
{
return log(v)/log(3.);
}
// Dump a 2D histogram image in entropy-alpha space
// the array is twice as wide as it is tall -- we use a square histogram,
// but generate two of them -- the "left" one is the 0<anisotropy<.5
// histogram, and the "right" is the .5<anisotropy<1 one.
// For Cloude-Pottier-8, anisotropy is ignored so when the histogram is
// dumped the two sides are added together, and we only dump the left
// half of the arrays when generating the histogram and classification map
// For Cloude-Potter-16, we dump the double-wide histograms and
// classification maps.
#define HIST_SIZE 512
int hist_vals[HIST_SIZE][HIST_SIZE][HIST_SIZE];
int class_map[HIST_SIZE][HIST_SIZE*2];
#define ENTROPY_ALPHA 0
#define ALPHA_ANISOTROPY 1
#define ANISOTROPY_ENTROPY 2
static int get_hist_val(int which, int ii, int jj, int kk)
{
switch (which) {
default:
case ENTROPY_ALPHA:
return hist_vals[jj][ii][kk];
case ALPHA_ANISOTROPY:
return hist_vals[kk][ii][jj];
case ANISOTROPY_ENTROPY:
return hist_vals[jj][kk][ii];
}
}
static void dump_hist(const char *base_filename, int which)
{
char *filename = NULL;
switch (which) {
default:
case ENTROPY_ALPHA:
filename = appendToBasename(base_filename, "_entropy_alpha_hist");
break;
case ALPHA_ANISOTROPY:
filename = appendToBasename(base_filename, "_alpha_anisotropy_hist");
break;
case ANISOTROPY_ENTROPY:
filename = appendToBasename(base_filename, "_anisotropy_entropy_hist");
break;
}
int size = HIST_SIZE;
meta_parameters *m = raw_init();
m->general->line_count = size;
m->general->sample_count = size;
m->general->data_type = INTEGER16;
m->general->no_data = 0;
m->general->image_data_type = IMAGE;
strcpy(m->general->basename, filename);
m->general->band_count = 1;
switch (which) {
default:
strcpy(m->general->bands, "???");
break;
case ENTROPY_ALPHA:
strcpy(m->general->bands, "Entropy-Alpha");
break;
case ALPHA_ANISOTROPY:
strcpy(m->general->bands, "Anisotropy-Alpha");
break;
case ANISOTROPY_ENTROPY:
strcpy(m->general->bands, "Entropy-Anisotropy");
break;
}
char *meta_file = appendExt(filename, ".meta");
char *img_file = appendExt(filename, ".img");
meta_write(m, meta_file);
FILE *fp = fopenImage(img_file, "wb");
int i,j,k;
// which= ENTROPY_ALPHA:
// i= alpha index [VERTICAL]
// j= entropy index [HORIZONTAL]
// which= ALPHA_ANISOTROPY:
// i= alpha index [VERTICAL]
// j= anisotropy index [HORIZONTAL]
// which= ANISOTROPY_ENTROPY:
// i= anisotropy index [VERTICAL]
// j= entropy index [HORIZONTAL]
float *buf = MALLOC(sizeof(float)*size);
for (i=0; i<size; ++i) {
for (j=0; j<size; ++j) {
buf[j] = 0;
for (k=0; k<size; ++k)
buf[j] += get_hist_val(which,i,j,k);
if (buf[j] > 32767) // avoid overflow
buf[j] = 32767;
}
put_float_line(fp,m,i,buf);
}
free(buf);
fclose(fp);
meta_free(m);
free(meta_file);
free(img_file);
free(filename);
}
static void dump_combined_hist(const char *base_filename)
{
char *filename = appendToBasename(base_filename, "_combined_hist");
int i,j,k,size=HIST_SIZE;
meta_parameters *m = raw_init();
m->general->line_count = size*2;
m->general->sample_count = size*2;
m->general->data_type = INTEGER16;
m->general->image_data_type = IMAGE;
m->general->no_data = 0;
m->general->band_count = 1;
strcpy(m->general->bands, "Histogram");
strcpy(m->general->basename, filename);
char *meta_file = appendExt(filename, ".meta");
char *img_file = appendExt(filename, ".img");
meta_write(m, meta_file);
FILE *fp = fopenImage(img_file, "wb");
float *buf = MALLOC(sizeof(float)*size*2);
// for the top size lines:
// left half = anisotropy/alpha
// right half = entropy/alpha
for (i=0; i<size; ++i) {
for (j=0; j<size; ++j) {
buf[j] = 0;
for (k=0; k<size; ++k)
buf[j] += get_hist_val(ALPHA_ANISOTROPY,i,j,k);
}
for (j=0; j<size; ++j) {
int jj = j+size;
buf[jj] = 0;
for (k=0; k<size; ++k)
buf[jj] += get_hist_val(ENTROPY_ALPHA,i,j,k);
}
// avoid overflow
for (j=0; j<size*2; ++j) {
if (buf[j] > 32767)
buf[j] = 32767;
}
put_float_line(fp,m,i,buf);
}
// for the bottom size lines:
// left half = zeros
// right half = anisotropy/entropy
for (j=0; j<size; ++j)
buf[j] = 0;
for (i=0; i<size; ++i) {
for (j=0; j<size; ++j) {
int jj = j+size;
buf[jj] = 0;
for (k=0; k<size; ++k)
buf[jj] += get_hist_val(ANISOTROPY_ENTROPY,i,j,k);
if (buf[jj] > 32767)
buf[jj] = 32767;
}
put_float_line(fp,m,i+size,buf);
}
free(buf);
fclose(fp);
meta_free(m);
free(meta_file);
free(img_file);
free(filename);
}
static void dump_class_map(const char *base_filename, int wide)
{
char *filename = appendToBasename(base_filename, "_class_map");
int height = HIST_SIZE;
int width = wide ? HIST_SIZE*2 : HIST_SIZE;
meta_parameters *m = raw_init();
m->general->line_count = height;
m->general->sample_count = width;
m->general->data_type = BYTE;
m->general->image_data_type = IMAGE;
strcpy(m->general->basename, filename);
char *meta_file = appendExt(filename, ".meta");
char *img_file = appendExt(filename, ".img");
meta_write(m, meta_file);
FILE *fp = fopenImage(img_file, "wb");
int i,j;
float *buf = MALLOC(sizeof(float)*width);
for (i=0; i<height; ++i) {
for (j=0; j<width; ++j)
buf[j] = class_map[i][j];
put_float_line(fp,m,i,buf);
}
free(buf);
fclose(fp);
meta_free(m);
free(meta_file);
free(img_file);
free(filename);
}
static double calc_alpha_real(double e)
{
// still not entirely clear why we have to put fabs() here
double alpha = acos(fabs(e));
// alpha should be 0-90
if (alpha < 0 || alpha > 1.571) {
printf("Invalid alpha value: %f\n", alpha);
alpha = 0;
}
return alpha;
}
static double calc_alpha(gsl_complex z)
{
// alpha: acos(e[0]), e=eigenvector of coherence matrix
return calc_alpha_real(GSL_REAL(z));
}
static void add_boundary(int wide)
{
const char *boundary_file = "classifications/ea_boundary.txt";
if (share_file_exists(boundary_file)) {
FILE *fp = fopen_share_file(boundary_file,"r");
// fopen_share_file() dies if it failed to open
assert(fp);
int k;
char line[256];
// skip past the header line, size line, blank line, headings line
for (k=0; k<4; ++k)
fgets(line,256,fp);
// now read the actual points
while (fgets(line,256,fp)) {
double entropy, alpha;
sscanf(line,"%lf,%lf", &entropy, &alpha);
int i = (HIST_SIZE-1)*(1-alpha/90.);
int j = entropy*HIST_SIZE;
class_map[i][j] = 255;
if (wide)
class_map[i][j+HIST_SIZE] = 255;
}
FCLOSE(fp);
}
else {
asfPrintStatus("Boundary map file (ea_boundary.txt) file not found."
"\n*** To get the entropy/alpha feasibilty region boundary on the "
"classification\n map, see asf_calpol.\n");
}
}
static void do_sinclair_bands(int band1, int band2, int band3,
PolarimetricImageRows *img_rows,
int line, int l, int multi, int chunk_size,
meta_parameters *outMeta, FILE *fout,
float *buf)
{
int j, m;
int ns = outMeta->general->sample_count;
if (multi) {
// multilook case -- average all buffered lines to produce a
// single output line
if (band1 >= 0) {
for (j=0; j<ns; ++j) {
buf[j] = 0.0;
for (m=0; m<chunk_size; ++m)
buf[j] += complex_amp(img_rows->s2_lines[m][j].hh);
buf[j] /= (float)chunk_size;
}
put_band_float_line(fout, outMeta, band1, line, buf);
}
if (band2 >= 0) {
for (j=0; j<ns; ++j) {
buf[j] = 0.0;
for (m=0; m<chunk_size; ++m) {
complexFloat c = complex_add(img_rows->s2_lines[m][j].hv,
img_rows->s2_lines[m][j].vh);
buf[j] += complex_amp(complex_scale(c, 0.5));
}
buf[j] /= (float)chunk_size;
}
put_band_float_line(fout, outMeta, band2, line, buf);
}
if (band3 >= 0) {
for (j=0; j<ns; ++j) {
buf[j] = 0.0;
for (m=0; m<chunk_size; ++m)
buf[j] += complex_amp(img_rows->s2_lines[m][j].vv);
buf[j] /= (float)chunk_size;
}
put_band_float_line(fout, outMeta, band3, line, buf);
}
}
else {
// not multilooking -- no averaging necessary
if (band1 >= 0) {
for (j=0; j<ns; ++j)
buf[j] = complex_amp(img_rows->s2_lines[l][j].hh);
put_band_float_line(fout, outMeta, band1, line, buf);
}
if (band2 >= 0) {
for (j=0; j<ns; ++j) {
complexFloat c = complex_add(img_rows->s2_lines[l][j].hv,
img_rows->s2_lines[l][j].vh);
buf[j] = complex_amp(complex_scale(c, 0.5));
}
put_band_float_line(fout, outMeta, band2, line, buf);
}
if (band3 >= 0) {
for (j=0; j<ns; ++j)
buf[j] = complex_amp(img_rows->s2_lines[l][j].vv);
put_band_float_line(fout, outMeta, band3, line, buf);
}
}
}
static void do_pauli_bands(int band1, int band2, int band3,
PolarimetricImageRows *img_rows,
int line, int l, int multi, int chunk_size,
meta_parameters *outMeta, FILE *fout,
float *buf)
{
int j, m;
int ns = outMeta->general->sample_count;
if (multi) {
// multilook case -- average all buffered lines to produce a
// single output line
if (band1 >= 0) {
for (j=0; j<ns; ++j) {
buf[j] = 0.0;
for (m=0; m<chunk_size; ++m)
buf[j] += img_rows->pauli_lines[m][j].A;
//buf[j] += complex_amp(img_rows->pauli_lines[m][j].A);
buf[j] /= (float)chunk_size;
}
put_band_float_line(fout, outMeta, band1, line, buf);
}
if (band2 >= 0) {
for (j=0; j<ns; ++j) {
buf[j] = 0.0;
for (m=0; m<chunk_size; ++m)
buf[j] += img_rows->pauli_lines[m][j].B;
//buf[j] += complex_amp(img_rows->pauli_lines[m][j].B);
buf[j] /= (float)chunk_size;
}
put_band_float_line(fout, outMeta, band2, line, buf);
}
if (band3 >= 0) {
for (j=0; j<ns; ++j) {
buf[j] = 0.0;
for (m=0; m<chunk_size; ++m)
buf[j] += img_rows->pauli_lines[m][j].C;
//buf[j] += complex_amp(img_rows->pauli_lines[m][j].C);
buf[j] /= (float)chunk_size;
}
put_band_float_line(fout, outMeta, band3, line, buf);
}
}
else {
// not multilooking -- no averaging necessary
if (band1 >= 0) {
for (j=0; j<ns; ++j)
buf[j] = img_rows->pauli_lines[l][j].A;
//buf[j] = complex_amp(img_rows->pauli_lines[l][j].A);
put_band_float_line(fout, outMeta, band1, line, buf);
}
if (band2 >= 0) {
for (j=0; j<ns; ++j)
buf[j] = img_rows->pauli_lines[l][j].B;
//buf[j] = complex_amp(img_rows->pauli_lines[l][j].B);
put_band_float_line(fout, outMeta, band2, line, buf);
}
if (band3 >= 0) {
for (j=0; j<ns; ++j)
buf[j] = img_rows->pauli_lines[l][j].C;
//buf[j] = complex_amp(img_rows->pauli_lines[l][j].C);
put_band_float_line(fout, outMeta, band3, line, buf);
}
}
}
static void
do_coherence_bands(int entropy_band, int anisotropy_band, int alpha_band,
int class_band,
PolarimetricImageRows *img_rows,
int line, int l, int multi, int chunk_size,
gsl_matrix_complex *T, gsl_vector *eval,
gsl_matrix_complex *evec, gsl_eigen_hermv_workspace *ws,
meta_parameters *outMeta, FILE *fout,
float *buf, classifier_t *classifier)
{
if (entropy_band >= 0 || anisotropy_band >= 0 || alpha_band >= 0 ||
class_band >= 0)
{
int ns = outMeta->general->sample_count;
int onl = outMeta->general->line_count;
float *entropy = MALLOC(sizeof(float)*ns);
float *anisotropy = MALLOC(sizeof(float)*ns);
float *alpha = MALLOC(sizeof(float)*ns);
// size of the horizontal window, used for ensemble averaging
// actual window size is hw*2+1
int hw;
if (multi)
hw = 0; // no horizontal averaging
else
hw = 2; // 5 pixels averaging horizontally
// coherence -- do ensemble averaging for each element
int j;
for (j=0; j<ns; ++j) {
int ii,jj,m;
for (ii=0; ii<3; ++ii) {
for (jj=0; jj<3; ++jj) {
gsl_complex c = gsl_complex_rect(0,0);
int k,n=0;
for (m=0; m<chunk_size; ++m) {
for (k=j-hw;k<=j+hw;++k) {
if (k>=0 && k<ns && m+line>l && m+line<onl-l) {
++n;
complexFloat f =
img_rows->coh_lines[m][k]->coeff[ii][jj];
c = gsl_complex_add_real(c, f.real);
c = gsl_complex_add_imag(c, f.imag);
}
}
}
if (n>1) {
gsl_complex_div_real(c, (float)n);
}
gsl_matrix_complex_set(T,ii,jj,c);
}
}
gsl_eigen_hermv(T, eval, evec, ws);
gsl_eigen_hermv_sort(eval, evec, GSL_EIGEN_SORT_ABS_DESC);
double e1 = gsl_vector_get(eval, 0);
double e2 = gsl_vector_get(eval, 1);
double e3 = gsl_vector_get(eval, 2);
double eT = e1+e2+e3;
double P1 = e1/eT;
double P2 = e2/eT;
double P3 = e3/eT;
double P1l3 = log3(P1);
double P2l3 = log3(P2);
double P3l3 = log3(P3);
// If a Pn value is small enough, the log value will be NaN.
// In this case, the value of -Pn*log3(Pn) is supposed to be
// zero - we have to force it.
entropy[j] =
(meta_is_valid_double(P1l3) ? -P1*P1l3 : 0) +
(meta_is_valid_double(P2l3) ? -P2*P2l3 : 0) +
(meta_is_valid_double(P3l3) ? -P3*P3l3 : 0);
// mathematically, entropy is limited to be between 0 and 1.
// however it sometimes is just a bit out of that range due
// to numerical anomalies
if (!meta_is_valid_double(entropy[j]))
entropy[j] = 0.0;
else if (entropy[j] < 0)
entropy[j] = 0.0;
else if (entropy[j] > 1)
entropy[j] = 1.0;
if (e2+e3 != 0)
anisotropy[j] = (e2-e3)/(e2+e3);
else
anisotropy[j] = 0;
// as for entropy, anisotropy is limited to be between 0 and 1.
// guard against numerical anomalies (usually this is due to
// one really big eigenvalue)
if (!meta_is_valid_double(anisotropy[j]))
anisotropy[j] = 0.0;
else if (anisotropy[j] < 0)
anisotropy[j] = 0.0;
else if (anisotropy[j] > 1)
anisotropy[j] = 1.0;
// calculate the "mean alpha" (mean scattering angle)
// this is the polar angle when expressing each eigenvector
// in spherical coordinates. the mean alpha is weighted by
// the eigenvector (so weight by P1-3)
double alpha1 = calc_alpha(gsl_matrix_complex_get(evec, 0, 0));
double alpha2 = calc_alpha(gsl_matrix_complex_get(evec, 0, 1));
double alpha3 = calc_alpha(gsl_matrix_complex_get(evec, 0, 2));
alpha[j] = R2D*(P1*alpha1 + P2*alpha2 + P3*alpha3);
if (!meta_is_valid_double(alpha[j]))
alpha[j] = 0.0;
}
if (entropy_band >= 0)
put_band_float_line(fout, outMeta, entropy_band, line, entropy);
if (anisotropy_band >= 0)
put_band_float_line(fout, outMeta, anisotropy_band, line, anisotropy);
if (alpha_band >= 0)
put_band_float_line(fout, outMeta, alpha_band, line, alpha);
if (class_band >= 0) {
assert(classifier != NULL);
for (j=0; j<ns; ++j) {
buf[j] = (float)classify(classifier, entropy[j], anisotropy[j],
alpha[j]);
}
put_band_float_line(fout, outMeta, class_band, line, buf);
}
for (j=0; j<ns; ++j) {
int entropy_index = entropy[j]*(float)HIST_SIZE;
if (entropy_index<0) entropy_index=0;
if (entropy_index>HIST_SIZE-1) entropy_index=HIST_SIZE-1;
int alpha_index = HIST_SIZE-1-alpha[j]/90.0*(float)HIST_SIZE;
if (alpha_index<0) alpha_index=0;
if (alpha_index>HIST_SIZE-1) alpha_index=HIST_SIZE-1;
//printf("%10.1f %10.1f %5d %5d --> %4d\n",
// entropy[j], alpha[j],
// entropy_index, alpha_index,
// ea_hist[entropy_index][alpha_index]+1);
int anisotropy_index = anisotropy[j]*(float)HIST_SIZE;
hist_vals[entropy_index][alpha_index][anisotropy_index] += 1;
}
free(entropy);
free(anisotropy);
free(alpha);
}
}
static int verify_equal_re(const char *id, float lhs, float rhs)
{
if (fabs(lhs - rhs) > .001) {
//printf("Not equal (%s): %f != %f\n", id, lhs, rhs);
return FALSE;
}
return TRUE;
}
static int verify_equal_cpx(const char *id, complexFloat lhs, complexFloat rhs)
{
if (fabs(lhs.real - rhs.real) > .001 ||
fabs(lhs.imag - rhs.imag) > .001)
{
//printf("Not equal (%s): (%f,%f) != (%f,%f)\n", id,
// lhs.real, lhs.imag, rhs.real, rhs.imag);
return FALSE;
}
return TRUE;
}
static int verify_fd(float hh2, float vv2, complexFloat hhvv, float fs,
float fd, complexFloat alpha, complexFloat beta)
{
int ok1,ok2,ok3;
// (1) hh2 = fs*beta*beta + fd*alpha*alpha
ok1 = verify_equal_re("Eq. 1", hh2, fs*complex_amp_sqr(beta) +
fd*complex_amp_sqr(alpha));
// (2) vv2 = fs + fd
ok2 = verify_equal_re("Eq. 2", vv2, fs+fd);
// (3) hhvv = fs*beta + fd*alpha
ok3 = verify_equal_cpx("Eq. 3", hhvv, complex_add(
complex_scale(beta, fs), complex_scale(alpha, fd)));
return ok1 && ok2 && ok3;
}
static void solve_fd1(float hh2, float vv2, complexFloat hhvv,
float *fs, float *fd, complexFloat *beta)
{
// 3 equations with 3 unknowns: (complex)
// |hh|^2 = fd + |b|^2 * fs
// |vv|^2 = fs + fd
// hh*conj(vv) = b*fs - fd
// fs, fd are real. beta (b) is complex.
// splitting beta into br and bi (real and imaginary)
// 4 equations and 4 unknown: (real)
// |hh|^2 = fd + |b|^2 * fs
// |vv|^2 = fs + fd
// Re(hh*conj(vv)) = br*fs - fd
// Im(hh*conj(vv)) = bi*fs
// For brevity:
float x = hhvv.real;
float y = hhvv.imag;
float h = hh2;
float v = vv2;
// Analytic solution of the 4 equations & 4 unknowns:
// fd = (-x^2 - y^2 + hv) / D1
// br = (hx + v^2 + hv + 3xv + 2x^2) / D2 - 1
// bi = D1 * y / D2
// fs = D2 / D1
// where
// D1 = h + v + 2x
// D2 = v^2 + 2xv + x^2 + y^2
float D1 = h + v + 2.*x;
float D2 = v*v + 2.*x*v + x*x + y*y;
*fd = (h*v - x*x - y*y) / D1;
*fs = D2 / D1;
float br = (h*x + v*v + h*v + 3.*x*v + 2.*x*x) / D2 - 1.;
float bi = D1 * y / D2;
*beta = complex_new(br,bi);
}
static void solve_fd2(float hh2, float vv2, complexFloat hhvv,
float *fs, float *fd, complexFloat *alpha)
{
// 3 equations with 3 unknowns: (complex)
// |hh|^2 = fs + |a|^2 * fd
// |vv|^2 = fs + fd
// hh*conj(vv) = a*fd + fs
// fs, fd are real. alpha (a) is complex.
// splitting alpha into ar and ai (real and imaginary)
// 4 equations and 4 unknown: (real)
// |hh|^2 = fs + |a|^2 * fd
// |vv|^2 = fs + fd
// Re(hh*conj(vv)) = ar*fd + fs
// Im(hh*conj(vv)) = ai*fd
// For brevity:
float x = hhvv.real;
float y = hhvv.imag;
float h = hh2;
float v = vv2;
// Analytic solution of the 4 equations & 4 unknowns:
// fs = (-x^2 - y^2 + hv) / D1
// ar = (hx - v^2 - hv + 3xv - 2x^2) / D2 + 1
// ai = D1 * y / D2
// fd = D2 / D1
// where
// D1 = h + v - 2x
// D2 = v^2 - 2xv + x^2 + y^2
float D1 = h + v - 2.*x;
float D2 = v*v - 2.*x*v + x*x + y*y;
*fs = (h*v - x*x - y*y) / D1;
*fd = D2 / D1;
float ar = (h*x - v*v - h*v + 3.*x*v - 2.*x*x) / D2 + 1.;
float ai = D1 * y / D2;
*alpha = complex_new(ar,ai);
}
static void do_freeman(int band1, int band2, int band3,
PolarimetricImageRows *img_rows,
int line, int l, int multi, int chunk_size,
meta_parameters *outMeta, FILE *fout)
{
if (band1 >= 0 || band2 >= 0 || band3 >= 0)
{
//if (outMeta->general->radiometry != r_SIGMA) {
// asfPrintError("The Freeman/Durden decomposition requires "
// "PowerScale (Sigma, non-db) data.\n");
//}
int j, m;
int ns = outMeta->general->sample_count;
float *hh2 = MALLOC(sizeof(float)*ns);
float *vv2 = MALLOC(sizeof(float)*ns);
float *hv2 = MALLOC(sizeof(float)*ns);
complexFloat *hhvv = MALLOC(sizeof(complexFloat)*ns);
float sf = 1.0 / (float)chunk_size;
if (multi) {
// multilook case -- average all buffered lines to produce a
// single output line
for (j=0; j<ns; ++j) {
hh2[j] = 0.0;
vv2[j] = 0.0;
hhvv[j] = complex_zero();
hv2[j] = 0.0;
for (m=0; m<chunk_size; ++m) {
complexFloat hh = img_rows->s2_lines[m][j].hh;
hh2[j] += complex_amp_sqr(hh);
complexFloat vv = img_rows->s2_lines[m][j].vv;
vv2[j] += complex_amp_sqr(vv);
hhvv[j] = complex_add(hhvv[j], complex_mul(hh, complex_conj(vv)));
hv2[j] += complex_amp_sqr(img_rows->s2_lines[m][j].hv);
}
hh2[j] *= sf;
vv2[j] *= sf;
hv2[j] *= sf;
hhvv[j] = complex_scale(hhvv[j], sf);
}
}
else {
// not multilooking -- no averaging necessary
for (j=0; j<ns; ++j) {
complexFloat hh = img_rows->s2_lines[l][j].hh;
hh2[j] = complex_amp_sqr(hh);
complexFloat vv = img_rows->s2_lines[l][j].vv;
vv2[j] = complex_amp_sqr(vv);
hhvv[j] = complex_mul(hh, complex_conj(vv));
hv2[j] = complex_amp_sqr(img_rows->s2_lines[l][j].hv);
}
}
float *Ps = MALLOC(sizeof(float)*ns);
float *Pd = MALLOC(sizeof(float)*ns);
float *Pv = MALLOC(sizeof(float)*ns);
// now calculate fs, fd and alpha or beta for each sample, and
// from those we can get the Ps, Pd, and Pv values
for (j=0; j<ns; ++j) {
float fs, fd;
complexFloat alpha, beta;
if (hhvv[j].real > 0) {
// Re(Shh*conj(Svv))>0 ==> alpha=-1, solve for fs, fd, and beta
solve_fd1(hh2[j], vv2[j], hhvv[j], &fs, &fd, &beta);
alpha = complex_new(-1, 0);
}
else {
// Re(Shh*conj(Svv))<0 ==> beta=1, solve for fs, fd, and alpha
solve_fd2(hh2[j], vv2[j], hhvv[j], &fs, &fd, &alpha);
beta = complex_new(1, 0);
}
// double-check the solution
verify_fd(hh2[j], vv2[j], hhvv[j], fs, fd, alpha, beta);
// now calculate the final contributions from each scattering mechanism
Ps[j] = fs * (1. + complex_amp_sqr(beta));
Pd[j] = fd * (1. + complex_amp_sqr(alpha));
Pv[j] = 8. * hv2[j];
// convert to dB
Ps[j] = 10*log10(Ps[j]*Ps[j]);
Pd[j] = 10*log10(Pd[j]*Pd[j]);
Pv[j] = 10*log10(Pv[j]*Pv[j]);
}
free(hh2);
free(vv2);
free(hv2);
free(hhvv);
if (band1 >= 0)
put_band_float_line(fout, outMeta, band1, line, Ps);
if (band2 >= 0)
put_band_float_line(fout, outMeta, band2, line, Pd);
if (band3 >= 0)
put_band_float_line(fout, outMeta, band3, line, Pv);
free(Pd);
free(Ps);
free(Pv);
}
}
static void do_class_map(classifier_t *classifier, int class_band, int wide,
const char *outFile)
{
// build the class_map array from the hist_vals array.
int i, j, k, size = HIST_SIZE;
if (class_band >= 0) {
if (!wide) {
// non-wide: this is the Cloude-Pottier 8 classes case, where
// we use only half of the class_map array
for (i=0; i<size; ++i) {
double alpha = (double)(size-1-i)/(double)size*90.;
class_map[i][0] = 0;
for (j=1; j<size; ++j) {
int count = 0;
for (k=0; k<size; ++k)
count += hist_vals[j][i][k];
if (count > 0) {
double entropy = (double)j/(double)size;
class_map[i][j] = classify(classifier, entropy, 0, alpha);
}
else
class_map[i][j] = 0;
}
}
// drawing the white border lines -- assumes look-up-tables use
// "255" as white. (cloude8.lut)
int prev = -1;
for (i=0; i<size; ++i) {
double alpha = (double)(size-1-i)/(double)size*90.;
for (j=0; j<size; ++j) {
double entropy = (double)j/(double)size;
int curr = classify(classifier, entropy, 0, alpha);
if (j>0 && prev != curr)
class_map[i][j] = 255;
prev = curr;
}
}
prev = -1;
for (j=0; j<size; ++j) {
double entropy = (double)j/(double)size;
for (i=0; i<size; ++i) {
double alpha = (double)(size-1-i)/(double)size*90.;
int curr = classify(classifier, entropy, 0, alpha);
if (i>0 && prev != curr)
class_map[i][j] = 255;
prev = curr;
}
}
// if we have the file "ea_boundary.txt" in the share directory
// (this file can be generated by calling make_entropy_alpha_boundary()
// defined below, and exposed via asf_calpol)
add_boundary(FALSE);
dump_class_map(outFile, FALSE);
}
else {
// wide: this is the Cloude-Pottier 16 classes case, where
// we use the full (double-width) ea_hist array, the left half
// being the anisotropy=0 plane, the right half being the
// anisotropy=.5 plane (though we actually use .55 below to ensure
// we're definitely in the >.5 blocks -- .5 could possibly be
// classified in the (0,.5) range depending on use of <= vs < above,
// roundoff, etc)
for (i=0; i<size; ++i) {
double alpha = (double)(size-1-i)/(double)size*90.;
for (j=0; j<size*2; ++j) {
if (j==0) {
class_map[i][j] = 0;
}
else if (j == size) {
class_map[i][j] = 255;
}
else {
int jj = j;
if (j>size) jj -= size;
int count = 0;
for (k=0; k<size; ++k)
count += hist_vals[jj][i][k];
if (count > 0) {
double entropy = (double)jj/(double)size;
double aniso = j > size ? 0.55 : 0.0;
class_map[i][j] = classify(classifier, entropy, aniso, alpha);
}
else
class_map[i][j] = 0;
}
}
}
// drawing the white border lines -- assumes look-up-tables use
// "255" as white. (cloude16.lut)
int prev = -1;
for (i=0; i<size; ++i) {
double alpha = (double)(size-1-i)/(double)size*90.;
for (j=0; j<size*2; ++j) {
double entropy = j > size ?
(double)(j-size)/(double)size :
(double)j/(double)size;
double aniso = j > size ? 0.55 : 0.0;
int curr = classify(classifier, entropy, aniso, alpha);
if (j>0 && prev != curr)
class_map[i][j] = 255;
prev = curr;
}
}
prev = -1;
for (j=0; j<size*2; ++j) {
double entropy = j > size ?
(double)(j-size)/(double)size :
(double)j/(double)size;
double aniso = j > size ? 0.55 : 0.0;
for (i=0; i<size; ++i) {
double alpha = (double)(size-1-i)/(double)size*90.;
int curr = classify(classifier, entropy, aniso, alpha);
if (i>0 && prev != curr)
class_map[i][j] = 255;
prev = curr;
}
}
// if we have the file "ea_boundary.txt" in the share directory
// (this file can be generated by calling make_entropy_alpha_boundary()
// defined below, and exposed via asf_calpol)
add_boundary(TRUE);
dump_class_map(outFile, TRUE);
}
}
}
void polarimetric_decomp(const char *inFile, const char *outFile,
int amplitude_band,
int pauli_1_band,
int pauli_2_band,
int pauli_3_band,
int entropy_band,
int anisotropy_band,
int alpha_band,
int sinclair_1_band,
int sinclair_2_band,
int sinclair_3_band,
int freeman_1_band,
int freeman_2_band,
int freeman_3_band,
const char *classFile,
int class_band)
{
int debug_mode = classFile && strcmp_case(classFile, "DEBUG")==0;
int debug_band = -1;
if (debug_mode) {
debug_band = class_band;
class_band = -1;
}
char *meta_name = appendExt(inFile, ".meta");
meta_parameters *inMeta = meta_read(meta_name);
meta_parameters *outMeta = meta_read(meta_name);
char *in_img_name = appendExt(inFile, ".img");
char *out_img_name = appendExt(outFile, ".img");
int i, j, k;
//my_randomize();
// chunk_size represents the number of rows we keep in memory at one
// time, centered on the row currently being processed. This is to
// handle the ensemble averaging that we do
int chunk_size = 5;
assert((chunk_size-1)%2==0); // chunk_size should be odd
// If the image is not multilooked, we will multilook it here, and use
// the multilooked values for the ensemble averaging. This will result
// in much less smoothing of the image.
int multi = FALSE;
if (inMeta->sar && inMeta->sar->multilook==0) {
multi = TRUE;
chunk_size = inMeta->sar->look_count;
}
// aliases
int nl = inMeta->general->line_count;
int ns = inMeta->general->sample_count;
FILE *fin = fopenImage(in_img_name, "rb");
FILE *fout = fopenImage(out_img_name, "wb");
// this struct will hold the current row being processed, and
// chunk_size/2 rows before & after
PolarimetricImageRows *img_rows =
polarimetric_image_rows_new(inMeta, chunk_size, multi);
// make sure all bands we need are there, and find their numbers
// and offsets
int ok = polarimetric_image_rows_get_bands(img_rows);
if (!ok)
asfPrintError("Not all required bands found-- "
"is this SLC quad-pol data?\n");
float *buf = MALLOC(sizeof(float)*ns);
// at the start, we want to load the buffers as follows: (for chunk_size=5)
// *lines[0] = ALL ZEROS
// *lines[1] = ALL ZEROS
// *lines[2] = line 0 of the image
// *lines[3] = line 1 of the image
// *lines[4] = line 2 of the image
// next time through the loop:
// *lines[0] = ALL ZEROS
// *lines[1] = line 0 of the image
// *lines[2] = line 1 of the image
// *lines[3] = line 2 of the image
// *lines[4] = line 3 of the image
// we don't actually move the data from line n to line n-1, we just move
// the pointers. initially, the pointers will match the buffer (as set
// in the loop directly above), but the second time through the pointers
// slide down one row (line 3 is loaded into the beginning of the buffer,
// but line pointer 4 points at the beginning).
if (multi) {
// multilook case:
// preload rows --> load look_count rows, these will all be combined
// to produce a single output line
polarimetric_image_rows_load_new_rows(img_rows, fin);
}
else {
// non-multilook case:
// preload rows --> center of window will be row 0.
// the next (chunk_size+1)/2 rows are also loaded, and ready to go.
for (i=0; i<(chunk_size+1)/2; ++i)
polarimetric_image_rows_load_next_row(img_rows, fin);
assert(img_rows->current_row == 0);
}
// output metadata differs from input only in the number
// of bands, and the band names
char *out_meta_name = appendExt(outFile, ".meta");
int nBands =
(amplitude_band>=0) +
(pauli_1_band>=0) + (pauli_2_band>=0) + (pauli_3_band>=0) +
(entropy_band>=0) + (anisotropy_band>=0) + (alpha_band>=0) +
(sinclair_1_band>=0) + (sinclair_2_band>=0) + (sinclair_3_band>=0) +
(class_band >= 0) +
(freeman_1_band>=0) + (freeman_2_band>=0) + (freeman_3_band>=0);
char bands[255];
strcpy(bands, "");
for (i=0; i<10; ++i) {
if (amplitude_band == i)
strcat(bands, "HH-AMP,");
else if (sinclair_1_band == i)
strcat(bands, "HH,");
else if (sinclair_2_band == i)
strcat(bands, "HV+VH_2,");
else if (sinclair_3_band == i)
strcat(bands, "VV,");
else if (pauli_1_band == i)
strcat(bands, "HH-VV,");
else if (pauli_2_band == i)
strcat(bands, "HV+VH,");
else if (pauli_3_band == i)
strcat(bands, "HH+VV,");
else if (entropy_band == i)
strcat(bands, "Entropy,");
else if (anisotropy_band == i)
strcat(bands, "Anisotro,"); // abbreviated version, agrees with GUI
else if (alpha_band == i)
strcat(bands, "Alpha,");
else if (freeman_1_band == i)
strcat(bands, "Ps,");
else if (freeman_2_band == i)
strcat(bands, "Pd,");
else if (freeman_3_band == i)
strcat(bands, "Pv,");
else if (class_band == i) {
if (!classFile)
strcat(bands,"Classified,");
else if (strncmp_case(classFile,"cloude8",7)==0)
strcat(bands, "Cloude-Pottier-8,");
else if (strncmp_case(classFile,"cloude16",8)==0)
strcat(bands, "Cloude-Pottier-16,");
else {
// append the classification filename as the band name (minus .cla)
char *s = appendExt(classFile,"");
strcat(bands, s);
strcat(bands, ",");
free(s);
}
}
else
break;
}
if (strlen(bands) > 0) // chop last comma
bands[strlen(bands)-1] = '\0';
outMeta->general->band_count = nBands;
strcpy(outMeta->general->bands, bands);
// for multilooking, the number of output lines shrinks by look_count
int onl = multi ? nl/chunk_size : nl;
if (multi) {
outMeta->sar->multilook = 1;
outMeta->general->line_count = onl;
outMeta->general->y_pixel_size *= outMeta->sar->look_count;
outMeta->sar->azimuth_time_per_pixel *= outMeta->sar->look_count;
}
outMeta->general->image_data_type = POLARIMETRIC_IMAGE;
meta_write(outMeta, out_meta_name);
free(out_meta_name);
// set up the classification, if needed
classifier_t *classifier = NULL;
if (classFile != NULL && class_band >= 0)
classifier = read_classifier(classFile);
// population histogram image, in entropy-alpha space
for (i=0; i<HIST_SIZE; ++i)
for (j=0; j<HIST_SIZE; ++j)
for (k=0; k<HIST_SIZE; ++k)
hist_vals[i][j][k] = 0;
//-----------------------------------------------------------------------
// done setting up metadata, now write the data
// gsl infrastructure for calculating eigen- vals & vecs for the
// coherence matrix
gsl_matrix_complex *T = gsl_matrix_complex_alloc(3,3);
gsl_vector *eval = gsl_vector_alloc(3);
gsl_matrix_complex *evec = gsl_matrix_complex_alloc(3,3);
gsl_eigen_hermv_workspace *ws = gsl_eigen_hermv_alloc(3);
// now loop through the lines of the output image
for (i=0; i<onl; ++i) {
// Indicates which line in the various *lines arrays contains
// what corresponds to line i in the output. since the line pointers
// slide, this never changes.
const int l = (chunk_size-1)/2;
// normal amplitude band (usually, this is added to allow terrcorr)
if (amplitude_band >= 0)
put_band_float_line(fout, outMeta, amplitude_band, i, img_rows->amp);
// if requested, generate sinlair output
do_sinclair_bands(sinclair_1_band, sinclair_2_band, sinclair_3_band,
img_rows, i, l, multi, chunk_size, outMeta, fout, buf);
// calculate the pauli output (magnitude of already-calculated
// complex pauli basis elements), and save the requested pauli
// bands in the output
do_pauli_bands(pauli_1_band, pauli_2_band, pauli_3_band,
img_rows, i, l, multi, chunk_size, outMeta, fout, buf);
// Freeman-Durden
do_freeman(freeman_1_band, freeman_2_band, freeman_3_band,
img_rows, i, l, multi, chunk_size, outMeta, fout);
// do any polarimetry that uses the coherence matrix
do_coherence_bands(entropy_band, anisotropy_band, alpha_band, class_band,
img_rows, i, l, multi, chunk_size, T, eval, evec, ws,
outMeta, fout, buf, classifier);
// load the next row, if there are still more to go
if (i<onl-1) {
if (multi) {
polarimetric_image_rows_load_new_rows(img_rows, fin);
}
else {
polarimetric_image_rows_load_next_row(img_rows, fin);
assert(img_rows->current_row == i+1);
}
}
asfLineMeter(i,onl);
}
if (entropy_band >= 0 || anisotropy_band >= 0 || alpha_band >= 0 ||
class_band >= 0)
{
if (entropy_band >= 0 || anisotropy_band >= 0 || alpha_band >= 0)
asfPrintStatus("Generating population histogram...\n");
else
asfPrintStatus("Generating population histograms and "
"classification map...\n");
// dump population graph & class map
int wide = FALSE;
if (class_band >= 0)
wide = strncmp_case(classFile,"cloude16",8) == 0;
// dump projections of the 3-d histogram
dump_hist(outFile, ENTROPY_ALPHA);
dump_hist(outFile, ALPHA_ANISOTROPY);
dump_hist(outFile, ANISOTROPY_ENTROPY);
dump_combined_hist(outFile);
// dump classification map (entropy/alpha)
do_class_map(classifier, class_band, wide, outFile);
}
gsl_vector_free(eval);
gsl_eigen_hermv_free(ws);
gsl_matrix_complex_free(evec);
gsl_matrix_complex_free(T);
polarimetric_image_rows_free(img_rows);
fclose(fin);
fclose(fout);
free(buf);
free(out_img_name);
free(in_img_name);
free(meta_name);
free_classifier(classifier);
meta_free(inMeta);
meta_free(outMeta);
}
static int has_amp_band(const char *inFile)
{
int ret = FALSE;
char *mfile = appendExt(inFile, ".meta");
if (fileExists(mfile)) {
meta_parameters *meta = meta_read(mfile);
if (strncmp_case(meta->general->bands, "AMP", 3) == 0)
ret = TRUE;
meta_free(meta);
}
free(mfile);
return ret;
}
void cpx2classification(const char *inFile, const char *outFile,
int tc_flag, const char *classFile)
{
if (tc_flag && has_amp_band(inFile))
polarimetric_decomp(inFile, outFile,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,classFile, 1);
else
polarimetric_decomp(inFile, outFile,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,classFile, 0);
}
void cpx2sinclair(const char *inFile, const char *outFile, int tc_flag)
{
asfPrintStatus("\n\nGenerating Sinclair decomposition channels\n");
if (tc_flag && has_amp_band(inFile))
polarimetric_decomp(inFile,outFile,0,-1,-1,-1,-1,-1,-1,1,2,3,-1,-1,-1,
NULL,-1);
else
polarimetric_decomp(inFile,outFile,-1,-1,-1,-1,-1,-1,-1,0,1,2,-1,-1,-1,
NULL,-1);
}
void cpx2pauli(const char *inFile, const char *outFile, int tc_flag)
{
asfPrintStatus("\n\nGenerating Pauli decomposition channels\n");
if (tc_flag && has_amp_band(inFile))
polarimetric_decomp(inFile,outFile,0,1,2,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,
NULL,-1);
else
polarimetric_decomp(inFile,outFile,-1,0,1,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,
NULL,-1);
}
void cpx2cloude_pottier(const char *inFile, const char *outFile, int tc_flag)
{
asfPrintStatus("\n\nCalculating entropy, anisotropy and alpha "
"for Cloude-Pottier classification\n");
cpx2classification(inFile, outFile, tc_flag, "cloude8.cla");
}
void cpx2cloude_pottier8(const char *inFile, const char *outFile, int tc_flag)
{
asfPrintStatus("\n\nCalculating entropy, anisotropy and alpha "
"for Cloude-Pottier classification (8 classes)\n");
cpx2classification(inFile, outFile, tc_flag, "cloude8.cla");
}
void cpx2cloude_pottier16(const char *inFile, const char *outFile, int tc_flag)
{
asfPrintStatus("\n\nCalculating entropy, anisotropy and alpha "
"for Cloude-Pottier classification (16 classes)\n");
cpx2classification(inFile, outFile, tc_flag, "cloude16.cla");
}
void cpx2entropy_anisotropy_alpha(const char *inFile, const char *outFile,
int tc_flag)
{
asfPrintStatus("\n\nCalculating entropy, anisotropy and alpha.\n");
if (tc_flag && has_amp_band(inFile))
polarimetric_decomp(inFile,outFile,0,-1,-1,-1,1,2,3,-1,-1,-1,-1,-1,-1,
NULL,-1);
else
polarimetric_decomp(inFile,outFile,-1,-1,-1,-1,0,1,2,-1,-1,-1,-1,-1,-1,
NULL,-1);
}
void cpx2freeman_durden(const char *inFile, const char *outFile, int tc_flag)
{
asfPrintStatus("\n\nGenerating Freeman/Durden decomposition channels\n");
if (tc_flag && has_amp_band(inFile))
polarimetric_decomp(inFile,outFile,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,2,3,
NULL,-1);
else
polarimetric_decomp(inFile,outFile,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,
NULL,-1);
}
static gsl_matrix *make_diag3(double e00, double e11, double e22)
{
gsl_matrix *mat = gsl_matrix_calloc(3, 3);
gsl_matrix_set(mat, 0, 0, e00);
gsl_matrix_set(mat, 1, 1, e11);
gsl_matrix_set(mat, 2, 2, e22);
return mat;
}
static void calc_entropy_alpha(gsl_matrix *mat, double *entropy, double *alpha)
{
gsl_vector *eval = gsl_vector_alloc(3);
gsl_matrix *evec = gsl_matrix_alloc(3,3);
gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(3);
gsl_eigen_symmv(mat, eval, evec, w);
gsl_eigen_symmv_free(w);
gsl_eigen_symmv_sort(eval, evec, GSL_EIGEN_SORT_ABS_ASC);
double e1 = gsl_vector_get(eval, 0);
double e2 = gsl_vector_get(eval, 1);
double e3 = gsl_vector_get(eval, 2);
double eT = e1+e2+e3;
double P1 = e1/eT;
double P2 = e2/eT;
double P3 = e3/eT;
double P1l3 = log3(P1);
double P2l3 = log3(P2);
double P3l3 = log3(P3);
// If a Pn value is small enough, the log value will be NaN.
// In this case, the value of -Pn*log3(Pn) is supposed to be
// zero - we have to force it.
*entropy =
(meta_is_valid_double(P1l3) ? -P1*P1l3 : 0) +
(meta_is_valid_double(P2l3) ? -P2*P2l3 : 0) +
(meta_is_valid_double(P3l3) ? -P3*P3l3 : 0);
// calculate the "mean alpha" (mean scattering angle)
// this is the polar angle when expressing each eigenvector
// in spherical coordinates. the mean alpha is weighted by
// the eigenvector (so weight by P1-3)
double alpha1 = calc_alpha_real(gsl_matrix_get(evec, 0, 0));
double alpha2 = calc_alpha_real(gsl_matrix_get(evec, 0, 1));
double alpha3 = calc_alpha_real(gsl_matrix_get(evec, 0, 2));
*alpha = R2D*(P1*alpha1 + P2*alpha2 + P3*alpha3);
if (!meta_is_valid_double(*alpha))
*alpha = 0.0;
gsl_vector_free(eval);
gsl_matrix_free(evec);
}
void make_entropy_alpha_boundary(const char *fname, int size)
{
FILE *fp = FOPEN(fname, "w");
fprintf(fp, "Entropy/Alpha Feasible Region Boundary\n");
fprintf(fp, "File Size: %d\n\n", size);
fprintf(fp, "Entropy,Alpha\n");
// number of points generated in each curve's section
int numtop = size/2;
int numbot1 = size/4;
int numbot2 = size/4;
// fix any roundoff problems, while ensuring that numbot1 & numbot2
// are equal
while (numtop+numbot1+numbot2 < size) {
++numbot2; ++numbot1;
}
while (numtop+numbot1+numbot2 > size) {
--numtop;
}
assert(numtop+numbot1+numbot2 == size);
int i;
double entropy, alpha;
// Generate the top curve by finding the eigenvalues of
// the matrix:
// [ 1 0 0 ]
// [ 0 m 0 ]
// [ 0 0 m ]
// for 0 <= m <= 1
for (i=0; i<numtop; ++i) {
double m = (double)i / (double)(numtop-1);
gsl_matrix *mat = make_diag3(1, m, m);
calc_entropy_alpha(mat, &entropy, &alpha);
fprintf(fp,"%f,%f\n",entropy,alpha);
gsl_matrix_free(mat);
asfPercentMeter((double)i/size);
}
// Generate the first part of the bottom curve by finding the eigenvalues
// of the matrix:
// [ 1 0 0 ]
// [ 0 1 0 ]
// [ 0 0 2m ]
// for 0 <= m <= 0.5
// ==> We just use m instead of 2m, and let m go from 0 to 1.
for (i=0; i<numbot1; ++i) {
double m = (double)i / (double)(numbot1-1);
gsl_matrix *mat = make_diag3(1, 1, m);
calc_entropy_alpha(mat, &entropy, &alpha);
fprintf(fp,"%f,%f\n",entropy,alpha);
gsl_matrix_free(mat);
asfPercentMeter((double)(i+numtop)/size);
}
// Generate the second part of the bottom curve by finding the eigenvalues
// of the matrix:
// [ 2m-1 0 0 ]
// [ 0 1 0 ]
// [ 0 0 1 ]
// for 0.5 <= m <= 1
// ==> We just use m instead of 2m-1, and let m go from 0 to 1.
for (i=0; i<numbot2; ++i) {
double m = (double)i / (double)(numbot2-1);
gsl_matrix *mat = make_diag3(m, 1, 1);
calc_entropy_alpha(mat, &entropy, &alpha);
fprintf(fp,"%f,%f\n",entropy,alpha);
gsl_matrix_free(mat);
asfPercentMeter((double)(i+numtop+numbot1)/size);
}
asfPercentMeter(1.0);
FCLOSE(fp);
}
| {
"alphanum_fraction": 0.6008521165,
"avg_line_length": 32.4531668153,
"ext": "c",
"hexsha": "bdd59a6dc3f5abccffc3b68174300c44363a7351",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z",
"max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "glshort/MapReady",
"max_forks_repo_path": "src/libasf_sar/polarimetry.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"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": "glshort/MapReady",
"max_issues_repo_path": "src/libasf_sar/polarimetry.c",
"max_line_length": 80,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "glshort/MapReady",
"max_stars_repo_path": "src/libasf_sar/polarimetry.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z",
"num_tokens": 23088,
"size": 72760
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C code for the conversion between time scales.
*
* Formulas are taken from the UNITED STATES NAVAL OBSERVATORY CIRCULAR NO. 179 by George H. Kaplan
* See http://aa.usno.navy.mil/publications/docs/Circular_179.php
*
*/
#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>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "timeconversion.h"
/***********************************************************/
/********* Core functions to compute overlaps **************/
/* Table of leap seconds - from LAL XLALLeapSeconds.h */
static const struct leaps_table { double jd; int gpssec; int taiutc; } leaps[] =
{
{2444239.5, -43200, 19}, /* 1980-Jan-01 */
{2444786.5, 46828800, 20}, /* 1981-Jul-01 */
{2445151.5, 78364801, 21}, /* 1982-Jul-01 */
{2445516.5, 109900802, 22}, /* 1983-Jul-01 */
{2446247.5, 173059203, 23}, /* 1985-Jul-01 */
{2447161.5, 252028804, 24}, /* 1988-Jan-01 */
{2447892.5, 315187205, 25}, /* 1990-Jan-01 */
{2448257.5, 346723206, 26}, /* 1991-Jan-01 */
{2448804.5, 393984007, 27}, /* 1992-Jul-01 */
{2449169.5, 425520008, 28}, /* 1993-Jul-01 */
{2449534.5, 457056009, 29}, /* 1994-Jul-01 */
{2450083.5, 504489610, 30}, /* 1996-Jan-01 */
{2450630.5, 551750411, 31}, /* 1997-Jul-01 */
{2451179.5, 599184012, 32}, /* 1999-Jan-01 */
{2453736.5, 820108813, 33}, /* 2006-Jan-01 */
{2454832.5, 914803214, 34}, /* 2009-Jan-01 */
{2456109.5, 1025136015, 35}, /* 2012-Jul-01 */
{2457204.5, 1119744016, 36} /* 2015-Jul-01 */
};
static const int numleaps = sizeof( leaps ) / sizeof( *leaps );
/* Returns the leap seconds TAI-UTC at a given GPS second */
static int leapseconds(const double gpstime)
{
int leap;
if ( gpstime < leaps[0].gpssec )
{
printf( "Error - Don't know leap seconds before GPS time %d\n", leaps[0].gpssec );
exit(1);
}
/* scan leap second table and locate the appropriate interval */
for ( leap = 1; leap < numleaps; ++leap )
if ( gpstime < leaps[leap].gpssec )
break;
return leaps[leap-1].taiutc;
}
/***********************************************************/
/********* Core functions to compute overlaps **************/
/* Function computing the correction from the earth rotation angle to the gmst angle */
/* Formula (2.12) of the USNO circular */
static double gmst_correction(const double gpstime) /* gpstime in seconds */
{
/* T is the number of julian centuries since J2000.0 */
double T = (gpstime - EPOCH_J2000_0_GPS)/(86400.0*36525.0);
double correction = 2*PI*(0.014506 + 4612.156534*T + 1.3915817*T*T - 0.00000044*T*T*T - 0.000029956*T*T*T*T - 0.0000000368*T*T*T*T*T)/15.0/86400.0;
return correction;
}
/* Earth rotation angle from the UT1 seconds elapsed since J2000.0 */
/* Formula (2.11) of the USNO circular */
static double era_angle_from_ut1(const double ut1_j2000) /* ut1_j2000 in seconds */
{
double DU = ut1_j2000/86400.0;
double fracDU = DU - trunc(DU);
double era_angle = 2*PI*(0.7790572732640 + 0.00273781191135448*DU + fracDU);
return era_angle;
}
/* Function computing the gmst angle from the gps time */
/* Formula (2.12) of the USNO circular */
double gmst_angle_from_gpstime(const double gpstime) /* gpstime in seconds */
{
/* UTC time - UTC at J2000, computed from the GPS time */
double utc_j2000 = (gpstime - EPOCH_J2000_0_GPS) - (leapseconds(gpstime) - EPOCH_J2000_0_TAI_UTC);
/* Earth rotation angle */
/* BEWARE: here we assimilate UTC and UT1 times - by construction, |UTC-UT1| < 1sec */
double era_angle = era_angle_from_ut1(utc_j2000);
/* GMST angle */
double gmst_angle = era_angle + gmst_correction(gpstime);
return gmst_angle;
}
| {
"alphanum_fraction": 0.6462850183,
"avg_line_length": 31.8217054264,
"ext": "c",
"hexsha": "35ae512ebd09ab6ec05b3bdb912f78ce25e4d0f4",
"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/timeconversion.c",
"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/timeconversion.c",
"max_line_length": 149,
"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/timeconversion.c",
"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": 1359,
"size": 4105
} |
#ifndef LINALG_H_GUARD
#define LINALG_H_GUARD
#include "coneOS.h"
#include <cblas.h>
#include <math.h>
void setAsScaledArray(double *x, const double * a,const double b,int len);
void scaleArray(double * a,const double b,int len);
double innerProd(const double * x, const double * y, int len);
double calcNorm(const double * v,int len);
double calcNormInf(const double *a, int l);
double calcNormSq(const double * v,int len);
void addScaledArray(double * a, const double * b, int n, const double sc);
double calcNormDiff(const double *a,const double *b, int l);
double calcNormInfDiff(const double *a, const double *b, int l);
void accumByAtrans(Data * d, const double *x, double *y);
void accumByA(Data * d, const double *x, double *y);
#endif
| {
"alphanum_fraction": 0.7372654155,
"avg_line_length": 37.3,
"ext": "h",
"hexsha": "997655fc6bb78c2f4dc1ec509f4c4d66bc344343",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-12-20T19:38:22.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-26T23:10:34.000Z",
"max_forks_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee",
"max_forks_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_forks_repo_name": "cvxgrp/coneos",
"max_forks_repo_path": "coneOSdense/linAlg.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_issues_repo_name": "cvxgrp/coneos",
"max_issues_repo_path": "coneOSdense/linAlg.h",
"max_line_length": 74,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "44b7c18be03ececa592e4f7aa85ced8c7a3366ee",
"max_stars_repo_licenses": [
"BSD-2-Clause-FreeBSD"
],
"max_stars_repo_name": "cvxgrp/coneos",
"max_stars_repo_path": "coneOSdense/linAlg.h",
"max_stars_repo_stars_event_max_datetime": "2015-08-29T07:42:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-08-29T07:42:29.000Z",
"num_tokens": 204,
"size": 746
} |
#include <gsl/gsl_complex.h>
#include <gsl/gsl_linalg.h>
void mgsl_linalg_complex_LU_det(gsl_matrix_complex *LU, int signum, gsl_complex *res)
{
gsl_complex ret = gsl_linalg_complex_LU_det(LU, signum);
*res = ret;
}
void mgsl_linalg_complex_LU_sgndet(gsl_matrix_complex *LU, int signum, gsl_complex *res)
{
gsl_complex ret = gsl_linalg_complex_LU_sgndet(LU, signum);
*res = ret;
}
void mgsl_linalg_complex_householder_transform(gsl_vector_complex *w, gsl_complex *res)
{
gsl_complex ret = gsl_linalg_complex_householder_transform(w);
*res = ret;
}
int mgsl_linalg_complex_householder_hm(gsl_complex *tau, gsl_vector_complex *v, gsl_matrix_complex *A)
{
return gsl_linalg_complex_householder_hm(*tau, v, A);
}
int mgsl_linalg_complex_householder_mh(gsl_complex *tau, gsl_vector_complex *v, gsl_matrix_complex *A)
{
return gsl_linalg_complex_householder_mh(*tau, v, A);
}
int mgsl_linalg_complex_householder_hv(gsl_complex *tau, gsl_vector_complex *v, gsl_vector_complex *w)
{
return gsl_linalg_complex_householder_hv(*tau, v, w);
}
| {
"alphanum_fraction": 0.7952606635,
"avg_line_length": 29.3055555556,
"ext": "c",
"hexsha": "198c0ce557247c600bf57b43e9e2b38d766427b0",
"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": "e3cfa4c97bbe73e5c646942a171af661e535e361",
"max_forks_repo_licenses": [
"Artistic-2.0"
],
"max_forks_repo_name": "frithnanth/raku-Math-Libgsl-LinearAlgebra",
"max_forks_repo_path": "src/linalg.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e3cfa4c97bbe73e5c646942a171af661e535e361",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Artistic-2.0"
],
"max_issues_repo_name": "frithnanth/raku-Math-Libgsl-LinearAlgebra",
"max_issues_repo_path": "src/linalg.c",
"max_line_length": 102,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e3cfa4c97bbe73e5c646942a171af661e535e361",
"max_stars_repo_licenses": [
"Artistic-2.0"
],
"max_stars_repo_name": "frithnanth/raku-Math-Libgsl-LinearAlgebra",
"max_stars_repo_path": "src/linalg.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 309,
"size": 1055
} |
/*
* 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 avl_6c9ab2d0_f8bc_4fb1_bc21_7fc0c6eb4bec_h
#define avl_6c9ab2d0_f8bc_4fb1_bc21_7fc0c6eb4bec_h
#include <assert.h>
#include <gslib/std.h>
__gslib_begin__
struct _avltree_trait_copy {};
struct _avltree_trait_detach {};
template<class _ty>
struct _avltreenode_cpy_wrapper
{
typedef _ty value;
typedef _avltreenode_cpy_wrapper<_ty> myref;
typedef _avltree_trait_copy tsf_behavior;
value _value;
myref* _left;
myref* _right;
myref* _parent;
int _balance;
myref()
{
_left = _right = _parent = nullptr;
_balance = 0;
}
value* get_ptr() { return &_value; }
const value* const_ptr() const { return &_value; }
value& get_ref() { return _value; }
const value& const_ref() const { return _value; }
void born() {}
void kill() {}
template<class _ctor>
void born() {}
template<class _ctor>
void kill() {}
void copy(const myref* a) { get_ref() = a->const_ref(); }
void attach(myref* a) { assert(0); }
void swap_data(myref* a) { std::swap(_value, a->_value); }
};
template<class _ty>
struct _avltreenode_wrapper
{
typedef _ty value;
typedef _avltreenode_wrapper<_ty> myref;
typedef _avltree_trait_detach tsf_behavior;
value* _value;
myref* _left;
myref* _right;
myref* _parent;
int _balance;
myref()
{
_left = _right = _parent = nullptr;
_value = nullptr;
_balance = 0;
}
value* get_ptr() { return _value; }
const value* const_ptr() const { return _value; }
value& get_ref() { return *_value; }
const value& const_ref() const { return *_value; }
void copy(const myref* a) { get_ref() = a->const_ref(); }
void born() { !! }
template<class _ctor>
void born() { _value = new _ctor; }
void kill() { if(_value) { delete _value; _value = nullptr; } }
template<class _ctor>
void kill() { if(_value) { delete _value; _value = nullptr; } }
void attach(myref* a)
{
assert(a && a->_value);
kill();
_value = a->_value;
a->_value = nullptr;
}
void swap_data(myref* a) { gs_swap(_value, a->_value); }
};
template<class _wrapper>
struct _avltree_allocator
{
typedef _wrapper wrapper;
static wrapper* born() { return new wrapper; }
static void kill(wrapper* w) { delete w; }
};
template<class _val>
struct _avltreenode_val
{
typedef _val value;
typedef const _val const_value;
typedef _avltreenode_val<_val> myref;
union
{
value* _vptr;
const_value* _cvptr;
};
myref() { _vptr = nullptr; }
value* get_wrapper() const { return _vptr; }
operator bool() const { return _vptr != nullptr; }
bool is_left() const { return (_cvptr && _cvptr->_parent) ? _cvptr->_parent->_left == _cvptr : false; }
bool is_right() const { return (_cvptr && _cvptr->_parent) ? _cvptr->_parent->_right == _cvptr : false; }
bool is_root() const { return _cvptr ? (!_cvptr->_parent) : false; }
bool is_leaf() const { return _cvptr ? (!_cvptr->_left && !_cvptr->_right) : false; }
int up_depth() const
{
int depth = 0;
for(value* p = _vptr; p; p = p->_parent, depth ++);
return depth;
}
int down_depth() const { return _down_depth(_vptr, 0); }
bool operator==(const value* v) const { return _vptr == v; }
bool operator!=(const value* v) const { return _vptr != v; }
int get_balance() const { return _vptr->_balance; }
void set_balance(int b) { _vptr->_balance = b; }
void swap_data(myref& a) { _vptr->swap_data(a._vptr); }
public:
static void connect_left_child(value* p, value* l)
{
assert(p);
p->_left = l;
if(l)
l->_parent = p;
}
static void connect_right_child(value* p, value* r)
{
assert(p);
p->_right = r;
if(r)
r->_parent = p;
}
static bool disconnect_parent_child(value* p, value* c)
{
assert(p && c && (c->_parent == p));
if(p->_left == c) {
p->_left = c->_parent = nullptr;
return true;
}
assert(p->_right == c);
p->_right = c->_parent = nullptr;
return false;
}
private:
static int _down_depth(value* v, int ctr)
{
if(v == nullptr)
return ctr;
ctr ++;
return gs_max(_down_depth(v->_left, ctr),
_down_depth(v->_right, ctr)
);
}
protected:
value* vleft() const { return _vptr ? _vptr->_left : nullptr; }
value* vright() const { return _vptr ? _vptr->_right : nullptr; }
value* vparent() const { return _vptr ? _vptr->_parent : nullptr; }
value* vsibling() const
{
if(!_vptr || !_vptr->_parent)
return nullptr;
if(is_left())
return _vptr->_right;
else if(is_right())
return _vptr->_left;
assert(!"unexpected.");
return nullptr;
}
value* vroot() const
{
if(!_vptr)
return nullptr;
value* p = _vptr;
for( ; p->_parent; p = p->_parent);
return p;
}
protected:
template<class _lambda, class _value>
static void preorder_traversal(_lambda lam, _value* v)
{
assert(v);
lam(v);
if(v->_left)
preorder_traversal(lam, v->_left);
if(v->_right)
preorder_traversal(lam, v->_right);
}
template<class _lambda, class _value>
static void inorder_traversal(_lambda lam, _value* v)
{
assert(v);
if(v->_left)
inorder_traversal(lam, v->_left);
lam(v);
if(v->_right)
inorder_traversal(lam, v->_right);
}
template<class _lambda, class _value>
static void postorder_traversal(_lambda lam, _value* v)
{
assert(v);
if(v->_left)
postorder_traversal(lam, v->_left);
if(v->_right)
postorder_traversal(lam, v->-right);
lam(v);
}
public:
template<class _lambda>
void inorder_traversal(_lambda lam) { if(_vptr) inorder_traversal(lam, _vptr); }
template<class _lambda>
void inorder_traversal(_lambda lam) const { if(_cvptr) inorder_traversal(lam, _cvptr); }
template<class _lambda>
void preorder_traversal(_lambda lam) { if(_vptr) preorder_traversal(lam, _vptr); }
template<class _lambda>
void preorder_traversal(_lambda lam) const { if(_cvptr) preorder_traversal(lam, _cvptr); }
template<class _lambda>
void postorder_traversal(_lambda lam) { if(_vptr) postorder_traversal(lam, _vptr); }
template<class _lambda>
void postorder_traversal(_lambda lam) const { if(_cvptr) postorder_traversal(lam, _cvptr); }
};
template<class _ty,
class _wrapper = _avltreenode_cpy_wrapper<_ty> >
class _avltree_const_iterator:
public _avltreenode_val<_wrapper>
{
public:
typedef _ty value;
typedef _wrapper wrapper;
typedef _avltree_const_iterator<_ty, _wrapper> iterator;
public:
iterator(const wrapper* w = nullptr) { _cvptr = w; }
bool is_valid() const { return _cvptr != nullptr; }
const value* get_ptr() const { return _cvptr->const_ptr(); }
const value* operator->() const { return _cvptr->const_ptr(); }
const value& operator*() const { return _cvptr->const_ref(); }
iterator left() const { return iterator(vleft()); }
iterator right() const { return iterator(vright()); }
iterator parent() const { return iterator(vparent()); }
iterator sibling() const { return iterator(vsibling()); }
iterator root() const { return iterator(vroot()); }
bool operator==(const iterator& that) const { return _cvptr == that._cvptr; }
bool operator!=(const iterator& that) const { return _cvptr != that._cvptr; }
};
template<class _ty,
class _wrapper = _avltreenode_cpy_wrapper<_ty> >
class _avltree_iterator:
public _avltree_const_iterator<_ty, _wrapper>
{
public:
typedef _ty value;
typedef _wrapper wrapper;
typedef _avltree_const_iterator<_ty, _wrapper> const_iterator;
typedef _avltree_const_iterator<_ty, _wrapper> superref;
typedef _avltree_iterator<_ty, _wrapper> iterator;
public:
iterator(wrapper* w): superref(w) {}
value* get_ptr() const { return _vptr->get_ptr(); }
value* operator->() const { return _vptr->get_ptr(); }
value& operator*() const { return _vptr->get_ref(); }
bool operator==(const iterator& that) const { return _vptr == that._vptr; }
bool operator!=(const iterator& that) const { return _vptr != that._vptr; }
bool operator==(const const_iterator& that) const { return _vptr == that._vptr; }
bool operator!=(const const_iterator& that) const { return _vptr != that._vptr; }
operator const_iterator() { return const_iterator(_cvptr); }
void to_root() { _vptr = vroot(); }
void to_left() { _vptr = vleft(); }
void to_right() { _vptr = vright(); }
void to_sibling() { _vptr = vsibling(); }
void to_parent() { _vptr = vparent(); }
iterator left() const { return iterator(vleft()); }
iterator right() const { return iterator(vright()); }
iterator parent() const { return iterator(vparent()); }
iterator sibling() const { return iterator(vsibling()); }
iterator root() const { return iterator(vroot()); }
};
template<class _ty,
class _wrapper = _avltreenode_cpy_wrapper<_ty>,
class _alloc = _avltree_allocator<_wrapper> >
class avltree:
public _avltreenode_val<_wrapper>
{
public:
typedef _ty value;
typedef _wrapper wrapper;
typedef _alloc alloc;
typedef avltree<value, wrapper, alloc> myref;
typedef _avltree_const_iterator<_ty, _wrapper> const_iterator;
typedef _avltree_iterator<_ty, _wrapper> iterator;
public:
avltree() { _vptr = nullptr; }
~avltree() { clear(); }
void clear() { destroy(get_root()); }
void destroy(iterator i)
{
if(!i.is_valid())
return;
if(iterator p = i.parent())
disconnect_parent_child(p.get_wrapper(), i.get_wrapper());
else {
assert(is_root(i));
_vptr = nullptr;
}
_destroy(i);
}
void adopt(wrapper* w)
{
assert(!_vptr && "use attach method.");
_vptr = w;
}
iterator get_root() const { return iterator(_vptr); }
const_iterator const_root() const { return const_iterator(_cvptr); }
bool is_root(iterator i) const { return i.is_valid() ? (_cvptr == i.get_wrapper()) : false; }
bool is_valid() const { return _cvptr != nullptr; }
bool is_mine(iterator i) const
{
if(!i.is_valid())
return false;
i.to_root();
return i.get_wrapper() == _vptr;
}
int depth() const { return _cvptr->down_depth(); }
void swap(myref& that) { gs_swap(_vptr, that._vptr); }
iterator find(const value& v) const { return find(get_root(), v); }
iterator find(iterator i, const value& v) const
{
if(!i) {
if(!is_valid())
return i;
i = get_root();
}
assert(i);
if(v == *i)
return i;
iterator n = (v < *i) ? i.left() : i.right();
return n ? find(n, v) : i;
}
template<class _ctor = value>
iterator insert(const value& v)
{
iterator i = get_root();
return !i ? _init<_ctor>(v) : _insert<_ctor>(i, v);
}
void erase(iterator i)
{
assert(i && is_mine(i));
if(i.is_leaf()) {
iterator p = i.parent();
if(p) {
disconnect_parent_child(p.get_wrapper(), i.get_wrapper());
_destroy(i);
_balance_erase(p);
return;
}
else {
assert(is_root(i));
_destroy(i);
_vptr = nullptr;
return;
}
}
if(i.left()) {
if(i.right()) { /* left & right */
iterator l = i.left();
iterator li = l;
for(; li.right(); li.to_right());
iterator lil = li.left();
i.swap_data(li);
if(lil) {
li.swap_data(lil);
destroy(lil);
_balance_erase(li);
return;
}
else {
iterator q = li.parent();
assert(q);
destroy(li);
_balance_erase(q);
return;
}
}
else { /* only left */
if(i.parent()) {
myref t;
iterator j = attach(detach(t, i.left()), i);
j.set_balance(i.get_balance());
_balance_erase(j);
return;
}
else {
myref t;
swap(detach(t, i.left()));
return;
}
}
}
else {
assert(i.right()); /* only right */
if(i.parent()) {
myref t;
iterator j = attach(detach(t, i.right()), i);
j.set_balance(i.get_balance());
_balance_erase(j);
return;
}
else {
myref t;
swap(detach(t, i.right()));
return;
}
}
}
void erase(const value& v)
{
if(iterator i = find(v))
erase(i);
}
/* The detach and attach methods, provide subtree operations */
myref& detach(myref& subtree, iterator i)
{
assert(i && is_mine(i));
if(subtree.is_valid())
subtree.clear();
detach<myref>(subtree, i);
return subtree;
}
template<class _cont>
void detach(_cont& cont)
{
cont.adopt(_vptr);
_vptr = nullptr;
}
template<class _cont>
void detach(_cont& cont, iterator i)
{
assert(i && is_mine(i));
if(i == get_root())
return detach(cont);
iterator p = i.parent();
assert(p);
disconnect_parent_child(p.get_wrapper(), i.get_wrapper());
cont.adopt(i.get_wrapper());
}
iterator attach(myref& subtree, iterator i)
{
assert(i && is_mine(i) && i.is_leaf());
if(i.is_root()) {
swap(subtree);
return get_root();
}
iterator p = i.parent();
assert(p);
bool leftp = disconnect_parent_child(p.get_wrapper(), i.get_wrapper());
gs_swap(subtree._vptr, i._vptr);
leftp ? connect_left_child(p.get_wrapper(), i.get_wrapper()) :
connect_right_child(p.get_wrapper(), i.get_wrapper());
subtree.clear();
return i;
}
public:
template<class _lambda>
void preorder_for_each(_lambda lam) { preorder_traversal([](wrapper* w) { lam(w->get_ptr()); }); }
template<class _lambda>
void preorder_const_for_each(_lambda lam) const { preorder_traversal([](const wrapper* w) { lam(w->const_ptr()); }); }
template<class _lambda>
void inorder_for_each(_lambda lam) { inorder_traversal([](wrapper* w) { lam(w->get_ptr()); }); }
template<class _lambda>
void inorder_const_for_each(_lambda lam) const { inorder_traversal([](const wrapper* w) { lam(w->const_ptr()); }); }
template<class _lambda>
void postorder_for_each(_lambda lam) { postorder_traversal([](wrapper* w) { lam(w->get_ptr()); }); }
template<class _lambda>
void postorder_const_for_each(_lambda lam) const { postorder_traversal([](const wrapper* w) { lam(w->const_ptr()); }); }
protected:
void _destroy(iterator i)
{
if(!i.is_valid())
return;
_destroy(i.left());
_destroy(i.right());
wrapper* w = i.get_wrapper();
w->kill();
alloc::kill(w);
}
template<class _ctor>
iterator _insert(iterator i, const value& v)
{
assert(i);
if(v == *i)
return iterator(nullptr); /* failed */
if(v < *i) {
if(i.left())
return _insert<_ctor>(i.left(), v);
iterator j = _add_left<_ctor>(i, v);
_balance_insert(j);
return j;
}
else {
if(i.right())
return _insert<_ctor>(i.right(), v);
iterator j = _add_right<_ctor>(i, v);
_balance_insert(j);
return j;
}
}
void _balance_insert(iterator i)
{
assert(i);
iterator p = i.parent();
if(!p)
return;
if(i.is_left()) {
switch(p.get_balance())
{
case -1:
(i.get_balance() == 1) ?
_left_right_rotate(p) :
_right_rotate(p);
break;
case 0:
p.set_balance(-1);
return _balance_insert(p);
case 1:
p.set_balance(0);
break;
default:
assert(!"unexpected.");
break;
}
}
else {
switch(p.get_balance())
{
case -1:
p.set_balance(0);
break;
case 0:
p.set_balance(1);
return _balance_insert(p);
case 1:
(i.get_balance() == -1) ?
_right_left_rotate(p) :
_left_rotate(p);
break;
default:
assert(!"unexpected.");
break;
}
}
}
void _balance_erase(iterator i)
{
assert(i);
int b = i.get_balance();
if(!b) {
i.set_balance(i.left() ? -1 : 1);
return;
}
if(!i.left()) {
if(b == -1)
i.set_balance(0);
else if(b == 1) {
iterator r = i.right();
if(!r)
i.set_balance(0);
else {
(r.get_balance() == -1) ?
_right_left_rotate(i) :
_left_rotate(i);
i.to_parent();
if(i.get_balance() == -1)
return;
}
}
else {
assert(!"unexpected.");
}
}
else if(!i.right()) {
if(b == 1)
i.set_balance(0);
else if(b == -1) {
iterator l = i.left();
if(!l)
i.set_balance(0);
else {
(l.get_balance() == 1) ?
_left_right_rotate(i) :
_right_rotate(i);
i.to_parent();
if(i.get_balance() == 1)
return;
}
}
else {
assert(!"unexpected.");
}
}
_balance_erase_(i);
}
void _balance_erase_(iterator i)
{
assert(i);
iterator p = i.parent();
if(!p)
return;
if(i.is_left()) {
switch(p.get_balance())
{
case -1:
p.set_balance(0);
return _balance_erase_(p);
case 0:
p.set_balance(1);
break;
case 1:
(p.right().get_balance() == -1) ?
_right_left_rotate(p) :
_left_rotate(p);
if(p.parent().get_balance() != -1)
return _balance_erase_(p.parent());
break;
default:
assert(!"unexpected.");
break;
}
}
else {
switch(p.get_balance())
{
case -1:
(p.left().get_balance() == 1) ?
_left_right_rotate(p) :
_right_rotate(p);
if(p.parent().get_balance() != 1)
return _balance_erase_(p.parent());
break;
case 0:
p.set_balance(-1);
break;
case 1:
p.set_balance(0);
return _balance_erase_(p);
default:
assert(!"unexpected.");
break;
}
}
}
iterator _left_rotate(iterator i)
{
assert(i && i.right());
iterator p = i.parent();
iterator r = i.right();
iterator rl = r.left();
if(p) {
i.is_left() ? connect_left_child(p.get_wrapper(), r.get_wrapper()) :
connect_right_child(p.get_wrapper(), r.get_wrapper());
}
else {
_vptr = r.get_wrapper();
_vptr->_parent = nullptr;
}
connect_left_child(r.get_wrapper(), i.get_wrapper());
connect_right_child(i.get_wrapper(), rl.get_wrapper());
if(r.get_balance() == 0) {
i.set_balance(1);
r.set_balance(-1);
}
else {
i.set_balance(0);
r.set_balance(0);
}
return r;
}
iterator _right_rotate(iterator i)
{
assert(i && i.left());
iterator p = i.parent();
iterator l = i.left();
iterator lr = l.right();
if(p) {
i.is_left() ? connect_left_child(p.get_wrapper(), l.get_wrapper()) :
connect_right_child(p.get_wrapper(), l.get_wrapper());
}
else {
_vptr = l.get_wrapper();
_vptr->_parent = nullptr;
}
connect_right_child(l.get_wrapper(), i.get_wrapper());
connect_left_child(i.get_wrapper(), lr.get_wrapper());
if(l.get_balance() == 0) {
i.set_balance(-1);
l.set_balance(1);
}
else {
i.set_balance(0);
l.set_balance(0);
}
return l;
}
iterator _left_right_rotate(iterator i)
{
assert(i && i.left());
iterator l = i.left();
iterator lr = l.right();
assert(lr);
iterator lrl = lr.left();
iterator lrr = lr.right();
iterator p = i.parent();
if(p) {
i.is_left() ? connect_left_child(p.get_wrapper(), lr.get_wrapper()) :
connect_right_child(p.get_wrapper(), lr.get_wrapper());
}
else {
_vptr = lr.get_wrapper();
_vptr->_parent = nullptr;
}
connect_left_child(lr.get_wrapper(), l.get_wrapper());
connect_right_child(lr.get_wrapper(), i.get_wrapper());
connect_right_child(l.get_wrapper(), lrl.get_wrapper());
connect_left_child(i.get_wrapper(), lrr.get_wrapper());
switch(lr.get_balance())
{
case -1:
i.set_balance(1);
l.set_balance(0);
break;
case 0:
i.set_balance(0);
l.set_balance(0);
break;
case 1:
i.set_balance(0);
l.set_balance(-1);
break;
default:
assert(!"unexpected.");
break;
}
lr.set_balance(0);
return lr;
}
iterator _right_left_rotate(iterator i)
{
assert(i && i.right());
iterator r = i.right();
iterator rl = r.left();
assert(rl);
iterator rll = rl.left();
iterator rlr = rl.right();
iterator p = i.parent();
if(p) {
i.is_left() ? connect_left_child(p.get_wrapper(), rl.get_wrapper()) :
connect_right_child(p.get_wrapper(), rl.get_wrapper());
}
else {
_vptr = rl.get_wrapper();
_vptr->_parent = nullptr;
}
connect_right_child(rl.get_wrapper(), r.get_wrapper());
connect_left_child(rl.get_wrapper(), i.get_wrapper());
connect_right_child(i.get_wrapper(), rll.get_wrapper());
connect_left_child(r.get_wrapper(), rlr.get_wrapper());
switch(rl.get_balance())
{
case -1:
i.set_balance(0);
r.set_balance(1);
break;
case 0:
i.set_balance(0);
r.set_balance(0);
break;
case 1:
i.set_balance(-1);
r.set_balance(0);
break;
default:
assert(!"unexpected.");
break;
}
rl.set_balance(0);
return rl;
}
template<class _ctor>
iterator _init()
{
assert(!_vptr);
_vptr = alloc::born();
_vptr->born<_ctor>();
return iterator(_vptr);
}
template<class _ctor>
iterator _init(const value& v)
{
assert(!_vptr);
_vptr = initval<_ctor, wrapper::tsf_behavior>::run(alloc::born(), v);
assert(_vptr);
return iterator(_vptr);
}
template<class _ctor>
iterator _add_left(iterator i, const value& v)
{
assert(i && !i.left());
wrapper* n = initval<_ctor, wrapper::tsf_behavior>::run(alloc::born(), v);
connect_left_child(i.get_wrapper(), n);
return iterator(n);
}
template<class _ctor>
iterator _add_right(iterator i, const value& v)
{
assert(i && !i.right());
wrapper* n = initval<_ctor, wrapper::tsf_behavior>::run(alloc::born(), v);
connect_right_child(i.get_wrapper(), n);
return iterator(n);
}
void _modified()
{
#if defined (DEBUG) || defined (_DEBUG)
debug_check(get_root());
#endif
}
protected:
friend struct initval;
template<class _ctor, class _tsftrait>
struct initval;
template<class _ctor>
struct initval<_ctor, _avltree_trait_copy>
{
static wrapper* run(wrapper* w, const value& v)
{
assert(w);
w->get_ref() = v;
return w;
}
};
template<class _ctor>
struct initval<_ctor, _avltree_trait_detach>
{
static wrapper* run(wrapper* w, const value& v)
{
assert(w);
w->_value = &v; /* or duplicate? */
return w;
}
};
public:
bool debug_check(iterator i)
{
if(!i)
return true;
check_root(i);
check_linkage(i);
check_order(i);
check_balance(i);
iterator l = i.left(), r = i.right();
if(!(l && debug_check(l)))
return false;
if(!(r && debug_check(r)))
return false;
return true;
}
bool check_root(iterator i)
{
assert(i);
if(is_root(i)) {
assert(!i.parent() && "root has no parent.");
return true;
}
assert(i.parent() && "non-root must have parent.");
return false;
}
void check_linkage(iterator i)
{
assert(i);
iterator l = i.left(), r = i.right();
if(l) { assert(l.parent() == i && "left link wrong."); }
if(r) { assert(r.parent() == i && "right link wrong."); }
}
void check_order(iterator i)
{
assert(i);
iterator l = i.left(), r = i.right();
if(l) {
iterator lm = l;
for(; lm.right(); lm = lm.right());
assert(*lm < *i && "left order wrong.");
}
if(r) {
iterator rm = r;
for(; rm.left(); rm = rm.left());
assert(*i < *rm && "right order wrong.");
}
}
void check_balance(iterator i)
{
assert(i);
iterator l = i.left(), r = i.right();
int h1 = 0, h2 = 0;
if(l) h1 = l.down_depth();
if(r) h2 = r.down_depth();
int b = i.get_balance();
assert(b == h2 - h1 && "balance wrong.");
}
};
__gslib_end__
#endif
| {
"alphanum_fraction": 0.5044486918,
"avg_line_length": 31.5446985447,
"ext": "h",
"hexsha": "07a831cc8933e11be84b3b1da84a99bcaa0cd551",
"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/avl.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/avl.h",
"max_line_length": 125,
"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/avl.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": 7006,
"size": 30346
} |
#pragma once
#include <Python.h> // has to be the first included header
#include <petsc.h>
/**
* Callback functions for PETSc and the SNES solver
*/
/**
* Nonlinear function F that gets solved by PETSc, solve for u such that F(u) = 0
* Input Parameters:
* snes - the SNES context
* u - input vector
* context - optional user-defined context
*
* Output Parameter:
* f - function vector
*/
template<typename T>
PetscErrorCode nonlinearFunction(SNES snes, Vec u, Vec f, void *context);
/**
* Evaluates Jacobian matrix
* Input Parameters:
* snes - the SNES context
* x - input vector
* context - optional user-defined context
*
* Output Parameters:
* jac - Jacobian matrix
* b - optionally different preconditioning matrix
*/
template<typename T>
PetscErrorCode jacobianFunctionAnalytic(SNES snes, Vec x, Mat jac, Mat b, void *context);
template<typename T>
PetscErrorCode jacobianFunctionFiniteDifferences(SNES snes, Vec x, Mat jac, Mat b, void *context);
template<typename T>
PetscErrorCode jacobianFunctionCombined(SNES snes, Vec x, Mat jac, Mat b, void *context);
/**
* Monitor convergence of nonlinear solver
*
* Input Parameters:
* snes - the SNES context
* its - iteration number
* norm - 2-norm function value (may be estimated)
* mctx - [optional] monitoring context
*/
template<typename T>
PetscErrorCode monitorFunction(SNES snes, PetscInt its, PetscReal norm, void *mctx);
#include "specialized_solver/solid_mechanics/hyperelasticity/02_petsc_callbacks.tpp"
| {
"alphanum_fraction": 0.7193778354,
"avg_line_length": 26.6034482759,
"ext": "h",
"hexsha": "0dfbd1ddbf7141359167f84c2b7cded0d1cb40ce",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-05-28T13:24:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-17T12:18:10.000Z",
"max_forks_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "maierbn/opendihu",
"max_forks_repo_path": "core/src/specialized_solver/solid_mechanics/hyperelasticity/02_petsc_callbacks.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0",
"max_issues_repo_issues_event_max_datetime": "2020-12-29T15:29:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-11-12T15:15:58.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "maierbn/opendihu",
"max_issues_repo_path": "core/src/specialized_solver/solid_mechanics/hyperelasticity/02_petsc_callbacks.h",
"max_line_length": 98,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "maierbn/opendihu",
"max_stars_repo_path": "core/src/specialized_solver/solid_mechanics/hyperelasticity/02_petsc_callbacks.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-20T04:46:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-25T19:29:34.000Z",
"num_tokens": 404,
"size": 1543
} |
#pragma once
#include <gsl/gsl>
#include <typeindex>
#include "halley/utils/utils.h"
#include "halley/data_structures/maybe.h"
#include "halley/bytes/byte_serializer.h"
#include <cstdint>
namespace Halley
{
class IMessageStream;
class MessageQueue;
class MessageQueueUDP;
class MessageQueueTCP;
class NetworkMessage
{
public:
virtual ~NetworkMessage() = default;
size_t getSerializedSize() const
{
if (!serialized) {
serialized = Serializer::toBytes(*this, getSerializerOptions());
}
return serialized->size();
}
void serializeTo(gsl::span<gsl::byte> dst) const
{
if (!serialized) {
serialized = Serializer::toBytes(*this, getSerializerOptions());
}
memcpy(dst.data(), serialized->data(), serialized->size());
}
Bytes getBytes() const
{
if (!serialized) {
serialized = Serializer::toBytes(*this, getSerializerOptions());
}
return *serialized;
}
virtual void serialize(Serializer& s) const = 0;
virtual void deserialize(Deserializer& s) = 0;
void setSeq(uint16_t seq) { this->seq = seq; }
uint16_t getSeq() const { return seq; }
void setChannel(uint8_t channel) { this->channel = channel; }
uint8_t getChannel() const { return channel; }
static SerializerOptions getSerializerOptions()
{
return SerializerOptions(SerializerOptions::maxVersion);
}
private:
uint16_t seq = 0;
uint8_t channel = -1;
mutable std::optional<Bytes> serialized;
};
class NetworkMessageFactoryBase
{
public:
virtual ~NetworkMessageFactoryBase() {}
virtual std::unique_ptr<NetworkMessage> create(gsl::span<const gsl::byte> src) const = 0;
virtual std::type_index getTypeIndex() const = 0;
};
template <typename T>
class NetworkMessageFactory : public NetworkMessageFactoryBase
{
public:
std::unique_ptr<NetworkMessage> create(gsl::span<const gsl::byte> src) const override
{
auto result = std::make_unique<T>();
auto s = Deserializer(src, T::getSerializerOptions());
result->deserialize(s);
return result;
}
std::type_index getTypeIndex() const override
{
return std::type_index(typeid(T));
}
};
class NetworkMessageFactories
{
public:
template <typename T>
void addFactory()
{
addFactory(std::make_unique<NetworkMessageFactory<T>>());
}
uint16_t getMessageType(NetworkMessage& msg) const;
std::unique_ptr<NetworkMessage> deserializeMessage(gsl::span<const gsl::byte> data, uint16_t msgType, uint16_t seq);
private:
std::map<std::type_index, uint16_t> typeToMsgIndex;
Vector<std::unique_ptr<NetworkMessageFactoryBase>> factories;
void addFactory(std::unique_ptr<NetworkMessageFactoryBase> factory);
};
}
| {
"alphanum_fraction": 0.7155756208,
"avg_line_length": 23.9459459459,
"ext": "h",
"hexsha": "113979e5303dee89e46186bad41b1b54dbb805db",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "amrezzd/halley",
"max_forks_repo_path": "src/engine/net/include/halley/net/connection/network_message.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "amrezzd/halley",
"max_issues_repo_path": "src/engine/net/include/halley/net/connection/network_message.h",
"max_line_length": 118,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5f6a5dd7d44b9c12d2c124436969ff2dfa69e3f4",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "amrezzd/halley",
"max_stars_repo_path": "src/engine/net/include/halley/net/connection/network_message.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 698,
"size": 2658
} |
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <math.h>
// #include <stdlib.h>
// #include <time.h>
double circle_overlap(double *rA, double radiiA, double *rB, double radiiB)
{
double rAB[2];
rAB[0] = rB[0] - rA[0];
rAB[1] = rB[1] - rA[1];
double F;
F = (pow(rAB[0], 2) + pow(rAB[1], 2)) / pow(radiiA + radiiB, 2);
return F;
}
size_t gen_pts_rsa_2d(double *x, double *y,
size_t npoints, double radius, int step_limit,
unsigned long randSeed)
{
// Setup GSL random number generator
const gsl_rng_type * T;
gsl_rng * r;
T = gsl_rng_default;
r = gsl_rng_alloc (T);
// Set the seed
// srand ( time(NULL) );
// unsigned long randSeed = rand();
gsl_rng_set(r, randSeed);
// Set the initial position
double xn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius;
double yn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius;
x[0] = xn;
y[0] = yn;
double diameter = 2 * radius;
size_t valid_pts;
double F;
int k, flag, step;
step = 0;
valid_pts = 1;
double rA[2];
double rB[2];
while ((valid_pts < npoints) & (step < step_limit))
{
xn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius;
yn = gsl_rng_uniform (r) * (1 - 2 * radius) + radius;
flag = 1;
for (k = 0; k < valid_pts; k++)
{
rA[0] = x[k];
rA[1] = y[k];
rB[0] = xn;
rB[1] = yn;
F = circle_overlap(&rA[0], radius, &rB[0], radius);
if (F < 1.0)
{
flag = 0;
break;
}
}
if (flag == 1)
{
x[valid_pts] = xn;
y[valid_pts] = yn;
valid_pts += 1;
}
step += 1;
}
gsl_rng_free (r);
return valid_pts;
}
unsigned int metro_md_2d(double *x, double *y,
double radius, size_t npoints, unsigned int step_limit,
unsigned long randSeed)
{
/* Setup GSL random number generator */
const gsl_rng_type * T;
gsl_rng * r;
T = gsl_rng_default;
r = gsl_rng_alloc (T);
/* Set the seed */
// srand ( time(NULL) );
// unsigned long randSeed = rand();
gsl_rng_set(r, randSeed);
double diameter = 2 * radius;
double F, dx, dy, xn, yn;
unsigned int step, i, k, flag, success_steps;
double rA[2];
double rB[2];
step = 0;
success_steps = 0;
while (step < step_limit)
{
i = step % npoints;
/* Generate new position */
while (1)
{
dx = diameter * (gsl_rng_uniform (r) - 0.5);
xn = x[i] + dx;
dy = diameter * (gsl_rng_uniform (r) - 0.5);
yn = y[i] + dy;
if (((xn > radius) & (xn < 1 - radius)) & ((yn > radius) & (yn < 1 - radius)) )
{
break;
}
}
/* Determine if new position overlaps with other positions */
flag = 1;
for (k = 0; k < npoints; k++)
{
rA[0] = x[k];
rA[1] = y[k];
rB[0] = xn;
rB[1] = yn;
F = circle_overlap(&rA[0], radius, &rB[0], radius);
if ((F < 1.0) & (i != k))
{
flag = 0;
break;
}
}
if (flag == 1)
{
x[i] = xn;
y[i] = yn;
success_steps = success_steps + 1;
}
step = step + 1;
}
gsl_rng_free (r);
return success_steps;
}
unsigned int metro_pd_2d(double *x, double *y,
double *radius, size_t npoints, int step_limit,
unsigned long randSeed)
{
/* Setup GSL random number generator */
const gsl_rng_type * T;
gsl_rng * r;
T = gsl_rng_default;
r = gsl_rng_alloc (T);
/* Set the seed */
// srand ( time(NULL) );
// unsigned long randSeed = rand();
gsl_rng_set(r, randSeed);
double F, dx, dy, xn, yn, diameter;
unsigned int step, i, k, flag, success_steps;
double rA[2];
double rB[2];
step = 0;
success_steps = 0;
while (step < step_limit)
{
i = step % npoints;
/* Generate new position */
while (1)
{
diameter = 2 * radius[i];
dx = diameter * (gsl_rng_uniform (r) - 0.5);
xn = x[i] + dx;
dy = diameter * (gsl_rng_uniform (r) - 0.5);
yn = y[i] + dy;
if (((xn > radius[i]) & (xn < 1 - radius[i])) & ((yn > radius[i]) & (yn < 1 - radius[i])) )
{
break;
}
}
/* Determine if new position overlaps with other positions */
flag = 1;
for (k = 0; k < npoints; k++)
{
rA[0] = x[k];
rA[1] = y[k];
rB[0] = xn;
rB[1] = yn;
F = circle_overlap(&rA[0], radius[i], &rB[0], radius[k]);
if ((F < 1.0) & (i != k))
{
flag = 0;
break;
}
}
if (flag == 1)
{
x[i] = xn;
y[i] = yn;
success_steps += 1;
}
step = step + 1;
}
gsl_rng_free (r);
return success_steps;
} | {
"alphanum_fraction": 0.4498869631,
"avg_line_length": 17.9324324324,
"ext": "c",
"hexsha": "107b6d56ade1dc50a2e792e51bd87abf8f1d93d1",
"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": "127603a519ae25979de6c6197810a7ea38ec945b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "aluchies/particle_packing",
"max_forks_repo_path": "particle_packing/cython/c/circle.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b",
"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": "aluchies/particle_packing",
"max_issues_repo_path": "particle_packing/cython/c/circle.c",
"max_line_length": 103,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "127603a519ae25979de6c6197810a7ea38ec945b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "aluchies/particle_packing",
"max_stars_repo_path": "particle_packing/cython/c/circle.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1565,
"size": 5308
} |
/*gcc poisson.c /usr/lib/libgsl.a /usr/lib/libm.a -o poisson.exe */
#include <stdio.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <math.h>
int
main (int argc, char *argv[])
{
if(argc < 2){
printf("print probability of obtaining N from poisson distribution\n");
printf("usage: poisson.exe mean N\n");
return 1;
}
const gsl_rng_type * T;
gsl_rng * r;
int billion = 1000000000;
int i, n = billion;
double mean = atof(argv[1]);
unsigned int found = atoi(argv[2]);
double prob = gsl_ran_poisson_pdf(found,mean);
printf("probability %f of getting %d from mean %f\n",prob,found,mean);
double totalprob = 0.0;
for(i=0; i<found; i++){
totalprob += gsl_ran_poisson_pdf(i,mean);
}
printf("probability %f of getting < %d from mean %f\n",
totalprob,found,mean);
printf("probability %f of getting >= %d from mean %f\n",
1.0-totalprob,found,mean);
/*
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
for (i = 0; i < n; i++)
{
double u = gsl_rng_uniform (r);
if(i > billion-5) printf("%.5f\n", u);
}
gsl_rng_free (r);
*/
return 0;
}
| {
"alphanum_fraction": 0.621434745,
"avg_line_length": 20.6607142857,
"ext": "c",
"hexsha": "d8108fac13afb760a022c7d9f18f793412ae3e66",
"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": "29cc7dae0c1e4df6aa0ca5c6f0b8a169c21b0ee9",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "QuarkNet-HEP/e-Labs",
"max_forks_repo_path": "cosmic/contrib/walta/coincidence/poisson/poisson.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "29cc7dae0c1e4df6aa0ca5c6f0b8a169c21b0ee9",
"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": "QuarkNet-HEP/e-Labs",
"max_issues_repo_path": "cosmic/contrib/walta/coincidence/poisson/poisson.c",
"max_line_length": 75,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "29cc7dae0c1e4df6aa0ca5c6f0b8a169c21b0ee9",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "QuarkNet-HEP/e-Labs",
"max_stars_repo_path": "cosmic/contrib/walta/coincidence/poisson/poisson.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 373,
"size": 1157
} |
#pragma once
#include <memory>
#include <memory_resource>
#include <gsl-lite/gsl-lite.hpp>
#include <sysmakeshift/memory.hpp>
namespace thrustshift {
namespace detail {
//! Allocate without initialization
template <typename T, typename A, typename SizeC>
T* allocate_array(A& alloc, SizeC sizeC) {
return std::allocator_traits<A>::allocate(alloc, std::size_t(sizeC));
}
template <typename ArrayT, typename A>
std::enable_if_t<
sysmakeshift::detail::extent_only<ArrayT>::value == 0,
std::unique_ptr<ArrayT, sysmakeshift::allocator_deleter<ArrayT, A>>>
allocate_unique(A alloc, std::size_t size) {
using T = std::remove_cv_t<sysmakeshift::detail::remove_extent_only_t<ArrayT>>;
static_assert(
std::is_same<typename std::allocator_traits<A>::value_type, T>::value,
"allocator has mismatching value_type");
T* ptr = detail::allocate_array<T>(alloc, size);
return {ptr, {std::move(alloc), size}};
}
} // namespace detail
/*! \brief Container which provides memory with a custom allocator.
*
* Useful in combination with memory which is not accessible on the
* host. E.g. you can use a device memory allocator with this class
* to obtain device memory and pass it as a span to a GPU kernel.
*/
template <typename T, class Allocator>
class not_a_vector {
public:
not_a_vector(std::size_t size, Allocator& alloc)
: ptr_(detail::allocate_unique<T[]>(alloc, size)), size_(size) {
}
gsl_lite::span<T> to_span() const {
return gsl_lite::make_span(ptr_.get(), size_);
}
private:
std::unique_ptr<T[], sysmakeshift::allocator_deleter<T[], Allocator>> ptr_;
std::size_t size_;
};
template <typename T, class Resource>
auto make_not_a_vector(std::size_t size, Resource& memory_resource) {
std::pmr::polymorphic_allocator<T> alloc(&memory_resource);
return not_a_vector<T, decltype(alloc)>(size, alloc);
}
/*! \brief Make not_a_vector object and the span on the corresponding buffer.
*
* This function makes it easier to construct the owning container and the view
* in one line of code with structured bindings.
*
* ```cpp
*
* auto [nav, span] = make_not_a_vector_and_span<T>(N, resource);
* ```
*/
template <typename T, class Resource>
auto make_not_a_vector_and_span(std::size_t size, Resource& memory_resource) {
std::pmr::polymorphic_allocator<T> alloc(&memory_resource);
auto nav = not_a_vector<T, decltype(alloc)>(size, alloc);
auto s = nav.to_span();
return std::make_tuple(std::move(nav), s);
}
} // namespace thrustshift
| {
"alphanum_fraction": 0.7266906763,
"avg_line_length": 29.75,
"ext": "h",
"hexsha": "e8fc09b5a7366bb87c7c55a3404029272f521fa9",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "pauleonix/thrustshift",
"max_forks_repo_path": "include/thrustshift/not-a-vector.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "pauleonix/thrustshift",
"max_issues_repo_path": "include/thrustshift/not-a-vector.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "pauleonix/thrustshift",
"max_stars_repo_path": "include/thrustshift/not-a-vector.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z",
"num_tokens": 628,
"size": 2499
} |
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_integration.h>
double f (double x, void *params);
void integral_gen (int nmin, int nmax, double vals[]);
double f (double x, void *params)
{
double n = *(double *) params;
double f = exp (-x) *pow (x, n);
return f;
}
void integral_gen (int nmin, int nmax, double vals[])
{
double result;
double error;
size_t np = 1000;
gsl_integration_workspace *w = gsl_integration_workspace_alloc (np);
gsl_function F;
for (double n = nmin; n <= nmax; n++)
{
F.function = &f;
F.params = &n;
gsl_integration_qag( &F, 0., 1., 0., 1.e-7, np, GSL_INTEG_GAUSS15, w, &result, &error);
vals[(int) n] = result;
}
}
| {
"alphanum_fraction": 0.5538656527,
"avg_line_length": 22.5428571429,
"ext": "c",
"hexsha": "0d09cfefb24e0ea9fccea7cc34bc2dc896b1bd03",
"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": "3dc878517e9b97125b2896092912d7cdbe1610ad",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Paulther/hw7",
"max_forks_repo_path": "integral_gen.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3dc878517e9b97125b2896092912d7cdbe1610ad",
"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": "Paulther/hw7",
"max_issues_repo_path": "integral_gen.c",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3dc878517e9b97125b2896092912d7cdbe1610ad",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Paulther/hw7",
"max_stars_repo_path": "integral_gen.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 227,
"size": 789
} |
/* linalg/test_common.c
*
* Copyright (C) 2017 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_rng.h>
static int create_random_vector(gsl_vector * v, gsl_rng * r);
static int create_posdef_matrix(gsl_matrix * m, gsl_rng * r);
static int create_hilbert_matrix2(gsl_matrix * m);
static int
create_random_vector(gsl_vector * v, gsl_rng * r)
{
const size_t N = v->size;
size_t i;
for (i = 0; i < N; ++i)
{
double vi = gsl_rng_uniform(r);
gsl_vector_set(v, i, vi);
}
return GSL_SUCCESS;
}
static int
create_symm_matrix(gsl_matrix * m, gsl_rng * r)
{
const size_t N = m->size1;
size_t i, j;
for (i = 0; i < N; ++i)
{
for (j = 0; j <= i; ++j)
{
double mij = gsl_rng_uniform(r);
gsl_matrix_set(m, i, j, mij);
}
}
/* copy lower triangle to upper */
gsl_matrix_transpose_tricpy('L', 0, m, m);
return GSL_SUCCESS;
}
static int
create_posdef_matrix(gsl_matrix * m, gsl_rng * r)
{
const size_t N = m->size1;
const double alpha = 10.0 * N;
size_t i;
/* The idea is to make a symmetric diagonally dominant
* matrix. Make a symmetric matrix and add alpha*I to
* its diagonal */
create_symm_matrix(m, r);
for (i = 0; i < N; ++i)
{
double mii = gsl_matrix_get(m, i, i);
gsl_matrix_set(m, i, i, mii + alpha);
}
return GSL_SUCCESS;
}
static int
create_hilbert_matrix2(gsl_matrix * m)
{
const size_t N = m->size1;
size_t i, j;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
gsl_matrix_set(m, i, j, 1.0/(i+j+1.0));
}
}
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6457073761,
"avg_line_length": 23.4056603774,
"ext": "c",
"hexsha": "360cc4aad524c887f7a32815bdc1ebbdc34e6acf",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/test_common.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/test_common.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017",
"max_stars_repo_path": "gsl-2.4/linalg/test_common.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z",
"num_tokens": 735,
"size": 2481
} |
// Implementation of the interface in uint8_image.h.
#include <errno.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
#include <glib.h>
#if GLIB_CHECK_VERSION (2, 6, 0)
# include <glib/gstdio.h>
#endif
#include <gsl/gsl_spline.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_math.h>
#include "asf_jpeg.h"
#include "uint8_image.h"
#include "asf.h"
#ifndef linux
#ifndef darwin
#ifndef win32
static double
round (double arg)
{
return floor (arg + 0.5);
}
#endif // #ifndef win32
#endif // #ifndef darwin
#endif // #ifndef linux
#include "asf_glib.h"
// Default cache size to use is 16 megabytes.
static const size_t default_cache_size = 16 * 1048576;
// This class wide data element keeps track of the number of temporary
// tile files opened by the current process, in order to give them
// unique names.
static unsigned long current_tile_file_number = 0;
// We need to ensure that multiple threads trying to create their own
// images concurently don't end up with the same temporary file
// names.
//G_LOCK_DEFINE_STATIC (current_tile_file_number);
#ifndef win32
// We don't want to let multiple threads twiddle the signal block mask
// concurrently, or we might end up with the wrong set of signals
// blocked. This lock is used to guarantee this can't happen (see the
// usage for a better explanation).
G_LOCK_DEFINE_STATIC (signal_block_activity);
#endif
// Return a FILE pointer refering to a new, already unlinked file in a
// location which hopefully has enough free space to serve as a block
// cache.
static FILE *
initialize_tile_cache_file (GString **tile_file_name)
{
// Create the temporary tile oriented storage file. This gets
// filled in in different ways depending on which creation routine
// we are using.
g_assert(*tile_file_name == NULL);
*tile_file_name = g_string_new ("");
// Here we do a slightly weird thing: if the current directory is
// writable, we create a temporary file in the current directory.
// We do this because the temporary file could well be pretty big
// and /tmp often maps to a small file system. The idea is that the
// directory the user is in is more likely to have the extra space
// required to hold the temporary file. Of course, if they have
// been carefully calculating their space requirements, they may be
// disappointed. We use a weird name that no sane user would ever
// use for one of their files, we hope.
//G_LOCK (current_tile_file_number);
g_assert (sizeof (long) >= sizeof (pid_t));
g_string_append_printf (*tile_file_name,
".uint8_image_tile_file_%ld_%lu",
(long) getpid (),
current_tile_file_number);
// This hard coded limit on the current number used to uniqueify
// file names limits us to creating no more than ULONG_MAX instances
// during a process.
g_assert (current_tile_file_number < ULONG_MAX);
current_tile_file_number++;
//G_UNLOCK (current_tile_file_number);
#ifndef win32
// We block signals while we create and unlink this file, so we
// don't end up leaving a huge temporary file somewhere.
// Theoretically, two parallel instantiations of image could end up
// in a race condition which would result in all signals ending up
// blocked after both were done with this section, so we consider
// this section critical and protect it with a lock.
G_LOCK (signal_block_activity);
sigset_t all_signals, old_set;
int return_code = sigfillset (&all_signals);
g_assert (return_code == 0);
return_code = sigprocmask (SIG_SETMASK, &all_signals, &old_set);
#endif
// FIXME?: It might be faster to use file descriptor based I/O
// everywhere, or at least for the big transfers. I'm not sure its
// worth the trouble though.
FILE *tile_file = fopen_tmp_file ((*tile_file_name)->str, "w+b");
if ( tile_file == NULL ) {
if ( errno != EACCES ) {
g_warning ("couldn't create file in current directory, and it wasn't"
"just a permissions problem");
}
else {
// Couldn't open in current directory, so try using tmpfile,
// which opens the file in the standardish place for the system.
// See the comment above about why opening in /tmp or the like
// is potentially bad.
tile_file = tmpfile ();
g_assert (tile_file != NULL);
}
}
else {
#ifndef win32
return_code = unlink_tmp_file ((*tile_file_name)->str);
g_assert (return_code == 0);
#endif
}
g_assert (tile_file != NULL);
#ifndef win32
return_code = sigprocmask (SIG_SETMASK, &old_set, NULL);
G_UNLOCK (signal_block_activity);
#endif
return tile_file;
}
// This routine does the work common to several of the differenct
// creation routines. Basically, it does everything but fill in the
// contents of the disk tile store.
static UInt8Image *
initialize_uint8_image_structure (ssize_t size_x, ssize_t size_y)
{
// Allocate instance memory.
UInt8Image *self = g_new0 (UInt8Image, 1);
// Validate and remember image size.
g_assert (size_x > 0 && size_y > 0);
self->size_x = size_x;
self->size_y = size_y;
// Greater of size_x and size_y.
size_t largest_dimension = (size_x > size_y ? size_x : size_y);
// If we can fit the entire image in a single square tile, then we
// want just a single big tile and we won't need to bother with the
// cache file since it won't ever be used, so we do things slightly
// differently. FIXME: it would be slightly better to also detect
// and specially handle the case where we have long narrow images
// that can fit in a single stip of tiles in the cache.
if ( largest_dimension * largest_dimension * sizeof (uint8_t)
<= default_cache_size ) {
self->cache_space = (largest_dimension * largest_dimension
* sizeof (uint8_t));
self->cache_area = self->cache_space / sizeof (uint8_t);
self->tile_size = largest_dimension;
self->cache_size_in_tiles = 1;
self->tile_count_x = 1;
self->tile_count_y = 1;
self->tile_count = 1;
self->tile_area = self->tile_size * self->tile_size;
self->cache = g_new (uint8_t, self->cache_area);
self->tile_addresses = g_new0 (uint8_t *, self->tile_count);
g_assert (NULL == 0x0); // Ensure g_new0 effectively sets to NULL.
// The tile queue shouldn't ever be needed in this case.
self->tile_queue = NULL;
// The tile file shouldn't ever be needed, so we set it to NULL to
// indicate this to a few other methods that use it directly, and
// to hopefully ensure that it triggers an exception if it is
// used.
self->tile_file = NULL;
return self;
}
// The default cache size compiled into the class.
self->cache_space = default_cache_size;
// Memory cache space, in pixels.
g_assert (self->cache_space % sizeof (uint8_t) == 0);
self->cache_area = self->cache_space / sizeof (uint8_t);
// How small do our tiles have to be on a side to fit two full rows
// of them in the memory cache? This is slightly tricky. In order
// to provide the services promised in the interface, we need to
// solve
//
// 2 * pow (t, 2) * ceil ((double)largest_dimension / t)
// <= self->cache_area
//
// for tile size t. I don't know the closed form solution if there
// is one, so toss out the ceil() and solve the easier
//
// 2 * pow (t, 2) * ((double)largest_dimension / t) <= self->cache_area
//
// and then decrement t iteratively until things work.
self->tile_size = self->cache_area / (2 * largest_dimension);
while ( (2 * self->tile_size * self->tile_size
* ceil ((double) largest_dimension / self->tile_size))
> self->cache_area ) {
self->tile_size--;
}
// Area of tiles, in pixels.
self->tile_area = (size_t) (self->tile_size * self->tile_size);
// Number of tiles which will fit in image cache.
self->cache_size_in_tiles = self->cache_area / self->tile_area;
// Can we fit at least as much as we intended in the cache?
g_assert (self->cache_size_in_tiles
>= 2 * (size_t) ceil ((double) largest_dimension
/ self->tile_size));
// Number of tiles image has been split into in x and y directions.
self->tile_count_x = (size_t) ceil ((double) self->size_x / self->tile_size);
self->tile_count_y = (size_t) ceil ((double) self->size_y / self->tile_size);
// Total number of image tiles image has been split into.
self->tile_count = self->tile_count_x * self->tile_count_y;
// We want to be able to pack a tile number into a pointer later, so
// we need it to fit into an integer.
g_assert (self->tile_count < INT_MAX);
// Did all that math work?
g_assert (self->tile_size * self->cache_size_in_tiles / 2
>= largest_dimension);
g_assert (self->cache_size_in_tiles * self->tile_area <= self->cache_area);
// Allocate memory for the in-memory cache.
self->cache = g_new (uint8_t, self->cache_area);
// Do we want to do mlock() here maybe?
// The addresses in the cache of the starts of each of the tiles.
// This array contains flattened tile addresses in the same way that
// image memory normally uses flattened pixel addresses, e.g. the
// address of tile x = 2, y = 4 is stored at self->tile_addresses[4
// * self->tile_count_x + 2]. If a tile isn't in the cache, the
// address is NULL (meaning it will have to be loaded).
self->tile_addresses = g_new0 (uint8_t *, self->tile_count);
g_assert (NULL == 0x0); // Ensure g_new0 effectively sets to NULL.
// Create a queue in order to keep track of which tile was loaded
// longest ago.
self->tile_queue = g_queue_new ();
// Get a new empty tile cache file pointer.
self->tile_file_name = NULL;
self->tile_file = initialize_tile_cache_file ( &(self->tile_file_name) );
return self;
}
UInt8Image *
uint8_image_thaw (FILE *file_pointer)
{
FILE *fp = file_pointer; // Convenience alias.
g_assert (file_pointer != NULL);
UInt8Image *self = g_new (UInt8Image, 1);
size_t read_count = fread (&(self->size_x), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->size_y), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->cache_space), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->cache_area), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->tile_size), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->cache_size_in_tiles), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->tile_count_x), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->tile_count_y), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->tile_count), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
read_count = fread (&(self->tile_area), sizeof (size_t), 1, fp);
g_assert (read_count == 1);
// The cache isn't serialized -- its a bit of a pain and probably
// almost never worth it.
self->cache = g_new (uint8_t, self->cache_area);
self->tile_addresses = g_new0 (uint8_t *, self->tile_count);
// We don't actually keep the tile queue in the serialized instance,
// but if the serialized pointer to it is NULL, we know we aren't
// using a tile cache file (i.e. the whole image fits in the memory
// cache).
read_count = fread (&(self->tile_queue), sizeof (GQueue *), 1, fp);
g_assert (read_count == 1);
// If there was no cache file...
if ( self->tile_queue == NULL ) {
// The tile_file structure field should also be NULL.
self->tile_file = NULL;
// we restore the file directly into the first and only tile (see
// the end of the uint8_image_new method).
self->tile_addresses[0] = self->cache;
read_count = fread (self->tile_addresses[0], sizeof (uint8_t),
self->tile_area, fp);
g_assert (read_count == self->tile_area);
}
// otherwise, an empty tile queue needs to be initialized, and the
// remainder of the serialized version is the tile block cache.
else {
self->tile_queue = g_queue_new ();
self->tile_file_name = NULL;
self->tile_file = initialize_tile_cache_file ( &(self->tile_file_name) );
uint8_t *buffer = g_new (uint8_t, self->tile_area);
size_t ii;
for ( ii = 0 ; ii < self->tile_count ; ii++ ) {
read_count = fread (buffer, sizeof (uint8_t), self->tile_area, fp);
g_assert (read_count == self->tile_area);
size_t write_count = fwrite (buffer, sizeof (uint8_t), self->tile_area,
self->tile_file);
if ( write_count < self->tile_area ) {
if ( feof (self->tile_file) ) {
fprintf (stderr,
"Premature end of file while trying to thaw UInt8Image "
"instance\n");
}
else {
g_assert (ferror (self->tile_file));
fprintf (stderr,
"Error writing tile cache file for UInt8Image instance "
"during thaw: %s\n", strerror (errno));
}
exit (EXIT_FAILURE);
}
g_assert (write_count == self->tile_area);
}
g_free (buffer);
}
return self;
}
UInt8Image *
uint8_image_new (ssize_t size_x, ssize_t size_y)
{
g_assert (size_x > 0 && size_y > 0);
UInt8Image *self = initialize_uint8_image_structure (size_x, size_y);
// If we need a tile file for an image of this size, prepare it.
if ( self->tile_file != NULL ) {
// The total width or height of all the tiles is probably greater
// than the width or height of the image itself.
size_t total_width = self->tile_count_x * self->tile_size;
size_t total_height = self->tile_count_y * self->tile_size;
// Fill the file full of zeros. FIXME: there is almost certainly
// a faster way to ensure that we have the disk space we need.
uint8_t *zero_line = g_new0 (uint8_t, total_width);
g_assert (0 == 0x0); // Ensure the g_new0 did what we think.
// We don't have to write in tile order because its all zeros anyway.
size_t ii;
for ( ii = 0 ; ii < total_height ; ii++ ) {
size_t write_count = fwrite (zero_line, sizeof (uint8_t), total_width,
self->tile_file);
// If we wrote less than expected,
if ( write_count < total_width ) {
// it must have been a write error (probably no space left),
g_assert (ferror (self->tile_file));
// so print an error message,
fprintf (stderr,
"Error writing tile cache file for UInt8Image instance: "
"%s\n", strerror (errno));
// and exit.
exit (EXIT_FAILURE);
}
}
// Done with the line of zeros.
g_free (zero_line);
}
// Everything fits in the cache (at the moment this means everything
// fits in the first tile, which is a bit of a FIXME), so just put
// it there.
else {
self->tile_addresses[0] = self->cache;
size_t ii, jj;
for ( ii = 0 ; ii < self->tile_size ; ii++ ) {
for ( jj = 0 ; jj < self->tile_size ; jj++ ) {
self->tile_addresses[0][ii * self->tile_size + jj] = 0;
}
}
}
return self;
}
UInt8Image *
uint_image_new_with_value (ssize_t size_x, ssize_t size_y, uint8_t value)
{
// Carefully clone-and-modified over from float_image.c, but not
// tested yet.
g_assert_not_reached ();
g_assert (size_x > 0 && size_y > 0);
UInt8Image *self = initialize_uint8_image_structure (size_x, size_y);
// If we need a tile file for an image of this size, prepare it.
if ( self->tile_file != NULL ) {
// The total width or height of all the tiles is probably greater
// than the width or height of the image itself.
size_t total_width = self->tile_count_x * self->tile_size;
size_t total_height = self->tile_count_y * self->tile_size;
// Fill the file full of the given value.
uint8_t *value_line = g_new (uint8_t, total_width);
size_t ii;
for ( ii = 0 ; ii < total_width ; ii++ ) {
value_line[ii] = value;
}
// We don't have to write in tile order because the values are all
// the same anyway.
for ( ii = 0 ; ii < total_height ; ii++ ) {
size_t write_count = fwrite (value_line, sizeof (uint8_t), total_width,
self->tile_file);
// If we wrote less than expected,
if ( write_count < total_width ) {
// it must have been a write error (probably no space left),
g_assert (ferror (self->tile_file));
// so print an error message,
fprintf (stderr,
"Error writing tile cache file for UInt8Image instance: "
"%s\n", strerror (errno));
// and exit.
exit (EXIT_FAILURE);
}
}
// Done with the line of values.
g_free (value_line);
}
// Everything fits in the cache (at the moment this means everything
// fits in the first tile, which is a bit of a FIXME), so just put
// it there.
else {
self->tile_addresses[0] = self->cache;
size_t ii, jj;
for ( ii = 0 ; ii < self->tile_size ; ii++ ) {
for ( jj = 0 ; jj < self->tile_size ; jj++ ) {
self->tile_addresses[0][ii * self->tile_size + jj] = value;
}
}
}
return self;
}
UInt8Image *
uint8_image_new_from_memory (ssize_t size_x, ssize_t size_y, uint8_t *buffer)
{
g_assert (size_x > 0 && size_y > 0);
g_assert_not_reached (); // Stubbed out for now.
// Compiler reassurance.
size_x = size_x;
size_y = size_y;
buffer = buffer;
return NULL;
}
// Bilinear interpolation for a point delta_x, delta_y from the lower
// left corner between values ul (upper left), ur (upper right), etc.
// The corner are considered to be corners of a unit square.
static float
bilinear_interpolate (double delta_x, double delta_y, float ul, float ur,
float ll, float lr)
{
float lv = ll + (lr - ll) * delta_x; // Lower value.
float uv = ul + (ur - ul) * delta_x; // Upper value.
return lv + (uv - lv) * delta_y;
}
UInt8Image *
uint8_image_copy (UInt8Image *model)
{
// This method should be totally fine, it is extremely trivial clone
// and modify from the corresponding method in float_image.c, but
// since its untested I disable it for the moment.
g_assert_not_reached ();
// FIXME: this could obviously be optimized a lot by copying the
// existed tile file, etc.
UInt8Image *self = uint8_image_new (model->size_x, model->size_y);
size_t ii, jj;
for ( ii = 0 ; ii < self->size_y ; ii++ ) {
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
uint8_image_set_pixel (self, jj, ii,
uint8_image_get_pixel (model, jj, ii));
}
}
return self;
}
UInt8Image *
uint8_image_new_from_model_scaled (UInt8Image *model, ssize_t scale_factor)
{
g_assert (model->size_x > 0 && model->size_y > 0);
g_assert (scale_factor > 0);
g_assert (scale_factor % 2 == 1);
UInt8Image *self
= uint8_image_new (round ((double) model->size_x / scale_factor),
round ((double) model->size_y / scale_factor));
// This method hasn't yet made the jump from FloatImage to here.
// The implementation should ultimately follow the one in FloatImage
// to achieve the interface description given in uint8_image.h.
g_assert_not_reached ();
return self;
}
UInt8Image *
uint8_image_new_subimage (UInt8Image *model, ssize_t x, ssize_t y,
ssize_t size_x, ssize_t size_y)
{
// Upper left corner must be in model.
g_assert (x >= 0 && y >= 0);
// Size of image to be created must be strictly positive.
g_assert (size_x >= 1 && size_y >= 1);
// Given model must be big enough to allow a subimage of the
// requested size to fit.
g_assert (model->size_x <= SSIZE_MAX && model->size_y <= SSIZE_MAX);
g_assert (x + size_x <= (ssize_t) model->size_x);
g_assert (y + size_y <= (ssize_t) model->size_y);
UInt8Image *self = uint8_image_new (size_x, size_y);
// Copy the image pixels from the model.
ssize_t ii, jj;
for ( ii = 0 ; ii < (ssize_t) self->size_x ; ii++ ) {
for ( jj = 0 ; jj < (ssize_t) self->size_y ; jj++ ) {
uint8_t pv = uint8_image_get_pixel (model, x + ii, y + jj);
uint8_image_set_pixel (self, ii, jj, pv);
}
}
return self;
}
// Return true iff file is size or larger.
static gboolean
is_large_enough (const char *file, off_t size)
{
struct stat stat_buffer;
#if GLIB_CHECK_VERSION(2, 6, 0)
int return_code = g_stat (file, &stat_buffer);
if ( return_code != 0 ) {
g_error ("Couldn't g_stat file %s: %s", file, strerror (errno));
}
#else
int return_code = stat (file, &stat_buffer);
if ( return_code != 0 ) {
g_error ("Couldn't stat file %s: %s", file, strerror (errno));
}
#endif
return stat_buffer.st_size >= size;
}
UInt8Image *
uint8_image_new_from_file (ssize_t size_x, ssize_t size_y, const char *file,
off_t offset)
{
g_assert (size_x > 0 && size_y > 0);
// Check in advance if the source file looks big enough (we will
// still need to check return codes as we read() data, of course).
g_assert (is_large_enough (file, offset + ((off_t) size_x * size_y
* sizeof (uint8_t))));
// Open the file to read data from.
FILE *fp = fopen (file, "rb");
// FIXME: we need some error handling and propagation here.
g_assert (fp != NULL);
UInt8Image *self = uint8_image_new_from_file_pointer (size_x, size_y, fp,
offset);
// Close file we read image from.
int return_code = fclose (fp);
g_assert (return_code == 0);
return self;
}
// Return true iff file referred to by file_pointer is larger than size.
static gboolean
file_pointed_to_larger_than (FILE *file_pointer, off_t size)
{
struct stat stat_buffer;
int return_code = fstat (fileno (file_pointer), &stat_buffer);
g_assert (return_code == 0);
return stat_buffer.st_size >= size;
}
UInt8Image *
uint8_image_new_from_file_pointer (ssize_t size_x, ssize_t size_y,
FILE *file_pointer, off_t offset)
{
g_assert (size_x > 0 && size_y > 0);
// Check in advance if the source file looks big enough (we will
// still need to check return codes as we read() data, of course).
g_assert (file_pointed_to_larger_than (file_pointer,
offset + ((off_t) size_x * size_y
* sizeof (uint8_t))));
UInt8Image *self = initialize_uint8_image_structure (size_x, size_y);
FILE *fp = file_pointer; // Convenience alias.
// Seek to the indicated offset in the file.
int return_code = FSEEK64 (fp, offset, SEEK_CUR);
g_assert (return_code == 0);
// If we need a tile file for an image of this size, we will load
// the data straight into it.
if ( self->tile_file != NULL ) {
// We will read the input image data in horizontal stips one tile
// high. Note that we probably won't be able to entirely fill the
// last tiles in each dimension with real data, since the image
// sizes rarely divide evenly by the numbers of tiles. So we fill
// it with zeros instead. The data off the edges of the image
// should never be accessed directly anyway.
// Some data for doing zero fill. If the tiles are bigger than
// the image itself, we need to make the available zero fill the
// size of the tile instead of the size of the file.
g_assert (self->tile_size <= SSIZE_MAX);
uint8_t *zero_line = g_new0 (uint8_t, (size_x > (ssize_t) self->tile_size ?
(size_t) size_x : self->tile_size));
g_assert (0 == 0x0);
// Buffer capable of holding a full strip.
uint8_t *buffer = g_new (uint8_t, self->tile_size * self->size_x);
// Reorganize data into tiles in tile oriented disk file.
size_t ii = 0;
for ( ii = 0 ; ii < self->tile_count_y ; ii++ ) {
// The "effective_height" of the strip is the portion of the
// strip for which data actually exists. If the effective
// height is less than self->tile>size, we will have to add some
// junk to fill up the extra part of the tile (which should
// never be accessed).
size_t effective_height;
if ( ii < self->tile_count_y - 1
|| self->size_y % self->tile_size == 0 ) {
effective_height = self->tile_size;
}
else {
effective_height = self->size_y % self->tile_size;
}
// Total area of the current strip.
size_t strip_area = effective_height * self->size_x;
// Read one strip of tiles worth of data from the file.
size_t read_count = fread (buffer, sizeof (uint8_t), strip_area, fp);
g_assert (read_count == strip_area);
// Write data from the strip into the tile store.
size_t jj;
for ( jj = 0 ; jj < self->tile_count_x ; jj++ ) {
// This is roughly analogous to effective_height.
size_t effective_width;
if ( jj < self->tile_count_x - 1
|| self->size_x % self->tile_size == 0) {
effective_width = self->tile_size;
}
else {
effective_width = self->size_x % self->tile_size;
}
size_t write_count; // For return of fwrite() calls.
size_t kk;
for ( kk = 0 ; kk < effective_height ; kk++ ) {
write_count
= fwrite (buffer + kk * self->size_x + jj * self->tile_size,
sizeof (uint8_t), effective_width, self->tile_file);
// If we wrote less than expected,
if ( write_count < effective_width ) {
// it must have been a write error (probably no space left),
g_assert (ferror (self->tile_file));
// so print an error message,
fprintf (stderr,
"Error writing tile cache file for UInt8Image "
"instance: %s\n", strerror (errno));
// and exit.
exit (EXIT_FAILURE);
}
if ( effective_width < self->tile_size ) {
// Amount we have left to write to fill out the last tile.
size_t edge_width = self->tile_size - effective_width;
write_count = fwrite (zero_line, sizeof (uint8_t), edge_width,
self->tile_file);
// If we wrote less than expected,
if ( write_count < edge_width ) {
// it must have been a write error (probably no space left),
g_assert (ferror (self->tile_file));
// so print an error message,
fprintf (stderr,
"Error writing tile cache file for UInt8Image "
"instance: %s\n", strerror (errno));
// and exit.
exit (EXIT_FAILURE);
}
}
}
// Finish writing the bottom of the tile for which there is no
// image data (should only happen if we are on the last strip of
// tiles).
for ( ; kk < self->tile_size ; kk++ ) {
g_assert (ii == self->tile_count_y - 1);
write_count = fwrite (zero_line, sizeof (uint8_t), self->tile_size,
self->tile_file);
// If we wrote less than expected,
if ( write_count < self->tile_size ) {
// it must have been a write error (probably no space left),
g_assert (ferror (self->tile_file));
// so print an error message,
fprintf (stderr,
"Error writing tile cache file for UInt8Image "
"instance: %s\n", strerror (errno));
// and exit.
exit (EXIT_FAILURE);
}
}
}
}
// Did we write the correct total amount of data?
g_assert (FTELL64 (self->tile_file)
== ((off_t) self->tile_area * self->tile_count
* sizeof (uint8_t)));
// Free temporary buffers.
g_free (buffer);
g_free (zero_line);
}
// Everything fits in the cache (at the moment this means everything
// fits in the first tile, which is a bit of a FIXME), so just put
// it there.
else {
self->tile_addresses[0] = self->cache;
size_t ii;
for ( ii = 0 ; ii < self->size_y ; ii++ ) {
// Address where the current row of pixels should end up.
uint8_t *row_address = self->tile_addresses[0] + ii * self->tile_size;
// Read the data.
size_t read_count = fread (row_address, sizeof (uint8_t), self->size_x,
fp);
g_assert (read_count == self->size_x);
}
}
return self;
}
UInt8Image *
uint8_image_new_from_file_scaled (ssize_t size_x, ssize_t size_y,
ssize_t original_size_x,
ssize_t original_size_y,
const char *file, off_t offset)
{
// This method has been carefully translated from the corresponding
// method in float_image.c, but it hasn't been tested yet.
g_assert_not_reached ();
g_assert (size_x > 0 && size_y > 0);
g_assert (original_size_x > 0 && original_size_y > 0);
// Image can only be scaled down with this routine, not up.
g_assert (size_x < original_size_x);
g_assert (size_y < original_size_y);
// Check in advance if the source file looks big enough (we will
// still need to check return codes as we read() data, of course).
g_assert (is_large_enough (file,
offset + ((off_t) original_size_x
* original_size_y
* sizeof (uint8_t))));
// Find the stride that we need to use in each dimension to evenly
// cover the original image space.
double stride_x = (size_x == 1 ? 0.0
: (double) (original_size_x - 1) / (size_x - 1));
double stride_y = (size_y == 1 ? 0.0
: (double) (original_size_y - 1) / (size_y - 1));
// Open the file to read data from.
FILE *fp = fopen (file, "rb");
// FIXME: we need some error handling and propagation here.
g_assert (fp != NULL);
// We will do a row at a time to save some possibly expensive
// seeking. So here we have an entire row worth of upper lefts,
// upper rights, etc.
uint8_t *uls = g_new (uint8_t, size_x);
uint8_t *urs = g_new (uint8_t, size_x);
uint8_t *lls = g_new (uint8_t, size_x);
uint8_t *lrs = g_new (uint8_t, size_x);
// Results of rounded bilinear interpolation for the current row.
uint8_t *interpolated_values = g_new (uint8_t, size_x);
// We will write the reduced resolution version of the image into a
// temporary file so we can leverage the new_from_file method and
// avoid trying to stick the whole reduced resolution image in
// memory.
FILE *reduced_image = tmpfile ();
ssize_t ii, jj;
for ( ii = 0 ; ii < size_y ; ii++ ) {
size_t read_count; // For fread calls.
int return_code; // For FSEEK64 calls.
// Input image y index of row above row of interest.
ssize_t in_ray = floor (ii * stride_y);
// Due to the vagaries of floating point arithmetic, we might run
// past the index of our last pixel by a little bit, so we correct.
if ( in_ray >= original_size_y - 1 ) {
// We better not be much over the last index though.
g_assert (in_ray < original_size_y);
// The index should be an integer, so floor should fix us up.
in_ray = floor (in_ray);
g_assert (in_ray == original_size_y - 1);
}
g_assert (in_ray < original_size_y);
// Input image y index of row below row of interest. If we would
// be off the image, we just take the last row a second time, and
// let the interpolation work things out.
ssize_t in_rby;
if ( in_ray == original_size_y - 1 ) {
in_rby = in_ray;
}
else {
in_rby = in_ray + 1;
}
// Fetch the row above.
for ( jj = 0 ; jj < size_x ; jj++ ) {
// Input image indicies of current upper left corner pixel.
ssize_t in_ul_x = floor (jj * stride_x);
// Watch for floating point inexactness (see comment above).
if ( G_UNLIKELY (in_ul_x >= original_size_x - 1) ) {
g_assert (in_ul_x < original_size_x);
in_ul_x = floor (in_ul_x);
g_assert (in_ul_x == original_size_x - 1);
}
g_assert (in_ul_x < original_size_x);
size_t in_ul_y = in_ray;
off_t sample_offset
= offset + sizeof (uint8_t) * ((off_t) in_ul_y * original_size_x
+ in_ul_x);
return_code = FSEEK64 (fp, sample_offset, SEEK_SET);
g_assert (return_code == 0);
read_count = fread (&(uls[jj]), sizeof (uint8_t), 1, fp);
g_assert (read_count == 1);
// If the upper left pixel was the last pixel in the input image,
if ( in_ul_x == original_size_x - 1 ) {
// just treat it as the upper right as well,
urs[jj] = uls[jj];
}
// otherwise read the next pixel as the upper right pixel.
else {
read_count = fread (&(urs[jj]), sizeof (uint8_t), 1, fp);
g_assert (read_count == 1);
}
}
// Fetch the row below.
for ( jj = 0 ; jj < size_x ; jj++ ) {
// Input image indicies of the lower left corner pixel.
ssize_t in_ll_x = floor (jj * stride_x);
// Watch for floating point inexactness (see comment above).
if ( G_UNLIKELY (in_ll_x >= original_size_y - 1) ) {
g_assert (in_ll_x < original_size_x);
in_ll_x = floor (in_ll_x);
g_assert (in_ll_x == original_size_x - 1);
}
g_assert (in_ll_x < original_size_x);
size_t in_ll_y = in_rby;
off_t sample_offset
= offset + sizeof (uint8_t) * ((off_t) in_ll_y * original_size_x
+ in_ll_x);
return_code = FSEEK64 (fp, sample_offset, SEEK_SET);
g_assert (return_code == 0);
read_count = fread (&(lls[jj]), sizeof (uint8_t), 1, fp);
g_assert (read_count == 1);
// If the lower left pixel was the last pixel in the input image,
if ( in_ll_x == original_size_x - 1 ) {
// just treat it as the lower right as well,
lrs[jj] = lls[jj];
}
// otherwise read the next pixel as the lower right pixel.
else {
read_count = fread (&(lrs[jj]), sizeof (uint8_t), 1, fp);
g_assert (read_count == 1);
}
}
// Perform the interpolation.
for ( jj = 0 ; jj < size_x ; jj++ ) {
double delta_x = stride_x * jj - floor (stride_x * jj);
double delta_y = -(stride_y * ii - floor (stride_y * ii));
float interpolated_value = bilinear_interpolate (delta_x, delta_y,
uls[jj], urs[jj],
lls[jj], lrs[jj]);
g_assert (interpolated_value >= 0);
g_assert (interpolated_value <= UINT8_MAX);
interpolated_values[jj] = round (interpolated_value);
}
size_t write_count = fwrite (interpolated_values, sizeof (uint8_t), size_x,
reduced_image);
g_assert (write_count == (size_t) size_x);
}
// We are done with the temporary buffers.
g_free (interpolated_values);
g_free (lrs);
g_free (lls);
g_free (urs);
g_free (uls);
// Reposition to the beginning of the temporary file to fit with
// operation of new_from_file_pointer method.
int return_code = FSEEK64 (reduced_image, (off_t) 0, SEEK_SET);
g_assert (return_code == 0);
// Slurp the scaled file back in as an instance.
UInt8Image *self
= uint8_image_new_from_file_pointer (size_x, size_y, reduced_image,
(off_t) 0);
// Now that we have an instantiated version of the image we are done
// with this temporary file.
return_code = fclose (reduced_image);
return self;
}
// Returns a new UInt8Image, for the image corresponding to the given metadata.
UInt8Image *
uint8_image_new_from_metadata(meta_parameters *meta, const char *file)
{
return uint8_image_band_new_from_metadata(meta, 0, file);
}
// Returns a new UInt8Image, for the image band corresponding to the
// given metadata.
UInt8Image *
uint8_image_band_new_from_metadata(meta_parameters *meta,
int band, const char *file)
{
int nl = meta->general->line_count;
int ns = meta->general->sample_count;
FILE * fp = FOPEN(file, "rb");
UInt8Image * bi = uint8_image_new(ns, nl);
int i,j;
unsigned char *buf = MALLOC(sizeof(unsigned char)*ns);
for (i = 0; i < nl; ++i) {
get_byte_line(fp, meta, i+band*nl, buf);
for (j = 0; j < ns; ++j)
uint8_image_set_pixel(bi, j, i, buf[j]);
}
free(buf);
fclose(fp);
return bi;
}
// Copy the contents of tile with flattened offset tile_offset from
// the memory cache to the disk file. Its probably easiest to
// understand this function by looking at how its used.
static void
cached_tile_to_disk (UInt8Image *self, size_t tile_offset)
{
// If we aren't using a tile file, this operation doesn't make
// sense.
g_assert (self->tile_file != NULL);
// We must have a legitimate tile_offset.
g_assert (tile_offset < self->tile_count);
// The tile we are trying to copy from cache to disk must be loaded
// in the cache for this operation to make sense.
g_assert (self->tile_addresses[tile_offset] != NULL);
int return_code
= FSEEK64 (self->tile_file,
(off_t) tile_offset * self->tile_area * sizeof (uint8_t),
SEEK_SET);
g_assert (return_code == 0);
size_t write_count = fwrite (self->tile_addresses[tile_offset],
sizeof (uint8_t), self->tile_area,
self->tile_file);
g_assert (write_count == self->tile_area);
}
// Return true iff tile (x, y) is already loaded into the memory cache.
static gboolean
tile_is_loaded (UInt8Image *self, ssize_t x, ssize_t y)
{
g_assert ( x >= 0 && (size_t) x < self->tile_count_x
&& y >= 0 && (size_t) y < self->tile_count_y );
size_t tile_offset = self->tile_count_x * y + x;
return self->tile_addresses[tile_offset] != NULL;
}
// Load (currently unloaded) tile (x, y) from disk cache into memory
// cache, possibly displacing the oldest tile already loaded, updating
// the load order queue, and returning the address of the tile loaded.
static uint8_t *
load_tile (UInt8Image *self, ssize_t x, ssize_t y)
{
// Make sure we haven't screwed up somehow and not created a tile
// file when in fact we should have.
g_assert (self->tile_file != NULL);
g_assert (!tile_is_loaded (self, x, y));
// Address into which tile gets loaded (to be returned).
uint8_t *tile_address;
// Offset of tile in flattened array.
size_t tile_offset = self->tile_count_x * y + x;
// We have to check and see if we have to displace an already loaded
// tile or not.
if ( self->tile_queue->length == self->cache_size_in_tiles ) {
// Displace tile loaded longest ago.
size_t oldest_tile
= GPOINTER_TO_INT (g_queue_pop_tail (self->tile_queue));
cached_tile_to_disk (self, oldest_tile);
tile_address = self->tile_addresses[oldest_tile];
self->tile_addresses[oldest_tile] = NULL;
}
else {
// Load tile into first free slot.
tile_address = self->cache + self->tile_queue->length * self->tile_area;
}
// Put the new tile address into the index, and put the index into
// the load order queue.
self->tile_addresses[tile_offset] = tile_address;
// Stash in queue by converting to a pointer (so it must fit in an int).
g_assert (tile_offset < INT_MAX);
g_queue_push_head (self->tile_queue,
GINT_TO_POINTER ((int) tile_offset));
// Load the tile data.
int return_code
= FSEEK64 (self->tile_file,
(off_t) tile_offset * self->tile_area * sizeof (uint8_t),
SEEK_SET);
g_assert (return_code == 0);
clearerr (self->tile_file);
size_t read_count = fread (tile_address, sizeof (uint8_t), self->tile_area,
self->tile_file);
if ( read_count < self->tile_area ) {
if ( ferror (self->tile_file) ) {
perror ("error reading tile cache file");
g_assert_not_reached ();
}
if ( feof (self->tile_file) ) {
fprintf (stderr,
"nothing left to read in tile cache file at offset %lld\n",
FTELL64 (self->tile_file));
g_assert_not_reached ();
}
}
g_assert (read_count == self->tile_area);
return tile_address;
}
uint8_t
uint8_image_get_pixel (UInt8Image *self, ssize_t x, ssize_t y)
{
// Are we at a valid image pixel?
g_assert (x >= 0 && (size_t) x < self->size_x);
g_assert (y >= 0 && (size_t) y < self->size_y);
// Get the pixel coordinates, including tile and pixel-in-tile.
g_assert (sizeof (long int) >= sizeof (size_t));
ldiv_t pc_x = ldiv (x, self->tile_size), pc_y = ldiv (y, self->tile_size);
// Offset of tile x, y, where tiles are viewed as pixels normally are.
size_t tile_offset = self->tile_count_x * pc_y.quot + pc_x.quot;
// Address of data for tile containing pixel of interest (may still
// have to be loaded from disk cache).
uint8_t *tile_address = self->tile_addresses[tile_offset];
// Load the tile containing the pixel of interest if necessary.
if ( G_UNLIKELY (tile_address == NULL) ) {
tile_address = load_tile (self, pc_x.quot, pc_y.quot);
}
// Return pixel of interest.
return tile_address[self->tile_size * pc_y.rem + pc_x.rem];
}
void
uint8_image_set_pixel (UInt8Image *self, ssize_t x, ssize_t y, uint8_t value)
{
// Are we at a valid image pixel?
g_assert (self != NULL);
g_assert (x >= 0 && (size_t) x <= self->size_x);
g_assert (y >= 0 && (size_t) y <= self->size_y);
// Get the pixel coordinates, including tile and pixel-in-tile.
g_assert (sizeof (long int) >= sizeof (size_t));
ldiv_t pc_x = ldiv (x, self->tile_size), pc_y = ldiv (y, self->tile_size);
// Offset of tile x, y, where tiles are viewed as pixels normally are.
size_t tile_offset = self->tile_count_x * pc_y.quot + pc_x.quot;
// Address of data for tile containing pixel of interest (may still
// have to be loaded from disk cache).
uint8_t *tile_address = self->tile_addresses[tile_offset];
// Load the tile containing the pixel of interest if necessary.
if ( G_UNLIKELY (tile_address == NULL) ) {
tile_address = load_tile (self, pc_x.quot, pc_y.quot);
}
// Set pixel of interest.
tile_address[self->tile_size * pc_y.rem + pc_x.rem] = value;
}
void
uint8_image_get_region (UInt8Image *self, ssize_t x, ssize_t y, ssize_t size_x,
ssize_t size_y, uint8_t *buffer)
{
g_assert (size_x >= 0);
g_assert (x >= 0);
g_assert ((size_t) x + (size_t) size_x - 1 < self->size_x);
g_assert (size_y >= 0);
g_assert (y >= 0);
g_assert ((size_t) y + (size_t) size_y - 1 < self->size_y);
ssize_t ii, jj; // Index variables.
for ( ii = 0 ; ii < size_y ; ii++ ) {
for ( jj = 0 ; jj < size_x ; jj++ ) {
// We are essentially returning a subimage from the big image.
// These are the indicies in the big image (self) of the current
// pixel.
size_t ix = x + jj, iy = y + ii;
buffer[ii * size_x + jj] = uint8_image_get_pixel (self, ix, iy);
}
}
}
void
uint8_image_set_region (UInt8Image *self, size_t x, size_t y, size_t size_x,
size_t size_y, uint8_t *buffer)
{
g_assert_not_reached (); // Stubbed out for now.
self = self; x = x; y = y; size_x = size_x, size_y = size_y; buffer = buffer;
}
void
uint8_image_get_row (UInt8Image *self, size_t row, uint8_t *buffer)
{
uint8_image_get_region (self, 0, row, self->size_x, 1, buffer);
}
uint8_t
uint8_image_get_pixel_with_reflection (UInt8Image *self, ssize_t x, ssize_t y)
{
// Carefully clone-and-modified over from float_image.c, but not
// tested yet.
//g_assert_not_reached ();
// Reflect at image edges as advertised.
if ( x < 0 ) {
x = -x;
}
else if ( (size_t) x >= self->size_x ) {
x = self->size_x - 2 - (x - self->size_x);
}
if ( y < 0 ) {
y = -y;
}
else if ( (size_t) y >= self->size_y ) {
y = self->size_y - 2 - (y - self->size_y);
}
return uint8_image_get_pixel (self, x, y);
}
void
uint8_image_statistics (UInt8Image *self, uint8_t *min, uint8_t *max,
double *mean, double *standard_deviation,
gboolean use_mask_value, uint8_t mask_value)
{
// Carefully clone-and-modified over from float_image.c, but not
// tested yet.
//g_assert_not_reached ();
// Minimum and maximum sample values as integers.
int imin = INT_MAX, imax = INT_MIN;
// Buffer for one row of samples.
uint8_t *row_buffer = g_new (uint8_t, self->size_x);
*mean = 0.0;
double s = 0.0;
size_t sample_count = 0; // Samples considered so far.
size_t ii, jj;
// If there is a mask value we are supposed to ignore,
if ( use_mask_value ) {
// iterate over all pixels, skipping pixels equal to mask value.
for ( ii = 0 ; ii < self->size_y ; ii++ ) {
asfPercentMeter((double)ii/(double)(self->size_y));
uint8_image_get_row (self, ii, row_buffer);
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
uint8_t cs = row_buffer[jj]; // Current sample.
if ( cs == mask_value ) {
continue;
}
if ( G_UNLIKELY (cs < imin) ) { imin = cs; }
if ( G_UNLIKELY (cs > imax) ) { imax = cs; }
double old_mean = *mean;
*mean += (cs - *mean) / (sample_count + 1);
s += (cs - old_mean) * (cs - *mean);
sample_count++;
}
}
asfPercentMeter(1.0);
}
else {
// There is no mask value to ignore, so we do the same as the
// above loop, but without the possible continue statement.
for ( ii = 0 ; ii < self->size_y ; ii++ ) {
asfPercentMeter((double)ii/(double)(self->size_y));
uint8_image_get_row (self, ii, row_buffer);
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
uint8_t cs = row_buffer[jj]; // Current sample.
if ( G_UNLIKELY (cs < imin) ) { imin = cs; }
if ( G_UNLIKELY (cs > imax) ) { imax = cs; }
double old_mean = *mean;
*mean += (cs - *mean) / (sample_count + 1);
s += (cs - old_mean) * (cs - *mean);
sample_count++;
}
}
asfPercentMeter(1.0);
}
g_free (row_buffer);
// Verify the new extrema have been found.
g_assert (imin != INT_MAX);
g_assert (imax != INT_MIN);
// The new extrema had better be in the range supported by uint8_t.
g_assert (imin >= 0);
g_assert (imax <= UINT8_MAX);
*min = imin;
*max = imax;
*standard_deviation = sqrt (s / (sample_count - 1));
}
int
uint8_image_band_statistics (UInt8Image *self, meta_stats *stats,
int line_count, int band_no,
gboolean use_mask_value, uint8_t mask_value)
{
// Carefully cloned-and-modified over from float_image.c, but not
// tested yet.
//g_assert_not_reached ();
// Minimum and maximum sample values as integers.
int imin = INT_MAX, imax = INT_MIN;
// Buffer for one row of samples.
uint8_t *row_buffer = g_new (uint8_t, self->size_x);
stats->mean = 0.0;
double s = 0.0;
size_t sample_count = 0; // Samples considered so far.
size_t ii, jj;
// If there is a mask value we are supposed to ignore,
if ( use_mask_value ) {
// iterate over all pixels, skipping pixels equal to mask value.
for ( ii = (band_no * line_count); // 0-ordered band number times lines is offset into image
ii < (band_no+1) * line_count && ii < self->size_y;
ii++ )
{
asfPercentMeter( (double)(ii - band_no*line_count)/(double)line_count );
uint8_image_get_row (self, ii, row_buffer);
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
uint8_t cs = row_buffer[jj]; // Current sample.
if ( cs == mask_value ) {
continue;
}
if ( G_UNLIKELY (cs < imin) ) { imin = cs; }
if ( G_UNLIKELY (cs > imax) ) { imax = cs; }
double old_mean = stats->mean;
stats->mean += (cs - stats->mean) / (sample_count + 1);
s += (cs - old_mean) * (cs - stats->mean);
sample_count++;
}
}
asfPercentMeter(1.0);
}
else {
// There is no mask value to ignore, so we do the same as the
// above loop, but without the possible continue statement.
for ( ii = (band_no * line_count); // 0-ordered band number times lines is offset into image
ii < (band_no+1) * line_count && ii < self->size_y;
ii++ )
{
asfPercentMeter( (double)(ii - band_no*line_count)/(double)line_count );
uint8_image_get_row (self, ii, row_buffer);
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
uint8_t cs = row_buffer[jj]; // Current sample.
if ( G_UNLIKELY (cs < imin) ) { imin = cs; }
if ( G_UNLIKELY (cs > imax) ) { imax = cs; }
double old_mean = stats->mean;
stats->mean += (cs - stats->mean) / (sample_count + 1);
s += (cs - old_mean) * (cs - stats->mean);
sample_count++;
}
}
asfPercentMeter(1.0);
}
g_free (row_buffer);
// Verify the new extrema have been found.
if (imin == INT_MAX || imax == INT_MIN)
return 1;
// The new extrema had better be in the range supported by uint8_t.
if (imin < 0 || imax > UINT8_MAX)
return 1;
stats->min = imin;
stats->max = imax;
stats->std_deviation = sqrt (s / (sample_count - 1));
return 0;
}
void
uint8_image_statistics_with_mask_interval (UInt8Image *self, uint8_t *min,
uint8_t *max, double *mean,
double *standard_deviation,
uint8_t interval_start,
uint8_t interval_end)
{
// This method is a trivial clone-and-modify of
// float_image_statistics, but it is totally untested at the moment.
g_assert_not_reached ();
// Minimum and maximum sample values as integers.
int imin = INT_MAX, imax = INT_MIN;
// Buffer for one row of samples.
uint8_t *row_buffer = g_new (uint8_t, self->size_x);
*mean = 0.0;
double s = 0.0;
size_t sample_count = 0; // Samples considered so far.
size_t ii, jj;
for ( ii = 0 ; ii < self->size_y ; ii++ ) {
uint8_image_get_row (self, ii, row_buffer);
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
uint8_t cs = row_buffer[jj]; // Current sample.
// If in the mask interval, do not consider this pixel any
// further.
if ( cs >= interval_start && cs <= interval_end ) {
continue;
}
if ( G_UNLIKELY (cs < imin) ) { imin = cs; }
if ( G_UNLIKELY (cs > imax) ) { imax = cs; }
double old_mean = *mean;
*mean += (cs - *mean) / (sample_count + 1);
s += (cs - old_mean) * (cs - *mean);
sample_count++;
}
}
g_free (row_buffer);
// Verify the new extrema have been found.
g_assert (imin != INT_MAX);
g_assert (imax != INT_MIN);
// The new extrema had better be in the range supported by uint8_t.
g_assert (imin >= 0);
g_assert (imax <= UINT8_MAX);
*min = imin;
*max = imax;
*standard_deviation = sqrt (s / (sample_count - 1));
}
void
uint8_image_approximate_statistics (UInt8Image *self, size_t stride,
double *mean, double *standard_deviation,
gboolean use_mask_value,
uint8_t mask_value)
{
// Rows and columns of samples that fit in image given stride
// stride.
size_t sample_columns = ceil (self->size_x / stride);
size_t sample_rows = ceil (self->size_y / stride);
// Total number of samples.
size_t sample_count = sample_columns * sample_rows;
// Create an image holding the sample values.
UInt8Image *sample_image = uint8_image_new (sample_columns, sample_rows);
// Load the sample values.
size_t current_sample = 0;
size_t ii;
for ( ii = 0 ; ii < sample_columns ; ii++ ) {
size_t jj;
for ( jj = 0 ; jj < sample_rows ; jj++ ) {
uint8_t sample = uint8_image_get_pixel (self, ii * stride, jj * stride);
uint8_image_set_pixel (sample_image, ii, jj, sample);
current_sample++;
}
}
// Ensure that we got the right number of samples in our image.
g_assert (current_sample == sample_count);
// Compute the exact statistics of the sampled version of the image.
// The _statistics method wants to compute min and max, so we let
// it, even though we don't do anything with them (since they are
// inaccurate).
uint8_t min, max;
uint8_image_statistics (sample_image, &min, &max, mean, standard_deviation,
use_mask_value, mask_value);
uint8_image_free (sample_image);
}
void
uint8_image_approximate_statistics_with_mask_interval
(UInt8Image *self, size_t stride, double *mean, double *standard_deviation,
uint8_t interval_start, uint8_t interval_end)
{
// This method is a trivial clone-and-modify of
// float_image_approximate_statistics, but it is totally untested at
// the moment.
g_assert_not_reached ();
// Rows and columns of samples that fit in image given stride
// stride.
size_t sample_columns = ceil (self->size_x / stride);
size_t sample_rows = ceil (self->size_y / stride);
// Total number of samples.
size_t sample_count = sample_columns * sample_rows;
// Create an image holding the sample values.
UInt8Image *sample_image = uint8_image_new (sample_columns, sample_rows);
// Load the sample values.
size_t current_sample = 0;
size_t ii;
for ( ii = 0 ; ii < sample_columns ; ii++ ) {
size_t jj;
for ( jj = 0 ; jj < sample_rows ; jj++ ) {
uint8_t sample = uint8_image_get_pixel (self, ii * stride, jj * stride);
uint8_image_set_pixel (sample_image, ii, jj, sample);
current_sample++;
}
}
// Ensure that we got the right number of samples in our image.
g_assert (current_sample == sample_count);
// Compute the exact statistics of the sampled version of the image.
// The _statistics method wants to compute min and max, so we let
// it, even though we don't do anything with them (since they are
// inaccurate).
uint8_t min, max;
uint8_image_statistics_with_mask_interval (sample_image, &min, &max,
mean, standard_deviation,
interval_start, interval_end);
uint8_image_free (sample_image);
}
gsl_histogram *
uint8_image_gsl_histogram (UInt8Image *self, double min, double max,
size_t bin_count)
{
// Carefully clone-and-modified over from float_image.c, but not
// tested yet.
g_assert_not_reached ();
// Initialize the histogram.
gsl_histogram *histogram = gsl_histogram_alloc (bin_count);
gsl_histogram_set_ranges_uniform (histogram, min, max);
// Buffer for one row of samples.
uint8_t *row_buffer = g_new (uint8_t, self->size_x);
// Populate the histogram over every sample in the image.
size_t ii, jj;
for (ii = 0 ; ii < self->size_y ; ii++ ) {
uint8_image_get_row (self, ii, row_buffer);
for ( jj = 0 ; jj < self->size_x ; jj++ ) {
gsl_histogram_increment (histogram, row_buffer[jj]);
}
}
g_free (row_buffer);
return histogram;
}
double
uint8_image_apply_kernel (UInt8Image *self, ssize_t x, ssize_t y,
gsl_matrix *kern)
{
// Carefully clone-and-modified over from float_image.c, but not
// tested yet.
g_assert_not_reached ();
g_assert (x >= 0 && (size_t) x < self->size_x);
g_assert (y >= 0 && (size_t) y < self->size_y);
g_assert (kern->size2 % 2 == 1);
g_assert (kern->size2 == kern->size1);
size_t ks = kern->size2; // Kernel size.
double sum = 0; // Result.
size_t ii;
for ( ii = 0 ; ii < kern->size1 ; ii++ ) {
ssize_t iy = y - ks / 2 + ii; // Current image y pixel index.
size_t jj;
for ( jj = 0 ; jj < kern->size2 ; jj++ ) {
ssize_t ix = x - ks / 2 + jj; // Current image x pixel index
sum += (gsl_matrix_get (kern, jj, ii)
* uint8_image_get_pixel_with_reflection (self, ix, iy));
}
}
return sum;
}
double
uint8_image_sample (UInt8Image *self, double x, double y,
uint8_image_sample_method_t sample_method)
{
g_assert (x >= 0.0 && x <= (double) self->size_x - 1.0);
g_assert (y >= 0.0 && y <= (double) self->size_y - 1.0);
switch ( sample_method ) {
case UINT8_IMAGE_SAMPLE_METHOD_NEAREST_NEIGHBOR:
return uint8_image_get_pixel (self, round (x), round (y));
break;
case UINT8_IMAGE_SAMPLE_METHOD_BILINEAR:
{
// Indicies of points we are interpolating between (x below, y
// below, etc., where below is interpreted in the numerical
// sense, not the image orientation sense.).
size_t xb = floor (x), yb = floor (y), xa = ceil (x), ya = ceil (y);
size_t ts = self->tile_size; // Convenience alias.
// Offset of xb, yb, etc. relative to tiles they lie in.
size_t xbto = xb % ts, ybto = yb % ts, xato = xa % ts, yato = ya % ts;
// Values of points we are interpolating between.
uint8_t ul, ur, ll, lr;
// If the points were are interpolating between don't span a
// tile edge, we load them straight from tile memory to save
// some time.
if ( G_LIKELY ( xbto != ts - 1 && xato != 0
&& ybto != ts - 1 && yato != 0) ) {
// The tile indicies.
size_t tx = xb / ts, ty = yb / ts;
// Tile offset in flattened list of tile addresses.
size_t tile_offset = ty * self->tile_count_x + tx;
uint8_t *tile_address = self->tile_addresses[tile_offset];
if ( G_UNLIKELY (tile_address == NULL) ) {
tile_address = load_tile (self, tx, ty);
}
ul = tile_address[ybto * self->tile_size + xbto];
ur = tile_address[ybto * self->tile_size + xato];
ll = tile_address[yato * self->tile_size + xbto];
lr = tile_address[yato * self->tile_size + xato];
}
else {
// We are spanning a tile edge, so we just get the pixels
// using the inefficient but easy get_pixel method.
ul = uint8_image_get_pixel (self, floor (x), floor (y));
ur = uint8_image_get_pixel (self, ceil (x), floor (y));
ll = uint8_image_get_pixel (self, floor (x), ceil (y));
lr = uint8_image_get_pixel (self, ceil (x), ceil (y));
}
// Upper and lower values interpolated in the x direction.
double ux = ul + (ur - ul) * (x - floor (x));
double lx = ll + (lr - ll) * (x - floor (x));
return ux + (lx - ux) * (y - floor (y));
}
break;
case UINT8_IMAGE_SAMPLE_METHOD_BICUBIC:
{
// Should never be here ...bicubic resampling can result in negative
// values and should not be used for resampling unsigned values...
//g_assert_not_reached ();
asfPrintError ("BICUBIC resampling for BYTE data is not supported.\n");
static gboolean first_time_through = TRUE;
// Splines in the x direction, and their lookup accelerators.
static double *x_indicies;
static double *values;
static gsl_spline **xss;
static gsl_interp_accel **xias;
// Spline between splines in the y direction, and lookup accelerator.
static double *y_spline_indicies;
static double *y_spline_values;
static gsl_spline *ys;
static gsl_interp_accel *yia;
// All these splines have size 4.
const size_t ss = 4;
size_t ii; // Index variable.
if ( first_time_through ) {
// Allocate memory for the splines in the x direction.
x_indicies = g_new (double, ss);
values = g_new (double, ss);
xss = g_new (gsl_spline *, ss);
xias = g_new (gsl_interp_accel *, ss);
for ( ii = 0 ; ii < ss ; ii++ ) {
xss[ii] = gsl_spline_alloc (gsl_interp_cspline, ss);
xias[ii] = gsl_interp_accel_alloc ();
}
// Allocate memory for the spline in the y direction.
y_spline_indicies = g_new (double, ss);
y_spline_values = g_new (double, ss);
ys = gsl_spline_alloc (gsl_interp_cspline, ss);
yia = gsl_interp_accel_alloc ();
first_time_through = FALSE;
}
// Get the values for the nearest 16 points.
size_t jj; // Index variable.
for ( ii = 0 ; ii < ss ; ii++ ) {
for ( jj = 0 ; jj < ss ; jj++ ) {
x_indicies[jj] = floor (x) - 1 + jj;
values[jj]
= uint8_image_get_pixel_with_reflection (self, x_indicies[jj],
floor (y) - 1 + ii);
}
gsl_spline_init (xss[ii], x_indicies, values, ss);
}
// Set up the spline that runs in the y direction.
for ( ii = 0 ; ii < ss ; ii++ ) {
y_spline_indicies[ii] = floor (y) - 1 + ii;
y_spline_values[ii] = gsl_spline_eval (xss[ii], x, xias[ii]);
}
gsl_spline_init (ys, y_spline_indicies, y_spline_values, ss);
double ret_val = gsl_spline_eval (ys, y, yia);
// NOTE... NOTE... BICUBIC resample returns negative values if the byte values are
// too close to zero and the spline fit goes negative in the neighborhood of the pixel
/*
if (ret_val > 255.0 || ret_val < 0.0) {
asfPrintWarning("Bicubic resampling of BYTE data returned out of range value (%f).\n"
"...Continuing, but negative values will be forced to zero, and values above 255\n"
" will be forced to 255\n",
ret_val);
if (ret_val > 265.0) {
asfPrintError("Bicubic resampling of BYTE data returned a value (%f) too far above 255.0 to\n"
"cap to 255.0\n", ret_val);
}
if (ret_val < -10.0) {
asfPrintError("Bicubic resampling of BYTE data returned a value (%f) too far below 0.0 to\n"
"cap to 0.0\n", ret_val);
}
ret_val = ret_val < 0.0 ? 0.0 : ret_val;
ret_val = ret_val > 255.0 ? 255.0 : ret_val;
}
*/
return ret_val;
}
break;
default:
g_assert_not_reached ();
return -42; // Reassure the compiler.
}
}
gboolean
uint8_image_equals (UInt8Image *self, UInt8Image *other)
{
// Compare image sizes.
if ( self->size_x != other->size_x ) {
return FALSE;
}
if ( self->size_y != other->size_y ) {
return FALSE;
}
size_t sz = self->size_x; // Convenience alias.
// Compare image pixels.
size_t ii, jj;
for ( ii = 0 ; ii < sz ; ii++ ) {
for ( jj = 0 ; jj < sz ; jj++ ) {
if ( G_UNLIKELY (uint8_image_get_pixel (self, jj, ii)
!= uint8_image_get_pixel (other, jj, ii)) ) {
return FALSE;
}
}
}
return TRUE;
}
// Flip an image about a horizontal line through the center of the image
void
uint8_image_flip_y(UInt8Image *self)
{
size_t ii, jj;
asfLineMeter(jj, self->size_y);
for (jj = 0; jj < self->size_y / 2; ++jj) {
asfLineMeter(2 * jj + 1, self->size_y);
size_t jj2 = self->size_y - 1 - jj;
for (ii = 0; ii < self->size_x; ++ii) {
uint8 a = uint8_image_get_pixel(self, ii, jj);
uint8 b = uint8_image_get_pixel(self, ii, jj2);
uint8_image_set_pixel(self, ii, jj, b);
uint8_image_set_pixel(self, ii, jj2, a);
}
}
asfLineMeter(1, 1);
}
// Flip an image about a vertical line through the center of the image
void
uint8_image_flip_x(UInt8Image *self)
{
size_t ii, jj;
for (ii = 0; ii < self->size_x / 2; ++ii) {
asfLineMeter(2 * ii + 1, self->size_y);
size_t ii2 = self->size_x - 1 - ii;
for (jj = 0; jj < self->size_y; ++jj) {
uint8 a = uint8_image_get_pixel(self, ii, jj);
uint8 b = uint8_image_get_pixel(self, ii2, jj);
uint8_image_set_pixel(self, ii, jj, b);
uint8_image_set_pixel(self, ii2, jj, a);
}
}
asfLineMeter(1, 1);
}
// Bring the tile cache file on the disk fully into sync with the
// latest image data stored in the memory cache.
static void
synchronize_tile_file_with_memory_cache (UInt8Image *self)
{
// If we aren't using a tile file, this operation doesn't make
// sense.
g_assert (self->tile_file != NULL);
guint ii;
for ( ii = 0 ; ii < self->tile_queue->length ; ii++ ) {
size_t tile_offset = GPOINTER_TO_INT (g_queue_peek_nth (self->tile_queue,
ii));
cached_tile_to_disk (self, tile_offset);
}
}
void
uint8_image_freeze (UInt8Image *self, FILE *file_pointer)
{
FILE *fp = file_pointer; // Convenience alias.
g_assert (file_pointer != NULL);
size_t write_count = fwrite (&(self->size_x), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->size_y), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->cache_space), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->cache_area), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->tile_size), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->cache_size_in_tiles), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->tile_count_x), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->tile_count_y), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->tile_count), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
write_count = fwrite (&(self->tile_area), sizeof (size_t), 1, fp);
g_assert (write_count == 1);
// We don't bother serializing the cache -- its a pain to keep track
// of and probably almost never worth it.
// We write the tile queue pointer away, so that when we later thaw
// the serialized version, we can tell if a cache file is in use or
// not (if it isn't tile_queue will be NULL).
write_count = fwrite (&(self->tile_queue), sizeof (GQueue *), 1, fp);
g_assert (write_count == 1);
// If there was no cache file...
if ( self->tile_queue == NULL ) {
// We store the contents of the first tile and are done.
write_count = fwrite (self->tile_addresses[0], sizeof (uint8_t),
self->tile_area, fp);
if ( write_count < self->tile_area ) {
if ( ferror (fp) ) {
fprintf (stderr, "Error writing serialized UInt8Image instance during "
"freeze: %s\n", strerror (errno));
exit (EXIT_FAILURE);
}
}
g_assert (write_count == self->tile_area);
}
// otherwise, the in memory cache needs to be copied into the tile
// file and the tile file saved in the serialized version of self.
else {
synchronize_tile_file_with_memory_cache (self);
uint8_t *buffer = g_new (uint8_t, self->tile_area);
size_t ii;
off_t tmp = FTELL64 (self->tile_file);
int return_code = FSEEK64 (self->tile_file, 0, SEEK_SET);
g_assert (return_code == 0);
for ( ii = 0 ; ii < self->tile_count ; ii++ ) {
size_t read_count = fread (buffer, sizeof (uint8_t), self->tile_area,
self->tile_file);
g_assert (read_count == self->tile_area);
write_count = fwrite (buffer, sizeof (uint8_t), self->tile_area, fp);
g_assert (write_count == self->tile_area);
}
return_code = FSEEK64 (self->tile_file, tmp, SEEK_SET);
g_assert (return_code == 0);
g_free (buffer);
}
}
int
uint8_image_band_store(UInt8Image *self, const char *file,
meta_parameters *meta, int append_flag)
{
// Give status
if (meta->general->band_count == 1)
asfPrintStatus("\n\nStoring image ...\n");
else
asfPrintStatus("\n\nStoring band ...\n");
// Open the file to write to.
FILE *fp = fopen (file, append_flag ? "ab" : "wb");
// FIXME: we need some error handling and propagation here.
g_assert (fp != NULL);
// We will write the image data in horizontal stips one line at a time.
uint8_t *line_buffer = g_new (uint8_t, self->size_x);
// Sanity check
if (meta->general->line_count != (int)self->size_y ||
meta->general->sample_count != (int)self->size_x)
{
asfPrintError("Inconsistency between metadata and image!\n"
"Metadata says: %dx%d LxS, image has %dx%d\n"
"Possibly did not write metadata before storing image.\n",
meta->general->line_count, meta->general->sample_count,
self->size_y, self->size_x);
}
// Reorganize data into tiles in tile oriented disk file.
int ii;
for ( ii = 0 ; ii < (int)self->size_y ; ii++ ) {
uint8_image_get_row (self, ii, line_buffer);
size_t write_count =
fwrite(line_buffer, sizeof(uint8_t), self->size_x, fp);
if (write_count < self->size_x) {
// it must have been a write error (no space left, possibly)
g_assert(ferror(self->tile_file));
// so print an error message
fprintf(stderr, "Error writing file %s: %s\n", file, strerror(errno));
// and exit
exit (EXIT_FAILURE);
}
g_assert(write_count == self->size_x);
}
// Done with the line buffer.
g_free (line_buffer);
// Close file being written.
int return_code = fclose (fp);
g_assert (return_code == 0);
// Return success code.
return 0;
}
int
uint8_image_store (UInt8Image *self, const char *file)
{
meta_parameters *meta;
meta = meta_read(file);
int ret = uint8_image_band_store(self, file, meta, 0);
meta_free(meta);
return ret;
}
int
uint8_image_export_as_jpeg (UInt8Image *self, const char *file,
size_t max_dimension, gboolean use_mask_value,
uint8_t mask_value)
{
// Carefully clone-and-modified over from float_image.c, but not
// tested yet.
g_assert_not_reached ();
size_t scale_factor; // Scale factor to use for output image.
if ( self->size_x > self->size_y ) {
scale_factor = ceil ((double) self->size_x / max_dimension);
}
else {
scale_factor = ceil ((double) self->size_y / max_dimension);
}
// We want the scale factor to be odd, so that we can easily use a
// standard kernel to average things.
if ( scale_factor % 2 == 0 ) {
scale_factor++;
}
// Output JPEG x and y dimensions.
size_t osx = self->size_x / scale_factor;
size_t osy = self->size_y / scale_factor;
// Number of pixels in output image.
size_t pixel_count = osx * osy;
// Pixels of the output image.
unsigned char *pixels = g_new (unsigned char, pixel_count);
JSAMPLE test_jsample; // For verifying properties of JSAMPLE type.
/* Here are some very funky checks to try to ensure that the JSAMPLE
really is the type we expect, so we can scale properly. */
g_assert (sizeof (unsigned char) == 1);
g_assert (sizeof (unsigned char) == sizeof (JSAMPLE));
test_jsample = 0;
test_jsample--;
g_assert (test_jsample == UCHAR_MAX);
// Stuff needed by libjpeg.
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error (&jerr);
jpeg_create_compress (&cinfo);
// Open output file.
FILE *fp = fopen (file, "wb");
if ( fp == NULL ) { perror ("error opening file"); }
// FIXME: we need some error handling and propagation here.
g_assert (fp != NULL);
// Connect jpeg output to the output file to be used.
jpeg_stdio_dest (&cinfo, fp);
// Set image parameters that libjpeg needs to know about.
cinfo.image_width = osx;
cinfo.image_height = osy;
cinfo.input_components = 1; // Grey scale => 1 color component / pixel.
cinfo.in_color_space = JCS_GRAYSCALE;
jpeg_set_defaults (&cinfo); // Use default compression parameters.
// Reassure libjpeg that we will be writing a complete JPEG file.
jpeg_start_compress (&cinfo, TRUE);
// As advertised, we will average pixels together.
g_assert (scale_factor % 2 != 0);
size_t kernel_size = scale_factor;
gsl_matrix *averaging_kernel
= gsl_matrix_alloc (kernel_size, kernel_size);
double kernel_value = 1.0 / ((double)kernel_size * kernel_size);
size_t ii, jj; // Index values.
for ( ii = 0 ; ii < averaging_kernel->size1 ; ii++ ) {
for ( jj = 0 ; jj < averaging_kernel->size2 ; jj++ ) {
gsl_matrix_set (averaging_kernel, ii, jj, kernel_value);
}
}
// Sample input image, putting scaled results into output image.
size_t sample_stride = scale_factor;
for ( ii = 0 ; ii < osy ; ii++ ) {
for ( jj = 0 ; jj < osx ; jj++ ) {
// Input image average pixel value.
double ival = uint8_image_apply_kernel (self, jj * sample_stride,
ii * sample_stride,
averaging_kernel);
// Set output value.
int32_t oval = round (ival);
// In case floating point arithmetic wierdness gets us in
// trouble, we correct.
if ( oval < 0 ) {
oval = 0;
}
else if ( oval > UINT8_MAX ) {
oval = UINT8_MAX;
}
pixels[ii * osx + jj] = oval;
}
}
// Write the jpeg, one row at a time.
const int rows_to_write = 1;
JSAMPROW *row_pointer = g_new (JSAMPROW, rows_to_write);
while ( cinfo.next_scanline < cinfo.image_height ) {
int rows_written;
row_pointer[0] = &(pixels[cinfo.next_scanline * osx]);
rows_written = jpeg_write_scanlines (&cinfo, row_pointer, rows_to_write);
g_assert (rows_written == rows_to_write);
}
g_free (row_pointer);
// Finsh compression and close the jpeg.
jpeg_finish_compress (&cinfo);
int return_code = fclose (fp);
g_assert (return_code == 0);
jpeg_destroy_compress (&cinfo);
g_free (pixels);
return 0; // Return success indicator.
}
size_t
uint8_image_get_cache_size (UInt8Image *self)
{
g_assert_not_reached (); // Stubbed out for now.
// Compiler reassurance.
self = self;
return 0;
}
void
uint8_image_set_cache_size (UInt8Image *self, size_t size)
{
g_assert_not_reached (); // Stubbed out for now.
// Compiler reassurance.
self = self; size = size;
}
void
uint8_image_free (UInt8Image *self)
{
// Close the tile file (which shouldn't have to remove it since its
// already unlinked), if we were ever using it.
if ( self->tile_file != NULL ) {
int return_code = fclose (self->tile_file);
g_assert (return_code == 0);
}
// Deallocate dynamic memory.
g_free (self->tile_addresses);
// If we didn't need a tile file, we also won't have a tile queue.
if ( self->tile_queue != NULL ) {
g_queue_free (self->tile_queue);
}
g_free (self->cache);
if (self->tile_file_name) {
#ifdef win32
unlink_tmp_file(self->tile_file_name->str);
g_string_free(self->tile_file_name, TRUE);
#endif
}
g_free (self);
}
| {
"alphanum_fraction": 0.6358734385,
"avg_line_length": 34.2705069124,
"ext": "c",
"hexsha": "3e3cf7a2f48c8061b191c7e5f979029023c37096",
"lang": "C",
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-05-15T08:01:09.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-26T18:18:33.000Z",
"max_forks_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "glshort/MapReady",
"max_forks_repo_path": "src/libasf_raster/uint8_image.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"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": "glshort/MapReady",
"max_issues_repo_path": "src/libasf_raster/uint8_image.c",
"max_line_length": 104,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "c9065400a64c87be46418ab32e3a251ca2f55fd5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "glshort/MapReady",
"max_stars_repo_path": "src/libasf_raster/uint8_image.c",
"max_stars_repo_stars_event_max_datetime": "2021-07-28T01:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-12-31T05:33:28.000Z",
"num_tokens": 20383,
"size": 74367
} |
#pragma once
#include <memory>
#include <gsl/span>
#include "graphics/math.h"
#include "infrastructure/macros.h"
namespace gfx {
using MdfRenderMaterialPtr = std::shared_ptr<class MdfRenderMaterial>;
class RenderingDevice;
class Texture;
using TextureRef = std::shared_ptr<Texture>;
struct Line2d {
XMFLOAT2 from;
XMFLOAT2 to;
XMCOLOR diffuse;
Line2d() {}
Line2d(XMFLOAT2 from, XMFLOAT2 to, XMCOLOR color)
: from(from), to(to), diffuse(color) {}
};
#pragma pack(push, 1)
struct Vertex2d {
XMFLOAT4 pos;
XMFLOAT4 normal;
XMCOLOR diffuse;
XMFLOAT2 uv;
};
#pragma pack(pop)
enum class SamplerType2d {
CLAMP,
WRAP,
POINT
};
class SamplerState;
/*
Renders shapes in 2d screen space.
*/
class ShapeRenderer2d {
public:
explicit ShapeRenderer2d(RenderingDevice& g);
~ShapeRenderer2d();
void DrawRectangle(float x, float y, float width, float height, gfx::Texture& texture, uint32_t color = 0xFFFFFFFF, SamplerType2d samplerType = SamplerType2d::CLAMP) {
DrawRectangle(x, y, width, height, &texture, color, samplerType);
}
void DrawRectangle(float x, float y, float width, float height, uint32_t color) {
DrawRectangle(x, y, width, height, nullptr, color);
}
void DrawRectangle(gsl::span<Vertex2d, 4> corners,
gfx::Texture* texture,
gfx::Texture* mask = nullptr,
SamplerType2d samplerType = SamplerType2d::CLAMP,
bool blending = true);
void DrawRectangle(gsl::span<Vertex2d, 4> corners,
const gfx::MdfRenderMaterialPtr &material);
void DrawRectangle(gsl::span<Vertex2d, 4> corners);
void DrawLines(gsl::span<Line2d> lines);
void DrawRectangleOutline(XMFLOAT2 topLeft, XMFLOAT2 bottomRight, XMCOLOR color);
void DrawFullScreenQuad();
/**
* Renders a circle/pie segment for use with the radial menu.
*/
void DrawPieSegment(int segments,
int x, int y,
float angleCenter, float angleWidth,
int innerRadius, int innerOffset,
int outerRadius, int outerOffset,
XMCOLOR color1, XMCOLOR color2);
NO_COPY_OR_MOVE(ShapeRenderer2d);
private:
void DrawRectangle(
float x, float y, float width, float height,
gfx::Texture* texture,
uint32_t color = 0xFFFFFFFF,
SamplerType2d samplerType = SamplerType2d::CLAMP
);
SamplerState &getSamplerState(SamplerType2d type) const;
struct Impl;
std::unique_ptr<Impl> mImpl;
};
}
| {
"alphanum_fraction": 0.7152485257,
"avg_line_length": 21.9814814815,
"ext": "h",
"hexsha": "a9dd6c216afbc0f13f58082ee2b1fe9699ba7af3",
"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": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "edoipi/TemplePlus",
"max_forks_repo_path": "Infrastructure/include/graphics/shaperenderer2d.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"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": "edoipi/TemplePlus",
"max_issues_repo_path": "Infrastructure/include/graphics/shaperenderer2d.h",
"max_line_length": 169,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "edoipi/TemplePlus",
"max_stars_repo_path": "Infrastructure/include/graphics/shaperenderer2d.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 682,
"size": 2374
} |
#ifndef _UTIL_H
#define _UTIL_H
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <chrono>
#include <string>
#include <random>
#include <algorithm>
#include <mutex>
#include <atomic>
#include <tbb/pipeline.h>
#include "blocks.pb.h"
#ifdef __APPLE__
extern "C"
{
#include <cblas.h>
}
extern "C"
{
void cblas_saxpy(const int N, const float alpha, const float *X,
const int incX, float *Y, const int incY);
void cblas_scopy(const int N, const float *X, const int incX,
float *Y, const int incY);
float cblas_sdot(const int N, const float *X, const int incX,
const float *Y, const int incY);
}
#else
#include "mkl.h"
#endif
typedef unsigned long long uint64;
typedef unsigned int uint32;
typedef std::chrono::high_resolution_clock Time;
#ifdef LEVEL1_DCACHE_LINESIZE
#define CACHE_LINE_SIZE LEVEL1_DCACHE_LINESIZE
#else
#define CACHE_LINE_SIZE 64
#endif
typedef struct {
int u_, v_;
float r_;
} Record;
extern std::chrono::time_point<Time> s,e;
extern std::default_random_engine generator;
extern std::normal_distribution<float> gaussian;
#ifdef FETCH
inline void prefetch_range(char *addr, size_t len) {
char *cp;
char *end = addr + len;
for (cp = addr; cp < end; cp += CACHE_LINE_SIZE)
__builtin_prefetch(cp,1,0);
}
#endif
inline void align_alloc(float** u, int nu, int dim) {
int piece = nu/1050000+1;
int nn = nu/piece;
int k;
for(k=0; k<piece-1; k++) {
u[k*nn] = (float*)mkl_malloc(nn*dim*sizeof(float), CACHE_LINE_SIZE);
for(int i=1; i<nn; i++)
u[k*nn+i] = u[k*nn+i-1] + dim;
}
u[k*nn] = (float*)mkl_malloc((nn+nu%piece)*dim*sizeof(float), CACHE_LINE_SIZE);
for(int i=1; i<nn+nu%piece; i++)
u[k*nn+i] = u[k*nn+i-1] + dim;
}
inline void plain_read(const char* data, mf::Blocks& blocks) {
FILE* fr = fopen(data, "rb");
std::vector<char> buf;
uint32 isize;
mf::Block* bk;
while(fread(&isize, 1, sizeof(isize), fr)) {
buf.resize(isize);
fread((char*)buf.data(), 1, isize, fr);
bk = blocks.add_block();
bk->ParseFromArray(buf.data(), isize);
}
fclose(fr);
}
inline float active(float val, int type) {
switch(type) {
case 0: return val; //least square
case 1: return 1.0f/(1.0f+expf(-val)); //sigmoid
}
}
inline float cal_grad(float r, float pred, int type) {
switch(type) {
case 0: return r - pred; //least square
case 1: return r - pred; //0-1 logistic regression
}
}
inline float next_float(){
return static_cast<float>( rand() ) / (static_cast<float>( RAND_MAX )+1.0);
}
inline float next_float2(){
return (static_cast<float>( rand() ) + 1.0 ) / (static_cast<float>(RAND_MAX) + 2.0);
}
inline float normsqr(float* x, int num) {
return cblas_sdot(num, x, 1, x, 1);
}
inline float sample_normal(){
float x,y,s;
do{
x = 2 * next_float2() - 1.0;
y = 2 * next_float2() - 1.0;
s = x*x + y*y;
}while( s >= 1.0 || s == 0.0 );
return x * sqrt( -2.0 * log(s) / s ) ;
}
inline float sample_gamma( float alpha, float beta ) {
if ( alpha < 1.0 ) {
float u;
do {
u = next_float();
} while (u == 0.0);
return sample_gamma(alpha + 1.0, beta) * pow(u, 1.0 / alpha);
} else {
float d,c,x,v,u;
d = alpha - 1.0/3.0;
c = 1.0 / sqrt( 9.0 * d );
do {
do {
x = sample_normal();
v = 1.0 + c*x;
} while ( v <= 0.0 );
v = v * v * v;
u = next_float();
} while ( (u >= (1.0 - 0.0331 * (x*x) * (x*x)))
&& (log(u) >= (0.5 * x * x + d * (1.0 - v + log(v)))) );
return d * v / beta;
}
}
inline void gamma_posterior( float &lambda, float prior_alpha, float prior_beta, float psum_sqr, float psum_cnt ){
float alpha = prior_alpha + 0.5*psum_cnt;
float beta = prior_beta + 0.5*psum_sqr;
lambda = sample_gamma( alpha, beta );
}
inline void normsqr_col(float** m, int d, int size, float* norm) {
#pragma omp parallel for
for(int i=0; i<d; i++) {
for(int j=0; j<size; j++) norm[i] += m[j][i]*m[j][i];
}
}
inline int padding(int dim) {
return ((dim*sizeof(float)-1)/CACHE_LINE_SIZE*CACHE_LINE_SIZE+CACHE_LINE_SIZE)/sizeof(float);
}
#endif
| {
"alphanum_fraction": 0.5872506306,
"avg_line_length": 25.9583333333,
"ext": "h",
"hexsha": "a81e2225424a53bb8012f6620f12e668c2745e96",
"lang": "C",
"max_forks_count": 37,
"max_forks_repo_forks_event_max_datetime": "2021-12-09T20:00:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-06-18T03:09:47.000Z",
"max_forks_repo_head_hexsha": "1d344da213dd11c43b95394f1420262ec828a022",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "dmlc/mf",
"max_forks_repo_path": "src/util.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "1d344da213dd11c43b95394f1420262ec828a022",
"max_issues_repo_issues_event_max_datetime": "2016-04-02T16:50:54.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-02T15:47:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "dmlc/mf",
"max_issues_repo_path": "src/util.h",
"max_line_length": 114,
"max_stars_count": 96,
"max_stars_repo_head_hexsha": "1d344da213dd11c43b95394f1420262ec828a022",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "dmlc/mf",
"max_stars_repo_path": "src/util.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-09T20:00:44.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-31T14:06:44.000Z",
"num_tokens": 1355,
"size": 4361
} |
#include <stdio.h>
#include <gsl/gsl_ieee_utils.h>
int
main (void)
{
float f = 1.0/3.0;
double d = 1.0/3.0;
double fd = f; /* promote from float to double */
printf (" f="); gsl_ieee_printf_float(&f);
printf ("\n");
printf ("fd="); gsl_ieee_printf_double(&fd);
printf ("\n");
printf (" d="); gsl_ieee_printf_double(&d);
printf ("\n");
return 0;
}
| {
"alphanum_fraction": 0.5857519789,
"avg_line_length": 16.4782608696,
"ext": "c",
"hexsha": "c7f111092bfe4e5c1942fd7f1e3ebb444a39a428",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/ieee.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/ieee.c",
"max_line_length": 51,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/doc/examples/ieee.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": 130,
"size": 379
} |
#ifndef libceed_petsc_examples_setup_h
#define libceed_petsc_examples_setup_h
#include <ceed.h>
#include <petsc.h>
#include "structs.h"
PetscErrorCode CeedDataDestroy(CeedInt i, CeedData data);
PetscErrorCode SetupLibceedByDegree(DM dm, Ceed ceed, CeedInt degree,
CeedInt topo_dim, CeedInt q_extra,
PetscInt num_comp_x, PetscInt num_comp_u,
PetscInt g_size, PetscInt xl_size,
BPData bp_data, CeedData data,
PetscBool setup_rhs, CeedVector rhs_ceed,
CeedVector *target);
PetscErrorCode CeedLevelTransferSetup(Ceed ceed, CeedInt num_levels,
CeedInt num_comp_u, CeedData *data, CeedInt *leveldegrees,
CeedQFunction qf_restrict, CeedQFunction qf_prolong);
#endif // libceed_petsc_examples_setup_h
| {
"alphanum_fraction": 0.5884732053,
"avg_line_length": 44.9545454545,
"ext": "h",
"hexsha": "4ba8ac4f3c28642a9a7c1cef75c8584c6b6be07e",
"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": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "wence-/libCEED",
"max_forks_repo_path": "examples/petsc/include/libceedsetup.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"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": "wence-/libCEED",
"max_issues_repo_path": "examples/petsc/include/libceedsetup.h",
"max_line_length": 96,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c785ad36304ed34c5edefb75cf1a0fe5445db17b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "wence-/libCEED",
"max_stars_repo_path": "examples/petsc/include/libceedsetup.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 214,
"size": 989
} |
/*
* Copyright (c) 1997-1999 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/* This file was automatically generated --- DO NOT EDIT */
/* Generated on Sun Nov 7 20:44:49 EST 1999 */
#include <fftw-int.h>
#include <fftw.h>
/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2hc-forward 10 */
/*
* This function contains 168 FP additions, 84 FP multiplications,
* (or, 126 additions, 42 multiplications, 42 fused multiply/add),
* 43 stack variables, and 80 memory accesses
*/
static const fftw_real K587785252 = FFTW_KONST(+0.587785252292473129168705954639072768597652438);
static const fftw_real K951056516 = FFTW_KONST(+0.951056516295153572116439333379382143405698634);
static const fftw_real K250000000 = FFTW_KONST(+0.250000000000000000000000000000000000000000000);
static const fftw_real K559016994 = FFTW_KONST(+0.559016994374947424102293417182819058860154590);
/*
* Generator Id's :
* $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $
* $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $
* $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $
*/
void fftw_hc2hc_forward_10(fftw_real *A, const fftw_complex *W, int iostride, int m, int dist)
{
int i;
fftw_real *X;
fftw_real *Y;
X = A;
Y = A + (10 * iostride);
{
fftw_real tmp170;
fftw_real tmp181;
fftw_real tmp162;
fftw_real tmp175;
fftw_real tmp165;
fftw_real tmp176;
fftw_real tmp166;
fftw_real tmp183;
fftw_real tmp155;
fftw_real tmp178;
fftw_real tmp158;
fftw_real tmp179;
fftw_real tmp159;
fftw_real tmp182;
fftw_real tmp168;
fftw_real tmp169;
ASSERT_ALIGNED_DOUBLE;
tmp168 = X[0];
tmp169 = X[5 * iostride];
tmp170 = tmp168 - tmp169;
tmp181 = tmp168 + tmp169;
{
fftw_real tmp160;
fftw_real tmp161;
fftw_real tmp163;
fftw_real tmp164;
ASSERT_ALIGNED_DOUBLE;
tmp160 = X[4 * iostride];
tmp161 = X[9 * iostride];
tmp162 = tmp160 - tmp161;
tmp175 = tmp160 + tmp161;
tmp163 = X[6 * iostride];
tmp164 = X[iostride];
tmp165 = tmp163 - tmp164;
tmp176 = tmp163 + tmp164;
}
tmp166 = tmp162 + tmp165;
tmp183 = tmp175 + tmp176;
{
fftw_real tmp153;
fftw_real tmp154;
fftw_real tmp156;
fftw_real tmp157;
ASSERT_ALIGNED_DOUBLE;
tmp153 = X[2 * iostride];
tmp154 = X[7 * iostride];
tmp155 = tmp153 - tmp154;
tmp178 = tmp153 + tmp154;
tmp156 = X[8 * iostride];
tmp157 = X[3 * iostride];
tmp158 = tmp156 - tmp157;
tmp179 = tmp156 + tmp157;
}
tmp159 = tmp155 + tmp158;
tmp182 = tmp178 + tmp179;
{
fftw_real tmp167;
fftw_real tmp171;
fftw_real tmp172;
fftw_real tmp186;
fftw_real tmp184;
fftw_real tmp185;
ASSERT_ALIGNED_DOUBLE;
tmp167 = K559016994 * (tmp159 - tmp166);
tmp171 = tmp159 + tmp166;
tmp172 = tmp170 - (K250000000 * tmp171);
X[iostride] = tmp167 + tmp172;
X[3 * iostride] = tmp172 - tmp167;
X[5 * iostride] = tmp170 + tmp171;
tmp186 = K559016994 * (tmp182 - tmp183);
tmp184 = tmp182 + tmp183;
tmp185 = tmp181 - (K250000000 * tmp184);
X[2 * iostride] = tmp185 - tmp186;
X[4 * iostride] = tmp186 + tmp185;
X[0] = tmp181 + tmp184;
}
{
fftw_real tmp173;
fftw_real tmp174;
fftw_real tmp177;
fftw_real tmp180;
ASSERT_ALIGNED_DOUBLE;
tmp173 = tmp155 - tmp158;
tmp174 = tmp162 - tmp165;
Y[-iostride] = -((K951056516 * tmp173) + (K587785252 * tmp174));
Y[-3 * iostride] = (K587785252 * tmp173) - (K951056516 * tmp174);
tmp177 = tmp175 - tmp176;
tmp180 = tmp178 - tmp179;
Y[-2 * iostride] = (K951056516 * tmp177) - (K587785252 * tmp180);
Y[-4 * iostride] = (K951056516 * tmp180) + (K587785252 * tmp177);
}
}
X = X + dist;
Y = Y - dist;
for (i = 2; i < m; i = i + 2, X = X + dist, Y = Y - dist, W = W + 9) {
fftw_real tmp39;
fftw_real tmp87;
fftw_real tmp132;
fftw_real tmp144;
fftw_real tmp73;
fftw_real tmp84;
fftw_real tmp85;
fftw_real tmp91;
fftw_real tmp92;
fftw_real tmp93;
fftw_real tmp100;
fftw_real tmp103;
fftw_real tmp128;
fftw_real tmp121;
fftw_real tmp122;
fftw_real tmp142;
fftw_real tmp50;
fftw_real tmp61;
fftw_real tmp62;
fftw_real tmp88;
fftw_real tmp89;
fftw_real tmp90;
fftw_real tmp107;
fftw_real tmp110;
fftw_real tmp127;
fftw_real tmp118;
fftw_real tmp119;
fftw_real tmp141;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp33;
fftw_real tmp131;
fftw_real tmp38;
fftw_real tmp130;
ASSERT_ALIGNED_DOUBLE;
tmp33 = X[0];
tmp131 = Y[-9 * iostride];
{
fftw_real tmp35;
fftw_real tmp37;
fftw_real tmp34;
fftw_real tmp36;
ASSERT_ALIGNED_DOUBLE;
tmp35 = X[5 * iostride];
tmp37 = Y[-4 * iostride];
tmp34 = c_re(W[4]);
tmp36 = c_im(W[4]);
tmp38 = (tmp34 * tmp35) - (tmp36 * tmp37);
tmp130 = (tmp36 * tmp35) + (tmp34 * tmp37);
}
tmp39 = tmp33 - tmp38;
tmp87 = tmp33 + tmp38;
tmp132 = tmp130 + tmp131;
tmp144 = tmp131 - tmp130;
}
{
fftw_real tmp67;
fftw_real tmp98;
fftw_real tmp83;
fftw_real tmp102;
fftw_real tmp72;
fftw_real tmp99;
fftw_real tmp78;
fftw_real tmp101;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp64;
fftw_real tmp66;
fftw_real tmp63;
fftw_real tmp65;
ASSERT_ALIGNED_DOUBLE;
tmp64 = X[4 * iostride];
tmp66 = Y[-5 * iostride];
tmp63 = c_re(W[3]);
tmp65 = c_im(W[3]);
tmp67 = (tmp63 * tmp64) - (tmp65 * tmp66);
tmp98 = (tmp65 * tmp64) + (tmp63 * tmp66);
}
{
fftw_real tmp80;
fftw_real tmp82;
fftw_real tmp79;
fftw_real tmp81;
ASSERT_ALIGNED_DOUBLE;
tmp80 = X[iostride];
tmp82 = Y[-8 * iostride];
tmp79 = c_re(W[0]);
tmp81 = c_im(W[0]);
tmp83 = (tmp79 * tmp80) - (tmp81 * tmp82);
tmp102 = (tmp81 * tmp80) + (tmp79 * tmp82);
}
{
fftw_real tmp69;
fftw_real tmp71;
fftw_real tmp68;
fftw_real tmp70;
ASSERT_ALIGNED_DOUBLE;
tmp69 = X[9 * iostride];
tmp71 = Y[0];
tmp68 = c_re(W[8]);
tmp70 = c_im(W[8]);
tmp72 = (tmp68 * tmp69) - (tmp70 * tmp71);
tmp99 = (tmp70 * tmp69) + (tmp68 * tmp71);
}
{
fftw_real tmp75;
fftw_real tmp77;
fftw_real tmp74;
fftw_real tmp76;
ASSERT_ALIGNED_DOUBLE;
tmp75 = X[6 * iostride];
tmp77 = Y[-3 * iostride];
tmp74 = c_re(W[5]);
tmp76 = c_im(W[5]);
tmp78 = (tmp74 * tmp75) - (tmp76 * tmp77);
tmp101 = (tmp76 * tmp75) + (tmp74 * tmp77);
}
tmp73 = tmp67 - tmp72;
tmp84 = tmp78 - tmp83;
tmp85 = tmp73 + tmp84;
tmp91 = tmp67 + tmp72;
tmp92 = tmp78 + tmp83;
tmp93 = tmp91 + tmp92;
tmp100 = tmp98 + tmp99;
tmp103 = tmp101 + tmp102;
tmp128 = tmp100 + tmp103;
tmp121 = tmp98 - tmp99;
tmp122 = tmp101 - tmp102;
tmp142 = tmp121 + tmp122;
}
{
fftw_real tmp44;
fftw_real tmp105;
fftw_real tmp60;
fftw_real tmp109;
fftw_real tmp49;
fftw_real tmp106;
fftw_real tmp55;
fftw_real tmp108;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp41;
fftw_real tmp43;
fftw_real tmp40;
fftw_real tmp42;
ASSERT_ALIGNED_DOUBLE;
tmp41 = X[2 * iostride];
tmp43 = Y[-7 * iostride];
tmp40 = c_re(W[1]);
tmp42 = c_im(W[1]);
tmp44 = (tmp40 * tmp41) - (tmp42 * tmp43);
tmp105 = (tmp42 * tmp41) + (tmp40 * tmp43);
}
{
fftw_real tmp57;
fftw_real tmp59;
fftw_real tmp56;
fftw_real tmp58;
ASSERT_ALIGNED_DOUBLE;
tmp57 = X[3 * iostride];
tmp59 = Y[-6 * iostride];
tmp56 = c_re(W[2]);
tmp58 = c_im(W[2]);
tmp60 = (tmp56 * tmp57) - (tmp58 * tmp59);
tmp109 = (tmp58 * tmp57) + (tmp56 * tmp59);
}
{
fftw_real tmp46;
fftw_real tmp48;
fftw_real tmp45;
fftw_real tmp47;
ASSERT_ALIGNED_DOUBLE;
tmp46 = X[7 * iostride];
tmp48 = Y[-2 * iostride];
tmp45 = c_re(W[6]);
tmp47 = c_im(W[6]);
tmp49 = (tmp45 * tmp46) - (tmp47 * tmp48);
tmp106 = (tmp47 * tmp46) + (tmp45 * tmp48);
}
{
fftw_real tmp52;
fftw_real tmp54;
fftw_real tmp51;
fftw_real tmp53;
ASSERT_ALIGNED_DOUBLE;
tmp52 = X[8 * iostride];
tmp54 = Y[-iostride];
tmp51 = c_re(W[7]);
tmp53 = c_im(W[7]);
tmp55 = (tmp51 * tmp52) - (tmp53 * tmp54);
tmp108 = (tmp53 * tmp52) + (tmp51 * tmp54);
}
tmp50 = tmp44 - tmp49;
tmp61 = tmp55 - tmp60;
tmp62 = tmp50 + tmp61;
tmp88 = tmp44 + tmp49;
tmp89 = tmp55 + tmp60;
tmp90 = tmp88 + tmp89;
tmp107 = tmp105 + tmp106;
tmp110 = tmp108 + tmp109;
tmp127 = tmp107 + tmp110;
tmp118 = tmp105 - tmp106;
tmp119 = tmp108 - tmp109;
tmp141 = tmp118 + tmp119;
}
{
fftw_real tmp115;
fftw_real tmp86;
fftw_real tmp116;
fftw_real tmp124;
fftw_real tmp126;
fftw_real tmp120;
fftw_real tmp123;
fftw_real tmp125;
fftw_real tmp117;
ASSERT_ALIGNED_DOUBLE;
tmp115 = K559016994 * (tmp62 - tmp85);
tmp86 = tmp62 + tmp85;
tmp116 = tmp39 - (K250000000 * tmp86);
tmp120 = tmp118 - tmp119;
tmp123 = tmp121 - tmp122;
tmp124 = (K951056516 * tmp120) + (K587785252 * tmp123);
tmp126 = (K951056516 * tmp123) - (K587785252 * tmp120);
Y[-5 * iostride] = tmp39 + tmp86;
tmp125 = tmp116 - tmp115;
Y[-7 * iostride] = tmp125 - tmp126;
X[3 * iostride] = tmp125 + tmp126;
tmp117 = tmp115 + tmp116;
Y[-9 * iostride] = tmp117 - tmp124;
X[iostride] = tmp117 + tmp124;
}
{
fftw_real tmp148;
fftw_real tmp143;
fftw_real tmp149;
fftw_real tmp147;
fftw_real tmp151;
fftw_real tmp145;
fftw_real tmp146;
fftw_real tmp152;
fftw_real tmp150;
ASSERT_ALIGNED_DOUBLE;
tmp148 = K559016994 * (tmp141 - tmp142);
tmp143 = tmp141 + tmp142;
tmp149 = tmp144 - (K250000000 * tmp143);
tmp145 = tmp50 - tmp61;
tmp146 = tmp73 - tmp84;
tmp147 = (K951056516 * tmp145) + (K587785252 * tmp146);
tmp151 = (K587785252 * tmp145) - (K951056516 * tmp146);
X[5 * iostride] = -(tmp143 + tmp144);
tmp152 = tmp149 - tmp148;
X[7 * iostride] = tmp151 - tmp152;
Y[-3 * iostride] = tmp151 + tmp152;
tmp150 = tmp148 + tmp149;
X[9 * iostride] = -(tmp147 + tmp150);
Y[-iostride] = tmp150 - tmp147;
}
{
fftw_real tmp96;
fftw_real tmp94;
fftw_real tmp95;
fftw_real tmp112;
fftw_real tmp114;
fftw_real tmp104;
fftw_real tmp111;
fftw_real tmp113;
fftw_real tmp97;
ASSERT_ALIGNED_DOUBLE;
tmp96 = K559016994 * (tmp90 - tmp93);
tmp94 = tmp90 + tmp93;
tmp95 = tmp87 - (K250000000 * tmp94);
tmp104 = tmp100 - tmp103;
tmp111 = tmp107 - tmp110;
tmp112 = (K951056516 * tmp104) - (K587785252 * tmp111);
tmp114 = (K951056516 * tmp111) + (K587785252 * tmp104);
X[0] = tmp87 + tmp94;
tmp113 = tmp96 + tmp95;
X[4 * iostride] = tmp113 - tmp114;
Y[-6 * iostride] = tmp113 + tmp114;
tmp97 = tmp95 - tmp96;
X[2 * iostride] = tmp97 - tmp112;
Y[-8 * iostride] = tmp97 + tmp112;
}
{
fftw_real tmp134;
fftw_real tmp129;
fftw_real tmp133;
fftw_real tmp138;
fftw_real tmp140;
fftw_real tmp136;
fftw_real tmp137;
fftw_real tmp139;
fftw_real tmp135;
ASSERT_ALIGNED_DOUBLE;
tmp134 = K559016994 * (tmp127 - tmp128);
tmp129 = tmp127 + tmp128;
tmp133 = tmp132 - (K250000000 * tmp129);
tmp136 = tmp91 - tmp92;
tmp137 = tmp88 - tmp89;
tmp138 = (K951056516 * tmp136) - (K587785252 * tmp137);
tmp140 = (K951056516 * tmp137) + (K587785252 * tmp136);
Y[0] = tmp129 + tmp132;
tmp139 = tmp134 + tmp133;
X[6 * iostride] = -(tmp139 - tmp140);
Y[-4 * iostride] = tmp140 + tmp139;
tmp135 = tmp133 - tmp134;
X[8 * iostride] = -(tmp135 - tmp138);
Y[-2 * iostride] = tmp138 + tmp135;
}
}
if (i == m) {
fftw_real tmp1;
fftw_real tmp24;
fftw_real tmp8;
fftw_real tmp10;
fftw_real tmp25;
fftw_real tmp26;
fftw_real tmp14;
fftw_real tmp28;
fftw_real tmp23;
fftw_real tmp17;
ASSERT_ALIGNED_DOUBLE;
tmp1 = X[0];
tmp24 = X[5 * iostride];
{
fftw_real tmp2;
fftw_real tmp3;
fftw_real tmp4;
fftw_real tmp5;
fftw_real tmp6;
fftw_real tmp7;
ASSERT_ALIGNED_DOUBLE;
tmp2 = X[4 * iostride];
tmp3 = X[6 * iostride];
tmp4 = tmp2 - tmp3;
tmp5 = X[8 * iostride];
tmp6 = X[2 * iostride];
tmp7 = tmp5 - tmp6;
tmp8 = tmp4 + tmp7;
tmp10 = K559016994 * (tmp4 - tmp7);
tmp25 = tmp2 + tmp3;
tmp26 = tmp5 + tmp6;
}
{
fftw_real tmp12;
fftw_real tmp13;
fftw_real tmp22;
fftw_real tmp15;
fftw_real tmp16;
fftw_real tmp21;
ASSERT_ALIGNED_DOUBLE;
tmp12 = X[iostride];
tmp13 = X[9 * iostride];
tmp22 = tmp12 + tmp13;
tmp15 = X[3 * iostride];
tmp16 = X[7 * iostride];
tmp21 = tmp15 + tmp16;
tmp14 = tmp12 - tmp13;
tmp28 = K559016994 * (tmp22 + tmp21);
tmp23 = tmp21 - tmp22;
tmp17 = tmp15 - tmp16;
}
X[2 * iostride] = tmp1 + tmp8;
{
fftw_real tmp18;
fftw_real tmp20;
fftw_real tmp11;
fftw_real tmp19;
fftw_real tmp9;
ASSERT_ALIGNED_DOUBLE;
tmp18 = (K587785252 * tmp14) - (K951056516 * tmp17);
tmp20 = (K951056516 * tmp14) + (K587785252 * tmp17);
tmp9 = tmp1 - (K250000000 * tmp8);
tmp11 = tmp9 - tmp10;
tmp19 = tmp10 + tmp9;
X[3 * iostride] = tmp11 - tmp18;
X[iostride] = tmp11 + tmp18;
X[4 * iostride] = tmp19 - tmp20;
X[0] = tmp19 + tmp20;
}
Y[-2 * iostride] = tmp23 - tmp24;
{
fftw_real tmp27;
fftw_real tmp32;
fftw_real tmp30;
fftw_real tmp31;
fftw_real tmp29;
ASSERT_ALIGNED_DOUBLE;
tmp27 = (K951056516 * tmp25) + (K587785252 * tmp26);
tmp32 = (K951056516 * tmp26) - (K587785252 * tmp25);
tmp29 = (K250000000 * tmp23) + tmp24;
tmp30 = tmp28 + tmp29;
tmp31 = tmp29 - tmp28;
Y[0] = -(tmp27 + tmp30);
Y[-4 * iostride] = tmp27 - tmp30;
Y[-iostride] = tmp31 - tmp32;
Y[-3 * iostride] = tmp32 + tmp31;
}
}
}
static const int twiddle_order[] =
{1, 2, 3, 4, 5, 6, 7, 8, 9};
fftw_codelet_desc fftw_hc2hc_forward_10_desc =
{
"fftw_hc2hc_forward_10",
(void (*)()) fftw_hc2hc_forward_10,
10,
FFTW_FORWARD,
FFTW_HC2HC,
223,
9,
twiddle_order,
};
| {
"alphanum_fraction": 0.5634144861,
"avg_line_length": 29.3078291815,
"ext": "c",
"hexsha": "19640e2b30a29081a6ec2f66fe2f4c509c176068",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z",
"max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "albertsgrc/ftdock-opt",
"max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_10.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"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": "albertsgrc/ftdock-opt",
"max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_10.c",
"max_line_length": 125,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "albertsgrc/ftdock-opt",
"max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_10.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z",
"num_tokens": 5274,
"size": 16471
} |
#ifndef __REGIONAL_H_
#define __REGIONAL_H_
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
typedef struct stochasticity_grid {
double *arr;
int height, width;
double weight_factor;
double stddev;
double mean;
int depth;
gsl_rng *rng;
double *weights;
} t_stochasticity_grid;
t_stochasticity_grid *create_stochasticity_grid(double *arr, int height, int width, double weight_factor, double mean, double stddev, long int seed);
void free_stochasticity_grid(t_stochasticity_grid *g);
void generate_stochasticity(t_stochasticity_grid *g);
#endif /* __REGIONAL_H_ */
| {
"alphanum_fraction": 0.7348242812,
"avg_line_length": 27.2173913043,
"ext": "h",
"hexsha": "9af76bfca13b673b28d73fa78c13f7b93fa6b798",
"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": "77b6e1abf72421d6268f5aa865559b134965d070",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "rybicki/corridor-spom",
"max_forks_repo_path": "passive/spom/model/src/regional.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "77b6e1abf72421d6268f5aa865559b134965d070",
"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": "rybicki/corridor-spom",
"max_issues_repo_path": "passive/spom/model/src/regional.h",
"max_line_length": 150,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "77b6e1abf72421d6268f5aa865559b134965d070",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "rybicki/corridor-spom",
"max_stars_repo_path": "passive/spom/model/src/regional.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 153,
"size": 626
} |
/**
*
* @file qwrapper_cgemv.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mark Gates
* @author Mathieu Faverge
* @date 2010-11-15
* @generated c Tue Jan 7 11:44:59 2014
*
**/
#include <cblas.h>
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_cgemv(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum trans, int m, int n,
PLASMA_Complex32_t alpha, const PLASMA_Complex32_t *A, int lda,
const PLASMA_Complex32_t *x, int incx,
PLASMA_Complex32_t beta, PLASMA_Complex32_t *y, int incy)
{
DAG_CORE_GEMV;
QUARK_Insert_Task(quark, CORE_cgemv_quark, task_flags,
sizeof(PLASMA_enum), &trans, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex32_t), &alpha, VALUE,
sizeof(PLASMA_Complex32_t)*m*n, A, INPUT,
sizeof(int), &lda, VALUE,
sizeof(PLASMA_Complex32_t)*n, x, INPUT,
sizeof(int), &incx, VALUE,
sizeof(PLASMA_Complex32_t), &beta, VALUE,
sizeof(PLASMA_Complex32_t)*m, y, INOUT,
sizeof(int), &incy, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_cgemv_quark = PCORE_cgemv_quark
#define CORE_cgemv_quark PCORE_cgemv_quark
#endif
void CORE_cgemv_quark(Quark *quark)
{
PLASMA_enum trans;
int m, n, lda, incx, incy;
PLASMA_Complex32_t alpha, beta;
const PLASMA_Complex32_t *A, *x;
PLASMA_Complex32_t *y;
quark_unpack_args_11( quark, trans, m, n, alpha, A, lda, x, incx, beta, y, incy );
cblas_cgemv(
CblasColMajor,
(CBLAS_TRANSPOSE)trans,
m, n,
CBLAS_SADDR(alpha), A, lda,
x, incx,
CBLAS_SADDR(beta), y, incy);
}
| {
"alphanum_fraction": 0.5189873418,
"avg_line_length": 33.6911764706,
"ext": "c",
"hexsha": "c47cf35dbedca8bf97e66c256d7c4ee69c156101",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas-qwrapper/qwrapper_cgemv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_cgemv.c",
"max_line_length": 86,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas-qwrapper/qwrapper_cgemv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 646,
"size": 2291
} |
#ifndef __GSLSTREAM_H__
#define __GSLSTREAM_H__
#include "RngStream.h"
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
namespace rng {
class GSLStream : public RngStream {
public:
GSLStream() : type(gsl_rng_taus2) {}
virtual ~GSLStream() { free(); }
inline void alloc(unsigned long seed = time(NULL)) {
if (! is_alloc) {
rng = gsl_rng_alloc(type);
is_alloc = 1;
gsl_rng_set(rng,seed);
}
}
inline void free() {
if (is_alloc) {
gsl_rng_free(rng);
is_alloc = 0;
}
}
inline void uniform(size_t n, double* r, double a = 0.0, double b = 1.0) {
for (size_t i = 0; i < n; ++i) {
r[i] = a + (b-a)*gsl_rng_uniform(rng);
}
}
inline void uniform_int(size_t n, int* r, int a = 0, int b = 10) {
for (size_t i = 0; i < n; ++i) {
r[i] = a + gsl_rng_uniform_int(rng,b-a);
}
}
inline void shuffle(int* x, size_t n) { gsl_ran_shuffle(rng,x,n,sizeof(int)); }
inline void shuffle(double* x, size_t n) { gsl_ran_shuffle(rng,x,n,sizeof(double)); }
inline void multinomial(size_t k, size_t n, const double* p, unsigned* a) {
gsl_ran_multinomial(rng,k,n,p,a);
}
inline void gaussian(size_t n, double* r, double mu = 0.0, double sigma = 1.0) {
*r = gsl_ran_gaussian(rng,sigma) + mu;
};
inline void poisson(size_t n, int* k, double lambda) {
*k = gsl_ran_poisson(rng,lambda);
}
protected:
const gsl_rng_type* type;
gsl_rng* rng;
};
}
#endif
| {
"alphanum_fraction": 0.5541871921,
"avg_line_length": 25.375,
"ext": "h",
"hexsha": "25afb2ede268b6fe449ad3dbb9f5b5f86d6e37a6",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "52846467f9ae91f7c31a8983b913cf722de93218",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gaberoo/cdream",
"max_forks_repo_path": "include/rng/GSLStream.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "52846467f9ae91f7c31a8983b913cf722de93218",
"max_issues_repo_issues_event_max_datetime": "2016-10-29T15:00:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-29T15:00:00.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gaberoo/cdream",
"max_issues_repo_path": "include/rng/GSLStream.h",
"max_line_length": 91,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "52846467f9ae91f7c31a8983b913cf722de93218",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gaberoo/cdream",
"max_stars_repo_path": "include/rng/GSLStream.h",
"max_stars_repo_stars_event_max_datetime": "2018-02-03T11:48:27.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-09-07T23:49:41.000Z",
"num_tokens": 477,
"size": 1624
} |
/*
findcluster_ternary_par.c
written by Eunseok Lee
function: find the most representative cluster function
v1: Feb 2, 2018
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/stat.h>
//#include <cem.h>
#include <mpi.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
void randperm(int*, int);
void load_double_mat(double*, int, int, int, char*);
void load_int_mat(int*, int, int, int, char*);
void load_double_array(double*, int, char*);
void load_int_array(int*, int, char*);
void load_double_value(int,char);
void load_int_value(int,char);
int mat_size_row(int*);
int find_value_in_array(int*,int,int,int);
void mat2d_prod(double*, int, int, double*, int, int, double*, int, int);
double obtainerr2_par(int,int,double*, int, int, int*, int, double*);
void least_square_solver(double*, int, int, double*, double*);
#define MASTER 0
#define FROM_MASTER 1
#define FROM_WORKER 2
int main(int argc, char **argv)
{
int n1, n2, n3;
int np, nfu;
double kv[3][3], pk[3][3], pp[8][3];
double *rp, *rpL, *rpN, *rpO;
int *map_to_cluster1, *map_to_cluster2, *map_to_cluster3;
int *nlist;
int neighbor_num;
int ncluster, ncluster2, ncluster3, ncorr_col;
int c2start, c3start;
int data;
double *E, *Ef;
int ndata;
int i, j, k, nj, nk, ctn;
int iter, max_iter;
double kT=0.0256; // Default value of kT
int howmanycluster;
int dispfreq;
char buff_line[200], dummy[200], param_name[100];
int param_name_len;
double cvs_tol = 0.01; // Default value of cvs_tol
int construct_corr_mat = 0; //Default value of construct_corr_mat
// mpi parameters and initialization
int numprocs, rank, mtype;
int row_dist_size;
int row_ini, row_end, row_offset;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs); // Get # processors
MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get my rank (id)
if (numprocs>1)
printf("Parallel computing: the input files are read by all nodes. Multiple messages are not due to error!\n",numprocs);
// Construct conrrelation matrix. It can also be loaded.
int n_corr_mat_ug_row;
int n_non_singular_col;
FILE *fp;
char dirname[100]="dir_inputs";
char paramfilename[100];
sprintf(paramfilename,"%s/param.dat",dirname);
char corr_mat_ugs_filename[200];
fp = fopen(paramfilename, "r");
while(fgets(buff_line,sizeof(buff_line),fp) != NULL) {
if (buff_line[0] == '#') {
// printf("Comment line: %s",buff_line);
continue;
}
strcpy(param_name,"corr_mat_ugs_filename");
param_name_len = strlen(param_name);
strncpy(dummy,buff_line,param_name_len);
dummy[param_name_len] = '\0';
if (strcmp(dummy,param_name)==0) {
sscanf(buff_line,"%s %s",dummy,corr_mat_ugs_filename);
if (rank == MASTER)
printf("corr_mat_ugs_filename = %s\n",corr_mat_ugs_filename);
}
strcpy(param_name,"n_corr_mat_ug_row");
param_name_len = strlen(param_name);
strncpy(dummy,buff_line,param_name_len);
dummy[param_name_len] = '\0';
if (strcmp(dummy,param_name)==0) {
sscanf(buff_line,"%s %d",dummy,&n_corr_mat_ug_row);
if (rank == MASTER)
printf("n_corr_mat_ug_row = %d\n",n_corr_mat_ug_row);
}
strcpy(param_name,"n_non_singular_col");
param_name_len = strlen(param_name);
strncpy(dummy,buff_line,param_name_len);
dummy[param_name_len] = '\0';
if (strcmp(dummy,param_name)==0) {
sscanf(buff_line,"%s %d",dummy,&n_non_singular_col);
if (rank == MASTER)
printf("n_non_singular_col = %d\n",n_non_singular_col);
}
strcpy(param_name,"howmanycluster");
param_name_len = strlen(param_name);
strncpy(dummy,buff_line,param_name_len);
dummy[param_name_len] = '\0';
if (strcmp(dummy,param_name)==0) {
sscanf(buff_line,"%s %d",dummy,&howmanycluster);
if (rank == MASTER)
printf("howmanycluster = %d\n",howmanycluster);
}
strcpy(param_name,"max_iter");
param_name_len = strlen(param_name);
strncpy(dummy,buff_line,param_name_len);
dummy[param_name_len] = '\0';
if (strcmp(dummy,param_name)==0) {
sscanf(buff_line,"%s %d",dummy,&max_iter);
if (rank == MASTER)
printf("max_iter = %d\n",max_iter);
}
strcpy(param_name,"kT");
param_name_len = strlen(param_name);
strncpy(dummy,buff_line,param_name_len);
dummy[param_name_len] = '\0';
if (strcmp(dummy,param_name)==0) {
sscanf(buff_line,"%s %lf",dummy,&kT);
if (rank == MASTER)
printf("kT = %f\n",kT);
}
strcpy(param_name,"cvs_tol");
param_name_len = strlen(param_name);
strncpy(dummy,buff_line,param_name_len);
dummy[param_name_len] = '\0';
if (strcmp(dummy,param_name)==0) {
sscanf(buff_line,"%s %lf",dummy,&cvs_tol);
if (rank == MASTER)
printf("cvs_tol = %f\n",cvs_tol);
}
strcpy(param_name,"dispfreq");
param_name_len = strlen(param_name);
strncpy(dummy,buff_line,param_name_len);
dummy[param_name_len] = '\0';
if (strcmp(dummy,param_name)==0) {
sscanf(buff_line,"%s %d",dummy,&dispfreq);
if (rank == MASTER)
printf("dispfreq = %d\n",dispfreq);
}
}
fclose(fp);
char loadfilename[100];
double *corr_mat_ugs;
corr_mat_ugs = (double*) malloc(n_corr_mat_ug_row*n_non_singular_col*sizeof(double));
sprintf(loadfilename,"%s/%s",dirname,corr_mat_ugs_filename);
load_double_mat(corr_mat_ugs,n_corr_mat_ug_row,n_non_singular_col,1,loadfilename);
int usefulcorr_col[n_non_singular_col];
sprintf(loadfilename,"%s/usefulcorr_col.dat",dirname);
load_int_array(usefulcorr_col,n_non_singular_col,loadfilename);
double Ef_ug[n_corr_mat_ug_row];
sprintf(loadfilename,"%s/Ef_ug.dat",dirname);
load_double_array(Ef_ug,n_corr_mat_ug_row,loadfilename);
/* int nC_ug[n_corr_mat_ug_row];
sprintf(loadfilename,"%s/nC_ug.dat",dirname);
load_int_array(nC_ug,n_corr_mat_ug_row,loadfilename);
*/
row_offset = (int) ceil(n_corr_mat_ug_row*1.0/numprocs);
if (numprocs>1 && rank==MASTER)
printf("Correlation Matrix is calculated over %d processors: row_offset = %d\n",numprocs,row_offset);
double err2_sum_from_master;
double err2_sum_from_worker;
int cluster_set1[howmanycluster];
/**** Start of MC simulation ****/
if (rank == MASTER) {
int cluster_set1_old[howmanycluster], cluster_set1_min[howmanycluster], cluster_set2[n_non_singular_col-howmanycluster];
double cvs, cvs_old, cvs_min;
int select1, select2, target, candidate;
for (i=0;i<howmanycluster;i++)
cluster_set1[i] = i;
for (i=0;i<n_non_singular_col-howmanycluster;i++)
cluster_set2[i] = i+howmanycluster;
mtype = FROM_MASTER;
for (i=1;i<numprocs;i++) {
MPI_Send(&cluster_set1, howmanycluster, MPI_INT, i, mtype, MPI_COMM_WORLD);
}
row_ini = rank * row_offset;
row_end = row_ini +row_offset;
err2_sum_from_master = obtainerr2_par(row_ini,row_end,corr_mat_ugs,n_corr_mat_ug_row,n_non_singular_col,cluster_set1,howmanycluster,Ef_ug);
// printf("initial err2 = %f\n",err2_sum_from_master);
for (i=1;i<numprocs;i++) {
mtype = FROM_WORKER;
MPI_Recv(&err2_sum_from_worker, 1, MPI_DOUBLE, i, mtype, MPI_COMM_WORLD, &status);
err2_sum_from_master += err2_sum_from_worker;
}
printf("initial err2 = %f\n",err2_sum_from_master);
cvs = sqrt(err2_sum_from_master/n_corr_mat_ug_row);
cvs_min = cvs;
for (i=0;i<howmanycluster;i++)
cluster_set1_min[i] = cluster_set1[i];
printf("initial cvs = %f\n",cvs);
for (iter=0;iter<max_iter;iter++) {
select1 = (int) floor(drand48()*howmanycluster);
select2 = (int) floor(drand48()*(n_non_singular_col-howmanycluster));
target = cluster_set1[select1];
candidate = cluster_set2[select2];
cvs_old = cvs;
cluster_set1[select1] = candidate;
mtype = FROM_MASTER;
for (i=1;i<numprocs;i++) {
MPI_Send(&cluster_set1, howmanycluster, MPI_INT, i, mtype, MPI_COMM_WORLD);
}
row_ini = rank * row_offset;
row_end = row_ini +row_offset;
err2_sum_from_master = obtainerr2_par(row_ini,row_end,corr_mat_ugs,n_corr_mat_ug_row,n_non_singular_col,cluster_set1,howmanycluster,Ef_ug);
for (i=1;i<numprocs;i++) {
mtype = FROM_WORKER;
MPI_Recv(&err2_sum_from_worker, 1, MPI_DOUBLE, i, mtype, MPI_COMM_WORLD, &status);
err2_sum_from_master += err2_sum_from_worker;
}
cvs = sqrt(err2_sum_from_master/n_corr_mat_ug_row);
if (cvs < cvs_old)
cluster_set2[select2] = target;
else if (exp(-(cvs-cvs_old)/kT) > drand48())
cluster_set2[select2] = target;
else {
cluster_set1[select1] = target;
cvs = cvs_old;
}
if (cvs < cvs_min) {
for (i=0;i<howmanycluster;i++)
cluster_set1_min[i] = cluster_set1[i];
cvs_min = cvs;
}
if (cvs < cvs_tol)
break;
if (iter%dispfreq==0)
printf("iter=%8d, cvs=%f, cvs_min=%f, cvs_min/fu=%f\n",iter,cvs,cvs_min,cvs_min/72);
}
// print the result
printf("End of MC iteration. The selected clusters are...\n");
printf("ID in non-singular | ID in entire\n");
for (i=0;i<howmanycluster;i++)
printf(" %4d %4d\n",cluster_set1_min[i],usefulcorr_col[cluster_set1_min[i]]);
double err_pred, rms;
double Ef_pred[n_corr_mat_ug_row];
double *corr_mat_ugs_reduced;
corr_mat_ugs_reduced = (double*) malloc(n_corr_mat_ug_row*howmanycluster*sizeof(double));
double eci[howmanycluster];
for (i=0;i<n_corr_mat_ug_row;i++) {
for (j=0;j<howmanycluster;j++)
*(corr_mat_ugs_reduced+howmanycluster*i+j) = *(corr_mat_ugs+n_non_singular_col*i+cluster_set1_min[j]);
}
least_square_solver(corr_mat_ugs_reduced,n_corr_mat_ug_row,howmanycluster,Ef_ug,eci);
mat2d_prod(Ef_pred,n_corr_mat_ug_row,1,corr_mat_ugs_reduced,n_corr_mat_ug_row,howmanycluster,eci,howmanycluster,1);
err_pred = 0.0;
for (i=0;i<n_corr_mat_ug_row;i++)
err_pred += (Ef_ug[i] - Ef_pred[i])*(Ef_ug[i] - Ef_pred[i]);
rms = sqrt(err_pred/n_corr_mat_ug_row);
// Write result into files
FILE *fp2, *fp3;
char cluster_set_filename[200];
char eci_filename[100];
strcpy(dirname,"dir_result");
struct stat st = {0};
if (stat(dirname, &st) == -1) {
mkdir(dirname,0777);
printf("Created a new directory for storing result.\n");
}
sprintf(cluster_set_filename, "%s/cluster_set_N%d.dat",dirname,howmanycluster);
sprintf(eci_filename,"%s/x.dat",dirname);
fp2 = fopen(cluster_set_filename,"w");
fp3 = fopen(eci_filename,"w");
for (i=0;i<howmanycluster;i++) {
fprintf(fp2,"%4d\t%4d\n",cluster_set1_min[i],usefulcorr_col[cluster_set1_min[i]]);
fprintf(fp3,"%.4f\n",eci[i]);
}
}
else {
for (iter=0;iter<(max_iter+1);iter++) {
mtype = FROM_MASTER;
MPI_Recv(&cluster_set1, howmanycluster, MPI_INT, MASTER, mtype, MPI_COMM_WORLD, &status);
row_ini = rank * row_offset;
row_end = row_ini + row_offset;
if (rank == numprocs-1)
row_end = n_corr_mat_ug_row; // last processor till the last row, -1 is taken inside obtainerr2_par
err2_sum_from_worker = obtainerr2_par(row_ini,row_end,corr_mat_ugs,n_corr_mat_ug_row,n_non_singular_col,cluster_set1,howmanycluster,Ef_ug);
mtype = FROM_WORKER;
MPI_Send(&err2_sum_from_worker, 1, MPI_DOUBLE, MASTER, mtype, MPI_COMM_WORLD);
}
}
MPI_Finalize();
}
void load_double_mat(double *A, int Arow, int Acol, int Apgs, char *datfilename) {
FILE *fp;
int i, j, k;
double tmp;
printf("filename: %s\n", datfilename);
fp = fopen(datfilename, "r");
for (k=0;k<Apgs;k++)
for (i=0;i<Arow;i++)
for (j=0;j<Acol;j++) {
fscanf(fp, "%lf", &tmp);
*(A+Arow*Acol*k+Acol*i+j) = tmp;
}
fclose(fp);
}
void load_int_mat(int *A, int Arow, int Acol, int Apgs, char *datfilename) {
FILE *fp;
int i, j, k, tmp;
printf("filename: %s\n", datfilename);
fp = fopen(datfilename, "r");
for (k=0;k<Apgs;k++)
for (i=0;i<Arow;i++)
for (j=0;j<Acol;j++) {
fscanf(fp, "%d", &tmp);
*(A+Arow*Acol*k+Acol*i+j) = tmp;
}
fclose(fp);
}
void load_int_array(int *array, int arraysize, char *datfilename) {
FILE *fp;
int i;
printf("filename: %s\n", datfilename);
fp = fopen(datfilename, "r");
// printf("step2\n");
for (i=0;i<arraysize;i++) {
fscanf(fp, "%d", &array[i]);
// printf("%d\n",array[i]);
}
fclose(fp);
// printf("step3\n");
}
void load_double_array(double *array, int arraysize, char *datfilename) {
FILE *fp;
int i;
printf("filename: %s\n", datfilename);
fp = fopen(datfilename, "r");
// printf("step4\n");
for (i=0;i<arraysize;i++) {
fscanf(fp, "%lf", &array[i]);
// printf("%f\n",array[i]);
}
fclose(fp);
// printf("step5\n");
}
void randperm(int *a, int np) {
int i, id1, id2, id3, tmpr, num_perm;
num_perm = 100*np;
for (i=0;i<np;i++)
*(a+i) = i;
for (i=0;i<num_perm;i++) {
id1 = rand() % np;
id3 = rand() % np;
id2 = (id1 + id3) % np;
if (id1 != id2) {
tmpr = *(a+id2);
*(a+id2) = *(a+id1);
*(a+id1) = tmpr;
}
}
}
int find_value_in_array(int *A, int target_rowA, int colA, int target_value) {
int i;
for (i=0;i<colA;i++)
if (*(A+colA*target_rowA+i)==target_value)
return(i);
if (i==colA)
return(-1);
}
| {
"alphanum_fraction": 0.5910909576,
"avg_line_length": 33.92760181,
"ext": "c",
"hexsha": "9d9fe134e8ea395d625a564f34f52711c95871f8",
"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/findcluster_ternary_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/findcluster_ternary_par.c",
"max_line_length": 151,
"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/findcluster_ternary_par.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4131,
"size": 14996
} |
// Copyright 2019 Victor Hugo Schulz
// 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 ATTITUDE_DETERMINATION_H
#define ATTITUDE_DETERMINATION_H
#include <iostream> // NEEDED FOR DEBUG ONLY
#include <vector>
#include <cmath>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
extern "C" {
#include <cblas.h>
#include <clapack.h>
}
#include "structures_st.h"
#include "standard_structures.h"
namespace st{
class AttitudeDetermination
{
public:
AttitudeDetermination();
std_str::Sky process(std_str::Sky identified);
private:
double trace(double *m, int size);
void eye(double *m, int size, double alpha);
};
}
#endif // ATTITUDE_DETERMINATION_H
| {
"alphanum_fraction": 0.7479131886,
"avg_line_length": 26.0434782609,
"ext": "h",
"hexsha": "0327e2945a051028697b3702bcc2f621f75500ff",
"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": "5216feb8036506503713c0c1f89728ecc40b3d5c",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "schulz89/Verification-Platform-for-Star-Trackers",
"max_forks_repo_path": "src/tcp_dut_client/attitude_determination.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "5216feb8036506503713c0c1f89728ecc40b3d5c",
"max_issues_repo_issues_event_max_datetime": "2020-10-30T06:25:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-10-30T06:25:21.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "schulz89/Verification-Platform-for-Star-Trackers",
"max_issues_repo_path": "src/tcp_dut_client/attitude_determination.h",
"max_line_length": 75,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "5216feb8036506503713c0c1f89728ecc40b3d5c",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "schulz89/Verification-Platform-for-Star-Trackers",
"max_stars_repo_path": "src/tcp_dut_client/attitude_determination.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-18T21:14:26.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-03-06T10:32:00.000Z",
"num_tokens": 281,
"size": 1198
} |
/*
* emu.c
* Edited and renamed to fr_emu.c for cosmo_pmc by Martin Kilbinger 2013.
*
*
* Created by Earl Lawrence on 9/17/09.
* Update 10/9/2012
*
* This program was prepared by Los Alamos National Security, LLC at Los Alamos National Laboratory (LANL)
* under contract No. DE-AC52-06NA25396 with the U.S. Department of Energy (DOE). All rights in the program
* are reserved by the DOE and Los Alamos National Security, LLC. Permission is granted to the public to
* copy and use this software without charge, provided that this Notice and any statement of authorship are
* reproduced on all copies. Neither the U.S. Government nor LANS makes any warranty, express or implied,
* or assumes any liability or responsibility for the use of this software.
*
*
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_errno.h>
#include "coyote.h"
#include "fr_constants.h"
/* Copy parameters to emulator input array */
void fill_xstar6_wo_z(double omega_m, double omega_b, double n_spec, double sigma_8, double w0_de, double h_100,
double xstar[])
{
/* Orders reversed: (omega_b <-> omega_m), (w0_de <-> sigma_8), compared to v1 */
xstar[0] = omega_b;
xstar[1] = omega_m;
xstar[2] = n_spec;
xstar[3] = h_100 * 100;
xstar[4] = w0_de;
xstar[5] = sigma_8;
}
/* ============================================================ *
* Returns the Coyote non-linear power spectrum. k is in units *
* of h/Mpc, h_100 is now an independent parameter (Coyote v2). *
* It is also used to transform it to [1/Mpc] as *
* needed by the Coyote emulator. *
* Six parameters, for coyote13. *
* ============================================================ */
double P_NL_coyote6(double omega_m, double omega_b, double n_spec, double sigma_8, double w0_de,
double h_100, double a, double k, double **ystar_allz, error **err)
{
double xstar[p], ystar[2*fr_nsim], val, k_invMpc;
int ihi, ilo, i;
/* Copy cosmological parameters */
fill_xstar6_wo_z(omega_m, omega_b, n_spec, sigma_8, w0_de, h_100, xstar);
/* Redshift */
xstar[p] = 1.0/a - 1.0;
/* Input k is [h/Mpc], Coyote interpolates on k_invMpc in [1/Mpc] */
k_invMpc = k * h_100;
/* Check k-range */
testErrorRetVA(k_invMpc < fr_ksim[0] || k_invMpc > fr_ksim[fr_nsim-1], coyote_range,
"Fourier mode k=%g 1/Mpc out of range [%g;%g]",
*err, __LINE__, -1.0, k_invMpc, fr_ksim[0], fr_ksim[fr_nsim-1]);
if (*ystar_allz == NULL) {
*ystar_allz = malloc_err(sizeof(double) * fr_rs * fr_nsim, err);
forwardError(*err, __LINE__, -1.0);
/* The actual emulator, filling the array in (k, z) */
//testErrorRet(ystar_allz == NULL, io_null, "Coyote13: array for (k,z) 'ystar_allz' not initialised",
// *err, __LINE__,);
fr_fill_ystar_allz(*ystar_allz, xstar, err);
forwardError(*err, __LINE__, -1.0);
}
/* ystar: first half = k, second half = P(k) */
fr_emu(xstar, ystar, *ystar_allz, err);
forwardError(*err, __LINE__, -1.0);
/* Looking for right k-index with bisection */
ilo = 0;
ihi = fr_nsim-1;
while (ihi - ilo > 1) {
i = (ihi + ilo) >> 1;
if (ystar[i] > k_invMpc) ihi = i;
else ilo = i;
}
testErrorRetVA(ihi == ilo, math_wrongValue, "Bisection failed, both indices equal (%d)", *err, __LINE__, -1.0, ihi);
/* Linear interpolation */
val = (k_invMpc - ystar[ilo]) / (ystar[ihi] - ystar[ilo]) * (ystar[fr_nsim + ihi]
- ystar[fr_nsim + ilo]) + ystar[fr_nsim + ilo];
/* Coyote P(k) [Mpc^3] -> output P(k) [(Mpc/h)^3] */
val *= h_100 * h_100 * h_100;
return val;
}
void fr_check_range(const double *xstar, error **err)
{
int i;
for(i=0; i<p; i++) {
testErrorRetVA((xstar[i] < fr_xmin[i]) || (xstar[i] > fr_xmin[i]+fr_xrange[i]), coyote_range,
"Coyote FrankenEmu parameter #%d (%g) out of range [%g; %g]",
*err, __LINE__,, i, xstar[i], fr_xmin[i], fr_xmin[i] + fr_xrange[i]);
} // for(i=0; i<p; i++)
// Check redshift to make sure we're interpolating
testErrorRetVA((xstar[p] < 0) || (xstar[p] > 4), coyote_range,
"Redshift %g out of range [%g;%g]", *err, __LINE__,, xstar[p], 0.0, 4.0);
}
/* ============================================================ *
* The actual emulation. Fills the array ystar_allz for (k, z). *
* Cosmological parameters, placeholder for the output, type of *
* output.
* xstar[p] = redshift is not used here, only the p=6 cosmo. *
* parameters. *
* ============================================================ */
void fr_fill_ystar_allz(double *ystar_allz, const double *xstar, error **err)
{
const double sd = 0.16002;
int i, j, k;
double xstarstd[p], wstar[peta], Sigmastar[peta][m], ystaremu[neta];
double logc;
// Interpolation stuff for k
gsl_spline *lininterp_k = gsl_spline_alloc(gsl_interp_linear, neta/rs);
gsl_interp_accel *accel = gsl_interp_accel_alloc();
//fprintf(stderr, "MKDEBUG: Filling ystar_allz for (%g, %g, %g, %g, %g, %g)\n",
// xstar[0], xstar[1], xstar[2], xstar[3], xstar[4], xstar[5]);
// Standardize the inputs
for(i=0; i<p; i++) {
xstarstd[i] = (xstar[i] - fr_xmin[i]) / fr_xrange[i];
}
// Compute the covariances between the new input and sims for all PCs
for(i=0; i<peta; i++) {
for(j=0; j<m; j++) {
logc = 0.0;
for(k=0; k<p; k++) {
logc -= fr_beta[i][k]*dsqr(fr_x[j][k]-xstarstd[k]);
}
Sigmastar[i][j] = exp(logc)/fr_lamz[i];
}
}
// Compute wstar, the predicted PC weights for the new input
for(i=0; i<peta; i++) {
wstar[i]=0.0;
for(j=0; j<m; j++) {
wstar[i] += Sigmastar[i][j] * fr_KrigBasis[i][j];
}
}
// Compute ystar, the new output
for(i=0; i<neta; i++) {
ystaremu[i] = 0.0;
for(j=0; j<peta; j++) {
ystaremu[i] += fr_K[i][j]*wstar[j];
}
ystaremu[i] = ystaremu[i]*sd + fr_mean[i];
}
// Interpolate the emulated output onto the original domain.
for(i=0; i<rs; i++) {
gsl_spline_init(lininterp_k, fr_kemu, &ystaremu[i*neta/rs], neta/rs);
for(j=0; j<fr_nsim; j++) {
ystar_allz[i*fr_nsim+j] = gsl_spline_eval(lininterp_k, fr_ksim[j], accel);
}
gsl_interp_accel_reset(accel);
}
gsl_spline_free(lininterp_k);
gsl_interp_accel_free(accel);
}
/* ============================================================ *
* This used to be the actual emulation, now fr_fill_ystar_allz *
* is called from here. *
* xstar[p+1] contains the six cosmological parameters plus the *
* redshift. *
* ============================================================ */
void fr_emu(const double *xstar, double *ystar, const double *ystar_allz, error **err)
{
int i, j;
//double ystar_allz[rs*fr_nsim];
double zemu[rs], ybyz[rs];
/* CosmoPMC version of Coyote: no initialisation, no static variables */
// Interpolation stuff z
gsl_spline *lininterp_z = gsl_spline_alloc(gsl_interp_linear, rs);
gsl_interp_accel *accel = gsl_interp_accel_alloc();
// Check the inputs to make sure we're interpolating.
fr_check_range(xstar, err);
forwardError(*err, __LINE__,);
// Fill in the k values for the final output; first half of ystar
for(i=0; i<fr_nsim; i++) {
ystar[i] = fr_ksim[i];
}
// Interpolate on to the desired redshift
// The order needs to be reversed here.
for(i=0; i<rs; i++) {
zemu[i] = (1/fr_aemu[rs-i-1]) - 1.0;
}
for(i=0; i<fr_nsim; i++) {
// Build an array with the values of y for a given value of z
// Reverse the order
for(j=0; j<rs; j++) {
ybyz[rs-j-1] = ystar_allz[j*fr_nsim+i];
}
gsl_spline_init(lininterp_z, zemu, ybyz, rs);
ystar[fr_nsim+i] = gsl_spline_eval(lininterp_z, xstar[p], accel);
gsl_interp_accel_reset(accel);
}
//printf("z interped\n");
// Transform to P(k); second half of ystar
for(j=0; j<fr_nsim; j++) {
ystar[fr_nsim+j] = ystar[fr_nsim+j] - 1.5*log10(fr_ksim[j]);
ystar[fr_nsim+j] = pow(10.0,ystar[fr_nsim+j])*2.0*M_PI*M_PI;
}
// Free some stuff. I always forget this.
// Thanks to Tim Eifler for discovering it (apparently the hard way).
gsl_spline_free(lininterp_z);
gsl_interp_accel_free(accel);
}
/* Undefine constants from fr_constants.h */
#undef m
#undef neta
#undef p
#undef peta
#undef rs
| {
"alphanum_fraction": 0.5847933127,
"avg_line_length": 34.11328125,
"ext": "c",
"hexsha": "6baa743994ddec7b72e48036a748920c1da468f4",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "danielgruen/ccv",
"max_forks_repo_path": "src/nicaea_2.5/Coyote/src/fr_emu.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "danielgruen/ccv",
"max_issues_repo_path": "src/nicaea_2.5/Coyote/src/fr_emu.c",
"max_line_length": 119,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "danielgruen/ccv",
"max_stars_repo_path": "src/nicaea_2.5/Coyote/src/fr_emu.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z",
"num_tokens": 2775,
"size": 8733
} |
/* multifit/multireg.c
*
* Copyright (C) 2015 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.
*/
/*
* References:
*
* [1] P. C. Hansen & D. P. O'Leary, "The use of the L-curve in
* the regularization of discrete ill-posed problems", SIAM J. Sci.
* Comput. 14 (1993), pp. 1487-1503.
*
* [2] P. C. Hansen, "Discrete Inverse Problems: Insight and Algorithms,"
* SIAM Press, 2010.
*/
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#include "linear_common.c"
int
gsl_multifit_linear_solve (const double lambda,
const gsl_matrix * X,
const gsl_vector * y,
gsl_vector * c,
double *rnorm,
double *snorm,
gsl_multifit_linear_workspace * work)
{
size_t rank;
int status;
status = multifit_linear_solve(X, y, GSL_DBL_EPSILON, lambda, &rank, c,
rnorm, snorm, work);
return status;
} /* gsl_multifit_linear_solve() */
/*
gsl_multifit_linear_applyW()
Apply weight matrix to (X,y) LS system
Inputs: X - least squares matrix n-by-p
w - weight vector n-by-1 or NULL for W = I
y - right hand side n-by-1
WX - (output) sqrt(W) X, n-by-p
Wy - (output) sqrt(W) y, n-by-1
Notes:
1) If w = NULL, on output WX = X and Wy = y
2) It is allowed for WX = X and Wy = y for in-place transform
*/
int
gsl_multifit_linear_applyW(const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_matrix * WX,
gsl_vector * Wy)
{
const size_t n = X->size1;
const size_t p = X->size2;
if (n != y->size)
{
GSL_ERROR("y vector does not match X", GSL_EBADLEN);
}
else if (w != NULL && n != w->size)
{
GSL_ERROR("weight vector does not match X", GSL_EBADLEN);
}
else if (n != WX->size1 || p != WX->size2)
{
GSL_ERROR("WX matrix dimensions do not match X", GSL_EBADLEN);
}
else if (n != Wy->size)
{
GSL_ERROR("Wy vector must be length n", GSL_EBADLEN);
}
else
{
size_t i;
/* copy WX = X; Wy = y if distinct pointers */
if (WX != X)
gsl_matrix_memcpy(WX, X);
if (Wy != y)
gsl_vector_memcpy(Wy, y);
if (w != NULL)
{
/* construct WX = sqrt(W) X and Wy = sqrt(W) y */
for (i = 0; i < n; ++i)
{
double wi = gsl_vector_get(w, i);
double swi;
gsl_vector_view row = gsl_matrix_row(WX, i);
double *yi = gsl_vector_ptr(Wy, i);
if (wi < 0.0)
wi = 0.0;
swi = sqrt(wi);
gsl_vector_scale(&row.vector, swi);
*yi *= swi;
}
}
return GSL_SUCCESS;
}
}
/*
gsl_multifit_linear_wstdform1()
Using regularization matrix
L = diag(l_1,l_2,...,l_p), transform to Tikhonov standard form:
X~ = sqrt(W) X L^{-1}
y~ = sqrt(W) y
c~ = L c
Inputs: L - Tikhonov matrix as a vector of diagonal elements p-by-1;
or NULL for L = I
X - least squares matrix n-by-p
y - right hand side vector n-by-1
w - weight vector n-by-1; or NULL for W = I
Xs - least squares matrix in standard form X~ n-by-p
ys - right hand side vector in standard form y~ n-by-1
work - workspace
Return: success/error
Notes:
1) It is allowed for X = Xs and y = ys
*/
int
gsl_multifit_linear_wstdform1 (const gsl_vector * L,
const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_multifit_linear_workspace * work)
{
const size_t n = X->size1;
const size_t p = X->size2;
if (n > work->nmax || p > work->pmax)
{
GSL_ERROR("observation matrix larger than workspace", GSL_EBADLEN);
}
else if (L != NULL && p != L->size)
{
GSL_ERROR("L vector does not match X", GSL_EBADLEN);
}
else if (n != y->size)
{
GSL_ERROR("y vector does not match X", GSL_EBADLEN);
}
else if (w != NULL && n != w->size)
{
GSL_ERROR("weight vector does not match X", GSL_EBADLEN);
}
else if (n != Xs->size1 || p != Xs->size2)
{
GSL_ERROR("Xs matrix dimensions do not match X", GSL_EBADLEN);
}
else if (n != ys->size)
{
GSL_ERROR("ys vector must be length n", GSL_EBADLEN);
}
else
{
int status = GSL_SUCCESS;
/* compute Xs = sqrt(W) X and ys = sqrt(W) y */
status = gsl_multifit_linear_applyW(X, w, y, Xs, ys);
if (status)
return status;
if (L != NULL)
{
size_t j;
/* construct X~ = sqrt(W) X * L^{-1} matrix */
for (j = 0; j < p; ++j)
{
gsl_vector_view Xj = gsl_matrix_column(Xs, j);
double lj = gsl_vector_get(L, j);
if (lj == 0.0)
{
GSL_ERROR("L matrix is singular", GSL_EDOM);
}
gsl_vector_scale(&Xj.vector, 1.0 / lj);
}
}
return status;
}
}
/*
gsl_multifit_linear_stdform1()
Using regularization matrix L = diag(l_1,l_2,...,l_p),
and W = I, transform to Tikhonov standard form:
X~ = X L^{-1}
y~ = y
c~ = L c
Inputs: L - Tikhonov matrix as a vector of diagonal elements p-by-1
X - least squares matrix n-by-p
y - right hand side vector n-by-1
Xs - least squares matrix in standard form X~ n-by-p
ys - right hand side vector in standard form y~ n-by-1
work - workspace
Return: success/error
Notes:
1) It is allowed for X = Xs
*/
int
gsl_multifit_linear_stdform1 (const gsl_vector * L,
const gsl_matrix * X,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_multifit_linear_workspace * work)
{
int status;
status = gsl_multifit_linear_wstdform1(L, X, NULL, y, Xs, ys, work);
return status;
}
int
gsl_multifit_linear_L_decomp (gsl_matrix * L, gsl_vector * tau)
{
const size_t m = L->size1;
const size_t p = L->size2;
int status;
if (tau->size != GSL_MIN(m, p))
{
GSL_ERROR("tau vector must be min(m,p)", GSL_EBADLEN);
}
else if (m >= p)
{
/* square or tall L matrix */
status = gsl_linalg_QR_decomp(L, tau);
return status;
}
else
{
/* more columns than rows, compute qr(L^T) */
gsl_matrix_view LTQR = gsl_matrix_view_array(L->data, p, m);
gsl_matrix *LT = gsl_matrix_alloc(p, m);
/* XXX: use temporary storage due to difficulties in transforming
* a rectangular matrix in-place */
gsl_matrix_transpose_memcpy(LT, L);
gsl_matrix_memcpy(<QR.matrix, LT);
gsl_matrix_free(LT);
status = gsl_linalg_QR_decomp(<QR.matrix, tau);
return status;
}
}
/*
gsl_multifit_linear_wstdform2()
Using regularization matrix L which is m-by-p, transform to Tikhonov
standard form. This routine is separated into two cases:
Case 1: m >= p, here we can use the QR decomposition of L = QR, and note
that ||L c|| = ||R c|| where R is p-by-p. Therefore,
X~ = X R^{-1} is n-by-p
y~ = y is n-by-1
c~ is p-by-1
M is not used
Case 2: m < p
X~ is (n - p + m)-by-m
y~ is (n - p + m)-by-1
c~ is m-by-1
M is n-by-p (workspace)
Inputs: LQR - output from gsl_multifit_linear_L_decomp()
Ltau - output from gsl_multifit_linear_L_decomp()
X - least squares matrix n-by-p
w - weight vector n-by-1; or NULL for W = I
y - right hand side vector n-by-1
Xs - (output) least squares matrix in standard form
case 1: n-by-p
case 2: (n - p + m)-by-m
ys - (output) right hand side vector in standard form
case 1: n-by-1
case 2: (n - p + m)-by-1
M - (output) workspace matrix needed to reconstruct solution vector
case 1: not used
case 2: n-by-p
work - workspace
Return: success/error
Notes:
1) If m >= p, on output:
Xs = X R^{-1}
ys = y
2) If m < p, on output:
M(:,1:pm) contains QR decomposition of A * K_o, needed to reconstruct
solution vector, where pm = p - m; M(:,p) contains Householder scalars
*/
int
gsl_multifit_linear_wstdform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_matrix * M,
gsl_multifit_linear_workspace * work)
{
const size_t m = LQR->size1;
const size_t n = X->size1;
const size_t p = X->size2;
if (n > work->nmax || p > work->pmax)
{
GSL_ERROR("observation matrix larger than workspace", GSL_EBADLEN);
}
else if (p != LQR->size2)
{
GSL_ERROR("LQR and X matrices have different numbers of columns", GSL_EBADLEN);
}
else if (n != y->size)
{
GSL_ERROR("y vector does not match X", GSL_EBADLEN);
}
else if (w != NULL && n != w->size)
{
GSL_ERROR("weights vector must be length n", GSL_EBADLEN);
}
else if (m >= p) /* square or tall L matrix */
{
/* the sizes of Xs and ys depend on whether m >= p or m < p */
if (n != Xs->size1 || p != Xs->size2)
{
GSL_ERROR("Xs matrix must be n-by-p", GSL_EBADLEN);
}
else if (n != ys->size)
{
GSL_ERROR("ys vector must have length n", GSL_EBADLEN);
}
else
{
int status;
size_t i;
gsl_matrix_const_view R = gsl_matrix_const_submatrix(LQR, 0, 0, p, p);
/* compute Xs = sqrt(W) X and ys = sqrt(W) y */
status = gsl_multifit_linear_applyW(X, w, y, Xs, ys);
if (status)
return status;
/* compute X~ = X R^{-1} using QR decomposition of L */
for (i = 0; i < n; ++i)
{
gsl_vector_view v = gsl_matrix_row(Xs, i);
/* solve: R^T y = X_i */
gsl_blas_dtrsv(CblasUpper, CblasTrans, CblasNonUnit, &R.matrix, &v.vector);
}
return GSL_SUCCESS;
}
}
else /* L matrix with m < p */
{
const size_t pm = p - m;
const size_t npm = n - pm;
/*
* This code closely follows section 2.6.1 of Hansen's
* "Regularization Tools" manual
*/
if (npm != Xs->size1 || m != Xs->size2)
{
GSL_ERROR("Xs matrix must be (n-p+m)-by-m", GSL_EBADLEN);
}
else if (npm != ys->size)
{
GSL_ERROR("ys vector must be of length (n-p+m)", GSL_EBADLEN);
}
else if (n != M->size1 || p != M->size2)
{
GSL_ERROR("M matrix must be n-by-p", GSL_EBADLEN);
}
else
{
int status;
gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p);
gsl_vector_view b = gsl_vector_subvector(work->t, 0, n);
gsl_matrix_view LTQR = gsl_matrix_view_array(LQR->data, p, m); /* qr(L^T) */
gsl_matrix_view Rp = gsl_matrix_view_array(LQR->data, m, m); /* R factor of L^T */
gsl_vector_const_view LTtau = gsl_vector_const_subvector(Ltau, 0, m);
/*
* M(:,1:p-m) will hold QR decomposition of A K_o; M(:,p) will hold
* Householder scalars
*/
gsl_matrix_view MQR = gsl_matrix_submatrix(M, 0, 0, n, pm);
gsl_vector_view Mtau = gsl_matrix_subcolumn(M, p - 1, 0, GSL_MIN(n, pm));
gsl_matrix_view AKo, AKp, HqTAKp;
gsl_vector_view v;
size_t i;
/* compute A = sqrt(W) X and b = sqrt(W) y */
status = gsl_multifit_linear_applyW(X, w, y, &A.matrix, &b.vector);
if (status)
return status;
/* compute: A <- A K = [ A K_p ; A K_o ] */
gsl_linalg_QR_matQ(<QR.matrix, <tau.vector, &A.matrix);
AKp = gsl_matrix_submatrix(&A.matrix, 0, 0, n, m);
AKo = gsl_matrix_submatrix(&A.matrix, 0, m, n, pm);
/* compute QR decomposition [H,T] = qr(A * K_o) and store in M */
gsl_matrix_memcpy(&MQR.matrix, &AKo.matrix);
gsl_linalg_QR_decomp(&MQR.matrix, &Mtau.vector);
/* AKp currently contains A K_p; apply H^T from the left to get H^T A K_p */
gsl_linalg_QR_QTmat(&MQR.matrix, &Mtau.vector, &AKp.matrix);
/* the last npm rows correspond to H_q^T A K_p */
HqTAKp = gsl_matrix_submatrix(&AKp.matrix, pm, 0, npm, m);
/* solve: Xs R_p^T = H_q^T A K_p for Xs */
gsl_matrix_memcpy(Xs, &HqTAKp.matrix);
for (i = 0; i < npm; ++i)
{
gsl_vector_view x = gsl_matrix_row(Xs, i);
gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit, &Rp.matrix, &x.vector);
}
/*
* compute: ys = H_q^T b; this is equivalent to computing
* the last q elements of H^T b (q = npm)
*/
v = gsl_vector_subvector(&b.vector, pm, npm);
gsl_linalg_QR_QTvec(&MQR.matrix, &Mtau.vector, &b.vector);
gsl_vector_memcpy(ys, &v.vector);
return GSL_SUCCESS;
}
}
}
int
gsl_multifit_linear_stdform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * y,
gsl_matrix * Xs,
gsl_vector * ys,
gsl_matrix * M,
gsl_multifit_linear_workspace * work)
{
int status;
status = gsl_multifit_linear_wstdform2(LQR, Ltau, X, NULL, y, Xs, ys, M, work);
return status;
}
/*
gsl_multifit_linear_genform1()
Backtransform regularized solution vector using matrix
L = diag(L)
*/
int
gsl_multifit_linear_genform1 (const gsl_vector * L,
const gsl_vector * cs,
gsl_vector * c,
gsl_multifit_linear_workspace * work)
{
if (L->size > work->pmax)
{
GSL_ERROR("L vector does not match workspace", GSL_EBADLEN);
}
else if (L->size != cs->size)
{
GSL_ERROR("cs vector does not match L", GSL_EBADLEN);
}
else if (L->size != c->size)
{
GSL_ERROR("c vector does not match L", GSL_EBADLEN);
}
else
{
/* compute true solution vector c = L^{-1} c~ */
gsl_vector_memcpy(c, cs);
gsl_vector_div(c, L);
return GSL_SUCCESS;
}
}
/*
gsl_multifit_linear_wgenform2()
Backtransform regularized solution vector in standard form to recover
original vector
Inputs: LQR - output from gsl_multifit_linear_L_decomp()
Ltau - output from gsl_multifit_linear_L_decomp()
X - original least squares matrix n-by-p
w - original weight vector n-by-1 or NULL for W = I
y - original rhs vector n-by-1
cs - standard form solution vector
c - (output) original solution vector p-by-1
M - matrix computed by gsl_multifit_linear_wstdform2()
work - workspace
*/
int
gsl_multifit_linear_wgenform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * w,
const gsl_vector * y,
const gsl_vector * cs,
const gsl_matrix * M,
gsl_vector * c,
gsl_multifit_linear_workspace * work)
{
const size_t m = LQR->size1;
const size_t n = X->size1;
const size_t p = X->size2;
if (n > work->nmax || p > work->pmax)
{
GSL_ERROR("X matrix does not match workspace", GSL_EBADLEN);
}
else if (p != LQR->size2)
{
GSL_ERROR("LQR matrix does not match X", GSL_EBADLEN);
}
else if (p != c->size)
{
GSL_ERROR("c vector does not match X", GSL_EBADLEN);
}
else if (w != NULL && n != w->size)
{
GSL_ERROR("w vector does not match X", GSL_EBADLEN);
}
else if (n != y->size)
{
GSL_ERROR("y vector does not match X", GSL_EBADLEN);
}
else if (m >= p) /* square or tall L matrix */
{
if (p != cs->size)
{
GSL_ERROR("cs vector must be length p", GSL_EBADLEN);
}
else
{
int s;
gsl_matrix_const_view R = gsl_matrix_const_submatrix(LQR, 0, 0, p, p); /* R factor of L */
/* solve R c = cs for true solution c, using QR decomposition of L */
gsl_vector_memcpy(c, cs);
s = gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit, &R.matrix, c);
return s;
}
}
else /* rectangular L matrix with m < p */
{
if (m != cs->size)
{
GSL_ERROR("cs vector must be length m", GSL_EBADLEN);
}
else if (n != M->size1 || p != M->size2)
{
GSL_ERROR("M matrix must be size n-by-p", GSL_EBADLEN);
}
else
{
int status;
const size_t pm = p - m;
gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p);
gsl_vector_view b = gsl_vector_subvector(work->t, 0, n);
gsl_matrix_view Rp = gsl_matrix_view_array(LQR->data, m, m); /* R_p */
gsl_matrix_view LTQR = gsl_matrix_view_array(LQR->data, p, m);
gsl_vector_const_view LTtau = gsl_vector_const_subvector(Ltau, 0, m);
gsl_matrix_const_view MQR = gsl_matrix_const_submatrix(M, 0, 0, n, pm);
gsl_vector_const_view Mtau = gsl_matrix_const_subcolumn(M, p - 1, 0, GSL_MIN(n, pm));
gsl_matrix_const_view To = gsl_matrix_const_submatrix(&MQR.matrix, 0, 0, pm, pm);
gsl_vector_view workp = gsl_vector_subvector(work->xt, 0, p);
gsl_vector_view v1, v2;
/* compute A = sqrt(W) X and b = sqrt(W) y */
status = gsl_multifit_linear_applyW(X, w, y, &A.matrix, &b.vector);
if (status)
return status;
/* initialize c to zero */
gsl_vector_set_zero(c);
/* compute c = L_inv cs = K_p R_p^{-T} cs */
/* set c(1:m) = R_p^{-T} cs */
v1 = gsl_vector_subvector(c, 0, m);
gsl_vector_memcpy(&v1.vector, cs);
gsl_blas_dtrsv(CblasUpper, CblasTrans, CblasNonUnit, &Rp.matrix, &v1.vector);
/* c <- K R_p^{-T} cs = [ K_p R_p^{_T} cs ; 0 ] */
gsl_linalg_QR_Qvec(<QR.matrix, <tau.vector, c);
/* compute: b1 = b - A L_inv cs */
gsl_blas_dgemv(CblasNoTrans, -1.0, &A.matrix, c, 1.0, &b.vector);
/* compute: b2 = H^T b1 */
gsl_linalg_QR_QTvec(&MQR.matrix, &Mtau.vector, &b.vector);
/* compute: b3 = T_o^{-1} b2 */
v1 = gsl_vector_subvector(&b.vector, 0, pm);
gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit, &To.matrix, &v1.vector);
/* compute: b4 = K_o b3 */
gsl_vector_set_zero(&workp.vector);
v2 = gsl_vector_subvector(&workp.vector, m, pm);
gsl_vector_memcpy(&v2.vector, &v1.vector);
gsl_linalg_QR_Qvec(<QR.matrix, <tau.vector, &workp.vector);
/* final solution vector */
gsl_vector_add(c, &workp.vector);
return GSL_SUCCESS;
}
}
}
int
gsl_multifit_linear_genform2 (const gsl_matrix * LQR,
const gsl_vector * Ltau,
const gsl_matrix * X,
const gsl_vector * y,
const gsl_vector * cs,
const gsl_matrix * M,
gsl_vector * c,
gsl_multifit_linear_workspace * work)
{
int status;
status = gsl_multifit_linear_wgenform2(LQR, Ltau, X, NULL, y, cs, M, c, work);
return status;
}
/*
gsl_multifit_linear_lreg()
Calculate regularization parameters to use in L-curve
analysis
Inputs: smin - smallest singular value of LS system
smax - largest singular value of LS system > 0
reg_param - (output) vector of regularization parameters
derived from singular values
Return: success/error
*/
int
gsl_multifit_linear_lreg (const double smin, const double smax,
gsl_vector * reg_param)
{
if (smax <= 0.0)
{
GSL_ERROR("smax must be positive", GSL_EINVAL);
}
else
{
const size_t N = reg_param->size;
/* smallest regularization parameter */
const double smin_ratio = 16.0 * GSL_DBL_EPSILON;
const double new_smin = GSL_MAX(smin, smax*smin_ratio);
double ratio;
size_t i;
gsl_vector_set(reg_param, N - 1, new_smin);
/* ratio so that reg_param(1) = s(1) */
ratio = pow(smax / new_smin, 1.0 / ((double)N - 1.0));
/* calculate the regularization parameters */
for (i = N - 1; i > 0 && i--; )
{
double rp1 = gsl_vector_get(reg_param, i + 1);
gsl_vector_set(reg_param, i, ratio * rp1);
}
return GSL_SUCCESS;
}
}
/*
gsl_multifit_linear_lcurve()
Calculate L-curve using regularization parameters estimated
from singular values of least squares matrix
Inputs: y - right hand side vector
reg_param - (output) vector of regularization parameters
derived from singular values
rho - (output) vector of residual norms ||y - X c||
eta - (output) vector of solution norms ||lambda c||
work - workspace
Return: success/error
Notes:
1) SVD of X must be computed first by calling multifit_linear_svd();
work->n and work->p are initialized by this function
*/
int
gsl_multifit_linear_lcurve (const gsl_vector * y,
gsl_vector * reg_param,
gsl_vector * rho, gsl_vector * eta,
gsl_multifit_linear_workspace * work)
{
const size_t n = y->size;
const size_t N = rho->size; /* number of points on L-curve */
if (n != work->n)
{
GSL_ERROR("y vector does not match workspace", GSL_EBADLEN);
}
else if (N < 3)
{
GSL_ERROR ("at least 3 points are needed for L-curve analysis",
GSL_EBADLEN);
}
else if (N != eta->size)
{
GSL_ERROR ("size of rho and eta vectors do not match",
GSL_EBADLEN);
}
else if (reg_param->size != eta->size)
{
GSL_ERROR ("size of reg_param and eta vectors do not match",
GSL_EBADLEN);
}
else
{
int status = GSL_SUCCESS;
const size_t p = work->p;
size_t i, j;
gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p);
gsl_vector_view S = gsl_vector_subvector(work->S, 0, p);
gsl_vector_view xt = gsl_vector_subvector(work->xt, 0, p);
gsl_vector_view workp = gsl_matrix_subcolumn(work->QSI, 0, 0, p);
gsl_vector_view workp2 = gsl_vector_subvector(work->D, 0, p); /* D isn't used for regularized problems */
const double smax = gsl_vector_get(&S.vector, 0);
const double smin = gsl_vector_get(&S.vector, p - 1);
double dr; /* residual error from projection */
double normy = gsl_blas_dnrm2(y);
double normUTy;
/* compute projection xt = U^T y */
gsl_blas_dgemv (CblasTrans, 1.0, &A.matrix, y, 0.0, &xt.vector);
normUTy = gsl_blas_dnrm2(&xt.vector);
dr = normy*normy - normUTy*normUTy;
/* calculate regularization parameters */
gsl_multifit_linear_lreg(smin, smax, reg_param);
for (i = 0; i < N; ++i)
{
double lambda = gsl_vector_get(reg_param, i);
double lambda_sq = lambda * lambda;
for (j = 0; j < p; ++j)
{
double sj = gsl_vector_get(&S.vector, j);
double xtj = gsl_vector_get(&xt.vector, j);
double f = sj / (sj*sj + lambda_sq);
gsl_vector_set(&workp.vector, j, f * xtj);
gsl_vector_set(&workp2.vector, j, (1.0 - sj*f) * xtj);
}
gsl_vector_set(eta, i, gsl_blas_dnrm2(&workp.vector));
gsl_vector_set(rho, i, gsl_blas_dnrm2(&workp2.vector));
}
if (n > p && dr > 0.0)
{
/* add correction to residual norm (see eqs 6-7 of [1]) */
for (i = 0; i < N; ++i)
{
double rhoi = gsl_vector_get(rho, i);
double *ptr = gsl_vector_ptr(rho, i);
*ptr = sqrt(rhoi*rhoi + dr);
}
}
/* restore D to identity matrix */
gsl_vector_set_all(work->D, 1.0);
return status;
}
} /* gsl_multifit_linear_lcurve() */
/*
gsl_multifit_linear_lcorner()
Determine point on L-curve of maximum curvature. For each
set of 3 points on the L-curve, the circle which passes through
the 3 points is computed. The radius of the circle is then used
as an estimate of the curvature at the middle point. The point
with maximum curvature is then selected.
Inputs: rho - vector of residual norms ||A x - b||
eta - vector of solution norms ||L x||
idx - (output) index i such that
(log(rho(i)),log(eta(i))) is the point of
maximum curvature
Return: success/error
*/
int
gsl_multifit_linear_lcorner(const gsl_vector *rho,
const gsl_vector *eta,
size_t *idx)
{
const size_t n = rho->size;
if (n < 3)
{
GSL_ERROR ("at least 3 points are needed for L-curve analysis",
GSL_EBADLEN);
}
else if (n != eta->size)
{
GSL_ERROR ("size of rho and eta vectors do not match",
GSL_EBADLEN);
}
else
{
int s = GSL_SUCCESS;
size_t i;
double x1, y1; /* first point of triangle on L-curve */
double x2, y2; /* second point of triangle on L-curve */
double rmin = -1.0; /* minimum radius of curvature */
/* initial values */
x1 = log(gsl_vector_get(rho, 0));
y1 = log(gsl_vector_get(eta, 0));
x2 = log(gsl_vector_get(rho, 1));
y2 = log(gsl_vector_get(eta, 1));
for (i = 1; i < n - 1; ++i)
{
/*
* The points (x1,y1), (x2,y2), (x3,y3) are the previous,
* current, and next point on the L-curve. We will find
* the circle which fits these 3 points and take its radius
* as an estimate of the curvature at this point.
*/
double x3 = log(gsl_vector_get(rho, i + 1));
double y3 = log(gsl_vector_get(eta, i + 1));
double x21 = x2 - x1;
double y21 = y2 - y1;
double x31 = x3 - x1;
double y31 = y3 - y1;
double h21 = x21*x21 + y21*y21;
double h31 = x31*x31 + y31*y31;
double d = fabs(2.0 * (x21*y31 - x31*y21));
double r = sqrt(h21*h31*((x3-x2)*(x3-x2)+(y3-y2)*(y3-y2))) / d;
/* if d =~ 0 then there are nearly colinear points */
if (gsl_finite(r))
{
/* check for smallest radius of curvature */
if (r < rmin || rmin < 0.0)
{
rmin = r;
*idx = i;
}
}
/* update previous/current L-curve values */
x1 = x2;
y1 = y2;
x2 = x3;
y2 = y3;
}
/* check if a minimum radius was found */
if (rmin < 0.0)
{
/* possibly co-linear points */
GSL_ERROR("failed to find minimum radius", GSL_EINVAL);
}
return s;
}
} /* gsl_multifit_linear_lcorner() */
/*
gsl_multifit_linear_lcorner2()
Determine point on L-curve (lambda^2, ||c||^2) of maximum curvature.
For each set of 3 points on the L-curve, the circle which passes through
the 3 points is computed. The radius of the circle is then used
as an estimate of the curvature at the middle point. The point
with maximum curvature is then selected.
This routine is based on the paper
M. Rezghi and S. M. Hosseini, "A new variant of L-curve for Tikhonov
regularization", J. Comp. App. Math., 231 (2009).
Inputs: reg_param - vector of regularization parameters
eta - vector of solution norms ||L x||
idx - (output) index i such that
(lambda(i)^2,eta(i)^2) is the point of
maximum curvature
Return: success/error
*/
int
gsl_multifit_linear_lcorner2(const gsl_vector *reg_param,
const gsl_vector *eta,
size_t *idx)
{
const size_t n = reg_param->size;
if (n < 3)
{
GSL_ERROR ("at least 3 points are needed for L-curve analysis",
GSL_EBADLEN);
}
else if (n != eta->size)
{
GSL_ERROR ("size of reg_param and eta vectors do not match",
GSL_EBADLEN);
}
else
{
int s = GSL_SUCCESS;
size_t i;
double x1, y1; /* first point of triangle on L-curve */
double x2, y2; /* second point of triangle on L-curve */
double rmin = -1.0; /* minimum radius of curvature */
/* initial values */
x1 = gsl_vector_get(reg_param, 0);
x1 *= x1;
y1 = gsl_vector_get(eta, 0);
y1 *= y1;
x2 = gsl_vector_get(reg_param, 1);
x2 *= x2;
y2 = gsl_vector_get(eta, 1);
y2 *= y2;
for (i = 1; i < n - 1; ++i)
{
/*
* The points (x1,y1), (x2,y2), (x3,y3) are the previous,
* current, and next point on the L-curve. We will find
* the circle which fits these 3 points and take its radius
* as an estimate of the curvature at this point.
*/
double lamip1 = gsl_vector_get(reg_param, i + 1);
double etaip1 = gsl_vector_get(eta, i + 1);
double x3 = lamip1 * lamip1;
double y3 = etaip1 * etaip1;
double x21 = x2 - x1;
double y21 = y2 - y1;
double x31 = x3 - x1;
double y31 = y3 - y1;
double h21 = x21*x21 + y21*y21;
double h31 = x31*x31 + y31*y31;
double d = fabs(2.0 * (x21*y31 - x31*y21));
double r = sqrt(h21*h31*((x3-x2)*(x3-x2)+(y3-y2)*(y3-y2))) / d;
/* if d =~ 0 then there are nearly colinear points */
if (gsl_finite(r))
{
/* check for smallest radius of curvature */
if (r < rmin || rmin < 0.0)
{
rmin = r;
*idx = i;
}
}
/* update previous/current L-curve values */
x1 = x2;
y1 = y2;
x2 = x3;
y2 = y3;
}
/* check if a minimum radius was found */
if (rmin < 0.0)
{
/* possibly co-linear points */
GSL_ERROR("failed to find minimum radius", GSL_EINVAL);
}
return s;
}
} /* gsl_multifit_linear_lcorner2() */
#define GSL_MULTIFIT_MAXK 100
/*
gsl_multifit_linear_L()
Compute discrete approximation to derivative operator of order
k on a regular grid of p points, ie: L is (p-k)-by-p
*/
int
gsl_multifit_linear_Lk(const size_t p, const size_t k, gsl_matrix *L)
{
if (p <= k)
{
GSL_ERROR("p must be larger than derivative order", GSL_EBADLEN);
}
else if (k >= GSL_MULTIFIT_MAXK - 1)
{
GSL_ERROR("derivative order k too large", GSL_EBADLEN);
}
else if (p - k != L->size1 || p != L->size2)
{
GSL_ERROR("L matrix must be (p-k)-by-p", GSL_EBADLEN);
}
else
{
double c_data[GSL_MULTIFIT_MAXK];
gsl_vector_view cv = gsl_vector_view_array(c_data, k + 1);
size_t i, j;
/* zeroth derivative */
if (k == 0)
{
gsl_matrix_set_identity(L);
return GSL_SUCCESS;
}
gsl_matrix_set_zero(L);
gsl_vector_set_zero(&cv.vector);
gsl_vector_set(&cv.vector, 0, -1.0);
gsl_vector_set(&cv.vector, 1, 1.0);
for (i = 1; i < k; ++i)
{
double cjm1 = 0.0;
for (j = 0; j < k + 1; ++j)
{
double cj = gsl_vector_get(&cv.vector, j);
gsl_vector_set(&cv.vector, j, cjm1 - cj);
cjm1 = cj;
}
}
/* build L, the c_i are the entries on the diagonals */
for (i = 0; i < k + 1; ++i)
{
gsl_vector_view v = gsl_matrix_superdiagonal(L, i);
double ci = gsl_vector_get(&cv.vector, i);
gsl_vector_set_all(&v.vector, ci);
}
return GSL_SUCCESS;
}
} /* gsl_multifit_linear_Lk() */
/*
gsl_multifit_linear_Lsobolev()
Construct Sobolev smoothing norm operator
L = [ a_0 I; a_1 L_1; a_2 L_2; ...; a_k L_k ]
by computing the Cholesky factor of L^T L
Inputs: p - number of columns of L
kmax - maximum derivative order (< p)
alpha - vector of weights; alpha_k multiplies L_k, size kmax + 1
L - (output) upper triangular Sobolev matrix p-by-p,
stored in upper triangle
work - workspace
Notes:
1) work->Q is used to store intermediate L_k matrices
*/
int
gsl_multifit_linear_Lsobolev(const size_t p, const size_t kmax,
const gsl_vector *alpha, gsl_matrix *L,
gsl_multifit_linear_workspace *work)
{
if (p > work->pmax)
{
GSL_ERROR("p is larger than workspace", GSL_EBADLEN);
}
else if (p <= kmax)
{
GSL_ERROR("p must be larger than derivative order", GSL_EBADLEN);
}
else if (kmax + 1 != alpha->size)
{
GSL_ERROR("alpha must be size kmax + 1", GSL_EBADLEN);
}
else if (p != L->size1)
{
GSL_ERROR("L matrix is wrong size", GSL_EBADLEN);
}
else if (L->size1 != L->size2)
{
GSL_ERROR("L matrix is not square", GSL_ENOTSQR);
}
else
{
int s;
size_t j, k;
gsl_vector_view d = gsl_matrix_diagonal(L);
const double alpha0 = gsl_vector_get(alpha, 0);
/* initialize L to alpha0^2 I */
gsl_matrix_set_zero(L);
gsl_vector_add_constant(&d.vector, alpha0 * alpha0);
for (k = 1; k <= kmax; ++k)
{
gsl_matrix_view Lk = gsl_matrix_submatrix(work->Q, 0, 0, p - k, p);
double ak = gsl_vector_get(alpha, k);
/* compute a_k L_k */
s = gsl_multifit_linear_Lk(p, k, &Lk.matrix);
if (s)
return s;
gsl_matrix_scale(&Lk.matrix, ak);
/* LTL += L_k^T L_k */
gsl_blas_dsyrk(CblasLower, CblasTrans, 1.0, &Lk.matrix, 1.0, L);
}
s = gsl_linalg_cholesky_decomp(L);
if (s)
return s;
/* copy Cholesky factor to upper triangle and zero out bottom */
gsl_matrix_transpose_tricpy('L', 1, L, L);
for (j = 0; j < p; ++j)
{
for (k = 0; k < j; ++k)
gsl_matrix_set(L, j, k, 0.0);
}
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.544008106,
"avg_line_length": 29.9066339066,
"ext": "c",
"hexsha": "4573fa930cd11bce3aad8330cd7b28d9345db1e8",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/multireg.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit/multireg.c",
"max_line_length": 111,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017",
"max_stars_repo_path": "gsl-2.4/multifit/multireg.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z",
"num_tokens": 10072,
"size": 36516
} |
#pragma once
#include <cblas.h>
#include <aml/defs.h>
#include <aml/handle.h>
namespace aml {
namespace impl {
namespace cpu {
inline CBLAS_TRANSPOSE convert_op(char op) {
if (op == 'n') {
return CblasNoTrans;
} else {
return CblasTrans;
}
}
/** BLAS LEVEL 1 **************************************************************/
inline float nrm2(aml::Handle h,
Index n,
const float *x) {
AML_ASSERT_INT(n);
auto tic = h.tic("cpu_snrm2_" + std::to_string(n));
float res = cblas_snrm2(n, x, 1);
tic.stop();
return res;
}
inline double nrm2(aml::Handle h,
Index n,
const double *x) {
AML_ASSERT_INT(n);
auto tic = h.tic("cpu_dnrm2_" + std::to_string(n));
double res = cblas_dnrm2(n, x, 1);
tic.stop();
return res;
}
/** BLAS LEVEL 2 **************************************************************/
inline void gemv(aml::Handle h,
char op,
Index m,
Index n,
float alpha,
const float *a,
Index lda,
const float *x,
float beta,
float *y) {
AML_ASSERT_INT(m, n, lda);
auto tic = h.tic("cpu_sgemv_" + std::to_string(m) + "_" + std::to_string(n));
cblas_sgemv(CblasColMajor,
convert_op(op), m, n, alpha, a, lda, x, 1, beta, y, 1);
tic.stop();
}
inline void gemv(aml::Handle h,
char op,
Index m,
Index n,
double alpha,
const double *a,
Index lda,
const double *x,
double beta,
double *y) {
AML_ASSERT_INT(m, n, lda);
auto tic = h.tic("cpu_dgemv_" + std::to_string(m) + "_" + std::to_string(n));
cblas_dgemv(CblasColMajor,
convert_op(op), m, n, alpha, a, lda, x, 1, beta, y, 1);
tic.stop();
}
inline void trsv(aml::Handle h,
char op,
Index m,
const float *a,
Index lda,
float *x) {
AML_ASSERT_INT(m, lda);
auto tic = h.tic("cpu_strsv_" + std::to_string(m));
cblas_strsv(CblasColMajor, CblasLower,
convert_op(op), CblasNonUnit, m, a, lda, x, 1);
tic.stop();
}
inline void trsv(aml::Handle h,
char op,
Index m,
const double *a,
Index lda,
double *x) {
AML_ASSERT_INT(m, lda);
auto tic = h.tic("cpu_dtrsv_" + std::to_string(m));
cblas_dtrsv(CblasColMajor, CblasLower,
convert_op(op), CblasNonUnit, m, a, lda, x, 1);
tic.stop();
}
/** BLAS LEVEL 3 **************************************************************/
inline void gemm(aml::Handle h,
char op_a,
char op_b,
Index m,
Index n,
Index k,
float alpha,
const float *a,
Index lda,
const float *b,
Index ldb,
float beta,
float *c,
Index ldc) {
AML_ASSERT_INT(m, n, k, lda, ldb, ldc);
auto tic = h.tic("cpu_sgemm_"
+ std::to_string(m) + "_" + std::to_string(n) + "_" + std::to_string(k));
cblas_sgemm(CblasColMajor, convert_op(op_a), convert_op(op_b),
m, n, k, alpha, a, lda, b, ldb, beta, c, ldc);
tic.stop();
}
inline void gemm(aml::Handle h,
char op_a,
char op_b,
Index m,
Index n,
Index k,
double alpha,
const double *a,
Index lda,
const double *b,
Index ldb,
double beta,
double *c,
Index ldc) {
AML_ASSERT_INT(m, n, k, lda, ldb, ldc);
auto tic = h.tic("cpu_dgemm_"
+ std::to_string(m) + "_" + std::to_string(n) + "_" + std::to_string(k));
cblas_dgemm(CblasColMajor, convert_op(op_a), convert_op(op_b),
m, n, k, alpha, a, lda, b, ldb, beta, c, ldc);
tic.stop();
}
inline void syrk(aml::Handle h,
char op,
Index n,
Index k,
float alpha,
const float *a,
Index lda,
float beta,
float *c,
Index ldc) {
AML_ASSERT_INT(n, k, lda, ldc);
auto tic = h.tic("cpu_ssyrk_" + std::to_string(n) + "_" + std::to_string(k));
cblas_ssyrk(CblasColMajor, CblasLower,
convert_op(op), n, k, alpha, a, lda, beta, c, ldc);
tic.stop();
}
inline void syrk(aml::Handle h,
char op,
Index n,
Index k,
double alpha,
const double *a,
Index lda,
double beta,
double *c,
Index ldc) {
AML_ASSERT_INT(n, k, lda, ldc);
auto tic = h.tic("cpu_dsyrk_" + std::to_string(n) + "_" + std::to_string(k));
cblas_dsyrk(CblasColMajor, CblasLower,
convert_op(op), n, k, alpha, a, lda, beta, c, ldc);
tic.stop();
}
inline void trsm(aml::Handle h,
char op,
Index m,
Index n,
float alpha,
const float *a,
Index lda,
float *b,
Index ldb) {
AML_ASSERT_INT(m, n, lda, ldb);
auto tic = h.tic("cpu_strsm_" + std::to_string(m) + "_" + std::to_string(n));
cblas_strsm(
CblasColMajor, CblasRight, CblasLower, convert_op(op), CblasNonUnit,
m, n, alpha, a, lda, b, ldb);
tic.stop();
}
inline void trsm(aml::Handle h,
char op,
Index m,
Index n,
double alpha,
const double *a,
Index lda,
double *b,
Index ldb) {
AML_ASSERT_INT(m, n, lda, ldb);
auto tic = h.tic("cpu_dtrsm_" + std::to_string(m) + "_" + std::to_string(n));
cblas_dtrsm(
CblasColMajor, CblasRight, CblasLower, convert_op(op), CblasNonUnit,
m, n, alpha, a, lda, b, ldb);
tic.stop();
}
} // namespace cpu
} // namespace impl
} // namespace aml
| {
"alphanum_fraction": 0.4612329202,
"avg_line_length": 25.4817813765,
"ext": "h",
"hexsha": "417f7c72e694ca57e3bb75627335a6875528bb93",
"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": "337607309ad1b7aa9369b39d471b38240046d60f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "foges/aml",
"max_forks_repo_path": "include/aml/impl/cpu/blas.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "337607309ad1b7aa9369b39d471b38240046d60f",
"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": "foges/aml",
"max_issues_repo_path": "include/aml/impl/cpu/blas.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "337607309ad1b7aa9369b39d471b38240046d60f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "foges/aml",
"max_stars_repo_path": "include/aml/impl/cpu/blas.h",
"max_stars_repo_stars_event_max_datetime": "2019-12-29T07:38:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-12-29T07:38:48.000Z",
"num_tokens": 1633,
"size": 6294
} |
/*! \file deleter.h
\brief gsl_interp_accelとgsl_splineのデリータを宣言・定義したヘッダファイル
Copyright © 2015 @dc1394 All Rights Reserved.
This software is released under the BSD 2-Clause License.
*/
#ifndef _DELETER_H_
#define _DELETER_H_
#pragma once
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
namespace getdata {
//! A function.
/*!
gsl_interp_accelへのポインタを解放するラムダ式
\param acc gsl_interp_accelへのポインタ
*/
static auto const gsl_interp_accel_deleter = [](gsl_interp_accel * acc) {
gsl_interp_accel_free(acc);
};
//! A function.
/*!
gsl_splineへのポインタを解放するラムダ式
\param spline gsl_splineへのポインタ
*/
static auto const gsl_spline_deleter = [](gsl_spline * spline) {
gsl_spline_free(spline);
};
}
#endif // _DELETER_H_
| {
"alphanum_fraction": 0.67324291,
"avg_line_length": 21.3421052632,
"ext": "h",
"hexsha": "0bab56f063e03d45b799af313d5c2ec04be8b12b",
"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": "0ac49e883a4f9b92a48d224350f3d1967a1dbfe7",
"max_forks_repo_licenses": [
"Intel",
"X11",
"OLDAP-2.2.1",
"Unlicense"
],
"max_forks_repo_name": "dc1394/SchracVisualize",
"max_forks_repo_path": "getdata/deleter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0ac49e883a4f9b92a48d224350f3d1967a1dbfe7",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Intel",
"X11",
"OLDAP-2.2.1",
"Unlicense"
],
"max_issues_repo_name": "dc1394/SchracVisualize",
"max_issues_repo_path": "getdata/deleter.h",
"max_line_length": 77,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "0ac49e883a4f9b92a48d224350f3d1967a1dbfe7",
"max_stars_repo_licenses": [
"Intel",
"X11",
"OLDAP-2.2.1",
"Unlicense"
],
"max_stars_repo_name": "dc1394/SchracVisualize",
"max_stars_repo_path": "getdata/deleter.h",
"max_stars_repo_stars_event_max_datetime": "2016-01-08T04:52:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-02T05:26:00.000Z",
"num_tokens": 263,
"size": 811
} |
// MIT License
// Copyright (c) [2017] [Vinay Yuvashankar]
// 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.
/** \file ERSP.cc
\brief This file contains all of the function required to generate the Event Related Spectral Pertubation of EEG signals.
*/
#include "wavelet.h"
#include <gsl/gsl_statistics.h>
#define NORMALIZATION_FACTOR 0.375402913609157562
int ERSP (double * raw_data, double* scales, const int sampling_frequency, const int n,
const int J, int const trials, const int padding_type,
double * output)
{
int i, j, x;
//Calculate the necessary constants for the Continuous Wavelet Transform.
const int PADDED_SIZE = CalculatePaddingSize(n, padding_type);
const int m = PRE_EVENT_TIME * sampling_frequency;
const double dw = (2 * M_PI * sampling_frequency)/(PADDED_SIZE); //NOT IN RAD/SEC in Hz
fftw_init_threads();
#pragma omp parallel private(i, j, x) shared(raw_data, output, scales) default(none)
{
//Array Inits
double * pre_stimulus, *wavelet_out, *baseline_out;
fftw_complex *data_in, *fft_data, *filter_convolution, *fftw_result;
fftw_plan plan_forward, plan_backward;
//Memory Allocations
wavelet_out = (double*) malloc( n * J * sizeof(double) );
baseline_out = (double*) malloc( n * J * sizeof(double) );
pre_stimulus = (double*) malloc( m * sizeof(double) );
//FFTW Memory Allocations
data_in = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE );
fft_data = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE );
filter_convolution = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE );
fftw_result = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * PADDED_SIZE );
#pragma omp critical (make_plan)
{
fftw_plan_with_nthreads(1);
if (fftw_import_wisdom_from_filename("FFTW_Plan.wise") == 0)
{
printf("No FFTW Plan, using an unoptimized method\n");
plan_forward = fftw_plan_dft_1d(PADDED_SIZE, data_in, fft_data, FFTW_FORWARD, FFTW_ESTIMATE);
plan_backward = fftw_plan_dft_1d(PADDED_SIZE, filter_convolution, fftw_result, FFTW_BACKWARD, FFTW_ESTIMATE);
}
else
{
plan_forward = fftw_plan_dft_1d(PADDED_SIZE, data_in, fft_data, FFTW_FORWARD, FFTW_EXHAUSTIVE);
plan_backward = fftw_plan_dft_1d(PADDED_SIZE, filter_convolution, fftw_result, FFTW_BACKWARD, FFTW_EXHAUSTIVE);
}
}
/*Begin ERSP*/
#pragma omp for
for ( x = 0; x < trials; ++x)
{
memset(data_in, 0.0, sizeof( fftw_complex ) * PADDED_SIZE);
memset(fft_data, 0.0, sizeof( fftw_complex ) * PADDED_SIZE);
memset(filter_convolution, 0.0, sizeof( fftw_complex ) * PADDED_SIZE);
memset(fftw_result, 0.0, sizeof( fftw_complex ) * PADDED_SIZE);
/*Begin Wavelet Analysis*/
PopulateDataArray(raw_data, n, x,
PADDED_SIZE, padding_type, data_in);
fftw_execute(plan_forward);
for (i = 0; i < J; ++i)
{
FrequencyMultiply(fft_data, PADDED_SIZE, scales[i], dw,
filter_convolution);
//Take the inverse FFT and store it in fftw_result
fftw_execute(plan_backward);
//Calculate the power and store it in result this may need to be changed to accomodate for phase
for (j = 0; j < n; ++j)
{
wavelet_out[i * n + j] = MAGNITUDE(fftw_result[j][0], fftw_result[j][1]) / (NORMALIZATION_FACTOR * sqrt(scales[i]) );
}
}
/*End Wavelet Analysis*/
//Remove the baseline
RemoveBaseline(pre_stimulus, wavelet_out,
n, J, m,
baseline_out);
for ( i = 0; i < n * J; ++i)
{
output[i] += fabs(baseline_out[i]);
}
}
#pragma omp for simd
for ( i = 0; i < n * J; ++i)
{
output[i] /= trials;
}
/*End ERSP*/
//Sanitation Engineering
fftw_destroy_plan(plan_forward); fftw_destroy_plan(plan_backward);
fftw_free(data_in); fftw_free(fft_data); fftw_free(filter_convolution); fftw_free(fftw_result);
free(pre_stimulus); free(baseline_out); free(wavelet_out);
}/*End of OpenMP*/
return(0);
}
int RemoveBaseline(double* pre_stimulus, double* pre_baseline_array,
const int n, const int J, const int m,
double* output)
{
double value;
double mean, sDeviation;
const int stride = 1;
int i, j;
for ( i = 0; i < J; ++i)
{
//Copy the pre trial results from each frequency block into pre_stimulus.
for ( j = 0; j < m; ++j)
{
pre_stimulus[j] = pre_baseline_array[i * n + j];
}
//Calculate mean and standard deviation
mean = gsl_stats_mean(pre_stimulus, stride, m);
sDeviation = gsl_stats_sd_m(pre_stimulus, stride, m, mean);
//Remove the Baseline
for ( j = 0; j < n; ++j)
{
value = pre_baseline_array[i * n + j] * pre_baseline_array[i * n + j];
output[i * n + j] = (fabs(value) - mean) / sDeviation;
// output[i * n + j] = ( pre_baseline_array[i * n + j] - mean ) / sDeviation;
}
}
return(0);
}
int Generate_FFTW_Wisdom(int padded_size)
{
int success_flag = 1;
//Array Inits
fftw_complex *data_in, *fft_data, *filter_convolution, *fftw_result;
fftw_plan plan_forward, plan_backward;
fftw_init_threads();
//FFTW Memory Allocations
data_in = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * padded_size );
fft_data = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * padded_size );
filter_convolution = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * padded_size );
fftw_result = (fftw_complex *) fftw_malloc( sizeof( fftw_complex ) * padded_size );
//FFTW Planning
fftw_plan_with_nthreads(1);
printf("Generating an Exhaustive FFTW Plan\n");
plan_forward = fftw_plan_dft_1d(padded_size, data_in, fft_data, FFTW_FORWARD, FFTW_EXHAUSTIVE);
plan_backward = fftw_plan_dft_1d(padded_size, filter_convolution, fftw_result, FFTW_BACKWARD, FFTW_EXHAUSTIVE);
printf("Writing FFTW plan to FFTW_Plan.wise\n");
if (fftw_export_wisdom_to_filename("FFTW_Plan.wise") != 0)
{
success_flag = 0;
}
fftw_destroy_plan(plan_forward); fftw_destroy_plan(plan_backward);
fftw_free(data_in); fftw_free(fft_data); fftw_free(filter_convolution); fftw_free(fftw_result);
return(success_flag);
}
int FrequencyMultiply(fftw_complex* fft_data,
const int data_size, const double scale, const double dw,
fftw_complex* filter_convolution)
{
int j;
double value;
//Compute the Fourier Morlet at 0 and N/2
double norm = sqrt(scale);
value = CompleteFourierMorlet(0.0, scale, norm);
filter_convolution[0][0] = (fft_data[0][0]/data_size) * value;
filter_convolution[0][1] = (fft_data[0][1]/data_size) * value;
filter_convolution[data_size/2][0] = 0.0;
filter_convolution[data_size/2][1] = 0.0;
//Compute the Fourier Morlet Convolution in between
for (j = 1; j < data_size/2 - 1; ++j)
{
value = CompleteFourierMorlet( j * dw , scale, norm);
filter_convolution[j][0] = (fft_data[j][0]/data_size) * value;
filter_convolution[j][1] = (fft_data[j][1]/data_size) * value;
filter_convolution[data_size- j][0] = 0.0;
filter_convolution[data_size- j][1] = 0.0;
}
return(0);
}
int PopulateDataArray(double* input_data, const int data_size, const int trial_number,
const int padded_size, const int padding_type,
fftw_complex* output_data)
{
const double ramp = 2.0/data_size; // = 1.0/ n / 2
double gain;
int i;
int output_counter = 0;
int input_counter = 0;
switch(padding_type)
{
case 0: //No Padding what so ever
//populate the FFTW data vector.
for (i = 0; i < data_size; ++i)
{
output_data[i][0] = input_data[trial_number * data_size + i];
output_data[i][1] = 0.0;
}
break;
case 1: //Zero - Padding
//populate the FFTW data vector.
for (i = 0; i < data_size; ++i)
{
output_data[i][0] = input_data[trial_number * data_size + i];
output_data[i][1] = 0.0;
}
//Horse the rest of the data vector to zero just in case
for (i = data_size; i < padded_size; ++i)
{
output_data[i][0] = 0.0;
output_data[i][1] = 0.0;
}
break;
case 2: //Duplicate array and ramp up and ramp down output
for (i = 0; i < data_size; ++i)
{
output_data[i][0] = input_data[trial_number * data_size + i];
output_data[i][1] = 0.0;
}
for (i = 0; i < (int) (0.5* data_size); ++i)
{
output_counter = data_size + i;
input_counter = (int) (trial_number * data_size + (0.5*data_size) + i);
gain = i * ramp;
output_data[output_counter][0] = (1.0 - gain) * input_data[input_counter];
output_data[output_counter][1] = 0.0;
output_data[output_counter + (int) (0.5 * data_size)][0] = gain * input_data[trial_number * data_size + i];
output_data[output_counter + (int) (0.5 * data_size)][1] = 0.0;
}
break;
default: //Return just the array no padding.
//populate the FFTW data vector.
for (i = 0; i < data_size; ++i)
{
output_data[i][0] = input_data[trial_number * data_size + i];
output_data[i][1] = 0.0;
}
break;
}
return(padding_type);
} | {
"alphanum_fraction": 0.6674498287,
"avg_line_length": 33.6019736842,
"ext": "c",
"hexsha": "224415a7d874ff1646ecf5785e7727f8882ebc8d",
"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": "bc96cd74939a7022d64dbea86483fb4a579dd24d",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "yuvashankar/Research",
"max_forks_repo_path": "src/ERSP.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bc96cd74939a7022d64dbea86483fb4a579dd24d",
"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": "yuvashankar/Research",
"max_issues_repo_path": "src/ERSP.c",
"max_line_length": 122,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bc96cd74939a7022d64dbea86483fb4a579dd24d",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "yuvashankar/Research",
"max_stars_repo_path": "src/ERSP.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2987,
"size": 10215
} |
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
typedef struct ornsteinuhlenbeckprocess_{
int steps;
double dt;
double sigma;
double *x;
gsl_rng *rng;
} OrnsteinUhlenbeckProcess;
void OrnsteinUhlenbeckProcess_run(OrnsteinUhlenbeckProcess *self) {
int i;
double sgm = self->sigma * sqrt(self->dt);
for (i = 1; i < self->steps; ++i){
self->x[i] = (1 - self->dt) * self->x[i-1] \
+ gsl_ran_gaussian_ziggurat(self->rng, sgm);
}
}
| {
"alphanum_fraction": 0.66875,
"avg_line_length": 22.8571428571,
"ext": "c",
"hexsha": "b8dad9f78532489c99b635c801e4f45678d9e538",
"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": "44f30077857fc96cb77539f3fe0a7e8112f86c82",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tkf/comparatist",
"max_forks_repo_path": "lib/libcomparatist_oup.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "44f30077857fc96cb77539f3fe0a7e8112f86c82",
"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": "tkf/comparatist",
"max_issues_repo_path": "lib/libcomparatist_oup.c",
"max_line_length": 67,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "44f30077857fc96cb77539f3fe0a7e8112f86c82",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tkf/comparatist",
"max_stars_repo_path": "lib/libcomparatist_oup.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 163,
"size": 480
} |
#pragma once
#include <gsl/gsl>
#include <d3d11.h>
#undef min
#undef max
namespace Halley {
class DX11Video;
class DX11Buffer {
public:
enum class Type
{
Vertex,
Index,
Constant
};
DX11Buffer(DX11Video& video, Type type, size_t initialSize = 0);
DX11Buffer(DX11Buffer&& other) noexcept;
~DX11Buffer();
DX11Buffer(const DX11Buffer& other) = delete;
DX11Buffer& operator=(const DX11Buffer& other) = delete;
DX11Buffer& operator=(DX11Buffer&& other) = delete;
void setData(gsl::span<const gsl::byte> data);
ID3D11Buffer*& getBuffer();
UINT getOffset() const;
UINT getLastSize() const;
bool canFit(size_t size) const;
void reset();
void clear();
private:
DX11Video& video;
Type type;
ID3D11Buffer* buffer = nullptr;
size_t curSize = 0;
size_t curPos = 0;
size_t lastSize = 0;
size_t lastPos = 0;
bool waitingReset = false;
void resize(size_t size);
};
}
| {
"alphanum_fraction": 0.6791845494,
"avg_line_length": 18.64,
"ext": "h",
"hexsha": "bd15739ebe271b43fb20b7178740a4c103fea9bf",
"lang": "C",
"max_forks_count": 193,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T12:59:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-10-23T06:08:41.000Z",
"max_forks_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "sunhay/halley",
"max_forks_repo_path": "src/plugins/dx11/src/dx11_buffer.h",
"max_issues_count": 53,
"max_issues_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_issues_repo_issues_event_max_datetime": "2022-01-10T13:52:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-10-09T16:25:04.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "sunhay/halley",
"max_issues_repo_path": "src/plugins/dx11/src/dx11_buffer.h",
"max_line_length": 72,
"max_stars_count": 3262,
"max_stars_repo_head_hexsha": "fc4f153956cc34d7fa02b76850e22183b8e30e25",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "sunhay/halley",
"max_stars_repo_path": "src/plugins/dx11/src/dx11_buffer.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T17:47:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-10T15:24:10.000Z",
"num_tokens": 291,
"size": 932
} |
#include <math.h>
#include <gsl/gsl_nan.h>
#include "csm_all.h"
#include <egsl/egsl_macros.h>
void find_neighbours(LDP ld, int i, int max_num, int*indexes, size_t*num_found);
void filter_orientation(double theta0, double rho0, size_t n,
const double*thetas, const double*rhos, double *alpha, double*cov0_alpha );
/** Requires the "cluster" field to be set */
void ld_compute_orientation(LDP ld, int size_neighbourhood, double sigma) {
int i;
for(i=0;i<ld->nrays;i++){
if(!ld_valid_ray(ld,i) || (ld->cluster[i] == -1)) {
ld->alpha[i] = GSL_NAN;
ld->cov_alpha[i] = GSL_NAN;
ld->alpha_valid[i] = 0;
continue;
}
int neighbours[size_neighbourhood*2];
size_t num_neighbours;
find_neighbours(ld, i, size_neighbourhood, neighbours, &num_neighbours);
if(0==num_neighbours) {
ld->alpha[i] = GSL_NAN;
ld->cov_alpha[i] = GSL_NAN;
ld->alpha_valid[i] = 0;
continue;
}
/* printf("orientation for i=%d:\n",i); */
double thetas[num_neighbours];
double readings[num_neighbours];
size_t a=0;
for(a=0;a<num_neighbours;a++) {
thetas[a] = ld->theta[neighbours[a]];
readings[a] = ld->readings[neighbours[a]];
/* printf(" j = %d theta = %f rho = %f\n", neighbours[a], thetas[a],readings[a]); */
}
double alpha=42, cov0_alpha=32;
filter_orientation(ld->theta[i],ld->readings[i],num_neighbours,
thetas,readings,&alpha,&cov0_alpha);
if(gsl_isnan(alpha)) {
ld->alpha[i] = GSL_NAN;
ld->cov_alpha[i] = GSL_NAN;
ld->alpha_valid[i] = 0;
} else {
ld->alpha[i] = alpha;
ld->cov_alpha[i] = cov0_alpha * square(sigma);
ld->alpha_valid[i] = 1;
}
/* printf("---------- i = %d alpha = %f sigma=%f cov_alpha = %f\n", i, alpha, ld->cov_alpha[i]);*/
}
}
/** A very cool algorithm for finding the orientation */
void filter_orientation(double theta0, double rho0, size_t n,
const double*thetas, const double*rhos, double *alpha, double*cov0_alpha ) {
egsl_push();
/* Y = L x + R epsilon */
val Y = zeros(n,1);
val L = ones(n,1);
val R = zeros(n,n+1);
size_t i; for(i=0;i<n;i++) {
*egsl_atmp(Y, i, 0) = (rhos[i]-rho0)/(thetas[i]-theta0);
*egsl_atmp(R, i, 0) = -1/(thetas[i]-theta0);
*egsl_atmp(R, i, i+1) = +1/(thetas[i]-theta0);
}
val eRinv = inv(m(R, tr(R)));
val vcov_f1 = inv(m3(tr(L),eRinv, L));
val vf1 = m4(vcov_f1, tr(L), eRinv, Y);
double cov_f1 = *egsl_atmp(vcov_f1,0,0);
double f1 = *egsl_atmp(vf1,0,0);
*alpha = theta0 - atan(f1/rho0);
if(cos(*alpha)*cos(theta0)+sin(*alpha)*sin(theta0)>0)
*alpha = *alpha + M_PI;
double dalpha_df1 = rho0 / (square(rho0) + square(f1));
double dalpha_drho = -f1 / (square(rho0) + square(f1));
*cov0_alpha = square(dalpha_df1) * cov_f1 + square(dalpha_drho);
if(gsl_isnan(*alpha)) {
egsl_print("Y",Y);
egsl_print("L",L);
egsl_print("R",R);
egsl_print("eRinv",eRinv);
egsl_print("vcov_f1",vcov_f1);
printf(" f1 = %f cov =%f \n", f1,cov_f1);
printf(" f1/rho = %f \n", f1/rho0);
printf(" atan = %f \n", atan(f1/rho0));
printf(" theta0= %f \n", theta0);
}
egsl_pop();
/*
// printf("dalpha_df1 = %f dalpha_drho = %f\n",dalpha_df1,dalpha_drho);
// printf("f1 = %f covf1 = %f alpha = %f cov_alpha = %f\n ",f1,cov_f1,*alpha,*cov0_alpha);
// printf("sotto = %f\n ",(square(rho0) + square(f1)));
// printf(" alpha = %f sigma= %f°\n", *alpha, rad2deg(0.01*sqrt(*cov0_alpha)));
printf("l= ");
gsl_matrix_fprintf(stdout, l, "%f");
printf("\ny= ");
gsl_matrix_fprintf(stdout, y, "%f");
printf("\nr= ");
gsl_matrix_fprintf(stdout, r, "%f");
printf("\ninv(r*r)= ");
gsl_matrix_fprintf(stdout, Rinv, "%f");
printf("\nf1 = %lf ",f1);
printf("\ncov_f1 = %lf ",cov_f1);
*/
}
/* indexes: an array of size "max_num*2" */
void find_neighbours(LDP ld, int i, int max_num, int*indexes, size_t*num_found) {
*num_found = 0;
int up = i;
while ((up+1 <= i+max_num) && (up+1<ld->nrays) && ld_valid_ray(ld,up+1)
&& (ld->cluster[up+1] == ld->cluster[i])) {
up+=1;
indexes[(*num_found)++] = up;
}
int down = i;
while ((down >= i-max_num) && (down-1>=0) && ld_valid_ray(ld,down-1) &&
(ld->cluster[down-1] == ld->cluster[i])) {
down-=1;
indexes[(*num_found)++] = down;
}
}
| {
"alphanum_fraction": 0.6116920152,
"avg_line_length": 28.0533333333,
"ext": "c",
"hexsha": "5c3eb8998d50b87ba69b2afd2ca6e6c4d08eda13",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alecone/ROS_project",
"max_forks_repo_path": "src/csm/sm/csm/orientation.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "alecone/ROS_project",
"max_issues_repo_path": "src/csm/sm/csm/orientation.c",
"max_line_length": 100,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f058fb0bc5c4c9b1a590b7536f75b83af35b7785",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alecone/ROS_project",
"max_stars_repo_path": "src/csm/sm/csm/orientation.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1542,
"size": 4208
} |
#ifndef SOLVER_H
#define SOLVER_H
#if PY_MAJOR_VERSION >= 3
#define PY3K
#endif
// include user-defined headers
#include "common.h"
#include "utils.h"
#include <gsl/gsl_errno.h>
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
typedef struct _TOV_Tuple {
double a;
double b;
double c;
} Pair;
#endif | {
"alphanum_fraction": 0.7089783282,
"avg_line_length": 14.6818181818,
"ext": "h",
"hexsha": "ac7997b4a524bf9fbb7b0685689aa0c25dc3783e",
"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": "f3510c4d0628374998e4cb102f9beabc701e02f4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lujiajing1126/tov-solver",
"max_forks_repo_path": "src/solver.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f3510c4d0628374998e4cb102f9beabc701e02f4",
"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": "lujiajing1126/tov-solver",
"max_issues_repo_path": "src/solver.h",
"max_line_length": 31,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "f3510c4d0628374998e4cb102f9beabc701e02f4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lujiajing1126/tov-solver",
"max_stars_repo_path": "src/solver.h",
"max_stars_repo_stars_event_max_datetime": "2019-02-22T05:46:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-02-22T05:46:28.000Z",
"num_tokens": 93,
"size": 323
} |
/* examples/C/ssmfe/precond_ssmfe.c */
/* Laplacian on a square grid (using SPRAL_SSMFE routines) */
#include "spral.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <cblas.h>
/* Header that implements Laplacian and preconditioners */
#include "laplace2d.h"
int main(void) {
const int m = 20; /* grid points along each side */
const int n = m*m; /* problem size */
const int nep = 5; /* eigenpairs wanted */
double lambda[2*nep]; /* eigenvalues */
double X[2*nep][n]; /* eigenvectors */
struct spral_ssmfe_rcid rci; /* reverse communication data */
struct spral_ssmfe_options options; /* options */
void *keep; /* private data */
struct spral_ssmfe_inform inform; /* information */
/* Initialize options to default values */
spral_ssmfe_default_options(&options);
/* gap between the last converged eigenvalue and the rest of the spectrum
* must be at least 0.1 times average gap between computed eigenvalues */
options.left_gap = -0.1;
rci.job = 0; keep = NULL;
while(true) { /* reverse communication loop */
spral_ssmfe_standard_double(&rci, nep, 2*nep, lambda, n, &X[0][0], n,
&keep, &options, &inform);
switch ( rci.job ) {
case 1:
apply_laplacian(m, m, rci.nx, rci.x, rci.y);
break;
case 2:
apply_gauss_seidel_step(m, m, rci.nx, rci.x, rci.y);
break;
default:
goto finished;
}
}
finished:
printf("%d eigenpairs converged in %d iterations\n", inform.left, inform.iteration);
for(int i=0; i<inform.left; i++)
printf(" lambda[%1d] = %13.7e\n", i, lambda[i]);
spral_ssmfe_free_double(&keep, &inform);
/* Success */
return 0;
}
| {
"alphanum_fraction": 0.6034197463,
"avg_line_length": 33.5740740741,
"ext": "c",
"hexsha": "9d7384afacb4b3bf71e9a15b46703bbcfcd86ad9",
"lang": "C",
"max_forks_count": 19,
"max_forks_repo_forks_event_max_datetime": "2022-02-28T14:58:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-09-30T20:52:47.000Z",
"max_forks_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "mjacobse/spral",
"max_forks_repo_path": "examples/C/ssmfe/precond_ssmfe.c",
"max_issues_count": 51,
"max_issues_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898",
"max_issues_repo_issues_event_max_datetime": "2022-03-11T12:52:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-09-20T19:01:18.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "mjacobse/spral",
"max_issues_repo_path": "examples/C/ssmfe/precond_ssmfe.c",
"max_line_length": 87,
"max_stars_count": 76,
"max_stars_repo_head_hexsha": "9bf003b2cc199928ec18c967ce0e009d98790898",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mjacobse/spral",
"max_stars_repo_path": "examples/C/ssmfe/precond_ssmfe.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T00:11:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-10-03T13:58:37.000Z",
"num_tokens": 503,
"size": 1813
} |
/* This module contains the routine rotCurveSpline, which takes a
tabulated rotaiton curve and calculates a B-spline fit to it and
its derivatives. */
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_multifit.h>
#include "rotCurveSpline.h"
struct dpsidr_params {
gsl_bspline_workspace *wksp;
#ifdef GSL1
gsl_bspline_deriv_workspace *dwksp;
#endif
gsl_vector *B, *coef;
gsl_matrix *dB, *cov;
};
double dpsidr(double r, void *params) {
double vphi, err;
struct dpsidr_params *p = (struct dpsidr_params *) params;
#ifdef GSL1
gsl_bspline_deriv_eval(log(r), 2, p->dB, p->wksp, p->dwksp);
#else
gsl_bspline_deriv_eval(log(r), 2, p->dB, p->wksp);
#endif
gsl_matrix_get_col(p->B, p->dB, 0);
gsl_multifit_linear_est(p->B, p->coef, p->cov, &vphi, &err);
return(-vphi*vphi/r);
}
void
rotCurveSpline(const double *rTab, const double *vTab,
const unsigned long nTab,
const unsigned long bspline_degree,
const unsigned long bspline_breakpoints,
const double *r, const unsigned long nr,
double *vphi, double *psi,
double *beta) {
gsl_vector *xInput, *vInput, *coef, *B, *bkpt_vec;
gsl_matrix *dB, *cov, *pred;
gsl_bspline_workspace *wksp;
#ifdef GSL1
gsl_bspline_deriv_workspace *dwksp;
#endif
gsl_multifit_linear_workspace *mw;
gsl_integration_workspace *intwksp;
gsl_function dpsidr_func;
struct dpsidr_params params;
double x0, x1, v0, bkpt_sum_target, sum, x, Bij, chisq;
double dvphidlogr, err, psiInt;
unsigned long bspline_ncoef, i, j, ptr;
/* Safety check: make sure we have enough data points for the choice
of degree and breakpoints */
bspline_ncoef = bspline_breakpoints + bspline_degree - 2;
if (bspline_ncoef > nTab) {
fprintf(stderr, "Error: %lu data points for %lu coefficients; ndata must be >= ncoef = nbreakpoints + degree - 2\n", nTab, bspline_ncoef);
exit(1);
}
/* Initialize the GSL vectors to hold the data table */
xInput = gsl_vector_alloc(nTab);
vInput = gsl_vector_alloc(nTab);
for (i=0; i<nTab; i++) {
gsl_vector_set(xInput, i, log(rTab[i]));
gsl_vector_set(vInput, i, vTab[i]);
}
/* Allocate workspace for and associated stuff for B-spline solver */
wksp = gsl_bspline_alloc(bspline_degree, bspline_breakpoints);
#ifdef GSL1
dwksp = gsl_bspline_deriv_alloc(bspline_degree);
#endif
B = gsl_vector_alloc(bspline_ncoef);
dB = gsl_matrix_alloc(bspline_ncoef, 3);
/* Compute breakpoint locations using the method of Gans & Gill,
Applied Spectroscopy, 38, 297, 1984. The formula for
uniformly-spaced data is that two successive breakpoints t_i and t_i+1
should be separated by an amount such that
sum_{x=t_i}^{x=t_i+1} f(x)^0.5 dx = S_T
where
S_T = (1/(m+1)) sum f(x_i)^0.5 dx.
Here the first sum runs over all data points between t_i and
t_i+1, and the second runs all data points; m is the number of
knots, and f(x) is the function to be approximated. This formula
assumes uniform spacing dx, but here it is modified for
non-uniform data spacing such that dx is taken to be the mean
size of the data interval, averaging over the left and right
sides.
*/
v0 = gsl_vector_get(vInput, 0);
x0 = gsl_vector_get(xInput, 0);
x1 = gsl_vector_get(xInput, 1);
bkpt_sum_target = sqrt(v0) * (x1-x0);
for (i=1; i<nTab-1; i++) {
v0 = gsl_vector_get(vInput, i);
x0 = gsl_vector_get(xInput, i-1);
x1 = gsl_vector_get(xInput, i+1);
bkpt_sum_target += sqrt(v0) * 0.5 * (x1-x0);
}
v0 = gsl_vector_get(vInput, nTab-1);
x0 = gsl_vector_get(xInput, nTab-2);
x1 = gsl_vector_get(xInput, nTab-1);
bkpt_sum_target += sqrt(v0) * (x1-x0);
bkpt_sum_target /= (bspline_breakpoints + 1);
bkpt_vec = gsl_vector_alloc(bspline_breakpoints);
gsl_vector_set(bkpt_vec, 0, gsl_vector_get(xInput, 0));
gsl_vector_set(bkpt_vec, bspline_breakpoints-1,
gsl_vector_get(xInput, nTab-1));
ptr=0;
for (i=1; i<bspline_breakpoints-2; i++) {
sum = 0;
while (sum < bkpt_sum_target) {
if (ptr == 0) {
v0 = gsl_vector_get(vInput, 0);
x0 = gsl_vector_get(xInput, 0);
x1 = gsl_vector_get(xInput, 1);
sum += sqrt(v0) * (x1-x0);
} else if (ptr == nTab-1) {
v0 = gsl_vector_get(vInput, nTab-1);
x0 = gsl_vector_get(xInput, nTab-2);
x1 = gsl_vector_get(xInput, nTab-1);
sum += sqrt(v0) * (x1-x0);
} else {
v0 = gsl_vector_get(vInput, ptr);
x0 = gsl_vector_get(xInput, ptr-1);
x1 = gsl_vector_get(xInput, ptr+1);
sum += sqrt(v0) * 0.5 * (x1-x0);
}
ptr++;
if (ptr == nTab) break;
}
if (ptr == nTab) break;
gsl_vector_set(bkpt_vec, i, gsl_vector_get(xInput, ptr-1));
}
gsl_vector_set(bkpt_vec, i, gsl_vector_get(xInput, nTab-1));
/* Construct knots vector */
gsl_bspline_knots(bkpt_vec, wksp);
/* Allocate workspace for the least squares fit to find the B spline
coefficients; pred is the predictor variable matrix, cov is the
covariance matrix, coef is the vector of best-fitting
coefficients, and mw is the workspace used by the gsl fitter */
pred = gsl_matrix_alloc(nTab, bspline_ncoef);
mw = gsl_multifit_linear_alloc(nTab, bspline_ncoef);
cov = gsl_matrix_alloc(bspline_ncoef, bspline_ncoef);
coef = gsl_vector_alloc(bspline_ncoef);
/* Load the predictor matrix with the B spline functions evaluated
at the input positions */
for (i=0; i<nTab; i++) {
x = gsl_vector_get(xInput, i); /* Position of data point */
gsl_bspline_eval(x, B, wksp); /* Evaluate B splines at this
position */
/* Load predictor matrix */
for (j=0; j<bspline_ncoef; j++) {
Bij = gsl_vector_get(B, j);
gsl_matrix_set(pred, i, j, Bij);
}
}
/* Perform least squares fit to find coefficients */
gsl_multifit_linear(pred, vInput, coef, cov, &chisq, mw);
/* Compute B-spline fits at input positions */
for (i=0; i<nr; i++) {
#ifdef GSL1
gsl_bspline_deriv_eval(log(r[i]), 2, dB, wksp, dwksp);
#else
gsl_bspline_deriv_eval(log(r[i]), 2, dB, wksp);
#endif
gsl_matrix_get_col(B, dB, 0);
gsl_multifit_linear_est(B, coef, cov, vphi+i, &err);
gsl_matrix_get_col(B, dB, 1);
gsl_multifit_linear_est(B, coef, cov, &dvphidlogr, &err);
beta[i] = dvphidlogr / vphi[i];
}
/* Compute potential at cell centers and edges by numerically
integrating from grid edge to center */
intwksp = gsl_integration_workspace_alloc(4096);
dpsidr_func.function = &dpsidr;
dpsidr_func.params = ¶ms;
params.wksp = wksp;
#ifdef GSL1
params.dwksp = dwksp;
#endif
params.B = B;
params.coef = coef;
params.dB = dB;
params.cov = cov;
psi[nr-1] = 0.0;
for (i=nr-1; i>0; i--) {
gsl_integration_qag(&dpsidr_func, r[i], r[i-1],
1e-6*vphi[i]*vphi[i]*
(r[i+1]-r[i]),
1e-6, 4096, 6, intwksp, &psiInt, &err);
psi[i-1] = psi[i] - psiInt;
}
/* Free memory */
gsl_matrix_free(pred);
gsl_vector_free(bkpt_vec);
gsl_vector_free(xInput);
gsl_vector_free(vInput);
gsl_multifit_linear_free(mw);
gsl_vector_free(coef);
gsl_vector_free(B);
gsl_matrix_free(dB);
gsl_matrix_free(cov);
gsl_bspline_free(wksp);
#ifdef GSL1
gsl_bspline_deriv_free(dwksp);
#endif
gsl_integration_workspace_free(intwksp);
}
| {
"alphanum_fraction": 0.6801974767,
"avg_line_length": 32.4088888889,
"ext": "c",
"hexsha": "e54d595667b1eab08e36adf67c3ad0f5d33075a6",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-11-20T02:11:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-19T04:41:37.000Z",
"max_forks_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "franciscaconcha/amuse-vader",
"max_forks_repo_path": "src/amuse/community/vader/src/rotCurveSpline.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"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": "franciscaconcha/amuse-vader",
"max_issues_repo_path": "src/amuse/community/vader/src/rotCurveSpline.c",
"max_line_length": 142,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "franciscaconcha/amuse-vader",
"max_stars_repo_path": "src/amuse/community/vader/src/rotCurveSpline.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2316,
"size": 7292
} |
#pragma once
#include <chrono>
#include <fmt/printf.h>
#include <gsl/gsl-lite.hpp>
namespace angonoka::cli {
/**
Pretty-print values.
This class is mostly used for specializing user-defined
formatters for the fmt library. We don't want to specialize
the formatter for the original type because we might not
always want a human-readable output.
Instead of specializing fmt::formatter<std::chrono::seconds>
we specialize fmt::formatter<humanize<std::chrono::seconds>>
thus not interfering with the original formatter.
@var value Value to be pretty-printed
*/
template <typename T> struct humanize {
T value;
};
template <typename T> humanize(T) -> humanize<T>;
namespace detail {
/**
Enum that tells if a human-readable duration
printing should continue parsing durations of a
smaller scale or stop.
*/
enum DurationParsing : bool { continue_, stop };
/**
Helper function to print durations in human-readable form.
@param article "a" or "an"
@param name Duration (seconds, minutes, etc)
@return Formatter function
*/
template <typename T>
constexpr auto
humanize_duration(gsl::czstring article, gsl::czstring name)
{
return [=](auto total, auto& ctx) {
const auto dur = std::chrono::round<T>(total);
if (dur == dur.zero()) return DurationParsing::continue_;
const auto ticks = dur.count();
if (ticks == 1) {
fmt::format_to(
ctx.out(),
"about {} {}",
article,
name);
} else {
fmt::format_to(ctx.out(), "{} {}s", ticks, name);
}
return DurationParsing::stop;
};
}
} // namespace detail
} // namespace angonoka::cli
namespace fmt {
using angonoka::cli::humanize;
/**
User-defined formatter for std::chrono durations.
*/
template <typename... Ts>
struct fmt::formatter<humanize<std::chrono::duration<Ts...>>> {
using value_type = humanize<std::chrono::duration<Ts...>>;
static constexpr auto parse(format_parse_context& ctx)
{
return ctx.end();
}
template <typename FormatContext>
constexpr auto format(const value_type& obj, FormatContext& ctx)
{
using angonoka::cli::detail::humanize_duration;
using namespace std::literals::chrono_literals;
using namespace std::chrono;
constexpr auto min_threshold = 5s;
if (obj.value <= min_threshold)
return format_to(ctx.out(), "a few seconds");
[&](auto&&... fns) {
(fns(obj.value, ctx) || ...);
}(humanize_duration<months>("a", "month"),
humanize_duration<days>("a", "day"),
humanize_duration<hours>("an", "hour"),
humanize_duration<minutes>("a", "minute"),
humanize_duration<seconds>("a", "second"));
return ctx.out();
}
};
} // namespace fmt
| {
"alphanum_fraction": 0.599801061,
"avg_line_length": 30.4646464646,
"ext": "h",
"hexsha": "efdc92ef127343c1c6ac6a68037ae3de297fa815",
"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": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "coffee-lord/angonoka",
"max_forks_repo_path": "src/cli/humanize.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_issues_repo_issues_event_max_datetime": "2022-02-12T19:55:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-02-12T19:52:27.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "coffee-lord/angonoka",
"max_issues_repo_path": "src/cli/humanize.h",
"max_line_length": 69,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "a8a4a79da4092630c5243c2081f92ba39d0b056c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "coffee-lord/angonoka",
"max_stars_repo_path": "src/cli/humanize.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-21T21:53:24.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-10-23T18:05:25.000Z",
"num_tokens": 669,
"size": 3016
} |
#pragma once
#include "RTTI.h"
#include <stack>
#include <gsl\gsl>
#include <GL/gl3w.h>
#include "Framebuffer.h"
namespace Library
{
class RenderTarget : public RTTI
{
RTTI_DECLARATIONS(RenderTarget, RTTI)
public:
RenderTarget() = default;
RenderTarget(const RenderTarget&) = delete;
RenderTarget(RenderTarget&&) = default;
RenderTarget& operator=(const RenderTarget&) = delete;
RenderTarget& operator=(RenderTarget&&) = default;
virtual ~RenderTarget() = default;
void GenTexture(GLuint width, GLuint height);
GLuint GetTextureID();
void Begin();
void End();
void RebindCurrentRenderTargets();
protected:
std::shared_ptr<Framebuffer> mDrawTarget;
private:
static std::stack<std::shared_ptr<Framebuffer>> sRenderTargetStack;
};
} | {
"alphanum_fraction": 0.7302204929,
"avg_line_length": 20.8378378378,
"ext": "h",
"hexsha": "1f94051f1d69f5f1893c88e496a534343e9b20e5",
"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": "628e9aed116022175cc0c59c88ace7688309628c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "DakkyDaWolf/OpenGL",
"max_forks_repo_path": "source/Library.Shared/RenderTarget.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c",
"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": "DakkyDaWolf/OpenGL",
"max_issues_repo_path": "source/Library.Shared/RenderTarget.h",
"max_line_length": 69,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "628e9aed116022175cc0c59c88ace7688309628c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "DakkyDaWolf/OpenGL",
"max_stars_repo_path": "source/Library.Shared/RenderTarget.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 190,
"size": 771
} |
/*
Copyright 2016, D. E. Shaw Research.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of D. E. Shaw Research nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
#pragma GCC diagnostic ignored "-Wconversion"
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wexpansion-to-defined"
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#ifdef _MSC_FULL_VER
// 4311 - 'type cast': pointer truncation from 'char[54]' to 'long'
// 4202 - nonstandard extension used: non-constant aggregate initializer
// 4127 - conditional expression is constant
// 4302 - 'type cast': truncation from 'const char *' to 'long'
#pragma warning(push)
#pragma warning(disable : 4311 4204 4127 4302)
#endif
#include "rng/config.h"
#include "Random123/conventional/gsl_cbrng.h"
#include "ut_gsl.h"
#include <assert.h>
#include <gsl/gsl_randist.h>
#include <stdio.h>
/* Exercise the GSL_CBRNG macro */
GSL_CBRNG(cbrng, threefry4x64); /* creates gsl_rng_cbrng */
int main(int argc, char **argv) {
int i;
gsl_rng *r;
gsl_rng *rcopy;
unsigned long x;
rngRemember(unsigned long save);
rngRemember(unsigned long saved[5]);
double sum = 0.;
(void)argc;
(void)argv; /* unused */
/* Silence an unused-parameter warning. */
(void)argc;
r = gsl_rng_alloc(gsl_rng_cbrng);
assert(gsl_rng_min(r) == 0);
assert(gsl_rng_max(r) == 0xffffffffUL); /* Not necessarily ~0UL */
assert(gsl_rng_size(r) > 0);
printf("%s\nulongs from %s in initial state\n", argv[0], gsl_rng_name(r));
for (i = 0; i < 5; i++) {
x = gsl_rng_get(r);
rngRemember(saved[i] = x);
printf("%d: 0x%lx\n", i, x);
assert(x != 0);
}
printf("uniforms from %s\n", gsl_rng_name(r));
for (i = 0; i < 5; i++) {
double z = gsl_rng_uniform(r);
sum += z;
printf("%d: %.4g\n", i, z);
}
assert(sum < 0.9 * 5 && sum > 0.1 * 5 &&
(long)"sum must be reasonably close to 0.5*number of trials");
rngRemember(save =) gsl_rng_get(r);
gsl_rng_set(r, 0xdeadbeef); /* set a non-zero seed */
printf("ulongs from %s after seed\n", gsl_rng_name(r));
for (i = 0; i < 5; i++) {
x = gsl_rng_get(r);
printf("%d: 0x%lx\n", i, x);
assert(x != 0);
}
/* make a copy of the total state */
rcopy = gsl_rng_alloc(gsl_rng_cbrng);
gsl_rng_memcpy(rcopy, r);
printf("uniforms from %s\n", gsl_rng_name(r));
sum = 0.;
for (i = 0; i < 5; i++) {
double x2 = gsl_rng_uniform(r);
rngRemember(double y = gsl_rng_uniform(rcopy));
printf("%d: %.4g\n", i, x2);
sum += x2;
assert(x2 == y);
}
assert(gsl_rng_get(r) != save);
assert(sum < 0.9 * 5 && sum > 0.1 * 5 &&
(long)"sum must be reasonably close to 0.5*number of trials");
/* gsl_rng_set(*, 0) is supposed to recover the default seed */
gsl_rng_set(r, 0);
printf("ulongs from %s after restore to initial\n", gsl_rng_name(r));
for (i = 0; i < 5; i++) {
x = gsl_rng_get(r);
assert(x == saved[i]);
printf("%d: 0x%lx\n", i, x);
assert(x != 0);
}
printf("uniforms from %s\n", gsl_rng_name(r));
for (i = 0; i < 5; i++) {
printf("%d: %.4g\n", i, gsl_rng_uniform(r));
}
gsl_rng_free(rcopy);
gsl_rng_free(r);
printf("ut_gsl: OK\n");
return 0;
}
#ifdef _MSC_FULL_VER
#pragma warning(pop)
#endif
#ifdef __clang__
// Restore clang diagnostics to previous state.
#pragma clang diagnostic pop
#endif
#ifdef __GNUC__
// Restore GCC diagnostics to previous state.
#pragma GCC diagnostic pop
#endif
| {
"alphanum_fraction": 0.6901408451,
"avg_line_length": 30.8113207547,
"ext": "c",
"hexsha": "6475d484be524997ca13d1e46e7b2a7beed44163",
"lang": "C",
"max_forks_count": 31,
"max_forks_repo_forks_event_max_datetime": "2021-09-08T02:33:34.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-03-02T19:51:15.000Z",
"max_forks_repo_head_hexsha": "b8e3bcd38ab739615c1df506268d70bf99929efa",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "jhchang-lanl/Draco",
"max_forks_repo_path": "src/rng/test/ut_gsl.c",
"max_issues_count": 848,
"max_issues_repo_head_hexsha": "b8e3bcd38ab739615c1df506268d70bf99929efa",
"max_issues_repo_issues_event_max_datetime": "2022-01-11T18:56:50.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-01-16T01:03:38.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "jhchang-lanl/Draco",
"max_issues_repo_path": "src/rng/test/ut_gsl.c",
"max_line_length": 76,
"max_stars_count": 43,
"max_stars_repo_head_hexsha": "b8e3bcd38ab739615c1df506268d70bf99929efa",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "jhchang-lanl/Draco",
"max_stars_repo_path": "src/rng/test/ut_gsl.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T07:53:43.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-02-17T23:47:36.000Z",
"num_tokens": 1370,
"size": 4899
} |
#include <linux/types.h>
#include "sweeny_bfs.h"
#include <stdio.h>
#include "timeseries.h"
#include "extract_args.h"
#include <math.h>
#include <gsl/gsl_rng.h>
#ifdef SEQUENTIAL
char impl_title[] = "Sequential BFS implementation";
#define TS_FILE_D "../time_series/sbfs/simulation_l%u_q%.4f_b%.4f_c%.4f_s%u.hdf5"
#define INFO_STRING "*Sequential BFS implementation of Sweeny's algorithm*\n"
#define INIT init_sweeny_sbfs
#define SIMULATE simulate_sweeny_sbfs
#define DESTROY destroy_sweeny_sbfs
#else
char impl_title[] = "Interleaved BFS implementation";
#define TS_FILE_D "../time_series/ibfs/simulation_l%u_q%.4f_b%.4f_c%.4f_s%u.hdf5"
#define INFO_STRING "*Interleaved BFS implementation of Sweeny's algorithm*\n"
#define INIT init_sweeny_ibfs
#define SIMULATE simulate_sweeny_ibfs
#define DESTROY destroy_sweeny_ibfs
#endif
#define BUF_LEN 512
char fn[BUF_LEN];
char verbose=0;
__u32 DX;
__u32 N;
__u32 seed;
double q;
double coupling;
double beta;
double v;
double K;
__u32 steps;
__s8 *bonds;
gsl_rng * r;
char *filename;
__u32 cutoff;
__u32 *num_bonds , *num_cluster, *size_giant;
__u64 *sec_cs_moment,*four_cs_moment;
int main(int argc, char *argv[])
{
if(!extractArgs(argc, argv,impl_title))
return EXIT_FAILURE;
snprintf(fn,BUF_LEN,TS_FILE_D,DX,q,beta,coupling,seed);
if(!init_observables())
return EXIT_FAILURE;
if(!INIT(q,DX,beta,coupling,cutoff,steps,seed,num_bonds,num_cluster,size_giant,sec_cs_moment,four_cs_moment))
return EXIT_FAILURE;
if(!SIMULATE())
return EXIT_FAILURE;
DESTROY();
save_timeseries();
destroy_observables();
return EXIT_SUCCESS;
}
/******************************************************************************
*****************************************************************************/
| {
"alphanum_fraction": 0.6840354767,
"avg_line_length": 27.7538461538,
"ext": "c",
"hexsha": "e46ea006743b692c22d8b40a8984b56822e2a164",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2017-04-10T14:18:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-10T14:18:57.000Z",
"max_forks_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ermeel86/sweeny",
"max_forks_repo_path": "src/sy_bfs_mc.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_issues_repo_issues_event_max_datetime": "2018-08-20T09:32:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-08-19T09:29:25.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ernmeel/sweeny",
"max_issues_repo_path": "src/sy_bfs_mc.c",
"max_line_length": 113,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ernmeel/sweeny",
"max_stars_repo_path": "src/sy_bfs_mc.c",
"max_stars_repo_stars_event_max_datetime": "2017-04-10T14:18:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-03T10:57:43.000Z",
"num_tokens": 486,
"size": 1804
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_sort.h>
#include "cosmocalc.h"
static double linear_powspec_norm;
static gsl_spline *cosmocalc_sigmaR_spline = NULL;
static gsl_interp_accel *cosmocalc_sigmaR_acc = NULL;
static gsl_spline *cosmocalc_Rsigma_spline = NULL;
static gsl_interp_accel *cosmocalc_Rsigma_acc = NULL;
static void init_cosmocalc_peakheight_table(void);
static void init_cosmocalc_peakheight_table(void)
{
static int initFlag = 1;
static int currCosmoNum;
double sigmar_table[COSMOCALC_PEAKHEIGHT_TABLE_LENGTH];
double topHatRad_table[COSMOCALC_PEAKHEIGHT_TABLE_LENGTH];
size_t sindex[COSMOCALC_PEAKHEIGHT_TABLE_LENGTH];
double tmpDouble[COSMOCALC_PEAKHEIGHT_TABLE_LENGTH];
long i;
double rad;
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
linear_powspec_norm = cosmoData.Sigma8*cosmoData.Sigma8/tophatradnorm_linear_powspec_exact_nonorm(8.0);
for(i=0;i<COSMOCALC_PEAKHEIGHT_TABLE_LENGTH;++i)
{
rad = log(PH_R_MAX/PH_R_MIN)/(COSMOCALC_PEAKHEIGHT_TABLE_LENGTH-1.0)*((double) i) + log(PH_R_MIN);
topHatRad_table[i] = rad;
sigmar_table[i] = log(sqrt(linear_powspec_norm*tophatradnorm_linear_powspec_exact_nonorm(exp(rad))));
}
//init the spline and accelerators
if(cosmocalc_sigmaR_spline != NULL)
gsl_spline_free(cosmocalc_sigmaR_spline);
cosmocalc_sigmaR_spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_PEAKHEIGHT_TABLE_LENGTH));
gsl_spline_init(cosmocalc_sigmaR_spline,topHatRad_table,sigmar_table,(size_t) (COSMOCALC_PEAKHEIGHT_TABLE_LENGTH));
if(cosmocalc_sigmaR_acc != NULL)
gsl_interp_accel_reset(cosmocalc_sigmaR_acc);
else
cosmocalc_sigmaR_acc = gsl_interp_accel_alloc();
//reverse the table
gsl_sort_index(sindex,sigmar_table,(size_t) 1,(size_t) (COSMOCALC_PEAKHEIGHT_TABLE_LENGTH));
for(i=0;i<COSMOCALC_PEAKHEIGHT_TABLE_LENGTH;++i)
tmpDouble[i] = sigmar_table[sindex[i]];
for(i=0;i<COSMOCALC_PEAKHEIGHT_TABLE_LENGTH;++i)
sigmar_table[i] = tmpDouble[i];
for(i=0;i<COSMOCALC_PEAKHEIGHT_TABLE_LENGTH;++i)
tmpDouble[i] = topHatRad_table[sindex[i]];
for(i=0;i<COSMOCALC_PEAKHEIGHT_TABLE_LENGTH;++i)
topHatRad_table[i] = tmpDouble[i];
//init the spline and accelerators
if(cosmocalc_Rsigma_spline != NULL)
gsl_spline_free(cosmocalc_Rsigma_spline);
cosmocalc_Rsigma_spline = gsl_spline_alloc(GSL_SPLINE_TYPE,(size_t) (COSMOCALC_PEAKHEIGHT_TABLE_LENGTH));
gsl_spline_init(cosmocalc_Rsigma_spline,sigmar_table,topHatRad_table,(size_t) (COSMOCALC_PEAKHEIGHT_TABLE_LENGTH));
if(cosmocalc_Rsigma_acc != NULL)
gsl_interp_accel_reset(cosmocalc_Rsigma_acc);
else
cosmocalc_Rsigma_acc = gsl_interp_accel_alloc();
}
}
double sigmaRtophat_exact(double topHatRad, double a)
{
static int initFlag = 1;
static int currCosmoNum;
static double linear_powspec_norm;
double gf;
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
linear_powspec_norm = cosmoData.Sigma8*cosmoData.Sigma8/tophatradnorm_linear_powspec_exact_nonorm(8.0);
}
gf = growth_function(a);
return sqrt(linear_powspec_norm*tophatradnorm_linear_powspec_exact_nonorm(topHatRad))*gf;
}
double sigmaRtophat(double topHatRad, double a)
{
static int initFlag = 1;
static int currCosmoNum;
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
init_cosmocalc_peakheight_table();
}
return exp(gsl_spline_eval(cosmocalc_sigmaR_spline,log(topHatRad),cosmocalc_sigmaR_acc))*growth_function(a);
}
double sigmaMtophat(double m, double a)
{
return sigmaRtophat(pow(m/(4.0/3.0*M_PI*RHO_CRIT*cosmoData.OmegaM),1.0/3.0),a);
}
double sigmaMtophat_exact(double m, double a)
{
return sigmaRtophat_exact(pow(m/(4.0/3.0*M_PI*RHO_CRIT*cosmoData.OmegaM),1.0/3.0),a);
}
double inverse_sigmaRtophat(double sigmaR, double a)
{
static int initFlag = 1;
static int currCosmoNum;
if(initFlag == 1 || currCosmoNum != cosmoData.cosmoNum)
{
initFlag = 0;
currCosmoNum = cosmoData.cosmoNum;
init_cosmocalc_peakheight_table();
}
return exp(gsl_spline_eval(cosmocalc_Rsigma_spline,log(sigmaR/growth_function(a)),cosmocalc_Rsigma_acc));
}
double inverse_sigmaMtophat(double sigmaR, double a)
{
return (4.0/3.0*M_PI*RHO_CRIT*cosmoData.OmegaM)*pow(inverse_sigmaRtophat(sigmaR,a),3.0);
}
double inverse_nuMtophat(double nu, double a)
{
return (4.0/3.0*M_PI*RHO_CRIT*cosmoData.OmegaM)*pow(inverse_sigmaRtophat(DELTAC/nu,a),3.0);
}
double inverse_nuRtophat(double nu, double a)
{
return inverse_sigmaRtophat(DELTAC/nu,a);
}
| {
"alphanum_fraction": 0.7361441013,
"avg_line_length": 32.8051948052,
"ext": "c",
"hexsha": "e38b9f03a075cf060e54e94eea3fd66579be14ab",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z",
"max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "beckermr/cosmocalc",
"max_forks_repo_path": "src/peakheight.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "beckermr/cosmocalc",
"max_issues_repo_path": "src/peakheight.c",
"max_line_length": 121,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "beckermr/cosmocalc",
"max_stars_repo_path": "src/peakheight.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1566,
"size": 5052
} |
#ifdef _MSC_VER
#if _MSC_VER >= 1910
#include <CppCoreCheck/warnings.h>
#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)
#endif // _MSC_VER >= 1910
#endif // _MSC_VER
#include <gsl/gsl>
#ifdef _MSC_VER
#if _MSC_VER >= 1910
#pragma warning(default: ALL_CPPCORECHECK_WARNINGS)
#endif // _MSC_VER >= 1910
#endif // _MSC_VER
| {
"alphanum_fraction": 0.7469512195,
"avg_line_length": 19.2941176471,
"ext": "h",
"hexsha": "38084f0b3cbda1ae74d314e773eba027cb502215",
"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": "e3ed0472f3ca449c3082cae5b5d9629e2e8e1699",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "TomoyukiAota/CoreCheckerAndGsl",
"max_forks_repo_path": "include/gsl_wrapper.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e3ed0472f3ca449c3082cae5b5d9629e2e8e1699",
"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": "TomoyukiAota/CoreCheckerAndGsl",
"max_issues_repo_path": "include/gsl_wrapper.h",
"max_line_length": 51,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e3ed0472f3ca449c3082cae5b5d9629e2e8e1699",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "TomoyukiAota/CoreCheckerAndGsl",
"max_stars_repo_path": "include/gsl_wrapper.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 97,
"size": 328
} |
#include "odeint.h"
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <float.h>
#include <stdio.h>
#if HAVE_MKL_CBLAS
#include <mkl_cblas.h>
#elif HAVE_OPENBLAS
#include <openblas/cblas.h>
#else
#include <cblas.h>
#endif
/* TODO:
* - implicit methods
* - off-GPU
*/
/**
* The maximum number of steps.
*/
#define MAX_STEP 8
/**
* @name: Name of the method
* @steps: Number of steps
* @last_step_is_update: Indicate if the last step correspond to the update, in
* which case no final update is computed and the last transient 'y' is used.
* @c: Whole step weight
* @a: Previous steps weights
* @b: Final step weights
* @order: Order of the final update used to adjust the step size
* @e: Error estimate
* @error_estimate_order: Order of the error estimate (unused)
*/
typedef struct _OdeIntMeta
{
const char *name;
int steps;
int last_step_is_update;
int error_estimate;
double c[MAX_STEP];
double a[(MAX_STEP*(MAX_STEP-1))/2];
double b[MAX_STEP];
int order;
double e[MAX_STEP];
int error_estimate_order;
} OdeIntMeta;
/*
* Butcher table
*
* For method that provide no error estimate, we reuse the last step, which
* will yield no error.
*/
const OdeIntMeta INTEGRATOR_META[] =
{
{"euler", 1, 0, 0,
{0.0},
{0},
{1.0}, 1,
{0}, 0},
{"heuns", 2, 0, 0,
{0.0, 1.0},
{1.0},
{1.0/2.0, 1.0/2.0}, 2,
{0}, 0},
{"heuns-euler", 2, 0, 1,
{0.0, 1.0},
{1.0},
{1.0/2.0, 1.0/2.0}, 2,
{1.0, 0.0}, 1},
{"bogacki-shampine", 4, 1, 1,
{0.0, 1.0/2.0, 3.0/4.0, 1.0},
{1.0/2.0,
0.0, 3.0/4.0,
2.0/9.0, 1.0/3.0, 4.0/9.0},
{2.0/9.0, 1.0/3.0, 4.0/9.0, 0.0}, 3,
{7.0/24.0, 1.0/4.0, 1.0/3.0, 1.0/8.0}, 2},
{"runge-kutta", 4, 0, 0,
{0.0, 1.0/2.0, 1.0/2.0, 1.0},
{1.0/2.0,
0.0, 1.0/2.0,
0.0, 0.0, 1.0},
{1.0/6.0, 1.0/3.0, 1.0/3.0, 1.0/6.0}, 4,
{0}, 0},
{"runge-kutta-fehlberg", 6, 0, 1,
{0.0, 1.0/4.0, 3.0/8.0, 12.0/13.0, 1.0, 1.0/2.0},
{1.0/4.0,
3.0/32.0, 9.0/32.0,
1932.0/2197.0, -7200.0/2197.0, 7296.0/2197.0,
439.0/216.0, -8.0, 3680.0/513.0, -845/4104.0,
-8.0/27.0, 2.0, -3544.0/2565.0, 1859.0/4104.0, -11.0/40.0},
{16.0/135.0, 0.0, 6656.0/12825.0, 28561.0/56430.0, -9.0/50.0, 2.0/55.0}, 5,
{25.0/216.0, 0.0, 1408.0/2565.0, 2197.0/4104.0, -1.0/5.0, 0.0}, 4},
{"cash-karp", 6, 0, 1,
{0.0, 1.0/5.0, 3.0/10.0, 3.0/5.0, 1.0, 7.0/8.0},
{1.0/5.0,
3.0/40.0, 9.0/40.0,
3.0/10.0, -9.0/10.0, 6.0/5.0,
-11.0/54.0, 5.0/2.0, -70.0/27.0, 35.0/27.0,
1631.0/55296.0, 175.0/512.0, 575.0/13824.0, 44275.0/110592.0, 253.0/4096.0},
{37.0/378.0, 0.0, 250.0/621.0, 125.0/594.0, 0.0, 512.0/1771.0}, 5,
{2825.0/27648.0, 0.0, 18575.0/48384.0, 13525.0/55296.0, 277.0/14336.0, 1.0/4.0}, 4},
{"dormand-prince", 7, 1, 1,
{0.0, 1.0/5.0, 3.0/10.0, 4.0/5.0, 8.0/9.0, 1.0, 1.0},
{1.0/5.0,
3.0/40.0, 9.0/40.0,
44.0/45.0, -56.0/15.0, 32.0/9.0,
19372.0/6561.0, -25360.0/2187.0, 64448.0/6561.0, -212.0/729.0,
9017.0/3168.0, -355.0/33.0, 46732.0/5247.0, 49.0/176.0, -5103.0/18656.0,
35.0/384.0, 0.0, 500.0/1113.0, 125.0/192.0, -2187.0/6784.0, 11.0/84.0},
{35.0/384.0, 0.0, 500.0/1113.0, 125.0/192.0, -2187.0/6784.0, 11.0/84.0, 0.0}, 5,
{5179.0/57600.0, 0.0, 7571.0/16695.0, 393.0/640.0, -92097.0/339200.0, 187.0/2100.0, 1.0/40.0}, 4}
};
struct _OdeIntIntegrator
{
const OdeIntMeta *integrator_meta;
double *t;
double *y;
size_t n;
double rtol;
double atol;
double *transient_y;
double *transient_ye;
double *F; // dy/dt
double h;
};
/**
* odeint_integrator_new:
* @t0: Initial timestep
* @y0: Initial value for the system which will be updated throughout the
* integration
* @n: Number of equations and variables (each variable has a differential equation w.r.t. time 't')
* @rtol: Relative tolerance (i.e. number of significant digits)
* @atol: Absolute tolerance
*/
OdeIntIntegrator *
odeint_integrator_new (OdeIntMethod method,
double *t0,
double *y0,
size_t n,
double rtol,
double atol)
{
OdeIntIntegrator *ret = malloc (sizeof (OdeIntIntegrator));
ret->integrator_meta = &INTEGRATOR_META[method];
ret->t = t0;
ret->y = y0;
ret->n = n;
/* we need at least 2 steps for the initial step size estimate */
ret->F = calloc ((ret->integrator_meta->steps + 1) * n, sizeof (double));
/* transient states for multi-step methods */
ret->transient_y = malloc ( n * sizeof (double) );
ret->transient_ye = malloc ( n * sizeof (double) );
ret->rtol = rtol;
ret->atol = atol;
ret->h = 0;
assert (ret->F != NULL);
return ret;
}
/**
* odeint_integrator_integrate:
* @func: The function to integrate
* @user_data:
* @tw: The upper integration bound, which may also be smaller than the current
* time.
*
* Integrate dy/dt = @func(t, y) over [t, @tw] or [@tw, t] if @tw < t.
*/
void
odeint_integrator_integrate (OdeIntIntegrator *self,
OdeIntFunc func,
void *user_data,
double tw)
{
double t0 = *self->t;
double t;
/* transient state for the multi-step method */
double *y = self->transient_y;
double *ye = self->transient_ye;
// Estimate initial step size using order, local curvature and tolerance
// information
//
// reference:
// H. A. Watts, “Starting Step Size for an ODE Solver,” Journal of
// Computational and Applied Mathematics 9, no. 2 (June 1, 1983): 177–91,
// https://doi.org/10.1016/0377-0427(83)90040-7.
if (self->h == 0)
{
double epsilon = sqrt (DBL_EPSILON);
func (t0, self->y, self->F, user_data);
/* simple Euler step */
cblas_dcopy (self->n, self->y, 1, y, 1);
cblas_daxpy (self->n,
epsilon,
self->F,
1,
y,
1);
func (t0 + epsilon, y, self->F + self->n, user_data);
cblas_daxpy (self->n,
-1,
self->F,
1,
self->F + self->n,
1);
double y_norm = cblas_dnrm2 (self->n, self->F + self->n, 1) / epsilon;
assert (isfinite (y_norm));
// if the has no curvature whatsoever, the step size will be infinite,
self->h = sqrt (2.0) * pow (self->atol, 1.0 / (self->integrator_meta->order + 1)) / sqrt (y_norm);
}
size_t iteration = 0;
while (fabs (tw - *self->t) >= self->rtol * fabs (tw) + self->atol)
{
iteration++;
t = *self->t;
// ensure we always land exactly on the upper integration bound
// if we went too far, the step size will be negative and still point
// toward the integration bound
#define fsign(x)((x) < 0. ? -1. : 1.)
self->h = fsign (tw - t) * fmin (fabs (self->h), fabs (tw - t));
int step;
for (step = 0; step < self->integrator_meta->steps; step++)
{
/* restore state at the beginning of the step */
cblas_dcopy (self->n, self->y, 1, y, 1);
int prev_step;
for (prev_step = 0; prev_step < step; prev_step++)
{
cblas_daxpy (self->n,
self->h * self->integrator_meta->a[(step * step - step)/2 + prev_step],
self->F + prev_step * self->n,
1,
y,
1);
}
/* update from previous steps */
func (t + self->h * self->integrator_meta->c[step], y, self->F + (step * self->n), user_data);
}
// final update
if (!self->integrator_meta->last_step_is_update)
{
/* restore state at the beginning of the step */
cblas_dcopy (self->n, self->y, 1, y, 1);
int step;
for (step = 0; step < self->integrator_meta->steps; step++)
{
cblas_daxpy (self->n,
self->h * self->integrator_meta->b[step],
self->F + step * self->n,
1,
y,
1);
}
}
// error estimate
if (self->integrator_meta->error_estimate)
{
/* restore state at the beginning of the step */
cblas_dcopy (self->n, self->y, 1, ye, 1);
int step;
for (step = 0; step < self->integrator_meta->steps; step++)
{
cblas_daxpy (self->n,
self->h * self->integrator_meta->e[step],
self->F + step * self->n,
1,
ye,
1);
}
// component-wise error
double error_ratio = 0;
size_t i;
for (i = 0; i < self->n; i++)
{
double tol = self->rtol * fmax (fabs (ye[i]), fabs(y[i])) + self->atol;
double error = fabs (ye[i] - y[i]);
error_ratio = fmax (error_ratio, error / tol);
}
assert (isfinite (error_ratio));
// check if the step is accepted
if (error_ratio <= 1)
{
*self->t = t + self->h;
cblas_dcopy (self->n, y, 1, self->y, 1);
}
// compute optimal step size
self->h = self->h * pow (1.0 / error_ratio, 1.0 / self->integrator_meta->order);
}
else
{
*self->t = t + self->h;
cblas_dcopy (self->n, y, 1, self->y, 1);
}
}
}
void odeint_integrator_free (OdeIntIntegrator *self)
{
free (self->transient_y);
free (self->transient_ye);
free (self->F);
free (self);
}
| {
"alphanum_fraction": 0.4661489265,
"avg_line_length": 31.9096209913,
"ext": "c",
"hexsha": "e70264623df433ced75f5f06a9117001ccdef7e6",
"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": "64569acae18401007e25b045c19c7ca0fe2b2a1c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "major-lab/mirbooking",
"max_forks_repo_path": "contrib/odeint/odeint.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "64569acae18401007e25b045c19c7ca0fe2b2a1c",
"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": "major-lab/mirbooking",
"max_issues_repo_path": "contrib/odeint/odeint.c",
"max_line_length": 117,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "64569acae18401007e25b045c19c7ca0fe2b2a1c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "major-lab/mirbooking",
"max_stars_repo_path": "contrib/odeint/odeint.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3742,
"size": 10945
} |
#include <config.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_fft_complex.h>
#define BASE_DOUBLE
#include "templates_on.h"
#include "compare_source.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "compare_source.c"
#include "templates_off.h"
#undef BASE_FLOAT
| {
"alphanum_fraction": 0.7527839644,
"avg_line_length": 18.7083333333,
"ext": "c",
"hexsha": "9a636511d5f98d23822792d46bfed9a5c0e7e55e",
"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/fft/compare.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/fft/compare.c",
"max_line_length": 32,
"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/fft/compare.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": 112,
"size": 449
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.