Search is not available for this dataset
text string | meta dict |
|---|---|
#pragma once
#include <memory>
#include <gsl/gsl>
/// Holds code related to computer memory.
namespace MEMORY
{
/// A type alias to improve readability for non-null raw pointers.
/// @tparam Type - The type of the underyling item being pointed to.
template <typename Type>
using NonNullRawPointer = gsl::strict_not_null<Type*>;
/// A type alias to improve readability for non-null unique pointers.
/// @tparam Type - The type of the underlying item in the pointer.
template <typename Type>
using NonNullUniquePointer = gsl::strict_not_null<std::unique_ptr<Type>>;
/// A type alias to improve readability for non-null shared pointers.
/// @tparam Type - The type of the underlying item in the pointer.
template <typename Type>
using NonNullSharedPointer = gsl::strict_not_null<std::shared_ptr<Type>>;
}
| {
"alphanum_fraction": 0.7166276347,
"avg_line_length": 35.5833333333,
"ext": "h",
"hexsha": "b511177ac9adfa42d42fecd10e053b1564c424ad",
"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": "7db1595ef7b17a0485b8a07abeb20d8f9cd0ea63",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "jpike/CppLibraries",
"max_forks_repo_path": "Memory/Pointers.h",
"max_issues_count": 61,
"max_issues_repo_head_hexsha": "7db1595ef7b17a0485b8a07abeb20d8f9cd0ea63",
"max_issues_repo_issues_event_max_datetime": "2021-10-02T13:34:43.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-04-11T21:26:12.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "jpike/CppLibraries",
"max_issues_repo_path": "Memory/Pointers.h",
"max_line_length": 77,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7db1595ef7b17a0485b8a07abeb20d8f9cd0ea63",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "jpike/CppLibraries",
"max_stars_repo_path": "Memory/Pointers.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 188,
"size": 854
} |
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <string.h>
#ifdef ACCELERATE
#include <Accelerate/Accelerate.h>
#else
#include <cblas.h>
#endif
#include "neural.h"
void
neural_feed_forward(struct neural_net_layer *head, float *x, int batch_size)
{
/* point "current" layer to head and set input as feature array x */
struct neural_net_layer *curr = head;
struct neural_net_layer *next;
curr->act = x;
int in_nodes;
int out_nodes;
while ((next = curr->next) != NULL) {
in_nodes = curr->in_nodes;
out_nodes = curr->out_nodes;
/* act = X * Theta^T + bias */
for (int i = 0; i < batch_size; i++) {
memcpy(next->act + i * out_nodes, curr->bias, out_nodes * sizeof(float));
}
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasTrans, batch_size, out_nodes, in_nodes,
1.0, curr->act, in_nodes, curr->theta, in_nodes, 1.0, next->act, out_nodes);
/* apply sigmoid function */
for (int i = 0; i < out_nodes * batch_size; i++) {
next->act[i] = 1.0 / (1 + expf(-next->act[i]));
}
/* transition to next layer */
curr = next;
}
}
void
neural_sgd_feed_forward(struct neural_net_layer *head, float *x)
{
/* point "current" layer to head and set input as feature array x */
struct neural_net_layer *curr = head;
struct neural_net_layer *next;
curr->act = x;
int rows;
int cols;
while ((next = curr->next) != NULL) {
rows = curr->out_nodes;
cols = curr->in_nodes;
/* act = theta * x + act */
memcpy(next->act, curr->bias, rows * sizeof(float));
cblas_sgemv(CblasRowMajor, CblasNoTrans, rows, cols, 1.0, curr->theta,
cols, curr->act, 1, 1.0, next->act, 1);
/* apply sigmoid function */
for (int i = 0; i < rows; i++) {
next->act[i] = 1.0 / (1 + expf(-next->act[i]));
}
/* transition to next layer */
curr = next;
}
}
void
neural_back_prop(struct neural_net_layer *tail, float *y, const int batch_size,
const float alpha, const float lambda)
{
/* get delta from final predictions vs. actual; delta = a - y */
cblas_scopy(tail->in_nodes * batch_size, tail->act, 1, tail->delta, 1);
cblas_saxpy(tail->in_nodes * batch_size, -1.0, y, 1, tail->delta, 1);
struct neural_net_layer *curr;
struct neural_net_layer *prev;
int in_nodes;
int out_nodes;
for (curr = tail; curr->prev != NULL; curr = prev) {
prev = curr->prev;
in_nodes = prev->in_nodes;
out_nodes = prev->out_nodes;
/* Delta^(n-1) = Delta^(n) * Theta^(n-1) .* A^(n-1) (1 - A^(n-1)) */
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, batch_size, in_nodes, out_nodes,
1.0, curr->delta, out_nodes, prev->theta, in_nodes, 0.0, prev->delta, in_nodes);
for (int j = 0; j < in_nodes * batch_size; j++) {
prev->delta[j] *= (prev->act[j] * (1 - prev->act[j]));
}
}
for (curr = tail; curr->prev != NULL; curr = prev) {
prev = curr->prev;
in_nodes = prev->in_nodes;
out_nodes = prev->out_nodes;
/* bias -= alpha * delta */
for (int i = 0; i < batch_size; i++) {
cblas_saxpy(out_nodes, -alpha, curr->delta + i * out_nodes, 1, prev->bias, 1);
}
/* Theta -= alpha * (Delta^T * Act + lambda * Theta) */
cblas_sgemm(CblasRowMajor, CblasTrans, CblasNoTrans, out_nodes, in_nodes, batch_size,
-alpha, curr->delta, out_nodes, prev->act, in_nodes, 1 - alpha * lambda,
prev->theta, in_nodes);
}
}
void
neural_sgd_back_prop(struct neural_net_layer *tail, float *y, const float alpha,
const float lambda)
{
/* get delta from final predictions vs. actual; delta = a - y */
cblas_scopy(tail->in_nodes, tail->act, 1, tail->delta, 1);
cblas_saxpy(tail->in_nodes, -1.0, y, 1, tail->delta, 1);
struct neural_net_layer *curr;
struct neural_net_layer *prev;
int rows;
int cols;
for (curr = tail; curr->prev != NULL; curr = prev) {
prev = curr->prev;
rows = prev->out_nodes;
cols = prev->in_nodes;
/* delta^(n-1) = theta^(n-1)T * delta^(n) .* a^(n-1) (1 - a^(n-1)) */
cblas_sgemv(CblasRowMajor, CblasTrans, rows, cols, 1.0, prev->theta,
cols, curr->delta, 1, 0.0, prev->delta, 1);
for (int j = 0; j < cols; j++) {
prev->delta[j] *= (prev->act[j] * (1 - prev->act[j]));
}
}
for (curr = tail; curr->prev != NULL; curr = prev) {
prev = curr->prev;
rows = prev->out_nodes;
cols = prev->in_nodes;
/* bias -= alpha * delta */
cblas_saxpy(rows, -alpha, curr->delta, 1, prev->bias, 1);
/* theta -= alpha * (delta * actT + lambda * theta) */
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, rows, cols, 1, -alpha,
curr->delta, 1, prev->act, cols, 1 - alpha * lambda, prev->theta, cols);
}
}
void
neural_train_iteration(struct neural_net_layer *head, struct neural_net_layer *tail,
float *features, float *labels, const int n_samples, const int batch_size,
const float alpha, const float lambda)
{
int n_features = head->in_nodes;
int n_labels = tail->in_nodes;
int i;
if (batch_size == 1) {
for (i = 0; i < n_samples; i++) {
neural_sgd_feed_forward(head, features + i * n_features);
neural_sgd_back_prop(tail, labels + i * n_labels, alpha, lambda);
}
} else {
for (i = 0; i < n_samples / batch_size; i++) {
neural_feed_forward(head, features + i * n_features * batch_size, batch_size);
neural_back_prop(tail, labels + i * n_labels * batch_size, batch_size, alpha, lambda);
}
/* take care of remaining examples */
int remainder = n_samples % batch_size;
if (remainder > 0) {
neural_feed_forward(head, features + i * n_features * batch_size, remainder);
neural_back_prop(tail, labels + i * n_labels * batch_size, remainder, alpha, lambda);
}
}
}
void
neural_predict_prob(struct neural_net_layer *head, struct neural_net_layer *tail,
float *features, float *preds, const int n_samples, const int batch_size)
{
int n_features = head->in_nodes;
int n_labels = tail->in_nodes;
int i;
if (batch_size == 1) {
for (i = 0; i < n_samples; i++) {
neural_sgd_feed_forward(head, features + i * n_features);
memcpy(preds + i * n_labels, tail->act, n_labels * sizeof(float));
}
} else {
for (i = 0; i < n_samples / batch_size; i++) {
neural_feed_forward(head, features + i * n_features * batch_size, batch_size);
memcpy(preds + i * n_labels * batch_size, tail->act,
n_labels * batch_size * sizeof(float));
}
/* take care of remaining examples */
int remainder = n_samples % batch_size;
if (remainder > 0) {
neural_feed_forward(head, features + i * n_features * batch_size, remainder);
memcpy(preds + i * n_labels * batch_size, tail->act,
n_labels * remainder * sizeof(float));
}
}
}
| {
"alphanum_fraction": 0.6511699037,
"avg_line_length": 29.995412844,
"ext": "c",
"hexsha": "85c7dc5a3c395e7eb8084102677e7ca8dd980504",
"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": "5de244c702915bff404a31c2b10820cdec67130a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "jwilk-forks/pyneural",
"max_forks_repo_path": "src/neural.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5de244c702915bff404a31c2b10820cdec67130a",
"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": "jwilk-forks/pyneural",
"max_issues_repo_path": "src/neural.c",
"max_line_length": 89,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5de244c702915bff404a31c2b10820cdec67130a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "jwilk-forks/pyneural",
"max_stars_repo_path": "src/neural.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2109,
"size": 6539
} |
#ifndef BATCH_EXTRACTOR_H_IVH3CLLQ
#define BATCH_EXTRACTOR_H_IVH3CLLQ
#include <gsl/gsl>
#include <optional>
#include <sens_loc/util/correctness_util.h>
#include <string_view>
namespace sens_loc::apps {
/// \ingroup feature-plotter-driver
/// Defines a strongly typed switch for the color to use. Will be mapped
/// to the actual OpenCV-color using \c color_to_bgr.
enum class feature_color {
green,
blue,
red,
orange,
purple, ///< Nice purple.
all ///< Draws all keypoints with different colors.
};
/// Convert a color name to the corresponding \c feature_color.
/// The string must match with the enum-value, e.g. "green".
/// \ingroup feature-plotter-driver
inline feature_color str_to_color(std::string_view color_string) noexcept {
#define COLOR_SWITCH(COLOR) \
if (color_string == #COLOR) \
return feature_color::COLOR;
COLOR_SWITCH(all)
COLOR_SWITCH(green)
COLOR_SWITCH(blue)
COLOR_SWITCH(red)
COLOR_SWITCH(purple)
COLOR_SWITCH(orange)
UNREACHABLE("Unexpected color to convert"); // LCOV_EXCL_LINE
}
/// Provide a conversion from the \¢ feature_color to actual OpenCV colors.
/// \ingroup feature-plotter-driver
struct color_to_bgr {
// Color Space in BGR.
static cv::Scalar convert(feature_color c) {
using cv::Scalar;
switch (c) {
case feature_color::all: return Scalar::all(-1);
case feature_color::green: return Scalar(5, 117, 65);
case feature_color::blue: return Scalar(226, 144, 74);
case feature_color::red: return Scalar(27, 2, 208);
case feature_color::purple: return Scalar(254, 19, 144);
case feature_color::orange: return Scalar(35, 166, 245);
}
UNREACHABLE("Invalid enum-value!"); // LCOV_EXCL_LINE
}
};
/// Helper class that visits a list of images plots keypoints onto them.
/// \ingroup feature-plotter-driver
class batch_plotter {
public:
batch_plotter(std::string_view feature_file_pattern,
std::string_view output_file_pattern,
feature_color color,
std::optional<std::string_view> target_image_file_pattern)
: _feature_file_pattern{feature_file_pattern}
, _ouput_file_pattern{output_file_pattern}
, _color{color}
, _target_image_file_pattern{target_image_file_pattern} {
Expects(!_feature_file_pattern.empty());
Expects(!_ouput_file_pattern.empty());
if (_target_image_file_pattern)
Expects(!_target_image_file_pattern->empty());
}
/// Process a whole batch of files in the range [start, end].
[[nodiscard]] bool process_batch(int start, int end) const noexcept;
private:
/// Process a single feature file. Called in parallel from \c process_batch.
[[nodiscard]] bool process_index(int idx) const noexcept;
/// The feature-detector creates files with the keypoints. This file-pattern
/// needs to be provided in order to plot those keypoints.
std::string_view _feature_file_pattern;
/// File pattern for the output image to be written to.
/// These images are 8-bit RGB images!
std::string_view _ouput_file_pattern;
/// Color to draw the keypoints in.
feature_color _color;
/// Even though the feature-files should have a path to the original image,
/// the features were detected on, this path might not be the desired target
/// for plotting. This is the case for plotting multiple feature keypoints
/// or if the path to the file is incorrect.
std::optional<std::string_view> _target_image_file_pattern;
};
} // namespace sens_loc::apps
#endif /* end of include guard: BATCH_EXTRACTOR_H_IVH3CLLQ */
| {
"alphanum_fraction": 0.6689136635,
"avg_line_length": 37.0865384615,
"ext": "h",
"hexsha": "0a0a75051f911fcc47828501feed835c31ec517f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "JonasToth/depth-conversions",
"max_forks_repo_path": "src/apps/keypoint_plotter/batch_plotter.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "JonasToth/depth-conversions",
"max_issues_repo_path": "src/apps/keypoint_plotter/batch_plotter.h",
"max_line_length": 80,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "5c8338276565d846c07673e83f94f6841006872b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "JonasToth/depth-conversions",
"max_stars_repo_path": "src/apps/keypoint_plotter/batch_plotter.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-14T09:14:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-30T07:09:49.000Z",
"num_tokens": 876,
"size": 3857
} |
/* matrix/gsl_matrix_complex_float.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_COMPLEX_FLOAT_H__
#define __GSL_MATRIX_COMPLEX_FLOAT_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_complex_float.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size1;
size_t size2;
size_t tda;
float * data;
gsl_block_complex_float * block;
int owner;
} gsl_matrix_complex_float ;
typedef struct
{
gsl_matrix_complex_float matrix;
} _gsl_matrix_complex_float_view;
typedef _gsl_matrix_complex_float_view gsl_matrix_complex_float_view;
typedef struct
{
gsl_matrix_complex_float matrix;
} _gsl_matrix_complex_float_const_view;
typedef const _gsl_matrix_complex_float_const_view gsl_matrix_complex_float_const_view;
/* Allocation */
gsl_matrix_complex_float *
gsl_matrix_complex_float_alloc (const size_t n1, const size_t n2);
gsl_matrix_complex_float *
gsl_matrix_complex_float_calloc (const size_t n1, const size_t n2);
gsl_matrix_complex_float *
gsl_matrix_complex_float_alloc_from_block (gsl_block_complex_float * b,
const size_t offset,
const size_t n1, const size_t n2, const size_t d2);
gsl_matrix_complex_float *
gsl_matrix_complex_float_alloc_from_matrix (gsl_matrix_complex_float * b,
const size_t k1, const size_t k2,
const size_t n1, const size_t n2);
gsl_vector_complex_float *
gsl_vector_complex_float_alloc_row_from_matrix (gsl_matrix_complex_float * m,
const size_t i);
gsl_vector_complex_float *
gsl_vector_complex_float_alloc_col_from_matrix (gsl_matrix_complex_float * m,
const size_t j);
void gsl_matrix_complex_float_free (gsl_matrix_complex_float * m);
/* Views */
_gsl_matrix_complex_float_view
gsl_matrix_complex_float_submatrix (gsl_matrix_complex_float * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_complex_float_view
gsl_matrix_complex_float_row (gsl_matrix_complex_float * m, const size_t i);
_gsl_vector_complex_float_view
gsl_matrix_complex_float_column (gsl_matrix_complex_float * m, const size_t j);
_gsl_vector_complex_float_view
gsl_matrix_complex_float_diagonal (gsl_matrix_complex_float * m);
_gsl_vector_complex_float_view
gsl_matrix_complex_float_subdiagonal (gsl_matrix_complex_float * m, const size_t k);
_gsl_vector_complex_float_view
gsl_matrix_complex_float_superdiagonal (gsl_matrix_complex_float * m, const size_t k);
_gsl_matrix_complex_float_view
gsl_matrix_complex_float_view_array (float * base,
const size_t n1,
const size_t n2);
_gsl_matrix_complex_float_view
gsl_matrix_complex_float_view_array_with_tda (float * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_complex_float_view
gsl_matrix_complex_float_view_vector (gsl_vector_complex_float * v,
const size_t n1,
const size_t n2);
_gsl_matrix_complex_float_view
gsl_matrix_complex_float_view_vector_with_tda (gsl_vector_complex_float * v,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_complex_float_const_view
gsl_matrix_complex_float_const_submatrix (const gsl_matrix_complex_float * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
_gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_row (const gsl_matrix_complex_float * m,
const size_t i);
_gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_column (const gsl_matrix_complex_float * m,
const size_t j);
_gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_diagonal (const gsl_matrix_complex_float * m);
_gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_subdiagonal (const gsl_matrix_complex_float * m,
const size_t k);
_gsl_vector_complex_float_const_view
gsl_matrix_complex_float_const_superdiagonal (const gsl_matrix_complex_float * m,
const size_t k);
_gsl_matrix_complex_float_const_view
gsl_matrix_complex_float_const_view_array (const float * base,
const size_t n1,
const size_t n2);
_gsl_matrix_complex_float_const_view
gsl_matrix_complex_float_const_view_array_with_tda (const float * base,
const size_t n1,
const size_t n2,
const size_t tda);
_gsl_matrix_complex_float_const_view
gsl_matrix_complex_float_const_view_vector (const gsl_vector_complex_float * v,
const size_t n1,
const size_t n2);
_gsl_matrix_complex_float_const_view
gsl_matrix_complex_float_const_view_vector_with_tda (const gsl_vector_complex_float * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
gsl_complex_float gsl_matrix_complex_float_get(const gsl_matrix_complex_float * m, const size_t i, const size_t j);
void gsl_matrix_complex_float_set(gsl_matrix_complex_float * m, const size_t i, const size_t j, const gsl_complex_float x);
gsl_complex_float * gsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m, const size_t i, const size_t j);
const gsl_complex_float * gsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m, const size_t i, const size_t j);
void gsl_matrix_complex_float_set_zero (gsl_matrix_complex_float * m);
void gsl_matrix_complex_float_set_identity (gsl_matrix_complex_float * m);
void gsl_matrix_complex_float_set_all (gsl_matrix_complex_float * m, gsl_complex_float x);
int gsl_matrix_complex_float_fread (FILE * stream, gsl_matrix_complex_float * m) ;
int gsl_matrix_complex_float_fwrite (FILE * stream, const gsl_matrix_complex_float * m) ;
int gsl_matrix_complex_float_fscanf (FILE * stream, gsl_matrix_complex_float * m);
int gsl_matrix_complex_float_fprintf (FILE * stream, const gsl_matrix_complex_float * m, const char * format);
int gsl_matrix_complex_float_memcpy(gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src);
int gsl_matrix_complex_float_swap(gsl_matrix_complex_float * m1, gsl_matrix_complex_float * m2);
int gsl_matrix_complex_float_swap_rows(gsl_matrix_complex_float * m, const size_t i, const size_t j);
int gsl_matrix_complex_float_swap_columns(gsl_matrix_complex_float * m, const size_t i, const size_t j);
int gsl_matrix_complex_float_swap_rowcol(gsl_matrix_complex_float * m, const size_t i, const size_t j);
int gsl_matrix_complex_float_transpose (gsl_matrix_complex_float * m);
int gsl_matrix_complex_float_transpose_memcpy (gsl_matrix_complex_float * dest, const gsl_matrix_complex_float * src);
int gsl_matrix_complex_float_isnull (const gsl_matrix_complex_float * m);
int gsl_matrix_complex_float_add (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);
int gsl_matrix_complex_float_sub (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);
int gsl_matrix_complex_float_mul_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);
int gsl_matrix_complex_float_div_elements (gsl_matrix_complex_float * a, const gsl_matrix_complex_float * b);
int gsl_matrix_complex_float_scale (gsl_matrix_complex_float * a, const gsl_complex_float x);
int gsl_matrix_complex_float_add_constant (gsl_matrix_complex_float * a, const gsl_complex_float x);
int gsl_matrix_complex_float_add_diagonal (gsl_matrix_complex_float * a, const gsl_complex_float x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
int gsl_matrix_complex_float_get_row(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t i);
int gsl_matrix_complex_float_get_col(gsl_vector_complex_float * v, const gsl_matrix_complex_float * m, const size_t j);
int gsl_matrix_complex_float_set_row(gsl_matrix_complex_float * m, const size_t i, const gsl_vector_complex_float * v);
int gsl_matrix_complex_float_set_col(gsl_matrix_complex_float * m, const size_t j, const gsl_vector_complex_float * v);
#ifdef HAVE_INLINE
extern inline
gsl_complex_float
gsl_matrix_complex_float_get(const gsl_matrix_complex_float * m,
const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
gsl_complex_float zero = {{0,0}};
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, zero) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, zero) ;
}
#endif
return *(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;
}
extern inline
void
gsl_matrix_complex_float_set(gsl_matrix_complex_float * m,
const size_t i, const size_t j, const gsl_complex_float x)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
#endif
*(gsl_complex_float *)(m->data + 2*(i * m->tda + j)) = x ;
}
extern inline
gsl_complex_float *
gsl_matrix_complex_float_ptr(gsl_matrix_complex_float * m,
const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
#endif
return (gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;
}
extern inline
const gsl_complex_float *
gsl_matrix_complex_float_const_ptr(const gsl_matrix_complex_float * m,
const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
#endif
return (const gsl_complex_float *)(m->data + 2*(i * m->tda + j)) ;
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_MATRIX_COMPLEX_FLOAT_H__ */
| {
"alphanum_fraction": 0.6985312422,
"avg_line_length": 38.625,
"ext": "h",
"hexsha": "8b27958679d65f11a680a1d99a80d0d97f6c2f72",
"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": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "andrewkern/segSiteHMM",
"max_forks_repo_path": "extern/include/gsl/gsl_matrix_complex_float.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "andrewkern/segSiteHMM",
"max_issues_repo_path": "extern/include/gsl/gsl_matrix_complex_float.h",
"max_line_length": 129,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ad97da6f6bc94f91e72d75f37fa33ca949d9bb60",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "andrewkern/segSiteHMM",
"max_stars_repo_path": "extern/include/gsl/gsl_matrix_complex_float.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2698,
"size": 12051
} |
/**
* File: utils.h
*
* Author: Vishal R (vishalr@pesu.pes.edu or vishalramesh01@gmail.com)
*
* Summary of File:
* Matrix operation library required for cdnn. Contains all the header files for matrix operations.
*/
#ifndef UTILS_H
#define UTILS_H
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <omp.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <cblas.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <termcap.h>
#ifdef __cplusplus
extern "C"{
#endif
typedef struct array{
float * matrix;
int shape[2];
}dARRAY;
dARRAY * zeros(int * dims);
dARRAY * ones(int * dims);
dARRAY * eye(int * dims);
dARRAY * randn(int * dims);
dARRAY * add(dARRAY * MatrixA, dARRAY * MatrixB);
dARRAY * addScalar(dARRAY * matrix, float scalar);
dARRAY * subtract(dARRAY * MatrixA, dARRAY * MatrixB);
dARRAY * subScalar(dARRAY * matrix, float scalar);
dARRAY * sum(dARRAY * matrix, int axis);
dARRAY * transpose(dARRAY * Matrix);
dARRAY * dot(dARRAY * MatrixA, dARRAY * MatrixB);
dARRAY * multiply(dARRAY * MatrixA, dARRAY * MatrixB);
dARRAY * mulScalar(dARRAY * matrix, float scalar);
dARRAY * divison(dARRAY * MatrixA, dARRAY * MatrixB);
dARRAY * divScalar(dARRAY * matrix, float scalar);
dARRAY * power(dARRAY * matrix, float power);
dARRAY * squareroot(dARRAY * matrix);
dARRAY * exponentional(dARRAY * matrix);
dARRAY * b_cast(dARRAY * MatrixA, dARRAY * MatrixB);
dARRAY * reshape(dARRAY * matrix, int * dims);
int * permutation(int length);
float mean(dARRAY * matrix);
float var(dARRAY * matrix, char * type);
float std(dARRAY * matrix, char * type);
float gaussGenerator(float * cache, int * return_cache);
float gaussRandom();
float rand_norm(float mu, float std);
float frobenius_norm(dARRAY * matrix);
float Manhattan_distance(dARRAY * matrix);
int size(dARRAY * A);
void shape(dARRAY * A);
void free2d(dARRAY * matrix);
void sleep_my(int milliseconds);
void cleanSTDIN();
void get_safe_nn_threads();
#ifdef __cplusplus
}
#endif
#endif //UTILS_H | {
"alphanum_fraction": 0.6822211853,
"avg_line_length": 27.8311688312,
"ext": "h",
"hexsha": "6b979ae217171a1516bee9914c51ba91b2d4443a",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-08-15T12:46:42.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-17T06:38:42.000Z",
"max_forks_repo_head_hexsha": "75425e01d7948c51b9dcae0524a80d6e3ccdd424",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "adimehta03/cDNN",
"max_forks_repo_path": "include/cdnn/utils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "75425e01d7948c51b9dcae0524a80d6e3ccdd424",
"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": "adimehta03/cDNN",
"max_issues_repo_path": "include/cdnn/utils.h",
"max_line_length": 103,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "75425e01d7948c51b9dcae0524a80d6e3ccdd424",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "adimehta03/cDNN",
"max_stars_repo_path": "include/cdnn/utils.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-14T04:51:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-17T06:29:03.000Z",
"num_tokens": 606,
"size": 2143
} |
/*
* 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_MATH_ODE_SOLVER_GSL_H_
#define SIM_MATH_ODE_SOLVER_GSL_H_
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
#include <stdint.h>
#include <vector>
#include "common/macros.h"
#include "sim/math/ode_solver.h"
#include "sim/sim_types.h"
namespace sim {
// Wrapper for the GSL ODE library.
class GslOdeSolver : public OdeSolver {
public:
explicit GslOdeSolver(const OdeSystem &ode_system,
const SimOdeSolverParams ¶ms);
~GslOdeSolver() {
if (ode_driver_ != nullptr) gsl_odeiv2_driver_free(ode_driver_);
}
OdeSolverStatus Integrate(double t0, double tf, const std::vector<double> &x0,
double *t_int, std::vector<double> *x) override;
private:
// Static callback function for the GSL ODE solver.
//
// Args:
// t: Time at which derivative will be evaluated.
// x: Array of length num_states() containing the state at which
// the derivative will be evaluated.
// dx: Array of length num_states() into which the derivative is stored.
// context: Pointer to the OdeSolver class containing the OdeSystem.
//
// Returns:
// GSL_SUCCESS if the derivative was calculated successfully,
// GSL_FAILURE if the time step was too large, or
// GSL_EBADFUNC if the integration should be aborted immediately.
static int32_t GslCallback(double t, const double x[], double dx[],
void *context);
// Solver parameters.
const SimOdeSolverParams ¶ms_;
// ODE to be solved.
const OdeSystem &ode_system_;
// Parameters for GSL.
gsl_odeiv2_system sys_;
gsl_odeiv2_driver *ode_driver_;
DISALLOW_COPY_AND_ASSIGN(GslOdeSolver);
};
} // namespace sim
#endif // SIM_MATH_ODE_SOLVER_GSL_H_
| {
"alphanum_fraction": 0.7078746825,
"avg_line_length": 30.6753246753,
"ext": "h",
"hexsha": "0befb4297c5d76acb52df286780b26b54a1f4109",
"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/math/ode_solver_gsl.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/math/ode_solver_gsl.h",
"max_line_length": 80,
"max_stars_count": 1178,
"max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "leozz37/makani",
"max_stars_repo_path": "sim/math/ode_solver_gsl.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": 586,
"size": 2362
} |
/*
*/
#ifndef MINIMIZER_H
#define MINIMIZER_H
#include <iostream>
#include "Vector.h"
#include <stdexcept>
#ifdef USE_GSL
extern "C" {
#include <gsl/gsl_multimin.h>
}
namespace PsimagLite {
template<typename FunctionType>
typename FunctionType::FieldType myFunction(const gsl_vector *v, void *params)
{
FunctionType* ft = (FunctionType *)params;
return ft->operator()(v->data,v->size);
}
template<typename FunctionType>
void myDfunction(const gsl_vector *v,
void *params,
gsl_vector* df)
{
FunctionType* ft = (FunctionType *)params;
ft->df(v->data,v->size,df->data,df->size);
}
template<typename FunctionType>
void myFdFunction(const gsl_vector *v,
void *params,
double *f,
gsl_vector *df)
{
*f = myFunction<FunctionType>(v, params);
myDfunction<FunctionType>(v, params, df);
}
template<typename RealType,typename FunctionType>
class Minimizer {
typedef typename FunctionType::FieldType FieldType;
typedef typename Vector<FieldType>::Type VectorType;
typedef Minimizer<RealType,FunctionType> ThisType;
public:
enum {GSL_SUCCESS=::GSL_SUCCESS, GSL_CONTINUE=::GSL_CONTINUE};
Minimizer(FunctionType& function,SizeType maxIter, bool verbose = false)
: function_(function),
maxIter_(maxIter),
verbose_(verbose),
status_(100),
gslT_(gsl_multimin_fminimizer_nmsimplex2),
gslS_(gsl_multimin_fminimizer_alloc(gslT_,function_.size())),
gslDt_(gsl_multimin_fdfminimizer_conjugate_fr),
gslDs_(gsl_multimin_fdfminimizer_alloc (gslDt_, function_.size()))
{}
~Minimizer()
{
gsl_multimin_fminimizer_free(gslS_);
gsl_multimin_fdfminimizer_free(gslDs_);
}
int simplex(VectorType& minVector,RealType delta=1e-3,RealType tolerance=1e-3)
{
gsl_vector *x;
/* Starting point, */
x = gsl_vector_alloc (function_.size());
for (SizeType i=0;i<minVector.size();i++)
gsl_vector_set (x, i, minVector[i]);
gsl_vector *xs;
xs = gsl_vector_alloc (function_.size());
for (SizeType i=0;i<minVector.size();i++)
gsl_vector_set (xs, i, delta);
gsl_multimin_function func;
func.f= myFunction<FunctionType>;
func.n = function_.size();
func.params = &function_;
gsl_multimin_fminimizer_set (gslS_, &func, x, xs);
SizeType iter = 0;
RealType prevValue = 0;
for (;iter<maxIter_;iter++) {
status_ = gsl_multimin_fminimizer_iterate (gslS_);
if (status_) {
String gslError(gsl_strerror(status_));
String msg("Minimizer::simplex(...): GSL Error: ");
msg += gslError + "\n";
throw RuntimeError(msg);
}
RealType size = gsl_multimin_fminimizer_size(gslS_);
status_ = gsl_multimin_test_size(size, tolerance);
if (verbose_) {
RealType thisValue = function_(gslS_->x->data,func.n);
RealType diff = fabs(thisValue - prevValue);
std::cerr<<"simplex: "<<iter<<" "<<thisValue<<" diff= "<<diff;
std::cerr<<" status= "<<status_<<" size="<<size<<"\n";
prevValue = thisValue;
}
if (status_ == GSL_SUCCESS) break;
}
found(minVector,gslS_->x,iter);
gsl_vector_free (x);
gsl_vector_free (xs);
return iter;
}
int conjugateGradient(VectorType& minVector,
RealType delta=1e-3,
RealType delta2=1e-3,
RealType tolerance=1e-3,
SizeType saveEvery = 0)
{
gsl_vector *x;
/* Starting point, */
x = gsl_vector_alloc (function_.size());
for (SizeType i=0;i<minVector.size();i++)
gsl_vector_set (x, i, minVector[i]);
gsl_multimin_function_fdf func;
func.f= myFunction<FunctionType>;
func.df = myDfunction<FunctionType>;
func.fdf = myFdFunction<FunctionType>;
func.n = function_.size();
func.params = &function_;
gsl_multimin_fdfminimizer_set(gslDs_, &func, x, delta, delta2);
RealType prevValue = 0;
SizeType iter = 0;
for (;iter<maxIter_;iter++) {
status_ = gsl_multimin_fdfminimizer_iterate(gslDs_);
if (status_) {
String gslError(gsl_strerror(status_));
String msg("Minimizer::conjugateGradient(...): GSL Error: ");
msg += gslError + "\n";
throw RuntimeError(msg);
}
status_ = gsl_multimin_test_gradient (gslDs_->gradient, tolerance);
if (verbose_) {
RealType thisValue = function_(gslDs_->x->data,func.n);
RealType diff = fabs(thisValue - prevValue);
std::cerr<<"conjugateGradient: "<<iter<<" "<<thisValue;
std::cerr<<" diff= "<<diff;
std::cerr<<" gradientNorm= "<<gradientNorm(gslDs_->x);
std::cerr<<" status= "<<status_<<"\n";
prevValue = thisValue;
}
if (status_ == GSL_SUCCESS) break;
if (saveEvery > 0 && iter%saveEvery==0)
printIntermediate(gslDs_->x, iter);
}
found(minVector,gslDs_->x,iter);
gsl_vector_free (x);
return iter;
}
int status() const { return status_; }
String statusString() const
{
switch (status_) {
case GSL_SUCCESS:
return "GSL_SUCCESS";
break;
case GSL_CONTINUE:
return "GSL_CONTINUE";
break;
default:
return "UNKNOWN";
break;
}
}
private:
void found(VectorType& minVector,gsl_vector* x,SizeType iter)
{
for (SizeType i=0;i<minVector.size();i++)
minVector[i] = gsl_vector_get(x,i);
}
void printIntermediate(gsl_vector* x, SizeType iter) const
{
std::cerr<<"INTERMEDIATE "<<iter<<"\n";
std::cerr<<x->size<<"\n";
for (SizeType i=0;i<x->size;i++)
std::cerr<<gsl_vector_get(x,i)<<"\n";
}
RealType gradientNorm(const gsl_vector *v) const
{
gsl_vector* df = gsl_vector_alloc (function_.size());
myDfunction<FunctionType>(v,&function_,df);
RealType sum = 0;
for (int i = 0; i < df->size; ++i) {
RealType tmp = gsl_vector_get(df,i);
sum += PsimagLite::conj(tmp) * tmp;
}
gsl_vector_free (df);
return sqrt(sum);
}
FunctionType& function_;
SizeType maxIter_;
bool verbose_;
int status_;
const gsl_multimin_fminimizer_type *gslT_;
gsl_multimin_fminimizer *gslS_;
const gsl_multimin_fdfminimizer_type *gslDt_;
gsl_multimin_fdfminimizer *gslDs_;
}; // class Minimizer
}
#else
namespace PsimagLite {
template<typename RealType,typename FunctionType>
class Minimizer {
typedef typename FunctionType::FieldType FieldType;
typedef typename Vector<FieldType>::Type VectorType;
public:
enum {GSL_SUCCESS=0, GSL_CONTINUE=1};
Minimizer(FunctionType&,SizeType, bool = false)
{
String str("Minimizer needs the gsl\n");
throw RuntimeError(str);
}
int simplex(VectorType&,RealType=1e-3,RealType=1e-3)
{
String str("Minimizer needs the gsl\n");
throw RuntimeError(str);
}
int status() const { return 1; }
String statusString() const
{
return "Minimizer needs the gsl";
}
};
} // namespace PsimagLite
#endif
#endif // MINIMIZER_H
| {
"alphanum_fraction": 0.6760226933,
"avg_line_length": 24.0071684588,
"ext": "h",
"hexsha": "1761598a5dcd9f0d506e4206298d76e06d3bdd89",
"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": "ffa0ffad75c5db218a9edea1a9581fed98c2648f",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "npatel37/PsimagLiteORNL",
"max_forks_repo_path": "src/Minimizer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f",
"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": "npatel37/PsimagLiteORNL",
"max_issues_repo_path": "src/Minimizer.h",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "ffa0ffad75c5db218a9edea1a9581fed98c2648f",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "npatel37/PsimagLiteORNL",
"max_stars_repo_path": "src/Minimizer.h",
"max_stars_repo_stars_event_max_datetime": "2019-11-13T22:13:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-11-13T22:13:51.000Z",
"num_tokens": 1913,
"size": 6698
} |
#pragma once
#include <memory>
#include <gsl/span>
#include "halley/time/halleytime.h"
#include "../session/network_session.h"
#include "entity_network_remote_peer.h"
#include "halley/bytes/serialization_dictionary.h"
#include "halley/entity/system.h"
#include "halley/entity/world.h"
namespace Halley {
class EntityFactory;
class Resources;
class World;
class NetworkSession;
class EntitySessionSharedData : public SharedData {
public:
};
class EntityClientSharedData : public SharedData {
public:
std::optional<Rect4i> viewRect;
void serialize(Serializer& s) const override;
void deserialize(Deserializer& s) override;
};
class EntityNetworkSession : NetworkSession::IListener, NetworkSession::ISharedDataHandler, public IWorldNetworkInterface {
public:
class IEntityNetworkSessionListener {
public:
virtual ~IEntityNetworkSessionListener() = default;
virtual void onStartSession(NetworkSession::PeerId myPeerId) = 0;
virtual void onRemoteEntityCreated(EntityRef entity, NetworkSession::PeerId peerId) {}
virtual void setupInterpolators(DataInterpolatorSet& interpolatorSet, EntityRef entity, bool remote) = 0;
virtual bool isEntityInView(EntityRef entity, const EntityClientSharedData& clientData) = 0;
};
EntityNetworkSession(std::shared_ptr<NetworkSession> session, Resources& resources, std::set<String> ignoreComponents, IEntityNetworkSessionListener* listener);
~EntityNetworkSession() override;
void setWorld(World& world, SystemMessageBridge bridge);
void sendUpdates(Time t, Rect4i viewRect, gsl::span<const std::pair<EntityId, uint8_t>> entityIds); // Takes pairs of entity id and owner peer id
void receiveUpdates();
World& getWorld() const;
EntityFactory& getFactory() const;
NetworkSession& getSession() const;
bool hasWorld() const;
const EntityFactory::SerializationOptions& getEntitySerializationOptions() const;
const EntityDataDelta::Options& getEntityDeltaOptions() const;
const SerializerOptions& getByteSerializationOptions() const;
SerializationDictionary& getSerializationDictionary();
Time getMinSendInterval() const;
void onRemoteEntityCreated(EntityRef entity, NetworkSession::PeerId peerId);
void requestSetupInterpolators(DataInterpolatorSet& interpolatorSet, EntityRef entity, bool remote);
void setupOutboundInterpolators(EntityRef entity);
bool isReadyToStart() const;
bool isEntityInView(EntityRef entity, const EntityClientSharedData& clientData) const;
Vector<Rect4i> getRemoteViewPorts() const;
bool isHost() override;
bool isRemote(ConstEntityRef entity) const override;
void sendEntityMessage(EntityRef entity, int messageType, Bytes messageData) override;
void sendSystemMessage(String targetSystem, int messageType, Bytes messageData, SystemMessageDestination destination, SystemMessageCallback callback) override;
void sendToAll(EntityNetworkMessage msg);
void sendToPeer(EntityNetworkMessage msg, NetworkSession::PeerId peerId);
protected:
void onStartSession(NetworkSession::PeerId myPeerId) override;
void onPeerConnected(NetworkSession::PeerId peerId) override;
void onPeerDisconnected(NetworkSession::PeerId peerId) override;
std::unique_ptr<SharedData> makeSessionSharedData() override;
std::unique_ptr<SharedData> makePeerSharedData() override;
private:
struct QueuedMessage {
NetworkSession::PeerId fromPeerId;
EntityNetworkMessage message;
};
struct PendingSysMsgResponse {
SystemMessageCallback callback;
};
Resources& resources;
std::shared_ptr<EntityFactory> factory;
IEntityNetworkSessionListener* listener = nullptr;
SystemMessageBridge messageBridge;
uint32_t systemMessageId = 0;
HashMap<uint32_t, PendingSysMsgResponse> pendingSysMsgResponses;
EntityFactory::SerializationOptions entitySerializationOptions;
EntityDataDelta::Options deltaOptions;
SerializerOptions byteSerializationOptions;
SerializationDictionary serializationDictionary;
std::shared_ptr<NetworkSession> session;
Vector<EntityNetworkRemotePeer> peers;
Vector<QueuedMessage> queuedPackets;
HashMap<int, Vector<EntityNetworkMessage>> outbox;
bool readyToStart = false;
bool canProcessMessage(const EntityNetworkMessage& msg) const;
void processMessage(NetworkSession::PeerId fromPeerId, EntityNetworkMessage msg);
void onReceiveEntityUpdate(NetworkSession::PeerId fromPeerId, EntityNetworkMessage msg);
void onReceiveReady(NetworkSession::PeerId fromPeerId, const EntityNetworkMessageReadyToStart& msg);
void onReceiveMessageToEntity(NetworkSession::PeerId fromPeerId, const EntityNetworkMessageEntityMsg& msg);
void onReceiveSystemMessage(NetworkSession::PeerId fromPeerId, const EntityNetworkMessageSystemMsg& msg);
void onReceiveSystemMessageResponse(NetworkSession::PeerId fromPeerId, const EntityNetworkMessageSystemMsgResponse& msg);
void sendMessages();
void setupDictionary();
};
}
| {
"alphanum_fraction": 0.8051500406,
"avg_line_length": 37.6488549618,
"ext": "h",
"hexsha": "cdb33cc917e721893a2577db710fb1a3a18442ec",
"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/entity/entity_network_session.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/entity/entity_network_session.h",
"max_line_length": 162,
"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/entity/entity_network_session.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1109,
"size": 4932
} |
#pragma once
#include <algorithm>
#include <array>
#include <cstdint>
#include <initializer_list>
#include <iterator>
#include <sstream>
#include <string>
#include <absl/types/span.h>
#include <gsl/gsl>
#include "chainerx/constant.h"
#include "chainerx/error.h"
#include "chainerx/optional_container_arg.h"
#include "chainerx/stack_vector.h"
namespace chainerx {
class Axes : public StackVector<int8_t, kMaxNdim> {
using BaseVector = StackVector<int8_t, kMaxNdim>;
public:
using const_iterator = BaseVector::const_iterator;
using const_reverse_iterator = BaseVector::const_reverse_iterator;
// TODO(niboshi): Declare other types required for this class to be a container.
Axes() = default;
~Axes() = default;
// by iterators
template <typename InputIt>
Axes(InputIt first, InputIt last) {
if (std::distance(first, last) > kMaxNdim) {
throw DimensionError{"too many dimensions: ", std::distance(first, last)};
}
insert(begin(), first, last);
}
// by span
explicit Axes(absl::Span<const int8_t> axes) : Axes{axes.begin(), axes.end()} {}
// by initializer list
Axes(std::initializer_list<int8_t> axes) : Axes{axes.begin(), axes.end()} {}
// copy
Axes(const Axes&) = default;
Axes& operator=(const Axes&) = default;
// move
Axes(Axes&&) = default;
Axes& operator=(Axes&&) = default;
std::string ToString() const;
int8_t ndim() const noexcept { return gsl::narrow_cast<int8_t>(size()); }
int8_t& operator[](int8_t index) {
if (!(0 <= index && static_cast<size_t>(index) < size())) {
throw DimensionError{"index out of bounds"};
}
return this->StackVector::operator[](index);
}
const int8_t& operator[](int8_t index) const {
if (!(0 <= index && static_cast<size_t>(index) < size())) {
throw DimensionError{"index out of bounds"};
}
return this->StackVector::operator[](index);
}
// span
absl::Span<const int8_t> span() const { return {*this}; }
};
std::ostream& operator<<(std::ostream& os, const Axes& axes);
using OptionalAxes = OptionalContainerArg<Axes>;
namespace internal {
bool IsAxesPermutation(const Axes& axes, int8_t ndim);
// Normalizes possibly-negative axis to non-negative axis in [0, ndim).
// If `axis` does not fit in [-ndim, ndim), DimensionError is thrown.
int8_t NormalizeAxis(int8_t axis, int8_t ndim);
// Resolves the axis argument of many operations.
// Negative axes are converted to non-negative ones (by wrapping at ndim).
Axes GetNormalizedAxes(const Axes& axis, int8_t ndim);
// Resolves the axis argument of many operations.
// Negative axes are converted to non-negative ones (by wrapping at ndim).
// Axes are then sorted.
Axes GetSortedAxes(const Axes& axis, int8_t ndim);
// Resolves the axis argument of many operations.
// Negative axes are converted to non-negative ones (by wrapping at ndim).
// Axes are then sorted.
// nullopt is converted to a vector of all axes.
Axes GetSortedAxesOrAll(const OptionalAxes& axis, int8_t ndim);
} // namespace internal
} // namespace chainerx
| {
"alphanum_fraction": 0.6775316456,
"avg_line_length": 29.5327102804,
"ext": "h",
"hexsha": "c80b224338e1c8e5d2818658e0252d0de8db8869",
"lang": "C",
"max_forks_count": 1150,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T02:29:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-06-02T03:39:46.000Z",
"max_forks_repo_head_hexsha": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zaltoprofen/chainer",
"max_forks_repo_path": "chainerx_cc/chainerx/axes.h",
"max_issues_count": 5998,
"max_issues_repo_head_hexsha": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1",
"max_issues_repo_issues_event_max_datetime": "2022-03-08T01:42:44.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-06-01T06:40:17.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zaltoprofen/chainer",
"max_issues_repo_path": "chainerx_cc/chainerx/axes.h",
"max_line_length": 86,
"max_stars_count": 3705,
"max_stars_repo_head_hexsha": "3b03f9afc80fd67f65d5e0395ef199e9506b6ee1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zaltoprofen/chainer",
"max_stars_repo_path": "chainerx_cc/chainerx/axes.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T10:46:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-06-01T07:36:12.000Z",
"num_tokens": 786,
"size": 3160
} |
// Alessandro Casalino
//
// Compile with (Mac with default homebrew gsl 2.6) gcc-9 -O2 coupled_quintessence_evolve.c -o coupled_quintessence_evolve.exe -L/usr/local/Cellar/gsl/2.6/lib -I/usr/local/Cellar/gsl/2.6/include -lgsl
// Run with ./coupled_quintessence_evolve.exe
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>
// PHYSICAL PARAMETERS VALUES
// INITIAL CONDITIONS
// Initial value of the scale factor
double a_init = 1e-14;
// Final value of the scale factor
double a_end = 1.1;
// Values of fractional density for the cosmological matter today
double Omega_rad_0 = 8e-5;
double Omega_b_0 = 0.0486;//0.0490439;
double Omega_Lambda_0 = 0.;//0.6911;
double Omega_cdm_0 = 0.2589;//0.264201;
// Physical constants for output conversions
double _G_ = 6.67428e-11; /**< Newton constant in m^3/Kg/s^2 */
double _MPc_over_m_ = 3.085677581282e22; // Conversion factor from Mpc to m
double _Gyr_over_Mpc_ = 3.06601394e2; // Conversion factor from Gyr to Mpc
double _c_ = 2.99792458e8; // Speed of light in m/s
double _H0_ = 67.74; // H0 of LCDM in Km/s/Mpc (h:0.6731)
double fourpiG = 0.5;
double T_CONF = 1.;
// COMPUTATION PARAMETERS VALUES
// Number of points used in the computation
int points = (int) 1e6;
// Max particle horizon value
double max_tau = 40.;
// Min particle horizon value
double min_tau = 1e-9;
// Raise this value to make the csv file smaller, but decreasing resolution
// The value inserted is the ratio between the number of values written in a full resolution file / decreased resolution file
int csv_resolution = 10;
// BISECTION PARAMTERS
// Bisection precision
double delta_bisection = 1e-2;
// Bisection target
// 1: mg_field
// 2: mg_field_p
// 3: potential_constant
int bisection_type = 3;
double bisection_min = 0.;
double bisection_max = 20.;
// Initial conditions (considered accordingly to the bisection_type choice)
double mg_field_bk_0 = 1e-20;
double mg_field_p_bk_0 = 1.;
// TEST MODE
// Provides some informations on the terminal and the .csv file during the computation (1: on, others: off)
int TEST_MODE = 1;
// Definition of the POTENTIAL
// For a list of the models see above
double mg_pot_const = 1.;
double mg_pot_exp = -0.5;
double mg_pot(const double mg_field_bk) {
return mg_pot_const * pow(mg_field_bk, mg_pot_exp);
}
double mg_pot_p(const double mg_field_bk) {
return mg_pot_exp * mg_pot_const * pow(mg_field_bk, mg_pot_exp - 1.);
}
// Definition of the COUPLING FUNCION
// For a list of the models see above
double mg_coupl_const = 0.1;
double mg_coupl(const double mg_field_bk) {
// 2 factor to be consistent with hi_class units (8 pi G = 1)
return mg_coupl_const * mg_field_bk * mg_field_bk;
}
double mg_coupl_p(const double mg_field_bk) {
return 2.*mg_coupl_const * mg_field_bk;
}
double mg_coupl_pp(const double mg_field_bk) {
return 2.*mg_coupl_const;
}
// Definitions of DIFFERENTIAL EQUATION system
// Need to have first order equations to use Runge Kutta
//
double a_p_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)
{
return a_p;
}
double a_pp_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)
{
double a3 = a * a * a;
double rhoa3 = (Omega_cdm_0 + Omega_b_0) + (Omega_Lambda_0 * a3) + (Omega_rad_0 / a);
double Pa3 = - (Omega_Lambda_0 * a3) + 1./3. * (Omega_rad_0 / a );
return fourpiG / 3. * ( (rhoa3 - 3. * Pa3) - a * mg_field_p_bk * mg_field_p_bk * (1. + 3./2./fourpiG * mg_coupl_pp(mg_field_bk)) + 4. * a3 * mg_pot(mg_field_bk) + 3./2./fourpiG * a3 * mg_pot_p(mg_field_bk) * mg_coupl_p(mg_field_bk))/(1. + mg_coupl(mg_field_bk) + 3./4./fourpiG * mg_coupl_p(mg_field_bk) * mg_coupl_p(mg_field_bk));
}
double mg_field_bk_p_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)
{
return mg_field_p_bk;
}
double mg_field_bk_pp_rk4(const double a, const double a_p, const double mg_field_bk, const double mg_field_p_bk)
{
double a2 = a * a;
double rhoa2 = (Omega_cdm_0 + Omega_b_0) / a + (Omega_Lambda_0 * a2) + (Omega_rad_0 / a / a);
double Pa2 = - (Omega_Lambda_0 * a2) + 1./3. * (Omega_rad_0 / a / a );
return - 2. * a_p/a * mg_field_p_bk + ( - mg_pot_p(mg_field_bk) * a2 * ( 1. + mg_coupl(mg_field_bk) ) + ( rhoa2 - 3. * Pa2 + 4. * a2 * mg_pot(mg_field_bk) - mg_field_p_bk * mg_field_p_bk * ( 1. + 3./2./fourpiG * mg_coupl_pp(mg_field_bk) ) ) /2. * mg_coupl_p(mg_field_bk) ) / (1. + mg_coupl(mg_field_bk) + 3./4./fourpiG * mg_coupl_p(mg_field_bk) * mg_coupl_p(mg_field_bk) );
}
double Hconf(const double a, const double mg_field_bk, const double mg_field_p_bk)
{
double a2 = a * a;
double rhoa2 = (Omega_cdm_0 + Omega_b_0) / a + (Omega_Lambda_0 * a2) + (Omega_rad_0 / a / a);
return - mg_field_p_bk * mg_coupl_p(mg_field_bk)/(1. + mg_coupl(mg_field_bk))/2. + sqrt((2. * fourpiG / 3.) * (1. + mg_coupl(mg_field_bk)) * ( rhoa2 + (mg_field_p_bk * mg_field_p_bk / 2.) + (a2 * mg_pot(mg_field_bk)) ) + mg_field_p_bk * mg_field_p_bk/4. * mg_coupl_p(mg_field_bk) * mg_coupl_p(mg_field_bk))/(1. + mg_coupl(mg_field_bk));
}
// Integrand for the particle horizon integral
double particleHorizonIntegrand(double a, double mg_field_bk, double mg_field_p_bk)
{
return 1. / ( a * Hconf(a, mg_field_bk, mg_field_p_bk) );
}
// Particle horizon integral step
double particleHorizon(const int i, double * a, double * mg_field_bk, double * mg_field_p_bk) {
double h = a[i]-a[i-1];
double fa = particleHorizonIntegrand(a[i-1],mg_field_bk[i-1],mg_field_p_bk[i-1]);
double fb = particleHorizonIntegrand(a[i],mg_field_bk[i],mg_field_p_bk[i]);
return h*(fa+fb)/2.;
}
int scan_for_a0 (double * a, double ae) {
int i=0;
for(i=0; a[i] <= ae && i < points; i++);
return i;
}
// Function used to print results stored in vectors as a csv file
void csv(double * t, double * a, double * a_p, double * mg_field_bk, double * mg_field_p_bk, double * particleHorizonVec, char * filename) {
FILE *fp;
fp = fopen (filename, "w+");
fprintf(fp, "%s, %s, %s, %s, %s, %s, %s, %s", "t", "a(t)", "H(t)/H0", "H_prime(t)/H0^2", "Omega_df", "Omega_r", "Omega_b", "Omega_cdm");
fprintf(fp, ", %s", "omega_df");
fprintf(fp, ", %s", "PH"); // Particle horizon
fprintf(fp, ", %s", "mg_field");
fprintf(fp, ", %s", "mg_field_p");
if(TEST_MODE==1) fprintf(fp, ", %s", "H_check(t)/H0");
fprintf(fp, "\n");
// Time conversion factor
// double tcf = 1./_H0_/(60.*60.*24.*365.*1e9)*_MPc_over_m_/1000.;
int i = 0;
double particleHorizonRes = 0.;
for(i=1;i<points;i++){
particleHorizonRes += particleHorizon(i,a,mg_field_bk,mg_field_p_bk);
particleHorizonVec[i] = particleHorizonRes;
}
i = 0;
int i_a0 = scan_for_a0(a,1.);
double H0 = Hconf(a[i_a0],mg_field_bk[i_a0],mg_field_p_bk[i_a0]);
int w1=0, w2=0, w3=0;
while( a[i] <= a_end ){
double H = Hconf(a[i],mg_field_bk[i],mg_field_p_bk[i]); // this is the Hubble constant with conformal time
double H_prime = a_pp_rk4(a[i], a_p[i], mg_field_bk[i], mg_field_p_bk[i]) / a[i] - H * H; // this is Hubble prime with conformal time
double phi_pp = mg_field_bk_pp_rk4(a[i], a_p[i], mg_field_bk[i], mg_field_p_bk[i]);
double P_df = - mg_pot(mg_field_bk[i]) + mg_field_p_bk[i] * mg_field_p_bk[i]/2./a[i]/a[i] + 1./(2.*fourpiG)*( mg_coupl(mg_field_bk[i])*(H*H+2.*H_prime) + (H*mg_field_p_bk[i]+phi_pp) * mg_coupl_p(mg_field_bk[i]) + mg_field_p_bk[i] * mg_field_p_bk[i] * mg_coupl_pp(mg_field_bk[i]))/a[i]/a[i];
double rho_df = mg_pot(mg_field_bk[i]) + mg_field_p_bk[i] * mg_field_p_bk[i]/2./a[i]/a[i] - 3./2./fourpiG * ( H * mg_field_p_bk[i] * mg_coupl_p(mg_field_bk[i]) + H * H * mg_coupl(mg_field_bk[i]))/a[i]/a[i];
double Omega_df = 2. * fourpiG / 3. * a[i] * a[i] * rho_df /H /H;
double Omega_rad = 2. * fourpiG / 3. * Omega_rad_0 /a[i] /a[i] /H /H;
double Omega_b = 2. * fourpiG / 3. * Omega_b_0 /a[i] /H /H;
double Omega_cdm = 2. * fourpiG / 3. * Omega_cdm_0 /a[i] /H /H;
if(rho_df<0 && w1==0 && i>0){
printf("WARNING: the energy density is negative at a = %e\n", a[i]);
w1++;
}
if( (Omega_df+Omega_rad+Omega_b+Omega_cdm > 1.01 || Omega_df+Omega_rad+Omega_b+Omega_cdm < 0.99) && w2==0){
printf("WARNING: the fractional density sum is %e at a = %e\n", Omega_df+Omega_rad+Omega_b+Omega_cdm,a[i]);
w2++;
}
if( (Omega_df> 1. || Omega_rad > 1. || Omega_b > 1. || Omega_cdm > 1.) && w3==0){
printf("WARNING: one fractional density is > 1 at a = %e\n", a[i]);
w3++;
}
double omega_df = P_df/rho_df;
if(T_CONF==0) H_prime = ( H_prime - H * H )/a[i]/a[i]; // this is Hubble prime with cosmological time
if(T_CONF==0) H = H / a[i]; // this it the Hubble constant with cosmological time
fprintf(fp, "%e, %e, %e, %e, %e, %e, %e, %e", t[i], a[i], H / H0, H_prime /H0 /H0, Omega_df, Omega_rad, Omega_b, Omega_cdm );
fprintf(fp, ", %e", omega_df);
fprintf(fp, ", %e", particleHorizonVec[i]);
fprintf(fp, ", %e", mg_field_bk[i]);
fprintf(fp, ", %e", mg_field_p_bk[i]);
if(TEST_MODE==1){
double H_test;
H_test = a_p[i]/a[i];
if(T_CONF==0) H_test = H_test / a[i];
fprintf(fp, ", %e", H_test / sqrt(2. * fourpiG / 3. / (1. + mg_coupl(mg_field_bk[i_a0])) ));
}
fprintf(fp, "\n");
if(a[i+csv_resolution]<= a_end){
i=i+csv_resolution;
}
else{
i++;
}
}
fclose(fp);
}
// This divides an interval in a logarithmic scale of basis 10, and store results in input vector v
void logscale10 (double * v, double A, double B, int points){
int i;
double a = log10(A);
double b = log10(B);
double h = (b - a) / (points-1.0);
for(i=0;i<points;i++){
v[i] = pow(10.0, a + i * h);
}
}
// This function is a temporal step of the Runge-Kutta 4 method:
// evolves the system for a time equal to dtau (h in the program)
void mg_rungekutta4bg(double * f, const double dtau)
{
double a = f[1];
double a_p = f[2];
double mg_field_bk = f[3];
double mg_field_p_bk = f[4];
double k1a, k2a, k3a, k4a;
double k1ap, k2ap, k3ap, k4ap;
double k1f, k2f, k3f, k4f;
double k1fp, k2fp, k3fp, k4fp;
k1a = a_p_rk4 (a, a_p, mg_field_bk, mg_field_p_bk);
k1ap = a_pp_rk4 (a, a_p, mg_field_bk, mg_field_p_bk);
k1f = mg_field_bk_p_rk4 (a, a_p, mg_field_bk, mg_field_p_bk);
k1fp = mg_field_bk_pp_rk4 (a, a_p, mg_field_bk, mg_field_p_bk);
k2a = a_p_rk4 (a + k1a * dtau / 2., a_p + k1ap * dtau / 2., mg_field_bk + k1f * dtau / 2., mg_field_p_bk + k1fp * dtau / 2.);
k2ap = a_pp_rk4 (a + k1a * dtau / 2., a_p + k1ap * dtau / 2., mg_field_bk + k1f * dtau / 2., mg_field_p_bk + k1fp * dtau / 2.);
k2f = mg_field_bk_p_rk4 (a + k1a * dtau / 2., a_p + k1ap * dtau / 2., mg_field_bk + k1f * dtau / 2., mg_field_p_bk + k1fp * dtau / 2.);
k2fp = mg_field_bk_pp_rk4 (a + k1a * dtau / 2., a_p + k1ap * dtau / 2., mg_field_bk + k1f * dtau / 2., mg_field_p_bk + k1fp * dtau / 2.);
k3a = a_p_rk4 (a + k2a * dtau / 2., a_p + k2ap * dtau / 2., mg_field_bk + k2f * dtau / 2., mg_field_p_bk + k2fp * dtau / 2.);
k3ap = a_pp_rk4 (a + k2a * dtau / 2., a_p + k2ap * dtau / 2., mg_field_bk + k2f * dtau / 2., mg_field_p_bk + k2fp * dtau / 2.);
k3f = mg_field_bk_p_rk4 (a + k2a * dtau / 2., a_p + k2ap * dtau / 2., mg_field_bk + k2f * dtau / 2., mg_field_p_bk + k2fp * dtau / 2.);
k3fp = mg_field_bk_pp_rk4 (a + k2a * dtau / 2., a_p + k2ap * dtau / 2., mg_field_bk + k2f * dtau / 2., mg_field_p_bk + k2fp * dtau / 2.);
k4a = a_p_rk4 (a + k3a * dtau, a_p + k3ap * dtau, mg_field_bk + k3f * dtau, mg_field_p_bk + k3fp * dtau);
k4ap = a_pp_rk4 (a + k3a * dtau, a_p + k3ap * dtau, mg_field_bk + k3f * dtau, mg_field_p_bk + k3fp * dtau);
k4f = mg_field_bk_p_rk4 (a + k3a * dtau, a_p + k3ap * dtau, mg_field_bk + k3f * dtau, mg_field_p_bk + k3fp * dtau);
k4fp = mg_field_bk_pp_rk4 (a + k3a * dtau, a_p + k3ap * dtau, mg_field_bk + k3f * dtau, mg_field_p_bk + k3fp * dtau);
f[1] += dtau * (k1a + 2. * k2a + 2. * k3a + k4a) / 6.;
f[2] += dtau * (k1ap + 2. * k2ap + 2. * k3ap + k4ap) / 6.;
f[3] += dtau * (k1f + 2. * k2f + 2. * k3f + k4f) / 6.;
f[4] += dtau * (k1fp + 2. * k2fp + 2. * k3fp + k4fp) / 6.;
}
// This function evolves the system with the Runge-Kutta 4 method until t_stop
double rk4(double * t, double * a, double * a_p, double * mg_field_bk, double * mg_field_p_bk, double Omega_f_0) {
double f[5];
int i = 0;
// Call the function for a logarithmic scale of time
// We don't start from t = 0 to avoid problems with quintessence potentials
logscale10(t,min_tau,max_tau,points);
while( i < points - 1 ){
f[0] = t[i];
f[1] = a[i];
f[2] = a_p[i];
f[3] = mg_field_bk[i];
f[4] = mg_field_p_bk[i];
mg_rungekutta4bg(f, t[i+1]-t[i]);
a[i+1] = f[1];
a_p[i+1] = f[2];
mg_field_bk[i+1] = f[3];
mg_field_p_bk[i+1] = f[4];
i++;
}
i = scan_for_a0(a,1.);
double H = Hconf(a[i], mg_field_bk[i], mg_field_p_bk[i]);
double rho_df = mg_pot(mg_field_bk[i]) + mg_field_p_bk[i] * mg_field_p_bk[i]/2./a[i]/a[i] - 3./2./fourpiG * ( H * mg_field_p_bk[i] * mg_coupl_p(mg_field_bk[i]) + H * H * mg_coupl(mg_field_bk[i]))/a[i]/a[i];
double Omega_df = 2. * fourpiG / 3. * a[i] * a[i] * rho_df /H /H;
return Omega_df - Omega_f_0;
}
double bisection (double min, double max, double * t, double * a, double * a_p, double * mg_field_bk, double * mg_field_p_bk, const double Omega_f_0, int type) {
double result = 0.;
double C = (max+min)/2.;
if(type==1){
printf("\t-> Bisection target: mg_field_bk.\n", result);
if(TEST_MODE==1) printf("\n");
while(fabs((max-min)/min)>delta_bisection){
a_p[0] = a_init * Hconf(a[0], min, mg_field_p_bk[0]);
mg_field_bk[0] = min;
double rk4_min = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);
a_p[0] = a_init * Hconf(a[0], C, mg_field_p_bk[0]);
mg_field_bk[0] = C;
double rk4_C = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);
if(rk4_min*rk4_C>=0) {
min=C;
}
else {
max=C;
}
C=(max+min)/2.;
if (TEST_MODE == 1) printf("TEST_MODE ON - min: %e , max: %e, C: %e, rk4_min: %e , rk4_C: %e \n", min, max, C, rk4_min, rk4_C);
}
result = (max+min)/2.;
if(TEST_MODE==1) printf("\n");
printf("\t-> Result of bisection method is mg_field_bk: %e (internal units).\n", result);
}
else if(type==2){
printf("\t-> Bisection target: mg_field_p_bk.\n", result);
if(TEST_MODE==1) printf("\n");
while(fabs((max-min)/min)>delta_bisection){
a_p[0] = a_init * Hconf(a[0], mg_field_bk[0], min);
mg_field_p_bk[0] = min;
double rk4_min = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);
a_p[0] = a_init * Hconf(a[0], mg_field_bk[0], C);
mg_field_p_bk[0] = C;
double rk4_C = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);
if(rk4_min*rk4_C>=0) {
min=C;
}
else {
max=C;
}
C=(max+min)/2.;
if (TEST_MODE == 1) printf("TEST_MODE ON - min: %e , max: %e, C: %e, rk4_min: %e , rk4_C: %e \n", min, max, C, rk4_min, rk4_C);
}
result = (max+min)/2.;
if(TEST_MODE==1) printf("\n");
printf("\t-> Result of bisection method is mg_field_p_bk: %e (internal units).\n", result);
}
else if(type==3){
printf("\t-> Bisection target: mg_pot_const.\n", result);
if(TEST_MODE==1) printf("\n");
while(fabs((max-min)/min)>delta_bisection){
mg_pot_const = min;
a_p[0] = a_init * Hconf(a[0], mg_field_bk[0], mg_field_p_bk[0]);
double rk4_min = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);
mg_pot_const = C;
a_p[0] = a_init * Hconf(a[0], mg_field_bk[0], mg_field_p_bk[0]);
double rk4_C = rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);
if(rk4_min*rk4_C>=0) {
min=C;
}
else {
max=C;
}
C=(max+min)/2.;
if (TEST_MODE == 1) printf("TEST_MODE ON - min: %e , max: %e, C: %e, rk4_min: %e , rk4_C: %e \n", min, max, C, rk4_min, rk4_C);
}
result = (max+min)/2.;
if(TEST_MODE==1) printf("\n");
printf("\t-> Result of bisection method is mg_pot_const: %e (internal units).\n", result);
}
else{
result = 0.;
}
return result;
}
int main() {
double Omega_f_0 = 1. - Omega_Lambda_0 - Omega_rad_0 - Omega_b_0 - Omega_cdm_0;
printf("\n\t\t----------------------------------------\n\n");
// Definition of the vector needed for the evolution functions
double * t; double * a; double * a_p; double * mg_field_bk; double * mg_field_p_bk; double * particleHorizonVec;
t = (double *) malloc(sizeof(double) * points);
a = (double *) malloc(sizeof(double) * points);
a_p = (double *) malloc(sizeof(double) * points);
mg_field_bk = (double *) malloc(sizeof(double) * points);
mg_field_p_bk = (double *) malloc(sizeof(double) * points);
particleHorizonVec = (double *) malloc(sizeof(double) * points);
if(!t||!a||!a_p||!mg_field_bk||!mg_field_p_bk||!particleHorizonVec){
printf("Error! The memory cannot be allocated. The program will be terminated.\n");
exit(1);
}
// Initial conditions (tau=0)
a[0] = a_init;
mg_field_bk[0] = mg_field_bk_0;
mg_field_p_bk[0] = mg_field_p_bk_0;
printf("\n Extended quintessence evolution\n");
printf("\n Parameters used: \n");
printf("\t- Potential constant: %e\n", mg_pot_const);
printf("\t- Potential exponent: %e\n", mg_pot_exp);
printf("\t- Function constant: %e\n", mg_coupl_const);
printf(" Searching for best initial value for the dark fluid ... \n \n");
double bisection_result = bisection(bisection_min, bisection_max, t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0,bisection_type);
if (bisection_type==1) {
mg_field_bk[0] = bisection_result;
if(mg_field_bk[0] > bisection_max*(1.-0.05)) printf("\n\n WARNING: it seems that the initial value is too near the bounds! \n\n");
}
else if (bisection_type==2) {
mg_field_p_bk[0] = bisection_result;
if(mg_field_p_bk[0] > bisection_max*(1.-0.05)) printf("\n\n WARNING: it seems that the initial value is too near the bounds! \n\n");
}
else if (bisection_type==3) {
mg_pot_const = bisection_result;
if(mg_pot_const > bisection_max*(1.-0.05)) printf("\n\n WARNING: it seems that the initial value is too near the bounds! \n\n");
}
else {
printf("No bisection type chosen. The evolution will be computed with provided initial conditions.");
}
a_p[0] = a_init * Hconf(a_init, mg_field_bk[0], mg_field_p_bk[0]);
printf("\n\n Evolving the system ...\n");
rk4(t, a, a_p, mg_field_bk, mg_field_p_bk, Omega_f_0);
int last_int = scan_for_a0(a,a_end);
int last_int_print = scan_for_a0(a,1.);
if(last_int >= points-1) printf("\n\n WARNING: the a = a_end value seems not to be reached in the result vectors! \n\n");
double t_age = 0.;
int i = 0;
for(i=2;i<last_int_print;i++){
t_age += (a[i]+a[i-1])*(t[i]-t[i-1])/2.;
}
printf("\n Results:\n");
printf("\t- H0: %f \n", a_p[last_int_print]/a[last_int_print]/sqrt(2. * fourpiG / 3.) );
printf("\t- Age of the Universe: %f Gyr\n", sqrt(2. * fourpiG / 3.) * t_age/_H0_/(60.*60.*24.*365.*1e9)*_MPc_over_m_/1000.);//t[last_int_print]/((4*M_PI)/3.)
if(TEST_MODE==1) printf("\t- Number of points: %d \n", last_int);
char filename[50];
sprintf (filename, "coupl_mg_bk.csv");
csv(t, a, a_p, mg_field_bk, mg_field_p_bk, particleHorizonVec, filename);
printf("\n The results are saved in '.csv' files.\n");
if(TEST_MODE==1) printf("\n TEST_MODE ON: check the values of H in .csv file. They must be equal!");
printf("\n\t\t----------------------------------------\n");
free(a);free(a_p);free(mg_field_bk);free(mg_field_p_bk);free(particleHorizonVec);
printf("\n");
exit(0);
}
| {
"alphanum_fraction": 0.6209092691,
"avg_line_length": 35.1931034483,
"ext": "c",
"hexsha": "ae0a8353532263f4b4ce354a2169ade96e7a3935",
"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": "97dd3f4320f0c61eccae387d5fd945336084e863",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "alessandrocasalino/mgevolution",
"max_forks_repo_path": "mg/coupled_quintessence_evolve.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "97dd3f4320f0c61eccae387d5fd945336084e863",
"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": "alessandrocasalino/mgevolution",
"max_issues_repo_path": "mg/coupled_quintessence_evolve.c",
"max_line_length": 374,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "97dd3f4320f0c61eccae387d5fd945336084e863",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "alessandrocasalino/mgevolution",
"max_stars_repo_path": "mg/coupled_quintessence_evolve.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7401,
"size": 20412
} |
#include <gsl/gsl_sf_gamma.h>
//
// TIMING
//
// Clock functions
static vector<double> ClockTimes;
static double C0;
double Clock() { return double(clock()) / CLOCKS_PER_SEC; }
void StartClocking()
{
ClockTimes.clear();
C0 = Clock();
}
void ClockCheckpoint(unsigned int cp)
{
double C1 = Clock();
if (cp >= ClockTimes.size()) ClockTimes.resize(cp + 1, 0.0);
ClockTimes[cp] += C1 - C0;
C0 = C1;
}
void ShowClockInfo()
{
double total = 0;
for (unsigned int i = 0; i < ClockTimes.size(); ++i)
{
cout << "Checkpoint " << i << ": " << ClockTimes[i] << "\n";
total += ClockTimes[i];
}
cout << "Total time: " << total << " seconds.\n";
}
//
// DISCRETE DISTRIBUTION
//
struct Parameters;
class MNApprox
{
public:
static const unsigned int NVariants = 32;
static const unsigned int VariantMask = 31;
void Set(Parameters& P, Randomizer& Rand, vector<double>& p);
void operator()(unsigned int N, vector<unsigned int>& out)
{
out.assign(out.size(), 0);
for (unsigned int shift = 0; shift < 32; ++shift)
{
if ((N >> shift) & 1)
{
for (unsigned int i = 0; i < out.size(); ++i)
{
out[i] += x[shift][cycle[shift]][i];
}
cycle[shift] = (cycle[shift] + 1) & VariantMask;
}
}
}
private:
vector<vector<vector<unsigned int>>> x;
vector<unsigned int> cycle;
};
// An arbitrary discrete distribution, used for maturation times in compartments
class Discrete
{
public:
// Create distribution from set of unnormalised weights
void operator=(std::vector<double> uw)
{
weights = uw;
double total = accumulate(weights.begin(), weights.end(), 0.0);
for (auto& w : weights)
w /= total;
storage.assign(weights.size(), 0);
}
// Normalised weights
std::vector<double> weights;
// Storage for draws of integers
std::vector<unsigned int> storage;
// Fast approximate multinomial draws
MNApprox mn_approx;
};
//
// MATRIX
//
struct Matrix
{
Matrix()
: nc(0)
{ }
Matrix(double X, unsigned int nrow, unsigned int ncol)
: x(nrow * ncol, X), nc(ncol)
{ }
Matrix(vector<double> X, unsigned int nrow, unsigned int ncol)
: x(X), nc(ncol)
{
if (x.size() != nrow * ncol)
throw runtime_error("Improperly sized matrix.");
}
double& operator()(unsigned int i, unsigned int j)
{
return x[i * nc + j];
}
unsigned int NCol() { return nc; }
unsigned int NRow() { return x.size() / nc; }
vector<double> x;
unsigned int nc;
};
void MNApprox::Set(Parameters& P, Randomizer& Rand, vector<double>& p)
{
x.assign(32, vector<vector<unsigned int>>(NVariants, vector<unsigned int>(p.size(), 0)));
cycle.assign(NVariants, 0);
for (unsigned int shift = 0; shift < 32; ++shift)
for (unsigned int variant = 0; variant < NVariants; ++variant)
gsl_ran_multinomial(Rand.GSL_RNG(), p.size(), 1 << shift, &p[0], &x[shift][variant][0]);
}
| {
"alphanum_fraction": 0.5706143129,
"avg_line_length": 22.0839160839,
"ext": "h",
"hexsha": "bdd461854490a1eb809e02a1b4941ff26406edfa",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-07-15T00:11:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-15T00:11:25.000Z",
"max_forks_repo_head_hexsha": "149997f77dddfe48906e15c1e4c0dcda976c0a6f",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "yangclaraliu/covid_europe_vac_app",
"max_forks_repo_path": "deprecated_4_speed/covidm_for_fitting/model_v1/helper.h",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "149997f77dddfe48906e15c1e4c0dcda976c0a6f",
"max_issues_repo_issues_event_max_datetime": "2020-10-31T10:56:44.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-10-31T08:41:20.000Z",
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "yangclaraliu/covid_europe_vac_app",
"max_issues_repo_path": "deprecated_4_speed/covidm_for_fitting/model_v1/helper.h",
"max_line_length": 100,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "1119331676dcf397242610a4b1da08582c3e7faf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nicholasdavies/covid-tiers",
"max_stars_repo_path": "fitting/covidm_for_fitting/model_v1/helper.h",
"max_stars_repo_stars_event_max_datetime": "2021-11-22T07:33:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-31T22:18:20.000Z",
"num_tokens": 843,
"size": 3158
} |
/* randist/chisq.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_sf_gamma.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* The chisq distribution has the form
p(x) dx = (1/(2*Gamma(nu/2))) (x/2)^(nu/2 - 1) exp(-x/2) dx
for x = 0 ... +infty */
double
gsl_ran_chisq (const gsl_rng * r, const double nu)
{
double chisq = 2 * gsl_ran_gamma (r, nu / 2, 1.0);
return chisq;
}
double
gsl_ran_chisq_pdf (const double x, const double nu)
{
if (x < 0)
{
return 0 ;
}
else
{
if(nu == 2.0)
{
return exp(-x/2.0) / 2.0;
}
else
{
double p;
double lngamma = gsl_sf_lngamma (nu / 2);
p = exp ((nu / 2 - 1) * log (x/2) - x/2 - lngamma) / 2;
return p;
}
}
}
| {
"alphanum_fraction": 0.6274875622,
"avg_line_length": 25.935483871,
"ext": "c",
"hexsha": "aef22ec36bdf519f2fc74a997116ed4d8f89f9be",
"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/randist/chisq.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/chisq.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/chisq.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": 502,
"size": 1608
} |
#include "rb_sm.h"
#include <stdio.h>
#include <gsl/gsl_nan.h>
#include <options/options.h>
struct sm_params rb_sm_params;
struct sm_result rb_sm_result;
void rb_sm_init_journal(const char*journal_file) {
jj_set_stream(open_file_for_writing(journal_file));
/* sm_journal_open(journal_file);*/
}
void rb_sm_close_journal() {
FILE * s = jj_get_stream();
if(s) fclose(s);
jj_set_stream(0);
}
void rb_sm_odometry(double x, double y, double theta){
rb_sm_params.first_guess[0]=x;
rb_sm_params.first_guess[1]=y;
rb_sm_params.first_guess[2]=theta;
}
void rb_sm_odometry_cov(double cov_x, double cov_y, double cov_theta){
}
struct option* ops = 0;
int rb_sm_set_configuration(const char*name, const char*value) {
if(!ops) {
ops = options_allocate(30);
sm_options(&rb_sm_params, ops);
}
if(!options_try_pair(ops, name, value)) {
return 0;
} else
return 1;
}
const char *rb_result_to_json() {
static char buf[5000];
JO jo = result_to_json(&rb_sm_params, &rb_sm_result);
strcpy(buf, jo_to_string(jo));
jo_free(jo);
return buf;
}
int rb_sm_icp() {
sm_icp(&rb_sm_params, &rb_sm_result);
return rb_sm_result.valid;
}
int rb_sm_gpm() {
sm_gpm(&rb_sm_params, &rb_sm_result);
return rb_sm_result.valid;
}
void rb_set_laser_ref(const char*s) {
rb_sm_params.laser_ref = string_to_ld(s);
/* fprintf(stderr, "Set laser_ref to %p\n ", rb_sm_params.laser_ref );*/
}
void rb_set_laser_sens(const char*s) {
rb_sm_params.laser_sens = string_to_ld(s);
/* fprintf(stderr, "Set laser_sens to %p\n ", rb_sm_params.laser_sens );*/
}
void rb_sm_cleanup() {
if(rb_sm_params.laser_ref)
ld_free(rb_sm_params.laser_ref);
if(rb_sm_params.laser_sens)
ld_free(rb_sm_params.laser_sens);
}
LDP string_to_ld(const char*s) {
JO jo = json_parse(s);
if(!jo) {
fprintf(stderr, "String passed from Ruby is invalid JSON: \n\n%s\n", s);
return 0;
}
LDP ld = json_to_ld(jo);
if(!ld) {
fprintf(stderr, "String passed from Ruby is valid JSON, "
"but can't load laser_data. \n\n%s\n", s);
return 0;
}
jo_free(jo);
return ld;
}
| {
"alphanum_fraction": 0.7196489517,
"avg_line_length": 21.1443298969,
"ext": "c",
"hexsha": "53da151003c1a66147e415ea9cf24a085bdf6efe",
"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/misc/sm_ruby_wrapper/rb_sm.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/misc/sm_ruby_wrapper/rb_sm.c",
"max_line_length": 74,
"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/misc/sm_ruby_wrapper/rb_sm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 610,
"size": 2051
} |
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_vector.h>
/* Compile all the inline matrix functions */
#define COMPILE_INLINE_STATIC
#include "build.h"
#include <gsl/gsl_matrix.h>
| {
"alphanum_fraction": 0.7462686567,
"avg_line_length": 18.2727272727,
"ext": "c",
"hexsha": "fe595fa189f61d40e911309e35a30b21f12325a4",
"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/matrix/matrix.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/matrix/matrix.c",
"max_line_length": 45,
"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/matrix/matrix.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": 51,
"size": 201
} |
/*
ODE: a program to get optime Runge-Kutta and multi-steps methods.
Copyright 2011-2019, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file rk_6_2.c
* \brief Source file to optimize Runge-Kutta 6 steps 2nd order methods.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2011-2019.
*/
#define _GNU_SOURCE
#include <string.h>
#include <math.h>
#include <libxml/parser.h>
#include <glib.h>
#include <libintl.h>
#include <gsl/gsl_rng.h>
#include "config.h"
#include "utils.h"
#include "optimize.h"
#include "rk.h"
#include "rk_6_2.h"
#define DEBUG_RK_6_2 0 ///< macro to debug.
/**
* Function to obtain the coefficients of a 6 steps 2nd order Runge-Kutta
* method.
*/
int
rk_tb_6_2 (Optimize * optimize) ///< Optimize struct.
{
long double *tb, *r;
#if DEBUG_RK_6_2
fprintf (stderr, "rk_tb_6_2: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t6 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
b21 (tb) = r[2];
t3 (tb) = r[3];
b31 (tb) = r[4];
b32 (tb) = r[5];
t4 (tb) = r[6];
b41 (tb) = r[7];
b42 (tb) = r[8];
b43 (tb) = r[9];
t5 (tb) = r[10];
b51 (tb) = r[11];
b52 (tb) = r[12];
b53 (tb) = r[13];
b54 (tb) = r[14];
b62 (tb) = r[15];
b63 (tb) = r[16];
b64 (tb) = r[17];
b65 (tb) = r[18];
b61 (tb) = (0.5L - b62 (tb) * t2 (tb) - b63 (tb) * t3 (tb)
- b64 (tb) * t4 (tb) - b65 (tb) * t5 (tb)) / t1 (tb);
if (isnan (b61 (tb)))
return 0;
rk_b_6 (tb);
#if DEBUG_RK_6_2
rk_print_tb (optimize, "rk_tb_6_2", stderr);
fprintf (stderr, "rk_tb_6_2: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 6 steps 2nd order, 3rd order in
* equations depending only in time, Runge-Kutta method.
*/
int
rk_tb_6_2t (Optimize * optimize) ///< Optimize struct.
{
long double *tb, *r;
#if DEBUG_RK_6_2
fprintf (stderr, "rk_tb_6_2t: start\n");
#endif
tb = optimize->coefficient;
r = optimize->random_data;
t6 (tb) = 1.L;
t1 (tb) = r[0];
t2 (tb) = r[1];
b21 (tb) = r[2];
t3 (tb) = r[3];
b31 (tb) = r[4];
b32 (tb) = r[5];
t4 (tb) = r[6];
b41 (tb) = r[7];
b42 (tb) = r[8];
b43 (tb) = r[9];
t5 (tb) = r[10];
b51 (tb) = r[11];
b52 (tb) = r[12];
b53 (tb) = r[13];
b54 (tb) = r[14];
b61 (tb) = r[15];
b62 (tb) = r[16];
b63 (tb) = r[17];
b64 (tb) = (1.L / 3.L - 0.5L * t5 (tb)
- b61 (tb) * t1 (tb) * (t1 (tb) - t5 (tb))
- b62 (tb) * t2 (tb) * (t2 (tb) - t5 (tb))
- b63 (tb) * t3 (tb) * (t3 (tb) - t5 (tb)))
/ (t4 (tb) * (t4 (tb) - t5 (tb)));
if (isnan (b64 (tb)))
return 0;
b65 (tb) = (0.5L - b61 (tb) * t1 (tb) - b62 (tb) * t2 (tb)
- b63 (tb) * t3 (tb) - b64 (tb) * t4 (tb)) / t5 (tb);
if (isnan (b65 (tb)))
return 0;
rk_b_6 (tb);
#if DEBUG_RK_6_2
rk_print_tb (optimize, "rk_tb_6_2t", stderr);
fprintf (stderr, "rk_tb_6_2t: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 6 steps 1st-2nd order Runge-Kutta
* pair.
*/
int
rk_tb_6_2p (Optimize * optimize) ///< Optimize struct.
{
long double *tb;
#if DEBUG_RK_6_2
fprintf (stderr, "rk_tb_6_2p: start\n");
#endif
if (!rk_tb_6_2 (optimize))
return 0;
tb = optimize->coefficient;
e61 (tb) = e62 (tb) = e63 (tb) = e64 (tb) = 0.L;
rk_e_6 (tb);
#if DEBUG_RK_6_2
fprintf (stderr, "rk_tb_6_2p: end\n");
#endif
return 1;
}
/**
* Function to obtain the coefficients of a 6 steps 1st-2nd order, 1st-3rd order
* in equations depending only in time, Runge-Kutta pair.
*/
int
rk_tb_6_2tp (Optimize * optimize) ///< Optimize struct.
{
long double *tb;
#if DEBUG_RK_6_2
fprintf (stderr, "rk_tb_6_2tp: start\n");
#endif
if (!rk_tb_6_2t (optimize))
return 0;
tb = optimize->coefficient;
e61 (tb) = e62 (tb) = e63 (tb) = e64 (tb) = 0.L;
rk_e_6 (tb);
#if DEBUG_RK_6_2
fprintf (stderr, "rk_tb_6_2tp: end\n");
#endif
return 1;
}
/**
* Function to calculate the objective function of a 6 steps 2nd order
* Runge-Kutta method.
*
* \return objective function value.
*/
long double
rk_objective_tb_6_2 (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_6_2
fprintf (stderr, "rk_objective_tb_6_2: start\n");
#endif
tb = rk->tb->coefficient;
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b60 (tb) < 0.L)
o += b60 (tb);
if (b61 (tb) < 0.L)
o += b61 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L,
fmaxl (t1 (tb),
fmaxl (t2 (tb),
fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_6_2
fprintf (stderr, "rk_objective_tb_6_2: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_6_2: end\n");
#endif
return o;
}
/**
* Function to calculate the objective function of a 6 steps 2nd order, third
* order in equations depending only on time, Runge-Kutta method.
*
* \return objective function value.
*/
long double
rk_objective_tb_6_2t (RK * rk) ///< RK struct.
{
long double *tb;
long double o;
#if DEBUG_RK_6_2
fprintf (stderr, "rk_objective_tb_6_2t: start\n");
#endif
tb = rk->tb->coefficient;
#if DEBUG_RK_6_2
rk_print_tb (optimize, "rk_objective_tb_6_2t", stderr);
#endif
o = fminl (0.L, b20 (tb));
if (b30 (tb) < 0.L)
o += b30 (tb);
if (b40 (tb) < 0.L)
o += b40 (tb);
if (b50 (tb) < 0.L)
o += b50 (tb);
if (b60 (tb) < 0.L)
o += b60 (tb);
if (b64 (tb) < 0.L)
o += b64 (tb);
if (b65 (tb) < 0.L)
o += b65 (tb);
if (o < 0.L)
{
o = 40.L - o;
goto end;
}
o = 30.L
+ fmaxl (1.L,
fmaxl (t1 (tb),
fmaxl (t2 (tb),
fmaxl (t3 (tb), fmaxl (t4 (tb), t5 (tb))))));
if (rk->strong)
{
rk_bucle_ac (rk);
o = fminl (o, *rk->ac0->optimal);
}
end:
#if DEBUG_RK_6_2
fprintf (stderr, "rk_objective_tb_6_2t: optimal=%Lg\n", o);
fprintf (stderr, "rk_objective_tb_6_2t: end\n");
#endif
return o;
}
| {
"alphanum_fraction": 0.59600863,
"avg_line_length": 25.4845360825,
"ext": "c",
"hexsha": "277f47f514a3f51e65264c6bb28c1416558a4659",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/ode",
"max_forks_repo_path": "rk_6_2.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/ode",
"max_issues_repo_path": "rk_6_2.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "463b8402ed4aac140a4c4ca2295a69dcce98b061",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/ode",
"max_stars_repo_path": "rk_6_2.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2745,
"size": 7416
} |
/*
* optimize_tnc.h
*
* Created on: Feb 9, 2010
* Author: smitty
*/
#ifndef _OPTIMIZE_CONT_MODELS_NLOPT_H_
#define _OPTIMIZE_CONT_MODELS_NLOPT_H_
#include <nlopt.h>
#include "cont_models.h"
#include <armadillo>
using namespace arma;
double nlopt_bm_sr(unsigned n, const double *x, double *grad, void *data);
double nlopt_bm_sr_log(unsigned n, const double *x, double *grad, void *data);
double nlopt_ou_sr_log(unsigned n, const double *x, double *grad, void *data);
double nlopt_bm_bl(unsigned n, const double *x, double *grad, void *data);
vector<double> optimize_single_rate_bm_nlopt(rowvec & _x, mat & _vcv,bool log);
vector<double> optimize_single_rate_bm_ou_nlopt(rowvec & _x, mat & _vcv);
vector<double> optimize_single_rate_bm_bl(Tree * tr);
#endif /* _OPTIMIZE_CONT_MODELS_NLOPT_H_ */
| {
"alphanum_fraction": 0.7567901235,
"avg_line_length": 30,
"ext": "h",
"hexsha": "b78d5e69c6780aff0f494bf2e438c0d87f280eef",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2022-03-31T18:23:31.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-18T05:20:26.000Z",
"max_forks_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jlanga/smsk_orthofinder",
"max_forks_repo_path": "src/phyx-1.01/src/optimize_cont_models_nlopt.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123",
"max_issues_repo_issues_event_max_datetime": "2018-11-08T13:59:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-08-21T07:26:13.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jlanga/smsk_selection",
"max_issues_repo_path": "src/phyx-1.01/src/optimize_cont_models_nlopt.h",
"max_line_length": 79,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "08070c6d4a6fbd9320265e1e698c95ba80f81123",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jlanga/smsk_selection",
"max_stars_repo_path": "src/phyx-1.01/src/optimize_cont_models_nlopt.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-03T10:22:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-18T05:20:20.000Z",
"num_tokens": 238,
"size": 810
} |
#define USE_GSL_INTEGRATION 0
#if USE_GSL_INTEGRATION
#include <gsl/gsl_integration.h>
#endif
struct integrand_params {
u32 n[2];
u32 component_count;
u32 coeff_count;
f64* coeff;
nlse_operator_func* op;
void* op_userdata;
struct basis basis;
};
static void sbmf_log_integration_result(struct quadgk_result* res) {
sbmf_log_info("integral: %.10e", res->integral);
sbmf_log_info("error: %.10e", res->error);
//sbmf_log_info("performed evals: %d", res->performed_evals);
sbmf_log_info("converged: %s", (res->converged) ? "yes" : "no");
}
/* functions to handle spatial guesses */
struct guess_integrand_params {
u32 n;
nlse_spatial_guess_func* func;
struct basis b;
};
void guess_integrand(f64* out, f64* in, u32 len, void* data) {
struct guess_integrand_params* params = data;
f64 eig[len];
params->b.eigenfunc(params->n, len, eig, in);
f64 sample[len];
params->func(sample, in, len, NULL);
for (u32 i = 0; i < len; ++i) {
out[i] = eig[i] * sample[i];
}
}
/* function to sample linear and non-linear matrix elements */
static void linear_me_integrand(f64* out, f64* in, u32 len, void* data) {
struct integrand_params* params = data;
f64 eig1[len];
f64 eig2[len];
params->basis.eigenfunc(params->n[0], len, eig1, in);
params->basis.eigenfunc(params->n[1], len, eig2, in);
f64 op[len];
params->op(len, op, in, 0, NULL, params->op_userdata);
for (u32 i = 0; i < len; ++i) {
out[i] = eig1[i]*eig2[i]*op[i];
}
}
static void nonlinear_me_integrand(f64* out, f64* in, u32 len, void* data) {
struct integrand_params* params = data;
f64 eig1[len];
f64 eig2[len];
params->basis.eigenfunc(params->n[0], len, eig1, in);
params->basis.eigenfunc(params->n[1], len, eig2, in);
f64 sample[len*params->component_count];
for (u32 i = 0; i < params->component_count; ++i) {
params->basis.sample(params->coeff_count, ¶ms->coeff[i*params->coeff_count], len, &sample[i*len], in);
}
f64 op[len];
params->op(len, op, in, params->component_count, sample, params->op_userdata);
for (u32 i = 0; i < len; ++i) {
out[i] = eig1[i]*eig2[i]*op[i];
}
}
#if USE_GSL_INTEGRATION
static f64 nonlinear_me_integrand_gsl(f64 in, void* data) {
struct integrand_params* params = data;
f64 eig1;
f64 eig2;
params->basis.eigenfunc(params->n[0], 1, &eig1, &in);
params->basis.eigenfunc(params->n[1], 1, &eig2, &in);
f64 sample[params->component_count];
for (u32 i = 0; i < params->component_count; ++i) {
params->basis.sample(params->coeff_count, ¶ms->coeff[i*params->coeff_count], 1, &sample[i], &in);
}
f64 op;
params->op(1, &op, &in, params->component_count, sample, params->op_userdata);
return eig1*eig2*op;
}
#endif
struct nlse_result nlse_solver(struct nlse_settings settings, const u32 component_count, struct nlse_component* component) {
/* Lazy */
const u32 N = settings.num_basis_funcs;
/* Setup results struct */
struct nlse_result res = {
.iterations = 0,
.component_count = component_count,
.coeff_count = N,
.coeff = sbmf_stack_push(component_count*(N*sizeof(f64))),
.abs_error = sbmf_stack_push(component_count*sizeof(f64)),
.energy = sbmf_stack_push(component_count*sizeof(f64)),
.residual = sbmf_stack_push(component_count*sizeof(f64)),
.hamiltonian = sbmf_stack_push(component_count * sizeof(struct symmetric_bandmat)),
.converged = false,
};
for (u32 i = 0; i < component_count; ++i) {
res.hamiltonian[i] = symmetric_bandmat_new(N,N);
}
/* Place to store coeffs from previous iterations */
f64* old_coeff = sbmf_stack_push(component_count*(N*sizeof(f64)));
f64* old_energy = sbmf_stack_push(component_count * sizeof(f64));
struct quadgk_settings int_settings = {
.gk = (settings.gk.gauss_size > 0) ? settings.gk : gk15,
.abs_error_tol = 1e-15,
.rel_error_tol = 1e-8,
.max_iters = settings.max_quadgk_iters,
};
/* Setup intial guess values for coeffs */
for (u32 i = 0; i < component_count; ++i) {
switch (component[i].guess.type) {
case DEFAULT_GUESS: {
for (u32 j = 0; j < res.coeff_count; ++j) {
res.coeff[i*res.coeff_count + j] = 0;
}
/* Initialize the i:th component to the i:th eigenfunction */
res.coeff[i*res.coeff_count + i] = 1;
break;
}
case SPATIAL_GUESS: {
struct guess_integrand_params p = {
.func = component[i].guess.data.spatial_guess,
.b = settings.basis,
};
int_settings.userdata = &p;
f64* out = &res.coeff[i*res.coeff_count];
for (u32 j = 0; j < res.coeff_count; ++j) {
p.n = j;
struct quadgk_result r;
u8 quadgk_memory[quadgk_required_memory_size(&int_settings)];
quadgk_infinite_interval(guess_integrand, &int_settings, quadgk_memory, &r);
out[j] = r.integral;
}
f64_normalize(out, out, res.coeff_count);
break;
}
case COEFF_GUESS: {
component[i].guess.data.coeff_guess(&res.coeff[i*res.coeff_count], res.coeff_count, i);
break;
}
case RANDOM_GUESS: {
struct symmetric_bandmat bm = symmetric_bandmat_new_zero(N,N);
SYMMETRIC_BANDMAT_FOREACH(bm, r,c) {
u32 index = symmetric_bandmat_index(bm, r,c);
bm.data[index] = 2.0 * ((f64)rand()/(f64)RAND_MAX) - 1.0;
}
struct eigen_result_real eigres = find_eigenpairs_sparse_real(bm, 1, EV_SMALLEST);
for (u32 j = 0; j < res.coeff_count; ++j) {
res.coeff[i*res.coeff_count + j] = eigres.eigenvectors[j];
}
break;
}
default:
sbmf_log_error("nlse_solver: component %u has invalid guess!", i);
return res;
};
}
struct integrand_params params = {
.component_count = res.component_count,
.coeff_count = res.coeff_count,
.coeff = res.coeff,
.op = NULL,
.basis = settings.basis,
};
/*
* Unique number of me's that need to be calculated in
* a symmetric matrix
*/
const u32 matrix_element_count = symmetric_bandmat_element_count(N);
/* Precompute indices for matrix elements
* This way we get a single array looping
* over the matrix which is easier to
* parallelize well.
* Picking the first hamiltonian as a
* dummny matrix just to get the correct
* iteration.
* */
u32 matrix_element_rows[matrix_element_count];
u32 matrix_element_cols[matrix_element_count];
{
u32 matrix_element_index = 0;
SYMMETRIC_BANDMAT_FOREACH(res.hamiltonian[0], r,c) {
matrix_element_rows[matrix_element_index] = r;
matrix_element_cols[matrix_element_index] = c;
matrix_element_index++;
}
}
/* Construct linear hamiltonian */
struct symmetric_bandmat linear_hamiltonian = symmetric_bandmat_new_zero(N,N);
{
if (settings.spatial_pot_perturbation) {
params.op = settings.spatial_pot_perturbation;
#pragma omp parallel for firstprivate(params, int_settings) shared(res)
for (u32 i = 0; i < matrix_element_count; ++i) {
u32 r = matrix_element_rows[i];
u32 c = matrix_element_cols[i];
int_settings.userdata = ¶ms;
params.n[0] = r;
params.n[1] = c;
u8 quadgk_memory[quadgk_required_memory_size(&int_settings)];
struct quadgk_result int_res;
quadgk_infinite_interval(linear_me_integrand, &int_settings, quadgk_memory, &int_res);
if (fabs(int_res.integral) <= settings.zero_threshold)
int_res.integral = 0.0;
if (!int_res.converged) {
sbmf_log_error("In construction of linear hamiltonian:");
sbmf_log_error("\tIntegration failed for %d,%d", r,c);
sbmf_log_integration_result(&int_res);
}
assert(int_res.converged);
u32 me_index = symmetric_bandmat_index(linear_hamiltonian, r,c);
linear_hamiltonian.data[me_index] = int_res.integral;
}
}
for (u32 i = 0; i < res.coeff_count; ++i) {
u32 me_index = symmetric_bandmat_index(linear_hamiltonian, i,i);
linear_hamiltonian.data[me_index] += settings.basis.eigenval(i);
}
assert(symmetric_bandmat_is_valid(linear_hamiltonian));
}
#if USE_GSL_INTEGRATION
const u32 num_threads = omp_get_max_threads();
gsl_integration_workspace* ws[num_threads];
/* Create gsl workspaces if necessary */
for (u32 i = 0; i < num_threads; ++i) {
ws[i] = gsl_integration_workspace_alloc(settings.max_iterations);
}
#endif
struct symmetric_bandmat old_Hs[res.component_count];
struct symmetric_bandmat premix_Hs[res.component_count];
for (u32 i = 0; i < res.component_count; ++i) {
old_Hs[i] = symmetric_bandmat_new(N,N);
premix_Hs[i] = symmetric_bandmat_new(N,N);
}
/* Do the actual iterations */
for (; res.iterations < settings.max_iterations; ++res.iterations) {
sbmf_log_info("nlse starting iteration %u", res.iterations);
memcpy(old_energy, res.energy, res.component_count * sizeof(f64));
/* Call debug callback if requested by user */
if (settings.measure_every > 0 &&
settings.debug_callback &&
res.iterations % settings.measure_every == 0) {
settings.debug_callback(settings, res);
}
/* Should we still apply mixing? */
if (settings.orbital_mixing > 0 && settings.mix_until_iteration > 0 && res.iterations == settings.mix_until_iteration) {
settings.orbital_mixing = 0;
}
if (settings.hamiltonian_mixing > 0 && settings.mix_until_iteration > 0 && res.iterations == settings.mix_until_iteration) {
settings.hamiltonian_mixing = 0;
}
if (settings.orbital_choice != NLSE_ORBITAL_MAXIMUM_OVERLAP && settings.mom_enable_at_iteration > 0 && res.iterations == settings.mom_enable_at_iteration) {
settings.orbital_choice = NLSE_ORBITAL_MAXIMUM_OVERLAP;
}
/* Apply orbital mixing */
for (u32 i = 0; i < component_count; ++i) {
if (settings.orbital_mixing > 0.0) {
//res.energy[i] = (1.0 - settings.orbital_mixing) * res.energy[i] + settings.orbital_mixing*old_energy[i];
for (u32 j = 0; j < res.coeff_count; ++j) {
res.coeff[i*res.coeff_count + j] =
(1.0 - settings.orbital_mixing) * res.coeff[i*res.coeff_count + j] + settings.orbital_mixing * old_coeff[i*res.coeff_count + j];
}
f64_normalize(&res.coeff[i*res.coeff_count], &res.coeff[i*res.coeff_count], res.coeff_count);
}
}
memcpy(old_coeff, res.coeff, res.component_count * N * sizeof(f64));
/*
* Construct all the Hamiltonians
*/
for (u32 i = 0; i < component_count; ++i) {
params.op = component[i].op;
params.op_userdata = component[i].userdata;
memcpy(old_Hs[i].data, res.hamiltonian[i].data, N*N*sizeof(f64));
/* Construct the i:th component's hamiltonian */
#pragma omp parallel for firstprivate(params, int_settings) shared(res, linear_hamiltonian)
for (u32 j = 0; j < matrix_element_count; ++j) {
u32 r = matrix_element_rows[j];
u32 c = matrix_element_cols[j];
int_settings.userdata = ¶ms;
params.n[0] = r;
params.n[1] = c;
#if USE_GSL_INTEGRATION
integration_result int_res;
gsl_function F;
F.function = nonlinear_me_integrand_gsl;
F.params = ¶ms;
gsl_integration_qagi(&F, 1e-10, 1e-7, settings.max_iterations, ws[omp_get_thread_num()], &int_res.integral, &int_res.error);
int_res.converged = true;
#else
u8 quadgk_memory[quadgk_required_memory_size(&int_settings)];
struct quadgk_result int_res;
quadgk_infinite_interval(nonlinear_me_integrand, &int_settings, quadgk_memory, &int_res);
#endif
/* Check if the resultant integral is less than what we can resolve,
* if so, zero it.
*/
if (fabs(int_res.integral) <= settings.zero_threshold)
int_res.integral = 0.0;
if (!int_res.converged) {
sbmf_log_error("In construction of component %u's hamiltonian:", i);
sbmf_log_error("\tIntegration failed for %d,%d", r,c);
sbmf_log_integration_result(&int_res);
}
assert(int_res.converged);
u32 me_index = symmetric_bandmat_index(res.hamiltonian[i], r,c);
res.hamiltonian[i].data[me_index] = linear_hamiltonian.data[me_index] + int_res.integral;
premix_Hs[i].data[me_index] = res.hamiltonian[i].data[me_index];
if (settings.hamiltonian_mixing > 0) {
res.hamiltonian[i].data[me_index] = (1.0 - settings.hamiltonian_mixing)*res.hamiltonian[i].data[me_index] + settings.hamiltonian_mixing*old_Hs[i].data[me_index];
}
}
assert(symmetric_bandmat_is_valid(res.hamiltonian[i]));
}
/*
* Solve and normalize all the Hamiltonian
* eigenvalue problems
*/
for (u32 i = 0; i < component_count; ++i) {
struct eigen_result_real eigres;
u32 new_orbital_index = 0;
switch (settings.orbital_choice) {
case NLSE_ORBITAL_LOWEST_ENERGY: {
eigres = find_eigenpairs_sparse_real(res.hamiltonian[i], 1, EV_SMALLEST);
f64_normalize(&eigres.eigenvectors[0], &eigres.eigenvectors[0], res.coeff_count);
break;
}
case NLSE_ORBITAL_MAXIMUM_OVERLAP: {
eigres = find_eigenpairs_sparse_real(res.hamiltonian[i], settings.mom_orbitals_to_consider, EV_SMALLEST);
f64 maximum_overlap = -INFINITY;
for (u32 j = 0; j < settings.mom_orbitals_to_consider; ++j) {
f64_normalize(&eigres.eigenvectors[j*res.coeff_count], &eigres.eigenvectors[j*res.coeff_count], res.coeff_count);
f64 overlap = 0.0;
for (u32 k = 0; k < res.coeff_count; ++k) {
f64 a = eigres.eigenvectors[j*res.coeff_count + k];
f64 b = old_coeff[i*res.coeff_count + k];
overlap += a*b;
}
overlap = fabs(overlap);
if (overlap > maximum_overlap) {
new_orbital_index = j;
maximum_overlap = overlap;
}
}
break;
}
default: {
sbmf_log_panic("nlse_solver(...): Unspecified energy selection method!");
assert(0);
}
};
/* Copy energies and coeffs */
res.energy[i] = eigres.eigenvalues[new_orbital_index];
for (u32 j = 0; j < res.coeff_count; ++j) {
res.coeff[i*res.coeff_count + j] = eigres.eigenvectors[res.coeff_count*new_orbital_index + j];
}
f64_normalize(&res.coeff[i*res.coeff_count], &res.coeff[i*res.coeff_count], res.coeff_count);
///* Apply orbital mixing */
//if (settings.orbital_mixing > 0.0) {
// res.energy[i] = (1.0 - settings.orbital_mixing) * res.energy[i] + settings.orbital_mixing*old_energy[i];
// for (u32 j = 0; j < res.coeff_count; ++j) {
// res.coeff[i*res.coeff_count + j] =
// (1.0 - settings.orbital_mixing) * res.coeff[i*res.coeff_count + j] + settings.orbital_mixing * old_coeff[i*res.coeff_count + j];
// }
// f64_normalize(&res.coeff[i*res.coeff_count], &res.coeff[i*res.coeff_count], res.coeff_count);
//}
}
/* Calculate error */
for (u32 i = 0; i < component_count; ++i) {
f64 sum_diff = 0.0;
f64 sum_prev = 0.0;
for (u32 j = 0; j < res.coeff_count; ++j) {
f64 diff = fabs(res.coeff[i*res.coeff_count + j]) - fabs(old_coeff[i*res.coeff_count + j]);
sum_diff += diff*diff;
sum_prev += old_coeff[i*res.coeff_count + j]*old_coeff[i*res.coeff_count + j];
}
res.abs_error[i] = sqrt(sum_diff);
}
/* Break condition */
bool should_exit = true;
for (u32 i = 0; i < component_count; ++i) {
if (res.abs_error[i] > settings.abs_error_tol)
should_exit = false;
sbmf_log_info("\t[%u] -- abs error: %.10e energy: %.10e", i, res.abs_error[i], res.energy[i]);
}
if (should_exit) {
res.converged = true;
break;
}
}
#if USE_GSL_INTEGRATION
/* free gsl workspaces if necessary */
for (u32 i = 0; i < num_threads; ++i) {
gsl_integration_workspace_free(ws[i]);
}
#endif
/* Compute residuals */
for (u32 i = 0; i < component_count; ++i) {
f64 ans1[N], ans2[N];
symmetric_bandmat_mulv(ans1, premix_Hs[i], &res.coeff[i*N]);
for (u32 j = 0; j < N; ++j) {
ans2[j] = res.energy[i] * res.coeff[i*N + j];
}
f64 sum = 0.0;
for (u32 j = 0; j < N; ++j) {
sum += fabs(ans1[j] - ans2[j]);
}
sum = sqrt(sum);
res.residual[i] = sum;
sbmf_log_info("\t[%u] residual %e", i, sum);
}
return res;
}
/*
* basic serialization
*/
void nlse_write_to_binary_file(const char* file, struct nlse_result res) {
FILE* fd = fopen(file, "w");
fwrite(&res.iterations, sizeof(u32), 1, fd);
fwrite(&res.component_count, sizeof(u32), 1, fd);
fwrite(&res.coeff_count, sizeof(u32), 1, fd);
fwrite(res.coeff, sizeof(f64), res.coeff_count*res.component_count, fd);
fwrite(res.abs_error, sizeof(f64), res.component_count, fd);
fwrite(res.energy, sizeof(f64), res.component_count, fd);
for (u32 i = 0; i < res.component_count; ++i) {
fwrite(&res.hamiltonian[i].size, sizeof(u32), 1, fd);
fwrite(&res.hamiltonian[i].bandcount, sizeof(u32), 1, fd);
u32 elements_written = fwrite(res.hamiltonian[i].data, sizeof(f64),
res.hamiltonian[i].bandcount*res.hamiltonian[i].size,
fd);
assert(elements_written == res.hamiltonian[i].bandcount*res.hamiltonian[i].size);
}
fwrite(&res.converged, sizeof(bool), 1, fd);
fclose(fd);
}
struct nlse_result nlse_read_from_binary_file(const char* file) {
struct nlse_result res;
FILE* fd = fopen(file, "r");
fread(&res.iterations, sizeof(u32), 1, fd);
fread(&res.component_count, sizeof(u32), 1, fd);
fread(&res.coeff_count, sizeof(u32), 1, fd);
res.coeff = sbmf_stack_push(sizeof(f64)*res.coeff_count*res.component_count);
fread(res.coeff, sizeof(f64), res.coeff_count*res.component_count, fd);
res.abs_error = sbmf_stack_push(sizeof(f64)*res.component_count);
fread(res.abs_error, sizeof(f64), res.component_count, fd);
res.energy = sbmf_stack_push(sizeof(f64)*res.component_count);
fread(res.energy, sizeof(f64), res.component_count, fd);
res.hamiltonian = sbmf_stack_push(res.component_count * sizeof(struct symmetric_bandmat));
for (u32 i = 0; i < res.component_count; ++i) {
u32 size, bandcount;
fread(&size, sizeof(u32), 1, fd);
fread(&bandcount, sizeof(u32), 1, fd);
res.hamiltonian[i] = symmetric_bandmat_new(bandcount, size);
u32 bytes_written = fread(res.hamiltonian[i].data, sizeof(f64),
bandcount*size,
fd);
assert(bytes_written == bandcount*size);
}
fread(&res.converged, sizeof(bool), 1, fd);
fclose(fd);
sbmf_log_info("loaded:");
sbmf_log_info(" iterations: %u", res.iterations);
sbmf_log_info(" component_count: %u", res.component_count);
sbmf_log_info(" coeff_count: %u", res.coeff_count);
for (u32 i = 0; i < res.component_count; ++i) {
sbmf_log_info(" [%u]: size: %u", i, res.hamiltonian[i].size);
sbmf_log_info(" [%u]: bandcount: %u", i, res.hamiltonian[i].bandcount);
}
return res;
}
| {
"alphanum_fraction": 0.6826505362,
"avg_line_length": 32.6481149013,
"ext": "c",
"hexsha": "810f1f427920efc4bf55dd61d05efbfdf040a5fe",
"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": "8856068236987081fe20814ab565456b7f92b822",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "AntonJohansson/sbmf",
"max_forks_repo_path": "src/sbmf/methods/nlse_solver.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8856068236987081fe20814ab565456b7f92b822",
"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": "AntonJohansson/sbmf",
"max_issues_repo_path": "src/sbmf/methods/nlse_solver.c",
"max_line_length": 166,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8856068236987081fe20814ab565456b7f92b822",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "AntonJohansson/sbmf",
"max_stars_repo_path": "src/sbmf/methods/nlse_solver.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5525,
"size": 18185
} |
/*
Copyright (C) 2019-2020 JingWeiZhangHuai <jingweizhanghuai@163.com>
Licensed under the Apache License, Version 2.0; 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.
*/
#include "morn_util.h"
#include <cblas.h>
#ifdef MORN_USE_CL
#include <CL/cl.h>
#include <clBLAS.h>
cl_context mDeviceContext(int device);
cl_command_queue mDeviceQueue(int device);
#endif
#define MORN_NO_TRANS 0
#define MORN_TRANS 1
struct HandleCLBlas
{
int clblas_setup;
};
void endCLBlas(struct HandleCLBlas *handle)
{
NULL;
#ifdef MORN_USE_CL
if(handle->clblas_setup) clblasTeardown();
#endif
}
#define HASH_CLBlas 0x3b4b7c3a
static struct HandleCLBlas *morn_clblas_handle=NULL;
void SetupCLBlas()
{
MHandle *hdl=mHandle(mMornObject(NULL,DFLT),CLBlas);
morn_clblas_handle=(struct HandleCLBlas *)(hdl->handle);
if(hdl->valid==0)
{
#ifdef MORN_USE_CL
mException(clblasSetup()!=CL_SUCCESS,EXIT,"CLBlas not work");
morn_clblas_handle->clblas_setup=1;
#endif
hdl->valid=1;
}
}
void mSgemm(int device,int a_trans,int b_trans,int m,int n,int k,float alpha,MMemoryBlock *a,int sa,MMemoryBlock *b,int sb,float beta,MMemoryBlock *c,int sc)
{
#ifdef MORN_USE_CL
if(device!=MORN_HOST)
{
a_trans=(a_trans==MORN_TRANS)?clblasTrans:clblasNoTrans;
b_trans=(b_trans==MORN_TRANS)?clblasTrans:clblasNoTrans;
if(morn_clblas_handle==NULL) SetupCLBlas();
device = c->device;
mMemoryBlockCopy(a,device);
mMemoryBlockCopy(b,device);
cl_event a_event=(cl_event)(a->cl_evt);
cl_event b_event=(cl_event)(b->cl_evt);
cl_event c_event=(cl_event)(c->cl_evt);
cl_event event_list[2] = {a_event,b_event};
cl_command_queue queue=mDeviceQueue(device);
int ret=clblasSgemm(clblasRowMajor,a_trans,b_trans,m,n,k,alpha,a->cl_data,0,sa,b->cl_data,0,sb,beta,c->cl_data,0,sc,1,&queue,2,event_list,&c_event);
mException(ret!=CL_SUCCESS,EXIT,"clblas error");
c->flag = MORN_DEVICE;
return;
}
#endif
a_trans=(a_trans==MORN_TRANS)?CblasTrans:CblasNoTrans;
b_trans=(b_trans==MORN_TRANS)?CblasTrans:CblasNoTrans;
cblas_sgemm(CblasRowMajor,a_trans,b_trans,m,n,k,alpha,a->data,sa,b->data,sb,beta,c->data,sc);
}
char *saxpby=mString(
__kernel void saxpby(__global const float* a,__global float* b,const float alpha,const float beta,const int sa,const int sb)
{
const int idx = get_global_id(0);
const int ia = idx*sa;
const int ib = idx*sb;
b[ib]=a[ia]*alpha+b[ib]*beta;
});
void mSaxpby(int device,int n,float alpha,MMemoryBlock *a,int sa,float beta,MMemoryBlock *b,int sb)
{
#ifdef MORN_USE_CL
if(device!=MORN_HOST)
{
mCLFunction(saxpby,CLSIZE(n),CLIN(a),CLINOUT(b),CLPARA(&alpha,sizeof(float)),CLPARA(&beta,sizeof(float)),CLPARA(&sa,sizeof(int)),CLPARA(&sb,sizeof(int)));
return;
}
#endif
cblas_saxpby(n,alpha,a->data,sa,beta,b->data,sb);
} | {
"alphanum_fraction": 0.7013827596,
"avg_line_length": 35.7789473684,
"ext": "c",
"hexsha": "fedc2bb889a681f8063f9b128f76cc822c6f34e5",
"lang": "C",
"max_forks_count": 35,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T11:34:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-26T05:09:23.000Z",
"max_forks_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ishine/Morn",
"max_forks_repo_path": "src/wrap/morn_blas.c",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0",
"max_issues_repo_issues_event_max_datetime": "2020-04-07T15:05:18.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-09-29T02:52:41.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ishine/Morn",
"max_issues_repo_path": "src/wrap/morn_blas.c",
"max_line_length": 501,
"max_stars_count": 121,
"max_stars_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ishine/Morn",
"max_stars_repo_path": "src/wrap/morn_blas.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:23:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-24T05:53:42.000Z",
"num_tokens": 997,
"size": 3399
} |
#pragma once
#include "continuation_scheduler.h"
#include <arcana/threading/cancellation.h>
#include <arcana/threading/task.h>
#include <gsl/gsl>
#include <condition_variable>
#include <mutex>
#include <optional>
namespace Babylon::Graphics
{
class SafeTimespanGuarantor
{
public:
SafeTimespanGuarantor(std::optional<arcana::cancellation_source>&);
continuation_scheduler<>& OpenScheduler()
{
return m_openDispatcher.scheduler();
}
continuation_scheduler<>& CloseScheduler()
{
return m_closeDispatcher.scheduler();
}
using SafetyGuarantee = gsl::final_action<std::function<void()>>;
SafetyGuarantee GetSafetyGuarantee();
void Open();
void RequestClose();
void Lock();
void Unlock();
private:
enum class State
{
Open,
Closing,
Closed,
Locked
};
std::optional<arcana::cancellation_source>& m_cancellation;
State m_state{State::Locked};
uint32_t m_count{};
std::mutex m_mutex{};
std::condition_variable m_condition_variable{};
continuation_dispatcher<> m_openDispatcher{};
continuation_dispatcher<> m_closeDispatcher{};
};
}
| {
"alphanum_fraction": 0.6119969628,
"avg_line_length": 23.1052631579,
"ext": "h",
"hexsha": "23ecb8cafc567b6d0cc0c32ff777ecbbc2bd4d95",
"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": "18ea83ee51e4e5d8b1763cf8d9ef5b48b2f9bb0a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SergioRZMasson/BabylonNative",
"max_forks_repo_path": "Core/Graphics/InternalInclude/Babylon/Graphics/SafeTimespanGuarantor.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "18ea83ee51e4e5d8b1763cf8d9ef5b48b2f9bb0a",
"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": "SergioRZMasson/BabylonNative",
"max_issues_repo_path": "Core/Graphics/InternalInclude/Babylon/Graphics/SafeTimespanGuarantor.h",
"max_line_length": 75,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "18ea83ee51e4e5d8b1763cf8d9ef5b48b2f9bb0a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SergioRZMasson/BabylonNative",
"max_stars_repo_path": "Core/Graphics/InternalInclude/Babylon/Graphics/SafeTimespanGuarantor.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 263,
"size": 1317
} |
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_permutation.h>
#include "invwishpdf.h"
int main(int argc, char *argv[]){
int args;
int m, n;
double pdf, dof;
args = 1;
m = atoi(argv[args++]);
n = atoi(argv[args++]);
// allocate space for matrix X, test_copy, and Scale.
gsl_matrix *X = gsl_matrix_alloc(m, n);
gsl_matrix *inv = gsl_matrix_alloc(m,n);
gsl_matrix *Scale = gsl_matrix_alloc(m, n);
gsl_matrix_set_identity(Scale);
fill_matrix(X);
dof = m + 1;
pdf = iwishpdf(X, Scale, inv, dof);
// Print the data
printf("\n%s", "Inverse Wishart matrix");
print_matrix(X);
printf("\n%s", "Scale matrix");
print_matrix(Scale);
printf("\n%s", "Wishart matrix");
print_matrix(inv);
printf("\n%s", "Density");
printf("\n%f\n", pdf);
return(0);
}
gsl_matrix fill_matrix(gsl_matrix *X)
{
int i,j;
int step = 0;
int n = X->size1;
int m = X->size2;
// Create a test matrix
double a_vect[] = {0.17955079, -0.09332222, -0.01273225, -0.09332222, 0.28282278, 0.01724885, -0.01273225, 0.01724885, 0.14424177};
for (i = 0; i < m; ++i){
for (j = 0; j < n; ++j){
gsl_matrix_set(X, i, j, a_vect[step++]);
}
}
return(*X);
}
double iwishpdf(gsl_matrix *X, gsl_matrix *Scale, gsl_matrix *inv, double dof)
{
double X_det, scale_det, denom, pdf, trace, numerator;
int m = X->size1;
int n = X->size2;
// Allocate matrix for inv(X)
gsl_matrix *for_mult = gsl_matrix_alloc(m, n);
// Get determinant of X and Scale matrix
X_det = matrix_determ(X);
scale_det = matrix_determ(Scale);
// Invert X
inv_matrix(X,inv);
// Multiple Scale * inv(X)
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, Scale, inv, 1.0, for_mult);
// Get trace of above.
trace = matrix_trace(for_mult);
numerator = pow(scale_det, dof / 2.0) * pow(X_det, (-dof-m-1)/ 2.0) * exp(-0.5 * trace);
denom = pow(2,dof * m / 2) * mv_gamma(dof/2, m);
pdf = (numerator/denom);
return(pdf);
}
gsl_matrix inv_matrix(gsl_matrix *X, gsl_matrix *inv)
{
int s;
int n = X->size1;
int m = X->size2;
gsl_matrix *a_copy = gsl_matrix_alloc(m, n);
gsl_matrix_memcpy( a_copy, X );
gsl_permutation *P = gsl_permutation_alloc(n);
gsl_linalg_LU_decomp(a_copy, P, &s);
gsl_linalg_LU_invert(a_copy, P, inv);
return(*inv);
}
double matrix_determ(gsl_matrix *X)
{
int s;
int n = X->size1;
int m = X->size2;
gsl_matrix *a_copy = gsl_matrix_alloc(m, n);
gsl_matrix_memcpy(a_copy, X );
gsl_permutation *P = gsl_permutation_alloc(n);
gsl_linalg_LU_decomp(a_copy, P, &s);
double my_det = gsl_linalg_LU_det (a_copy, s);
return(my_det);
}
double matrix_trace(gsl_matrix *X){
int i, m;
m = X->size1;
double trace = 0.0;
for(i=0;i<m;i++){
trace += gsl_matrix_get(X,i,i);
}
return(trace);
}
double mv_gamma(double a, double d){
double val = 1.0;
int i;
for(i = 1; i <= d; i++){
val *= gsl_sf_gamma(a - (0.5 * (i - 1)));
}
val *= pow(M_PI, (d * (d - 1) / 4.0));
return(val);
}
void print_matrix(gsl_matrix *X)
{
int i, j;
int n = X->size1;
int m = X->size2;
printf("\n");
for(i=0; i<m; i++){
for(j=0; j<n; j++){
printf("%05.2f ", gsl_matrix_get(X, i, j));
}
printf("\n");
}
}
| {
"alphanum_fraction": 0.6438515081,
"avg_line_length": 21.4161490683,
"ext": "c",
"hexsha": "d9df9b40e5c49c047cac0576aa08638c20507122",
"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": "f04423365a0b0bd36096019df47b40e1b32af5f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ags-wsu/inv_wishart_density",
"max_forks_repo_path": "invwishpdf.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f04423365a0b0bd36096019df47b40e1b32af5f2",
"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": "ags-wsu/inv_wishart_density",
"max_issues_repo_path": "invwishpdf.c",
"max_line_length": 136,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f04423365a0b0bd36096019df47b40e1b32af5f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ags-wsu/inv_wishart_density",
"max_stars_repo_path": "invwishpdf.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1197,
"size": 3448
} |
#ifndef ARRUS_COMMON_FORMAT_H
#define ARRUS_COMMON_FORMAT_H
// String formatting and parsing utilities.
// Currently wraps fmt library calls.
#include <fmt/format.h>
#include <stdexcept>
#include <cctype>
#include <vector>
#include <set>
#include <unordered_set>
#include <optional>
#include <sstream>
#include <gsl/span>
#include <boost/algorithm/string/join.hpp>
#include "arrus/core/api/common/Tuple.h"
#include "arrus/core/api/common/Interval.h"
namespace arrus {
template<typename... Args>
auto format(Args &&... args) {
return fmt::format(std::forward<Args>(args)...);
}
/**
* Returns true if the given string contains numeric characters only.
*
* @param num string to verify
* @return true if the given string contains numeric characters only,
* false otherwise.
*/
inline bool isDigitsOnly(const std::string &num) {
return std::all_of(num.begin(), num.end(), isdigit);
}
/**
* General purpose 'toString' function basing on ostream << operator.
*/
template<typename T>
std::string toString(const T &t) {
std::ostringstream ss;
ss << t;
return ss.str();
}
template<typename T>
inline std::string toString(const std::vector<T> &values) {
std::vector<std::string> vStr(values.size());
std::transform(std::begin(values), std::end(values), std::begin(vStr),
[](auto v) { return std::to_string(v); });
return boost::algorithm::join(vStr, ", ");
}
template<typename T>
inline std::string toString(
const gsl::span<T> &values) {
std::vector<std::string> vStr(values.size());
std::transform(std::begin(values), std::end(values), std::begin(vStr),
[](auto v) { return std::to_string(v); });
return boost::algorithm::join(vStr, ", ");
}
template<typename T>
inline std::string toStringTransform(
const std::vector<T> &values,
const std::function<std::string(const T&)> &func) {
std::vector<std::string> vStr(values.size());
std::transform(std::begin(values), std::end(values), std::begin(vStr),
[&func](T v) { return func(v); });
return boost::algorithm::join(vStr, ", ");
}
template<typename T>
inline std::string toString(const ::std::set<T> &values) {
std::vector<std::string> vStr(values.size());
std::transform(std::begin(values), std::end(values), std::begin(vStr),
[](auto v) { return std::to_string(v); });
return boost::algorithm::join(vStr, ", ");
}
template<typename T>
inline std::string toString(const ::std::unordered_set<T> &values) {
std::vector<std::string> vStr(values.size());
std::transform(std::begin(values), std::end(values), std::begin(vStr),
[](auto v) { return std::to_string(v); });
return boost::algorithm::join(vStr, ", ");
}
template<typename T>
inline std::string toString(const std::optional<T> value) {
if(value.has_value()) {
return std::to_string(value.value());
} else return "(no value)";
}
template<typename T>
inline std::string toString(const Tuple<T> tuple) {
return ::arrus::format("Tuple({})", toString(tuple.getValues()));
}
template<typename T>
inline std::string toString(const Interval<T> i) {
return ::arrus::format("Interval: start: {}, right: {}",
i.start(), i.end());
}
}
#endif //ARRUS_COMMON_FORMAT_H
| {
"alphanum_fraction": 0.6433713257,
"avg_line_length": 29.5044247788,
"ext": "h",
"hexsha": "9984672e483b93cd4e5b24200494b8fec98f7622",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-12-13T08:53:31.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-22T16:13:06.000Z",
"max_forks_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064",
"max_forks_repo_licenses": [
"BSL-1.0",
"MIT"
],
"max_forks_repo_name": "us4useu/arrus",
"max_forks_repo_path": "arrus/common/format.h",
"max_issues_count": 60,
"max_issues_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064",
"max_issues_repo_issues_event_max_datetime": "2022-03-12T17:39:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-11-06T04:59:06.000Z",
"max_issues_repo_licenses": [
"BSL-1.0",
"MIT"
],
"max_issues_repo_name": "us4useu/arrus",
"max_issues_repo_path": "arrus/common/format.h",
"max_line_length": 74,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "10487b09f556e327ddb1bec28fbaccf3b8b08064",
"max_stars_repo_licenses": [
"BSL-1.0",
"MIT"
],
"max_stars_repo_name": "us4useu/arrus",
"max_stars_repo_path": "arrus/common/format.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-18T09:41:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-02-04T19:56:08.000Z",
"num_tokens": 796,
"size": 3334
} |
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
int
main()
{
const gsl_interp2d_type *T = gsl_interp2d_bilinear;
const size_t N = 100; /* number of points to interpolate */
const double xa[] = { 0.0, 1.0 }; /* define unit square */
const double ya[] = { 0.0, 1.0 };
const size_t nx = sizeof(xa) / sizeof(double); /* x grid points */
const size_t ny = sizeof(ya) / sizeof(double); /* y grid points */
double *za = malloc(nx * ny * sizeof(double));
gsl_spline2d *spline = gsl_spline2d_alloc(T, nx, ny);
gsl_interp_accel *xacc = gsl_interp_accel_alloc();
gsl_interp_accel *yacc = gsl_interp_accel_alloc();
size_t i, j;
/* set z grid values */
gsl_spline2d_set(spline, za, 0, 0, 0.0);
gsl_spline2d_set(spline, za, 0, 1, 1.0);
gsl_spline2d_set(spline, za, 1, 1, 0.5);
gsl_spline2d_set(spline, za, 1, 0, 1.0);
/* initialize interpolation */
gsl_spline2d_init(spline, xa, ya, za, nx, ny);
/* interpolate N values in x and y and print out grid for plotting */
for (i = 0; i < N; ++i)
{
double xi = i / (N - 1.0);
for (j = 0; j < N; ++j)
{
double yj = j / (N - 1.0);
double zij = gsl_spline2d_eval(spline, xi, yj, xacc, yacc);
printf("%f %f %f\n", xi, yj, zij);
}
printf("\n");
}
gsl_spline2d_free(spline);
gsl_interp_accel_free(xacc);
gsl_interp_accel_free(yacc);
free(za);
return 0;
}
| {
"alphanum_fraction": 0.6094793057,
"avg_line_length": 27.7407407407,
"ext": "c",
"hexsha": "3777c1075ced82acae519a34ce2b120898af1e4b",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/interp2d.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/doc/examples/interp2d.c",
"max_line_length": 73,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/doc/examples/interp2d.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": 515,
"size": 1498
} |
#ifndef __PROJ_GAUSS_MIXTURES_H__
#define __PROJ_GAUSS_MIXTURES_H__
/* include */
#include <stdbool.h>
#include <float.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_linalg.h>
/* variable declarations and definitions */
double halflogtwopi; /* constant used in calculation */
int nthreads;
int tid;
struct gaussian{
double alpha;
gsl_vector *mm;
gsl_matrix *VV;
};
struct datapoint{
gsl_vector *ww;
gsl_matrix *SS;
gsl_matrix *RR;
double logweight;
};
struct gaussian * newgaussians, * startnewgaussians;
gsl_matrix * qij;
gsl_permutation * p;
gsl_vector * wminusRm, * TinvwminusRm;
gsl_matrix * Tij,* Tij_inv, * VRT, * VRTTinv, * Rtrans, * I;
struct modelbs{
gsl_vector *bbij;
gsl_matrix *BBij;
};
struct modelbs * bs;
FILE *logfile,*convlogfile;
gsl_rng * randgen; /* global random number generator */
/* function declarations */
static inline bool bovy_isfin(double x){ /* true if x is finite */
return (x > DBL_MAX || x < -DBL_MAX) ? false : true;}
void minmax(gsl_matrix * q, int row, bool isrow, double * min, double * max);
double logsum(gsl_matrix * q, int row, bool isrow);
double normalize_row(gsl_matrix * q, int row,bool isrow,bool noweight, double weight);
void bovy_randvec(gsl_vector * eps, int d, double length); /* returns random vector */
double bovy_det(gsl_matrix * A);/* determinant of matrix A */
void calc_splitnmerge(struct datapoint * data,int N,struct gaussian * gaussians, int K, gsl_matrix * qij, int * snmhierarchy);
void splitnmergegauss(struct gaussian * gaussians,int K, gsl_matrix * qij, int j, int k, int l);
void proj_EM_step(struct datapoint * data, int N, struct gaussian * gaussians, int K,bool * fixamp, bool * fixmean, bool * fixcovar, double * avgloglikedata, bool likeonly, double w,bool noproj, bool diagerrs, bool noweight);
void proj_EM(struct datapoint * data, int N, struct gaussian * gaussians, int K,bool * fixamp, bool * fixmean, bool * fixcovar, double * avgloglikedata, double tol,long long int maxiter, bool likeonly, double w,bool keeplog, FILE *logfile,FILE *tmplogfile, bool noproj, bool diagerrs, bool noweight);
void proj_gauss_mixtures(struct datapoint * data, int N, struct gaussian * gaussians, int K,bool * fixamp, bool * fixmean, bool * fixcovar, double * avgloglikedata, double tol,long long int maxiter, bool likeonly, double w, int splitnmerge, bool keeplog, FILE *logfile,FILE *convlogfile, bool noproj, bool diagerrs, bool noweight);
void calc_qstarij(double * qstarij, gsl_matrix * qij, int partial_indx[3]);
#endif /* proj_gauss_mixtures.h */
| {
"alphanum_fraction": 0.7393474088,
"avg_line_length": 37.7536231884,
"ext": "h",
"hexsha": "e6da53c29447e9be03a4ad14fb5f8eee225417c8",
"lang": "C",
"max_forks_count": 26,
"max_forks_repo_forks_event_max_datetime": "2021-12-13T03:37:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-05T22:21:22.000Z",
"max_forks_repo_head_hexsha": "b66d2af16503bc46d785ac9c9ba447ecc29b6fae",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "surbut/mashr",
"max_forks_repo_path": "src/proj_gauss_mixtures.h",
"max_issues_count": 24,
"max_issues_repo_head_hexsha": "b66d2af16503bc46d785ac9c9ba447ecc29b6fae",
"max_issues_repo_issues_event_max_datetime": "2021-11-19T01:01:22.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-07T01:42:22.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "surbut/mashr",
"max_issues_repo_path": "src/proj_gauss_mixtures.h",
"max_line_length": 331,
"max_stars_count": 73,
"max_stars_repo_head_hexsha": "b66d2af16503bc46d785ac9c9ba447ecc29b6fae",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "surbut/mashr",
"max_stars_repo_path": "src/proj_gauss_mixtures.h",
"max_stars_repo_stars_event_max_datetime": "2022-01-21T01:27:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-22T09:22:38.000Z",
"num_tokens": 744,
"size": 2605
} |
/**
* Copyright 2016 José Manuel Abuín Mosquera <josemanuel.abuin@usc.es>
*
* This file is part of Matrix Market Suite.
*
* Matrix Market Suite 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.
*
* Matrix Market Suite 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 Matrix Market Suite. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <cblas.h>
#include "DMxV.h"
#include "basic.h"
void usageDMxV(){
fprintf(stderr, "\n");
fprintf(stderr, "Usage: MM-Suite DMxV [options] <input-matrix> <input-vector>\n");
fprintf(stderr, "\nInput/output options:\n\n");
fprintf(stderr, " -o STR Output file name. Default: stdout\n");
fprintf(stderr, " -r Input format is row per line. Default: False\n");
fprintf(stderr, "\nParameters options:\n\n");
fprintf(stderr, " -a DOUBLE Alpha. Default: 1.0\n");
fprintf(stderr, " -b DOUBLE Beta. Default: 0.0\n");
fprintf(stderr, "\nPerformance options:\n\n");
fprintf(stderr, " -t INT Number of threads to use in OpenBLAS. Default: 1\n");
fprintf(stderr, "\n");
}
int DMxV(int argc, char *argv[]) {
int ret_code = 1;
int option;
unsigned long *II;
unsigned long *J;
double *values;
unsigned long M;
unsigned long N;
unsigned long long nz;
double *vectorValues;
unsigned long M_Vector;
unsigned long N_Vector;
unsigned long long nz_vector;
char *outputFileName = NULL;
char *inputMatrixFile = NULL;
char *inputVectorFile = NULL;
char *outputVectorFile = NULL;
int inputFormatRow = 0;
int basicOps = 0;
int numThreads = 1;
double alpha = 1.0;
double beta = 0.0;
while ((option = getopt(argc, argv,"ero:b:a:t:")) >= 0) {
switch (option) {
case 'o' :
//free(outputFileName);
outputFileName = (char *) malloc(sizeof(char)*strlen(optarg)+1);
strcpy(outputFileName,optarg);
break;
case 'r':
inputFormatRow = 1;
break;
case 'e':
basicOps = 1;
break;
case 'b':
beta = atof(optarg);
break;
case 'a':
alpha = atof(optarg);
break;
case 't':
numThreads = atoi(optarg);
break;
default: break;
}
}
if ((optind + 3 != argc) && (optind + 2 != argc)) {
usageDMxV();
return 0;
}
openblas_set_num_threads(numThreads);
if(optind + 3 == argc) { //We have an output vector
outputVectorFile = (char *)malloc(sizeof(char)*strlen(argv[optind+2])+1);
strcpy(outputVectorFile,argv[optind+2]);
}
if(outputFileName == NULL) {
outputFileName = (char *) malloc(sizeof(char)*7);
sprintf(outputFileName,"stdout");
}
inputMatrixFile = (char *)malloc(sizeof(char)*strlen(argv[optind])+1);
if(inputMatrixFile == NULL) {
fprintf(stderr, "[%s] Error reserving memory for input matrix file name\n",__func__);
return 0;
}
inputVectorFile = (char *)malloc(sizeof(char)*strlen(argv[optind+1])+1);
if(inputVectorFile == NULL) {
fprintf(stderr, "[%s] Error reserving memory for input vector file name\n",__func__);
return 0;
}
strcpy(inputMatrixFile,argv[optind]);
strcpy(inputVectorFile,argv[optind+1]);
//Read matrix
if(inputFormatRow){
if(!readDenseCoordinateMatrixRowLine(inputMatrixFile,&II,&J,&values,&M,&N,&nz)){
usageDMxV();
fprintf(stderr, "[%s] Can not read Matrix\n",__func__);
return 0;
}
}
else {
if(!readDenseCoordinateMatrix(inputMatrixFile,&II,&J,&values,&M,&N,&nz)){
usageDMxV();
fprintf(stderr, "[%s] Can not read Matrix\n",__func__);
return 0;
}
}
//Read vector
if(!readDenseVector(inputVectorFile, &vectorValues,&M_Vector,&N_Vector,&nz_vector)){
usageDMxV();
fprintf(stderr, "[%s] Can not read Vector\n",__func__);
return 0;
}
/*
void cblas_dgemv(const enum CBLAS_ORDER order,
const enum CBLAS_TRANSPOSE TransA, const int M, const int N,
const double alpha, const double *A, const int lda,
const double *X, const int incX, const double beta,
double *Y, const int incY);
*/
double *result=(double *) malloc(nz_vector * sizeof(double));
//Read output vector if any
if(outputVectorFile != NULL) {
if(!readDenseVector(outputVectorFile, &result,&M_Vector,&N_Vector,&nz_vector)){
usageDMxV();
fprintf(stderr, "[%s] Can not read Vector %s\n",__func__, outputVectorFile);
return 0;
}
}
//cblas_dgemv(CblasColMajor,CblasNoTrans,M,N,1.0,values,N,vectorValues,1,0.0,result,1);
double t_real = realtime();
if(basicOps){
mms_dgemv(M, N, alpha, values, vectorValues,beta, result);
}
else{
cblas_dgemv(CblasRowMajor,CblasNoTrans,M,N,alpha,values,N,vectorValues,1,beta,result,1);
}
fprintf(stderr, "\n[%s] Time spent in cblas_dgemv: %.6f sec\n", __func__, realtime() - t_real);
writeDenseVector(outputFileName, result,M_Vector,N_Vector,nz_vector);
return ret_code;
}
| {
"alphanum_fraction": 0.6465422613,
"avg_line_length": 26.0285714286,
"ext": "c",
"hexsha": "c26125a057e5017d8bd7dec1d3c72e8dc5e3f053",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "vkeller/math-454",
"max_forks_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/DMxV.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "vkeller/math-454",
"max_issues_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/DMxV.c",
"max_line_length": 96,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0bf3a81214f094dbddec868d3d133986b31f4b01",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "vkeller/math-454",
"max_stars_repo_path": "projects/CG/GENMAT/matrix-market-suite/src/operations/DMxV.c",
"max_stars_repo_stars_event_max_datetime": "2021-05-19T13:31:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-19T13:31:49.000Z",
"num_tokens": 1526,
"size": 5466
} |
/* ieee-utils/fp-x86linux.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 <stdio.h>
#include <fpu_control.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_ieee_utils.h>
/* Handle libc5, where _FPU_SETCW is not available, suggested by
OKUJI Yoshinori <okuji@gnu.org> and Evgeny Stambulchik
<fnevgeny@plasma-gate.weizmann.ac.il> */
#ifndef _FPU_SETCW
#include <i386/fpu_control.h>
#define _FPU_SETCW(cw) __setfpucw(cw)
#endif
int
gsl_ieee_set_mode (int precision, int rounding, int exception_mask)
{
unsigned short mode = 0 ;
switch (precision)
{
case GSL_IEEE_SINGLE_PRECISION:
mode |= _FPU_SINGLE ;
break ;
case GSL_IEEE_DOUBLE_PRECISION:
mode |= _FPU_DOUBLE ;
break ;
case GSL_IEEE_EXTENDED_PRECISION:
mode |= _FPU_EXTENDED ;
break ;
default:
mode |= _FPU_EXTENDED ;
}
switch (rounding)
{
case GSL_IEEE_ROUND_TO_NEAREST:
mode |= _FPU_RC_NEAREST ;
break ;
case GSL_IEEE_ROUND_DOWN:
mode |= _FPU_RC_DOWN ;
break ;
case GSL_IEEE_ROUND_UP:
mode |= _FPU_RC_UP ;
break ;
case GSL_IEEE_ROUND_TO_ZERO:
mode |= _FPU_RC_ZERO ;
break ;
default:
mode |= _FPU_RC_NEAREST ;
}
if (exception_mask & GSL_IEEE_MASK_INVALID)
mode |= _FPU_MASK_IM ;
if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)
mode |= _FPU_MASK_DM ;
if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)
mode |= _FPU_MASK_ZM ;
if (exception_mask & GSL_IEEE_MASK_OVERFLOW)
mode |= _FPU_MASK_OM ;
if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)
mode |= _FPU_MASK_UM ;
if (exception_mask & GSL_IEEE_TRAP_INEXACT)
{
mode &= ~ _FPU_MASK_PM ;
}
else
{
mode |= _FPU_MASK_PM ;
}
_FPU_SETCW(mode) ;
return GSL_SUCCESS ;
}
| {
"alphanum_fraction": 0.6857030327,
"avg_line_length": 25.39,
"ext": "c",
"hexsha": "4e0c1d574e5da601368ca0b074393008ec91148b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/ieee-utils/fp-x86linux.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/ieee-utils/fp-x86linux.c",
"max_line_length": 72,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/ieee-utils/fp-x86linux.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": 718,
"size": 2539
} |
/* AUTORIGHTS
Copyright (C) 2007 Princeton University
This file is part of Ferret Toolkit.
Ferret Toolkit 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, 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <cass.h>
#include <hash_table.h>
#include <arena.h>
#define MAX_INT 2147483647
#define DEFAULT_PRIME 1017881
//#define DEFAULT_PRIME 507217
//#define DEFAULT_PRIME 432251
//#define DEFAULT_PRIME 300301
//#define DEFAULT_PRIME 128311
//#define DEFAULT_PRIME 10007
MemArena *hasharena;
typedef struct nodeT {
int val;
struct nodeT *next;
} nodeT;
typedef struct bucketT {
int cnt, idx;
nodeT *nodes;
} bucketT;
struct hashTable_t {
int size;
int cnt_item; // number of items
int cnt_bucket; // number of non-empty buckets
int key_size; // size of hash key (number of integers)
hashT rndVec;
bucketT **buckets;
};
void
hashTable_init(void)
{
hasharena = mkmemarena(NULL, NULL, NULL, 0);
}
void
hashT_print(hashT key, int key_size, const char *tag, FILE *fp)
{
int i;
fprintf(fp, "[%d", key[0]);
for (i=1; i<key_size; i++)
fprintf(fp, ",%d", key[i]);
fprintf(fp, "]%s", tag);
}
nodeT *
nodeT_new(int val)
{
nodeT *ret = (nodeT *)memarenamalloc(hasharena, sizeof(nodeT));
if (ret) {
ret->val = val;
ret->next = NULL;
}
return ret;
}
bucketT *
bucketT_new(int idx)
{
bucketT *ret = (bucketT *)memarenamalloc(hasharena, sizeof(bucketT));
if (ret) {
ret->idx = idx;
ret->cnt = 0;
ret->nodes = NULL;
}
return ret;
}
void
bucketT_insert(bucketT *bucket, int val)
{
nodeT *node = nodeT_new(val);
if (bucket->cnt > 0)
node->next = bucket->nodes;
bucket->nodes = node;
bucket->cnt++;
}
void
bucketT_free(bucketT *bucket)
{
#ifdef NOTDEF // arena takes care of freeing the bucket
nodeT *p, *q;
if (bucket) {
p = bucket->nodes;
while (p != NULL) {
q = p->next;
free(p);
p = q;
}
free(bucket);
}
#endif
}
int
bucketT_dump(bucketT *bucket, CASS_FILE *out)
{
int ret;
nodeT *p = bucket->nodes;
ret = cass_write_uint32(&(bucket->cnt), 1, out);
assert(ret == 1);
ret = 0;
while (p != NULL) {
ret += cass_write_uint32(&(p->val), 1, out);
p = p->next;
}
assert(ret == bucket->cnt);
return 0;
}
bucketT *
bucketT_load(int idx, CASS_FILE *in)
{
int i, ret, cnt, val;
bucketT *bucket = bucketT_new(idx);
ret = cass_read_uint32(&cnt, 1, in);
assert(ret == 1);
ret = 0;
for (i=0; i<cnt; i++) {
ret += cass_read_uint32(&val, 1, in);
bucketT_insert(bucket, val);
}
assert(ret == cnt);
return bucket;
}
hashTable_t *
hashTable_new(int key_size)
{
int i;
hashTable_t *ret = (hashTable_t *)malloc(sizeof(hashTable_t));
const gsl_rng_type *T;
gsl_rng *r;
ret->key_size = key_size;
ret->rndVec = (int *)calloc(key_size, sizeof(int));
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc(T);
for (i=0; i<key_size; i++)
ret->rndVec[i] = (int)(gsl_rng_uniform(r) * MAX_INT);
gsl_rng_free(r);
ret->size = DEFAULT_PRIME;
ret->buckets = (bucketT **)calloc(ret->size, sizeof(bucketT *));
for (i=0; i<ret->size; i++)
ret->buckets[i] = NULL;
ret->cnt_item = 0;
ret->cnt_bucket = 0;
return ret;
}
int
hashTable_free(hashTable_t *hash_table)
{
int i;
if (hash_table != NULL) {
for (i=0; i<hash_table->size; i++) {
if (hash_table->buckets[i] != NULL)
bucketT_free(hash_table->buckets[i]);
}
free(hash_table->buckets);
free(hash_table->rndVec);
free(hash_table);
}
return 0;
}
int
hashTable_dump(hashTable_t *hash_table, CASS_FILE *out)
{
int i, ret;
ret = cass_write_uint32(&(hash_table->key_size), 1, out);
ret += cass_write_uint32(&(hash_table->cnt_item), 1, out);
ret += cass_write_uint32(&(hash_table->cnt_bucket), 1, out);
assert(ret == 3);
ret = cass_write_uint32(hash_table->rndVec,
hash_table->key_size, out);
assert(ret == hash_table->key_size);
for (i=0; i<hash_table->size; i++)
if (hash_table->buckets[i] != NULL) {
ret = cass_write_uint32(&i, 1, out);
assert(ret == 1);
ret = bucketT_dump(hash_table->buckets[i], out);
if (ret != 0)
return ret;
}
return 0;
}
hashTable_t *
hashTable_load(CASS_FILE *in)
{
int i, x, ret;
int key_size, cnt_item, cnt_bucket;
hashTable_t *hash_table = type_calloc(hashTable_t, 1);
ret = cass_read_uint32(&key_size, 1, in);
ret += cass_read_uint32(&cnt_item, 1, in);
ret += cass_read_uint32(&cnt_bucket, 1, in);
assert(ret == 3);
hash_table->size = DEFAULT_PRIME;
hash_table->key_size = key_size;
hash_table->cnt_item = cnt_item;
hash_table->cnt_bucket = cnt_bucket;
hash_table->rndVec = (int *)calloc(key_size, sizeof(int));
ret = cass_read_uint32(hash_table->rndVec, key_size, in);
assert(ret == key_size);
hash_table->buckets = (bucketT **)calloc(hash_table->size,
sizeof(bucketT *));
for (i=0; i<cnt_bucket; i++) {
ret = cass_read_uint32(&x, 1, in);
assert(ret == 1);
hash_table->buckets[x] = bucketT_load(x, in);
if (hash_table->buckets[x] == NULL)
return NULL;
}
return hash_table;
}
int
hashTable_hash(hashTable_t *table, hashT key)
{
int i, k, sum = 0;
for (i=0; i<table->key_size; i++) {
//printf("%d\t", key[i]);
sum += table->rndVec[i] * key[i];
}
k = abs(sum % (table->size));
//printf("%d\n", k);
return k;
}
void
hashTable_insert(hashTable_t *table, hashT key, int val)
{
int idx;
bucketT *bucket;
idx = hashTable_hash(table, key);
bucket = table->buckets[idx];
if (bucket == NULL) {
bucket = bucketT_new(idx);
table->buckets[idx] = bucket;
table->cnt_bucket++;
}
bucketT_insert(bucket, val);
table->cnt_item++;
}
bucketT *
hashTable_get_bucket(hashTable_t *table, hashT key)
{
int idx = hashTable_hash(table, key);
return table->buckets[idx];
}
int
hashTable_search(hashTable_t *table, bitmap_t *map, hashT key)
{
int i;
nodeT *p;
int idx = hashTable_hash(table, key);
bucketT *bucket = table->buckets[idx];
if (bucket) {
p = bucket->nodes;
for (i=0; i<bucket->cnt; i++) {
bitmap_insert(map, p->val);
p = p->next;
}
}
return 0;
}
| {
"alphanum_fraction": 0.6480373559,
"avg_line_length": 19.8063583815,
"ext": "c",
"hexsha": "7ab90f54f70afcbf5ff9261cd62dfd57b1f94fc1",
"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/netapps/netferret/src/server/src/hash_table.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/netapps/netferret/src/server/src/hash_table.c",
"max_line_length": 71,
"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/netapps/netferret/src/server/src/hash_table.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": 2216,
"size": 6853
} |
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2013.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#ifndef OPENMS_ANALYSIS_MAPMATCHING_TRANSFORMATIONMODEL_H
#define OPENMS_ANALYSIS_MAPMATCHING_TRANSFORMATIONMODEL_H
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_interp.h>
namespace OpenMS
{
/**
@brief Base class for transformation models
Implements the identity (no transformation). Parameters and data are ignored.
@ingroup MapAlignment
*/
class OPENMS_DLLAPI TransformationModel
{
public:
/// Coordinate pair
typedef std::pair<DoubleReal, DoubleReal> DataPoint;
/// Vector of coordinate pairs
typedef std::vector<DataPoint> DataPoints;
/// Constructor
TransformationModel() {}
/// Alternative constructor (derived classes should implement this one!)
TransformationModel(const TransformationModel::DataPoints &,
const Param &) :
params_() {}
/// Destructor
virtual ~TransformationModel() {}
/// Evaluates the model at the given value
virtual DoubleReal evaluate(const DoubleReal value) const
{
return value;
}
/// Gets the (actual) parameters
void getParameters(Param & params) const
{
params = params_;
}
/// Gets the default parameters
static void getDefaultParameters(Param & params)
{
params.clear();
}
protected:
/// Parameters
Param params_;
};
/**
@brief Linear model for transformations
The model can be inferred from data or specified using explicit parameters. If data is given, a least squares fit is used to find the model parameters (slope and intercept). Depending on parameter @p symmetric_regression, a normal regression (@e y on @e x) or symmetric regression (@f$ y - x @f$ on @f$ y + x @f$) is performed.
Without data, the model can be specified by giving the parameters @p slope and @p intercept explicitly.
@ingroup MapAlignment
*/
class OPENMS_DLLAPI TransformationModelLinear :
public TransformationModel
{
public:
/**
@brief Constructor
@exception IllegalArgument is thrown if neither data points nor explicit parameters (slope/intercept) are given.
*/
TransformationModelLinear(const DataPoints & data, const Param & params);
/// Destructor
~TransformationModelLinear();
/// Evaluates the model at the given value
virtual DoubleReal evaluate(const DoubleReal value) const;
using TransformationModel::getParameters;
/// Gets the "real" parameters
void getParameters(DoubleReal & slope, DoubleReal & intercept) const;
/// Gets the default parameters
static void getDefaultParameters(Param & params);
/**
@brief Computes the inverse
@exception DivisionByZero is thrown if the slope is zero.
*/
void invert();
protected:
/// Parameters of the linear model
DoubleReal slope_, intercept_;
/// Was the model estimated from data?
bool data_given_;
/// Use symmetric regression?
bool symmetric_;
};
/**
@brief Interpolation model for transformations
Between the data points, the interpolation uses the neighboring points. Outside the range spanned by the points, we extrapolate using a line through the first and the last point.
Different types of interpolation (controlled by the parameter @p interpolation_type) are supported: "linear", "polynomial", "cspline", and "akima". Note that the number of required data points may differ between types.
@ingroup MapAlignment
*/
class OPENMS_DLLAPI TransformationModelInterpolated :
public TransformationModel
{
public:
/**
@brief Constructor
@exception IllegalArgument is thrown if there are not enough data points or if an unknown interpolation type is given.
*/
TransformationModelInterpolated(const DataPoints & data,
const Param & params);
/// Destructor
~TransformationModelInterpolated();
/// Evaluates the model at the given value
DoubleReal evaluate(const DoubleReal value) const;
/// Gets the default parameters
static void getDefaultParameters(Param & params);
protected:
/// Data coordinates
std::vector<double> x_, y_;
/// Number of data points
size_t size_;
/// Look-up accelerator
gsl_interp_accel * acc_;
/// Interpolation function
gsl_interp * interp_;
/// Linear model for extrapolation
TransformationModelLinear * lm_;
};
/**
@brief B-spline model for transformations
In the range of the data points, the transformation is evaluated from a cubic smoothing spline fit to the points. The number of breakpoints is given as a parameter (@p num_breakpoints). Outside of this range, linear extrapolation through the last point with the slope of the spline at that point is used.
Positioning of the breakpoints is controlled by the parameter @p break_positions. Valid choices are "uniform" (equidistant spacing on the data range) and "quantiles" (equal numbers of data points in every interval).
@ingroup MapAlignment
*/
class OPENMS_DLLAPI TransformationModelBSpline :
public TransformationModel
{
public:
/**
@brief Constructor
@exception IllegalArgument is thrown if not enough data points are given or if the required parameter @p num_breakpoints is missing.
*/
TransformationModelBSpline(const DataPoints & data, const Param & params);
/// Destructor
~TransformationModelBSpline();
/// Evaluates the model at the given value
DoubleReal evaluate(const DoubleReal value) const;
/// Gets the default parameters
static void getDefaultParameters(Param & params);
protected:
/**
@brief Finds quantile values
@param x Data vector to find quantiles in
@param quantiles Quantiles to find (values between 0 and 1)
@param results Resulting quantiles (vector must be already allocated to the correct size!)
*/
void getQuantiles_(const gsl_vector * x, const std::vector<double> &
quantiles, gsl_vector * results);
/// Computes the B-spline fit
void computeFit_();
/// Computes the linear extrapolation
void computeLinear_(const double pos, double & slope, double & offset,
double & sd_err);
/// Vectors for B-spline computation
gsl_vector * x_, * y_, * w_, * bsplines_, * coeffs_;
/// Covariance matrix
gsl_matrix * cov_;
/// B-spline workspace
gsl_bspline_workspace * workspace_;
/// Number of data points and coefficients
size_t size_, ncoeffs_;
// First/last breakpoint
double xmin_, xmax_;
/// Parameters for linear extrapolation
double slope_min_, slope_max_, offset_min_, offset_max_;
/// Fitting errors of linear extrapolation
double sd_err_left_, sd_err_right_;
};
} // end of namespace OpenMS
#endif // OPENMS_ANALYSIS_MAPMATCHING_TRANSFORMATIONMODEL_H
| {
"alphanum_fraction": 0.6772562383,
"avg_line_length": 35.53515625,
"ext": "h",
"hexsha": "681cdfe66f49e678fdd470d5a7b22c8cf6c2612f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_forks_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_forks_repo_name": "kreinert/OpenMS",
"max_forks_repo_path": "src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "45455356482ce5ab35e32e445609b291ec78a6d6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_issues_repo_name": "kreinert/OpenMS",
"max_issues_repo_path": "src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h",
"max_line_length": 334,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "b182ba576e0cbfbe420b8edb0dd1c42bb6c973f3",
"max_stars_repo_licenses": [
"Zlib",
"Apache-2.0"
],
"max_stars_repo_name": "open-ms/all-svn-branches",
"max_stars_repo_path": "include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h",
"max_stars_repo_stars_event_max_datetime": "2018-05-23T03:43:10.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-05-23T03:43:10.000Z",
"num_tokens": 1844,
"size": 9097
} |
#pragma once
#define NOMINMAX
#define NODRAWTEXT
#define NOGDI
#define NOBITMAP
#define NOMCX
#define NOSERVICE
#define NOHELP
#include <iostream>
#include <vector>
#include <string>
#include <string_view>
#include <sstream>
#include <variant>
#include <codecvt>
#include <locale>
#include <filesystem>
#include <fstream>
#include <chrono>
#include <functional>
#include <numeric>
#ifndef _WIN32
#include <wsl/winadapter.h>
#include "directml_guids.h"
#else
#include <Windows.h>
#endif
#include <wil/result.h>
#include <wrl/client.h>
#include <gsl/gsl>
#include <rapidjson/document.h>
#include <rapidjson/istreamwrapper.h>
#include <fmt/format.h>
#ifdef _GAMING_XBOX_SCARLETT // Xbox Series X/S - Use GDK
#include <d3d12_xs.h>
#include <d3dx12_xs.h>
#include <d3d12shader_xs.h>
#include <dxcapi_xs.h>
#include <pix3.h>
using IAdapter = IDXGIAdapter;
#elif _GAMING_XBOX_XBOXONE // XboxOne - Use GDK
#include <d3d12_x.h>
#include <d3dx12_x.h>
#include <d3d12shader_x.h>
#include <dxcapi_x.h>
#include <pix3.h>
using IAdapter = IDXGIAdapter;
#else // Desktop/PC - Use DirectX-Headers
#include <directx/d3d12.h>
#include <directx/d3dx12.h>
#include <directx/dxcore.h>
#ifndef DXCOMPILER_NONE
#include <directx/d3d12shader.h>
#endif
#include <dxcapi.h>
#include <WinPixEventRuntime/pix3.h>
#define IGraphicsUnknown IUnknown
#define IID_GRAPHICS_PPV_ARGS IID_PPV_ARGS
using IAdapter = IDXCoreAdapter;
#endif
#include <DirectML.h>
#include "DirectMLX.h"
#include "Logging.h" | {
"alphanum_fraction": 0.7618724559,
"avg_line_length": 21.0571428571,
"ext": "h",
"hexsha": "28bfeab2cedaf51911a7cb94b472114b5fcdf495",
"lang": "C",
"max_forks_count": 20,
"max_forks_repo_forks_event_max_datetime": "2020-06-12T15:57:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-13T12:56:29.000Z",
"max_forks_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "miaobin/DirectML",
"max_forks_repo_path": "DxDispatch/src/dxdispatch/pch.h",
"max_issues_count": 4,
"max_issues_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836",
"max_issues_repo_issues_event_max_datetime": "2020-06-09T01:51:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-05-10T09:12:59.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "miaobin/DirectML",
"max_issues_repo_path": "DxDispatch/src/dxdispatch/pch.h",
"max_line_length": 57,
"max_stars_count": 61,
"max_stars_repo_head_hexsha": "d4657006a60a7b7d9baf17638c42aee27258c836",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "miaobin/DirectML",
"max_stars_repo_path": "DxDispatch/src/dxdispatch/pch.h",
"max_stars_repo_stars_event_max_datetime": "2020-06-14T07:36:27.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-07T14:41:46.000Z",
"num_tokens": 423,
"size": 1474
} |
/**
*
* @file core_ssyrfb.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @date 2010-11-15
* @generated s Tue Jan 7 11:44:48 2014
*
**/
#include <lapacke.h>
#include "common.h"
#undef COMPLEX
#define REAL
/***************************************************************************//**
*
* @ingroup CORE_float
*
* CORE_ssyrfb overwrites the symmetric complex N-by-N tile C with
*
* Q**T*C*Q
*
* where Q is a complex unitary matrix defined as the product of k
* elementary reflectors
*
* Q = H(1) H(2) . . . H(k)
*
* as returned by CORE_sgeqrt. Only PlasmaLower supported!
*
*******************************************************************************
*
* @param[in] uplo
* @arg PlasmaLower : the upper part of the symmetric matrix C
* is not referenced.
* @arg PlasmaUpper : the lower part of the symmetric matrix C
* is not referenced (not supported).
*
* @param[in] n
* The number of rows/columns of the tile C. N >= 0.
*
* @param[in] k
* The number of elementary reflectors whose product defines
* the matrix Q. K >= 0.
*
* @param[in] ib
* The inner-blocking size. IB >= 0.
*
* @param[in] nb
* The blocking size. NB >= 0.
*
* @param[in] A
* The i-th column must contain the vector which defines the
* elementary reflector H(i), for i = 1,2,...,k, as returned by
* CORE_sgeqrt in the first k columns of its array argument A.
*
* @param[in] lda
* The leading dimension of the array A. LDA >= max(1,N).
*
* @param[in] T
* The IB-by-K triangular factor T of the block reflector.
* T is upper triangular by block (economic storage);
* The rest of the array is not referenced.
*
* @param[in] ldt
* The leading dimension of the array T. LDT >= IB.
*
* @param[in,out] C
* On entry, the symmetric N-by-N tile C.
* On exit, C is overwritten by Q**T*C*Q.
*
* @param[in] ldc
* The leading dimension of the array C. LDC >= max(1,M).
*
* @param[in,out] WORK
* On exit, if INFO = 0, WORK(1) returns the optimal LDWORK.
*
* @param[in] ldwork
* The dimension of the array WORK. LDWORK >= max(1,N);
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_ssyrfb = PCORE_ssyrfb
#define CORE_ssyrfb PCORE_ssyrfb
#define CORE_sormlq PCORE_sormlq
#define CORE_sormqr PCORE_sormqr
int CORE_sormlq(PLASMA_enum side, PLASMA_enum trans,
int M, int N, int IB, int K,
const float *V, int LDV,
const float *T, int LDT,
float *C, int LDC,
float *WORK, int LDWORK);
int CORE_sormqr(PLASMA_enum side, PLASMA_enum trans,
int M, int N, int K, int IB,
const float *V, int LDV,
const float *T, int LDT,
float *C, int LDC,
float *WORK, int LDWORK);
#endif
int CORE_ssyrfb( PLASMA_enum uplo, int n,
int k, int ib, int nb,
const float *A, int lda,
const float *T, int ldt,
float *C, int ldc,
float *WORK, int ldwork )
{
float tmp;
int i, j;
/* Check input arguments */
if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) {
coreblas_error(1, "Illegal value of uplo");
return -1;
}
if (n < 0) {
coreblas_error(2, "Illegal value of n");
return -2;
}
if (k < 0) {
coreblas_error(3, "Illegal value of k");
return -3;
}
if (ib < 0) {
coreblas_error(4, "Illegal value of ib");
return -4;
}
if (nb < 0) {
coreblas_error(5, "Illegal value of nb");
return -5;
}
if ( (lda < max(1,n)) && (n > 0) ) {
coreblas_error(7, "Illegal value of lda");
return -7;
}
if ( (ldt < max(1,ib)) && (ib > 0) ) {
coreblas_error(9, "Illegal value of ldt");
return -9;
}
if ( (ldc < max(1,n)) && (n > 0) ) {
coreblas_error(11, "Illegal value of ldc");
return -11;
}
if (uplo == PlasmaLower) {
/* Rebuild the symmetric block: WORK <- C */
for (j = 0; j < n; j++) {
*(WORK + j + j * ldwork) = *(C + ldc*j + j);
for (i = j+1; i < n; i++){
tmp = *(C + i + j*ldc);
*(WORK + i + j * ldwork) = tmp;
*(WORK + j + i * ldwork) = ( tmp );
}
}
/* Left */
CORE_sormqr(PlasmaLeft, PlasmaTrans, n, n, k, ib,
A, lda, T, ldt, WORK, ldwork, WORK+nb*ldwork, ldwork);
/* Right */
CORE_sormqr(PlasmaRight, PlasmaNoTrans, n, n, k, ib,
A, lda, T, ldt, WORK, ldwork, WORK+nb*ldwork, ldwork);
/*
* Copy back the final result to the lower part of C
*/
LAPACKE_slacpy_work( LAPACK_COL_MAJOR, lapack_const(PlasmaLower), n, n, WORK, ldwork, C, ldc );
}
else {
/* Rebuild the symmetric block: WORK <- C */
for (j = 0; j < n; j++) {
for (i = 0; i < j; i++){
tmp = *(C + i + j*ldc);
*(WORK + i + j * ldwork) = tmp;
*(WORK + j + i * ldwork) = ( tmp );
}
*(WORK + j + j * ldwork) = *(C + ldc*j + j);
}
/* Right */
CORE_sormlq(PlasmaRight, PlasmaTrans, n, n, k, ib,
A, lda, T, ldt, WORK, ldwork, WORK+nb*ldwork, ldwork);
/* Left */
CORE_sormlq(PlasmaLeft, PlasmaNoTrans, n, n, k, ib,
A, lda, T, ldt, WORK, ldwork, WORK+nb*ldwork, ldwork);
/*
* Copy back the final result to the upper part of C
*/
LAPACKE_slacpy_work( LAPACK_COL_MAJOR, lapack_const(PlasmaUpper), n, n, WORK, ldwork, C, ldc );
}
return 0;
}
| {
"alphanum_fraction": 0.4929422836,
"avg_line_length": 31.5643564356,
"ext": "c",
"hexsha": "1b56821b01b2d985762a45b84c0bd38d834e47fb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas/core_ssyrfb.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_ssyrfb.c",
"max_line_length": 103,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_ssyrfb.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1813,
"size": 6376
} |
#include <string.h>
#include <gbpLib.h>
#include <gbpMisc.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_blas.h>
void invert_square_matrix(double *matrix_in, int size, double *inverse_out) {
gsl_matrix * matrix;
gsl_matrix * LU_decomp;
gsl_matrix * inverse;
gsl_permutation *permutation;
int signum;
gsl_matrix_view m;
double * matrix_copy;
int i_x, i_y, i_M;
// Allocate some RAM and set some pointers
matrix_copy = (double *)SID_malloc(sizeof(double) * size * size);
memcpy(matrix_copy, matrix_in, sizeof(double) * size * size);
m = gsl_matrix_view_array(matrix_copy, size, size);
matrix = &m.matrix;
LU_decomp = matrix;
inverse = gsl_matrix_alloc(size, size);
permutation = gsl_permutation_alloc(size);
// Perform LU decomposition. Result ends-up in matrix,
// which is pointed to by LU_decomp
gsl_linalg_LU_decomp(matrix, permutation, &signum);
gsl_linalg_LU_invert(LU_decomp, permutation, inverse);
// Copy result into the out-going array
for(i_y = 0, i_M = 0; i_y < size; i_y++) {
for(i_x = 0; i_x < size; i_x++, i_M++) {
inverse_out[i_M] = gsl_matrix_get(inverse, i_x, i_y);
}
}
// Test that the matrix*inverse=identity
/*
for(i_x=0;i_x<size;i_x++){
for(i_y=0;i_y<size;i_y++,i_M++){
double test;
int j_M;
test=0.;
for(j_M=0;j_M<size;j_M++) test+=matrix_in[i_y*size+j_M]*inverse_out[j_M*size+i_x];
fprintf(stderr,"%le ",test);
}
fprintf(stderr,"\n");
}
*/
// Free some RAM
gsl_matrix_free(inverse);
gsl_permutation_free(permutation);
SID_free(SID_FARG matrix_copy);
}
| {
"alphanum_fraction": 0.6137479542,
"avg_line_length": 31.0677966102,
"ext": "c",
"hexsha": "f07b31cc4bfccc8295fbe038e1792ded99a430d9",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpMath/gbpMisc/invert_matrix.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpMath/gbpMisc/invert_matrix.c",
"max_line_length": 92,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpMath/gbpMisc/invert_matrix.c",
"max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z",
"num_tokens": 502,
"size": 1833
} |
/*
* Implement Heap sort -- direct and indirect sorting
* Based on descriptions in Sedgewick "Algorithms in C"
*
* Copyright (C) 1999 Thomas Walter
*
* 18 February 2000: Modified for GSL by Brian Gough
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3, or (at your option) any
* later version.
*
* This source 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.
*/
#include <config.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#define BASE_LONG_DOUBLE
#include "templates_on.h"
#include "sortvecind_source.c"
#include "templates_off.h"
#undef BASE_LONG_DOUBLE
#define BASE_DOUBLE
#include "templates_on.h"
#include "sortvecind_source.c"
#include "templates_off.h"
#undef BASE_DOUBLE
#define BASE_FLOAT
#include "templates_on.h"
#include "sortvecind_source.c"
#include "templates_off.h"
#undef BASE_FLOAT
#define BASE_ULONG
#include "templates_on.h"
#include "sortvecind_source.c"
#include "templates_off.h"
#undef BASE_ULONG
#define BASE_LONG
#include "templates_on.h"
#include "sortvecind_source.c"
#include "templates_off.h"
#undef BASE_LONG
#define BASE_UINT
#include "templates_on.h"
#include "sortvecind_source.c"
#include "templates_off.h"
#undef BASE_UINT
#define BASE_INT
#include "templates_on.h"
#include "sortvecind_source.c"
#include "templates_off.h"
#undef BASE_INT
#define BASE_USHORT
#include "templates_on.h"
#include "sortvecind_source.c"
#include "templates_off.h"
#undef BASE_USHORT
#define BASE_SHORT
#include "templates_on.h"
#include "sortvecind_source.c"
#include "templates_off.h"
#undef BASE_SHORT
#define BASE_UCHAR
#include "templates_on.h"
#include "sortvecind_source.c"
#include "templates_off.h"
#undef BASE_UCHAR
#define BASE_CHAR
#include "templates_on.h"
#include "sortvecind_source.c"
#include "templates_off.h"
#undef BASE_CHAR
| {
"alphanum_fraction": 0.7709190672,
"avg_line_length": 24.032967033,
"ext": "c",
"hexsha": "aa1aa8a7de9c893da540952dab155bb67468720c",
"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/sort/sortvecind.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/sort/sortvecind.c",
"max_line_length": 77,
"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/sort/sortvecind.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": 529,
"size": 2187
} |
#if !defined(PETIGA_H)
#define PETIGA_H
/*
#include <petscconf.h>
#undef static inline
#define static inline static __inline
*/
#include <petsc.h>
#if PETSC_VERSION_LT(3,7,0)
#error "PetIGA requires PETSc 3.7 or higher"
#endif
#include <petsc/private/petscimpl.h>
#if PETSC_VERSION_LT(3,8,0)
# ifdef PETSC_FUNCTION_NAME
# undef __FUNCT__
# define __FUNCT__ PETSC_FUNCTION_NAME
# endif
#endif
#if PETSC_VERSION_LT(3,17,0)
#undef SETERRQ
#define SETERRQ(comm,ierr,...) return PetscError(comm,__LINE__,PETSC_FUNCTION_NAME,__FILE__,ierr,PETSC_ERROR_INITIAL,__VA_ARGS__)
#endif
typedef ISLocalToGlobalMapping LGMap;
#define LGMap LGMap
/* ---------------------------------------------------------------- */
typedef struct _p_IGA *IGA;
typedef struct _n_IGAAxis *IGAAxis;
typedef struct _n_IGARule *IGARule;
typedef struct _n_IGABasis *IGABasis;
typedef struct _n_IGAForm *IGAForm;
typedef struct _n_IGAElement *IGAElement;
typedef struct _n_IGAPoint *IGAPoint;
typedef struct _n_IGAProbe *IGAProbe;
/* ---------------------------------------------------------------- */
struct _n_IGAAxis {
PetscInt refct;
/**/
PetscInt p; /* polynomial order */
PetscInt m; /* last knot index */
PetscReal *U; /* knot vector */
/**/
PetscBool periodic; /* periodicity */
PetscInt nnp,nel; /* bases, spans */
PetscInt *span; /* span indices */
};
PETSC_EXTERN PetscErrorCode IGAAxisCreate(IGAAxis *axis);
PETSC_EXTERN PetscErrorCode IGAAxisDestroy(IGAAxis *axis);
PETSC_EXTERN PetscErrorCode IGAAxisReset(IGAAxis axis);
PETSC_EXTERN PetscErrorCode IGAAxisReference(IGAAxis axis);
PETSC_EXTERN PetscErrorCode IGAAxisCopy(IGAAxis base,IGAAxis axis);
PETSC_EXTERN PetscErrorCode IGAAxisDuplicate(IGAAxis base,IGAAxis *axis);
PETSC_EXTERN PetscErrorCode IGAAxisSetPeriodic(IGAAxis axis,PetscBool periodic);
PETSC_EXTERN PetscErrorCode IGAAxisGetPeriodic(IGAAxis axis,PetscBool *periodic);
PETSC_EXTERN PetscErrorCode IGAAxisSetDegree(IGAAxis axis,PetscInt p);
PETSC_EXTERN PetscErrorCode IGAAxisGetDegree(IGAAxis axis,PetscInt *p);
PETSC_EXTERN PetscErrorCode IGAAxisSetKnots(IGAAxis axis,PetscInt m,const PetscReal U[]);
PETSC_EXTERN PetscErrorCode IGAAxisGetKnots(IGAAxis axis,PetscInt *m,PetscReal *U[]);
PETSC_EXTERN PetscErrorCode IGAAxisGetLimits(IGAAxis axis,PetscReal *Ui,PetscReal *Uf);
PETSC_EXTERN PetscErrorCode IGAAxisGetSizes(IGAAxis axis,PetscInt *nel,PetscInt *nnp);
PETSC_EXTERN PetscErrorCode IGAAxisGetSpans(IGAAxis axis,PetscInt *nel,PetscInt *spans[]);
PETSC_EXTERN PetscErrorCode IGAAxisInit(IGAAxis axis,PetscInt p,PetscInt m,const PetscReal U[]);
PETSC_EXTERN PetscErrorCode IGAAxisInitBreaks(IGAAxis axis,PetscInt nu,const PetscReal u[],PetscInt C);
PETSC_EXTERN PetscErrorCode IGAAxisInitUniform(IGAAxis axis,PetscInt N,PetscReal Ui,PetscReal Uf,PetscInt C);
PETSC_EXTERN PetscErrorCode IGAAxisSetUp(IGAAxis axis);
typedef enum {
IGA_RULE_LEGENDRE=0, /* Gauss-Legendre */
IGA_RULE_LOBATTO, /* Gauss-Lobatto */
IGA_RULE_REDUCED, /* Reduced Gauss-Legendre */
IGA_RULE_USER /* User-defined */
} IGARuleType;
PETSC_EXTERN const char *const IGARuleTypes[];
struct _n_IGARule {
PetscInt refct;
/**/
IGARuleType type; /* rule type */
/**/
PetscInt nqp; /* number of quadrature points */
PetscReal *point; /* [nqp] quadrature points */
PetscReal *weight; /* [nqp] quadrature weights */
};
PETSC_EXTERN PetscErrorCode IGARuleCreate(IGARule *rule);
PETSC_EXTERN PetscErrorCode IGARuleDestroy(IGARule *rule);
PETSC_EXTERN PetscErrorCode IGARuleReset(IGARule rule);
PETSC_EXTERN PetscErrorCode IGARuleReference(IGARule rule);
PETSC_EXTERN PetscErrorCode IGARuleCopy(IGARule base,IGARule rule);
PETSC_EXTERN PetscErrorCode IGARuleDuplicate(IGARule base,IGARule *rule);
PETSC_EXTERN PetscErrorCode IGARuleSetType(IGARule rule,IGARuleType type);
PETSC_EXTERN PetscErrorCode IGARuleSetSize(IGARule rule,PetscInt nqp);
PETSC_EXTERN PetscErrorCode IGARuleSetUp(IGARule rule);
PETSC_EXTERN PetscErrorCode IGARuleSetRule(IGARule rule,PetscInt q,const PetscReal x[],const PetscReal w[]);
PETSC_EXTERN PetscErrorCode IGARuleGetRule(IGARule rule,PetscInt *q,PetscReal *x[],PetscReal *w[]);
typedef enum {
IGA_BASIS_BSPLINE=0, /* B-Spline basis functions */
IGA_BASIS_BERNSTEIN, /* Bernstein polynomials (C^0 B-Spline basis) */
IGA_BASIS_LAGRANGE, /* Lagrange polynomials on Newton-Cotes points */
IGA_BASIS_SPECTRAL /* Lagrange polynomials on Gauss-Lobatto points */
} IGABasisType;
PETSC_EXTERN const char *const IGABasisTypes[];
struct _n_IGABasis {
PetscInt refct;
/**/
IGABasisType type; /* basis type */
/**/
PetscInt nel; /* number of elements */
PetscInt nqp; /* number of quadrature points */
PetscInt nen; /* number of local basis functions */
PetscInt *offset; /* [nel] basis offset */
PetscReal *detJac; /* [nel] element length */
PetscReal *weight; /* [nel][nqp] quadrature weight */
PetscReal *point; /* [nel][nqp] quadrature point */
PetscReal *value; /* [nel][nqp][nen][5] basis derivatives */
PetscReal bnd_detJac;
PetscReal bnd_weight;
PetscReal bnd_point[2];
PetscReal *bnd_value[2]; /* [nen][5] */
};
PETSC_EXTERN PetscErrorCode IGABasisCreate(IGABasis *basis);
PETSC_EXTERN PetscErrorCode IGABasisDestroy(IGABasis *basis);
PETSC_EXTERN PetscErrorCode IGABasisReset(IGABasis basis);
PETSC_EXTERN PetscErrorCode IGABasisReference(IGABasis basis);
PETSC_EXTERN PetscErrorCode IGABasisSetType(IGABasis basis,IGABasisType type);
PETSC_EXTERN PetscErrorCode IGABasisInitQuadrature (IGABasis basis,IGAAxis axis,IGARule rule);
PETSC_EXTERN PetscErrorCode IGABasisInitCollocation(IGABasis basis,IGAAxis axis);
/* ---------------------------------------------------------------- */
typedef PetscErrorCode (*IGAFormExact)(IGAPoint point,PetscInt k,PetscScalar V[],void *ctx);
typedef PetscErrorCode (*IGAFormScalar)(IGAPoint point,const PetscScalar U[],PetscInt n,PetscScalar S[],void *ctx);
typedef PetscErrorCode (*IGAFormVector)(IGAPoint point,PetscScalar F[],void *ctx);
typedef PetscErrorCode (*IGAFormMatrix)(IGAPoint point,PetscScalar K[],void *ctx);
typedef PetscErrorCode (*IGAFormSystem)(IGAPoint point,PetscScalar K[],PetscScalar F[],void *ctx);
typedef PetscErrorCode (*IGAFormFunction)(IGAPoint point,
const PetscScalar U[],
PetscScalar F[],void *ctx);
typedef PetscErrorCode (*IGAFormJacobian)(IGAPoint point,
const PetscScalar U[],
PetscScalar J[],void *ctx);
typedef PetscErrorCode (*IGAFormIFunction)(IGAPoint point,
PetscReal a,const PetscScalar V[],
PetscReal t,const PetscScalar U[],
PetscScalar F[],void *ctx);
typedef PetscErrorCode (*IGAFormIJacobian)(IGAPoint point,
PetscReal a,const PetscScalar V[],
PetscReal t,const PetscScalar U[],
PetscScalar J[],void *ctx);
typedef PetscErrorCode (*IGAFormI2Function)(IGAPoint point,
PetscReal a,const PetscScalar A[],
PetscReal v,const PetscScalar V[],
PetscReal t,const PetscScalar U[],
PetscScalar F[],void *ctx);
typedef PetscErrorCode (*IGAFormI2Jacobian)(IGAPoint point,
PetscReal a,const PetscScalar A[],
PetscReal v,const PetscScalar V[],
PetscReal t,const PetscScalar U[],
PetscScalar J[],void *ctx);
typedef PetscErrorCode (*IGAFormIEFunction)(IGAPoint point,
PetscReal a,const PetscScalar V[],
PetscReal t,const PetscScalar U[],
PetscReal t0,const PetscScalar U0[],
PetscScalar F[],void *ctx);
typedef PetscErrorCode (*IGAFormIEJacobian)(IGAPoint point,
PetscReal a,const PetscScalar V[],
PetscReal t,const PetscScalar U[],
PetscReal t0,const PetscScalar U0[],
PetscScalar J[],void *ctx);
typedef PetscErrorCode (*IGAFormRHSFunction)(IGAPoint point,
PetscReal t,const PetscScalar U[],
PetscScalar F[],void *ctx);
typedef PetscErrorCode (*IGAFormRHSJacobian)(IGAPoint point,
PetscReal t,const PetscScalar U[],
PetscScalar J[],void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormJacobianFD(IGAPoint p,
const PetscScalar U[],
PetscScalar J[],void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormIJacobianFD(IGAPoint p,
PetscReal s,const PetscScalar V[],
PetscReal t,const PetscScalar U[],
PetscScalar J[],void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormIEJacobianFD(IGAPoint p,
PetscReal s, const PetscScalar V[],
PetscReal t, const PetscScalar U[],
PetscReal t0,const PetscScalar U0[],
PetscScalar J[],void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormI2JacobianFD(IGAPoint p,
PetscReal a,const PetscScalar A[],
PetscReal v,const PetscScalar V[],
PetscReal t,const PetscScalar U[],
PetscScalar J[],void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormRHSJacobianFD(IGAPoint p,
PetscReal t,const PetscScalar U[],
PetscScalar F[],void *ctx);
typedef struct _IGAFormBC *IGAFormBC;
struct _IGAFormBC {
PetscInt count;
PetscInt field[64];
PetscScalar value[64];
};
typedef struct _IGAFormOps *IGAFormOps;
struct _IGAFormOps {
/**/
IGAFormVector Vector;
void *VecCtx;
IGAFormMatrix Matrix;
void *MatCtx;
IGAFormSystem System;
void *SysCtx;
/**/
IGAFormFunction Function;
void *FunCtx;
IGAFormJacobian Jacobian;
void *JacCtx;
/**/
IGAFormIFunction IFunction;
IGAFormI2Function I2Function;
void *IFunCtx;
IGAFormIJacobian IJacobian;
IGAFormI2Jacobian I2Jacobian;
void *IJacCtx;
/**/
IGAFormIEFunction IEFunction;
void *IEFunCtx;
IGAFormIEJacobian IEJacobian;
void *IEJacCtx;
/**/
IGAFormRHSFunction RHSFunction;
void *RHSFunCtx;
IGAFormRHSJacobian RHSJacobian;
void *RHSJacCtx;
};
struct _n_IGAForm {
PetscInt refct;
/**/
IGAFormOps ops;
PetscInt dof;
IGAFormBC value[3][2];
IGAFormBC load [3][2];
PetscBool visit[3][2];
};
PETSC_EXTERN PetscErrorCode IGAGetForm(IGA iga,IGAForm *form);
PETSC_EXTERN PetscErrorCode IGASetForm(IGA iga,IGAForm form);
PETSC_EXTERN PetscErrorCode IGAFormCreate(IGAForm *form);
PETSC_EXTERN PetscErrorCode IGAFormDestroy(IGAForm *form);
PETSC_EXTERN PetscErrorCode IGAFormReset(IGAForm form);
PETSC_EXTERN PetscErrorCode IGAFormReference(IGAForm form);
PETSC_EXTERN PetscErrorCode IGAFormSetBoundaryValue(IGAForm form,PetscInt axis,PetscInt side,PetscInt field,PetscScalar value);
PETSC_EXTERN PetscErrorCode IGAFormSetBoundaryLoad (IGAForm form,PetscInt axis,PetscInt side,PetscInt field,PetscScalar value);
PETSC_EXTERN PetscErrorCode IGAFormSetBoundaryForm (IGAForm form,PetscInt axis,PetscInt side,PetscBool flag);
PETSC_EXTERN PetscErrorCode IGAFormClearBoundary (IGAForm form,PetscInt axis,PetscInt side);
PETSC_EXTERN PetscErrorCode IGAFormSetVector (IGAForm form,IGAFormVector Vector, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetMatrix (IGAForm form,IGAFormMatrix Matrix, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetSystem (IGAForm form,IGAFormSystem System, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetFunction (IGAForm form,IGAFormFunction Function, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetJacobian (IGAForm form,IGAFormJacobian Jacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetIFunction (IGAForm form,IGAFormIFunction IFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetIJacobian (IGAForm form,IGAFormIJacobian IJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetI2Function (IGAForm form,IGAFormI2Function IFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetI2Jacobian (IGAForm form,IGAFormI2Jacobian IJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetIEFunction (IGAForm form,IGAFormIEFunction IEFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetIEJacobian (IGAForm form,IGAFormIEJacobian IEJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetRHSFunction(IGAForm form,IGAFormRHSFunction RHSFunction,void *ctx);
PETSC_EXTERN PetscErrorCode IGAFormSetRHSJacobian(IGAForm form,IGAFormRHSJacobian RHSJacobian,void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFixTable(IGA iga,Vec table);
PETSC_EXTERN PetscErrorCode IGASetBoundaryValue(IGA iga,PetscInt axis,PetscInt side,PetscInt field,PetscScalar value);
PETSC_EXTERN PetscErrorCode IGASetBoundaryLoad (IGA iga,PetscInt axis,PetscInt side,PetscInt field,PetscScalar value);
PETSC_EXTERN PetscErrorCode IGASetBoundaryForm (IGA iga,PetscInt axis,PetscInt side,PetscBool flag);
PETSC_EXTERN PetscErrorCode IGASetFormVector (IGA iga,IGAFormVector Vector, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormMatrix (IGA iga,IGAFormMatrix Matrix, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormSystem (IGA iga,IGAFormSystem System, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormFunction (IGA iga,IGAFormFunction Function, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormJacobian (IGA iga,IGAFormJacobian Jacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormIFunction (IGA iga,IGAFormIFunction IFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormIJacobian (IGA iga,IGAFormIJacobian IJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormI2Function (IGA iga,IGAFormI2Function IFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormI2Jacobian (IGA iga,IGAFormI2Jacobian IJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormIEFunction (IGA iga,IGAFormIEFunction IEFunction, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormIEJacobian (IGA iga,IGAFormIEJacobian IEJacobian, void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormRHSFunction(IGA iga,IGAFormRHSFunction RHSFunction,void *ctx);
PETSC_EXTERN PetscErrorCode IGASetFormRHSJacobian(IGA iga,IGAFormRHSJacobian RHSJacobian,void *ctx);
/* ---------------------------------------------------------------- */
typedef struct _IGAOps *IGAOps;
struct _IGAOps {
PetscErrorCode (*create)(IGA);
PetscErrorCode (*destroy)(IGA);
PetscErrorCode (*view)(IGA);
PetscErrorCode (*setup)(IGA);
PetscErrorCode (*setfromoptions)(IGA);
};
struct _p_IGA {
PETSCHEADER(struct _IGAOps);
PetscBool setup;
PetscInt setupstage;
PetscBool collocation;
VecType vectype;
MatType mattype;
char **fieldname;
PetscInt dim; /* parametric dimension of the function space*/
PetscInt dof; /* number of degrees of freedom per node */
PetscInt order; /* maximum derivative order */
IGAAxis axis[3];
IGARule rule[3];
IGABasis basis[3];
IGAForm form;
IGAElement iterator;
PetscBool rational;
PetscInt geometry;
PetscInt property;
PetscReal *rationalW;
PetscReal *geometryX;
PetscScalar *propertyA;
PetscBool fixtable;
PetscScalar *fixtableU;
PetscInt proc_sizes[3];
PetscInt proc_ranks[3];
PetscInt elem_sizes[3];
PetscInt elem_start[3];
PetscInt elem_width[3];
PetscInt geom_sizes[3];
PetscInt geom_lstart[3];
PetscInt geom_lwidth[3];
PetscInt geom_gstart[3];
PetscInt geom_gwidth[3];
PetscInt node_shift[3];
PetscInt node_sizes[3];
PetscInt node_lstart[3];
PetscInt node_lwidth[3];
PetscInt node_gstart[3];
PetscInt node_gwidth[3];
AO ao;
LGMap lgmap;
PetscLayout map;
VecScatter g2l,l2g,l2l;
PetscInt nwork;
Vec vwork[16];
Vec natural;
VecScatter n2g,g2n;
DM elem_dm;
DM geom_dm;
DM node_dm;
DM draw_dm;
};
PETSC_EXTERN PetscClassId IGA_CLASSID;
#define IGA_FILE_CLASSID 1211299
PETSC_EXTERN PetscErrorCode IGAInitializePackage(void);
PETSC_EXTERN PetscErrorCode IGAFinalizePackage(void);
PETSC_EXTERN PetscErrorCode IGARegisterAll(void);
PETSC_EXTERN PetscErrorCode IGACreate(MPI_Comm comm,IGA *iga);
PETSC_EXTERN PetscErrorCode IGADestroy(IGA *iga);
PETSC_EXTERN PetscErrorCode IGAReset(IGA iga);
PETSC_EXTERN PetscErrorCode IGASetUp(IGA iga);
PETSC_EXTERN PetscErrorCode IGAView(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGAGetOptionsPrefix(IGA iga,const char *prefix[]);
PETSC_EXTERN PetscErrorCode IGASetOptionsPrefix(IGA iga,const char prefix[]);
PETSC_EXTERN PetscErrorCode IGAPrependOptionsPrefix(IGA iga,const char prefix[]);
PETSC_EXTERN PetscErrorCode IGAAppendOptionsPrefix(IGA iga,const char prefix[]);
PETSC_EXTERN PetscErrorCode IGASetFromOptions(IGA iga);
PETSC_EXTERN PetscErrorCode IGAViewFromOptions(IGA iga,PetscObject obj,const char name[]);
PETSC_EXTERN PetscErrorCode IGAOptionsAlias(const char name[],const char defval[],const char alias[]);
PETSC_EXTERN PetscErrorCode IGALoad(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGASave(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGARead(IGA iga,const char filename[]);
PETSC_EXTERN PetscErrorCode IGAWrite(IGA iga,const char filename[]);
PETSC_EXTERN PetscErrorCode IGAPrint(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGADraw(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGASetGeometryDim(IGA iga,PetscInt dim);
PETSC_EXTERN PetscErrorCode IGAGetGeometryDim(IGA iga,PetscInt *dim);
PETSC_EXTERN PetscErrorCode IGALoadGeometry(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGASaveGeometry(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGASetPropertyDim(IGA iga,PetscInt dim);
PETSC_EXTERN PetscErrorCode IGAGetPropertyDim(IGA iga,PetscInt *dim);
PETSC_EXTERN PetscErrorCode IGALoadProperty(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGASaveProperty(IGA iga,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGALoadVec(IGA iga,Vec vec,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGASaveVec(IGA iga,Vec vec,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGADrawVec(IGA iga,Vec vec,PetscViewer viewer);
PETSC_EXTERN PetscErrorCode IGAReadVec(IGA iga,Vec vec,const char filename[]);
PETSC_EXTERN PetscErrorCode IGAWriteVec(IGA iga,Vec vec,const char filename[]);
PETSC_EXTERN PetscErrorCode IGADrawVecVTK(IGA iga,Vec vec,const char filename[]);
PETSC_EXTERN PetscErrorCode IGASetDim(IGA iga,PetscInt dim);
PETSC_EXTERN PetscErrorCode IGAGetDim(IGA iga,PetscInt *dim);
PETSC_EXTERN PetscErrorCode IGASetDof(IGA iga,PetscInt dof);
PETSC_EXTERN PetscErrorCode IGAGetDof(IGA iga,PetscInt *dof);
PETSC_EXTERN PetscErrorCode IGASetName(IGA iga,const char name[]);
PETSC_EXTERN PetscErrorCode IGAGetName(IGA iga,const char *name[]);
PETSC_EXTERN PetscErrorCode IGASetFieldName(IGA iga,PetscInt field,const char name[]);
PETSC_EXTERN PetscErrorCode IGAGetFieldName(IGA iga,PetscInt field,const char *name[]);
PETSC_EXTERN PetscErrorCode IGASetOrder(IGA iga,PetscInt order);
PETSC_EXTERN PetscErrorCode IGAGetOrder(IGA iga,PetscInt *order);
PETSC_EXTERN PetscErrorCode IGASetProcessors(IGA iga,PetscInt i,PetscInt processors);
PETSC_EXTERN PetscErrorCode IGASetBasisType(IGA iga,PetscInt i,IGABasisType type);
PETSC_EXTERN PetscErrorCode IGASetRuleType(IGA iga,PetscInt i,IGARuleType type);
PETSC_EXTERN PetscErrorCode IGASetRuleSize(IGA iga,PetscInt i,PetscInt nqp);
PETSC_EXTERN PetscErrorCode IGASetQuadrature(IGA iga,PetscInt i,PetscInt q);
PETSC_EXTERN PetscErrorCode IGASetUseCollocation(IGA iga,PetscBool collocation);
PETSC_EXTERN PetscErrorCode IGAGetComm(IGA iga,MPI_Comm *comm);
PETSC_EXTERN PetscErrorCode IGAGetAxis(IGA iga,PetscInt i,IGAAxis *axis);
PETSC_EXTERN PetscErrorCode IGAGetRule(IGA iga,PetscInt i,IGARule *rule);
PETSC_EXTERN PetscErrorCode IGAGetBasis(IGA iga,PetscInt i,IGABasis *basis);
PETSC_EXTERN PetscErrorCode IGACreateDMDA(IGA iga,PetscInt bs,
const PetscInt gsizes[],
const PetscInt lsizes[],
const PetscBool periodic[],
PetscBool stencil_box,
PetscInt stencil_width,
DM *dm);
PETSC_EXTERN PetscErrorCode IGACreateElemDM(IGA iga,PetscInt bs,DM *dm);
PETSC_EXTERN PetscErrorCode IGACreateGeomDM(IGA iga,PetscInt bs,DM *dm);
PETSC_EXTERN PetscErrorCode IGACreateNodeDM(IGA iga,PetscInt bs,DM *dm);
PETSC_EXTERN PetscErrorCode IGAGetElemDM(IGA iga,DM *dm);
PETSC_EXTERN PetscErrorCode IGAGetGeomDM(IGA iga,DM *dm);
PETSC_EXTERN PetscErrorCode IGAGetNodeDM(IGA iga,DM *dm);
PETSC_EXTERN PetscErrorCode IGASetVecType(IGA iga,const VecType vectype);
PETSC_EXTERN PetscErrorCode IGASetMatType(IGA iga,const MatType mattype);
PETSC_EXTERN PetscErrorCode IGACreateVec(IGA iga,Vec *vec);
PETSC_EXTERN PetscErrorCode IGACreateMat(IGA iga,Mat *mat);
PETSC_EXTERN PetscErrorCode IGACreateCoordinates(IGA iga,Vec *coords);
PETSC_EXTERN PetscErrorCode IGACreateRigidBody(IGA iga,MatNullSpace *nsp);
PETSC_EXTERN PetscErrorCode IGACreateLocalVec(IGA iga, Vec *lvec);
PETSC_EXTERN PetscErrorCode IGAGetLocalVec(IGA iga,Vec *lvec);
PETSC_EXTERN PetscErrorCode IGARestoreLocalVec(IGA iga,Vec *lvec);
PETSC_EXTERN PetscErrorCode IGAGlobalToLocalBegin(IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGAGlobalToLocalEnd (IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGAGlobalToLocal (IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToGlobalBegin(IGA iga,Vec lvec,Vec gvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToGlobalEnd (IGA iga,Vec lvec,Vec gvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToGlobal (IGA iga,Vec lvec,Vec gvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToLocalBegin (IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToLocalEnd (IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGALocalToLocal (IGA iga,Vec gvec,Vec lvec,InsertMode addv);
PETSC_EXTERN PetscErrorCode IGAGetNaturalVec(IGA iga,Vec *nvec);
PETSC_EXTERN PetscErrorCode IGANaturalToGlobal(IGA iga,Vec nvec,Vec gvec);
PETSC_EXTERN PetscErrorCode IGAGlobalToNatural(IGA iga,Vec gvec,Vec nvec);
PETSC_EXTERN PetscErrorCode IGAGetLocalVecArray(IGA iga,Vec gvec,Vec *lvec,const PetscScalar *array[]);
PETSC_EXTERN PetscErrorCode IGARestoreLocalVecArray(IGA iga,Vec gvec,Vec *lvec,const PetscScalar *array[]);
PETSC_EXTERN PetscErrorCode IGAClone(IGA iga,PetscInt dof,IGA *newiga);
#define DMIGA "iga"
PETSC_EXTERN PetscErrorCode DMIGACreate(IGA iga,DM *dm);
PETSC_EXTERN PetscErrorCode DMIGASetIGA(DM dm,IGA iga);
PETSC_EXTERN PetscErrorCode DMIGAGetIGA(DM dm,IGA *iga);
/* ---------------------------------------------------------------- */
struct _n_IGAElement {
PetscInt refct;
/**/
PetscInt start[3];
PetscInt width[3];
PetscInt sizes[3];
PetscInt ID[3];
/**/
PetscBool atboundary;
PetscInt boundary_id;
/**/
PetscInt count;
PetscInt index;
/**/
PetscInt neq;
PetscInt nen;
PetscInt dof;
PetscInt dim;
PetscInt nsd;
PetscInt npd;
PetscInt *mapping; /*[nen] */
PetscInt *rowmap; /*[neq] */
PetscInt *colmap; /*[nen] */
PetscBool rational;
PetscReal *rationalW; /*[nen] */
PetscBool geometry;
PetscReal *geometryX; /*[nen][nsd] */
PetscBool property;
PetscScalar *propertyA; /*[nen][npd] */
PetscInt nqp;
PetscInt sqp[3];
PetscReal *weight; /* [nqp] */
PetscReal *detJac; /* [nqp] */
PetscReal *basis[5]; /*0: [nqp][nen] */
/*1: [nqp][nen][dim] */
/*2: [nqp][nen][dim][dim] */
/*3: [nqp][nen][dim][dim][dim] */
/*4: [nqp][nen][dim][dim][dim][dim] */
PetscReal *shape[5]; /*0: [nqp][nen] */
/*1: [nqp][nen][nsd] */
/*2: [nqp][nen][nsd][nsd] */
/*3: [nqp][nen][nsd][nsd][nsd] */
/*4: [nqp][nen][nsd][nsd][nsd][nsd] */
PetscReal *mapU[5]; /*0: [nqp][dim] */
/*1: [nqp][dim][nsd] */
/*2: [nqp][dim][nsd][nsd] */
/*3: [nqp][dim][nsd][nsd][nsd] */
/*4: [nqp][dim][nsd][nsd][nsd][nsd] */
PetscReal *mapX[5]; /*0: [nqp][nsd] */
/*1: [nqp][nsd][dim] */
/*2: [nqp][nsd][dim][dim] */
/*3: [nqp][nsd][dim][dim][dim] */
/*4: [nqp][nsd][dim][dim][dim][dim] */
PetscReal *normal; /* [nqp][nsd] */
PetscReal *detX; /* [nqp] */
PetscReal *detS; /* [nqp] */
IGA parent;
IGAPoint iterator;
PetscBool collocation;
PetscInt nfix;
PetscInt *ifix;
PetscScalar *vfix;
PetscScalar *ufix;
PetscInt nflux;
PetscInt *iflux;
PetscScalar *vflux;
PetscInt nval;
PetscScalar *wval[8];
PetscInt nvec;
PetscScalar *wvec[8];
PetscInt nmat;
PetscScalar *wmat[4];
};
PETSC_EXTERN PetscErrorCode IGAElementCreate(IGAElement *element);
PETSC_EXTERN PetscErrorCode IGAElementDestroy(IGAElement *element);
PETSC_EXTERN PetscErrorCode IGAElementReference(IGAElement element);
PETSC_EXTERN PetscErrorCode IGAElementReset(IGAElement element);
PETSC_EXTERN PetscErrorCode IGAElementInit(IGAElement element,IGA iga);
PETSC_EXTERN PetscErrorCode IGAGetElement(IGA iga,IGAElement *element);
PETSC_EXTERN PetscErrorCode IGABeginElement(IGA iga,IGAElement *element);
PETSC_EXTERN PetscBool IGANextElement(IGA iga,IGAElement element);
PETSC_EXTERN PetscErrorCode IGAEndElement(IGA iga,IGAElement *element);
PETSC_EXTERN PetscBool IGAElementNextForm(IGAElement element,PetscBool visit[][2]);
PETSC_EXTERN PetscErrorCode IGAElementGetPoint(IGAElement element,IGAPoint *point);
PETSC_EXTERN PetscErrorCode IGAElementBeginPoint(IGAElement element,IGAPoint *point);
PETSC_EXTERN PetscBool IGAElementNextPoint(IGAElement element,IGAPoint point);
PETSC_EXTERN PetscErrorCode IGAElementEndPoint(IGAElement element,IGAPoint *point);
PETSC_EXTERN PetscErrorCode IGAElementBuildClosure(IGAElement element);
PETSC_EXTERN PetscErrorCode IGAElementBuildTabulation(IGAElement element);
PETSC_EXTERN PetscErrorCode IGAElementGetParent(IGAElement element,IGA *parent);
PETSC_EXTERN PetscErrorCode IGAElementGetIndex(IGAElement element,PetscInt *index);
PETSC_EXTERN PetscErrorCode IGAElementGetCount(IGAElement element,PetscInt *count);
PETSC_EXTERN PetscErrorCode IGAElementGetSizes(IGAElement element,PetscInt *neq,PetscInt *nen,PetscInt *dof);
PETSC_EXTERN PetscErrorCode IGAElementGetClosure(IGAElement element,PetscInt *nen,const PetscInt *mapping[]);
PETSC_EXTERN PetscErrorCode IGAElementGetIndices(IGAElement element,
PetscInt *neq,const PetscInt *rowmap[],
PetscInt *nen,const PetscInt *colmap[]);
PETSC_EXTERN PetscErrorCode IGAElementGetWorkVec(IGAElement element,PetscScalar *V[]);
PETSC_EXTERN PetscErrorCode IGAElementGetWorkMat(IGAElement element,PetscScalar *M[]);
PETSC_EXTERN PetscErrorCode IGAElementGetValues(IGAElement element,const PetscScalar arrayU[],PetscScalar *U[]);
PETSC_EXTERN PetscErrorCode IGAElementBuildFix(IGAElement element);
PETSC_EXTERN PetscErrorCode IGAElementDelValues(IGAElement element,PetscScalar V[]);
PETSC_EXTERN PetscErrorCode IGAElementFixValues(IGAElement element,PetscScalar U[]);
PETSC_EXTERN PetscErrorCode IGAElementFixSystem(IGAElement element,PetscScalar K[],PetscScalar F[]);
PETSC_EXTERN PetscErrorCode IGAElementFixFunction(IGAElement element,PetscScalar F[]);
PETSC_EXTERN PetscErrorCode IGAElementFixJacobian(IGAElement element,PetscScalar J[]);
PETSC_EXTERN PetscErrorCode IGAElementAssembleVec(IGAElement element,const PetscScalar F[],Vec vec);
PETSC_EXTERN PetscErrorCode IGAElementAssembleMat(IGAElement element,const PetscScalar K[],Mat mat);
/* ---------------------------------------------------------------- */
struct _n_IGAPoint {
PetscInt refct;
/**/
PetscBool atboundary;
PetscInt boundary_id;
/**/
PetscInt count;
PetscInt index;
/**/
PetscInt neq;
PetscInt nen;
PetscInt dof;
PetscInt dim;
PetscInt nsd;
PetscInt npd;
PetscReal *rational;/* [nen] */
PetscReal *geometry;/* [nen][nsd] */
PetscScalar *property;/* [nen][npd] */
PetscReal *weight; /* [1] */
PetscReal *detJac; /* [1] */
PetscReal *point; /* [dim] */
PetscReal *normal; /* [nsd] */
PetscReal *basis[5]; /*0: [nen] */
/*1: [nen][dim] */
/*2: [nen][dim][dim] */
/*3: [nen][dim][dim][dim] */
/*4: [nen][dim][dim][dim][dim] */
PetscReal *shape[5]; /*0: [nen] */
/*1: [nen][nsd] */
/*2: [nen][nsd][nsd] */
/*3: [nen][nsd][nsd][nsd] */
/*3: [nen][nsd][nsd][nsd][nsd] */
PetscReal *mapU[5]; /*0: [dim] */
/*1: [dim][nsd] */
/*2: [dim][nsd][nsd] */
/*3: [dim][nsd][nsd][nsd] */
/*4: [dim][nsd][nsd][nsd][nsd] */
PetscReal *mapX[5]; /*0: [nsd] */
/*1: [nsd][dim] */
/*2: [nsd][dim][dim] */
/*3: [nsd][dim][dim][dim] */
/*4: [nsd][dim][dim][dim][dim] */
PetscReal *detX; /* [1] */
PetscReal *detS; /* [1] */
IGAElement parent;
PetscInt nvec;
PetscScalar *wvec[8];
PetscInt nmat;
PetscScalar *wmat[4];
};
PETSC_EXTERN PetscErrorCode IGAPointCreate(IGAPoint *point);
PETSC_EXTERN PetscErrorCode IGAPointDestroy(IGAPoint *point);
PETSC_EXTERN PetscErrorCode IGAPointReference(IGAPoint point);
PETSC_EXTERN PetscErrorCode IGAPointReset(IGAPoint point);
PETSC_EXTERN PetscErrorCode IGAPointInit(IGAPoint point,IGAElement element);
PETSC_EXTERN PetscErrorCode IGAPointGetParent(IGAPoint point,IGAElement *element);
PETSC_EXTERN PetscErrorCode IGAPointGetIndex(IGAPoint point,PetscInt *index);
PETSC_EXTERN PetscErrorCode IGAPointGetCount(IGAPoint point,PetscInt *count);
PETSC_EXTERN PetscErrorCode IGAPointAtBoundary(IGAPoint point,PetscInt *axis,PetscInt *side);
PETSC_EXTERN PetscErrorCode IGAPointGetSizes(IGAPoint point,PetscInt *neq,PetscInt *nen,PetscInt *dof);
PETSC_EXTERN PetscErrorCode IGAPointGetDims(IGAPoint point,PetscInt *dim,PetscInt *nsd,PetscInt *npd);
PETSC_EXTERN PetscErrorCode IGAPointGetQuadrature(IGAPoint point,PetscReal *weigth,PetscReal *detJac);
PETSC_EXTERN PetscErrorCode IGAPointGetBasisFuns(IGAPoint point,PetscInt der,const PetscReal *basisfuns[]);
PETSC_EXTERN PetscErrorCode IGAPointGetShapeFuns(IGAPoint point,PetscInt der,const PetscReal *shapefuns[]);
PETSC_EXTERN PetscErrorCode IGAPointFormPoint(IGAPoint p,PetscReal x[]);
PETSC_EXTERN PetscErrorCode IGAPointFormGeomMap(IGAPoint p,PetscReal x[]);
PETSC_EXTERN PetscErrorCode IGAPointFormGradGeomMap(IGAPoint p,PetscReal F[]);
PETSC_EXTERN PetscErrorCode IGAPointFormInvGradGeomMap(IGAPoint p,PetscReal G[]);
PETSC_EXTERN PetscErrorCode IGAPointEvaluate (IGAPoint p,PetscInt ider,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointFormValue(IGAPoint p,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointFormGrad (IGAPoint p,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointFormHess (IGAPoint p,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointFormDel2 (IGAPoint p,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointFormDer3 (IGAPoint p,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointFormDer4 (IGAPoint p,const PetscScalar U[],PetscScalar u[]);
PETSC_EXTERN PetscErrorCode IGAPointGetWorkVec(IGAPoint point,PetscScalar *V[]);
PETSC_EXTERN PetscErrorCode IGAPointGetWorkMat(IGAPoint point,PetscScalar *M[]);
PETSC_EXTERN PetscErrorCode IGAPointAddArray(IGAPoint point,PetscInt n,const PetscScalar a[],PetscScalar A[]);
PETSC_EXTERN PetscErrorCode IGAPointAddVec(IGAPoint point,const PetscScalar f[],PetscScalar F[]);
PETSC_EXTERN PetscErrorCode IGAPointAddMat(IGAPoint point,const PetscScalar k[],PetscScalar K[]);
/* ---------------------------------------------------------------- */
struct _n_IGAProbe {
PetscInt refct;
/**/
IGA iga;
Vec gvec;
Vec lvec;
/**/
PetscInt order;
PetscBool collective;
PetscBool offprocess;
/**/
PetscInt dim;
PetscInt nsd;
PetscInt dof;
PetscInt p[3];
PetscReal *U[3];
PetscInt n[3];
PetscInt s[3];
PetscInt w[3];
const PetscReal *arrayW;
const PetscReal *arrayX;
const PetscScalar *arrayA;
/**/
PetscInt nen;
PetscInt *map;
PetscReal *W;
PetscReal *X;
PetscScalar *A;
/**/
PetscReal point[3];
PetscInt ID[3];
PetscReal *BD[3];
PetscReal *basis[5]; /*0: [nen] */
/*1: [nen][dim] */
/*2: [nen][dim][dim] */
/*3: [nen][dim][dim][dim] */
/*4: [nen][dim][dim][dim][dim] */
PetscReal *shape[5]; /*0: [nen] */
/*1: [nen][nsd] */
/*2: [nen][nsd][nsd] */
/*3: [nen][nsd][nsd][nsd] */
/*4: [nen][nsd][nsd][nsd][nsd] */
PetscReal *mapU[5]; /*0: [dim] */
/*1: [dim][nsd] */
/*2: [dim][nsd][nsd] */
/*3: [dim][nsd][nsd][nsd] */
/*4: [dim][nsd][nsd][nsd][nsd] */
PetscReal *mapX[5]; /*0: [nsd] */
/*1: [nsd][dim] */
/*2: [nsd][dim][dim] */
/*3: [nsd][dim][dim][dim] */
/*4: [nsd][dim][dim][dim][dim] */
PetscReal *detX;
};
PETSC_EXTERN PetscErrorCode IGAProbeCreate(IGA iga,Vec A,IGAProbe *prb);
PETSC_EXTERN PetscErrorCode IGAProbeDestroy(IGAProbe *prb);
PETSC_EXTERN PetscErrorCode IGAProbeReference(IGAProbe prb);
PETSC_EXTERN PetscErrorCode IGAProbeSetOrder(IGAProbe prb,PetscInt order);
PETSC_EXTERN PetscErrorCode IGAProbeSetCollective(IGAProbe prb,PetscBool collective);
PETSC_EXTERN PetscErrorCode IGAProbeSetVec(IGAProbe prb,Vec A);
PETSC_EXTERN PetscErrorCode IGAProbeSetPoint(IGAProbe prb,const PetscReal u[]);
PETSC_EXTERN PetscErrorCode IGAProbeGeomMap (IGAProbe prb,PetscReal x[]);
PETSC_EXTERN PetscErrorCode IGAProbeEvaluate (IGAProbe prb,PetscInt der,PetscScalar A[]);
PETSC_EXTERN PetscErrorCode IGAProbeFormValue(IGAProbe prb,PetscScalar A[]);
PETSC_EXTERN PetscErrorCode IGAProbeFormGrad (IGAProbe prb,PetscScalar A[]);
PETSC_EXTERN PetscErrorCode IGAProbeFormHess (IGAProbe prb,PetscScalar A[]);
PETSC_EXTERN PetscErrorCode IGAProbeFormDer3 (IGAProbe prb,PetscScalar A[]);
PETSC_EXTERN PetscErrorCode IGAProbeFormDer4 (IGAProbe prb,PetscScalar A[]);
/* ---------------------------------------------------------------- */
PETSC_EXTERN PetscLogEvent IGA_FormScalar;
PETSC_EXTERN PetscLogEvent IGA_FormVector;
PETSC_EXTERN PetscLogEvent IGA_FormMatrix;
PETSC_EXTERN PetscLogEvent IGA_FormSystem;
PETSC_EXTERN PetscLogEvent IGA_FormFunction;
PETSC_EXTERN PetscLogEvent IGA_FormJacobian;
PETSC_EXTERN PetscLogEvent IGA_FormIFunction;
PETSC_EXTERN PetscLogEvent IGA_FormIJacobian;
PETSC_EXTERN PetscErrorCode IGAComputeErrorNorm(IGA iga,PetscInt k,
Vec vecU,IGAFormExact Exact,
PetscReal enorm[],void *ctx);
PETSC_EXTERN PetscErrorCode IGAComputeScalar(IGA iga,Vec U,
PetscInt n,PetscScalar S[],
IGAFormScalar Scalar,void *ctx);
#define PCIGAEBE "igaebe"
#define PCIGABBB "igabbb"
PETSC_EXTERN PetscErrorCode IGAComputeVector(IGA iga,Vec B);
PETSC_EXTERN PetscErrorCode IGAComputeMatrix(IGA iga,Mat A);
PETSC_EXTERN PetscErrorCode IGAComputeSystem(IGA iga,Mat A,Vec B);
PETSC_EXTERN PetscErrorCode IGAComputeFunction(IGA iga,Vec U,Vec F);
PETSC_EXTERN PetscErrorCode IGAComputeJacobian(IGA iga,Vec U,Mat J);
PETSC_EXTERN PetscErrorCode IGAComputeIFunction(IGA iga,
PetscReal a,Vec V,
PetscReal t,Vec U,
Vec F);
PETSC_EXTERN PetscErrorCode IGAComputeIJacobian(IGA iga,
PetscReal a,Vec V,
PetscReal t,Vec U,
Mat J);
PETSC_EXTERN PetscErrorCode IGAComputeIEFunction(IGA iga,
PetscReal a, Vec V,
PetscReal t, Vec U,
PetscReal t0,Vec U0,
Vec F);
PETSC_EXTERN PetscErrorCode IGAComputeIEJacobian(IGA iga,
PetscReal a, Vec V,
PetscReal t, Vec U,
PetscReal t0,Vec U0,
Mat J);
PETSC_EXTERN PetscErrorCode IGAComputeRHSFunction(IGA iga,
PetscReal t,Vec U,
Vec F);
PETSC_EXTERN PetscErrorCode IGAComputeRHSJacobian(IGA iga,
PetscReal t,Vec U,
Mat J);
PETSC_EXTERN PetscErrorCode IGAComputeI2Function(IGA iga,
PetscReal a,Vec vecA,
PetscReal v,Vec vecV,
PetscReal t,Vec vecU,
Vec vecF);
PETSC_EXTERN PetscErrorCode IGAComputeI2Jacobian(IGA iga,
PetscReal a,Vec vecA,
PetscReal v,Vec vecV,
PetscReal t,Vec vecU,
Mat matJ);
PETSC_EXTERN PetscErrorCode KSPSetIGA(KSP ksp,IGA iga);
PETSC_EXTERN PetscErrorCode SNESSetIGA(SNES snes,IGA iga);
PETSC_EXTERN PetscErrorCode TSSetIGA(TS ts,IGA iga);
PETSC_EXTERN PetscErrorCode IGACreateKSP(IGA iga,KSP *ksp);
PETSC_EXTERN PetscErrorCode IGACreateSNES(IGA iga,SNES *snes);
PETSC_EXTERN PetscErrorCode IGACreateTS(IGA iga,TS *ts);
PETSC_EXTERN PetscErrorCode IGACreateTS2(IGA iga, TS *ts);
/* ---------------------------------------------------------------- */
PETSC_EXTERN PetscErrorCode IGAKSPFormRHS(KSP,Vec,void*);
PETSC_EXTERN PetscErrorCode IGAKSPFormOperators(KSP,Mat,Mat,void*);
PETSC_EXTERN PetscErrorCode IGASNESFormFunction(SNES,Vec,Vec,void*);
PETSC_EXTERN PetscErrorCode IGASNESFormJacobian(SNES,Vec,Mat,Mat,void*);
PETSC_EXTERN PetscErrorCode IGATSFormIFunction(TS,PetscReal,Vec,Vec,Vec,void*);
PETSC_EXTERN PetscErrorCode IGATSFormIJacobian(TS,PetscReal,Vec,Vec,PetscReal,Mat,Mat,void*);
PETSC_EXTERN PetscErrorCode IGATSFormI2Function(TS,PetscReal,Vec,Vec,Vec,Vec,void*);
PETSC_EXTERN PetscErrorCode IGATSFormI2Jacobian(TS,PetscReal,Vec,Vec,Vec,PetscReal,PetscReal,Mat,Mat,void*);
PETSC_EXTERN PetscErrorCode IGAPreparePCMG(IGA iga,PC pc);
PETSC_EXTERN PetscErrorCode IGAPreparePCBDDC(IGA iga,PC pc);
PETSC_EXTERN PetscErrorCode IGAPreparePCH2OPUS(IGA iga,PC pc);
PETSC_EXTERN PetscErrorCode IGASetOptionsHandlerPC(PC pc);
PETSC_EXTERN PetscErrorCode IGASetOptionsHandlerKSP(KSP ksp);
PETSC_EXTERN PetscErrorCode IGASetOptionsHandlerSNES(SNES snes);
PETSC_EXTERN PetscErrorCode IGASetOptionsHandlerTS(TS ts);
/* ---------------------------------------------------------------- */
#if defined(PETSC_USE_DEBUG)
#define IGACheckSetUp(iga,arg) do { \
if (PetscUnlikely(!(iga)->setup)) \
SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE, \
"Must call IGASetUp() on argument %D \"%s\" before %s()", \
(arg),#iga,PETSC_FUNCTION_NAME); \
} while (0)
#define IGACheckSetUpStage(iga,arg,stg) do { \
if (PetscUnlikely((iga)->setupstage<(stg))) IGACheckSetUp(iga,arg); \
} while (0)
#else
#define IGACheckSetUp(iga,arg) do {} while (0)
#define IGACheckSetUpStage(iga,arg,stg) do {} while (0)
#endif
#define IGACheckSetUpStage1(iga,arg) IGACheckSetUpStage(iga,arg,1)
#define IGACheckSetUpStage2(iga,arg) IGACheckSetUpStage(iga,arg,2)
#if defined(PETSC_USE_DEBUG)
#define IGACheckFormOp(iga,arg,FormOp) do { \
if (!iga->form->ops->FormOp) \
SETERRQ(((PetscObject)iga)->comm,PETSC_ERR_USER, \
"Must call IGASetForm%s() " \
"on argument %D \"%s\" before %s()", \
#FormOp,(arg),#iga,PETSC_FUNCTION_NAME); \
} while (0)
#else
#define IGACheckFormOp(iga,arg,FormOp) do {} while (0)
#endif
/* ---------------------------------------------------------------- */
PETSC_EXTERN PetscErrorCode IGAOptionsAlias(const char name[],const char defval[],const char alias[]);
PETSC_EXTERN PetscErrorCode IGAOptionsDefault(const char prefix[],const char name[],const char value[]);
PETSC_EXTERN PetscErrorCode IGAOptionsReject(const char prefix[],const char name[]);
PETSC_EXTERN PetscEnum IGAGetOptEnum(const char prefix[],const char name[],const char *const elist[],PetscEnum defval);
PETSC_EXTERN const char* IGAGetOptString(const char prefix[],const char name[],const char defval[]);
PETSC_EXTERN PetscBool IGAGetOptBool(const char prefix[],const char name[],PetscBool defval);
PETSC_EXTERN PetscInt IGAGetOptInt(const char prefix[],const char name[],PetscInt defval);
PETSC_EXTERN PetscReal IGAGetOptReal(const char prefix[],const char name[],PetscReal defval);
PETSC_EXTERN PetscScalar IGAGetOptScalar(const char prefix[],const char name[],PetscScalar defval);
/* ---------------------------------------------------------------- */
#if PETSC_VERSION_LT(3,8,0)
PETSC_EXTERN PetscErrorCode TSSetMaxSteps(TS,PetscInt);
PETSC_EXTERN PetscErrorCode TSGetMaxSteps(TS,PetscInt*);
PETSC_EXTERN PetscErrorCode TSSetMaxTime(TS,PetscReal);
PETSC_EXTERN PetscErrorCode TSGetMaxTime(TS,PetscReal*);
#endif
#define TSALPHA1 TSALPHA
PETSC_EXTERN PetscErrorCode TSAlphaUseAdapt(TS,PetscBool);
#else
/* ---------------------------------------------------------------- */
#endif/*PETIGA_H*/
| {
"alphanum_fraction": 0.6670560485,
"avg_line_length": 46.2733887734,
"ext": "h",
"hexsha": "3d6ee66ea9022cacb598d319841155dab2f390ad",
"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": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "dalcinl/PetIGA",
"max_forks_repo_path": "include/petiga.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8",
"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": "dalcinl/PetIGA",
"max_issues_repo_path": "include/petiga.h",
"max_line_length": 129,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "a1ffe3be8710dbc0ee43e7b9adff99d4059784d8",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "dalcinl/PetIGA",
"max_stars_repo_path": "include/petiga.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-20T19:56:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-05-19T17:19:43.000Z",
"num_tokens": 11945,
"size": 44515
} |
/* vector/gsl_vector_int.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_VECTOR_INT_H__
#define __GSL_VECTOR_INT_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_int.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
int *data;
gsl_block_int *block;
int owner;
}
gsl_vector_int;
typedef struct
{
gsl_vector_int vector;
} _gsl_vector_int_view;
typedef _gsl_vector_int_view gsl_vector_int_view;
typedef struct
{
gsl_vector_int vector;
} _gsl_vector_int_const_view;
typedef const _gsl_vector_int_const_view gsl_vector_int_const_view;
/* Allocation */
GSL_FUN gsl_vector_int *gsl_vector_int_alloc (const size_t n);
GSL_FUN gsl_vector_int *gsl_vector_int_calloc (const size_t n);
GSL_FUN gsl_vector_int *gsl_vector_int_alloc_from_block (gsl_block_int * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN gsl_vector_int *gsl_vector_int_alloc_from_vector (gsl_vector_int * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_FUN void gsl_vector_int_free (gsl_vector_int * v);
/* Views */
GSL_FUN _gsl_vector_int_view
gsl_vector_int_view_array (int *v, size_t n);
GSL_FUN _gsl_vector_int_view
gsl_vector_int_view_array_with_stride (int *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_int_const_view
gsl_vector_int_const_view_array (const int *v, size_t n);
GSL_FUN _gsl_vector_int_const_view
gsl_vector_int_const_view_array_with_stride (const int *base,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_int_view
gsl_vector_int_subvector (gsl_vector_int *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_int_view
gsl_vector_int_subvector_with_stride (gsl_vector_int *v,
size_t i,
size_t stride,
size_t n);
GSL_FUN _gsl_vector_int_const_view
gsl_vector_int_const_subvector (const gsl_vector_int *v,
size_t i,
size_t n);
GSL_FUN _gsl_vector_int_const_view
gsl_vector_int_const_subvector_with_stride (const gsl_vector_int *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
GSL_FUN void gsl_vector_int_set_zero (gsl_vector_int * v);
GSL_FUN void gsl_vector_int_set_all (gsl_vector_int * v, int x);
GSL_FUN int gsl_vector_int_set_basis (gsl_vector_int * v, size_t i);
GSL_FUN int gsl_vector_int_fread (FILE * stream, gsl_vector_int * v);
GSL_FUN int gsl_vector_int_fwrite (FILE * stream, const gsl_vector_int * v);
GSL_FUN int gsl_vector_int_fscanf (FILE * stream, gsl_vector_int * v);
GSL_FUN int gsl_vector_int_fprintf (FILE * stream, const gsl_vector_int * v,
const char *format);
GSL_FUN int gsl_vector_int_memcpy (gsl_vector_int * dest, const gsl_vector_int * src);
GSL_FUN int gsl_vector_int_reverse (gsl_vector_int * v);
GSL_FUN int gsl_vector_int_swap (gsl_vector_int * v, gsl_vector_int * w);
GSL_FUN int gsl_vector_int_swap_elements (gsl_vector_int * v, const size_t i, const size_t j);
GSL_FUN int gsl_vector_int_max (const gsl_vector_int * v);
GSL_FUN int gsl_vector_int_min (const gsl_vector_int * v);
GSL_FUN void gsl_vector_int_minmax (const gsl_vector_int * v, int * min_out, int * max_out);
GSL_FUN size_t gsl_vector_int_max_index (const gsl_vector_int * v);
GSL_FUN size_t gsl_vector_int_min_index (const gsl_vector_int * v);
GSL_FUN void gsl_vector_int_minmax_index (const gsl_vector_int * v, size_t * imin, size_t * imax);
GSL_FUN int gsl_vector_int_add (gsl_vector_int * a, const gsl_vector_int * b);
GSL_FUN int gsl_vector_int_sub (gsl_vector_int * a, const gsl_vector_int * b);
GSL_FUN int gsl_vector_int_mul (gsl_vector_int * a, const gsl_vector_int * b);
GSL_FUN int gsl_vector_int_div (gsl_vector_int * a, const gsl_vector_int * b);
GSL_FUN int gsl_vector_int_scale (gsl_vector_int * a, const int x);
GSL_FUN int gsl_vector_int_add_constant (gsl_vector_int * a, const double x);
GSL_FUN int gsl_vector_int_axpby (const int alpha, const gsl_vector_int * x, const int beta, gsl_vector_int * y);
GSL_FUN int gsl_vector_int_sum (const gsl_vector_int * a);
GSL_FUN int gsl_vector_int_equal (const gsl_vector_int * u,
const gsl_vector_int * v);
GSL_FUN int gsl_vector_int_isnull (const gsl_vector_int * v);
GSL_FUN int gsl_vector_int_ispos (const gsl_vector_int * v);
GSL_FUN int gsl_vector_int_isneg (const gsl_vector_int * v);
GSL_FUN int gsl_vector_int_isnonneg (const gsl_vector_int * v);
GSL_FUN INLINE_DECL int gsl_vector_int_get (const gsl_vector_int * v, const size_t i);
GSL_FUN INLINE_DECL void gsl_vector_int_set (gsl_vector_int * v, const size_t i, int x);
GSL_FUN INLINE_DECL int * gsl_vector_int_ptr (gsl_vector_int * v, const size_t i);
GSL_FUN INLINE_DECL const int * gsl_vector_int_const_ptr (const gsl_vector_int * v, const size_t i);
#ifdef HAVE_INLINE
INLINE_FUN
int
gsl_vector_int_get (const gsl_vector_int * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
INLINE_FUN
void
gsl_vector_int_set (gsl_vector_int * v, const size_t i, int x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
INLINE_FUN
int *
gsl_vector_int_ptr (gsl_vector_int * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (int *) (v->data + i * v->stride);
}
INLINE_FUN
const int *
gsl_vector_int_const_ptr (const gsl_vector_int * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(i >= v->size))
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const int *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_INT_H__ */
| {
"alphanum_fraction": 0.658622791,
"avg_line_length": 33.7654320988,
"ext": "h",
"hexsha": "c8bbcd3fbae68e1854a804ae793b14517dcdcd92",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/VimbaCamJILA",
"max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_int.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a",
"max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/VimbaCamJILA",
"max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_vector_int.h",
"max_line_length": 114,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "mgreter/astrometrylib",
"max_stars_repo_path": "vendor/gsl/gsl/gsl_vector_int.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z",
"num_tokens": 2004,
"size": 8205
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <complex.h>
#include <math.h>
#include <fftw3.h>
#include <gsl/gsl_sf_legendre.h>
#include "fsht.h"
#include "util.h"
int fshtinit (shdata *dat, int deg, int ntheta, int nphi, int measfft) {
int ierr;
complex double *fftbuf;
/* This is actually one more than the maximum degree. */
dat->deg = deg;
/* The number of theta samples must at least equal the SH degree. */
if (ntheta < deg) dat->ntheta = deg;
else dat->ntheta = ntheta;
/* At least this many phi values are required for fast FFT evaluation. */
if (2 * deg - 1 > nphi) dat->nphi = 2 * deg - 1;
else dat->nphi = nphi;
/* Allocate the theta points and weights. */
dat->theta = calloc (2 * dat->ntheta, sizeof(double));
dat->weights = dat->theta + dat->ntheta;
/* Find the Legendre-Gauss quadrature points. */
gauleg (dat->ntheta, dat->theta, dat->weights);
/* Temporarily allocate an FFT data buffer for planning. */
fftbuf = fftw_malloc (dat->ntheta * dat->nphi * sizeof(complex double));
/* Plan the forward and inverse transforms. */
dat->fplan = fftw_plan_many_dft (1, &(dat->nphi), dat->ntheta, fftbuf,
&(dat->nphi), 1, dat->nphi, fftbuf, &(dat->nphi), 1,
dat->nphi, FFTW_FORWARD, measfft ? FFTW_MEASURE : FFTW_ESTIMATE);
dat->bplan = fftw_plan_many_dft (1, &(dat->nphi), dat->ntheta, fftbuf,
&(dat->nphi), 1, dat->nphi, fftbuf, &(dat->nphi), 1,
dat->nphi, FFTW_BACKWARD, measfft ? FFTW_MEASURE : FFTW_ESTIMATE);
/* The FFT buffer is no longer necessary, and will be reallocated
* on-the-fly when it is needed later. */
fftw_free (fftbuf);
return 0;
}
int fshtfree (shdata *dat) {
if (dat->theta) free (dat->theta);
fftw_destroy_plan (dat->fplan);
fftw_destroy_plan (dat->bplan);
dat->ntheta = dat->nphi = dat->deg = 0;
return 0;
}
/* Scale the components of the spherical harmonic coefficients to relate the
* far-field signature to the spherical harmonic expansion. The default (for
* non-negative sgn) properly scales SH coefficients AFTER a forward
* transform (angular to spherical). If sgn is negative, it scales the SH
* coefficients BEFORE an inverse transform (spherical to angular). */
int shscale (complex double *samp, shdata *dat, int sgn) {
complex double cscale[4] = { I, -1.0, -I, 1.0 };
int i, j, off, idx;
/* For negative sgn, flip the signs of the imaginary multipliers. */
if (sgn < 0) {
cscale[0] = -I;
cscale[2] = I;
}
for (i = 0; i < dat->deg; ++i) {
idx = i % 4;
off = i * dat->nphi;
/* Scale the zero order for all degrees. */
samp[off] *= cscale[idx];
/* Scale the nonzero orders for all degrees. */
for (j = 1; j <= i; ++j) {
samp[off + j] *= cscale[idx];
samp[off + dat->nphi - j] *= cscale[idx];
}
}
return 0;
}
/* Forward spherical harmonic transform: take samples of the function in theta
* and phi into SH coefficients. */
int ffsht (complex double *samp, shdata *dat, int maxdeg) {
int i, j, k, aoff, npk, dm1, deg = maxdeg;
long lgn, lgi;
double pc, scale, *lgvals;
complex double *beta, *fftbuf;
/* Copy the samples to the FFT buffer and perform the FFT. */
fftbuf = fftw_malloc (dat->ntheta * dat->nphi * sizeof(complex double));
memcpy (fftbuf, samp, dat->ntheta * dat->nphi * sizeof(complex double));
/* Perform an in-place FFT of the buffer. */
fftw_execute_dft (dat->fplan, fftbuf, fftbuf);
/* Zero out the input samples, to prepare for storage of coefficients. */
memset (samp, 0, dat->ntheta * dat->nphi * sizeof(complex double));
beta = fftbuf;
/* If no maximum degree is specified, use the default. */
if (maxdeg < 1) deg = dat->deg;
dm1 = deg - 1;
/* Create storage for all Legendre polynomials. */
lgn = gsl_sf_legendre_array_n (dm1);
lgvals = malloc (lgn * sizeof(double));
for (i = 0; i < dat->ntheta; ++i) {
/* The scale factor that will be required. */
scale = 2 * M_PI * dat->weights[i] / dat->nphi;
/* Build the Legendre polynomials that we need.
* Don't use Condon-Shortley phase factor. */
gsl_sf_legendre_array_e (GSL_SF_LEGENDRE_SPHARM, dm1, dat->theta[i], 1., lgvals);
/* Handle m = 0 for all degrees. */
for (j = 0; j < deg; ++j) {
lgi = gsl_sf_legendre_array_index(j, 0);
samp[j * dat->nphi] += scale * beta[0] * lgvals[lgi];
}
/* Handle nonzero orders for all relevant degrees. */
for (k = 1; k < deg; ++k) {
npk = dat->nphi - k;
for (j = k; j < deg; ++j) {
aoff = j * dat->nphi;
lgi = gsl_sf_legendre_array_index(j, k);
pc = scale * lgvals[lgi];
/* The positive-order coefficient. */
samp[aoff + k] += pc * beta[k];
/* The negative-order coefficient. */
samp[aoff + npk] += pc * beta[npk];
}
}
beta += dat->nphi;
}
/* The FFT buffer is no longer required. */
fftw_free (fftbuf);
return deg;
}
/* Inverse spherical harmonic transform: take SH coefficients to sample of the
* function in theta and phi. */
int ifsht (complex double *samp, shdata *dat, int maxdeg) {
int i, j, k, aoff, npk, dm1, n, deg = maxdeg;
long lgn, lgi;
double *lgvals;
complex double *beta, *fftbuf;
/* The non-polar samples. */
n = dat->ntheta * dat->nphi;
/* Zero out the FFT buffer to prepare for evaluation of function. */
fftbuf = fftw_malloc (n * sizeof(complex double));
memset (fftbuf, 0, n * sizeof(complex double));
beta = fftbuf;
/* Use the default degree if no maximum is specified. */
if (maxdeg < 1) deg = dat->deg;
dm1 = deg - 1;
/* Create storage for all Legendre polynomials. */
lgn = gsl_sf_legendre_array_n(dm1);
lgvals = malloc (lgn * sizeof(double));
for (i = 0; i < dat->ntheta; ++i) {
/* Build the Legendre polynomials that we need. */
/* Don't use the Condon-Shortley phase factor. */
gsl_sf_legendre_array_e (GSL_SF_LEGENDRE_SPHARM, dm1, dat->theta[i], 1., lgvals);
for (j = 0; j < deg; ++j) {
lgi = gsl_sf_legendre_array_index(j, 0);
beta[0] += samp[j * dat->nphi] * lgvals[lgi];
}
for (k = 1; k < deg; ++k) {
npk = dat->nphi - k;
for (j = k; j < deg; ++j) {
aoff = j * dat->nphi;
lgi = gsl_sf_legendre_array_index(j, k);
/* The positive-order coefficient. */
beta[k] += samp[aoff + k] * lgvals[lgi];
/* The negative-order coefficient. */
beta[npk] += samp[aoff + npk] * lgvals[lgi];
}
}
/* Move the next theta value in the FFT array. */
beta += dat->nphi;
}
/* Perform the inverse FFT and copy the values to the storage area. */
fftw_execute_dft (dat->bplan, fftbuf, fftbuf);
memcpy (samp, fftbuf, n * sizeof(complex double));
/* Eliminate the FFT buffer. */
fftw_free (fftbuf);
free (lgvals);
return deg;
}
| {
"alphanum_fraction": 0.64386257,
"avg_line_length": 28.9780701754,
"ext": "c",
"hexsha": "a2a365e0bd487259f5bab595415d44316abae591",
"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": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "ahesford/fastsphere",
"max_forks_repo_path": "fsht.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2",
"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": "ahesford/fastsphere",
"max_issues_repo_path": "fsht.c",
"max_line_length": 83,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "18d8bd2d73aaabeafe4ead48955c8d8190eddbf2",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "ahesford/fastsphere",
"max_stars_repo_path": "fsht.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2134,
"size": 6607
} |
/* ode-initval/rk2simp.c
*
* Copyright (C) 2004 Tuomo Keskitalo
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Runge-Kutta 2, Gaussian implicit. Also known as implicit midpoint rule.
Non-linear equations solved by linearization, LU-decomposition
and matrix inversion. For reference, see eg.
Ascher, U.M., Petzold, L.R., Computer methods for ordinary
differential and differential-algebraic equations, SIAM,
Philadelphia, 1998.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv.h>
#include <gsl/gsl_linalg.h>
#include "odeiv_util.h"
typedef struct
{
double *Y1;
double *y0;
double *y0_orig;
double *ytmp;
double *dfdy; /* Jacobian */
double *dfdt; /* time derivatives, not used */
double *y_onestep;
gsl_permutation *p;
}
rk2simp_state_t;
static void *
rk2simp_alloc (size_t dim)
{
rk2simp_state_t *state =
(rk2simp_state_t *) malloc (sizeof (rk2simp_state_t));
if (state == 0)
{
GSL_ERROR_NULL ("failed to allocate space for rk2simp_state",
GSL_ENOMEM);
}
state->Y1 = (double *) malloc (dim * sizeof (double));
if (state->Y1 == 0)
{
free (state);
GSL_ERROR_NULL ("failed to allocate space for Y1", GSL_ENOMEM);
}
state->y0 = (double *) malloc (dim * sizeof (double));
if (state->y0 == 0)
{
free (state->Y1);
free (state);
GSL_ERROR_NULL ("failed to allocate space for y0", GSL_ENOMEM);
}
state->y0_orig = (double *) malloc (dim * sizeof (double));
if (state->y0_orig == 0)
{
free (state->Y1);
free (state->y0);
free (state);
GSL_ERROR_NULL ("failed to allocate space for y0_orig", GSL_ENOMEM);
}
state->ytmp = (double *) malloc (dim * sizeof (double));
if (state->ytmp == 0)
{
free (state->Y1);
free (state->y0);
free (state->y0_orig);
free (state);
GSL_ERROR_NULL ("failed to allocate space for ytmp", GSL_ENOMEM);
}
state->dfdy = (double *) malloc (dim * dim * sizeof (double));
if (state->dfdy == 0)
{
free (state->Y1);
free (state->y0);
free (state->y0_orig);
free (state->ytmp);
free (state);
GSL_ERROR_NULL ("failed to allocate space for dfdy", GSL_ENOMEM);
}
state->dfdt = (double *) malloc (dim * sizeof (double));
if (state->dfdt == 0)
{
free (state->Y1);
free (state->y0);
free (state->y0_orig);
free (state->ytmp);
free (state->dfdy);
free (state);
GSL_ERROR_NULL ("failed to allocate space for dfdt", GSL_ENOMEM);
}
state->y_onestep = (double *) malloc (dim * sizeof (double));
if (state->y_onestep == 0)
{
free (state->Y1);
free (state->y0);
free (state->y0_orig);
free (state->ytmp);
free (state->dfdy);
free (state->dfdt);
free (state);
GSL_ERROR_NULL ("failed to allocate space for y_onestep", GSL_ENOMEM);
}
state->p = gsl_permutation_alloc (dim);
if (state->p == 0)
{
free (state->Y1);
free (state->y0);
free (state->y0_orig);
free (state->ytmp);
free (state->dfdy);
free (state->dfdt);
free (state->y_onestep);
free (state);
GSL_ERROR_NULL ("failed to allocate space for p", GSL_ENOMEM);
}
return state;
}
static int
rk2simp_step (double *y, rk2simp_state_t * state,
const double h, const double t,
const size_t dim, const gsl_odeiv_system * sys)
{
/* Makes a Runge-Kutta 2nd order semi-implicit advance with step size h.
y0 is initial values of variables y.
The linearized semi-implicit equations to calculate are:
Y1 = y0 + h/2 * (1 - h/2 * df/dy)^(-1) * f(t + h/2, y0)
y = y0 + h * f(t + h/2, Y1)
*/
const double *y0 = state->y0;
double *Y1 = state->Y1;
double *ytmp = state->ytmp;
size_t i;
int s, ps;
gsl_matrix_view J = gsl_matrix_view_array (state->dfdy, dim, dim);
/* First solve Y1.
Calculate the inverse matrix (1 - h/2 * df/dy)^-1
*/
/* Create matrix to J */
s = GSL_ODEIV_JA_EVAL (sys, t, y0, state->dfdy, state->dfdt);
if (s != GSL_SUCCESS)
{
return s;
}
gsl_matrix_scale (&J.matrix, -h / 2.0);
gsl_matrix_add_diagonal(&J.matrix, 1.0);
/* Invert it by LU-decomposition to invmat */
s += gsl_linalg_LU_decomp (&J.matrix, state->p, &ps);
if (s != GSL_SUCCESS)
{
return GSL_EFAILED;
}
/* Evaluate f(t + h/2, y0) */
s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, y0, ytmp);
if (s != GSL_SUCCESS)
{
return s;
}
/* Calculate Y1 = y0 + h/2 * ((1-h/2 * df/dy)^-1) ytmp */
{
gsl_vector_const_view y0_view = gsl_vector_const_view_array(y0, dim);
gsl_vector_view ytmp_view = gsl_vector_view_array(ytmp, dim);
gsl_vector_view Y1_view = gsl_vector_view_array(Y1, dim);
s = gsl_linalg_LU_solve (&J.matrix, state->p,
&ytmp_view.vector, &Y1_view.vector);
gsl_vector_scale (&Y1_view.vector, 0.5 * h);
gsl_vector_add (&Y1_view.vector, &y0_view.vector);
}
/* And finally evaluation of f(t + h/2, Y1) and calculation of y */
s = GSL_ODEIV_FN_EVAL (sys, t + 0.5 * h, Y1, ytmp);
if (s != GSL_SUCCESS)
{
return s;
}
for (i = 0; i < dim; i++)
{
y[i] = y0[i] + h * ytmp[i];
}
return s;
}
static int
rk2simp_apply (void *vstate, size_t dim, double t, double h,
double y[], double yerr[], const double dydt_in[],
double dydt_out[], const gsl_odeiv_system * sys)
{
rk2simp_state_t *state = (rk2simp_state_t *) vstate;
size_t i;
double *y0 = state->y0;
double *y0_orig = state->y0_orig;
double *y_onestep = state->y_onestep;
/* Error estimation is done by step doubling procedure */
DBL_MEMCPY (y0, y, dim);
/* Save initial values in case of failure */
DBL_MEMCPY (y0_orig, y, dim);
/* First traverse h with one step (save to y_onestep) */
DBL_MEMCPY (y_onestep, y, dim);
{
int s = rk2simp_step (y_onestep, state, h, t, dim, sys);
if (s != GSL_SUCCESS)
{
return s;
}
}
/* Then with two steps with half step length (save to y) */
{
int s = rk2simp_step (y, state, h / 2.0, t, dim, sys);
if (s != GSL_SUCCESS)
{
/* Restore original y vector */
DBL_MEMCPY (y, y0_orig, dim);
return s;
}
}
DBL_MEMCPY (y0, y, dim);
{
int s = rk2simp_step (y, state, h / 2.0, t + h / 2.0, dim, sys);
if (s != GSL_SUCCESS)
{
/* Restore original y vector */
DBL_MEMCPY (y, y0_orig, dim);
return s;
}
}
/* Derivatives at output */
if (dydt_out != NULL)
{
int s = GSL_ODEIV_FN_EVAL (sys, t + h, y, dydt_out);
if (s != GSL_SUCCESS)
{
/* Restore original y vector */
DBL_MEMCPY (y, y0_orig, dim);
return s;
}
}
/* Error estimation */
for (i = 0; i < dim; i++)
{
yerr[i] = 4.0 * (y[i] - y_onestep[i]) / 3.0;
}
return GSL_SUCCESS;
}
static int
rk2simp_reset (void *vstate, size_t dim)
{
rk2simp_state_t *state = (rk2simp_state_t *) vstate;
DBL_ZERO_MEMSET (state->Y1, dim);
DBL_ZERO_MEMSET (state->y0, dim);
DBL_ZERO_MEMSET (state->y0_orig, dim);
DBL_ZERO_MEMSET (state->ytmp, dim);
DBL_ZERO_MEMSET (state->dfdt, dim * dim);
DBL_ZERO_MEMSET (state->dfdt, dim);
DBL_ZERO_MEMSET (state->y_onestep, dim);
return GSL_SUCCESS;
}
static unsigned int
rk2simp_order (void *vstate)
{
rk2simp_state_t *state = (rk2simp_state_t *) vstate;
state = 0; /* prevent warnings about unused parameters */
return 2;
}
static void
rk2simp_free (void *vstate)
{
rk2simp_state_t *state = (rk2simp_state_t *) vstate;
free (state->Y1);
free (state->y0);
free (state->y0_orig);
free (state->ytmp);
free (state->dfdy);
free (state->dfdt);
free (state->y_onestep);
gsl_permutation_free (state->p);
free (state);
}
static const gsl_odeiv_step_type rk2simp_type = {
"rk2simp", /* name */
0, /* can use dydt_in? */
1, /* gives exact dydt_out? */
&rk2simp_alloc,
&rk2simp_apply,
&rk2simp_reset,
&rk2simp_order,
&rk2simp_free
};
const gsl_odeiv_step_type *gsl_odeiv_step_rk2simp = &rk2simp_type;
| {
"alphanum_fraction": 0.600810426,
"avg_line_length": 23.7786458333,
"ext": "c",
"hexsha": "6d979e02bc164903c8b6af937b4b2f71d2062dc4",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ode-initval/rk2simp.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/ode-initval/rk2simp.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/ode-initval/rk2simp.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": 2814,
"size": 9131
} |
#pragma once
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include <DirectXMath.h>
#include <gsl\gsl>
#include "DrawableGameComponent.h"
#include "MatrixHelper.h"
#include "VectorHelper.h"
#include "BasicMaterial.h"
namespace Library
{
class Mesh;
class ProxyModel final : public DrawableGameComponent
{
RTTI_DECLARATIONS(ProxyModel, DrawableGameComponent)
public:
ProxyModel(Game& game, const std::shared_ptr<Camera>& camera, const std::string& modelFileName, float scale = 1.0f);
ProxyModel(const ProxyModel&) = delete;
ProxyModel(ProxyModel&&) = default;
ProxyModel& operator=(const ProxyModel&) = delete;
ProxyModel& operator=(ProxyModel&&) = default;
~ProxyModel() = default;
const DirectX::XMFLOAT3& Position() const;
const DirectX::XMFLOAT3& Direction() const;
const DirectX::XMFLOAT3& Up() const;
const DirectX::XMFLOAT3& Right() const;
DirectX::XMVECTOR PositionVector() const;
DirectX::XMVECTOR DirectionVector() const;
DirectX::XMVECTOR UpVector() const;
DirectX::XMVECTOR RightVector() const;
bool& DisplayWireframe();
void SetPosition(float x, float y, float z);
void SetPosition(DirectX::FXMVECTOR position);
void SetPosition(const DirectX::XMFLOAT3& position);
void ApplyRotation(DirectX::CXMMATRIX transform);
void ApplyRotation(const DirectX::XMFLOAT4X4& transform);
void SetColor(const DirectX::XMFLOAT4& color);
virtual void Initialize() override;
virtual void Update(const GameTime& gameTime) override;
virtual void Draw(const GameTime& gameTime) override;
private:
DirectX::XMFLOAT4X4 mWorldMatrix{ MatrixHelper::Identity };
DirectX::XMFLOAT3 mPosition{ Vector3Helper::Zero };
DirectX::XMFLOAT3 mDirection{ Vector3Helper::Forward };
DirectX::XMFLOAT3 mUp{ Vector3Helper::Up };
DirectX::XMFLOAT3 mRight{ Vector3Helper::Right };
BasicMaterial mMaterial;
std::string mModelFileName;
float mScale;
winrt::com_ptr<ID3D11Buffer> mVertexBuffer;
winrt::com_ptr<ID3D11Buffer> mIndexBuffer;
std::uint32_t mIndexCount{ 0 };
bool mDisplayWireframe{ true };
bool mUpdateWorldMatrix{ true };
bool mUpdateMaterial{ true };
};
} | {
"alphanum_fraction": 0.7503493246,
"avg_line_length": 31.115942029,
"ext": "h",
"hexsha": "d55d8305fcba7d0a0b999a049ec2122615f920eb",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_forks_repo_path": "source/Library.Shared/ProxyModel.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_issues_repo_path": "source/Library.Shared/ProxyModel.h",
"max_line_length": 118,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "05a05c5c26784dafa9a89747276f385252951f2f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ssshammi/real-time-3d-rendering-with-directx-and-hlsl",
"max_stars_repo_path": "source/Library.Shared/ProxyModel.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 589,
"size": 2147
} |
/*
* Copyright 2014 Marc Normandin
*
* 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.
*/
/*
* rng.h
*
* Created on: Jul 3, 2013
* Author: marc
*/
#ifndef RNG_H_
#define RNG_H_
#include <climits> // ULONG_MAX
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <iostream>
// Seeds for GNU GSL random number generators
typedef unsigned long int gslseed_t;
class RandomNumberGenerator
{
public:
/*
RandomNumberGenerator()
: mRngType( gsl_rng_default ), mSeed( time(0) ) {
initializeRNG();
}*/
RandomNumberGenerator(const gslseed_t& seed)
: mRngType( gsl_rng_default ), mSeed( seed )
{
initializeRNG();
}
RandomNumberGenerator(const RandomNumberGenerator& rhs)
{
mRngType = rhs.mRngType;
mRng = gsl_rng_clone( rhs.mRng );
mSeed = rhs.randomSeed();
gsl_rng_set (mRng, mSeed);
}
~RandomNumberGenerator()
{
gsl_rng_free( mRng );
}
// Random uniform number between 0 and 1.
double uniform() const
{
return gsl_rng_uniform( mRng );
}
// Random uniform number between min and max
double uniform(const double min, const double max) const
{
const double u = uniform();
return ( min + u * (max - min) );
}
double gaussian(const double sigma) const
{
return ( gsl_ran_gaussian (mRng, sigma) );
}
// Beta distribution. Random x between 0 and 1.
double beta(const double alpha, const double beta) const
{
return ( gsl_ran_beta(mRng, alpha, beta) );
}
gslseed_t randomSeed() const
{
// I wrote the following after looking into the GSL code itself.
const unsigned long int offset = mRng->type->min;
const unsigned long int range = mRng->type->max - offset;
gslseed_t rseed = 1 + gsl_rng_uniform_int(mRng, range-2);
//std::cerr << "generated random seed = " << rseed << std::endl;
return rseed;
}
protected:
void initializeRNG()
{
mRng = gsl_rng_alloc (mRngType);
gsl_rng_set (mRng, mSeed);
}
private:
// Prevent copying and assignment
//RandomNumberGenerator(const RandomNumberGenerator&);
void operator=(const RandomNumberGenerator&);
const gsl_rng_type* mRngType;
gslseed_t mSeed;
gsl_rng* mRng;
};
#endif /* RNG_H_ */
| {
"alphanum_fraction": 0.6400275577,
"avg_line_length": 25.025862069,
"ext": "h",
"hexsha": "e667f20c0a1836ff194644368798c7a42ddbe81b",
"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": "6690fde0de155acd44ba5a3eab4224276f120ed5",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "marcnormandin/ParticleSwarmOptimization",
"max_forks_repo_path": "rng.h",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5",
"max_issues_repo_issues_event_max_datetime": "2015-06-11T20:48:15.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-27T05:48:44.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "marcnormandin/ParticleSwarmOptimization",
"max_issues_repo_path": "rng.h",
"max_line_length": 79,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "6690fde0de155acd44ba5a3eab4224276f120ed5",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "marcnormandin/ParticleSwarmOptimization",
"max_stars_repo_path": "rng.h",
"max_stars_repo_stars_event_max_datetime": "2018-04-09T21:25:19.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-28T05:27:28.000Z",
"num_tokens": 741,
"size": 2903
} |
/* movstat/funcacc.c
*
* Moving window accumulator for arbitrary user-defined function
*
* Copyright (C) 2018 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_movstat.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_statistics.h>
typedef double funcacc_type_t;
typedef funcacc_type_t ringbuf_type_t;
#include "ringbuf.c"
typedef struct
{
funcacc_type_t *window; /* linear array for current window */
ringbuf *rbuf; /* ring buffer storing current window */
} funcacc_state_t;
static size_t
funcacc_size(const size_t n)
{
size_t size = 0;
size += sizeof(funcacc_state_t);
size += n * sizeof(funcacc_type_t);
size += ringbuf_size(n);
return size;
}
static int
funcacc_init(const size_t n, void * vstate)
{
funcacc_state_t * state = (funcacc_state_t *) vstate;
state->window = (funcacc_type_t *) ((unsigned char *) vstate + sizeof(funcacc_state_t));
state->rbuf = (ringbuf *) ((unsigned char *) state->window + n * sizeof(funcacc_type_t));
ringbuf_init(n, state->rbuf);
return GSL_SUCCESS;
}
static int
funcacc_insert(const funcacc_type_t x, void * vstate)
{
funcacc_state_t * state = (funcacc_state_t *) vstate;
/* add new element to ring buffer */
ringbuf_insert(x, state->rbuf);
return GSL_SUCCESS;
}
static int
funcacc_delete(void * vstate)
{
funcacc_state_t * state = (funcacc_state_t *) vstate;
if (!ringbuf_is_empty(state->rbuf))
ringbuf_pop_back(state->rbuf);
return GSL_SUCCESS;
}
static int
funcacc_get(void * params, funcacc_type_t * result, const void * vstate)
{
const funcacc_state_t * state = (const funcacc_state_t *) vstate;
gsl_movstat_function *f = (gsl_movstat_function *) params;
size_t n = ringbuf_copy(state->window, state->rbuf);
*result = GSL_MOVSTAT_FN_EVAL(f, n, state->window);
return GSL_SUCCESS;
}
static const gsl_movstat_accum func_accum_type =
{
funcacc_size,
funcacc_init,
funcacc_insert,
funcacc_delete,
funcacc_get
};
const gsl_movstat_accum *gsl_movstat_accum_userfunc = &func_accum_type;
| {
"alphanum_fraction": 0.7318021201,
"avg_line_length": 25.7272727273,
"ext": "c",
"hexsha": "b880652de5ee91368dc044a8d5348e52897f16aa",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/movstat/funcacc.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/movstat/funcacc.c",
"max_line_length": 91,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/movstat/funcacc.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": 753,
"size": 2830
} |
#ifndef BIO_RUN_MATCH_H_
#define BIO_RUN_MATCH_H_
#include "bio/defs.h"
#include "bio/common.h"
#include "bio/match_hit.h"
#include "bio/sequence.h"
#include "bio/biobase_filter.h"
#include "bio/pssm_match.h"
#include "bio/phylogenetics.h"
#include "bio/biobase_db.h"
#include "bio/biobase_data_traits.h"
#include <boost/filesystem/path.hpp>
#include <vector>
#include <set>
#include <gsl/gsl_sf_log.h>
#include <gsl/gsl_sf_exp.h>
namespace boost { namespace program_options {
//forward decl
class options_description;
} }
BIO_NS_START
enum ScoreAlgorithm
{
OTT_SCORE_ALGORITHM,
BAYESIAN_SCORE_ALGORITHM
};
struct MatchParams
{
MatchParams(
float_t t,
ScoreAlgorithm alg = OTT_SCORE_ALGORITHM,
bool or_better = false)
: threshold( t )
, score_algorithm( alg )
, or_better( or_better )
{
}
float_t threshold;
ScoreAlgorithm score_algorithm;
bool or_better;
};
struct MatchResults
{
MatchResults();
MatchResults(
TableLink link,
Hit result);
TableLink link;
Hit result;
size_t number;
bool operator<(const MatchResults & rhs) const
{
if (result == rhs.result)
{
if (link == rhs.link)
{
return number < rhs.number;
}
else
{
return link < rhs.link;
}
}
else
{
return result < rhs.result;
}
}
protected:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & link;
ar & result;
ar & number;
}
};
typedef std::vector<MatchResults> match_result_vec_t;
typedef boost::shared_ptr< match_result_vec_t > match_result_vec_ptr_t;
void sort_by_position(match_result_vec_t & matches);
std::ostream & operator<<(std::ostream & os, const MatchResults & match);
/** Compare based initially on position, then link. */
struct MatchResultsPositionLessThan
{
bool
operator()(const MatchResults & h1, const MatchResults & h2) const
{
return
h1.result.position < h2.result.position
||
(
h1.result.position == h2.result.position
&&
h1.link < h2.link
);
}
};
inline
std::ostream &
operator<<(std::ostream & os, const MatchResults & details) {
os
<< details.link << ","
<< details.result;
return os;
}
/**
Score all the pssm on the sequence between match_seq_begin and match_seq_end and put the results in result_insert_it.
Returns an estimate that the pssm binds the sequence.
*/
template <class Pssm, class ResultInsIt>
float_t
score_pssm(
const Pssm & pssm,
seq_t::const_iterator match_seq_begin,
seq_t::const_iterator match_seq_end,
const MatchParams & params,
ResultInsIt & result_insert_it)
{
Scorers scorers(match_seq_begin, match_seq_end);
//const hit_vec_t & hit_results = scorers.bayesian_scores.get_result(pssm);
const hit_vec_t & hit_results =
OTT_SCORE_ALGORITHM == params.score_algorithm
? scorers.ott_normalised_scores.get_result(pssm)
: ( params.or_better
? scorers.bayesian_scores.get_result(pssm)
: scorers.bayesian_or_better_scores.get_result(pssm));
float_t p_does_not_bind = 1.0;
for (hit_vec_t::const_iterator i = hit_results.begin();
hit_results.end() != i;
++i)
{
if (i->score > params.threshold)
{
p_does_not_bind *= ( float_t( 1.0 ) - i->score );
MatchResults result(pssm.get_link(), *i);
assert(result.result.position < (int) (match_seq_end - match_seq_begin)); //make sure the position is not too high
*result_insert_it++ = result;
}
}
return float_t( 1.0 ) - p_does_not_bind;
}
/** Score all the pssms between begin and end and put the results in result_insert_it. */
template <class PssmIt, class ResultInsIt>
size_t
score_pssms(
PssmIt pssm_begin,
PssmIt pssm_end,
seq_t::const_iterator match_seq_begin,
seq_t::const_iterator match_seq_end,
const MatchParams & params,
ResultInsIt & result_insert_it)
{
size_t num_pssms_matched = 0;
for ( ; pssm_begin != pssm_end; ++pssm_begin)
{
try
{
score_pssm(
*(pssm_begin->second.get()),
match_seq_begin,
match_seq_end,
params,
result_insert_it);
++num_pssms_matched;
}
catch (const std::exception & ex)
{
std::cerr << "Could not score " << pssm_begin->second->get_name() << ": " << ex.what() << std::endl;
}
catch (const std::string & ex)
{
std::cerr << "Could not score " << pssm_begin->second->get_name() << ": " << ex << std::endl;
}
catch (const char * ex)
{
std::cerr << "Could not score " << pssm_begin->second->get_name() << ": " << ex << std::endl;
}
catch (...)
{
std::cerr << "Could not score " << pssm_begin->second->get_name() << std::endl;
}
}
return num_pssms_matched;
}
template <class SeqIt, class ResultInsIt, class ConsFilter, class MatrixFilter>
void
pssm_match(
SeqIt seq_begin,
SeqIt seq_end,
float_t threshold,
ScoreAlgorithm algorithm,
bool use_or_better,
ConsFilter consensus_filter,
MatrixFilter matrix_filter,
ResultInsIt result_inserter)
{
typedef boost::filter_iterator<MatrixFilter, Matrix::map_t::const_iterator> matrix_filter_it;
typedef boost::filter_iterator<ConsFilter, Site::map_t::const_iterator> site_filter_it;
const matrix_filter_it matrices_begin(matrix_filter, BiobaseDb::singleton().get_matrices().begin(), BiobaseDb::singleton().get_matrices().end());
const matrix_filter_it matrices_end(matrix_filter, BiobaseDb::singleton().get_matrices().end(), BiobaseDb::singleton().get_matrices().end());
const site_filter_it sites_begin(consensus_filter, BiobaseDb::singleton().get_sites().begin(), BiobaseDb::singleton().get_sites().end());
const site_filter_it sites_end(consensus_filter, BiobaseDb::singleton().get_sites().end(), BiobaseDb::singleton().get_sites().end());
if (matrices_begin == matrices_end && sites_begin == sites_end)
{
throw std::logic_error( "No PSSMs match filter" );
}
MatchParams params(threshold, algorithm, use_or_better);
{
//std::cout << "Scoring matrices" << std::endl;
//const size_t num_matched =
score_pssms(
matrices_begin,
matrices_end,
seq_begin,
seq_end,
params,
result_inserter);
// ostream_iterator<MatchResults>(cout, "\n"));
//std::cout << "Scored " << num_matched << " matrices" << std::endl;
}
{
//std::cout << "Scoring sites" << std::endl;
//const size_t num_matched =
score_pssms(
sites_begin,
sites_end,
seq_begin,
seq_end,
params,
result_inserter);
// ostream_iterator<MatchResults>(cout, "\n"));
//std::cout << "Scored " << num_matched << " sites" << std::endl;
}
}
void
pssm_match(
const seq_t & match_seq,
float_t threshold,
ScoreAlgorithm algorithm,
const boost::filesystem::path & file,
const std::string & title,
bool show_labels);
template <typename HitIt>
float_t
estimate_binding_prob(
HitIt hit_begin,
HitIt hit_end)
{
float_t product = 1.0;
for (HitIt hit = hit_begin; hit_end != hit; ++hit)
{
product *= float_t( 1.0f - hit->result.score );
}
return float_t(1.0 - product);
}
template <typename Exponent>
double
power(double x, Exponent y)
{
return
0 == x
? 0
: gsl_sf_exp(y * gsl_sf_log(x));
}
/** Adjusts hits for occurence in phylogenetically conserved sequence. */
template <typename ResultIt>
void
adjust_hits(
ResultIt results_begin,
ResultIt results_end,
seq_t::const_iterator seq_begin,
seq_t::const_iterator seq_end,
float_t threshold,
ScoreAlgorithm algorithm)
{
const MatchParams params(threshold, algorithm);
//maintain a set of already adjusted PSSMs
std::set<TableLink> already_adjusted;
//for each result
for (ResultIt result = results_begin; results_end != result; ++result)
{
//check we haven't checked this PSSM before
if (already_adjusted.end() != already_adjusted.find(result->link))
{
//we have so ignore it
continue;
}
//we need to estimate likelihood that it binds in phylogenetic sequence so run PSSM over sequence.
match_result_vec_t phylo_hits;
std::insert_iterator<bio::match_result_vec_t> inserter(phylo_hits, phylo_hits.begin());
switch (result->link.table_id)
{
case MATRIX_DATA:
score_pssm(
*BiobaseDb::singleton().get_entry<MATRIX_DATA>(result->link),
seq_begin,
seq_end,
params,
inserter);
break;
case SITE_DATA:
score_pssm(
*BiobaseDb::singleton().get_entry<SITE_DATA>(result->link),
seq_begin,
seq_end,
params,
inserter);
break;
default:
throw std::logic_error( "Unknown pssm type" );
}
const float_t binding_prob = estimate_binding_prob(phylo_hits.begin(), phylo_hits.end());
//adjust all the hits for this PSSM
for (ResultIt to_adjust = result; results_end != to_adjust; ++to_adjust)
{
if (to_adjust->link == result->link)
{
//to_adjust->result.score *= power(binding_prob, 5.0 * phylo_seq.conservation * phylo_seq.conservation);
to_adjust->result.score *= binding_prob;
}
}
//add to the list of already adjusted PSSMs
already_adjusted.insert(result->link);
}
}
/** Adjusts hits for occurence in phylogenetically conserved sequence. */
template <
typename ResultIt,
typename SeqRange >
void
adjust_hits_for_phylo_sequences(
ResultIt results_begin,
ResultIt results_end,
const SeqRange & sequences,
float_t threshold,
ScoreAlgorithm algorithm)
{
unsigned num_seqs = 0;
BOOST_FOREACH( const typename boost::range_value< SeqRange >::type & seq, sequences )
{
adjust_hits(
results_begin,
results_end,
seq.begin(),
seq.end(),
threshold,
algorithm );
++num_seqs;
}
std::cout << "Adjusted hits for " << num_seqs << " sequences" << std::endl;
for( ; results_begin != results_end; ++results_begin )
{
//adjust hits - raise to 1/#seqs
results_begin->result.score =
float_t(
( 0.0 == results_begin->result.score ) ? 0.0 : exp( log( results_begin->result.score ) / ( num_seqs + 1 ) ) );
}
}
/** Adjust hits by power. */
struct RaiseHitToPower
{
double power;
RaiseHitToPower(double power);
void operator()(MatchResults & hit) const;
};
/** Is a hit above a threshold? */
struct HitAboveThreshold
{
float_t threshold;
HitAboveThreshold(float_t threshold);
bool operator()(const MatchResults & results) const;
};
BIO_NS_END
#endif //BIO_RUN_MATCH_H_
| {
"alphanum_fraction": 0.6052408412,
"avg_line_length": 26.4988764045,
"ext": "h",
"hexsha": "92eeb25f63aa994e5abbecc933c361b53b96b580",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JohnReid/biopsy",
"max_forks_repo_path": "C++/include/bio/run_match.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "JohnReid/biopsy",
"max_issues_repo_path": "C++/include/bio/run_match.h",
"max_line_length": 149,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JohnReid/biopsy",
"max_stars_repo_path": "C++/include/bio/run_match.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2819,
"size": 11792
} |
/* ============================================================ *
* lensing_3rd.h *
* Martin Kilbinger, Liping Fu 2010. *
* ============================================================ */
#ifndef __LENSING_3RD_H
#define __LENSING_3RD_H
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <fftw3.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_plain.h>
#include <gsl/gsl_monte_vegas.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf_bessel.h>
#include "cosmo.h"
#include "nofz.h"
#include "lensing.h"
#include "errorlist.h"
#include "maths_base.h"
#define tenoverseven 1.428571428571
#define fouroverseven 0.571428571429
/* Minimum scale factor where a non-linear scale can be defined. *
* See {a,b,c}scocou. */
#define A_NL_MIN 0.02
#define s2_min 0.1
#define s2_max 1.0e6
#define N_s2 50
#define epsilon0 1.0e-2
#define N_EFF_MIN -2.0
/* more ce_xyz in smith2.h */
#define lensing_3rd_base -2400
#define lensing_3rd_wrongmode -1 + lensing_3rd_base
#define lensing_3rd_rootbracket -4 + lensing_3rd_base
#define lensing_3rd_slc -5 + lensing_3rd_base
typedef enum {fgauss=0, fpoly=1, ftophat=2, fdelta=3, fxip=4, fxim=5, fall=6} filter_t;
typedef enum {PT=0, SCOCOU=1, GM12} bispmode_t;
#define sbispmode_t(i) ( \
i==PT ? "PT" : \
i==SCOCOU ? "scocou01" : \
i==GM12 ? "GM12" : \
"")
#define Nbispmode_t 3
/* Intrinsic 3rd-order alignment model */
typedef enum {ia_3rd_none, ia_3rd_S08} ia_3rd_t;
#define sia_3rd_t(i) ( \
i==ia_3rd_none ? "none" : \
i==ia_3rd_S08 ? "S08" : \
"")
#define Nia_3rd_t 2
/* Bit-coded IA terms */
typedef enum {ia_3rd_undef, ia_GGI_GII_III, ia_only_GGI, ia_only_GII, ia_only_III} ia_3rd_terms_t;
#define sia_3rd_terms_t(i) ( \
i==ia_3rd_undef ? "undef" : \
i==ia_GGI_GII_III ? "GGI_GII_III" : \
i==ia_only_GGI ? "only_GGI" : \
i==ia_only_GII ? "only_GII" : \
i==ia_only_III ? "only_III" : \
"")
#define Nia_3rd_terms_t 5
/* Source-lens clustering */
typedef enum {slc_none, slc_FK13} slc_t;
#define sslc_t(i) ( \
i==slc_none ? "none" : \
i==slc_FK13 ? "slc_FK13" : \
"")
#define Nslc_t 2
typedef enum {kkk=0, kkg=1, kgg=2, ggg=3} bispfield_t;
typedef struct {
/* Lensing, including basic cosmology and redshift distribution)(s) */
cosmo_lens *lens;
/* Intrinsic alignment parameters */
ia_3rd_t ia;
ia_3rd_terms_t ia_terms;
double A_GGI, theta_GGI, A_GII, theta_GII;
/* Source-lens clustering */
slc_t slc;
double b_slc, gamma_slc;
/* ============================================================ *
* Precomputed stuff (at the moment only one redshift-bin). *
* ============================================================ */
interTable *k_NL, *n_eff;
double scale_NL_amin;
interTable2D **B_kappa[3];
bispmode_t bispmode;
} cosmo_3rd;
typedef struct {
double r1, r2;
cosmo_3rd *self;
} cosmo3ANDdoubleANDdouble;
typedef struct {
double r1, r2;
cosmo_3rd *self;
int i, n_bin[3];
} cosmo3ANDtomo;
typedef struct {
cosmo_3rd *self;
double R[3];
filter_t wfilter;
int n_bin[3];
int m;
error **err;
} cosmo3ANDmorestuff;
typedef struct {
cosmo_3rd *self;
error **err;
double a1, a2, f1, f2, R;
} cosmo3SLC;
cosmo_3rd *init_parameters_3rd(double OMEGAM, double OMEGAV, double W0_DE, double W1_DE,
double *W_POLY_DE, int N_POLY_DE,
double H100, double OMEGAB, double OMEGANUMASS,
double NEFFNUMASS, double NORM, double NSPEC,
int Nzbin, const int *Nnz, const nofz_t *nofz, double *par_nz,
nonlinear_t NONLINEAR, transfer_t TRANSFER,
growth_t GROWTH, de_param_t DEPARAM,
norm_t normmode,
ia_t IA, ia_terms_t IA_TERMS, double A_IA,
bispmode_t BISPMODE,
ia_3rd_t IA_3RD, ia_3rd_terms_t IA_3RD_TERMS, double A_GGI, double theta_GGI,
double A_GII, double theta_GII,
slc_t slc, double b_slc, double gamma_slc,
error **err);
void consistency_parameters_3rd(const cosmo_3rd *self, error **err);
cosmo_3rd *copy_parameters_3rd_only(cosmo_3rd *source, error **err);
void updateFrom_3rd(cosmo_3rd *avant, cosmo_3rd *apres, error **err);
cosmo_3rd *set_cosmological_parameters_to_default_lens_3rd(error **err);
void read_cosmological_parameters_lens_3rd(cosmo_3rd **self, FILE *F, error **err);
void free_parameters_3rd(cosmo_3rd **self);
void dump_param_3rd(cosmo_3rd* self, FILE *F, error **err);
double dcub(double a);
double n_eff_one(cosmo *self, double k, error **err);
double n_eff(cosmo_3rd *, double, int, error **);
double Q3(double, error **err);
double temp_NL(double, double, cosmo *, error **);
double scale_NL(cosmo_3rd *, double, error **);
double ascocou(cosmo_3rd *, double, double, error **);
double bscocou(cosmo_3rd *, double, double, error **);
double cscocou(cosmo_3rd *, double, double, error **);
double int_for_B_kappa_bar0(double a, void *intpar, error **err);
double int_for_B_kappa_bar1(double a, void *intpar, error **err);
double int_for_B_kappa_bar2(double a, void *intpar, error **err);
double int_for_B_kappa_bar3(double a, void *intpar, error **err);
double F2eff(cosmo_3rd *, double a, double k1, double k2, double cosphi, error **);
double F2bar(int, double, double, error **);
double F2(int, double, double, error **);
double F2cos(int, double, error **err);
double Q_123(cosmo_3rd *, double, double, double, double, error **);
double bb(cosmo_3rd *, double, double, double, int i_bin, int j_bin, int k_bin, error **);
double B_kappa_bar(cosmo_3rd *self, double s1, double s2, int abc, int i_bin, int j_bin, int k_bin, error **err);
double hept_rtbis(double (*func)(double,double,cosmo*,error**), double, double,
double, double, cosmo *, error **);
double B_delta(cosmo_3rd *self, double k1, double k2, double cosbeta, double a,
error **err);
double Uhat_one(double x, filter_t wfilter);
double Uhat(double eta, filter_t wfilter);
void permute3(double *x, int offset);
double int_for_map3_3d(double x[], size_t dim, void *intpar);
double map3_perm(cosmo_3rd *self, double R[3], int i_bin, int j_bin, int k_bin, filter_t wfilter, error **err);
double map3(cosmo_3rd *self, double R[3], int i_bin, int j_bin, int k_bin, filter_t wfilter, error **err);
double int_for_E_GGI(cosmo_lens *self, double zs1, double zs2, double zl, error **err);
double E_GGI(cosmo_lens *self, error **err);
double map3_GGI(cosmo_3rd *self, double theta, error **err);
double int_for_E_GII(cosmo_lens *self, double zs, double zl, error **err);
double E_GII(cosmo_lens *self, error **err);
double map3_GII(cosmo_3rd *self, double theta, error **err);
double map3_SLC_t1(cosmo_3rd *self, double R, int n_bin, error **err);
double bias_SLC(cosmo_3rd *self, double a, error **err);
double int_for_Q_mc(double x[], size_t dim, void *intpar);
double Q_mc(cosmo_3rd *self, double a1, double a2, double f1, double f2, double R, double *abserr,
double *chisqr, error **err);
double lensing_signal_3rd(cosmo_3rd *self, double theta[3], int i_bin, int j_bin, int k_bin, error **err);
void fill_dmm_map3gauss_diag(cosmo_3rd *self, double *data_minus_model, int start, const double *data,
int Nzbin, int Ntheta, double *theta, error **err);
void fill_dmm_map3gauss(cosmo_3rd *self, double *data_minus_model, int start, const double *data,
int Ntheta, double *theta, error **err);
double chi2_lensing_3rd(cosmo_3rd *self, datcov *dc, const cosebi_info_t *cosebi_info, error **err);
#endif
| {
"alphanum_fraction": 0.6777338603,
"avg_line_length": 33.2894736842,
"ext": "h",
"hexsha": "264522a192a250af440419e90dc812f9995b008d",
"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/Cosmo/include/lensing_3rd.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "danielgruen/ccv",
"max_issues_repo_path": "src/nicaea_2.5/Cosmo/include/lensing_3rd.h",
"max_line_length": 113,
"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/Cosmo/include/lensing_3rd.h",
"max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z",
"num_tokens": 2497,
"size": 7590
} |
#pragma once
#include <gsl/gsl>
/*
Helper class for reading structured binary data from a
memory stream.
*/
class BinaryReader {
public:
explicit BinaryReader(gsl::span<uint8_t> data) : mData(data) {}
template<typename T>
T Read() {
Expects(mData.size() >= sizeof(T));
auto result{ *reinterpret_cast<T*>(&mData[0]) };
mData = mData.subspan(sizeof(T));
return result;
}
std::string ReadFixedString(size_t length) {
Expects(mData.size() >= (int) length);
std::string result(length, '\0');
memcpy(&result[0], &mData[0], length);
result.resize(result.length());
mData = mData.subspan(length);
return result;
}
bool AtEnd() const {
return mData.size() == 0;
}
private:
gsl::span<uint8_t> mData;
};
| {
"alphanum_fraction": 0.6639455782,
"avg_line_length": 18.8461538462,
"ext": "h",
"hexsha": "7ab02719e299ad5d4927b33053f8379c261f6e03",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2021-11-15T23:14:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-02-04T21:19:53.000Z",
"max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "edoipi/TemplePlus",
"max_forks_repo_path": "Infrastructure/include/infrastructure/binaryreader.h",
"max_issues_count": 457,
"max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T02:19:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-01T22:07:45.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "edoipi/TemplePlus",
"max_issues_repo_path": "Infrastructure/include/infrastructure/binaryreader.h",
"max_line_length": 64,
"max_stars_count": 69,
"max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "edoipi/TemplePlus",
"max_stars_repo_path": "Infrastructure/include/infrastructure/binaryreader.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-15T06:13:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-05T14:09:25.000Z",
"num_tokens": 204,
"size": 735
} |
/*
** Implementation of LISA algorithm
** for statistical inference of fMRI images
**
** 1st level analysis using GLM (general linear model) with pre-coloring
**
** G.Lohmann, April 2017
*/
#include "viaio/Vlib.h"
#include "viaio/file.h"
#include "viaio/mu.h"
#include "viaio/option.h"
#include "viaio/os.h"
#include <viaio/VImage.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_permutation.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _OPENMP
#include <omp.h>
#endif /*_OPENMP*/
typedef struct TrialStruct {
int id;
float onset;
float duration;
float height;
} Trial;
extern void VIsolatedVoxels(VImage src,float threshold);
extern void VHistogram(gsl_histogram *histogram,VString filename);
extern void VCheckImage(VImage src);
extern void FDR(VImage src,VImage dest,gsl_histogram *nullhist,gsl_histogram *realhist,double);
extern double ttest1(double *data1,int n);
extern void ImageStats(VImage src,double *,double *,double *hmin,double *hmax);
extern Trial *ReadDesign(VStringConst designfile,int *numtrials,int *nevents);
extern gsl_matrix *VCreateDesign(int ntimesteps,int nevents,int,VBoolean,gsl_matrix *);
extern void VHemoModel(Trial *trial,int ntrials,int nevents,int ntimesteps,double tr,int,VBoolean,gsl_matrix *,gsl_matrix *);
extern Trial *CopyTrials(Trial *trial,int numtrials);
extern void VGLM(gsl_matrix *Data,gsl_matrix *X,gsl_matrix *XInv,gsl_vector *con,VImage map,VImage zmap);
extern Trial *ConcatenateTrials(Trial **trial,int *numtrials,float *run_duration,int dlists,int sumtrials);
extern double VImageVar(VImage src);
extern void VImageCount(VImage src);
extern void VBilateralFilter(VImage src,VImage,int radius,double var1,double var2,int);
extern void VGetHistRange(VImage src,double *hmin,double *hmax);
extern void VZScale(VImage src,float,float stddev);
extern float VGetMode(VImage src);
extern void GlobalMean(gsl_matrix *Data,gsl_matrix *covariates,int column);
extern gsl_matrix *VReadCovariates(VString cfile,VBoolean normalize);
extern VImage VoxelMap(VAttrList list);
extern gsl_matrix *VReadImageData(VAttrList *list,int nlists);
extern void VGetTimeInfos(VAttrList *list,int nlists,double *mtr,float *run_duration);
extern void VRowNormalize(gsl_matrix *Data);
extern void CheckTrialLabels(Trial *trial,int numtrials);
extern void HistoUpdate(VImage,gsl_histogram *);
extern void PlotDesign(gsl_matrix *X,double tr,VString filename);
void XCheckImage(VImage src,char *filename)
{
VAttrList out_list = VCreateAttrList();
VAppendAttr(out_list,"image",NULL,VImageRepn,src);
FILE *out_file = fopen(filename,"w");
VWriteFile (out_file, out_list);
}
/* shuffle each run separately to ensure exchangebility, concatenate individual permtables */
int **genperm(gsl_rng *rx,int *numtrials,int sumtrials,int dlists,int numperm)
{
int i,j,k;
int **permtable = (int **) VCalloc(numperm,sizeof(int *));
gsl_permutation **perm = (gsl_permutation **) VCalloc(dlists,sizeof(gsl_permutation *));
for (k=0; k<dlists; k++) {
perm[k] = gsl_permutation_alloc((size_t)numtrials[k]);
gsl_permutation_init (perm[k]);
}
for (i = 0; i < numperm; i++) {
permtable[i] = (int *) VCalloc(sumtrials,sizeof(int));
int jj=0;
for (k=0; k<dlists; k++) {
gsl_ran_shuffle (rx, perm[k]->data,numtrials[k],sizeof(size_t));
for (j=0; j<numtrials[k]; j++) {
permtable[i][j+jj] = perm[k]->data[j] + jj;
}
jj += numtrials[k];
}
}
for (k=0; k<dlists; k++) {
gsl_permutation_free(perm[k]);
}
return permtable;
}
VDictEntry HemoDict[] = {
{ "gamma_0", 0 },
{ "gamma_1", 1 },
{ "gamma_2", 2 },
{ "gauss", 3 },
{ NULL }
};
int main (int argc, char *argv[])
{
static VArgVector in_files;
static VArgVector des_files;
static VString cova_filename="";
static VString out_filename="";
static VString plot_filename="";
static VString mask_filename="";
static VShort hemomodel = 0;
static VBoolean firstcol = TRUE;
static VArgVector contrast;
static VFloat alpha = 0.05;
static VShort radius = 2;
static VFloat rvar = 2.0;
static VFloat svar = 2.0;
static VShort numiter = 2;
static VBoolean cleanup = TRUE;
static VBoolean demean = TRUE;
static VBoolean verbose = FALSE;
static VBoolean globalmean = FALSE;
static VShort numperm = 5000;
static VLong seed = 99402622;
static VShort nproc = 0;
static VOptionDescRec options[] = {
{"in", VStringRepn, 0, & in_files, VRequiredOpt, NULL,"Input files" },
{"out", VStringRepn, 1, & out_filename, VRequiredOpt, NULL,"Output file" },
{"design", VStringRepn, 0, & des_files, VRequiredOpt, NULL,"Design files (1st level)" },
{"contrast", VFloatRepn, 0, (VPointer) &contrast, VRequiredOpt, NULL, "Contrast vector"},
{"nuisance", VStringRepn, 1, & cova_filename, VOptionalOpt, NULL,"Nuisance regressors" },
{"demean",VBooleanRepn,1,(VPointer) &demean,VOptionalOpt,NULL,"Whether to subtract mean in nuisance regressors"},
{"hemo", VShortRepn, 1, (VPointer) &hemomodel, VOptionalOpt, HemoDict,"Hemodynamic model" },
{"col1", VBooleanRepn, 1, (VPointer) &firstcol, VOptionalOpt, NULL,"Whether to add a constant first column" },
{"alpha",VFloatRepn,1,(VPointer) &alpha,VOptionalOpt,NULL,"FDR significance level"},
{"perm",VShortRepn,1,(VPointer) &numperm,VOptionalOpt,NULL,"Number of permutations"},
{"seed",VLongRepn,1,(VPointer) &seed,VOptionalOpt,NULL,"Seed for random number generation"},
{"plotdesign", VStringRepn, 1, & plot_filename, VOptionalOpt, NULL,"Filename for plotting design matrix X" },
{"radius",VShortRepn,1,(VPointer) &radius,VOptionalOpt,NULL,"Bilateral parameter (radius in voxels)"},
{"rvar",VFloatRepn,1,(VPointer) &rvar,VOptionalOpt,NULL,"Bilateral parameter (radiometric)"},
{"svar",VFloatRepn,1,(VPointer) &svar,VOptionalOpt,NULL,"Bilateral parameter (spatial)"},
{"filteriterations",VShortRepn,1,(VPointer) &numiter,VOptionalOpt,NULL,"Bilateral parameter (number of iterations)"},
{"cleanup",VBooleanRepn,1,(VPointer) &cleanup,VOptionalOpt,NULL,"Whether to remove isloated voxels"},
{"mask", VStringRepn, 1, (VPointer) &mask_filename, VRequiredOpt, NULL, "Mask"},
{"j",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,"number of processors to use, '0' to use all"},
};
FILE *fp=NULL;
VString in_filename;
VAttrList out_list=NULL,geolist=NULL;
int i;
char *prg_name=GetLipsiaName("vlisa_precoloring");
fprintf (stderr, "%s\n", prg_name);
/* parse command line */
if (! VParseCommand (VNumber (options), options, & argc, argv)) {
VReportUsage (argv[0], VNumber (options), options, NULL);
exit (EXIT_FAILURE);
}
if (argc > 1) {
VReportBadArgs (argc, argv);
exit (EXIT_FAILURE);
}
/* omp-stuff */
#ifdef _OPENMP
int num_procs=omp_get_num_procs();
if (nproc > 0 && nproc < num_procs) num_procs = nproc;
fprintf(stderr," using %d cores\n",(int)num_procs);
omp_set_num_threads(num_procs);
#endif /* _OPENMP */
/* read functional image data */
int nlists = in_files.number;
if (nlists < 1) VError(" no input");
VAttrList *list = (VAttrList *) VCalloc(nlists,sizeof(VAttrList));
for (i=0; i<nlists; i++) {
in_filename = ((VString *) in_files.vector)[i];
fprintf(stderr," %3d: %s\n",i,in_filename);
list[i] = VReadAttrList(in_filename,0L,TRUE,FALSE);
if (geolist == NULL) {
geolist = VGetGeoInfo(list[i]);
double *DGeo = VGetGeoDim(geolist,NULL);
if (fabs(DGeo[0]-4.0) > 0.01) VError(" Input files must be 4D (not 3D)");
}
}
/* get number og design files */
int dlists = des_files.number;
if (dlists != nlists) {
VError(" number of input functional files (%d) and design files (%d) do not match",nlists,dlists);
}
/* apply brain mask or threshold */
VMultMinval(list,nlists,mask_filename,0.0);
/* read data and voxel map */
double tr=0;
float *run_duration = (float *) VCalloc(nlists,sizeof(float));
VGetTimeInfos(list,nlists,&tr,run_duration);
gsl_matrix *Data = VReadImageData(list,nlists);
VImage map = VoxelMap(list[0]);
int nslices = VPixel(map,0,3,0,VShort);
int nrows = VPixel(map,0,3,1,VShort);
int ncols = VPixel(map,0,3,2,VShort);
int ntimesteps = Data->size2;
/* additional regressors, no task labels, not included in permutations */
gsl_matrix *ctmp1=NULL;
gsl_matrix *ctmp2=NULL;
gsl_matrix *covariates=NULL;
int cdim = 1;
int nuisance_dim=0;
if (strlen(cova_filename) > 1) {
ctmp1 = VReadCovariates(cova_filename,demean);
if (ctmp1->size1 != Data->size2) VError(" num timesteps in covariate file not consistent with data");
nuisance_dim = ctmp1->size2;
}
if (globalmean) {
if (ctmp1 != NULL) cdim = ctmp1->size2+1;
ctmp2 = gsl_matrix_calloc(Data->size2,cdim);
GlobalMean(Data,ctmp2,(int)(cdim-1));
}
if (ctmp1 != NULL && ctmp2 == NULL) covariates = ctmp1;
if (ctmp2 != NULL) covariates = ctmp2;
/* design files with task labels */
Trial **trial = (Trial **) VCalloc(dlists,sizeof(Trial *));
int *numtrials = (int *) VCalloc(dlists,sizeof(int *));
int nevents = 0;
int sumtrials = 0;
for (i=0; i<dlists; i++) {
in_filename = ((VString *) des_files.vector)[i];
fprintf(stderr," %3d: %s\n",i,in_filename);
int kk=0,jj=0;
trial[i] = ReadDesign(in_filename,&kk,&jj);
numtrials[i] = kk;
if (jj > nevents) nevents = jj;
sumtrials += numtrials[i];
}
fprintf(stderr," Number of trials: %d, number of event types: %d\n",sumtrials,nevents);
Trial *alltrials = ConcatenateTrials(trial,numtrials,run_duration,nlists,sumtrials);
CheckTrialLabels(alltrials,sumtrials);
/* read contrast vector */
gsl_vector *cont = gsl_vector_alloc(contrast.number + nuisance_dim);
gsl_vector_set_zero(cont);
for (i=0; i < contrast.number; i++) {
double u = ((VFloat *)contrast.vector)[i];
gsl_vector_set(cont,i,u);
}
/* alloc initial design matrix X */
gsl_matrix *X = VCreateDesign(ntimesteps,nevents,(int)hemomodel,firstcol,covariates);
fprintf(stderr," Design file dimensions: %lu x %lu\n",X->size1,X->size2);
gsl_matrix *XInv = gsl_matrix_calloc(X->size2,X->size1);
if (X->size2 != cont->size) {
VError(" dimension of contrast vector (%ld) does not match design matrix (%ld)",cont->size-1,X->size2);
}
/* ini random permutations */
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);
if (verbose) fprintf(stderr," seed: %ld\n",(long)seed);
int **permtable = genperm(rx,numtrials,sumtrials,dlists,(int)numperm);
/* estimate null variance to adjust radiometric parameter, use first 30 permutations */
int nperm=0;
float stddev = 1.0;
double meanvar = 0.0;
if (numperm > 0) {
int tstperm = 30;
if (tstperm > numperm) tstperm = numperm;
VImage zmap = VCreateImage(nslices,nrows,ncols,VFloatRepn);
double varsum=0,nx=0;
for (nperm = 0; nperm < tstperm; nperm++) {
Trial *permtrials = CopyTrials(alltrials,sumtrials);
int j=0;
for (j=0; j<sumtrials; j++) {
int j0 = permtable[nperm][j];
permtrials[j].id = alltrials[j0].id;
}
gsl_matrix *X = VCreateDesign(ntimesteps,nevents,(int)hemomodel,firstcol,covariates);
gsl_matrix *XInv = gsl_matrix_calloc(X->size2,X->size1);
VHemoModel(permtrials,sumtrials,nevents,ntimesteps,tr,(int)hemomodel,firstcol,X,covariates);
VGLM(Data,X,XInv,cont,map,zmap);
varsum += VImageVar(zmap);
nx++;
gsl_matrix_free(X);
gsl_matrix_free(XInv);
VFree(permtrials);
}
meanvar = varsum/nx;
stddev = (float)(sqrt(meanvar)); /* update stddev */
VDestroyImage(zmap);
}
/* no permutation */
VImage zmap1 = VCreateImage(nslices,nrows,ncols,VFloatRepn);
VCopyImageAttrs (map,zmap1);
VImage dst1 = VCreateImageLike (zmap1);
VHemoModel(alltrials,sumtrials,nevents,ntimesteps,tr,(int)hemomodel,firstcol,X,covariates);
if (strlen(plot_filename) > 0) PlotDesign(X,tr,plot_filename);
VGLM(Data,X,XInv,cont,map,zmap1);
if (numperm == 0) {
double z = VImageVar(zmap1);
stddev = sqrt(z); /* update stddev */
}
float mode=0;
if (numperm > 0) VZScale(zmap1,mode,stddev);
VBilateralFilter(zmap1,dst1,(int)radius,(double)rvar,(double)svar,(int)numiter);
/* ini histograms */
double hmin=0,hmax=0;
VGetHistRange(dst1,&hmin,&hmax);
size_t nbins = 20000;
gsl_histogram *hist0 = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (hist0,hmin,hmax);
gsl_histogram *histz = gsl_histogram_alloc (nbins);
gsl_histogram_set_ranges_uniform (histz,hmin,hmax);
HistoUpdate(dst1,histz);
/* random permutations */
#pragma omp parallel for shared(Data) schedule(dynamic)
for (nperm = 0; nperm < numperm; nperm++) {
if (nperm%5 == 0) fprintf(stderr," perm %4d of %d\r",nperm,(int)numperm);
/* randomly shuffle trial labels */
Trial *permtrials = CopyTrials(alltrials,sumtrials);
int j=0;
for (j=0; j<sumtrials; j++) {
int j0 = permtable[nperm][j];
permtrials[j].id = alltrials[j0].id;
}
/* hemodynamic model */
gsl_matrix *X = VCreateDesign(ntimesteps,nevents,(int)hemomodel,firstcol,covariates);
gsl_matrix *XInv = gsl_matrix_calloc(X->size2,X->size1);
VHemoModel(permtrials,sumtrials,nevents,ntimesteps,tr,(int)hemomodel,firstcol,X,covariates);
/* GLM */
VImage zmap = VCreateImageLike(zmap1);
VGLM(Data,X,XInv,cont,map,zmap);
VZScale(zmap,mode,stddev);
gsl_matrix_free(X);
gsl_matrix_free(XInv);
VFree(permtrials);
/* bilateral filter */
VImage dst = VCreateImageLike (zmap);
VBilateralFilter(zmap,dst,(int)radius,(double)rvar,(double)svar,(int)numiter);
#pragma omp critical
{
HistoUpdate(dst,hist0);
}
VDestroyImage(dst);
VDestroyImage(zmap);
}
/* apply fdr */
VImage fdrimage = VCopyImage (dst1,NULL,VAllBands);
if (numperm > 0) {
FDR(dst1,fdrimage,hist0,histz,(double)alpha);
if (cleanup && alpha < 1.0) {
VIsolatedVoxels(fdrimage,(float)(1.0-alpha));
}
}
/*
** output
*/
out_list = VCreateAttrList ();
VHistory(VNumber(options),options,prg_name,&list[0],&out_list);
/* update geoinfo, 4D to 3D */
if (geolist != NULL) {
double *D = VGetGeoDim(geolist,NULL);
D[0] = 3;
D[4] = 1;
VSetGeoDim(geolist,D);
}
VSetGeoInfo(geolist,out_list);
VAppendAttr (out_list,"image",NULL,VImageRepn,fdrimage);
fp = VOpenOutputFile (out_filename, TRUE);
if (! VWriteFile (fp, out_list)) exit (1);
fclose(fp);
fprintf (stderr, "\n%s: done.\n", argv[0]);
exit(0);
}
| {
"alphanum_fraction": 0.6878612717,
"avg_line_length": 33.3587443946,
"ext": "c",
"hexsha": "bd574ceb52029e2c74c0c42241c1d8d0e9cb54f4",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T08:05:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-09-29T10:33:53.000Z",
"max_forks_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zrajna/lipsia",
"max_forks_repo_path": "src/stats/vlisa_precoloring/vlisa_precoloring.c",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_issues_repo_issues_event_max_datetime": "2022-02-16T13:42:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-11-12T15:47:56.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zrajna/lipsia",
"max_issues_repo_path": "src/stats/vlisa_precoloring/vlisa_precoloring.c",
"max_line_length": 125,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "8e7252653bd641df8f8d22ca5a9820507f154014",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zrajna/lipsia",
"max_stars_repo_path": "src/stats/vlisa_precoloring/vlisa_precoloring.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": 4577,
"size": 14878
} |
/* PSICOV - Protein Sparse Inverse COVariance analysis program */
/* by David T. Jones August 2011 - Copyright (C) 2011 University College London */
/* Version 1.05 - Last Edit 13/2/12 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <unistd.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#define FALSE 0
#define TRUE 1
#define SQR(x) ((x)*(x))
#define MAX(x,y) ((x)>(y)?(x):(y))
#define MIN(x,y) ((x)<(y)?(x):(y))
#define MAXSEQLEN 5000
#define MINSEQS 50
#define MINEFSEQS 100
extern glasso_(int *, double *, double *, int *, int *, int *, int *, double *, int *, double *, double *, int *, double *, int *);
/* Dump a rude message to standard error and exit */
void
fail(char *errstr)
{
fprintf(stderr, "\n*** %s\n\n", errstr);
exit(-1);
}
/* Convert AA letter to numeric code (0-21) */
int
aanum(int ch)
{
const static int aacvs[] =
{
999, 0, 3, 4, 3, 6, 13, 7, 8, 9, 21, 11, 10, 12, 2,
21, 14, 5, 1, 15, 16, 21, 19, 17, 21, 18, 6
};
return (isalpha(ch) ? aacvs[ch & 31] : 20);
}
/* Allocate matrix */
void *allocmat(int rows, int columns, int size)
{
int i;
void **p, *rp;
rp = malloc(rows * sizeof(void *) + sizeof(int));
if (rp == NULL)
fail("allocmat: malloc [] failed!");
*((int *)rp) = rows;
p = rp + sizeof(int);
for (i = 0; i < rows; i++)
if ((p[i] = calloc(columns, size)) == NULL)
fail("allocmat: malloc [][] failed!");
return p;
}
/* Free matrix */
void
freemat(void *rp)
{
int rows;
void **p = rp;
rows = *((int *)(rp - sizeof(int)));
while (rows--)
free(p[rows]);
free(rp - sizeof(int));
}
/* Allocate vector */
void *allocvec(int columns, int size)
{
void *p;
p = calloc(columns, size);
if (p == NULL)
fail("allocvec: calloc failed!");
return p;
}
struct sc_entry
{
float sc;
int i, j;
} *sclist;
/* Sort descending */
int cmpfn(const void *a, const void *b)
{
if (((struct sc_entry *)a)->sc == ((struct sc_entry *)b)->sc)
return 0;
if (((struct sc_entry *)a)->sc < ((struct sc_entry *)b)->sc)
return 1;
return -1;
}
int main(int argc, char **argv)
{
int a, b, i, j, k, seqlen, nids, s, nseqs, ncon, opt, ndim, approxflg=0, initflg=0, debugflg=0, diagpenflg=1, apcflg=1, maxit=10000, npair, nnzero, niter, jerr, shrinkflg=1, rawscflg = 1, pseudoc = 1, minseqsep = 5;
unsigned int *wtcount;
double thresh=1e-4, del, sum, score, (**pab)[21][21], **pa, wtsum, pc, **pcmat, *pcsum, pcmean, rhodefault = -1.0, lambda, smean, fnzero, lastfnzero, trialrho, rfact, r2, targfnzero = 0.0, scsum, scsumsq, mean, sd, zscore, ppv;
float *weight, idthresh = -1.0, maxgapf = 0.9;
char buf[4096], seq[MAXSEQLEN], *blockfn = NULL, **aln;
FILE *ifp;
while ((opt = getopt(argc, argv, "alnpr:b:i:t:c:g:d:j:")) >= 0)
switch (opt)
{
case 'a':
approxflg = 1;
break;
case 'n':
shrinkflg = 0;
break;
case 'p':
rawscflg = 0;
break;
case 'l':
apcflg = 0;
break;
case 'r':
rhodefault = atof(optarg);
break;
case 'd':
targfnzero = atof(optarg);
break;
case 't':
thresh = atof(optarg);
break;
case 'i':
idthresh = 1.0 - atof(optarg)/100.0;
break;
case 'c':
pseudoc = atoi(optarg);
break;
case 'j':
minseqsep = atoi(optarg);
break;
case 'b':
blockfn = strdup(optarg);
break;
case 'g':
maxgapf = atof(optarg);
break;
case '?':
exit(-1);
}
if (optind >= argc)
fail("Usage: psicov [options] alnfile\n\nOptions:\n-a\t: use approximate Lasso algorithm\n-n\t: don't pre-shrink the sample covariance matrix\n-p\t: output PPV estimates rather than raw scores\n-l\t: don't apply APC to Lasso output\n-r nnn\t: set initial rho parameter\n-d nnn\t: set target precision matrix sparsity (default 0 = not specified)\n-t nnn\t: set Lasso convergence threshold (default 1e-4)\n-i nnn\t: select BLOSUM weighting with given identity threshold (default selects threshold automatically)\n-c nnn\t: set pseudocount value (default 1)\n-j nnn\t: set minimum sequence separation (default 5)\n-g nnn\t: maximum fraction of gaps (default 0.9)\n-b file\t: read rho parameter file\n");
ifp = fopen(argv[optind], "r");
if (!ifp)
fail("Unable to open alignment file!");
for (nseqs=0;; nseqs++)
if (!fgets(seq, MAXSEQLEN, ifp))
break;
aln = allocvec(nseqs, sizeof(char *));
weight = allocvec(nseqs, sizeof(float));
wtcount = allocvec(nseqs, sizeof(unsigned int));
rewind(ifp);
if (!fgets(seq, MAXSEQLEN, ifp))
fail("Bad alignment file!");
seqlen = strlen(seq)-1;
if (nseqs < MINSEQS)
fail("Alignment too small - not enough homologous sequences to proceed (or change MINSEQS at your own risk!)");
if (!(aln[0] = malloc(seqlen)))
fail("Out of memory!");
for (j=0; j<seqlen; j++)
aln[0][j] = aanum(seq[j]);
for (i=1; i<nseqs; i++)
{
if (!fgets(seq, MAXSEQLEN, ifp))
break;
if (seqlen != strlen(seq)-1)
fail("Length mismatch in alignment file!");
if (!(aln[i] = malloc(seqlen)))
fail("Out of memory!");
for (j=0; j<seqlen; j++)
aln[i][j] = aanum(seq[j]);
}
/* Calculate sequence weights */
if (idthresh < 0.0)
{
double meanfracid = 0.0;
for (i=0; i<nseqs; i++)
for (j=i+1; j<nseqs; j++)
{
int nids;
float fracid;
for (nids=k=0; k<seqlen; k++)
if (aln[i][k] == aln[j][k])
nids++;
fracid = (float)nids / seqlen;
meanfracid += fracid;
}
meanfracid /= 0.5 * nseqs * (nseqs - 1.0);
idthresh = 0.38 * 0.32 / meanfracid;
}
for (i=0; i<nseqs; i++)
for (j=i+1; j<nseqs; j++)
{
int nthresh = seqlen * idthresh;
for (k=0; nthresh > 0 && k<seqlen; k++)
if (aln[i][k] != aln[j][k])
nthresh--;
if (nthresh > 0)
{
wtcount[i]++;
wtcount[j]++;
}
}
for (wtsum=i=0; i<nseqs; i++)
wtsum += (weight[i] = 1.0 / (1 + wtcount[i]));
if (wtsum < MINEFSEQS)
puts("\n*** WARNING - not enough sequence variation - or change MINEFSEQS at your own risk! ***\n");
pa = allocmat(seqlen, 21, sizeof(double));
pab = allocmat(seqlen, seqlen, 21*21*sizeof(double));
/* Calculate singlet frequencies with pseudocount */
for (i=0; i<seqlen; i++)
{
for (a=0; a<21; a++)
pa[i][a] = pseudoc;
for (k=0; k<nseqs; k++)
{
a = aln[k][i];
if (a < 21)
pa[i][a] += weight[k];
}
for (a=0; a<21; a++)
pa[i][a] /= pseudoc * 21.0 + wtsum;
}
/* Calculate pair frequencies with pseudocount */
for (i=0; i<seqlen; i++)
{
for (j=i+1; j<seqlen; j++)
{
for (a=0; a<21; a++)
for (b=0; b<21; b++)
pab[i][j][a][b] = pseudoc / 21.0;
for (k=0; k<nseqs; k++)
{
a = aln[k][i];
b = aln[k][j];
if (a < 21 && b < 21)
pab[i][j][a][b] += weight[k];
}
for (a=0; a<21; a++)
for (b=0; b<21; b++)
{
pab[i][j][a][b] /= pseudoc * 21.0 + wtsum;
pab[j][i][b][a] = pab[i][j][a][b];
// printf("%d/%d %d/%d %f %f %f %f\n", i+1, a, j+1, b, pab[i][j][a][b], pa[i][a] , pa[j][b], pab[i][j][a][b] - pa[i][a] * pa[j][b]);
}
}
}
for (i=0; i<seqlen; i++)
for (a=0; a<21; a++)
for (b=0; b<21; b++)
pab[i][i][a][b] = (a == b) ? pa[i][a] : 0.0;
gsl_matrix *cmat, *rho, *ww, *wwi, *tempmat;
ndim = seqlen * 21;
cmat = gsl_matrix_calloc(ndim, ndim);
/* Form the covariance matrix */
for (i=0; i<seqlen; i++)
for (j=0; j<seqlen; j++)
for (a=0; a<21; a++)
for (b=0; b<21; b++)
if (i != j)
gsl_matrix_set(cmat, i*21+a, j*21+b, pab[i][j][a][b] - pa[i][a] * pa[j][b]);
else if (a == b)
gsl_matrix_set(cmat, i*21+a, j*21+b, pab[i][j][a][b] - pa[i][a] * pa[j][b]);
freemat(pab);
/* Shrink sample covariance matrix towards shrinkage target F = Diag(1,1,1,...,1) * smean */
if (shrinkflg)
{
for (smean=i=0; i<ndim; i++)
smean += gsl_matrix_get(cmat, i, i);
smean /= (float)ndim;
lambda = 0.1;
// smean = 1;
tempmat = gsl_matrix_calloc(ndim, ndim);
gsl_set_error_handler_off();
for (;;)
{
gsl_matrix_memcpy(tempmat, cmat);
/* Test if positive definite using Cholesky decomposition */
if (!gsl_linalg_cholesky_decomp(tempmat))
break;
for (i=0; i<seqlen; i++)
for (j=0; j<seqlen; j++)
for (a=0; a<21; a++)
for (b=0; b<21; b++)
if (i != j)
gsl_matrix_set(cmat, i*21+a, j*21+b, (1.0 - lambda) * gsl_matrix_get(cmat, i*21+a, j*21+b));
else if (a == b)
gsl_matrix_set(cmat, i*21+a, j*21+b, smean * lambda + (1.0 - lambda) * gsl_matrix_get(cmat, i*21+a, j*21+b));
}
gsl_matrix_free(tempmat);
}
rho = gsl_matrix_alloc(ndim, ndim);
ww = gsl_matrix_alloc(ndim, ndim);
wwi = gsl_matrix_alloc(ndim, ndim);
lastfnzero=0.0;
/* Guess at a reasonable starting rho value if undefined */
if (rhodefault < 0.0)
trialrho = MAX(0.001, 1.0 / wtsum);
else
trialrho = rhodefault;
rfact = 0.0;
for (;;)
{
if (trialrho <= 0.0 || trialrho >= 1.0)
fail("Sorry - failed to find suitable value for rho (0 < rho < 1)!");
gsl_matrix_set_all(rho, trialrho);
for (i=0; i<seqlen; i++)
for (j=0; j<seqlen; j++)
for (a=0; a<21; a++)
for (b=0; b<21; b++)
if ((a != b && i == j) || pa[i][20] > maxgapf || pa[j][20] > maxgapf)
gsl_matrix_set(rho, i*21+a, j*21+b, 1e9);
/* Mask out regions if block-out list provided */
if (blockfn != NULL)
{
ifp = fopen(blockfn, "r");
for (;;)
{
if (fscanf(ifp, "%d %d %lf", &i, &j, &score) != 3)
break;
for (a=0; a<21; a++)
for (b=0; b<21; b++)
{
gsl_matrix_set(rho, (i-1)*21+a, (j-1)*21+b, score);
gsl_matrix_set(rho, (j-1)*21+b, (i-1)*21+a, score);
}
}
fclose(ifp);
}
/* All matrices are symmetric so no need to transpose before/after calling Fortran code */
glasso_(&ndim, cmat->data, rho->data, &approxflg, &initflg, &debugflg, &diagpenflg, &thresh, &maxit, ww->data, wwi->data, &niter, &del, &jerr);
if (targfnzero <= 0.0)
break;
for (npair=nnzero=i=0; i<ndim; i++)
for (j=i+1; j<ndim; j++,npair++)
if (gsl_matrix_get(wwi, i, j) != 0.0)
nnzero++;
fnzero = (double) nnzero / npair;
// printf("rho=%f fnzero = %f\n", trialrho, fnzero);
/* Stop iterating if we have achieved the target sparsity level */
if (fabs(fnzero - targfnzero)/targfnzero < 0.01)
break;
if (fnzero == 0.0)
{
/* As we have guessed far too high, halve rho and try again */
trialrho *= 0.5;
continue;
}
if (lastfnzero > 0.0 && fnzero != lastfnzero)
{
// printf("fnzero=%f lastfnzero=%f trialrho=%f oldtrialrho=%f\n", fnzero, lastfnzero, trialrho, trialrho/rfact);
rfact = pow(rfact, log(targfnzero / fnzero) / log(fnzero / lastfnzero));
// printf("New rfact = %f\n", rfact);
}
lastfnzero = fnzero;
/* Make a small trial step in the appropriate direction */
if (rfact == 0.0)
rfact = (fnzero < targfnzero) ? 0.9 : 1.1;
trialrho *= rfact;
}
gsl_matrix_free(rho);
gsl_matrix_free(ww);
/* Calculate background corrected scores using average product correction */
pcmat = allocmat(seqlen, seqlen, sizeof(double));
pcsum = allocvec(seqlen, sizeof(double));
pcmean = 0.0;
for (i=0; i<seqlen; i++)
for (j=i+1; j<seqlen; j++)
{
for (pc=a=0; a<20; a++)
for (b=0; b<20; b++)
pc += fabs(gsl_matrix_get(wwi, i*21+a, j*21+b));
pcmat[i][j] = pcmat[j][i] = pc;
pcsum[i] += pc;
pcsum[j] += pc;
pcmean += pc;
}
pcmean /= seqlen * (seqlen - 1) * 0.5;
/* Build final list of predicted contacts */
sclist = allocvec(seqlen * (seqlen - 1) / 2, sizeof(struct sc_entry));
for (scsum=scsumsq=ncon=i=0; i<seqlen; i++)
for (j=i+minseqsep; j<seqlen; j++)
if (pcmat[i][j] > 0.0)
{
/* Calculate APC score */
if (apcflg)
sclist[ncon].sc = pcmat[i][j] - pcsum[i] * pcsum[j] / SQR(seqlen - 1.0) / pcmean;
else
sclist[ncon].sc = pcmat[i][j];
scsum += sclist[ncon].sc;
scsumsq += SQR(sclist[ncon].sc);
sclist[ncon].i = i;
sclist[ncon++].j = j;
}
qsort(sclist, ncon, sizeof(struct sc_entry), cmpfn);
mean = scsum / ncon;
sd = sqrt(scsumsq / ncon - SQR(mean));
/* Print output in CASP RR format with optional PPV estimated from final Z-score */
if (rawscflg)
for (i=0; i<ncon; i++)
printf("%d %d 0 8 %f\n", sclist[i].i+1, sclist[i].j+1, sclist[i].sc);
else
for (i=0; i<ncon; i++)
{
zscore = (sclist[i].sc - mean) / sd;
ppv = 0.904 / (1.0 + 16.61 * exp(-0.8105 * zscore));
printf("%d %d 0 8 %f\n", sclist[i].i+1, sclist[i].j+1, ppv);
}
return 0;
}
| {
"alphanum_fraction": 0.5508226972,
"avg_line_length": 24.0851851852,
"ext": "c",
"hexsha": "757fb164a19794ee936ae2e048330ad224a72cb3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-09-05T02:43:44.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-09-05T02:43:44.000Z",
"max_forks_repo_head_hexsha": "daea50468c712bd7cc65e2078cdc3af4d55a5941",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "dgattiwsu/MSAVOLVE_v3.0a",
"max_forks_repo_path": "COEVOLUTION_METHODS/FUNCTIONS/PSICOV/psicov_unlimited.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "daea50468c712bd7cc65e2078cdc3af4d55a5941",
"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": "dgattiwsu/MSAVOLVE_v3.0a",
"max_issues_repo_path": "COEVOLUTION_METHODS/FUNCTIONS/PSICOV/psicov_unlimited.c",
"max_line_length": 701,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "daea50468c712bd7cc65e2078cdc3af4d55a5941",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "dgattiwsu/MSAVOLVE_v3.0a",
"max_stars_repo_path": "COEVOLUTION_METHODS/FUNCTIONS/PSICOV/psicov_unlimited.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4731,
"size": 13006
} |
#include <lapacke.h>
#include "tasks.h"
void chol_task_seq(void *ptr)
{
struct chol_task_arg *arg = (struct chol_task_arg*) ptr;
int n = arg->n;
double *A = arg->A;
int ldA = arg->ldA;
LAPACKE_dpotrf(LAPACK_COL_MAJOR, 'L', n, A, ldA);
}
| {
"alphanum_fraction": 0.6014760148,
"avg_line_length": 14.2631578947,
"ext": "c",
"hexsha": "fef9545f3825dc179bd425ee768347a5c8dc0b4f",
"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": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/pcp-runtime",
"max_forks_repo_path": "src/examples/dpotrf/task-chol-seq.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/pcp-runtime",
"max_issues_repo_path": "src/examples/dpotrf/task-chol-seq.c",
"max_line_length": 60,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/pcp-runtime",
"max_stars_repo_path": "src/examples/dpotrf/task-chol-seq.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 90,
"size": 271
} |
/* Copyright (c) 2011-2012, Jérémy Fix. 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. */
/* * None of 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 AUTHOR AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */
/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */
/* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */
/* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */
/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */
/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
#ifndef EKF_TYPES_H
#define EKF_TYPES_H
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include "ukf_math.h"
/**
* @short Extended Kalman Filter in the case of additive noise, the notations follow Van Der Merwe, phD, p. 36
*/
namespace ekf
{
class EvolutionNoise;
/**
* @short Structure holding the parameters of the statistical linearization
*
*/
typedef struct
{
/**
* @short Evolution noise type
*/
EvolutionNoise *evolution_noise;
/**
* @short Covariance of the observation noise
*/
double observation_noise;
/**
* @short Prior estimate of the covariance matrix
*/
double prior_pk;
/**
* @short Number of parameters to estimate
*/
int n;
/**
* @short Dimension of the output
*/
int no;
/**
* @short Is the observation gradient diagonal ? In that case, simplifications can be introduced
*/
bool observation_gradient_is_diagonal;
} ekf_param;
typedef struct
{
/**
* @short Current estimate of the state
*/
gsl_vector * xk;
/**
* @short Predicted state
*/
gsl_vector * xkm;
/**
* @short Variance-Covariance of the state
*/
gsl_matrix * Pxk;
/**
* @short Jacobian of the evolution function
*/
gsl_matrix *Fxk;
/**
* @short Variance covariance of the evolution noise
*/
gsl_matrix * Rv;
/**
* @short Current observation
*/
gsl_vector * yk;
/**
* @short Current innovations
*/
gsl_vector * ino_yk;
/**
* @short Jacobian of the observation function
*/
gsl_matrix *Hyk;
/**
* @short Variance covariance of the observation noise
*/
gsl_matrix * Rn;
/**
* @short Kalman gain
*/
gsl_matrix *Kk;
/**
* @short Temporary matrices
*/
gsl_matrix * temp_n_n;
gsl_matrix * temp_n_1;
gsl_matrix * temp_no_no;
gsl_matrix * temp_n_no;
gsl_matrix * temp_2_n_n;
gsl_vector * temp_no;
/**
* @short Optional parameters (this must be allocated and initialized from the user side!
*/
gsl_vector * params;
} ekf_state;
/**
* @short Mother class from which the evolution noises inherit
*/
class EvolutionNoise
{
protected:
double _initial_value;
public:
EvolutionNoise(double initial_value) : _initial_value(initial_value) {};
void init(ekf_param &p, ekf_state &s)
{
gsl_matrix_set_identity(s.Rv);
gsl_matrix_scale(s.Rv, _initial_value);
}
virtual void updateEvolutionNoise(ekf_param &p, ekf_state &s) = 0;
};
/**
* @short Annealing type evolution noise
*/
class EvolutionAnneal : public EvolutionNoise
{
double _decay, _lower_bound;
public:
EvolutionAnneal(double initial_value, double decay, double lower_bound) : EvolutionNoise(initial_value),
_decay(decay),
_lower_bound(lower_bound)
{ };
void updateEvolutionNoise(ekf_param &p, ekf_state &s)
{
for(int i = 0 ; i < p.n ; ++i)
{
for(int j = 0 ; j < p.n ; ++j)
{
if(i == j)
gsl_matrix_set(s.Rv, i, i, ukf::math::max(_decay * gsl_matrix_get(s.Rv,i,i),_lower_bound));
else
gsl_matrix_set(s.Rv, i, j, 0.0);
}
}
}
};
/**
* @short Forgetting type evolution noise
*/
class EvolutionRLS : public EvolutionNoise
{
double _decay;
public:
EvolutionRLS(double initial_value, double decay) : EvolutionNoise(initial_value), _decay(decay)
{
if(ukf::math::cmp_equal(_decay, 0.0))
printf("Forgetting factor should not be null !!\n");
};
void updateEvolutionNoise(ekf_param &p, ekf_state &s)
{
gsl_matrix_memcpy(s.Rv, s.Pxk);
gsl_matrix_scale(s.Rv, 1.0 / _decay - 1.0);
}
};
/**
* @short Robbins-Monro evolution noise
*/
class EvolutionRobbinsMonro : public EvolutionNoise
{
double _alpha;
public:
EvolutionRobbinsMonro(double initial_value, double alpha) : EvolutionNoise(initial_value),
_alpha(alpha)
{ };
void updateEvolutionNoise(ekf_param &p, ekf_state &s)
{
// Compute Kk * ino_yk
gsl_matrix_view mat_view = gsl_matrix_view_array(s.ino_yk->data, p.no, 1);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Kk, &mat_view.matrix, 0.0, s.temp_n_1);
// Compute : Rv = (1 - alpha) Rv + alpha . (Kk * ino_yk) * (Kk * ino_yk)^T
gsl_blas_dgemm(CblasNoTrans, CblasTrans, _alpha, s.temp_n_1, s.temp_n_1, (1.0 - _alpha),s.Rv);
}
};
}
#endif // EKF_TYPES_H
| {
"alphanum_fraction": 0.6541107108,
"avg_line_length": 25.6554621849,
"ext": "h",
"hexsha": "4130849aefcbb55a7654ed715246f9d899bf2ef8",
"lang": "C",
"max_forks_count": 52,
"max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z",
"max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "bahia14/C-Kalman-filtering",
"max_forks_repo_path": "src/ekf_types.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a",
"max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "bahia14/C-Kalman-filtering",
"max_issues_repo_path": "src/ekf_types.h",
"max_line_length": 158,
"max_stars_count": 101,
"max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "bahia14/C-Kalman-filtering",
"max_stars_repo_path": "src/ekf_types.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z",
"num_tokens": 1579,
"size": 6106
} |
#ifndef CWANNIER_PARTIALNUMVALUES_H
#define CWANNIER_PARTIALNUMVALUES_H
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include "HTightBinding.h"
#include "PartialDosValues.h"
#include "ctetra/sum.h"
double** PartialNumValues(HTightBinding *Hrs, gsl_matrix *R, int na, int nb, int nc, double num_total_electrons, double **Es, double num_E, double *E_Fermi, double **num_states_Fermi);
#endif //CWANNIER_PARTIALNUMVALUES_H
| {
"alphanum_fraction": 0.7917570499,
"avg_line_length": 32.9285714286,
"ext": "h",
"hexsha": "577599afdfee2f914bb63f2833653680dc55b885",
"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": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tflovorn/cwannier",
"max_forks_repo_path": "PartialNumValues.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"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": "tflovorn/cwannier",
"max_issues_repo_path": "PartialNumValues.h",
"max_line_length": 184,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "96b9719b098d3e2e7d6f4fa5b2c938aa460c5fb8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tflovorn/cwannier",
"max_stars_repo_path": "PartialNumValues.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 139,
"size": 461
} |
/*
F(4,3)
cc -static -o test_cblas_open main43.c -I /opt/OpenBLAS/include/ -L/opt/OpenBLAS/lib -lopenblas -lpthread -lgfortran
->For each cube of kernel
-> for each tile (a tile is a cube d x d x channel)
-> for each channel
-> Apply the winograd algorithm
-> sum the result of the previous channel to the result of the next channell
-> write the tile in a single output layer
->Add the output layer in che cube layer and change the kernel cube
*/
#include <cblas.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#define MAX_ELEMENTS 100
#define FILENAMELEN 10
#define DDIMENSION(m,r) (m+r-1)
#define OUTPUTDIMENSION(m,w,d) (m * (w / d))
typedef float * Matrix;
typedef Matrix * Cube;
typedef Cube * Hypercube;
void productABAt(float result[], float A[], float B[], int rowsA, int colsB, int colsA);
void twoDcorrelation(float C[], float g[], float D[], int m, int r, int d);
Matrix elaborateTile(Cube tile, Cube g, int m, int r, int d, int channel);
Cube fillTheTile(Cube image, int starth, int startw, int w, int d, int channel);
void saveOutputTile(Matrix output, Matrix tileOutput, int starth, int startw, int w, int d, int m);
Matrix elaborateKernel(Cube image, Cube g, int m, int r, int channel, int w, int h, int d);
/*START FUNCTION TO CREATE VARIABLES*/
Cube generateCube(int w, int h, int ch);
Matrix generateMatrix(int w, int h);
Hypercube readKernels(int w, int h, int ch, int k, char fileName[]);
Cube readInput(int w, int h, int ch, char fileName[]);
void printCube(Cube c, int w, int channel);
/*END FUNCTION TO CREARE VARIABLES*/
/*START FUNCTIONS TO READ THE FILES*/
void readFile(float result[], char fileName[]);
void generateNameAT(char* at, int m, int r);
void generateNameG(char* g, int m, int r);
void generateNameBT(char* g, int m, int r);
/* END FUNCRIONS TO READ THE FILES*/
static Matrix A; //Parameters that are used to make the lowest operation.
static Matrix B; //
static Matrix G; //
void main(int argc, char *argv[])
{
int m = atoi(argv[1]); //dimension of the output tile
int r = atoi(argv[2]); //dimension of the kernel rxr
int channel = atoi(argv[3]); //dimension of the channel
int k = atoi(argv[4]); //number of kernel
int w = atoi(argv[5]); //width of the image -> multiple of d
int h = atoi(argv[6]); //height of the image -> multiple of d
char * inputFilename = argv[7];
char * kernelFilename = argv[8];
int d = DDIMENSION(m,r);
char fnameAT[FILENAMELEN];
char fnameG[FILENAMELEN];
char fnameBT[FILENAMELEN];
generateNameAT(fnameAT, m,r);
generateNameG(fnameG, m,r);
generateNameBT(fnameBT, m,r);
A = generateMatrix(m, d);
B = generateMatrix(d, d);
G = generateMatrix(r, d);
readFile(A, fnameAT);
readFile(B, fnameBT);
readFile(G, fnameG);
Cube image = readInput(w, h, channel, inputFilename);
Hypercube kernel = readKernels(r, r, channel, k, kernelFilename);
printf("IMAGE\n");
printCube(image, w, channel);
printf("\nKERNELS\n");
for(int i = 0; i < k; i++)
{
printf("Kernel number %d\n", i);
printCube(kernel[i], r, channel);
}
printf("\n------------------\n");
Cube output = (Cube)malloc(k * sizeof(Matrix)); //k is the number of filters
//printf("START THE COMPUTATION - SLEEP FOR 3 SECONDS\n");
//sleep(3);
/*
* START COMPUTATION.
*/
clock_t start = clock();
for(int i = 0; i < k; i ++)
output[i] = elaborateKernel(image, kernel[i], m, r, channel, w, h, d);
clock_t end = clock();
/*
* END COMPUTATION.
*/
printf("OUTPUT:\n");
printCube(output, OUTPUTDIMENSION(m,w,d), k);
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
printf("\nTIME IN SECONDS TO DO F(%d,%d) = %f\n",m,r,seconds);
}
void printCube(Cube c, int w, int channel)
{
for(int i = 0; i < channel; i++)
{
printf("channel %d:\n",i);
for(int j = 0; j < w * w; j ++)
{
printf("%.2f ", c[i][j]);
if((j+1) % w == 0) printf("\n");
}
}
}
Matrix elaborateKernel(Cube image, Cube g, int m, int r, int channel, int w, int h, int d)
{
Matrix output = generateMatrix(OUTPUTDIMENSION(m,w,d), OUTPUTDIMENSION(m,w,d));
for(int i = 0; i < h; i = i + d)
{
for (int j = 0; j < w; j = j + d)
{
Cube tile = fillTheTile(image, i, j, w, d, channel);
Matrix tileOutput = elaborateTile(tile, g, m, r, d, channel);
saveOutputTile(output, tileOutput, i, j, w, d, m);
free(tileOutput);
free(tile);
}
}
return output;
}
/*
Write the output tile on the output image.
*/
void saveOutputTile(Matrix output, Matrix tileOutput, int starth, int startw, int w, int d, int m)
{
int outputWidth = OUTPUTDIMENSION(m,w,d);
int offsetw = (startw / d) * m;
int offseth = (starth / d) * m;
for(int y = 0; y < m; y ++)
for(int x = 0; x < m; x++)
output[(x + offsetw) + (outputWidth * (y + offseth))] = tileOutput[x + (m * y)];
}
/*
This function takes an image, it divides the image based on starth and startw and it returns a tile.
- image -> the all image
- starth -> height coordinate of the image where to start to make the tile
- startw -> width coordinate of the image where to start to make the tile
- w -> total width of the image
- d -> dimension of the tile -> d x d
- channel -> number of channels of the image
RESULT
- A cube d x d x channell that represent a single tile.
*/
Cube fillTheTile(Cube image, int starth, int startw, int w, int d, int channel)
{
Cube tile = generateCube(d, d, channel);
for(int c = 0; c < channel; c++)
for(int y = 0; y < d; y ++)
for(int x = 0; x < d; x++)
tile[c][x + (d * y)] = image[c][(startw + x) + (w * (y + starth))];
return tile;
}
/*
This function is used to make the combination with a tile and a kernel.
- tile has the dimension d x d and has 'channel' channels
- g is the kernel, it has the dimension of r x r and has 'channel' channels
- m -> dimension of the output
- r -> dimension of the kernel
- d -> dimension of the tile
- channell -> number of channels
RESULT
- it returns a matrix calculated by an element wise sum of the result of the function twoDcorrelation
calculated for each channel.
*/
Matrix elaborateTile(Cube tile, Cube g, int m, int r, int d, int channel)
{
Matrix temp = generateMatrix(d,d);
Matrix tileOutputBig = generateMatrix(d,d);
Matrix tileOutput = generateMatrix(m,m);
for(int i = 0; i < m * m; i++)
tileOutput[i] = 0;
for(int i = 0; i < channel; i++)
{
twoDcorrelation(temp, g[i], tile[i], m, r, d);
for(int j = 0 ; j < d * d; j++)
tileOutputBig[j] = tileOutputBig[j] + temp[j];
}
productABAt(tileOutput, A, tileOutputBig, m, d, d);
free(temp);
free(tileOutputBig);
return tileOutput;
}
Cube generateCube(int w, int h, int ch)
{
Cube cube = (Cube)malloc(ch * sizeof(Matrix));
for(int i = 0; i < ch; i++)
cube[i] = generateMatrix(w,h);
return cube;
}
Matrix generateMatrix(int w, int h)
{
return (Matrix)malloc(w * h * sizeof(float));
}
/*
Calculate a single channel for a single kernel for a single tile
Input Parameter:
- result -> matrix of the result
- g -> the considered kernel
- D -> the considered tile
- m -> Dimension of the output
- r -> dimension of the kernel
- d -> dimension of the tile (m + r - 1)
*/
void twoDcorrelation(float C[], float g[], float D[], int m, int r, int d)
{
float GgG[MAX_ELEMENTS];
float BDB[MAX_ELEMENTS];
int i=0;
productABAt(GgG, G, g, d, r, r);
productABAt(BDB, B, D, d, d, d);
for(i=0;i<d*d;i++)
C[i] = GgG[i] * BDB[i];
//productABAt(C, A, GgG, m, d, d);
}
/*
* Make the operation R = ABA**T
* Parameters:
* - Matrix Result
* - Matrix A and B
* - Number of rows of A -> rowsA
* - Number of cols of B -> colsB
* - Number of cols of A that is equal to the numer of rows of B -> colsA
* Result
* - Matrix result -> that is an rowsA x rowsA matrix
*/
void productABAt(float result[], float A[], float B[], int rowsA, int colsB, int colsA)
{
float C[MAX_ELEMENTS];
cblas_sgemm(CblasRowMajor, //Modo in cui è salvata la matrice, legge i numeri riga per riga
CblasNoTrans, //Non fare trasposta
CblasNoTrans, //Non fare trasposta
rowsA, //numero righe matrice A
colsB, //numero colonne matrice B
colsA, //numero colonne A & numero righe B
1, //moltiplicatore prima matrice
A, //Matrice A
colsA, //numero colonne matrice A
B, //Matrice B
colsB, //numero colonne matrice B
0, //Moltiplicatore matrice C
C, //matrice C
colsB); //numero righe matrice C
//C has rowsA rows and colsB cols
//the result has rowsA rows and rowsA cols
cblas_sgemm(CblasRowMajor,
CblasNoTrans,
CblasTrans,
rowsA, //numero righe matrice C
rowsA,
colsB,
1,
C,
colsB,
A,
colsA,
0,
result,
rowsA);
}
Cube readInput(int w, int h, int ch, char fileName[])
{
FILE *f;
f = fopen(fileName, "r");
if(f==NULL)
{
printf("I can not read the file %s\n", fileName);
exit(0);
}
int fi = 0;
int linesize = w*h;
Cube matrix = (Cube)malloc(ch * sizeof(Matrix));
for(int i = 0; i < ch; i++)
{
matrix[i] = (Matrix)malloc(linesize * sizeof(float));
while(!feof(f)&&fi<linesize)
{
fscanf(f, "%f", &matrix[i][fi]);
fi++;
}
fi=0;
}
fclose(f);
return matrix;
}
Hypercube readKernels(int w, int h, int ch, int k, char fileName[])
{
FILE *f;
f = fopen(fileName, "r");
if(f==NULL)
{
printf("I can not read the file %s\n", fileName);
exit(0);
}
int fi = 0;
int linesize = w*h;
int kernelsize = linesize*ch;
Hypercube matrix = (Hypercube)malloc(k * sizeof(Cube));
for(int i = 0; i < k; i++)
{
matrix[i] = (Cube)malloc(kernelsize * sizeof(Matrix));
for(int j=0; j< ch; j++)
{
matrix[i][j] = (Matrix)malloc(linesize * sizeof(float));
while(!feof(f) && fi<linesize)
{
fscanf(f, "%f", &matrix[i][j][fi]);
fi++;
}
fi=0;
}
}
fclose(f);
return matrix;
}
void readFile(float result[], char fileName[])
{
FILE *f;
f = fopen(fileName, "r");
if(f == NULL)
{
printf("I can not read the file %s\n", fileName);
exit(0);
}
int i = 0;
while(!feof(f))
{
fscanf(f, "%f", &result[i]);
i++;
}
fclose(f);
}
/* FILENAMES FUNCTIONS */
void generateNameAT(char* at, int m, int r){
at[0] = 'A';
at[1] = 'T';
at[2] = m + '0';
at[3] = 'x';
at[4] = r + '0';
at[5] = '.';
at[6] = 't';
at[7] = 'x';
at[8] = 't';
at[9] = '\0';
}
void generateNameG(char* g, int m, int r){
g[0] = 'G';
g[1] = m + '0';
g[2] = 'x';
g[3] = r + '0';
g[4] = '.';
g[5] = 't';
g[6] = 'x';
g[7] = 't';
g[8] = '\0';
}
void generateNameBT(char* g, int m, int r){
g[0] = 'B';
g[1] = 'T';
g[2] = m + '0';
g[3] = 'x';
g[4] = r + '0';
g[5] = '.';
g[6] = 't';
g[7] = 'x';
g[8] = 't';
g[9] = '\0';
}
| {
"alphanum_fraction": 0.6048100574,
"avg_line_length": 24.7787810384,
"ext": "c",
"hexsha": "292c9745ba023fe13dbcb8857ce8fba7b35813d2",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2022-02-18T09:57:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-03-15T14:49:21.000Z",
"max_forks_repo_head_hexsha": "3a7bc4a45280248c521d2ce8dde8b300d29aab79",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "whcjimmy/winograd-convolutional-nn",
"max_forks_repo_path": "main.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "3a7bc4a45280248c521d2ce8dde8b300d29aab79",
"max_issues_repo_issues_event_max_datetime": "2019-12-26T06:42:43.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-26T06:28:59.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "whcjimmy/winograd-convolutional-nn",
"max_issues_repo_path": "main.c",
"max_line_length": 116,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "3a7bc4a45280248c521d2ce8dde8b300d29aab79",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "whcjimmy/winograd-convolutional-nn",
"max_stars_repo_path": "main.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-16T13:19:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-07-16T01:17:39.000Z",
"num_tokens": 3564,
"size": 10977
} |
/*
NAME:
proj_gauss_mixtures_IDL
PURPOSE:
run the projected gaussian mixtures algorithm from IDL (or python)
CALLING SEQUENCE:
see IDL wrapper
INPUT:
from IDL wrapper
OUTPUT:
updated model gaussians and average loglikelihood, see IDL WRAPPER
REVISION HISTORY:
2008-09-21 - Written Bovy
2010-03-01 Added noproj option - Bovy
2010-04-01 Added noweight option and logweights - Bovy
*/
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <proj_gauss_mixtures.h>
int proj_gauss_mixtures_IDL(double * ydata, double * ycovar,
double * projection, double * logweights,
int N, int dy,
double * amp, double * xmean,
double * xcovar, int d, int K,
char * fixamp, char * fixmean,
char * fixcovar,
double * avgloglikedata, double tol,
int maxiter, char likeonly, double w,
char * logfilename, int slen, int splitnmerge,
char * convlogfilename, int convloglen,
char noprojection,char diagerrors,
char noweights){
//Set up logfiles
bool keeplog = true;
char logname[slen+1];
char convlogname[convloglen+1];
int ss;
if (*logfilename == 0 || likeonly != 0 || slen == 0)
keeplog = false;
else {
for (ss = 0; ss != slen; ++ss)
logname[ss] = (char) *(logfilename++);
for (ss = 0; ss != convloglen; ++ss)
convlogname[ss] = (char) *(convlogfilename++);
logfilename -= slen;
convlogfilename -= convloglen;
logname[slen] = '\0';
convlogname[convloglen] = '\0';
}
if (keeplog) {
logfile = fopen(logname,"a");
if (logfile == NULL) return -1;
convlogfile = fopen(convlogname,"w");
if (convlogfile == NULL) return -1;
}
if (keeplog){
time_t now;
time(&now);
fprintf(logfile,"#----------------------------------\n");
fprintf(logfile,"#\n#%s\n",asctime(localtime(&now)));
fprintf(logfile,"#----------------------------------\n");
fflush(logfile);
}
//Copy everything into the right formats
struct datapoint * data = (struct datapoint *) malloc( N * sizeof (struct datapoint) );
struct gaussian * gaussians = (struct gaussian *) malloc (K * sizeof (struct gaussian) );
bool noproj= (bool) noprojection;
bool noweight= (bool) noweights;
bool diagerrs= (bool) diagerrors;
int ii, jj,dd1,dd2;
for (ii = 0; ii != N; ++ii){
data->ww = gsl_vector_alloc(dy);
if ( ! noweight ) data->logweight = *(logweights++);
if ( diagerrs ) data->SS = gsl_matrix_alloc(dy,1);
else data->SS = gsl_matrix_alloc(dy,dy);
if ( ! noproj ) data->RR = gsl_matrix_alloc(dy,d);
for (dd1 = 0; dd1 != dy;++dd1)
gsl_vector_set(data->ww,dd1,*(ydata++));
if ( diagerrs)
for (dd1 = 0; dd1 != dy; ++dd1)
gsl_matrix_set(data->SS,dd1,0,*(ycovar++));
else
for (dd1 = 0; dd1 != dy; ++dd1)
for (dd2 = 0; dd2 != dy; ++dd2)
gsl_matrix_set(data->SS,dd1,dd2,*(ycovar++));
if ( ! noproj )
for (dd1 = 0; dd1 != dy; ++dd1)
for (dd2 = 0; dd2 != d; ++dd2)
gsl_matrix_set(data->RR,dd1,dd2,*(projection++));
else data->RR= NULL;
++data;
}
data -= N;
ydata -= N*dy;
if ( diagerrs ) ycovar -= N*dy;
else ycovar -= N*dy*dy;
if ( ! noproj ) projection -= N*dy*d;
for (jj = 0; jj != K; ++jj){
gaussians->mm = gsl_vector_alloc(d);
gaussians->VV = gsl_matrix_alloc(d,d);
gaussians->alpha = *(amp++);
for (dd1 = 0; dd1 != d; ++dd1)
gsl_vector_set(gaussians->mm,dd1,*(xmean++));
for (dd1 = 0; dd1 != d; ++dd1)
for (dd2 = 0; dd2 != d; ++dd2)
gsl_matrix_set(gaussians->VV,dd1,dd2,*(xcovar++));
++gaussians;
}
gaussians -= K;
amp -= K;
xmean -= K*d;
xcovar -= K*d*d;
//Print the initial model parameters to the logfile
int kk;
if (keeplog){
fprintf(logfile,"#\n#Using %i Gaussians and w = %f\n\n",K,w);
fprintf(logfile,"#\n#Initial model parameters used:\n\n");
for (kk=0; kk != K; ++kk){
fprintf(logfile,"#Gaussian ");
fprintf(logfile,"%i",kk);
fprintf(logfile,"\n");
fprintf(logfile,"#amp\t=\t");
fprintf(logfile,"%f",(*gaussians).alpha);
fprintf(logfile,"\n");
fprintf(logfile,"#mean\t=\t");
for (dd1=0; dd1 != d; ++dd1){
fprintf(logfile,"%f",gsl_vector_get(gaussians->mm,dd1));
if (dd1 < d-1) fprintf(logfile,"\t");
}
fprintf(logfile,"\n");
fprintf(logfile,"#covar\t=\t");
for (dd1=0; dd1 != d; ++dd1)
fprintf(logfile,"%f\t",gsl_matrix_get(gaussians->VV,dd1,dd1));
for (dd1=0; dd1 != d-1; ++dd1)
for (dd2=dd1+1; dd2 != d; ++dd2){
fprintf(logfile,"%f\t",gsl_matrix_get(gaussians->VV,dd1,dd2));
}
++gaussians;
fprintf(logfile,"\n#\n");
}
gaussians -= K;
fflush(logfile);
}
//Then run projected_gauss_mixtures
proj_gauss_mixtures(data,N,gaussians,K,(bool *) fixamp,
(bool *) fixmean, (bool *) fixcovar,avgloglikedata,
tol,(long long int) maxiter, (bool) likeonly, w,
splitnmerge,keeplog,logfile,convlogfile,noproj,diagerrs,
noweight);
//Print the final model parameters to the logfile
if (keeplog){
fprintf(logfile,"\n#Final model parameters obtained:\n\n");
for (kk=0; kk != K; ++kk){
fprintf(logfile,"#Gaussian ");
fprintf(logfile,"%i",kk);
fprintf(logfile,"\n");
fprintf(logfile,"#amp\t=\t");
fprintf(logfile,"%f",(*gaussians).alpha);
fprintf(logfile,"\n");
fprintf(logfile,"#mean\t=\t");
for (dd1=0; dd1 != d; ++dd1){
fprintf(logfile,"%f",gsl_vector_get(gaussians->mm,dd1));
if (dd1 < d-1) fprintf(logfile,"\t");
}
fprintf(logfile,"\n");
fprintf(logfile,"#covar\t=\t");
for (dd1=0; dd1 != d; ++dd1)
fprintf(logfile,"%f\t",gsl_matrix_get(gaussians->VV,dd1,dd1));
for (dd1=0; dd1 != d-1; ++dd1)
for (dd2=dd1+1; dd2 != d; ++dd2){
fprintf(logfile,"%f\t",gsl_matrix_get(gaussians->VV,dd1,dd2));
}
++gaussians;
fprintf(logfile,"\n#\n");
}
gaussians -= K;
fflush(logfile);
}
//Then update the arrays given to us by IDL
for (jj = 0; jj != K; ++jj){
*(amp++) = gaussians->alpha;
for (dd1 = 0; dd1 != d; ++dd1)
*(xmean++) = gsl_vector_get(gaussians->mm,dd1);
for (dd1 = 0; dd1 != d; ++dd1)
for (dd2 = 0; dd2 != d; ++dd2)
*(xcovar++) = gsl_matrix_get(gaussians->VV,dd1,dd2);
++gaussians;
}
gaussians -= K;
amp -= K;
xmean -= K*d;
xcovar -= K*d*d;
//And free any memory we allocated
for (ii = 0; ii != N; ++ii){
gsl_vector_free(data->ww);
gsl_matrix_free(data->SS);
if ( ! noproj ) gsl_matrix_free(data->RR);
++data;
}
data -= N;
free(data);
for (jj = 0; jj != K; ++jj){
gsl_vector_free(gaussians->mm);
gsl_matrix_free(gaussians->VV);
++gaussians;
}
gaussians -= K;
free(gaussians);
if (keeplog){
fclose(logfile);
fclose(convlogfile);
}
return 0;
}
| {
"alphanum_fraction": 0.5799251152,
"avg_line_length": 29.0543933054,
"ext": "c",
"hexsha": "fa0e5897c309d9794551a2db1a2d829630f1c782",
"lang": "C",
"max_forks_count": 26,
"max_forks_repo_forks_event_max_datetime": "2021-12-13T03:37:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-05T22:21:22.000Z",
"max_forks_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution",
"max_forks_repo_path": "src/proj_gauss_mixtures_IDL.c",
"max_issues_count": 24,
"max_issues_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780",
"max_issues_repo_issues_event_max_datetime": "2021-11-19T01:01:22.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-07T01:42:22.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution",
"max_issues_repo_path": "src/proj_gauss_mixtures_IDL.c",
"max_line_length": 91,
"max_stars_count": 73,
"max_stars_repo_head_hexsha": "bc6d58199b17cd5329d72f6af3c7ba7e6d2ae780",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "HaifengWangNAOC/Learn-Bovy-Extreme-deconvolution",
"max_stars_repo_path": "src/proj_gauss_mixtures_IDL.c",
"max_stars_repo_stars_event_max_datetime": "2022-01-21T01:27:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-22T09:22:38.000Z",
"num_tokens": 2313,
"size": 6944
} |
/**
* @copyright (c) 2017 King Abdullah University of Science and Technology (KAUST).
* All rights reserved.
**/
/**
* @file codelet_zhagdm.c
*
* Codelet for generating dense matrix from a problem determined according to current global setting of HiCMA library.
*
* HiCMA is a software package provided by King Abdullah University of Science and Technology (KAUST)
*
* @version 0.1.1
* @author Kadir Akbudak
* @date 2018-11-08
**/
#include "morse.h"
#include "runtime/starpu/chameleon_starpu.h"
#include "runtime/starpu/runtime_codelets.h"
ZCODELETS_HEADER(hagdm)
#include <assert.h>
#include <stdio.h>
#include <sys/time.h>//FIXME for gettimeofday
#include "hicma.h"
#include "starsh.h"
#include "starsh-spatial.h"
#include "starsh-randtlr.h"
#ifdef MKL
#include <mkl.h>
#include <mkl_lapack.h>
//#pragma message("MKL is used")
#else
#ifdef ARMPL
#include <armpl.h>
#else
#include <cblas.h>
#endif
#ifdef LAPACKE_UTILS
#include <lapacke_utils.h>
#endif
#include <lapacke.h>
//#pragma message("MKL is NOT used")
#endif
//#warning "An experimental feature is enabled!!!"
extern int steal_lrtile;
extern void _printmat(double * A, int m, int n, int ld);
void zhagdm(
int nrows_Dense,
int ncols_Dense,
double *Dense,
int ld_Dense,
int tile_row_index,
int tile_col_index,
int A_mt
)
{
if(steal_lrtile == 1 && tile_row_index == tile_col_index){
if(tile_row_index == A_mt-1) { // steal tile above
tile_row_index -= 1;
} else { // still tile below
tile_row_index += 1;
}
}
struct timeval tvalBefore, tvalAfter;
gettimeofday (&tvalBefore, NULL);
STARSH_cluster *RC = HICMA_get_starsh_format()->row_cluster, *CC = RC;
void *RD = RC->data, *CD = RD;
HICMA_get_starsh_format()->problem->kernel(nrows_Dense, ncols_Dense,
RC->pivot+RC->start[tile_row_index],
CC->pivot+CC->start[tile_col_index],
RD, CD, Dense, ld_Dense);
}
/**
* HICMA_TASK_zhagdm - Generate dense matrix from a problem determined according to current global setting of HiCMA library
*/
void HICMA_TASK_zhagdm( const MORSE_option_t *options,
int nrows_Dense, int ncols_Dense,
const MORSE_desc_t *Dense,
int ld_Dense,
int tile_row_index,
int tile_col_index,
int A_mt
)
{
struct starpu_codelet *codelet = &cl_zhagdm;
void (*callback)(void*) = NULL;
MORSE_BEGIN_ACCESS_DECLARATION;
MORSE_ACCESS_W(Dense, tile_row_index, tile_col_index);
MORSE_END_ACCESS_DECLARATION;
starpu_insert_task(
starpu_mpi_codelet(codelet),
STARPU_VALUE, &nrows_Dense, sizeof(int),
STARPU_VALUE, &ncols_Dense, sizeof(int),
STARPU_W, RTBLKADDR(Dense, double, tile_row_index, tile_col_index),
STARPU_VALUE, &ld_Dense, sizeof(int),
STARPU_VALUE, &tile_row_index, sizeof(int),
STARPU_VALUE, &tile_col_index, sizeof(int),
STARPU_VALUE, &A_mt, sizeof(int),
STARPU_PRIORITY, options->priority,
STARPU_CALLBACK, callback,
#if defined(CHAMELEON_CODELETS_HAVE_NAME)
STARPU_NAME, "zhagdm",
#endif
0);
}
/**
* cl_zhagdm_cpu_func - Generate a tile for random matrix.
*/
#if !defined(CHAMELEON_SIMULATION)
static void cl_zhagdm_cpu_func(void *descr[], void *cl_arg)
{
int nrows_Dense;
int ncols_Dense;
int ld_Dense;
int tile_row_index;
int tile_col_index;
int A_mt;
int maxrank;
double *Dense;
Dense = (double *)STARPU_MATRIX_GET_PTR(descr[0]);
starpu_codelet_unpack_args(cl_arg, &nrows_Dense, &ncols_Dense, &ld_Dense, &tile_row_index, &tile_col_index, &A_mt);
zhagdm(
nrows_Dense,
ncols_Dense,
Dense,
ld_Dense,
tile_row_index,
tile_col_index,
A_mt
);
}
#endif /* !defined(CHAMELEON_SIMULATION) */
/*
* Codelet definition
*/
CODELETS_CPU(zhagdm, 1, cl_zhagdm_cpu_func)
ZCODELETS_HEADER(hagdmi)
/**
* HICMA_TASK_zhagdmi - Generate dense matrix from a problem determined according to current global setting of HiCMA library
* This function takes indices of tiles of problem.
*/
void HICMA_TASK_zhagdmi( const MORSE_option_t *options,
int nrows_Dense, int ncols_Dense,
const MORSE_desc_t *Dense,
int ld_Dense,
int tile_row_index,
int tile_col_index,
int problem_row_index,
int problem_col_index
)
{
struct starpu_codelet *codelet = &cl_zhagdmi;
void (*callback)(void*) = NULL;
MORSE_BEGIN_ACCESS_DECLARATION;
MORSE_ACCESS_W(Dense, tile_row_index, tile_col_index);
MORSE_END_ACCESS_DECLARATION;
starpu_insert_task(
starpu_mpi_codelet(codelet),
STARPU_VALUE, &nrows_Dense, sizeof(int),
STARPU_VALUE, &ncols_Dense, sizeof(int),
STARPU_W, RTBLKADDR(Dense, double, tile_row_index, tile_col_index),
STARPU_VALUE, &ld_Dense, sizeof(int),
STARPU_VALUE, &tile_row_index, sizeof(int),
STARPU_VALUE, &tile_col_index, sizeof(int),
STARPU_VALUE, &problem_row_index, sizeof(int),
STARPU_VALUE, &problem_col_index, sizeof(int),
STARPU_PRIORITY, options->priority,
STARPU_CALLBACK, callback,
#if defined(CHAMELEON_CODELETS_HAVE_NAME)
STARPU_NAME, "zhagdm",
#endif
0);
}
/** cl_zhagdm_cpu_func - Generate a tile for random matrix.
* This function takes indices of tiles of problem.
*/
#if !defined(CHAMELEON_SIMULATION)
static void cl_zhagdmi_cpu_func(void *descr[], void *cl_arg)
{
int nrows_Dense;
int ncols_Dense;
int ld_Dense;
int tile_row_index;
int tile_col_index;
int maxrank;
double *Dense;
int problem_row_index;
int problem_col_index;
Dense = (double *)STARPU_MATRIX_GET_PTR(descr[0]);
starpu_codelet_unpack_args(cl_arg, &nrows_Dense, &ncols_Dense, &ld_Dense, &tile_row_index, &tile_col_index, &problem_row_index, &problem_col_index);
zhagdm(
nrows_Dense,
ncols_Dense,
Dense,
ld_Dense,
problem_row_index,
problem_col_index, -1
);
}
#endif /* !defined(CHAMELEON_SIMULATION) */
/*
* Codelet definition
*/
CODELETS_CPU(zhagdmi, 1, cl_zhagdmi_cpu_func)
| {
"alphanum_fraction": 0.6067094932,
"avg_line_length": 31.8409090909,
"ext": "c",
"hexsha": "224e7967559e13383a0b248d7fb26f79f6e1c7b8",
"lang": "C",
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T22:26:56.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-11-21T07:35:55.000Z",
"max_forks_repo_head_hexsha": "1807f9628df516d20d6265fdf0573c9bc9bf033b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "SamCao1991/hicma",
"max_forks_repo_path": "runtime/starpu/codelets/codelet_zhagdm.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "1807f9628df516d20d6265fdf0573c9bc9bf033b",
"max_issues_repo_issues_event_max_datetime": "2020-06-27T07:44:31.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-01-21T12:24:22.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "SamCao1991/hicma",
"max_issues_repo_path": "runtime/starpu/codelets/codelet_zhagdm.c",
"max_line_length": 152,
"max_stars_count": 19,
"max_stars_repo_head_hexsha": "1807f9628df516d20d6265fdf0573c9bc9bf033b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "SamCao1991/hicma",
"max_stars_repo_path": "runtime/starpu/codelets/codelet_zhagdm.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T09:37:50.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-11-27T11:17:49.000Z",
"num_tokens": 1770,
"size": 7005
} |
/* linalg/test_cholesky.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.
*/
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_permute_vector.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_permutation.h>
static int test_choleskyc_decomp_eps(const gsl_matrix_complex * m, const double eps, const char * desc);
static int test_choleskyc_decomp(gsl_rng * r);
static int test_choleskyc_invert(gsl_rng * r);
static int
test_choleskyc_decomp_eps(const gsl_matrix_complex * m, const double eps, const char * desc)
{
int s = 0;
const size_t M = m->size1;
const size_t N = m->size2;
size_t i, j;
gsl_matrix_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);
gsl_test_rel(GSL_REAL(aij), GSL_REAL(mij), eps,
"%s: real (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, GSL_REAL(aij), GSL_REAL(mij));
gsl_test_rel(GSL_IMAG(aij), GSL_IMAG(mij), eps,
"%s: imag (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, GSL_IMAG(aij), GSL_IMAG(mij));
}
}
gsl_matrix_complex_free(v);
gsl_matrix_complex_free(a);
gsl_matrix_complex_free(l);
gsl_matrix_complex_free(lh);
return s;
}
static int
test_choleskyc_decomp(gsl_rng * r)
{
int s = 0;
const size_t N_max = 50;
size_t N;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix_complex * m = gsl_matrix_complex_alloc(N, N);
create_posdef_complex_matrix(m, r);
test_choleskyc_decomp_eps(m, 1.0e6 * N * GSL_DBL_EPSILON, "cholesky_complex_decomp random");
gsl_matrix_complex_free(m);
}
return s;
}
static int
test_choleskyc_invert_eps(const gsl_matrix_complex * m, const double eps, const char * desc)
{
int s = 0;
const size_t N = m->size1;
size_t i, j;
gsl_matrix_complex * v = gsl_matrix_complex_alloc(N, N);
gsl_matrix_complex * c = gsl_matrix_complex_alloc(N, N);
gsl_matrix_complex_memcpy(v, m);
s += gsl_linalg_complex_cholesky_decomp(v);
s += gsl_linalg_complex_cholesky_invert(v);
gsl_blas_zhemm(CblasLeft, CblasUpper, GSL_COMPLEX_ONE, m, v, GSL_COMPLEX_ZERO, c);
/* c should be the identity matrix */
for (i = 0; i < N; ++i)
{
for (j = 0; j < N; ++j)
{
gsl_complex cij = gsl_matrix_complex_get(c, i, j);
double expected = (i == j) ? 1.0 : 0.0;
/* check real part */
gsl_test_rel(GSL_REAL(cij), expected, eps,
"%s: real (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, GSL_REAL(cij), expected);
/* check imaginary part */
gsl_test_rel(GSL_IMAG(cij), 0.0, eps,
"%s: imag (%3lu,%3lu)[%lu,%lu]: %22.18g %22.18g\n",
desc, N, N, i, j, GSL_IMAG(cij), 0.0);
}
}
gsl_matrix_complex_free(v);
gsl_matrix_complex_free(c);
return s;
}
static int
test_choleskyc_invert(gsl_rng * r)
{
int s = 0;
const size_t N_max = 50;
size_t N;
for (N = 1; N <= N_max; ++N)
{
gsl_matrix_complex * m = gsl_matrix_complex_alloc(N, N);
create_posdef_complex_matrix(m, r);
test_choleskyc_invert_eps(m, 32.0 * N * GSL_DBL_EPSILON, "cholesky_complex_invert random");
gsl_matrix_complex_free(m);
}
return s;
}
| {
"alphanum_fraction": 0.6211917992,
"avg_line_length": 28.8342541436,
"ext": "c",
"hexsha": "23d39ffb2b7e4f1364262b48da5a83b307dddbab",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "83fd1fc4cbd053a4f9b673d5cd5841823ddd4d8b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "karanbirsandhu/nu-sense",
"max_forks_repo_path": "test/lib/gsl-2.6/linalg/test_choleskyc.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/linalg/test_choleskyc.c",
"max_line_length": 104,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/linalg/test_choleskyc.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": 1552,
"size": 5219
} |
// SPDX-License-Identifier: MIT
// The MIT License (MIT)
//
// Copyright (c) 2014-2018, Institute for Software & Systems Engineering
// Copyright (c) 2018-2019, Johannes Leupolz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef PEMC_EXECUTABLE_MODEL_ABSTRACT_MODEL_H_
#define PEMC_EXECUTABLE_MODEL_ABSTRACT_MODEL_H_
#include <vector>
#include <gsl/span>
#include <gsl/gsl_byte>
#include <cstdint>
#include <atomic>
#include <stack>
#include <limits>
#include <functional>
#include "pemc/basic/tsc_index.h"
#include "pemc/basic/label.h"
#include "pemc/basic/model_capacity.h"
#include "pemc/basic/probability.h"
#include "pemc/basic/raw_memory.h"
#include "pemc/formula/formula.h"
#include "pemc/generic_traverser/i_transitions_calculator.h"
#include "pemc/generic_traverser/i_pre_state_storage_modifier.h"
#include "pemc/generic_traverser/i_post_state_storage_modifier.h"
#include "pemc/executable_model/i_choice_resolver.h"
namespace pemc {
class AbstractModel {
protected:
IChoiceResolver* choiceResolver = nullptr;
std::vector<std::function<bool()>> formulaEvaluators;
public:
AbstractModel() {}
virtual ~AbstractModel() {}
//AbstractModel(const AbstractModel&) = delete;
void setChoiceResolver(IChoiceResolver* _choiceResolver);
virtual void serialize(gsl::span<gsl::byte> position) {}
virtual void deserialize(gsl::span<gsl::byte> position) {}
virtual void setFormulasForLabel(const std::vector<std::shared_ptr<Formula>>& _formulas) {}
Label calculateLabel();
size_t choose(const gsl::span<Probability>& choices);
size_t choose(size_t numberOfChoices);
virtual void resetToInitialState() {}
virtual void step() {}
virtual int32_t getStateVectorSize() {return 0;}
};
}
#endif // PEMC_EXECUTABLE_MODEL_ABSTRACT_MODEL_H_
| {
"alphanum_fraction": 0.7507831535,
"avg_line_length": 34.2023809524,
"ext": "h",
"hexsha": "3a17b85947facbea18d2929ae018a2529e74feb0",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "joleuger/pemc",
"max_forks_repo_path": "pemc/executable_model/abstract_model.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "joleuger/pemc",
"max_issues_repo_path": "pemc/executable_model/abstract_model.h",
"max_line_length": 97,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "14deb5b97d4219ba3c92d3834ab71332997e9b13",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "joleuger/pemc",
"max_stars_repo_path": "pemc/executable_model/abstract_model.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 665,
"size": 2873
} |
#ifndef BIO_MATRIX_DEPENDENCIES_H_
#define BIO_MATRIX_DEPENDENCIES_H_
#include "bio/defs.h"
#include "bio/matrix.h"
#include "bio/contingency_homogeneity.h"
#include <boost/array.hpp>
#include <gsl/gsl_math.h>
#include <vector>
#include <numeric>
#include <set>
BIO_NS_START
/** Indexes a pair of bases for comparison. */
struct BasePair
{
/** The index of the base we wish to analyse. */
unsigned observed_index;
/** The index of the base we condition on. */
unsigned conditioned_index;
BasePair(unsigned observed_index, unsigned conditioned_index);
bool operator<(const BasePair & rhs) const;
};
std::ostream &
operator<<(std::ostream & os, const BasePair & base_pair);
/** A contingency table to compare a pair of bases. */
typedef ContingencyTable<4, 4> base_pair_contingency_table_t;
/** The contingency tables for all base pairs in a pssm. */
typedef std::map<BasePair, base_pair_contingency_table_t> pssm_contingency_tables_t;
/** The results of analysing the dependencies between a pair of bases. */
struct BasePairDependencyResults
{
double homogeneity_bayes_factor;
};
/** The results of the dependencies between all base pairs in a pssm. */
typedef std::map< BasePair, BasePairDependencyResults > pssm_dependency_results_t;
/** An iterator pointing to a result. */
typedef pssm_dependency_results_t::const_iterator pssm_dependency_result_it;
/** A less than operator that lets us sort by scores. */
struct HomogeneityLessThen
{
bool operator()(pssm_dependency_result_it lhs, pssm_dependency_result_it rhs) const;
};
/** An ordered set of results. */
typedef std::set< pssm_dependency_result_it, HomogeneityLessThen > pssm_dependency_result_set;
/** Contains all the sequences that were used to compose a Pssm. Indexed first by position then by sequence number. */
typedef std::vector< std::vector<char> > pssm_source_matrix_t;
typedef boost::shared_ptr< pssm_source_matrix_t > pssm_source_matrix_ptr_t;
typedef std::map< TableLink, pssm_source_matrix_ptr_t > pssm_source_map_t;
std::ostream &
operator<<(std::ostream & os, pssm_source_map_t::value_type value);
void
build_all_pssm_sources(pssm_source_map_t & pssm_source_map);
/** Take a Transfac matrix and generate a matrix from the sequences that defined it. */
void
build_pssm_source(
const Matrix * matrix,
pssm_source_matrix_t & pssm_source);
/** Adds a sequence to a pssm source. */
void
add_sequence_to_pssm_source(
const seq_t & sequence,
pssm_source_matrix_t & pssm_source);
/** Count the conditional frequencies in a matrix and generate contingency tables. */
void
count_frequencies(
const pssm_source_matrix_t & pssm_source,
pssm_contingency_tables_t & contingency_tables);
/** Calculate the dependencies in all the contingency tables. */
void
calculate_dependencies(
pssm_contingency_tables_t & contingency_tables,
pssm_dependency_results_t & results);
/** Build an ordered set of results. */
void
build_result_set(
pssm_dependency_results_t & results,
pssm_dependency_result_set & result_set);
struct MatrixDependencies
{
pssm_source_matrix_t pssm_source;
pssm_contingency_tables_t contingency_tables;
pssm_dependency_results_t results;
pssm_dependency_result_set result_set;
MatrixDependencies(const pssm_source_matrix_t & pssm_source);
MatrixDependencies(const Matrix * matrix);
MatrixDependencies();
};
typedef std::map<const Matrix *, MatrixDependencies> matrix_dependencies_map_t;
BIO_NS_END
#endif //BIO_MATRIX_DEPENDENCIES_H_
| {
"alphanum_fraction": 0.7904899135,
"avg_line_length": 27.3228346457,
"ext": "h",
"hexsha": "1700e32c8d672a9f96fcc4ce36883b3b9716f334",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JohnReid/biopsy",
"max_forks_repo_path": "C++/include/bio/matrix_dependencies.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "JohnReid/biopsy",
"max_issues_repo_path": "C++/include/bio/matrix_dependencies.h",
"max_line_length": 118,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1eeb714ba5b53f2ecf776d865d32e2078cbc0338",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JohnReid/biopsy",
"max_stars_repo_path": "C++/include/bio/matrix_dependencies.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 829,
"size": 3470
} |
/* Copyright 2016 by
Laboratoire d'Informatique de Paris 6 - Équipe PEQUAN
Sorbonne Universités
UPMC Univ Paris 06
UMR 7606, LIP6
4, place Jussieu
F-75252 Paris Cedex 05
France
Laboratoire d'Informatique de Paris 6, equipe PEQUAN,
UPMC Universite Paris 06 - CNRS - UMR 7606 - LIP6, Paris, France
Contributors:
Anastasia Volkova anastasia.volkova@lip6.fr
This software is a mathematical library whose purpose is to provide
functions to compute the Worst-Case Peak Gain measure of Linear
Time-Invariant Digital Filters.
This software is governed by the CeCILL-C 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-C
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 author, the holder 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-C license and that you accept its terms.
This program is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifndef SRC_LIB_CLAPACK_FUNCTIONS_CONFIG_H_
#define SRC_LIB_CLAPACK_FUNCTIONS_CONFIG_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#include "config.h"
#include "aux_funcs.h"
#include <f2c.h>
#ifdef CLAPACK_HEADER
#include <clapack.h>
#endif
#ifdef LAPACK_HEADER
#include <lapack.h>
#endif
#ifdef LAPACKE_HEADER
#include <lapacke.h>
#endif
#ifdef BLAS_HEADER
#include <blas.h>
#endif
#ifdef CBLAS_HEADER
#include <cblas.h>
#endif
#ifdef BLASWRAP_HEADER
#include <blaswrap.h>
#endif
#include <complex.h>
typedef struct complexdouble
{
double r;
double i;
}complexdouble;
#define doublereal double
#define lapack_int int
#define integer long int
#define lapacke_complex double _Complex
void my_zgetrf(int *m, int *n, complexdouble *A,
int *lda, int *ipiv, int *info);
void my_zgetri(int *n, complexdouble *A, int *lda,
int *ipiv, complexdouble *work, int *lwork, int *info);
void my_dgeevx(int* n, double *A, int* lda, double *wr, double *wi, double *vl,
int* ldvl, double *vr, int* ldvr, int *ilo, int *ihi,
double *scale, double *abnrm, double *rconde, double *rcondv,
double *work, int *lwork, long int *iwork, int *info);
#ifdef __cplusplus
}
#endif
#endif /* SRC_LIB_CLAPACK_FUNCTIONS_CONFIG_H_ */
| {
"alphanum_fraction": 0.7510180337,
"avg_line_length": 27.7258064516,
"ext": "h",
"hexsha": "7e9796212ffbed357d1aeb8637e7dba8eea1e2fb",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-07-20T10:25:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-09T22:20:03.000Z",
"max_forks_repo_head_hexsha": "b90253a4a6a650300454f5656a7e8410e0493175",
"max_forks_repo_licenses": [
"CECILL-B"
],
"max_forks_repo_name": "remi-garcia/WCPG",
"max_forks_repo_path": "WCPG/clapack_functions_config.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "b90253a4a6a650300454f5656a7e8410e0493175",
"max_issues_repo_issues_event_max_datetime": "2018-08-16T00:47:56.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-08-16T00:47:20.000Z",
"max_issues_repo_licenses": [
"CECILL-B"
],
"max_issues_repo_name": "remi-garcia/WCPG",
"max_issues_repo_path": "WCPG/clapack_functions_config.h",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "b90253a4a6a650300454f5656a7e8410e0493175",
"max_stars_repo_licenses": [
"CECILL-B"
],
"max_stars_repo_name": "remi-garcia/WCPG",
"max_stars_repo_path": "WCPG/clapack_functions_config.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 903,
"size": 3438
} |
/* linalg/qr_ur.c
*
* Copyright (C) 2019, 2020 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
/*
* this module contains routines for the QR factorization of a matrix
* using the recursive Level 3 BLAS algorithm of Elmroth and Gustavson with
* additional modifications courtesy of Julien Langou.
*/
static double qrtr_householder_transform (double *v0, gsl_vector * v);
/*
gsl_linalg_QR_UR_decomp()
Compute the QR decomposition of the "triangle on top of rectangle" matrix
[ S ] = Q [ R ]
[ A ] [ 0 ]
where S is N-by-N upper triangular and A is M-by-N dense.
Inputs: S - on input, upper triangular N-by-N matrix
on output, R factor in upper triangle
A - on input, dense M-by-N matrix
on output, Householder matrix V
T - (output) block reflector matrix, N-by-N
Notes:
1) Based on the Elmroth/Gustavson algorithm, taking into account the
sparse structure of the S matrix
2) The Householder matrix V has the special form:
N
V = [ I ] N
[ V~ ] M
The matrix V~ is stored in A on output; the identity is not stored
3) The orthogonal matrix is
Q = I - V T V^T
*/
int
gsl_linalg_QR_UR_decomp (gsl_matrix * S, gsl_matrix * A, gsl_matrix * T)
{
const size_t M = A->size1;
const size_t N = S->size1;
if (N != S->size2)
{
GSL_ERROR ("S matrix must be square", GSL_ENOTSQR);
}
else if (N != A->size2)
{
GSL_ERROR ("S and A have different number of columns", GSL_EBADLEN);
}
else if (T->size1 != N || T->size2 != N)
{
GSL_ERROR ("T matrix has wrong dimensions", GSL_EBADLEN);
}
else if (N == 1)
{
/* base case, compute Householder transform for single column matrix */
double * T00 = gsl_matrix_ptr(T, 0, 0);
double * S00 = gsl_matrix_ptr(S, 0, 0);
gsl_vector_view v = gsl_matrix_column(A, 0);
*T00 = qrtr_householder_transform(S00, &v.vector);
return GSL_SUCCESS;
}
else
{
/*
* partition matrices:
*
* N1 N2 N1 N2
* N1 [ S11 S12 ] and N1 [ T11 T12 ]
* N2 [ 0 S22 ] N2 [ 0 T22 ]
* M [ A1 A2 ]
*/
int status;
const size_t N1 = N / 2;
const size_t N2 = N - N1;
gsl_matrix_view S11 = gsl_matrix_submatrix(S, 0, 0, N1, N1);
gsl_matrix_view S12 = gsl_matrix_submatrix(S, 0, N1, N1, N2);
gsl_matrix_view S22 = gsl_matrix_submatrix(S, N1, N1, N2, N2);
gsl_matrix_view A1 = gsl_matrix_submatrix(A, 0, 0, M, N1);
gsl_matrix_view A2 = gsl_matrix_submatrix(A, 0, N1, M, N2);
gsl_matrix_view T11 = gsl_matrix_submatrix(T, 0, 0, N1, N1);
gsl_matrix_view T12 = gsl_matrix_submatrix(T, 0, N1, N1, N2);
gsl_matrix_view T22 = gsl_matrix_submatrix(T, N1, N1, N2, N2);
/*
* Eq. 2: recursively factor
*
* N1 N1
* N1 [ S11 ] = Q1 [ R11 ] N1
* N2 [ 0 ] [ 0 ] N2
* M [ A1 ] [ 0 ] M
*/
status = gsl_linalg_QR_UR_decomp(&S11.matrix, &A1.matrix, &T11.matrix);
if (status)
return status;
/*
* Eq. 3:
*
* N2 N2 N2
* N1 [ R12 ] = Q1^T [ S12 ] = [ S12 - W ] N1
* N2 [ S22~ ] [ S22 ] [ S22 ] N2
* M [ A2~ ] [ A2 ] [ A2 - V1~ W ] M
*
* where W = T11^T ( S12 + V1~^T A2 ), using T12 as temporary storage, and
*
* N1
* V1 = [ I ] N1
* [ 0 ] N2
* [ V1~ ] M
*/
gsl_matrix_memcpy(&T12.matrix, &S12.matrix); /* W := S12 */
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A1.matrix, &A2.matrix, 1.0, &T12.matrix); /* W := S12 + V1~^T A2 */
gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasTrans, CblasNonUnit, 1.0, &T11.matrix, &T12.matrix); /* W := T11^T W */
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, -1.0, &A1.matrix, &T12.matrix, 1.0, &A2.matrix); /* A2 := A2 - V1~ W */
gsl_matrix_sub(&S12.matrix, &T12.matrix); /* R12 := S12 - W */
/*
* Eq. 4: recursively factor
*
* [ S22~ ] = Q2~ [ R22 ]
* [ A2~ ] [ 0 ]
*/
status = gsl_linalg_QR_UR_decomp(&S22.matrix, &A2.matrix, &T22.matrix);
if (status)
return status;
/*
* Eq. 13: update T12 := -T11 * V1^T * V2 * T22
*
* where:
*
* N1 N2
* V1 = [ I ] N1 V2 = [ 0 ] N1
* [ 0 ] N2 [ I ] N2
* [ V1~ ] M [ V2~ ] M
*
* Note: V1^T V2 = V1~^T V2~
*/
gsl_blas_dgemm(CblasTrans, CblasNoTrans, 1.0, &A1.matrix, &A2.matrix, 0.0, &T12.matrix); /* T12 := V1~^T * V2~ */
gsl_blas_dtrmm(CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, -1.0, &T11.matrix, &T12.matrix); /* T12 := -T11 * T12 */
gsl_blas_dtrmm(CblasRight, CblasUpper, CblasNoTrans, CblasNonUnit, 1.0, &T22.matrix, &T12.matrix); /* T12 := T12 * T22 */
return GSL_SUCCESS;
}
}
/*
qrtr_householder_transform()
This routine is an optimized version of
gsl_linalg_householder_transform(), designed for the QR
decomposition of M-by-N matrices of the form:
B = [ S ]
[ A ]
where S is N-by-N upper triangular, and A is M-by-N dense.
This routine computes a householder transformation (tau,v) of a
x so that P x = [ I - tau*v*v' ] x annihilates x(1:n-1). x will
be a subcolumn of the matrix B, and so its structure will be:
x = [ x0 ] <- 1 nonzero value for the diagonal element of S
[ 0 ] <- N - j - 1 zeros, where j is column of matrix in [0,N-1]
[ x ] <- M nonzero values for the dense part A
Inputs: v0 - pointer to diagonal element of S
on input, v0 = x0;
v - on input, x vector
on output, householder vector v
*/
static double
qrtr_householder_transform (double *v0, gsl_vector * v)
{
/* replace v[0:M-1] with a householder vector (v[0:M-1]) and
coefficient tau that annihilate v[1:M-1] */
double alpha, beta, tau ;
/* compute xnorm = || [ 0 ; v ] ||, ignoring zero part of vector */
double xnorm = gsl_blas_dnrm2(v);
if (xnorm == 0)
{
return 0.0; /* tau = 0 */
}
alpha = *v0;
beta = - GSL_SIGN(alpha) * hypot(alpha, xnorm) ;
tau = (beta - alpha) / beta ;
{
double s = (alpha - beta);
if (fabs(s) > GSL_DBL_MIN)
{
gsl_blas_dscal (1.0 / s, v);
*v0 = beta;
}
else
{
gsl_blas_dscal (GSL_DBL_EPSILON / s, v);
gsl_blas_dscal (1.0 / GSL_DBL_EPSILON, v);
*v0 = beta;
}
}
return tau;
}
| {
"alphanum_fraction": 0.5632274094,
"avg_line_length": 30.95951417,
"ext": "c",
"hexsha": "71aa27b28f34736aff43cd60eacd5eac0ca222b7",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-02-14T12:31:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-20T16:22:57.000Z",
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ur.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ur.c",
"max_line_length": 129,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/linalg/qr_ur.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": 2477,
"size": 7647
} |
#ifndef __GSL_PERMUTE_VECTOR_H__
#define __GSL_PERMUTE_VECTOR_H__
#include <gsl/gsl_permute_vector_complex_long_double.h>
#include <gsl/gsl_permute_vector_complex_double.h>
#include <gsl/gsl_permute_vector_complex_float.h>
#include <gsl/gsl_permute_vector_long_double.h>
#include <gsl/gsl_permute_vector_double.h>
#include <gsl/gsl_permute_vector_float.h>
#include <gsl/gsl_permute_vector_ulong.h>
#include <gsl/gsl_permute_vector_long.h>
#include <gsl/gsl_permute_vector_uint.h>
#include <gsl/gsl_permute_vector_int.h>
#include <gsl/gsl_permute_vector_ushort.h>
#include <gsl/gsl_permute_vector_short.h>
#include <gsl/gsl_permute_vector_uchar.h>
#include <gsl/gsl_permute_vector_char.h>
#endif /* __GSL_PERMUTE_VECTOR_H__ */
| {
"alphanum_fraction": 0.8362892224,
"avg_line_length": 29.32,
"ext": "h",
"hexsha": "76265078630b7d116e29db2f73dca446f3220818",
"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": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ielomariala/Hex-Game",
"max_forks_repo_path": "gsl-2.6/gsl/gsl_permute_vector.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"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": "ielomariala/Hex-Game",
"max_issues_repo_path": "gsl-2.6/gsl/gsl_permute_vector.h",
"max_line_length": 55,
"max_stars_count": null,
"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/gsl/gsl_permute_vector.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 207,
"size": 733
} |
/* ieee-utils/env.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 <stdlib.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_errno.h>
void
gsl_ieee_env_setup (void)
{
const char * p = getenv("GSL_IEEE_MODE") ;
int precision = 0, rounding = 0, exception_mask = 0 ;
int comma = 0 ;
if (p == 0) /* GSL_IEEE_MODE environment variable is not set */
return ;
if (*p == '\0') /* GSL_IEEE_MODE environment variable is empty */
return ;
gsl_ieee_read_mode_string (p, &precision, &rounding, &exception_mask) ;
gsl_ieee_set_mode (precision, rounding, exception_mask) ;
fprintf(stderr, "GSL_IEEE_MODE=\"") ;
/* Print string with a preceeding comma if the list has already begun */
#define PRINTC(x) do {if(comma) fprintf(stderr,","); fprintf(stderr,x); comma++ ;} while(0)
switch (precision)
{
case GSL_IEEE_SINGLE_PRECISION:
PRINTC("single-precision") ;
break ;
case GSL_IEEE_DOUBLE_PRECISION:
PRINTC("double-precision") ;
break ;
case GSL_IEEE_EXTENDED_PRECISION:
PRINTC("extended-precision") ;
break ;
}
switch (rounding)
{
case GSL_IEEE_ROUND_TO_NEAREST:
PRINTC("round-to-nearest") ;
break ;
case GSL_IEEE_ROUND_DOWN:
PRINTC("round-down") ;
break ;
case GSL_IEEE_ROUND_UP:
PRINTC("round-up") ;
break ;
case GSL_IEEE_ROUND_TO_ZERO:
PRINTC("round-to-zero") ;
break ;
}
if ((exception_mask & GSL_IEEE_MASK_ALL) == GSL_IEEE_MASK_ALL)
{
PRINTC("mask-all") ;
}
else if ((exception_mask & GSL_IEEE_MASK_ALL) == 0)
{
PRINTC("trap-common") ;
}
else
{
if (exception_mask & GSL_IEEE_MASK_INVALID)
PRINTC("mask-invalid") ;
if (exception_mask & GSL_IEEE_MASK_DENORMALIZED)
PRINTC("mask-denormalized") ;
if (exception_mask & GSL_IEEE_MASK_DIVISION_BY_ZERO)
PRINTC("mask-division-by-zero") ;
if (exception_mask & GSL_IEEE_MASK_OVERFLOW)
PRINTC("mask-overflow") ;
if (exception_mask & GSL_IEEE_MASK_UNDERFLOW)
PRINTC("mask-underflow") ;
}
if (exception_mask & GSL_IEEE_TRAP_INEXACT)
PRINTC("trap-inexact") ;
fprintf(stderr,"\"\n") ;
}
| {
"alphanum_fraction": 0.6643073812,
"avg_line_length": 25.8,
"ext": "c",
"hexsha": "28eeb4997fe4baeb40857fda8dce4ac5127cd27f",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-02T01:32:59.000Z",
"max_forks_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "ICML14MoMCompare/spectral-learn",
"max_forks_repo_path": "code/em/treba/gsl-1.0/ieee-utils/env.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/ieee-utils/env.c",
"max_line_length": 91,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/ieee-utils/env.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": 802,
"size": 2967
} |
/* specfunc/bessel_Yn.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_psi.h>
#include <gsl/gsl_sf_bessel.h>
#include "error.h"
#include "bessel.h"
#include "bessel_amp_phase.h"
#include "bessel_olver.h"
/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/
/* assumes n >= 1 */
static int bessel_Yn_small_x(const int n, const double x, gsl_sf_result * result)
{
int k;
double y = 0.25 * x * x;
double ln_x_2 = log(0.5*x);
gsl_sf_result ln_nm1_fact;
double k_term;
double term1, sum1, ln_pre1;
double term2, sum2, pre2;
gsl_sf_lnfact_e((unsigned int)(n-1), &ln_nm1_fact);
ln_pre1 = -n*ln_x_2 + ln_nm1_fact.val;
if(ln_pre1 > GSL_LOG_DBL_MAX - 3.0) GSL_ERROR ("error", GSL_EOVRFLW);
sum1 = 1.0;
k_term = 1.0;
for(k=1; k<=n-1; k++) {
k_term *= y/(k * (n-k));
sum1 += k_term;
}
term1 = -exp(ln_pre1) * sum1 / M_PI;
pre2 = -exp(n*ln_x_2) / M_PI;
if(fabs(pre2) > 0.0) {
const int KMAX = 20;
gsl_sf_result psi_n;
gsl_sf_result npk_fact;
double yk = 1.0;
double k_fact = 1.0;
double psi_kp1 = -M_EULER;
double psi_npkp1;
gsl_sf_psi_int_e(n, &psi_n);
gsl_sf_fact_e((unsigned int)n, &npk_fact);
psi_npkp1 = psi_n.val + 1.0/n;
sum2 = (psi_kp1 + psi_npkp1 - 2.0*ln_x_2)/npk_fact.val;
for(k=1; k<KMAX; k++) {
psi_kp1 += 1./k;
psi_npkp1 += 1./(n+k);
k_fact *= k;
npk_fact.val *= n+k;
yk *= -y;
k_term = yk*(psi_kp1 + psi_npkp1 - 2.0*ln_x_2)/(k_fact*npk_fact.val);
sum2 += k_term;
}
term2 = pre2 * sum2;
}
else {
term2 = 0.0;
}
result->val = term1 + term2;
result->err = GSL_DBL_EPSILON * (fabs(ln_pre1)*fabs(term1) + fabs(term2));
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_SUCCESS;
}
/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/
int
gsl_sf_bessel_Yn_e(int n, const double x, gsl_sf_result * result)
{
int sign = 1;
if(n < 0) {
/* reduce to case n >= 0 */
n = -n;
if(GSL_IS_ODD(n)) sign = -1;
}
/* CHECK_POINTER(result) */
if(n == 0) {
int status = gsl_sf_bessel_Y0_e(x, result);
result->val *= sign;
return status;
}
else if(n == 1) {
int status = gsl_sf_bessel_Y1_e(x, result);
result->val *= sign;
return status;
}
else {
if(x <= 0.0) {
DOMAIN_ERROR(result);
}
if(x < 5.0) {
int status = bessel_Yn_small_x(n, x, result);
result->val *= sign;
return status;
}
else if(GSL_ROOT3_DBL_EPSILON * x > (n*n + 1.0)) {
int status = gsl_sf_bessel_Ynu_asympx_e((double)n, x, result);
result->val *= sign;
return status;
}
else if(n > 50) {
int status = gsl_sf_bessel_Ynu_asymp_Olver_e((double)n, x, result);
result->val *= sign;
return status;
}
else {
double two_over_x = 2.0/x;
gsl_sf_result r_by;
gsl_sf_result r_bym;
int stat_1 = gsl_sf_bessel_Y1_e(x, &r_by);
int stat_0 = gsl_sf_bessel_Y0_e(x, &r_bym);
double bym = r_bym.val;
double by = r_by.val;
double byp;
int j;
for(j=1; j<n; j++) {
byp = j*two_over_x*by - bym;
bym = by;
by = byp;
}
result->val = sign * by;
result->err = fabs(result->val) * (fabs(r_by.err/r_by.val) + fabs(r_bym.err/r_bym.val));
result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);
return GSL_ERROR_SELECT_2(stat_1, stat_0);
}
}
}
int
gsl_sf_bessel_Yn_array(const int nmin, const int nmax, const double x, double * result_array)
{
/* CHECK_POINTER(result_array) */
if(nmin < 0 || nmax < nmin || x <= 0.0) {
int j;
for(j=0; j<=nmax-nmin; j++) result_array[j] = 0.0;
GSL_ERROR ("error", GSL_EDOM);
}
else {
gsl_sf_result r_Ynm1;
gsl_sf_result r_Yn;
int stat_nm1 = gsl_sf_bessel_Yn_e(nmin, x, &r_Ynm1);
int stat_n = gsl_sf_bessel_Yn_e(nmin+1, x, &r_Yn);
double Ynp1;
double Yn = r_Yn.val;
double Ynm1 = r_Ynm1.val;
int n;
int stat = GSL_ERROR_SELECT_2(stat_nm1, stat_n);
if(stat == GSL_SUCCESS) {
for(n=nmin+1; n<=nmax+1; n++) {
result_array[n-nmin-1] = Ynm1;
Ynp1 = -Ynm1 + 2.0*n/x * Yn;
Ynm1 = Yn;
Yn = Ynp1;
}
}
else {
for(n=nmin; n<=nmax; n++) {
result_array[n-nmin] = 0.0;
}
}
return stat;
}
}
/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/
#include "eval.h"
double gsl_sf_bessel_Yn(const int n, const double x)
{
EVAL_RESULT(gsl_sf_bessel_Yn_e(n, x, &result));
}
| {
"alphanum_fraction": 0.5925454545,
"avg_line_length": 25.2293577982,
"ext": "c",
"hexsha": "3dc1a99b0d4491d7381f67a8e17bfad88f693d33",
"lang": "C",
"max_forks_count": 14,
"max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z",
"max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Brian-ning/HMNE",
"max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_Yn.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/specfunc/bessel_Yn.c",
"max_line_length": 95,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/specfunc/bessel_Yn.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": 1907,
"size": 5500
} |
/* vector/gsl_vector_uchar.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_VECTOR_UCHAR_H__
#define __GSL_VECTOR_UCHAR_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_block_uchar.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size;
size_t stride;
unsigned char *data;
gsl_block_uchar *block;
int owner;
}
gsl_vector_uchar;
typedef struct
{
gsl_vector_uchar vector;
} _gsl_vector_uchar_view;
typedef _gsl_vector_uchar_view gsl_vector_uchar_view;
typedef struct
{
gsl_vector_uchar vector;
} _gsl_vector_uchar_const_view;
typedef const _gsl_vector_uchar_const_view gsl_vector_uchar_const_view;
/* Allocation */
GSL_EXPORT gsl_vector_uchar *gsl_vector_uchar_alloc (const size_t n);
GSL_EXPORT gsl_vector_uchar *gsl_vector_uchar_calloc (const size_t n);
GSL_EXPORT gsl_vector_uchar *gsl_vector_uchar_alloc_from_block (gsl_block_uchar * b,
const size_t offset,
const size_t n,
const size_t stride);
GSL_EXPORT gsl_vector_uchar *gsl_vector_uchar_alloc_from_vector (gsl_vector_uchar * v,
const size_t offset,
const size_t n,
const size_t stride);
GSL_EXPORT void gsl_vector_uchar_free (gsl_vector_uchar * v);
/* Views */
GSL_EXPORT
_gsl_vector_uchar_view
gsl_vector_uchar_view_array (unsigned char *v, size_t n);
GSL_EXPORT
_gsl_vector_uchar_view
gsl_vector_uchar_view_array_with_stride (unsigned char *base,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_uchar_const_view
gsl_vector_uchar_const_view_array (const unsigned char *v, size_t n);
GSL_EXPORT
_gsl_vector_uchar_const_view
gsl_vector_uchar_const_view_array_with_stride (const unsigned char *base,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_uchar_view
gsl_vector_uchar_subvector (gsl_vector_uchar *v,
size_t i,
size_t n);
GSL_EXPORT
_gsl_vector_uchar_view
gsl_vector_uchar_subvector_with_stride (gsl_vector_uchar *v,
size_t i,
size_t stride,
size_t n);
GSL_EXPORT
_gsl_vector_uchar_const_view
gsl_vector_uchar_const_subvector (const gsl_vector_uchar *v,
size_t i,
size_t n);
GSL_EXPORT
_gsl_vector_uchar_const_view
gsl_vector_uchar_const_subvector_with_stride (const gsl_vector_uchar *v,
size_t i,
size_t stride,
size_t n);
/* Operations */
GSL_EXPORT unsigned char gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i);
GSL_EXPORT void gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x);
GSL_EXPORT unsigned char *gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i);
GSL_EXPORT const unsigned char *gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i);
GSL_EXPORT void gsl_vector_uchar_set_zero (gsl_vector_uchar * v);
GSL_EXPORT void gsl_vector_uchar_set_all (gsl_vector_uchar * v, unsigned char x);
GSL_EXPORT int gsl_vector_uchar_set_basis (gsl_vector_uchar * v, size_t i);
GSL_EXPORT int gsl_vector_uchar_fread (FILE * stream, gsl_vector_uchar * v);
GSL_EXPORT int gsl_vector_uchar_fwrite (FILE * stream, const gsl_vector_uchar * v);
GSL_EXPORT int gsl_vector_uchar_fscanf (FILE * stream, gsl_vector_uchar * v);
GSL_EXPORT int gsl_vector_uchar_fprintf (FILE * stream, const gsl_vector_uchar * v,
const char *format);
GSL_EXPORT int gsl_vector_uchar_memcpy (gsl_vector_uchar * dest, const gsl_vector_uchar * src);
GSL_EXPORT int gsl_vector_uchar_reverse (gsl_vector_uchar * v);
GSL_EXPORT int gsl_vector_uchar_swap (gsl_vector_uchar * v, gsl_vector_uchar * w);
GSL_EXPORT int gsl_vector_uchar_swap_elements (gsl_vector_uchar * v, const size_t i, const size_t j);
GSL_EXPORT unsigned char gsl_vector_uchar_max (const gsl_vector_uchar * v);
GSL_EXPORT unsigned char gsl_vector_uchar_min (const gsl_vector_uchar * v);
GSL_EXPORT void gsl_vector_uchar_minmax (const gsl_vector_uchar * v, unsigned char * min_out, unsigned char * max_out);
GSL_EXPORT size_t gsl_vector_uchar_max_index (const gsl_vector_uchar * v);
GSL_EXPORT size_t gsl_vector_uchar_min_index (const gsl_vector_uchar * v);
GSL_EXPORT void gsl_vector_uchar_minmax_index (const gsl_vector_uchar * v, size_t * imin, size_t * imax);
GSL_EXPORT int gsl_vector_uchar_add (gsl_vector_uchar * a, const gsl_vector_uchar * b);
GSL_EXPORT int gsl_vector_uchar_sub (gsl_vector_uchar * a, const gsl_vector_uchar * b);
GSL_EXPORT int gsl_vector_uchar_mul (gsl_vector_uchar * a, const gsl_vector_uchar * b);
GSL_EXPORT int gsl_vector_uchar_div (gsl_vector_uchar * a, const gsl_vector_uchar * b);
GSL_EXPORT int gsl_vector_uchar_scale (gsl_vector_uchar * a, const double x);
GSL_EXPORT int gsl_vector_uchar_add_constant (gsl_vector_uchar * a, const double x);
GSL_EXPORT int gsl_vector_uchar_isnull (const gsl_vector_uchar * v);
#ifdef HAVE_INLINE
extern inline
unsigned char
gsl_vector_uchar_get (const gsl_vector_uchar * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return v->data[i * v->stride];
}
extern inline
void
gsl_vector_uchar_set (gsl_vector_uchar * v, const size_t i, unsigned char x)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_VOID ("index out of range", GSL_EINVAL);
}
#endif
v->data[i * v->stride] = x;
}
extern inline
unsigned char *
gsl_vector_uchar_ptr (gsl_vector_uchar * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (unsigned char *) (v->data + i * v->stride);
}
extern inline
const unsigned char *
gsl_vector_uchar_const_ptr (const gsl_vector_uchar * v, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= v->size)
{
GSL_ERROR_NULL ("index out of range", GSL_EINVAL);
}
#endif
return (const unsigned char *) (v->data + i * v->stride);
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_VECTOR_UCHAR_H__ */
| {
"alphanum_fraction": 0.6849722186,
"avg_line_length": 32.9319148936,
"ext": "h",
"hexsha": "632455af130599fb4a98e3696bac0fefbb4a2d44",
"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_vector_uchar.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_vector_uchar.h",
"max_line_length": 119,
"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_vector_uchar.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1904,
"size": 7739
} |
#ifndef SEARCHPATTERNBUILDER_HHHHH
#define SEARCHPATTERNBUILDER_HHHHH
#include "detail/SearchPatternBase.h"
#include "SearchPattern.h"
#include <vector>
#include <string>
#include <memory>
#include <gsl/string_span>
namespace MPSig {
class SearchPatternBuilder {
std::vector<std::unique_ptr<detail::SearchPatternBase>> m_patternSteps;
public:
SearchPatternBuilder();
SearchPatternBuilder& HasHexPattern(gsl::cstring_span<-1> pattern);
SearchPatternBuilder& ReferencesBSTR(gsl::cwstring_span<-1> bstrText);
SearchPattern Compile();
};
}
#endif
| {
"alphanum_fraction": 0.7296849088,
"avg_line_length": 21.5357142857,
"ext": "h",
"hexsha": "89e99ea04eb71ce6a1526f5a730cf8c4dd96724c",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "KevinW1998/MultipassSigScanner",
"max_forks_repo_path": "src/search/SearchPatternBuilder.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "KevinW1998/MultipassSigScanner",
"max_issues_repo_path": "src/search/SearchPatternBuilder.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "13f290ec593ddbeed3c59c7fba642c1704bfd529",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "KevinW1998/MultipassSigScanner",
"max_stars_repo_path": "src/search/SearchPatternBuilder.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 139,
"size": 603
} |
#pragma once
#include <string>
#include <ntdll.h>
#include <gsl/span>
namespace pe
{
class module : public HINSTANCE__
{
public:
module() = delete;
uintptr_t handle() const;
template <class T>
inline auto rva_to(uint32_t rva)
{
return reinterpret_cast<T *>(reinterpret_cast<uintptr_t>(this) + rva);
}
template <class T>
inline auto rva_to(uint32_t rva) const
{
return reinterpret_cast<const T *>(reinterpret_cast<uintptr_t>(this) + rva);
}
std::wstring base_name() const;
std::wstring full_name() const;
IMAGE_DOS_HEADER *dos_header();
const IMAGE_DOS_HEADER *dos_header() const;
IMAGE_NT_HEADERS *nt_header();
const IMAGE_NT_HEADERS *nt_header() const;
size_t size() const;
gsl::span<class segment> segments();
gsl::span<const class segment> segments() const;
class segment *segment(const char* namename);
const class segment *segment(const char* name) const;
class export_directory *export_directory();
const class export_directory *export_directory() const;
void *find_function(const char *name) const;
void *find_function(uint32_t num) const;
};
class module *get_module(const wchar_t *name = nullptr);
class module *get_module_from_address(void *pc);
const class module *get_module_from_address(const void *pc);
class module *instance_module();
}
#include "module.inl"
| {
"alphanum_fraction": 0.7008547009,
"avg_line_length": 30.5217391304,
"ext": "h",
"hexsha": "319fea96ab14aa8e939cd1a9d815c92448c0a954",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-18T18:03:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-18T18:03:36.000Z",
"max_forks_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bnsmodpolice/loginhelper",
"max_forks_repo_path": "include/pe/module.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9",
"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": "bnsmodpolice/loginhelper",
"max_issues_repo_path": "include/pe/module.h",
"max_line_length": 82,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "7505878b225c7be144ec5e8abf4484133b2cbff9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bnsmodpolice/loginhelper",
"max_stars_repo_path": "include/pe/module.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-22T20:48:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-18T04:53:41.000Z",
"num_tokens": 341,
"size": 1404
} |
// Copyright (C) 2015 Vincent Lejeune
// For conditions of distribution and use, see copyright notice in License.txt
#pragma once
#include <vulkan\vulkan.h>
#include <array>
#include <gsl/gsl>
#define CHECK_VKRESULT(cmd) { VkResult res = (cmd); if (res != VK_SUCCESS) throw; }
namespace structures
{
constexpr VkAttachmentDescription attachment_description(
VkFormat format,
VkAttachmentLoadOp load_op,
VkAttachmentStoreOp store_op,
VkImageLayout initial_layout,
VkImageLayout final_layout,
VkSampleCountFlagBits sample_count = VK_SAMPLE_COUNT_1_BIT,
VkAttachmentLoadOp stencil_load_op = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
VkAttachmentStoreOp stencil_store_op = VK_ATTACHMENT_STORE_OP_DONT_CARE,
VkAttachmentDescriptionFlags flag = 0)
{
return{ flag, format, sample_count, load_op, store_op, stencil_load_op, stencil_store_op, initial_layout, final_layout };
}
}
| {
"alphanum_fraction": 0.8036117381,
"avg_line_length": 34.0769230769,
"ext": "h",
"hexsha": "cdf228cdf80b3c2f13e92956d918603e910f22f5",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-10-31T04:40:05.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-18T16:23:33.000Z",
"max_forks_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "vlj/YAGF",
"max_forks_repo_path": "include/VKAPI/vulkan_helpers.h",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f",
"max_issues_repo_issues_event_max_datetime": "2017-11-16T03:06:58.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-04-16T19:46:53.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "vlj/YAGF",
"max_issues_repo_path": "include/VKAPI/vulkan_helpers.h",
"max_line_length": 123,
"max_stars_count": 15,
"max_stars_repo_head_hexsha": "139ddc9c7d3552f383e235715713c30684b7067f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "vlj/YAGF",
"max_stars_repo_path": "include/VKAPI/vulkan_helpers.h",
"max_stars_repo_stars_event_max_datetime": "2019-10-23T23:30:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-16T19:41:41.000Z",
"num_tokens": 218,
"size": 886
} |
#pragma once
#include <gsl/gsl_multifit_nlinear.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_cdf.h>
#include <vector>
#include <functional>
#include <algorithm>
#include <tuple>
// this "fdf_Helper" helper class is used for create the polynomial to be fit in the runtime.
// Since GSL would like a static function, have to do some trick to make it happy
// see https://stackoverflow.com/questions/13074756/how-to-avoid-static-member-function-when-using-gsl-with-c?noredirect=1&lq=1
// https://stackoverflow.com/questions/6610046/stdfunction-and-stdbind-what-are-they-and-when-should-they-be-used
// https://stackoverflow.com/questions/7582546/using-generic-stdfunction-objects-with-member-functions-in-one-class
class PolynomialFit
{
public:
struct data
{
double* x;
double* y;
size_t n;
std::function<int(const gsl_vector* p, void* datafit, gsl_vector* f)> f = NULL;
std::function<int(const gsl_vector* p, void* datafit, gsl_matrix* J)> df = NULL;
std::function<int(const gsl_vector* p, const gsl_vector* v, void* datafit, gsl_vector* fvv)> fvv = NULL;
};
class fdf_Helper
{
public:
static int invoke_f(const gsl_vector* p, void* datafit, gsl_vector* f) {
PolynomialFit::data* dataf = static_cast<PolynomialFit::data*>(datafit);
return dataf->f(p, datafit, f);
}
static int invoke_df(const gsl_vector* p, void* datafit, gsl_matrix* J) {
PolynomialFit::data* dataf = static_cast<PolynomialFit::data*>(datafit);
return dataf->df(p, datafit, J);
}
static int invoke_fvv(const gsl_vector* p, const gsl_vector* v, void* datafit, gsl_vector* fvv) {
PolynomialFit::data* dataf = static_cast<PolynomialFit::data*>(datafit);
return dataf->fvv(p, v, datafit, fvv);
}
};
private:
gsl_vector* p0; /* initial fitting parameters: a0,...,an, (b0,b1)*/
gsl_vector* p; /* fitting parameters */
gsl_vector* f; /* residual yi-y(xi) */
gsl_matrix* covar; /*covariance matrix, not yet multiplied by sigma, so is not variance-covariance matrix*/
gsl_multifit_nlinear_fdf fdf;
gsl_multifit_nlinear_parameters fdf_params;
gsl_multifit_nlinear_workspace* work;
data fit_data;
size_t max_iter;
double ptol; /* tolerance on fitting parameter p */
double gtol; /* tolerance on gradient */
double ftol;
int info; /* fiting stop reason, for debug*/
double rss; /* mean of sum of residual square, dof corrected*/
gsl_vector* confid95;
public:
/* model function: a0 + a1*x + a2*x^2 +...+ b0*sqrt(x-b1) */
PolynomialFit() {};
PolynomialFit(size_t n, double* datax, double* datay, unsigned order, bool useSqrt,
std::vector<double> init_para,
size_t max_iter = 200, double ptol = 1.0e-8, double gtol = 1.0e-8, double ftol = 1.0e-8);
double polynomial(std::vector<double> para, double t);
~PolynomialFit();
void solve_system();
void set_data(double* datay);
void set_data(size_t n, double* datax, double* datay, bool free = true);
void set_initialP(std::vector<double> para);
std::vector<double> calcFittedGaussian();
std::vector<double> fittedPara() const;
std::vector<double> confidence95Interval() const;
private:
bool useSqrt;
unsigned order;
unsigned numOfPara;
void init_dataFunc();
//static int funcf_Wrapper/*next line is the argument of this "funcf_Wrapper"*/
//(const gsl_vector* p, void* datafit, gsl_vector* f);
//static int (*funcf_Wrapper/*next line is the argument of this "funcf_Wrapper"*/
//(std::function<int(const gsl_vector* p, void* datafit, gsl_vector* f)> func_f))
// (const gsl_vector* p, void* datafit, gsl_vector* f);
int func_f(const gsl_vector* p, void* datafit, gsl_vector* f);
int func_df(const gsl_vector* p, void* datafit, gsl_matrix* J);
int func_fvv(const gsl_vector* p, const gsl_vector* v, void* datafit, gsl_vector* fvv);
};
| {
"alphanum_fraction": 0.6356389215,
"avg_line_length": 37.7433628319,
"ext": "h",
"hexsha": "d71dc737442b290150c0f2a5ef8e221dedcbbf30",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_forks_repo_path": "Chimera/Source/AnalogInput/PolynomialFit.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/Source/AnalogInput/PolynomialFit.h",
"max_line_length": 127,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/Source/AnalogInput/PolynomialFit.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1122,
"size": 4265
} |
/**
*
* @file core_cgetf2_nopiv.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Omar Zenati
* @author Mathieu Faverge
* @date 2013-02-01
* @generated c Tue Jan 7 11:44:50 2014
*
**/
#include "common.h"
#include <math.h>
#include <lapacke.h>
/***************************************************************************//**
*
* @ingroup CORE_PLASMA_Complex32_t
*
* CORE_cgetf2_nopiv computes an LU factorization of a general diagonal
* dominant M-by-N matrix A witout no pivoting and no blocking. It is the
* internal function called by CORE_cgetrf_nopiv().
*
* The factorization has the form
* A = L * U
* where L is lower triangular with unit
* diagonal elements (lower trapezoidal if m > n), and U is upper
* triangular (upper trapezoidal if m < n).
*
* This is the right-looking Level 3 BLAS version of the algorithm.
*
*******************************************************************************
*
* @param[in] M
* The number of rows of the matrix A. M >= 0.
*
* @param[in] N
* The number of columns of the matrix A. N >= 0.
*
* @param[in,out] A
* On entry, the M-by-N matrix to be factored.
* On exit, the factors L and U from the factorization
* A = P*L*U; the unit diagonal elements of L are not stored.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,M).
*
*******************************************************************************
*
* @return
* \retval PLASMA_SUCCESS successful exit
* \retval <0 if INFO = -k, the k-th argument had an illegal value
* \retval >0 if INFO = k, U(k,k) is exactly zero. The factorization
* has been completed, but the factor U is exactly
* singular, and division by zero will occur if it is used
* to solve a system of equations.
*
******************************************************************************/
int
CORE_cgetf2_nopiv(int M, int N,
PLASMA_Complex32_t *A, int LDA)
{
PLASMA_Complex32_t mzone = (PLASMA_Complex32_t)-1.0;
PLASMA_Complex32_t alpha;
float sfmin;
int i, j, k;
int info;
/* Check input arguments */
info = 0;
if (M < 0) {
coreblas_error(1, "Illegal value of M");
return -1;
}
if (N < 0) {
coreblas_error(2, "Illegal value of N");
return -2;
}
if ((LDA < max(1,M)) && (M > 0)) {
coreblas_error(5, "Illegal value of LDA");
return -5;
}
/* Quick return */
if ( (M == 0) || (N == 0) )
return PLASMA_SUCCESS;
sfmin = LAPACKE_slamch_work('S');
k = min(M, N);
for(i=0 ; i < k; i++) {
alpha = A[i*LDA+i];
if ( alpha != (PLASMA_Complex32_t)0.0 ) {
/* Compute elements J+1:M of J-th column. */
if (i < M) {
if ( cabsf(alpha) > sfmin ) {
alpha = 1.0 / alpha;
cblas_cscal( M-i-1, CBLAS_SADDR(alpha), &(A[i*LDA+i+1]), 1);
} else {
for(j=i+1; j<M; j++)
A[LDA*i+j] = A[LDA*i+j] / alpha;
}
}
} else if ( info == 0 ) {
info = i;
goto end;
}
if ( i < k ) {
/* Update trailing submatrix */
cblas_cgeru(CblasColMajor,
M-i-1, N-i-1, CBLAS_SADDR(mzone),
&A[LDA* i +i+1], 1,
&A[LDA*(i+1)+i ], LDA,
&A[LDA*(i+1)+i+1], LDA);
}
}
end:
return info;
}
| {
"alphanum_fraction": 0.4795972443,
"avg_line_length": 30.192,
"ext": "c",
"hexsha": "3fb1640b0a47246a48c83059502a865565589b8f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "zhuangsc/Plasma-ompss1",
"max_forks_repo_path": "core_blas/core_cgetf2_nopiv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas/core_cgetf2_nopiv.c",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "zhuangsc/Plasma-ompss1",
"max_stars_repo_path": "core_blas/core_cgetf2_nopiv.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1053,
"size": 3774
} |
/* matrix/gsl_matrix_double.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MATRIX_DOUBLE_H__
#define __GSL_MATRIX_DOUBLE_H__
#if !defined( GSL_FUN )
# if !defined( GSL_DLL )
# define GSL_FUN extern
# elif defined( BUILD_GSL_DLL )
# define GSL_FUN extern __declspec(dllexport)
# else
# define GSL_FUN extern __declspec(dllimport)
# endif
#endif
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_inline.h>
#include <gsl/gsl_check_range.h>
#include <gsl/gsl_vector_double.h>
#include <gsl/gsl_blas_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct
{
size_t size1;
size_t size2;
size_t tda;
double * data;
gsl_block * block;
int owner;
} gsl_matrix;
typedef struct
{
gsl_matrix matrix;
} _gsl_matrix_view;
typedef _gsl_matrix_view gsl_matrix_view;
typedef struct
{
gsl_matrix matrix;
} _gsl_matrix_const_view;
typedef const _gsl_matrix_const_view gsl_matrix_const_view;
/* Allocation */
GSL_FUN gsl_matrix *
gsl_matrix_alloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix *
gsl_matrix_calloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix *
gsl_matrix_alloc_from_block (gsl_block * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_FUN gsl_matrix *
gsl_matrix_alloc_from_matrix (gsl_matrix * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_FUN gsl_vector *
gsl_vector_alloc_row_from_matrix (gsl_matrix * m,
const size_t i);
GSL_FUN gsl_vector *
gsl_vector_alloc_col_from_matrix (gsl_matrix * m,
const size_t j);
GSL_FUN void gsl_matrix_free (gsl_matrix * m);
/* Views */
GSL_FUN _gsl_matrix_view
gsl_matrix_submatrix (gsl_matrix * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_view
gsl_matrix_row (gsl_matrix * m, const size_t i);
GSL_FUN _gsl_vector_view
gsl_matrix_column (gsl_matrix * m, const size_t j);
GSL_FUN _gsl_vector_view
gsl_matrix_diagonal (gsl_matrix * m);
GSL_FUN _gsl_vector_view
gsl_matrix_subdiagonal (gsl_matrix * m, const size_t k);
GSL_FUN _gsl_vector_view
gsl_matrix_superdiagonal (gsl_matrix * m, const size_t k);
GSL_FUN _gsl_vector_view
gsl_matrix_subrow (gsl_matrix * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_view
gsl_matrix_subcolumn (gsl_matrix * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_view
gsl_matrix_view_array (double * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_view
gsl_matrix_view_array_with_tda (double * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_view
gsl_matrix_view_vector (gsl_vector * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_view
gsl_matrix_view_vector_with_tda (gsl_vector * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_const_view
gsl_matrix_const_submatrix (const gsl_matrix * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_const_view
gsl_matrix_const_row (const gsl_matrix * m,
const size_t i);
GSL_FUN _gsl_vector_const_view
gsl_matrix_const_column (const gsl_matrix * m,
const size_t j);
GSL_FUN _gsl_vector_const_view
gsl_matrix_const_diagonal (const gsl_matrix * m);
GSL_FUN _gsl_vector_const_view
gsl_matrix_const_subdiagonal (const gsl_matrix * m,
const size_t k);
GSL_FUN _gsl_vector_const_view
gsl_matrix_const_superdiagonal (const gsl_matrix * m,
const size_t k);
GSL_FUN _gsl_vector_const_view
gsl_matrix_const_subrow (const gsl_matrix * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_const_view
gsl_matrix_const_subcolumn (const gsl_matrix * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_const_view
gsl_matrix_const_view_array (const double * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_const_view
gsl_matrix_const_view_array_with_tda (const double * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_const_view
gsl_matrix_const_view_vector (const gsl_vector * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_const_view
gsl_matrix_const_view_vector_with_tda (const gsl_vector * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_FUN void gsl_matrix_set_zero (gsl_matrix * m);
GSL_FUN void gsl_matrix_set_identity (gsl_matrix * m);
GSL_FUN void gsl_matrix_set_all (gsl_matrix * m, double x);
GSL_FUN int gsl_matrix_fread (FILE * stream, gsl_matrix * m) ;
GSL_FUN int gsl_matrix_fwrite (FILE * stream, const gsl_matrix * m) ;
GSL_FUN int gsl_matrix_fscanf (FILE * stream, gsl_matrix * m);
GSL_FUN int gsl_matrix_fprintf (FILE * stream, const gsl_matrix * m, const char * format);
GSL_FUN int gsl_matrix_memcpy(gsl_matrix * dest, const gsl_matrix * src);
GSL_FUN int gsl_matrix_swap(gsl_matrix * m1, gsl_matrix * m2);
GSL_FUN int gsl_matrix_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src);
GSL_FUN int gsl_matrix_swap_rows(gsl_matrix * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_swap_columns(gsl_matrix * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_swap_rowcol(gsl_matrix * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_transpose (gsl_matrix * m);
GSL_FUN int gsl_matrix_transpose_memcpy (gsl_matrix * dest, const gsl_matrix * src);
GSL_FUN int gsl_matrix_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix * dest, const gsl_matrix * src);
GSL_FUN double gsl_matrix_max (const gsl_matrix * m);
GSL_FUN double gsl_matrix_min (const gsl_matrix * m);
GSL_FUN void gsl_matrix_minmax (const gsl_matrix * m, double * min_out, double * max_out);
GSL_FUN void gsl_matrix_max_index (const gsl_matrix * m, size_t * imax, size_t *jmax);
GSL_FUN void gsl_matrix_min_index (const gsl_matrix * m, size_t * imin, size_t *jmin);
GSL_FUN void gsl_matrix_minmax_index (const gsl_matrix * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_FUN int gsl_matrix_equal (const gsl_matrix * a, const gsl_matrix * b);
GSL_FUN int gsl_matrix_isnull (const gsl_matrix * m);
GSL_FUN int gsl_matrix_ispos (const gsl_matrix * m);
GSL_FUN int gsl_matrix_isneg (const gsl_matrix * m);
GSL_FUN int gsl_matrix_isnonneg (const gsl_matrix * m);
GSL_FUN int gsl_matrix_add (gsl_matrix * a, const gsl_matrix * b);
GSL_FUN int gsl_matrix_sub (gsl_matrix * a, const gsl_matrix * b);
GSL_FUN int gsl_matrix_mul_elements (gsl_matrix * a, const gsl_matrix * b);
GSL_FUN int gsl_matrix_div_elements (gsl_matrix * a, const gsl_matrix * b);
GSL_FUN int gsl_matrix_scale (gsl_matrix * a, const double x);
GSL_FUN int gsl_matrix_scale_rows (gsl_matrix * a, const gsl_vector * x);
GSL_FUN int gsl_matrix_scale_columns (gsl_matrix * a, const gsl_vector * x);
GSL_FUN int gsl_matrix_add_constant (gsl_matrix * a, const double x);
GSL_FUN int gsl_matrix_add_diagonal (gsl_matrix * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_FUN int gsl_matrix_get_row(gsl_vector * v, const gsl_matrix * m, const size_t i);
GSL_FUN int gsl_matrix_get_col(gsl_vector * v, const gsl_matrix * m, const size_t j);
GSL_FUN int gsl_matrix_set_row(gsl_matrix * m, const size_t i, const gsl_vector * v);
GSL_FUN int gsl_matrix_set_col(gsl_matrix * m, const size_t j, const gsl_vector * v);
/***********************************************************************/
/* inline functions if you are using GCC */
GSL_FUN INLINE_DECL double gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL void gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x);
GSL_FUN INLINE_DECL double * gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL const double * gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
double
gsl_matrix_get(const gsl_matrix * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VAL("first index out of range", GSL_EINVAL, 0) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VAL("second index out of range", GSL_EINVAL, 0) ;
}
}
#endif
return m->data[i * m->tda + j] ;
}
INLINE_FUN
void
gsl_matrix_set(gsl_matrix * m, const size_t i, const size_t j, const double x)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_VOID("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_VOID("second index out of range", GSL_EINVAL) ;
}
}
#endif
m->data[i * m->tda + j] = x ;
}
INLINE_FUN
double *
gsl_matrix_ptr(gsl_matrix * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (double *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
const double *
gsl_matrix_const_ptr(const gsl_matrix * m, const size_t i, const size_t j)
{
#if GSL_RANGE_CHECK
if (GSL_RANGE_COND(1))
{
if (i >= m->size1)
{
GSL_ERROR_NULL("first index out of range", GSL_EINVAL) ;
}
else if (j >= m->size2)
{
GSL_ERROR_NULL("second index out of range", GSL_EINVAL) ;
}
}
#endif
return (const double *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_DOUBLE_H__ */
| {
"alphanum_fraction": 0.6384820778,
"avg_line_length": 33.7677595628,
"ext": "h",
"hexsha": "7205c9e19d888958d1438d530cfd42a327811045",
"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": "0073e0515b87610b7f88ad2b07fc7d23618c159a",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "zhanghe9704/jspec2",
"max_forks_repo_path": "include/gsl/gsl_matrix_double.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a",
"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": "zhanghe9704/jspec2",
"max_issues_repo_path": "include/gsl/gsl_matrix_double.h",
"max_line_length": 126,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0073e0515b87610b7f88ad2b07fc7d23618c159a",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "zhanghe9704/jspec2",
"max_stars_repo_path": "include/gsl/gsl_matrix_double.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": 3131,
"size": 12359
} |
/* specfunc/gsl_sf_legendre.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2004 Gerard Jungman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#ifndef __GSL_SF_LEGENDRE_H__
#define __GSL_SF_LEGENDRE_H__
#include <gsl/gsl_sf_result.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
/* P_l(x) l >= 0; |x| <= 1
*
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_Pl_e(const int l, const double x, gsl_sf_result * result);
double gsl_sf_legendre_Pl(const int l, const double x);
/* P_l(x) for l=0,...,lmax; |x| <= 1
*
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_Pl_array(
const int lmax, const double x,
double * result_array
);
/* P_l(x) and P_l'(x) for l=0,...,lmax; |x| <= 1
*
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_Pl_deriv_array(
const int lmax, const double x,
double * result_array,
double * result_deriv_array
);
/* P_l(x), l=1,2,3
*
* exceptions: none
*/
int gsl_sf_legendre_P1_e(double x, gsl_sf_result * result);
int gsl_sf_legendre_P2_e(double x, gsl_sf_result * result);
int gsl_sf_legendre_P3_e(double x, gsl_sf_result * result);
double gsl_sf_legendre_P1(const double x);
double gsl_sf_legendre_P2(const double x);
double gsl_sf_legendre_P3(const double x);
/* Q_0(x), x > -1, x != 1
*
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_Q0_e(const double x, gsl_sf_result * result);
double gsl_sf_legendre_Q0(const double x);
/* Q_1(x), x > -1, x != 1
*
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_Q1_e(const double x, gsl_sf_result * result);
double gsl_sf_legendre_Q1(const double x);
/* Q_l(x), x > -1, x != 1, l >= 0
*
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_Ql_e(const int l, const double x, gsl_sf_result * result);
double gsl_sf_legendre_Ql(const int l, const double x);
/* P_l^m(x) m >= 0; l >= m; |x| <= 1.0
*
* Note that this function grows combinatorially with l.
* Therefore we can easily generate an overflow for l larger
* than about 150.
*
* There is no trouble for small m, but when m and l are both large,
* then there will be trouble. Rather than allow overflows, these
* functions refuse to calculate when they can sense that l and m are
* too big.
*
* If you really want to calculate a spherical harmonic, then DO NOT
* use this. Instead use legendre_sphPlm() below, which uses a similar
* recursion, but with the normalized functions.
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
int gsl_sf_legendre_Plm_e(const int l, const int m, const double x, gsl_sf_result * result);
double gsl_sf_legendre_Plm(const int l, const int m, const double x);
/* P_l^m(x) m >= 0; l >= m; |x| <= 1.0
* l=|m|,...,lmax
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
int gsl_sf_legendre_Plm_array(
const int lmax, const int m, const double x,
double * result_array
);
/* P_l^m(x) and d(P_l^m(x))/dx; m >= 0; lmax >= m; |x| <= 1.0
* l=|m|,...,lmax
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
int gsl_sf_legendre_Plm_deriv_array(
const int lmax, const int m, const double x,
double * result_array,
double * result_deriv_array
);
/* P_l^m(x), normalized properly for use in spherical harmonics
* m >= 0; l >= m; |x| <= 1.0
*
* There is no overflow problem, as there is for the
* standard normalization of P_l^m(x).
*
* Specifically, it returns:
*
* sqrt((2l+1)/(4pi)) sqrt((l-m)!/(l+m)!) P_l^m(x)
*
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_sphPlm_e(const int l, int m, const double x, gsl_sf_result * result);
double gsl_sf_legendre_sphPlm(const int l, const int m, const double x);
/* sphPlm(l,m,x) values
* m >= 0; l >= m; |x| <= 1.0
* l=|m|,...,lmax
*
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_sphPlm_array(
const int lmax, int m, const double x,
double * result_array
);
/* sphPlm(l,m,x) and d(sphPlm(l,m,x))/dx values
* m >= 0; l >= m; |x| <= 1.0
* l=|m|,...,lmax
*
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_sphPlm_deriv_array(
const int lmax, const int m, const double x,
double * result_array,
double * result_deriv_array
);
/* size of result_array[] needed for the array versions of Plm
* (lmax - m + 1)
*/
int gsl_sf_legendre_array_size(const int lmax, const int m);
/* Irregular Spherical Conical Function
* P^{1/2}_{-1/2 + I lambda}(x)
*
* x > -1.0
* exceptions: GSL_EDOM
*/
int gsl_sf_conicalP_half_e(const double lambda, const double x, gsl_sf_result * result);
double gsl_sf_conicalP_half(const double lambda, const double x);
/* Regular Spherical Conical Function
* P^{-1/2}_{-1/2 + I lambda}(x)
*
* x > -1.0
* exceptions: GSL_EDOM
*/
int gsl_sf_conicalP_mhalf_e(const double lambda, const double x, gsl_sf_result * result);
double gsl_sf_conicalP_mhalf(const double lambda, const double x);
/* Conical Function
* P^{0}_{-1/2 + I lambda}(x)
*
* x > -1.0
* exceptions: GSL_EDOM
*/
int gsl_sf_conicalP_0_e(const double lambda, const double x, gsl_sf_result * result);
double gsl_sf_conicalP_0(const double lambda, const double x);
/* Conical Function
* P^{1}_{-1/2 + I lambda}(x)
*
* x > -1.0
* exceptions: GSL_EDOM
*/
int gsl_sf_conicalP_1_e(const double lambda, const double x, gsl_sf_result * result);
double gsl_sf_conicalP_1(const double lambda, const double x);
/* Regular Spherical Conical Function
* P^{-1/2-l}_{-1/2 + I lambda}(x)
*
* x > -1.0, l >= -1
* exceptions: GSL_EDOM
*/
int gsl_sf_conicalP_sph_reg_e(const int l, const double lambda, const double x, gsl_sf_result * result);
double gsl_sf_conicalP_sph_reg(const int l, const double lambda, const double x);
/* Regular Cylindrical Conical Function
* P^{-m}_{-1/2 + I lambda}(x)
*
* x > -1.0, m >= -1
* exceptions: GSL_EDOM
*/
int gsl_sf_conicalP_cyl_reg_e(const int m, const double lambda, const double x, gsl_sf_result * result);
double gsl_sf_conicalP_cyl_reg(const int m, const double lambda, const double x);
/* The following spherical functions are specializations
* of Legendre functions which give the regular eigenfunctions
* of the Laplacian on a 3-dimensional hyperbolic space.
* Of particular interest is the flat limit, which is
* Flat-Lim := {lambda->Inf, eta->0, lambda*eta fixed}.
*/
/* Zeroth radial eigenfunction of the Laplacian on the
* 3-dimensional hyperbolic space.
*
* legendre_H3d_0(lambda,eta) := sin(lambda*eta)/(lambda*sinh(eta))
*
* Normalization:
* Flat-Lim legendre_H3d_0(lambda,eta) = j_0(lambda*eta)
*
* eta >= 0.0
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_H3d_0_e(const double lambda, const double eta, gsl_sf_result * result);
double gsl_sf_legendre_H3d_0(const double lambda, const double eta);
/* First radial eigenfunction of the Laplacian on the
* 3-dimensional hyperbolic space.
*
* legendre_H3d_1(lambda,eta) :=
* 1/sqrt(lambda^2 + 1) sin(lam eta)/(lam sinh(eta))
* (coth(eta) - lambda cot(lambda*eta))
*
* Normalization:
* Flat-Lim legendre_H3d_1(lambda,eta) = j_1(lambda*eta)
*
* eta >= 0.0
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_H3d_1_e(const double lambda, const double eta, gsl_sf_result * result);
double gsl_sf_legendre_H3d_1(const double lambda, const double eta);
/* l'th radial eigenfunction of the Laplacian on the
* 3-dimensional hyperbolic space.
*
* Normalization:
* Flat-Lim legendre_H3d_l(l,lambda,eta) = j_l(lambda*eta)
*
* eta >= 0.0, l >= 0
* exceptions: GSL_EDOM
*/
int gsl_sf_legendre_H3d_e(const int l, const double lambda, const double eta, gsl_sf_result * result);
double gsl_sf_legendre_H3d(const int l, const double lambda, const double eta);
/* Array of H3d(ell), 0 <= ell <= lmax
*/
int gsl_sf_legendre_H3d_array(const int lmax, const double lambda, const double eta, double * result_array);
/* associated legendre P_{lm} routines */
typedef enum
{
GSL_SF_LEGENDRE_SCHMIDT,
GSL_SF_LEGENDRE_SPHARM,
GSL_SF_LEGENDRE_FULL,
GSL_SF_LEGENDRE_NONE
} gsl_sf_legendre_t;
int gsl_sf_legendre_array(const gsl_sf_legendre_t norm,
const size_t lmax, const double x,
double result_array[]);
int gsl_sf_legendre_array_e(const gsl_sf_legendre_t norm,
const size_t lmax, const double x,
const double csphase,
double result_array[]);
int gsl_sf_legendre_deriv_array(const gsl_sf_legendre_t norm,
const size_t lmax, const double x,
double result_array[],
double result_deriv_array[]);
int gsl_sf_legendre_deriv_array_e(const gsl_sf_legendre_t norm,
const size_t lmax, const double x,
const double csphase,
double result_array[],
double result_deriv_array[]);
int gsl_sf_legendre_deriv_alt_array(const gsl_sf_legendre_t norm,
const size_t lmax, const double x,
double result_array[],
double result_deriv_array[]);
int gsl_sf_legendre_deriv_alt_array_e(const gsl_sf_legendre_t norm,
const size_t lmax, const double x,
const double csphase,
double result_array[],
double result_deriv_array[]);
int gsl_sf_legendre_deriv2_array(const gsl_sf_legendre_t norm,
const size_t lmax, const double x,
double result_array[],
double result_deriv_array[],
double result_deriv2_array[]);
int gsl_sf_legendre_deriv2_array_e(const gsl_sf_legendre_t norm,
const size_t lmax, const double x,
const double csphase,
double result_array[],
double result_deriv_array[],
double result_deriv2_array[]);
int gsl_sf_legendre_deriv2_alt_array(const gsl_sf_legendre_t norm,
const size_t lmax, const double x,
double result_array[],
double result_deriv_array[],
double result_deriv2_array[]);
int gsl_sf_legendre_deriv2_alt_array_e(const gsl_sf_legendre_t norm,
const size_t lmax, const double x,
const double csphase,
double result_array[],
double result_deriv_array[],
double result_deriv2_array[]);
size_t gsl_sf_legendre_array_n(const size_t lmax);
size_t gsl_sf_legendre_array_index(const size_t l, const size_t m);
size_t gsl_sf_legendre_nlm(const size_t lmax);
__END_DECLS
#endif /* __GSL_SF_LEGENDRE_H__ */
| {
"alphanum_fraction": 0.6483895383,
"avg_line_length": 31.625,
"ext": "h",
"hexsha": "962872aec13cba6f58de97fef1f2c8ff32216d66",
"lang": "C",
"max_forks_count": 5,
"max_forks_repo_forks_event_max_datetime": "2022-01-04T19:22:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-27T11:11:07.000Z",
"max_forks_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "snipekill/FPGen",
"max_forks_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_legendre.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "snipekill/FPGen",
"max_issues_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_legendre.h",
"max_line_length": 108,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4fa9a35cc5695d65509296790accd4b34071432d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "snipekill/FPGen",
"max_stars_repo_path": "benchmarks/gsl/build-klee/gsl/gsl_sf_legendre.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-20T21:02:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-07-06T02:44:11.000Z",
"num_tokens": 3156,
"size": 11891
} |
// Author: Samuel D. Relton
#include <stdio.h>
#include <cblas.h>
#include "sgemm_batched.h"
float A1[] = {
3, 1, 3,
1, 5, 9,
2, 6, 5
};
float B1[] = {
3, 1, 3,
1, 5, 9,
2, 6, 5
};
float C1[] = {
0, 0, 0,
0, 0, 0,
0, 0, 0
};
float A2[] = {
3, 1, 3,
1, 5, 9,
2, 6, 5
};
float B2[] = {
3, 1, 3,
1, 5, 9,
2, 6, 5
};
float C2[] = {
0, 0, 0,
0, 0, 0,
0, 0, 0
};
float ALPHA[] = {1.0, 1.0};
float BETA[] = {0.0, 0.0};
int LDA[] = {3, 3};
int LDB[] = {3, 3};
int LDC[] = {3, 3};
bblas_trans_t TRANSA[] = {CblasNoTrans, CblasNoTrans};
bblas_trans_t TRANSB[] = {CblasNoTrans, CblasNoTrans};
int M[] = {3, 3};
int N[] = {3, 3};
int K[] = {3, 3};
int BATCHCOUNT = 2;
bblas_batch_type_t BATCH_TYPE = BBLASFixed;
int INFO[] = {0, 0};
float *arrayA[] = {A1, A2};
float *arrayB[] = {B1, B2};
float *arrayC[] = {C1, C2};
int main()
{
int i, j, k;
sgemm_batched(TRANSA, TRANSB, M, N, K, ALPHA, arrayA,
LDA, arrayB, LDB, BETA, arrayC, LDC, BATCHCOUNT,
BATCH_TYPE, INFO);
for (k = 0; k < BATCHCOUNT; k++) {
putchar('\n');
for (i=0; i<3; ++i) {
for (j=0; j<3; ++j) {
printf("%5.1f", arrayC[k][i*3+j]);
}
putchar('\n');
}
}
return 0;
}
| {
"alphanum_fraction": 0.5076271186,
"avg_line_length": 13.5632183908,
"ext": "c",
"hexsha": "5461bc4e2e6571c681269fd71fbcaf780b05a409",
"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": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "NLAFET/BBLAS-ref",
"max_forks_repo_path": "src/test_sgemm.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d",
"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": "NLAFET/BBLAS-ref",
"max_issues_repo_path": "src/test_sgemm.c",
"max_line_length": 56,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "7f3bef184d4d7a9a8b5685185e16f77e5d317e6d",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "NLAFET/BBLAS-ref",
"max_stars_repo_path": "src/test_sgemm.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 566,
"size": 1180
} |
/*
** smooth variance computations
**
** M. Kuhlmann, MPI-KYB, Sept 2015
*/
#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>
VImage variance_smoothing(VImage *src[], float width)
{
size_t nslices, nrows, ncols;
/* image dims */
nslices = VImageNBands(src[0]);
nrows = VImageNRows(src[0]);
ncols = VImageNColumns(src[0]);
VImage var = VCreateImage(nslices,nrows,ncols,VFloatRepn);
VFillImage(var,VAllBands,0);
/*double *data,int n,double *a,double *v)*/
int j;
double ave,var,nx,s,u;
nx = (double)n;
ave = 0;
for (j=0; j<n; j++) ave += data[j];
ave /= nx;
var = u = 0;
for (j=0; j<n; j++) {
s = data[j]-ave;
u += s;
var += s*s;
}
var=(var-u*u/nx)/(nx-1);
/* smooth variance */
return var;
} | {
"alphanum_fraction": 0.609264854,
"avg_line_length": 18.0545454545,
"ext": "c",
"hexsha": "78d1c32ecb85046ae7b68e9f8ccf5a16de9370ca",
"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/varsmooth.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/varsmooth.c",
"max_line_length": 60,
"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/varsmooth.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": 341,
"size": 993
} |
/* randist/gsl_randist.h
*
* 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.
*/
#ifndef __GSL_RANDIST_H__
#define __GSL_RANDIST_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
unsigned int gsl_ran_bernoulli (const gsl_rng * r, double p);
double gsl_ran_bernoulli_pdf (const unsigned int k, double p);
double gsl_ran_beta (const gsl_rng * r, const double a, const double b);
double gsl_ran_beta_pdf (const double x, const double a, const double b);
unsigned int gsl_ran_binomial (const gsl_rng * r, double p, unsigned int n);
unsigned int gsl_ran_binomial_knuth (const gsl_rng * r, double p, unsigned int n);
unsigned int gsl_ran_binomial_tpe (const gsl_rng * r, double p, unsigned int n);
double gsl_ran_binomial_pdf (const unsigned int k, const double p, const unsigned int n);
double gsl_ran_exponential (const gsl_rng * r, const double mu);
double gsl_ran_exponential_pdf (const double x, const double mu);
double gsl_ran_exppow (const gsl_rng * r, const double a, const double b);
double gsl_ran_exppow_pdf (const double x, const double a, const double b);
double gsl_ran_cauchy (const gsl_rng * r, const double a);
double gsl_ran_cauchy_pdf (const double x, const double a);
double gsl_ran_chisq (const gsl_rng * r, const double nu);
double gsl_ran_chisq_pdf (const double x, const double nu);
void gsl_ran_dirichlet (const gsl_rng * r, const size_t K, const double alpha[], double theta[]);
double gsl_ran_dirichlet_pdf (const size_t K, const double alpha[], const double theta[]);
double gsl_ran_dirichlet_lnpdf (const size_t K, const double alpha[], const double theta[]);
double gsl_ran_erlang (const gsl_rng * r, const double a, const double n);
double gsl_ran_erlang_pdf (const double x, const double a, const double n);
double gsl_ran_fdist (const gsl_rng * r, const double nu1, const double nu2);
double gsl_ran_fdist_pdf (const double x, const double nu1, const double nu2);
double gsl_ran_flat (const gsl_rng * r, const double a, const double b);
double gsl_ran_flat_pdf (double x, const double a, const double b);
double gsl_ran_gamma (const gsl_rng * r, const double a, const double b);
double gsl_ran_gamma_int (const gsl_rng * r, const unsigned int a);
double gsl_ran_gamma_pdf (const double x, const double a, const double b);
double gsl_ran_gamma_mt (const gsl_rng * r, const double a, const double b);
double gsl_ran_gamma_knuth (const gsl_rng * r, const double a, const double b);
double gsl_ran_gaussian (const gsl_rng * r, const double sigma);
double gsl_ran_gaussian_ratio_method (const gsl_rng * r, const double sigma);
double gsl_ran_gaussian_ziggurat (const gsl_rng * r, const double sigma);
double gsl_ran_gaussian_pdf (const double x, const double sigma);
double gsl_ran_ugaussian (const gsl_rng * r);
double gsl_ran_ugaussian_ratio_method (const gsl_rng * r);
double gsl_ran_ugaussian_pdf (const double x);
double gsl_ran_gaussian_tail (const gsl_rng * r, const double a, const double sigma);
double gsl_ran_gaussian_tail_pdf (const double x, const double a, const double sigma);
double gsl_ran_ugaussian_tail (const gsl_rng * r, const double a);
double gsl_ran_ugaussian_tail_pdf (const double x, const double a);
void gsl_ran_bivariate_gaussian (const gsl_rng * r, double sigma_x, double sigma_y, double rho, double *x, double *y);
double gsl_ran_bivariate_gaussian_pdf (const double x, const double y, const double sigma_x, const double sigma_y, const double rho);
double gsl_ran_landau (const gsl_rng * r);
double gsl_ran_landau_pdf (const double x);
unsigned int gsl_ran_geometric (const gsl_rng * r, const double p);
double gsl_ran_geometric_pdf (const unsigned int k, const double p);
unsigned int gsl_ran_hypergeometric (const gsl_rng * r, unsigned int n1, unsigned int n2, unsigned int t);
double gsl_ran_hypergeometric_pdf (const unsigned int k, const unsigned int n1, const unsigned int n2, unsigned int t);
double gsl_ran_gumbel1 (const gsl_rng * r, const double a, const double b);
double gsl_ran_gumbel1_pdf (const double x, const double a, const double b);
double gsl_ran_gumbel2 (const gsl_rng * r, const double a, const double b);
double gsl_ran_gumbel2_pdf (const double x, const double a, const double b);
double gsl_ran_logistic (const gsl_rng * r, const double a);
double gsl_ran_logistic_pdf (const double x, const double a);
double gsl_ran_lognormal (const gsl_rng * r, const double zeta, const double sigma);
double gsl_ran_lognormal_pdf (const double x, const double zeta, const double sigma);
unsigned int gsl_ran_logarithmic (const gsl_rng * r, const double p);
double gsl_ran_logarithmic_pdf (const unsigned int k, const double p);
void gsl_ran_multinomial (const gsl_rng * r, const size_t K,
const unsigned int N, const double p[],
unsigned int n[] );
double gsl_ran_multinomial_pdf (const size_t K,
const double p[], const unsigned int n[] );
double gsl_ran_multinomial_lnpdf (const size_t K,
const double p[], const unsigned int n[] );
unsigned int gsl_ran_negative_binomial (const gsl_rng * r, double p, double n);
double gsl_ran_negative_binomial_pdf (const unsigned int k, const double p, double n);
unsigned int gsl_ran_pascal (const gsl_rng * r, double p, unsigned int n);
double gsl_ran_pascal_pdf (const unsigned int k, const double p, unsigned int n);
double gsl_ran_pareto (const gsl_rng * r, double a, const double b);
double gsl_ran_pareto_pdf (const double x, const double a, const double b);
unsigned int gsl_ran_poisson (const gsl_rng * r, double mu);
void gsl_ran_poisson_array (const gsl_rng * r, size_t n, unsigned int array[],
double mu);
double gsl_ran_poisson_pdf (const unsigned int k, const double mu);
double gsl_ran_rayleigh (const gsl_rng * r, const double sigma);
double gsl_ran_rayleigh_pdf (const double x, const double sigma);
double gsl_ran_rayleigh_tail (const gsl_rng * r, const double a, const double sigma);
double gsl_ran_rayleigh_tail_pdf (const double x, const double a, const double sigma);
double gsl_ran_tdist (const gsl_rng * r, const double nu);
double gsl_ran_tdist_pdf (const double x, const double nu);
double gsl_ran_laplace (const gsl_rng * r, const double a);
double gsl_ran_laplace_pdf (const double x, const double a);
double gsl_ran_levy (const gsl_rng * r, const double c, const double alpha);
double gsl_ran_levy_skew (const gsl_rng * r, const double c, const double alpha, const double beta);
double gsl_ran_weibull (const gsl_rng * r, const double a, const double b);
double gsl_ran_weibull_pdf (const double x, const double a, const double b);
void gsl_ran_dir_2d (const gsl_rng * r, double * x, double * y);
void gsl_ran_dir_2d_trig_method (const gsl_rng * r, double * x, double * y);
void gsl_ran_dir_3d (const gsl_rng * r, double * x, double * y, double * z);
void gsl_ran_dir_nd (const gsl_rng * r, size_t n, double * x);
void gsl_ran_shuffle (const gsl_rng * r, void * base, size_t nmembm, size_t size);
int gsl_ran_choose (const gsl_rng * r, void * dest, size_t k, void * src, size_t n, size_t size) ;
void gsl_ran_sample (const gsl_rng * r, void * dest, size_t k, void * src, size_t n, size_t size) ;
typedef struct { /* struct for Walker algorithm */
size_t K;
size_t *A;
double *F;
} gsl_ran_discrete_t;
gsl_ran_discrete_t * gsl_ran_discrete_preproc (size_t K, const double *P);
void gsl_ran_discrete_free(gsl_ran_discrete_t *g);
size_t gsl_ran_discrete (const gsl_rng *r, const gsl_ran_discrete_t *g);
double gsl_ran_discrete_pdf (size_t k, const gsl_ran_discrete_t *g);
__END_DECLS
#endif /* __GSL_RANDIST_H__ */
| {
"alphanum_fraction": 0.7566562028,
"avg_line_length": 46.2419354839,
"ext": "h",
"hexsha": "49775bde016824b7d6bc0dc527dd4d4e60c5aba0",
"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/gsl_randist.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/randist/gsl_randist.h",
"max_line_length": 133,
"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/gsl_randist.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": 2323,
"size": 8601
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <cblas.h>
#include "../../runtime/pcp.h"
#include "driver.h"
static double random_double(void)
{
return (double) rand() / RAND_MAX;
}
static void usage(char *prog)
{
printf("Usage: %s n m b p q\n", prog);
printf("\n");
printf("n: The size of the triangular matrix\n");
printf("m: The number of right-hand sides\n");
printf("b: The tile size\n");
printf("p: The number of threads (or 0 for one per core)\n");
printf("q: The size of the reserved set (or 0 to use the regular mode)\n");
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{
// Verify the number of command line options.
if (argc != 6 && argc != 7) {
usage(argv[0]);
}
// Parse command line.
int n = atoi(argv[1]);
int m = atoi(argv[2]);
int blksz = atoi(argv[3]);
int num_threads = atoi(argv[4]);
int reserved_set_size = atoi(argv[5]);
int verify = 1;
if (argc == 7) {
verify = 0;
}
// Verify options.
if (n < 1 ||
m < 1 ||
blksz < 1 ||
num_threads < 0 ||
reserved_set_size < 0 ||
(reserved_set_size >= num_threads && num_threads > 0)) {
usage(argv[0]);
}
// Start the runtime system.
pcp_start(num_threads);
// Set the execution mode.
if (reserved_set_size == 0) {
pcp_set_mode(PCP_REGULAR);
} else {
pcp_set_mode(PCP_FIXED);
pcp_set_reserved_set_size(reserved_set_size);
}
// Allocate matrices.
int ldL, ldX, ldB;
double *L, *X, *B;
ldL = ldX = ldB = n;
L = (double*) malloc(sizeof(double) * ldL * n);
X = (double*) malloc(sizeof(double) * ldX * m);
B = (double*) malloc(sizeof(double) * ldB * m);
#define L(i,j) L[(i) + (j) * ldL]
#define X(i,j) X[(i) + (j) * ldX]
#define B(i,j) B[(i) + (j) * ldB]
// Generate L.
printf("Generating lower triangular matrix L...\n");
for (int j = 0; j < n; ++j) {
for (int i = 0; i < j; ++i) {
L(i,j) = 0;
}
for (int i = j; i < n; ++i) {
L(i,j) = random_double();
}
L(j,j) = n;
}
// Generate B.
printf("Generating right-hand sides B...\n");
for (int j = 0; j < m; ++j) {
for (int i = 0; i < n; ++i) {
B(i,j) = random_double();
}
}
// Copy B to X.
printf("Copying B to X...\n");
for (int j = 0; j < m; ++j) {
for (int i = 0; i < n; ++i) {
X(i,j) = B(i,j);
}
}
// Call the driver.
printf("Calling the driver routine...\n");
parallel_forward_substitution(n, m, blksz, L, ldL, X, ldX);
if (verify) {
// Verify the solution.
printf("Verifying the solution... ");
fflush(stdout);
cblas_dtrmm(CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasNonUnit,
n, m,
1.0, L, ldL,
X, ldX);
double err = 0;
for (int j = 0; j < m; ++j) {
for (int i = 0; i < n; ++i) {
double e = X(i,j) - B(i,j);
err += e * e;
}
}
err = sqrt(err);
if (err / n < 1e-14) {
printf("PASSED\n");
} else {
printf("FAILED\n");
}
} else {
printf("Verification disabled\n");
}
// Save trace.
printf("Saving the trace...\n");
pcp_view_trace_tikz();
// Print statistics.
printf("Printing statistics...\n");
pcp_view_statistics_stdout();
// Stop the runtime system.
pcp_stop();
#undef L
#undef X
#undef B
// Clean up.
free(L);
free(X);
free(B);
return EXIT_SUCCESS;
}
| {
"alphanum_fraction": 0.4944029851,
"avg_line_length": 23.5974842767,
"ext": "c",
"hexsha": "cd0ee3e85da4fb6d5fe2d8ac9b19dbb7d5a1e738",
"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": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "NLAFET/pcp-runtime",
"max_forks_repo_path": "src/examples/dtrsm/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "NLAFET/pcp-runtime",
"max_issues_repo_path": "src/examples/dtrsm/main.c",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "222736152bc9448e55fc32da5ca55281a92bb4d5",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "NLAFET/pcp-runtime",
"max_stars_repo_path": "src/examples/dtrsm/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1111,
"size": 3752
} |
#ifndef UTIL_GSL_CONVERTER_H
#define UTIL_GSL_CONVERTER_H
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
namespace gsl {
inline
gsl_vector* convert_vec(const arma::vec & vector) {
gsl_vector * gsl_vec = gsl_vector_alloc(vector.n_elem);
#pragma omp parallel for
for(arma::uword i=0; i<vector.n_elem; i++) {
gsl_vector_set(gsl_vec, i, vector(i));
}
return gsl_vec;
}
inline
arma::vec convert_vec(const gsl_vector * gsl_vec) {
arma::vec arma_vec(gsl_vec->size);
#pragma omp parallel for
for(arma::uword i=0; i<arma_vec.n_elem; i++) {
arma_vec(i) = gsl_vector_get(gsl_vec, i);
}
return arma_vec;
}
inline
gsl_matrix* convert_mat(const arma::mat & mat) {
gsl_matrix * gsl_mat = gsl_matrix_alloc(mat.n_rows, mat.n_cols);
#pragma omp parallel for
for(arma::uword i=0; i<mat.n_rows; i++) {
for(arma::uword j=0; j<mat.n_cols; j++) {
gsl_matrix_set(gsl_mat, i, j, mat(i,j));
}
}
return gsl_mat;
}
inline
arma::mat convert_mat(const gsl_matrix * gsl_mat) {
arma::mat arma_mat(gsl_mat->size1, gsl_mat->size2);
#pragma omp parallel for
for(arma::uword i=0; i<arma_mat.n_rows; i++) {
for(arma::uword j=0; j<arma_mat.n_cols; j++) {
arma_mat(i,j) = gsl_matrix_get(gsl_mat, i, j);
}
}
return arma_mat;
}
}
#endif //UTIL_GSL_CONVERTER_H
| {
"alphanum_fraction": 0.679331307,
"avg_line_length": 19.0724637681,
"ext": "h",
"hexsha": "f937109a9a9a76a517626e9e4637fe6f2f44059d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Walter-Feng/Quartz",
"max_forks_repo_path": "include/quartz_internal/util/gsl_converter.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b",
"max_issues_repo_issues_event_max_datetime": "2020-06-17T05:26:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-02-27T04:46:41.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Walter-Feng/Quartz",
"max_issues_repo_path": "include/quartz_internal/util/gsl_converter.h",
"max_line_length": 66,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "f9af8cf41ec9882e109271ede3b7ad7c2a49af2b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Walter-Feng/Quartz",
"max_stars_repo_path": "include/quartz_internal/util/gsl_converter.h",
"max_stars_repo_stars_event_max_datetime": "2021-02-01T01:27:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-18T09:34:46.000Z",
"num_tokens": 412,
"size": 1316
} |
/**
* Copyright (C) 2021 FISCO BCOS.
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @brief interface for Ledger
* @file LedgerInterface.h
* @author: kyonRay
* @date: 2021-04-07
*/
#pragma once
#include "../../interfaces/crypto/CommonType.h"
#include "../../interfaces/protocol/Block.h"
#include "../../interfaces/protocol/BlockHeader.h"
#include "../../interfaces/protocol/Transaction.h"
#include "../../interfaces/protocol/TransactionReceipt.h"
#include "../../interfaces/storage/StorageInterface.h"
#include "LedgerConfig.h"
#include "LedgerTypeDef.h"
#include "bcos-utilities/Error.h"
#include <gsl/span>
#include <map>
namespace bcos::ledger
{
class LedgerInterface
{
public:
using Ptr = std::shared_ptr<LedgerInterface>;
LedgerInterface() = default;
virtual ~LedgerInterface() {}
/**
* @brief async prewrite a block in scheduler module
* @param block the block to commit
* @param callback trigger this callback when write is finished
*/
virtual void asyncPrewriteBlock(bcos::storage::StorageInterface::Ptr storage,
bcos::protocol::Block::ConstPtr block, std::function<void(Error::Ptr&&)> callback) = 0;
/**
* @brief async store txs in block when tx pool verify
* @param _txToStore tx bytes data list
* @param _txHashList tx hash list
* @param _onTxsStored callback
*/
virtual void asyncStoreTransactions(std::shared_ptr<std::vector<bytesConstPtr>> _txToStore,
crypto::HashListPtr _txHashList, std::function<void(Error::Ptr)> _onTxStored) = 0;
/**
* @brief async get block by blockNumber
* @param _blockNumber number of block
* @param _blockFlag flag bit of what the block be callback contains,
* you can checkout all flags in LedgerTypeDef.h
* @param _onGetBlock
*
* @example
* asyncGetBlockDataByNumber(10, HEADER|TRANSACTIONS, [](error, block){ doSomething(); });
*/
virtual void asyncGetBlockDataByNumber(protocol::BlockNumber _blockNumber, int32_t _blockFlag,
std::function<void(Error::Ptr, protocol::Block::Ptr)> _onGetBlock) = 0;
/**
* @brief async get latest block number
* @param _onGetBlock
*/
virtual void asyncGetBlockNumber(
std::function<void(Error::Ptr, protocol::BlockNumber)> _onGetBlock) = 0;
/**
* @brief async get block hash by block number
* @param _blockNumber the number of block to get
* @param _onGetBlock
*/
virtual void asyncGetBlockHashByNumber(protocol::BlockNumber _blockNumber,
std::function<void(Error::Ptr, crypto::HashType)> _onGetBlock) = 0;
/**
* @brief async get block number by block hash
* @param _blockHash the hash of block to get
* @param _onGetBlock
*/
virtual void asyncGetBlockNumberByHash(crypto::HashType const& _blockHash,
std::function<void(Error::Ptr, protocol::BlockNumber)> _onGetBlock) = 0;
/**
* @brief async get a batch of transaction by transaction hash list
* @param _txHashList transaction hash list, hash should be hex
* @param _withProof if true then it will callback MerkleProofPtr map in _onGetTx
* if false then MerkleProofPtr map will be nullptr
* @param _onGetTx return <error, [tx data in bytes], map<txHash, merkleProof>
*/
virtual void asyncGetBatchTxsByHashList(crypto::HashListPtr _txHashList, bool _withProof,
std::function<void(Error::Ptr, bcos::protocol::TransactionsPtr,
std::shared_ptr<std::map<std::string, MerkleProofPtr>>)>
_onGetTx) = 0;
/**
* @brief async get a transaction receipt by tx hash
* @param _txHash hash of transaction
* @param _withProof if true then it will callback MerkleProofPtr in _onGetTx
* if false then MerkleProofPtr will be nullptr
* @param _onGetTx
*/
virtual void asyncGetTransactionReceiptByHash(crypto::HashType const& _txHash, bool _withProof,
std::function<void(Error::Ptr, protocol::TransactionReceipt::ConstPtr, MerkleProofPtr)>
_onGetTx) = 0;
/**
* @brief async get total transaction count and latest block number
* @param _callback callback totalTxCount, totalFailedTxCount, and latest block number
*/
virtual void asyncGetTotalTransactionCount(std::function<void(Error::Ptr, int64_t _totalTxCount,
int64_t _failedTxCount, protocol::BlockNumber _latestBlockNumber)>
_callback) = 0;
/**
* @brief async get system config by table key
* @param _key the key of row, you can checkout all key in LedgerTypeDef.h
* @param _onGetConfig callback when get config, <value, latest block number>
*/
virtual void asyncGetSystemConfigByKey(std::string const& _key,
std::function<void(Error::Ptr, std::string, protocol::BlockNumber)> _onGetConfig) = 0;
/**
* @brief async get node list by type, can be sealer or observer
* @param _type the type of node, CONSENSUS_SEALER or CONSENSUS_OBSERVER
* @param _onGetConfig
*/
virtual void asyncGetNodeListByType(std::string const& _type,
std::function<void(Error::Ptr, consensus::ConsensusNodeListPtr)> _onGetConfig) = 0;
/**
* @brief async get a batch of nonce lists in blocks
* @param _startNumber start block number
* @param _offset batch offset, if batch is 0, then callback nonce list in start block number;
* if (_startNumber + _offset) > latest block number, then callback nonce lists in
* [_startNumber, latest number]
* @param _onGetList
*/
virtual void asyncGetNonceList(protocol::BlockNumber _startNumber, int64_t _offset,
std::function<void(
Error::Ptr, std::shared_ptr<std::map<protocol::BlockNumber, protocol::NonceListPtr>>)>
_onGetList) = 0;
};
} // namespace bcos::ledger
| {
"alphanum_fraction": 0.6860158311,
"avg_line_length": 40.26875,
"ext": "h",
"hexsha": "6ce1d1a3c461ee958418b9068f9f3cc9d2a285ab",
"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": "e9cc29151c90dd1f4634f4d52ba773bb216700ac",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "chuwen95/FISCO-BCOS",
"max_forks_repo_path": "bcos-framework/interfaces/ledger/LedgerInterface.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e9cc29151c90dd1f4634f4d52ba773bb216700ac",
"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": "chuwen95/FISCO-BCOS",
"max_issues_repo_path": "bcos-framework/interfaces/ledger/LedgerInterface.h",
"max_line_length": 100,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "e9cc29151c90dd1f4634f4d52ba773bb216700ac",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "chuwen95/FISCO-BCOS",
"max_stars_repo_path": "bcos-framework/interfaces/ledger/LedgerInterface.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-06T10:46:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-06T10:46:12.000Z",
"num_tokens": 1630,
"size": 6443
} |
/*
Authors:
G. Jungman
J. Scott (james.scott@lexifi.com)
*/
/* Implement Niederreiter base 2 generator.
* See:
* Bratley, Fox, Niederreiter, ACM Trans. Model. Comp. Sim. 2, 195 (1992)
*/
#include <config.h>
#include <gsl/gsl_qrng.h>
#include <gsl/gsl_rng.h>
#include <assert.h>
#define NIED2_BIT_COUNT 30
#define NIED2_NBITS (NIED2_BIT_COUNT+1)
/* Z_2 field operations */
#define NIED2_ADD(x,y) (((x)+(y))%2)
#define NIED2_MUL(x,y) (((x)*(y))%2)
#define NIED2_SUB(x,y) NIED2_ADD((x),(y))
void get_primitive_polynomials(int dimension, int *degree_table, int *primitive_polynomials);
static size_t nied2_state_size(unsigned int dimension);
static int nied2_init(void * state, unsigned int dimension);
static int nied2_get(void * state, unsigned int dimension, double * v);
static const gsl_qrng_type nied2_type =
{
"niederreiter-base-2",
0,
nied2_state_size,
nied2_init,
nied2_get
};
const gsl_qrng_type * gsl_qrng_niederreiter_2 = &nied2_type;
typedef struct
{
unsigned int sequence_count;
int *cj[NIED2_NBITS];
int *nextq;
} nied2_state_t;
static size_t nied2_state_size(unsigned int dimension)
{
return sizeof(nied2_state_t) + /* the struct */
sizeof(int) * dimension * NIED2_NBITS + /* cj */
sizeof(int) * dimension; /* nextq */
}
/* Multiply polynomials over Z_2.
* Notice use of a temporary vector,
* side-stepping aliasing issues when
* one of inputs is the same as the output
* [especially important in the original fortran version, I guess].
*/
static void poly_multiply(
const int pa[], int pa_degree,
const int pb[], int pb_degree,
int pc[], int * pc_degree, int max_degree
)
{
int j, k;
int *pt;
int pt_degree;
pt = (int *) malloc(sizeof(int) * (max_degree+1));
pt_degree = pa_degree + pb_degree;
assert(pt_degree <= max_degree);
for(k=0; k<=pt_degree; k++) {
int term = 0;
for(j=0; j<=k; j++) {
const int conv_term = NIED2_MUL(pa[k-j], pb[j]);
term = NIED2_ADD(term, conv_term);
}
pt[k] = term;
}
for(k=0; k<=pt_degree; k++) {
pc[k] = pt[k];
}
for(k=pt_degree+1; k<=max_degree; k++) {
pc[k] = 0;
}
*pc_degree = pt_degree;
free(pt);
}
/* Calculate the values of the constants V(J,R) as
* described in BFN section 3.3.
*
* px = appropriate irreducible polynomial for current dimension
* pb = polynomial defined in section 2.3 of BFN.
* pb is modified
*/
static void calculate_v(
const int px[], int px_degree,
int pb[], int * pb_degree,
int v[], int maxv, int max_degree, gsl_rng *rng
)
{
const int nonzero_element = 1; /* nonzero element of Z_2 */
/* The polynomial ph is px**(J-1), which is the value of B on arrival.
* In section 3.3, the values of Hi are defined with a minus sign:
* don't forget this if you use them later !
*/
int *ph;
/* int ph_degree = *pb_degree; */
int bigm = *pb_degree; /* m from section 3.3 */
int m; /* m from section 2.3 */
int r, k, kj;
ph = (int *) malloc(sizeof(int) * (max_degree+1));
for(k=0; k<=max_degree; k++) {
ph[k] = pb[k];
}
/* Now multiply B by PX so B becomes PX**J.
* In section 2.3, the values of Bi are defined with a minus sign :
* don't forget this if you use them later !
*/
poly_multiply(px, px_degree, pb, *pb_degree, pb, pb_degree, max_degree);
m = *pb_degree;
/* Now choose a value of Kj as defined in section 3.3.
* We must have 0 <= Kj < E*J = M.
* The limit condition on Kj does not seem very relevant
* in this program.
*/
/* Quoting from BFN: "Our program currently sets each K_q
* equal to eq. This has the effect of setting all unrestricted
* values of v to 1."
* Actually, it sets them to the arbitrary chosen value.
* Whatever.
*/
kj = gsl_rng_uniform_int(rng, bigm+1);
/* Now choose values of V in accordance with
* the conditions in section 3.3.
*/
for(r=0; r<kj; r++) {
v[r] = 0;
}
v[kj] = 1;
if(kj >= bigm) {
for(r=kj+1; r<m; r++) {
v[r] = gsl_rng_uniform_int(rng, 2); /* arbitrary element */
}
}
else {
/* This block is never reached. */
int term = NIED2_SUB(0, ph[kj]);
for(r=kj+1; r<bigm; r++) {
v[r] = gsl_rng_uniform_int(rng, 2); /* arbitrary element */
/* Check the condition of section 3.3,
* remembering that the H's have the opposite sign. [????????]
*/
term = NIED2_SUB(term, NIED2_MUL(ph[r], v[r]));
}
/* Now v[bigm] != term. */
v[bigm] = NIED2_ADD(nonzero_element, term);
for(r=bigm+1; r<m; r++) {
v[r] = gsl_rng_uniform_int(rng, 2); /* arbitrary element */
}
}
/* Calculate the remaining V's using the recursion of section 2.3,
* remembering that the B's have the opposite sign.
*/
for(r=0; r<=maxv-m; r++) {
int term = 0;
for(k=0; k<m; k++) {
term = NIED2_SUB(term, NIED2_MUL(pb[k], v[r+k]));
}
v[r+m] = term;
}
free(ph);
}
static int calculate_cj(nied2_state_t * ns, int dimension)
{
int ci[NIED2_NBITS][NIED2_NBITS];
int *v;
int r;
int i_dim;
int max_degree, maxv;
int *pb, *px;
gsl_rng *rng = gsl_rng_alloc(gsl_rng_default);
int *primitive_polynomials;
int *poly_degree;
poly_degree = (int *) malloc(sizeof(int) * (1+dimension));
primitive_polynomials = (int *) malloc(sizeof(int) * (1+dimension));
if (poly_degree==0 || primitive_polynomials==0)
GSL_ERROR_NULL ("allocation of degree table failed for niederreiter init", GSL_ENOMEM);
/* Generate the primitive polynomials. */
get_primitive_polynomials(dimension, poly_degree+1, primitive_polynomials+1);
poly_degree[0]=0; poly_degree[1]=1;
primitive_polynomials[0]=1;
primitive_polynomials[1]=2;
max_degree=NIED2_NBITS+poly_degree[dimension-1];
maxv = max_degree;
v = (int *) malloc(sizeof(int) * (1+maxv));
pb = (int *) malloc(sizeof(int) * (1+max_degree));
px = (int *) malloc(sizeof(int) * (1+max_degree));
if (v==0 || pb==0 || px==0)
GSL_ERROR_NULL ("allocation of degree table failed for niederreiter init", GSL_ENOMEM);
for(i_dim=0; i_dim<dimension; i_dim++) {
const int poly_index = i_dim + 1;
int j, k;
/* Niederreiter (page 56, after equation (7), defines two
* variables Q and U. We do not need Q explicitly, but we
* do need U.
*/
int u = 0;
/* For each dimension, we need to calculate powers of an
* appropriate irreducible polynomial, see Niederreiter
* page 65, just below equation (19).
* Copy the appropriate irreducible polynomial into PX,
* and its degree into E. Set polynomial B = PX ** 0 = 1.
* M is the degree of B. Subsequently B will hold higher
* powers of PX.
*/
int px_degree;
int pb_degree;
px_degree = poly_degree[poly_index];
pb_degree = 0;
for(k=0; k<=px_degree; k++) {
px[k] = (primitive_polynomials[poly_index] >> k) & 1;
pb[k] = 0;
}
for (;k<max_degree+1;k++) {
px[k] = 0;
pb[k] = 0;
}
pb[0] = 1;
for(j=0; j<NIED2_NBITS; j++) {
/* If U = 0, we need to set B to the next power of PX
* and recalculate V.
*/
if(u == 0) calculate_v(px, px_degree, pb, &pb_degree, v, maxv, max_degree, rng);
/* Now C is obtained from V. Niederreiter
* obtains A from V (page 65, near the bottom), and then gets
* C from A (page 56, equation (7)). However this can be done
* in one step. Here CI(J,R) corresponds to
* Niederreiter's C(I,J,R).
*/
for(r=0; r<NIED2_NBITS; r++) {
ci[r][j] = v[r+u];
}
/* Advance Niederreiter's state variables. */
++u;
if(u == px_degree) u = 0;
}
/* The array CI now holds the values of C(I,J,R) for this value
* of I. We pack them into array CJ so that CJ(I,R) holds all
* the values of C(I,J,R) for J from 1 to NBITS.
*/
for(r=0; r<NIED2_NBITS; r++) {
int term = 0;
for(j=0; j<NIED2_NBITS; j++) {
term = 2*term + ci[r][j];
}
ns->cj[r][i_dim] = term;
}
}
free(primitive_polynomials);
free(poly_degree);
free(v);
free(pb);
free(px);
gsl_rng_free(rng);
return GSL_SUCCESS;
}
static int nied2_init(void * state, unsigned int dimension)
{
nied2_state_t * n_state = (nied2_state_t *) state;
unsigned int i_dim, i_bits;
int ret;
if(dimension < 1) return GSL_EINVAL;
for (i_bits=0; i_bits<NIED2_NBITS; i_bits++)
n_state->cj[i_bits] =
(int *) ((char *) n_state +
sizeof(nied2_state_t) +
sizeof(int) * dimension * i_bits);
n_state->nextq =
(int *) ((char *) n_state +
sizeof(nied2_state_t) +
sizeof(int) * dimension * NIED2_NBITS);
if ((ret = calculate_cj(n_state, dimension)) != GSL_SUCCESS)
return ret;
/* skip the '0th' state, which is 0 */
for(i_dim=0; i_dim<dimension; i_dim++)
n_state->nextq[i_dim] = n_state->cj[0][i_dim];
n_state->sequence_count = 1;
return GSL_SUCCESS;
}
static int nied2_get(void * state, unsigned int dimension, double * v)
{
static const double recip = 1.0/(double)(1U << NIED2_NBITS); /* 2^(-nbits) */
nied2_state_t * n_state = (nied2_state_t *) state;
int r;
int c;
unsigned int i_dim;
/* Load the result from the saved state. */
for(i_dim=0; i_dim<dimension; i_dim++) {
v[i_dim] = n_state->nextq[i_dim] * recip;
}
/* Find the position of the least-significant zero in sequence_count.
* This is the bit that changes in the Gray-code representation as
* the count is advanced.
*/
r = 0;
c = n_state->sequence_count;
while(1) {
if((c % 2) == 1) {
++r;
c /= 2;
}
else break;
}
if(r >= NIED2_NBITS) return GSL_EFAILED; /* FIXME: better error code here */
/* Calculate the next state. */
for(i_dim=0; i_dim<dimension; i_dim++) {
n_state->nextq[i_dim] ^= n_state->cj[r][i_dim];
}
n_state->sequence_count++;
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6107849965,
"avg_line_length": 25.9715762274,
"ext": "c",
"hexsha": "4062f13ca7eee80719ec02f623dedc830264c2ad",
"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/contrib/jsqrng_niederreiter-2.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/contrib/jsqrng_niederreiter-2.c",
"max_line_length": 93,
"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/contrib/jsqrng_niederreiter-2.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": 3154,
"size": 10051
} |
#ifndef TTT_AUDIOCACHE_H
#define TTT_AUDIOCACHE_H
#include <SDL_mixer.h>
#include <gsl/util>
#include <vector>
#include <memory>
#include <string_view>
namespace ttt
{
// A class for caching sounds and music.
class AudioCache final
{
public:
using SizeType = gsl::index;
Mix_Music *loadMusic(std::string_view path);
Mix_Chunk *loadChunk(std::string_view path);
void unloadMusic(SizeType index) noexcept;
void unloadChunk(SizeType index) noexcept;
void eraseMusic(SizeType index) noexcept;
void eraseChunk(SizeType index) noexcept;
void clearMusic() noexcept;
void clearChunks() noexcept;
void clear() noexcept;
[[nodiscard]] Mix_Music *getMusic(SizeType index) const noexcept;
[[nodiscard]] Mix_Chunk *getChunk(SizeType index) const noexcept;
private:
std::vector<std::unique_ptr<Mix_Music, decltype(&Mix_FreeMusic)>> music;
std::vector<std::unique_ptr<Mix_Chunk, decltype(&Mix_FreeChunk)>> chunks;
};
inline void AudioCache::unloadMusic(SizeType index) noexcept { gsl::at(music, index).reset(); }
inline void AudioCache::unloadChunk(SizeType index) noexcept { gsl::at(chunks, index).reset(); }
inline void AudioCache::eraseMusic(SizeType index) noexcept { music.erase(music.cbegin() + index); }
inline void AudioCache::eraseChunk(SizeType index) noexcept { chunks.erase(chunks.cbegin() + index); }
inline void AudioCache::clearMusic() noexcept { music.clear(); }
inline void AudioCache::clearChunks() noexcept { chunks.clear(); }
inline Mix_Music *AudioCache::getMusic(SizeType index) const noexcept { return gsl::at(music, index).get(); }
inline Mix_Chunk *AudioCache::getChunk(SizeType index) const noexcept { return gsl::at(chunks, index).get(); }
}
#endif | {
"alphanum_fraction": 0.7447674419,
"avg_line_length": 31.8518518519,
"ext": "h",
"hexsha": "2e3255a9a94dd85df33f6518254a2292de95ca56",
"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": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "itsArtem/TicTacToe",
"max_forks_repo_path": "Source/AudioCache.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf",
"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": "itsArtem/TicTacToe",
"max_issues_repo_path": "Source/AudioCache.h",
"max_line_length": 111,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8c70a77e4603dd0ff22ec0621b978ec0685ec3cf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "itsArtem/TicTacToe",
"max_stars_repo_path": "Source/AudioCache.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 429,
"size": 1720
} |
/**
*
* @file qwrapper_dsygst.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:59 2014
*
**/
#include <lapacke.h>
#include "common.h"
#undef COMPLEX
#define REAL
/***************************************************************************//**
*
**/
void QUARK_CORE_dsygst(Quark *quark, Quark_Task_Flags *task_flags,
int itype, PLASMA_enum uplo, int n,
double *A, int lda,
double *B, int ldb,
PLASMA_sequence *sequence, PLASMA_request *request,
int iinfo)
{
QUARK_Insert_Task(quark, CORE_dsygst_quark, task_flags,
sizeof(int), &itype, VALUE,
sizeof(PLASMA_enum), &uplo, VALUE,
sizeof(int), &n, VALUE,
sizeof(double)*lda*n, A, INOUT,
sizeof(int), &lda, VALUE,
#ifdef COMPLEX
sizeof(double)*ldb*n, B, INOUT,
#else
sizeof(double)*ldb*n, B, INPUT,
#endif
sizeof(int), &ldb, VALUE,
sizeof(PLASMA_sequence*), &sequence, VALUE,
sizeof(PLASMA_request*), &request, VALUE,
sizeof(int), &iinfo, VALUE,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dsygst_quark = PCORE_dsygst_quark
#define CORE_dsygst_quark PCORE_dsygst_quark
#endif
void CORE_dsygst_quark(Quark *quark)
{
int itype;
PLASMA_enum uplo;
int n;
double *A;
int lda;
double *B;
int ldb;
PLASMA_sequence *sequence;
PLASMA_request *request;
int iinfo;
int info;
quark_unpack_args_10(quark, itype, uplo, n, A, lda, B, ldb, sequence, request, iinfo);
info = LAPACKE_dsygst_work(
LAPACK_COL_MAJOR,
itype,
lapack_const(uplo),
n, A, lda, B, ldb);
if (sequence->status == PLASMA_SUCCESS && info != 0)
plasma_sequence_flush(quark, sequence, request, iinfo+info);
}
| {
"alphanum_fraction": 0.5118043845,
"avg_line_length": 29.65,
"ext": "c",
"hexsha": "e4b2b0ba041c4b3e0c8a177c8ba1c28abf6bbdfb",
"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_dsygst.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_dsygst.c",
"max_line_length": 90,
"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_dsygst.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 613,
"size": 2372
} |
/**
* Set of functions to handle object slitless background subtraction
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#include <unistd.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_fit.h>
#include <gsl/gsl_multifit.h>
#include "fitsio.h"
#include "aXe_grism.h"
#include "aXe_utils.h"
#include "spce_sect.h"
#include "spce_fitting.h"
#include "spce_is_in.h"
#include "spc_back.h"
#define SQR(x) ((x)*(x))
#define MIN(x,y) (((x)<(y))?(x):(y))
#define MAX(x,y) (((x)>(y))?(x):(y))
/**
* Function: is_pt_in_a_beam
* The function checks whether a particular image pixel is part
* of a beam or not. The pixel is checked against an array
* of beams it could be part of.
*
* Parameters:
* @param apoint - the point to check
* @param iids - an array of is_in_descriptors for all the beams that
* should be checked
* @param tnbeams - number of beams in iids
*
* Returns:
* @return 1/0 - fixed values
*/
int
is_pt_in_a_beam (const px_point * const apoint,
const is_in_descriptor * const iids, const int tnbeams)
{
int i;
for (i = 0; i < tnbeams; i++)
{
if (apoint->x < (iids + i)->mini)
continue;
if (apoint->x > (iids + i)->maxi)
continue;
if (apoint->y < (iids + i)->minj)
continue;
if (apoint->y > (iids + i)->maxj)
continue;
if (is_in (apoint->x, apoint->y, iids + i))
{
return 1;
}
}
return 0;
}
/**
* Function: get_window_points
* The subroutine searches in a window around the tracepoint
* for pixels which are suited for the background determination.
* The extend of the window is specified in the beam structured,
* and pixel which are part of any beam can not be used.
*
* Parameters:
* @param obs - the observation
* @param bck_mask - the background mask
* @param actbeam - the beam to search interp points for
* @param tr_point - the integer trace point
*
* Returns:
* @return ret - the vector with the row numbers
*/
/*
gsl_vector_int *
get_window_points(observation *obs, gsl_matrix *bck_mask, beam actbeam,
px_point tr_point)
{
gsl_vector_int *tmp;
gsl_vector_int *ret;
int np_act=0;
int l_act;
int u_act;
int ii;
int ncols;
int onbeam=0;
double umax, lmax;
// extract the lower and upper window extend
umax = actbeam.backwindow.x;
lmax = actbeam.backwindow.y;
// get the number of columns
ncols=obs->grism->size2;
// allocate the vector
tmp = gsl_vector_int_alloc((int)ceil(lmax) + (int)ceil(umax) + 1);
// limit the starting point of the search
// to values within the image dimension
tr_point.y = MAX(0,tr_point.y);
tr_point.y = MIN((int)obs->grism->size2,tr_point.y);
// initialize the row numbers
// to search up- and downwards
l_act = tr_point.y -1;
u_act = tr_point.y;
if (!gsl_matrix_get(bck_mask,tr_point.x,tr_point.y))
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,"The closest pixel to the",
"trace at %i, %i must be part of an object!",tr_point.x,
tr_point.y );
// search downwards from the trace,
// assume to start on the beeam
onbeam=1;
while (l_act > -1 && fabs((double)l_act - (double)tr_point.y) < lmax)
{
// if the pixel is not part of any beam and is not NAN
if (gsl_matrix_get(bck_mask,tr_point.x,l_act) == 0 &&
!isnan(gsl_matrix_get(obs->grism, tr_point.x, l_act)))
{
// store the pixel index
gsl_vector_int_set(tmp, np_act, l_act);
if (onbeam)
onbeam = 0;
// enhance the counter
np_act++;
}
// if you are still on the beam
else if (onbeam && gsl_matrix_get(bck_mask,tr_point.x,l_act))
{
// store the pixel index
gsl_vector_int_set(tmp, np_act, l_act);
// enhance the counter
np_act++;
}
// decrease the search index
l_act--;
}
// search upwards from the trace,
// start always searching on the beam
onbeam=1;
while (u_act < ncols && fabs((double)u_act - (double)tr_point.y) < umax)
{
// if the pixel is not part of any beam and is not NAN
if (gsl_matrix_get(bck_mask,tr_point.x,u_act) == 0 &&
!isnan(gsl_matrix_get(obs->grism, tr_point.x, u_act)))
{
// store the pixel index
gsl_vector_int_set(tmp, np_act, u_act);
if (onbeam)
onbeam = 0;
// enhance the counter
np_act++;
}
// if you are still on the beam
else if (onbeam && gsl_matrix_get(bck_mask,tr_point.x,u_act))
{
// store the pixel index
gsl_vector_int_set(tmp, np_act, u_act);
// enhance the counter
np_act++;
}
// enhance the search index
u_act++;
}
// check whether the beam extends over
// the image. Add an artificial start or
// end point if necessary
if (l_act < 0)
gsl_vector_int_set(tmp, np_act++, -1);
if (u_act > ncols-1)
gsl_vector_int_set(tmp, np_act++, ncols);
if (np_act >0)
{
// transfer the row numbers to a
// vector of the right size
ret = gsl_vector_int_alloc(np_act);
for (ii=0; ii < np_act; ii++)
gsl_vector_int_set(ret, ii, gsl_vector_int_get(tmp, ii));
// sort the row numbers
gsl_sort_vector_int(ret);
}
else
{
ret = NULL;
}
gsl_vector_int_free(tmp);
// return the result
return ret;
}
*/
/**
* Function: get_interp_points
* The function searches for 2*n interpolation points above and
* below the trace. The search is iteratively from the trace
* in both directions. In case that the fram borders are met,
* the respective direction is "closed". The subroutine
* then tries to get more background pixels on the other
* size to reach the desired number.
*
* Parameters:
* @param obs - the observation
* @param bck_mask - the background mask
* @param np - the desired number of interp. points
* @param tr_point - the integer trace point
*
* Returns:
* @return ret - the vector with the row numbers
*/
gsl_vector_int *
get_interp_points(observation *obs, gsl_matrix *bck_mask,
int np, px_point tr_point)
{
gsl_vector_int *tmp;
gsl_vector_int *ret;
int np_act=0;
//int y_low;
//int y_upp;
int l_space=1;
int u_space=1;
int l_act;
int u_act;
int l_np=0;
int u_np=0;
int ncols=obs->grism->size2;
int ii;
// allocate the vector
tmp = gsl_vector_int_alloc(2*np+2);
// limit the starting ppoint of the search
// to values within the image dimension
tr_point.y = MAX(0,tr_point.y);
tr_point.y = MIN((int)obs->grism->size2,tr_point.y);
// initialize the row numbers
// to search up- and downwards
l_act = tr_point.y -1;
u_act = tr_point.y;
// as long as interpolation points are missing
// and one direction, either up or down,
// is 'open', continue searching
while (np_act < 2*np && (l_space || u_space))
{
// check whether the direction
// downwards is still open
if (l_space)
{
// move downward until you either find
// and interp. point or the end of the frame
while (l_act > -1 && (gsl_matrix_get(bck_mask,tr_point.x,l_act)
!=0 ||
isnan(gsl_matrix_get(obs->grism,
tr_point.x, l_act))))
{
l_act--;
}
// if you are at the end of the frame
if (l_act < 0)
{
// close the direction downwards
l_space=0;
}
else
{
// else store the interpolation point,
// do the various increments
gsl_vector_int_set(tmp, np_act, l_act);
np_act++;
l_np++;
l_act--;
}
}
// check whether the direction
// upwards is still open
if (u_space)
{
// move upward until you either find
// and interp. point or the end of the frame
while (u_act < ncols && (gsl_matrix_get(bck_mask,tr_point.x,u_act)
!=0 ||
isnan(gsl_matrix_get(obs->grism,
tr_point.x, u_act))))
{
u_act++;
}
// if you are at the end of the frame
if (u_act >= ncols)
{
// close the direction upwards
u_space=0;
}
else
{
// else store the interpolation point,
// do the various increments
gsl_vector_int_set(tmp, np_act, u_act);
np_act++;
u_np++;
u_act++;
}
}
}
// check whether the beam extends over
// the image. Add an artificial start or
// end point if necessary
if (!l_np)
gsl_vector_int_set(tmp, np_act++, -1);
if (!u_np)
gsl_vector_int_set(tmp, np_act++, ncols);
// transfer the row numbers to a
// vector of the right size
ret = gsl_vector_int_alloc(np_act);
for (ii=0; ii < np_act; ii++)
gsl_vector_int_set(ret, ii, gsl_vector_int_get(tmp, ii));
// sort the row numbers
gsl_sort_vector_int(ret);
// release memory
gsl_vector_int_free(tmp);
// return the result
return ret;
}
/**
* Function: compute_background
* The function extracts possible background pixels for a given
* beam using a specified interpolation functions.
* After possibly rejecting cosmics, the background is
* interpolated on the areas which are masked out. The interpolated
* values are filled into a background structure. If kappa-sigma klipping
* is applied, the clipped pixels are flagged in the dq-array
* of the background image.
*
* Parameters:
* @param obs - the object list
* @param actbeam - the beam to compute the background for
* @param bck_mask - the background mask
* @param fib - the baground structure
* @param npoints - the number of interpolation points
* @param interporder - the interpolation order
* @param niter_med - the number of iterations around the median
* @param niter_fit - the number of iterations around the fit
* @param kappa - the kappa value
*/
void
compute_background (observation *obs, beam actbeam, gsl_matrix *bck_mask,
fullimg_background *fib, int npoints,
int interporder, const int niter_med,
const int niter_fit, const double kappa)
{
px_point xborder;
gsl_vector_int *yvec;
trace_func *tracefun;
px_point tpoint;
double *ys, *fs, *ws, *yi;
//double var;
int i, ii;
int j, n;
int min_y, max_y;
// define the beam and the trace function
tracefun = actbeam.spec_trace;
/* If this beam's ignore flag is set to 1 then do nothing */
if (actbeam.ignore == 1)
return;
// determine the start and end point in x
xborder = get_xrange(obs, actbeam);
// Loop over all columns
for (i = xborder.x; i < xborder.y; i++)
{
// determine the pixel closest to the trace
tpoint.x = i;
tpoint.y = (int)floor(tracefun->func((double)i-actbeam.refpoint.x,
tracefun->data)
+ actbeam.refpoint.y+0.5);
// determine the interpolation points
// around the trace
yvec = get_interp_points(obs, bck_mask, npoints, tpoint);
//-----------------------------------------------------------------
// some code for FORS2 MXU
// if (actbeam.backwindow.x < 0.0)
// yvec = get_interp_points(obs, bck_mask, npoints, tpoint);
// else
// yvec = get_window_points(obs, bck_mask, actbeam, tpoint);
// give a warning and go to the next
// column if there are no background points
if (!yvec)
{
aXe_message (aXe_M_WARN4, __FILE__, __LINE__,
"No backgound points could be found for beam %C. "
"at collumn %d %d",
BEAM(actbeam.ID), i, tpoint.y );
continue;
}
// extract maximum and minimum 0f the y-values
min_y = gsl_vector_int_get(yvec, 0);
max_y = gsl_vector_int_get(yvec, yvec->size-1);
// if (actbeam.backwindow.x == 23.3 && actbeam.backwindow.y == 4.0)
// {
// fprintf(stdout, "%i <--> %i; ", min_y, max_y);
// if (min_y > tpoint.y - actbeam.width
// || max_y < tpoint.y + actbeam.width)
// fprintf(stdout, "%i %f <--> %f %i; ", min_y, tpoint.y - actbeam.width,
// tpoint.y + actbeam.width, max_y);
// }
// determine the size of the double vectors
// to make the background determination
// allocater the space and initialize
// all values to default
n = max_y - min_y + 1;
ys = (double *) malloc (n * sizeof (double));
fs = (double *) malloc (n * sizeof (double));
ws = (double *) malloc (n * sizeof (double));
yi = (double *) malloc (n * sizeof (double));
for (ii = 0; ii < n; ii++)
{
ys[ii] = min_y + ii;
fs[ii] = 0.0;
ws[ii] = 0.0;
}
// transfer the values from the image column
// to the double vectors, set the weight
for (ii = 0; ii < (int)yvec->size; ii++)
{
// extract the row number
j = gsl_vector_int_get (yvec, ii);
// check whether the row is inside the imag
// and whether the is no object on the pixel
if ((j != -1) && (j != (int)obs->grism->size2)
&& !gsl_matrix_get(bck_mask, tpoint.x, j))
{
// set the values and the weight
fs[j - min_y] = gsl_matrix_get (obs->grism, tpoint.x, j);
ws[j - min_y] = gsl_matrix_get (obs->pixerrs, tpoint.x, j);
}
}
// iterate on the background points to
// reject e.g. cosmics
if (niter_med > 0 || niter_fit > 0)
{
// iterate on the median
for (j=0; j < niter_med; j++)
kappa_sigma_clipp(ys, fs,ws, n,kappa, obs, tpoint.x);
// iterate on the fit
if (niter_fit > 0)
comp_kappasigma_interp( ys, fs, ws, n, interporder,
niter_fit, kappa, obs, tpoint.x);
}
// do the final background determination
comp_vector_interp( ys, fs, ws, yi, n, interporder, 1);
// copy the intepolated values
// to the background matrix
for (j = 0; j < n; j++)
{
if ((ys[j] < 0) || (ys[j] >= obs->grism->size2))
continue;
gsl_matrix_set (fib->bck, tpoint.x, (int) floor (ys[j]), fs[j]);
gsl_matrix_set (fib->err, tpoint.x, (int) floor (ys[j]), ws[j]);
}
// release memory
free (ys);
ys = NULL;
free (fs);
fs = NULL;
free (yi);
yi = NULL;
free (ws);
ws = NULL;
// release memory
gsl_vector_int_free(yvec);
}
}
/**
* Function: get_xrange
* The subroutine determines the extend of a beam in x-direction.
* The minimum and maximum value in x of pixels which are part
* of the particular beam are determined and returned.
*
* Parameters:
* @param obs - the object list
* @param actbeam - the beam to determine the extent for
*
* Returns:
* @return ret - Min/Max values of the beam in x
*/
px_point
get_xrange(observation *obs, beam actbeam)
{
px_point ret;
// Find the object starting and ending column
// for the beam of interest actbeam.corners
ret.x = MIN (MIN (MIN (actbeam.corners[0].x, actbeam.corners[1].x),
actbeam.corners[2].x), actbeam.corners[3].x);
ret.y = MAX (MAX (MAX (actbeam.corners[0].x, actbeam.corners[1].x),
actbeam.corners[2].x), actbeam.corners[3].x);
// limit the start and end column
// to the image size
ret.x = MAX(ret.x, 0);
ret.y = MIN(ret.y, (int)obs->grism->size1);
// warn if the beam is completely outside
// the grism image
if (ret.x > (int)obs->grism->size1 || ret.y < 0)
{
aXe_message (aXe_M_WARN4, __FILE__, __LINE__,
"Object is not in the image start_i:%d end_i:%d",
ret.x, ret.y);
}
// return the result
return ret;
}
/**
* Function: comp_kappasigma_interp
* The function performs a kappa-sigma clipping rejection
* on a set of data given in vectors for indipendent, dipendent
* and weight values. The differences to base the clipping on
* is "true value minus background value", where background
* value is determined using the identical algorithm as the
* final background determination.
*
* Parameters:
* @param xs - array for independent values
* @param ys - array for dependent values
* @param ws - weight array
* @param n - number of pixels
* @param interp - number indicating the interpolation scheme
* @param niter - the number of iterations
* @param kappa - the kappa value for rejection
* @param obs - the object list
* @param colnum - the column number
*/
void
comp_kappasigma_interp(const double *const xs, double *const ys,
double *const ws, const int n,
const int interp, const int niter, const double kappa,
observation *obs, int colnum)
{
double *ys_tmp;
double *yi_tmp;
double *y_diff;
double stdev;
int *iindex;
int i, m, j;
// allocate temporary vectors
ys_tmp = (double *) malloc (n * sizeof (double));
yi_tmp = (double *) malloc (n * sizeof (double));
y_diff = (double *) malloc (n * sizeof (double));
iindex = (int *) malloc (n * sizeof (int));
// transfer the dependent value
// to the tmp vector
for (i=0; i < n; i++)
ys_tmp[i] = ys[i];
// do niter times
for (j=0; j < niter; j++)
{
// make the background determination
comp_vector_interp(xs, ys_tmp, ws, yi_tmp, n, interp, 0);
// calculate for all background
// pixels the differences between
// the original and background value
m=0;
for (i=0; i < n; i++)
{
if (ws[i] != 0.0)
{
y_diff[m] = ys[i] - yi_tmp[i];
iindex[m] = i;
m++;
}
}
// compute the standard deviation
// on the differences
stdev = gsl_stats_sd (y_diff, 1, m);
// do the clipping
for (i=0; i < m; i++)
{
// check for pixels to exclude
if (fabs(y_diff[i]) > kappa*stdev)
{
// set its weight to 0.0
ws[iindex[i]] = 0.0;
// mark the pixel in the dq-array
if ( xs[iindex[i]] >= 0 && xs[iindex[i]] < obs->dq->size2)
gsl_matrix_set(obs->dq, colnum, xs[iindex[i]], DQ_KAPPA_SIGMA);
}
}
}
for (i=0; i < n; i++)
ys[i] = ys_tmp[i];
// free memory
free(ys_tmp);
free(yi_tmp);
free(y_diff);
free(iindex);
}
/**
* Function: kappa_sigma_clipp
* The subroutine performs one kappa-sigma step on the data
* given in various vectors for independent, dipendent and
* weight data. The difference to apply the clipping on
* is "original value <minus> median of the data set".
*
* Parameters:
* @param xs - array for independent values
* @param ys - array for dependent values
* @param ws - weight array
* @param n - number of pixels
* @param kappa - the kappa value for rejection
* @param obs - the object list
* @param colnum - the column number
*/
void
kappa_sigma_clipp(const double *const xs, double *const ys, double *const ws,
const int n, const double kappa, observation *obs,
int colnum)
{
double *ys_tmp, *ys_med;
int *iindex;
int ii, m=0, npixel=0;
double median=0.0, stdev=0.0;
// allocate memory for temporay vectors
ys_tmp = (double *) malloc (n * sizeof (double));
ys_med = (double *) malloc (n * sizeof (double));
iindex = (int *) malloc (n * sizeof (int));
// store the background values
// in the temporary vectors
for (ii=0; ii < n; ii++)
{
if (ws[ii] != 0.0)
{
ys_tmp[m] = ys[ii];
ys_med[m] = ys[ii];
iindex[m] = ii;
m++;
}
}
// derive median and standard deviation
gsl_sort (ys_tmp, 1, m);
median = gsl_stats_median_from_sorted_data(ys_tmp, 1, m);
stdev = gsl_stats_sd_m (ys_med, 1, m, median);
// apply the clipping
npixel=0;
for (ii=0; ii < m; ii++)
{
// check whether the pixel should
// be clipped
if (fabs(ys_med[ii]-median) > kappa*stdev)
{
// set the weight of a clipped pixel to 0.0
ws[iindex[ii]] = 0.0;
// mark the clipped pixel in the dq-array
gsl_matrix_set(obs->dq, colnum, xs[iindex[ii]], DQ_KAPPA_SIGMA);
}
else
{
npixel++;
}
}
// release memory
free(ys_med);
free(ys_tmp);
free(iindex);
}
/**
* Function: comp_vector_interp
* The function passes the interpolation data to the
* desired interpolating function.
*
* Parameters:
* @param xs - double vector containing the x values
* @param ys - double vector containing the y values
* @param ws - double vector containing the weights associated with ys
* @param n - number of points in xs,ys, and ws (must be greater than m!)
* @param interp - desired interpolation type
* @param final - indicates a final interpolation
*/
void
comp_vector_interp(const double *const xs, double *const ys,
double *const ws, double *const yi, const int n,
const int interp, const int final)
{
/* Median the background */
if (interp == -1)
{
comp_vector_median(xs, ys, ws, yi, n, final);
}
/* Straight average of the background */
else if (interp == 0)
{
comp_vector_average(xs, ys, ws, yi, n, final);
}
/* Linear interpolation of the background */
else if (interp == 1)
{
comp_vector_linear(xs, ys, ws, yi, n, final);
}
/* n(>1) order interpolation of the background */
else if (interp > 1)
{
comp_vector_polyN (interp + 1, xs, ys, ws, yi, n, final);
}
else
{
aXe_message(aXe_M_FATAL, __FILE__, __LINE__,
"Do not know what to do with interpolation: %i %s\n", interp);
}
}
void
compute_global_background (object **oblist, const int obj_index,
gsl_matrix *bck_mask, fullimg_background * fib,
int interporder)
{
int i, j, n;
double *ys, *fs, *ws, *yi;
//double *ws0;
observation *grism = oblist[obj_index]->grism_obs;
//long ma;
//double var;
for (i = 0; i < (int)grism->grism->size1; i++)
{
/* Loop over the columns of interest */
n = grism->grism->size2;
ys = (double *) malloc (n * sizeof (double));
fs = (double *) malloc (n * sizeof (double));
ws = (double *) malloc (n * sizeof (double));
yi = (double *) malloc (n * sizeof (double));
for (j = 0; j < n; j++)
{
ys[j] = j;
fs[j] = 0.0;
ws[j] = 0.0;
if ((gsl_matrix_get(bck_mask,i,j)==0) &&
(!(isnan(gsl_matrix_get(grism->grism, i,j)))))
{
fs[j]=gsl_matrix_get (grism->grism,i,j);
ws[j]=gsl_matrix_get (grism->grism,i,j);
}
}
/* Median the background */
if (interporder == -1)
{
double *tmp, med, std;
int nn = 0;
for (j = 0; j < n; j++)
{
if (ws[j] != 0.0)
{
nn++;
}
}
tmp = malloc (nn * sizeof (double));
nn = 0;
for (j = 0; j < n; j++)
{
if (ws[j] != 0.0)
{
tmp[nn] = fs[j];
nn++;
}
}
gsl_sort (tmp, 1, nn);
med = gsl_stats_median_from_sorted_data (tmp, 1, nn);
std = gsl_stats_sd (tmp, 1, nn);
//fprintf(stderr,"med: %g\n",med);
for (j = 0; j < n; j++)
{
if (ws[j] == 0.0)
{
fs[j] = med;
ws[j] = std;
}
// else
// {
// ws[j] = 1.0/sqrt(ws[j]);
// }
}
free (tmp);
tmp = NULL;
}
/* Straight average of the background */
if (interporder == 0)
{
double *tmp, sum = 0.0, avg = 0.0, std = 0.0;
int nn = 0;
nn = 0;
for (j = 0; j < n; j++)
{
if (ws[j] != 0.0)
{
nn++;
}
}
tmp = malloc (nn * sizeof (double));
nn = 0;
for (j = 0; j < n; j++)
{
if (ws[j] != 0.0)
{
sum += fs[j];
tmp[nn] = fs[j];
nn++;
}
}
if (nn > 0)
avg = sum / nn;
std = gsl_stats_sd (tmp, 1, nn);
for (j = 0; j < n; j++)
{
if (ws[j] == 0.0)
{
fs[j] = avg;
ws[j] = std;
}
// else
// {
// ws[j] = 1.0/sqrt(ws[j]);
// }
}
free (tmp);
tmp = NULL;
}
/* Linear interpolation of the background */
if (interporder == 1)
{
comp_vector_linear (ys, fs, ws, yi, n, 1);
// fit_vector_linear_t (ys, fs, ws, n);
}
/* n(>1) order interpolation of the background */
if (interporder > 1)
{
comp_vector_polyN (interporder + 1, ys,fs, ws, yi, n, 1);
// fit_vector_poly_N_t (interporder + 1, ys, fs, ws, n);
}
for (j = 0; j < n; j++)
{
if ((ys[j] < 0) || (ys[j] >= grism->grism->size2))
continue;
gsl_matrix_set (fib->bck, i, j,fs[j]);
gsl_matrix_set (fib->err, i, j,ws[j]);
}
free (ys);
ys = NULL;
free (fs);
fs = NULL;
free (ws);
ws = NULL;
}
}
/**
* Function: fullimg_background_function
* Returns the background level for the point x, y if a complete
* gsl_matrix of the background is available. This function is
* exposed to the outside through a pointer in the observation
* structure.
*
* Parameters:
* @param x ad nauseam
* @param y ad nauseam
* @param val pointer to a double to leave the background value in
* @param err pointer to a double to leave the absolute error of val in
* @param pars a gsl_matrix containing the background
*/
void
fullimg_background_function (const int x, const int y, PIXEL_T * const val,
PIXEL_T * const err,
const background * const back)
{
const fullimg_background *const fib = back->pars;
*val = gsl_matrix_get (fib->bck, (int) rint (x), (int) rint (y));
if (fib->err)
{
*err = gsl_matrix_get (fib->err, (int) rint (x), (int) rint (y));
}
else
{
*err = 0;
}
}
/**
* Function: compute_fullimg_background
* Computes a background image. All beams with ignore=1 are
* completely ignored. Anything else is not.
*
* Parameters:
* @param obs - a pointer to the observation structure to fill out
* @param oblist - a list of all objects of the observation
* @param npoints - number of points to examine when fitting the background
* @param interporder - order of the polynomial to fit to the background
* @param niter_med - order of the polynomial to fit to the background
* @param niter_fit - order of the polynomial to fit to the background
* @param kappa - order of the polynomial to fit to the background
*
* Returns:
* @return background - an allocated background structure
*
*/
background *
compute_fullimg_background (observation *obs, object **oblist,
int npoints, int interporder, const int niter_med,
const int niter_fit, const double kappa,
int nor_flag, const int sm_length, const double fwhm)
{
fullimg_background *fib;
background *backg;
gsl_matrix *bck_mask;
int i, j;
//object *const *obp;
// allocate space for the backgrounds
fib = (fullimg_background *)malloc (sizeof (fullimg_background));
fib->bck = gsl_matrix_alloc (obs->grism->size1, obs->grism->size2);
gsl_matrix_set_all (fib->bck, 0.);
fib->err = gsl_matrix_alloc (obs->grism->size1, obs->grism->size2);
gsl_matrix_set_all (fib->err, 0.);
if (nor_flag)
{
for (i = 0; i < (int)fib->bck->size1; i++)
{
for (j = 0; j < (int)fib->bck->size2; j++)
{
gsl_matrix_set (fib->bck, i, j,
gsl_matrix_get (obs->grism, i, j));
gsl_matrix_set (fib->err, i, j,
gsl_matrix_get (obs->pixerrs, i, j));
}
}
}
// allocate memory
backg = (background *)malloc (sizeof (background));
// create the mask image
bck_mask = aperture_mask(obs,oblist);
// in case that pixels may get dq values,
// make sure that there will be a dq-array
// if (niter_med > 0 || niter_fit > 0)
// {
if (!obs->dq)
obs->dq = gsl_matrix_alloc (obs->grism->size1, obs->grism->size2);
// initialize the dq-array
// gsl_matrix_set_all (obs->dq, 0.0);
// }
if (oblist != NULL)
{
// Now compute background for each beam, one after the other
// go over the whole object list
i=0;
while (oblist[i] != NULL) {
// go over each beam
for (j = 0; j < oblist[i]->nbeams; j++)
{
// check for beams to be neglected
if (oblist[i]->beams[j].ignore == 1)
{
continue;
}
else
{
// start the background interpolation
// for a specific beam
fprintf(stdout,"Computing background of BEAM %d%c.",
oblist[i]->ID,BEAM(oblist[i]->beams[j].ID));
compute_background(obs, oblist[i]->beams[j], bck_mask,
fib, npoints, interporder, niter_med,
niter_fit, kappa);
fprintf(stdout," Done.\n");
}
}
// increment the counter
i++;
}
}
// replace all NAN's with values 0.0
for (i = 0; i < (int)fib->bck->size1; i++)
{
for (j = 0; j < (int)fib->bck->size2; j++)
{
if(isnan(gsl_matrix_get (fib->bck, i, j)))
gsl_matrix_set (fib->bck, i, j,0.0);
if(isnan(gsl_matrix_get (fib->err, i, j)))
gsl_matrix_set (fib->err, i, j,0.0);
}
}
if (sm_length && fwhm)
gsmooth_background (bck_mask, sm_length, fwhm, fib);
// put together the result
backg->pars = fib;
backg->bck_func = &fullimg_background_function;
// free space
gsl_matrix_free(bck_mask);
// return the result
return backg;
}
/**
* Function: compute_backsub_mask
* Computes a mask image for the background subtraction. All pixels
* covered by at least one beam are set to a vale -100000 to distinguish
* them from pixels which are part of the background.
*
* Parameters:
* @param obs a pointer to the observation structure to fill out
* @param oblist a list of all objects of the observation
* @param npoints number of points to examine when fitting the background
* @param interporder order of the polynomial to fit to the background
*
* Returns:
* @return an allocated background structure
*
*/
background *
compute_backsub_mask (observation *obs, object **oblist)
{
fullimg_background *fib;// = malloc (sizeof (fullimg_background));
background *backg; // = malloc (sizeof (background));
gsl_matrix *bck_mask;
int i, j;
//object *const *obp;
//int tnbeams;
// make the mask image
bck_mask = aperture_mask(obs,oblist);
// allocate memory for the return structure
// and fill in some dummy values
fib = malloc (sizeof (fullimg_background));
fib->bck = gsl_matrix_alloc (obs->grism->size1, obs->grism->size2);
gsl_matrix_set_all (fib->bck, 0.);
fib->err = NULL;
// allocate memory for the return structure
backg = malloc (sizeof (background));
// transfer the pixel values from the grism image
// to the mask image
for (i = 0; i < (int)fib->bck->size1; i++)
{
for (j = 0; j < (int)fib->bck->size2; j++)
{
gsl_matrix_set (fib->bck, i, j,
gsl_matrix_get (obs->grism, i, j));
}
}
// set pixels occupied by beams
// to the value -10000000
for (i = 0; i < (int)fib->bck->size1; i++)
{
for (j = 0; j < (int)fib->bck->size2; j++)
{
if (gsl_matrix_get (bck_mask, i, j))
gsl_matrix_set (fib->bck, i, j, -1000000.0);
}
}
// release the dq-structure,
// otherwise it is saved to
// the mask image
if (obs->dq != NULL)
{
gsl_matrix_free (obs->dq);
obs->dq=NULL;
}
// release memory
gsl_matrix_free(bck_mask);
// assemble the return structure
backg->pars = fib;
backg->bck_func = &fullimg_background_function;
// return the result
return backg;
}
/**
* Function: compute_fullimg_global_background
* The subroutine computes the background image based on all pixels
* in a column which are not part of an object.
*
* Parameters:
* @param obs - a pointer to the observation structure to fill out
* @param oblist - a list of all objects of the observation
* @param interporder - order of the polynomial to fit to the background
*
* Returns:
* @return background - an allocated background structure
*
*/
background *
compute_fullimg_global_background(observation *obs, object **oblist,
int interporder, const int sm_length, const double fwhm)
{
fullimg_background *fib;
background *backg;
gsl_matrix *bck_mask;
int i, j;
object *const *obp;
int tnbeams;
// allocate memory
fib = (fullimg_background *)malloc (sizeof (fullimg_background));
backg = (background *)malloc (sizeof (background));
// allocate memory
bck_mask = aperture_mask(obs,oblist);
fib->bck = gsl_matrix_alloc (obs->grism->size1, obs->grism->size2);
fib->err = gsl_matrix_alloc (obs->grism->size1, obs->grism->size2);
// initialize the new arrays
gsl_matrix_set_all (fib->bck, 0.);
gsl_matrix_set_all (fib->err, 0.);
/* Count beams in observation */
if (oblist!=NULL)
{
tnbeams = 0;
for (obp = oblist; *obp; obp++)
{
for (i = 0; i < (*obp)->nbeams; i++)
{
// if (((*obp)->beams[i]).ignore!=1)
tnbeams++; /* Count ALL the beams */
}
}
}
/* Now compute global background using first beam grism info */
if (oblist != NULL) {
compute_global_background (oblist, 0, bck_mask,
fib, interporder);
}
// replace all NAN's with values 0.0
for (i = 0; i < (int)fib->bck->size1; i++)
{
for (j = 0; j < (int)fib->bck->size2; j++)
{
if(isnan(gsl_matrix_get (fib->bck, i, j)))
{
gsl_matrix_set (fib->bck, i, j,0.0);
}
if(isnan(gsl_matrix_get (fib->err, i, j)))
{
gsl_matrix_set (fib->err, i, j,0.0);
}
}
}
// make a Gaussian smoothing
// if requested
if (sm_length && fwhm)
gsmooth_background (bck_mask, sm_length, fwhm, fib);
// compose the result structure
backg->pars = fib;
backg->bck_func = &fullimg_background_function;
// return the result
return backg;
}
/**
* Function: free_fullimg_background
* Frees a background structure allocated using make_fullimg_background
*
* Parameters:
* @param backg - a pointer to the background structure to free
*/
void
free_fullimg_background (background * backg)
{
fullimg_background *fib = backg->pars;
gsl_matrix_free (fib->bck);
if (fib->err)
{
gsl_matrix_free (fib->err);
}
free (backg);
backg = NULL;
}
/**
* Function: aperture_mask
* This functions returns an image mask where pixels that are within
* an aperture are set to the number of aperture they appear.
* Skips any beams which are set to be ignored (ignore=1)
*
* Parameters:
* @param obs - a pointer to an observation structure
* @param oblist - a pointer to an object list
*
* Returns:
* @return bck - a pointer to a gsl_matrix
*/
gsl_matrix *
aperture_mask (observation * const obs, object **oblist)
{
int x, y,i=0,j;
double xrel, yrel, width;
is_in_descriptor iid;
px_point ll, ur;
gsl_matrix *bck;
sectionfun sf;
// create the image,
// set all values to zero
bck = gsl_matrix_alloc(obs->grism->size1,obs->grism->size2);
gsl_matrix_set_all(bck,0.0);
// Return a zero image when there is no
// beam in the list
if (oblist==NULL)
return bck;
// go over each object
while(oblist[i]!=NULL)
{
// go over each beam
for(j=0;j<oblist[i]->nbeams;j++)
{
// continue if the beam is to be ignored
if ((oblist[i]->beams[j]).ignore==1)
continue;
// check whther the trace is second order or
// even higher
if ((oblist[i]->beams[j]).spec_trace->type > 1)
{
// create the section function for second order
// traces such as FORSII
fill_in_sectionfun (&sf, (oblist[i]->beams[j]).orient,
&(oblist[i]->beams[j]));
}
else
{
// create the descriptor to set up the quadrangle routines
fill_is_in_descriptor (&iid, (oblist[i]->beams[j]).corners);
}
// check for the corners of the quadrangle.
// go over each point in x and y.
quad_to_bbox ((oblist[i]->beams[j]).corners, &ll, &ur);
for (x = ll.x; x <= ur.x; x++)
{
for (y = ll.y; y <= ur.y; y++)
{
// neglect the pixel if it is a]outside the
// image area
if ((x < 0) || (y < 0) || (x >= (int)obs->grism->size1)
|| (y >= (int)obs->grism->size2))
continue;
// check the order of the trace polynomial
if ((oblist[i]->beams[j]).spec_trace->type > 1)
{
// determine the trace distance and
// enhance the image value if the pixel
// satisfies the distance criterium
xrel = x-(oblist[i]->beams[j]).refpoint.x;
yrel = y-(oblist[i]->beams[j]).refpoint.y;
width = (oblist[i]->beams[j]).width+0.5;
if (tracedist_criteria(xrel, yrel, &sf, (oblist[i]->beams[j]).spec_trace, width))
gsl_matrix_set (bck,x,y,gsl_matrix_get (bck,x,y)+1);
}
else
{
// if (oblist[i]->ID == 11 && x == 59)
// fprintf(stdout, "xx: %i, yy: %i: %i\n", x, y, is_in (x, y, &iid));
// check whether the pixel is inside the quadrangle
// which defines the beam are, and enhance the image
// value if yes.
if (is_in (x, y, &iid))
gsl_matrix_set (bck,x,y,gsl_matrix_get (bck,x,y)+1);
}
}
}
}
// enhance the object counter
i++;
}
// return the resulting image
return bck;
}
/**
* Function: background_to_FITSimage
* Function to write the data and error content of a backgound
* observation pars component (if it is of type fullimg_background only)
* into the main HDU (data) and first extension (error) of a FITS file.
* A GQ array can be appended if an observation with a non NULL DQ is
* passed to this function
*
* Parameters:
* @param filename - name of the image
* @param bck - filled background structure
* @param obs - the observation the background is based upon
*/
void
background_to_FITSimage (char filename[], background * bck, observation *obs)
{
fitsfile *output;
long naxes[2];
int f_status = 0;
PIXEL_T *storage, *dp;
int x, y;
fullimg_background *pars;
int hdunum,hdutype;
pars = (fullimg_background *) bck->pars;
// Open the file for creating/appending
create_FITSimage (filename, 1);
fits_open_file (&output, filename, READWRITE, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"gsl_to_FITSimage: " "Could not open file: %s",
filename);
}
// count the number of extentions
fits_get_num_hdus (output, &hdunum, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"gsl_to_FITSimage: Could not get"
" number of HDU from: %s", filename);
}
// Move to last HDU
fits_movabs_hdu (output, hdunum, &hdutype, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"gsl_to_FITSimage: Could not mov"
" to HDU number %d in file: %s", hdunum, filename);
}
/* Get current HDU number */
fits_get_hdu_num (output, &hdunum);
// Deal with the SCI part of the background
naxes[0] = pars->bck->size1;
naxes[1] = pars->bck->size2;
// Allocate storage room
if (!(storage = malloc (naxes[0] * naxes[1] * sizeof (double))))
aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Out of memory");
// Populate the storage array
dp = storage;
for (y = 0; y < naxes[1]; y++)
{
for (x = 0; x < naxes[0]; x++)
{
*dp = gsl_matrix_get (pars->bck, x, y);
dp++;
}
}
/* create HDU extname */
fits_create_img (output, -32, 2, naxes, &f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"gsl_to_FITSimage: Could create SCI HDU in file: %s", filename);
}
fits_write_img (output, TFLOAT, 1, naxes[0] * naxes[1], storage,
&f_status);
if (f_status)
{
ffrprt (stderr, f_status);
aXe_message (aXe_M_FATAL, __FILE__, __LINE__,
"gsl_to_FITSimage: Could write SCI HDU in file: %s", filename);
}
/* write the HDU EXTNAME */
{
char comment[FLEN_COMMENT];
char str[FLEN_KEYWORD];
strcpy (str, "SCI");
strcpy (comment, "Extension name");
fits_write_key_str (output, "EXTNAME", str, comment, &f_status);
}
free (storage);
storage = NULL;
if (pars->err)
{
/* Deal with the error part of the background */
naxes[0] = pars->err->size1;
naxes[1] = pars->err->size2;
/* Allocate storage room */
if (!(storage = malloc (naxes[0] * naxes[1] * sizeof (double))))
{
aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Out of memory");
}
/* Populate the storage array */
dp = storage;
for (y = 0; y < naxes[1]; y++)
{
for (x = 0; x < naxes[0]; x++)
{
*dp = gsl_matrix_get (pars->err, x, y);
dp++;
}
}
/* create HDU extname */
/* Get current HDU number */
fits_get_hdu_num (output, &hdunum);
fits_create_img (output, -32, 2, naxes, &f_status);
fits_write_img (output, TFLOAT, 1, naxes[0] * naxes[1], storage,
&f_status);
/* Get current HDU number */
fits_get_hdu_num (output, &hdunum);
/* write the HDU EXTNAME */
{
char comment[FLEN_COMMENT];
char str[FLEN_KEYWORD];
strcpy (str, "ERR");
strcpy (comment, "Extension name");
fits_write_key_str (output, "EXTNAME", str, comment, &f_status);
}
free (storage);
storage = NULL;
}
/* Deal with the DQ part of the background */
if (obs->dq != NULL)
{
naxes[0] = obs->dq->size1;
naxes[1] = obs->dq->size2;
/* Allocate storage room */
if (!(storage = malloc (naxes[0] * naxes[1] * sizeof (double))))
{
aXe_message (aXe_M_FATAL, __FILE__, __LINE__, "Out of memory");
}
/* Populate the storage array */
dp = storage;
for (y = 0; y < naxes[1]; y++)
{
for (x = 0; x < naxes[0]; x++)
{
*dp = gsl_matrix_get (obs->dq, x, y);
dp++;
}
}
/* create HDU extname */
fits_create_img (output, 16, 2, naxes, &f_status);
fits_write_img (output, TFLOAT, 1, naxes[0] * naxes[1], storage,
&f_status);
/* write the HDU EXTNAME */
{
char comment[FLEN_COMMENT];
char str[FLEN_KEYWORD];
strcpy (str, "DQ");
strcpy (comment, "Extension name");
fits_write_key_str (output, "EXTNAME", str, comment, &f_status);
}
free (storage);
storage = NULL;
}
/* close file */
fits_close_file (output, &f_status);
}
/**
* Function: gsmooth_background
* Smooth all interpolated pixel in the background using a Gaussian
* function. The smoothing is done exclusively towards the x-values.
* The smoothing should help to reduce the noise from the limited number
* of background pixels.
*
* Parameters:
* @param bck_mask - the background mask
* @param smoot_length - number of pixels on either side to use for smoothing
* @param fwhm - fwhm of the Gaussian
* @param fib - the background structure
*/
void
gsmooth_background (const gsl_matrix *bck_mask, const int smooth_length,
const double fwhm, fullimg_background *fib)
{
double efactor;
int ix, iy;
gsl_vector *pixvalues;
gsl_vector *weights;
gsl_vector *pmask;
gsl_matrix *new_bck;
// allocate memory for the vectors
pixvalues = gsl_vector_alloc(2 * smooth_length + 1);
weights = gsl_vector_alloc(2 * smooth_length + 1);
pmask = gsl_vector_alloc(2 * smooth_length + 1);
// allocate the new background
// and initialize it
new_bck = gsl_matrix_alloc(bck_mask->size1, bck_mask->size2);
gsl_matrix_set_all(new_bck, 0.0);
// prepare the Gaussian
efactor = compute_efactor(fwhm);
// fill the weights
for (ix=0; ix < (int)weights->size; ix++)
gsl_vector_set(weights, ix, compute_gvalue((double)ix - (double)smooth_length, efactor));
// go over all rows
for (iy=0; iy < (int)fib->bck->size2; iy++)
{
// go over all columns
for (ix=0; ix < (int)fib->bck->size1; ix++)
{
// check whether the pixel IS part of a beam
if (!(gsl_matrix_get(bck_mask, ix, iy) != 0.0
&& gsl_matrix_get(fib->bck, ix, iy) !=0.0))
{
// transfer the old background value
gsl_matrix_set(new_bck, ix, iy, gsl_matrix_get(fib->bck, ix, iy));
}
else
{
// fill the pixel and mask values
fill_pixvalues(bck_mask, smooth_length, fib, ix, iy, pixvalues, pmask);
// fill in the weighted mean
gsl_matrix_set(new_bck, ix, iy, get_weighted_mean(pixvalues, weights, pmask));
}
}
}
// release the allocated dspace
gsl_vector_free(pixvalues);
gsl_vector_free(weights);
gsl_vector_free(pmask);
// release the memory of the
// old background
gsl_matrix_free(fib->bck);
// transfer the new background
// to the background structure
fib->bck = new_bck;
}
/**
* Function: get_weighted_mean
* The function computes the weighted mean of values stored in a value vector
* and a weight vector. As mask vector marks values pixels not to be considered.
* Using a separate mask vectorhas the advantage the weights can be kept
* constant and do not have to be re-calculated in repeated runs.
*
* Parameters:
* @param pixvalues - vector with pixel values
* @param weights - vector with weights
* @param pmask - mask vector
*
* Returns:
* @return sum/www - the weighted mean
*/
double
get_weighted_mean(const gsl_vector *pixvalues, const gsl_vector *weights,
const gsl_vector *pmask)
{
int index;
// initialize the total
// sum and weight
double sum=0.0;
double www=0.0;
for (index=0; index < (int)pixvalues->size; index ++)
{
if (gsl_vector_get(pmask, index))
{
// enhance the total sum
sum += gsl_vector_get(pixvalues, index) * gsl_vector_get(weights, index);
// enhance the total weight
www += gsl_vector_get(weights, index);
}
}
// return the total sum,
// divided by the total weight
return sum / www;
}
/**
* Function: fill_pixvalues
* The function provides the essential information for Gaussian smoothing
* for a single pixel. It fills a vector with the values of all pixels
* within the smoothing length. Not interpolated pixels are excluded.
* A mask vector provides the information on which position is filled
* with pixel values.
*
* Parameters:
* @param bck_mask - the background mask
* @param smoot_length - number of pixels on either side to use for smoothing
* @param fib - the background structure
* @param bck_mask - the background mask
* @param ix - x-value of central pixel
* @param iy - y-value of central pixel
* @param pixvalues - vector for pixel values
* @param pmask - vector for pixel mask
*/
void
fill_pixvalues(const gsl_matrix *bck_mask, const int smooth_length,
const fullimg_background *fib, const int ix, const int iy,
gsl_vector *pixvalues, gsl_vector *pmask)
{
int iact;
int index;
// initialize the pixel values
// and the mask
gsl_vector_set_all(pixvalues, 0.0);
gsl_vector_set_all(pmask, 0.0);
// iterate over the x-direction
index=0;
for (iact=ix-smooth_length; iact<=ix+smooth_length; iact++)
{
// check if you are within the chip
if (iact > -1 && iact < (int)bck_mask->size1)
{
// check whether the pixel was interpolated
// and whether the background is non-zero
if (gsl_matrix_get(bck_mask, iact, iy) != 0.0
&& gsl_matrix_get(fib->bck, iact, iy) != 0.0)
{
// if yes, get the pixel value and set the mask
gsl_vector_set(pixvalues, index, gsl_matrix_get(fib->bck, iact, iy));
gsl_vector_set(pmask, index, 1.0);
}
}
// enhance the vector index
index++;
}
}
/**
* Function: compute_gvalue
* The function computes the values of a Gauss function
* [exp(factor * xdiff^2)]. NO normalization factor is applied.
*
* Parameters:
* @param xdiff - the value [x-x_0]
* @param efactor - the factor for the exponent
*
* Returns:
* @return value - the Gaussian value
*/
double
compute_gvalue(const double xdiff, const double efactor)
{
double value;
// just compose the exp-function
value = exp(efactor * xdiff * xdiff);
// return the value
return value;
}
/**
* Function: compute_efactor
* The function computes the appropriate factor of the Gaussian for any
* FWHM given as input. This speeds up any later computation of the
* Gaussian.
*
* Parameters:
* @param fwhm - the input FWHM
*
* Returns:
* @return expfactor - the factor for the Gaussian
*/
double
compute_efactor(const double fwhm)
{
double sigma;
double expfactor;
// get the sigma value [sig = fwhm / (2 sqrt(2 ln(2)))]
sigma = fwhm / 2.3458;
// compute the factor for the Gaussian
expfactor = -1.0 / (2.0* sigma * sigma);
// return the factor
return expfactor;
}
| {
"alphanum_fraction": 0.5625435967,
"avg_line_length": 28.6718918919,
"ext": "c",
"hexsha": "2f4b7a1a8c501e3bfc8e71fa869bad97d512a3ac",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sosey/pyaxe",
"max_forks_repo_path": "cextern/src/spc_back.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sosey/pyaxe",
"max_issues_repo_path": "cextern/src/spc_back.c",
"max_line_length": 114,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sosey/pyaxe",
"max_stars_repo_path": "cextern/src/spc_back.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 14237,
"size": 53043
} |
#pragma once
#include "Common.h"
#include "PEFile.h"
#include "DelayLoadedModule.h"
#include <gsl/gsl>
namespace winlogo::pe_parser {
namespace details {
/**
* This is an input iterator for iterating over the delay-loaded modules of the delay-load
* directory.
*/
class DelayLoadDirectoryIterator {
public:
DelayLoadDirectoryIterator(PEFile file,
gsl::span<IMAGE_DELAYLOAD_DESCRIPTOR>::iterator iterator);
bool operator==(const DelayLoadDirectoryIterator& other) const noexcept;
bool operator!=(const DelayLoadDirectoryIterator& other) const noexcept;
DelayLoadedModule operator*() const noexcept;
DelayLoadDirectoryIterator& operator++() noexcept;
private:
PEFile m_peFile;
gsl::span<IMAGE_DELAYLOAD_DESCRIPTOR>::iterator m_current;
};
} // namespace details
/**
* This class represents an iterable view of a PE file's delay-loaded directory.
*/
class DelayLoadDirectory {
public:
/**
* Initialize the delay-load directory from its PE file.
*/
explicit DelayLoadDirectory(PEFile peFile);
/**
* Get the raw import descriptors.
*/
gsl::span<IMAGE_DELAYLOAD_DESCRIPTOR> rawDelayLoadDescriptors() const noexcept;
// Iterators for iterating over the imported modules.
details::DelayLoadDirectoryIterator begin() const noexcept;
details::DelayLoadDirectoryIterator end() const noexcept;
private:
/// The owning PE file.
PEFile m_peFile;
gsl::span<IMAGE_DELAYLOAD_DESCRIPTOR> m_delayLoadDescriptors;
};
} // namespace winlogo::pe_parser
| {
"alphanum_fraction": 0.723742839,
"avg_line_length": 25.7540983607,
"ext": "h",
"hexsha": "9d7da9e26a242eabd39719ff7638b2546e4b0a8b",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-11-20T12:06:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-11-20T12:06:02.000Z",
"max_forks_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "shsh999/WinLogo",
"max_forks_repo_path": "winlogo_core/DelayLoadDirectory.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e",
"max_issues_repo_issues_event_max_datetime": "2021-12-29T12:13:05.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-23T01:01:20.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "shsh999/WinLogo",
"max_issues_repo_path": "winlogo_core/DelayLoadDirectory.h",
"max_line_length": 90,
"max_stars_count": 12,
"max_stars_repo_head_hexsha": "9ad51469e3ed4bb593303d4d7919c484a3be092e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "shsh999/WinLogo",
"max_stars_repo_path": "winlogo_core/DelayLoadDirectory.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-22T07:18:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-04T22:10:13.000Z",
"num_tokens": 332,
"size": 1571
} |
/*
* 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_MATH_LINALG_H_
#define SIM_MATH_LINALG_H_
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <stdint.h>
// We use GSL style conventions here to maintain consistency with the
// GSL library. See GSL docs for comment.
#define GSL_VECTOR_STACK_ALLOC(v_, size_) \
double v_##_data[size_]; \
gsl_block v_##_block = {size_, v_##_data}; \
gsl_vector v_##_vector = {size_, 1, v_##_block.data, &v_##_block, 0}; \
gsl_vector *v_ = &v_##_vector;
#define GSL_MATRIX_STACK_ALLOC(m_, size1_, size2_) \
double m_##_data[(size1_) * (size2_)]; \
gsl_block m_##_block = {(size1_) * (size2_), m_##_data}; \
gsl_matrix m_##_matrix = {size1_, size2_, size2_, \
m_##_block.data, &m_##_block, 0}; \
gsl_matrix *m_ = &m_##_matrix;
double gsl_matrix_trace(const gsl_matrix *m);
const gsl_vector *gsl_matrix_diag(const gsl_matrix *m, gsl_vector *d);
void gsl_matrix_disp(const gsl_matrix *m);
void gsl_vector_disp(const gsl_vector *v);
const gsl_vector *gsl_vector_saturate(const gsl_vector *x, double low,
double high, gsl_vector *y);
double gsl_vector_norm_bound(const gsl_vector *x, double low);
double gsl_vector_dot(const gsl_vector *x, const gsl_vector *y);
#endif // SIM_MATH_LINALG_H_
| {
"alphanum_fraction": 0.6522583779,
"avg_line_length": 41.18,
"ext": "h",
"hexsha": "8f904ef9fd45bb38729dc2dc5eadc199c791b3ff",
"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/math/linalg.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/math/linalg.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/math/linalg.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": 504,
"size": 2059
} |
/**
*
* @file qwrapper_cgemv_tile.c
*
* PLASMA core_blas quark wrapper
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Mark Gates
* @date 2010-11-15
* @generated c Tue Jan 7 11:44:59 2014
*
**/
#include <cblas.h>
#include "common.h"
/***************************************************************************//**
*
* Version of zgemv for tile storage, to avoid dependency problem when
* computations are done within the tile. alpha and beta are passed as
* pointers so they can depend on runtime values.
*
* @param[in] Alock
* Pointer to tile owning submatrix A.
*
* @param[in] xlock
* Pointer to tile owning subvector x.
*
* @param[in] ylock
* Pointer to tile owning subvector y.
*
**/
void QUARK_CORE_cgemv_tile(Quark *quark, Quark_Task_Flags *task_flags,
PLASMA_enum trans,
int m, int n,
const PLASMA_Complex32_t *alpha, const PLASMA_Complex32_t *A, int lda,
const PLASMA_Complex32_t *x, int incx,
const PLASMA_Complex32_t *beta, PLASMA_Complex32_t *y, int incy,
const PLASMA_Complex32_t *Alock,
const PLASMA_Complex32_t *xlock,
const PLASMA_Complex32_t *ylock)
{
/* Quick return. Bad things happen if sizeof(...)*m*n is zero in QUARK_Insert_Task */
if ( m == 0 || n == 0 )
return;
DAG_SET_PROPERTIES("gemv", "lightslateblue");
QUARK_Insert_Task(quark, CORE_cgemv_tile_quark, task_flags,
sizeof(PLASMA_enum), &trans, VALUE,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex32_t), alpha, INPUT,
sizeof(PLASMA_Complex32_t)*m*n, A, NODEP, /* input; see Alock */
sizeof(int), &lda, VALUE,
sizeof(PLASMA_Complex32_t)*n, x, NODEP, /* input; see xlock */
sizeof(int), &incx, VALUE,
sizeof(PLASMA_Complex32_t), beta, INPUT,
sizeof(PLASMA_Complex32_t)*m, y, NODEP, /* inout; see ylock */
sizeof(int), &incy, VALUE,
sizeof(PLASMA_Complex32_t)*m*n, Alock, INPUT,
sizeof(PLASMA_Complex32_t)*n, xlock, INPUT,
sizeof(PLASMA_Complex32_t)*m, ylock, INOUT,
0);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_cgemv_tile_quark = PCORE_cgemv_tile_quark
#define CORE_cgemv_tile_quark PCORE_cgemv_tile_quark
#endif
void CORE_cgemv_tile_quark(Quark *quark)
{
PLASMA_enum trans;
int m, n, lda, incx, incy;
const 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.5273675065,
"avg_line_length": 37.9450549451,
"ext": "c",
"hexsha": "788dbabc9872eeb5c3125ae28e371bad74dfa375",
"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_tile.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "zhuangsc/Plasma-ompss1",
"max_issues_repo_path": "core_blas-qwrapper/qwrapper_cgemv_tile.c",
"max_line_length": 98,
"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_tile.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 923,
"size": 3453
} |
// Copyright 2012 Jesse Windle - jesse.windle@gmail.com
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see
// <http://www.gnu.org/licenses/>.
/*********************************************************************
This class wraps GSL's random number generator and random
distribution functions into a class. We use the Mersenne Twister
for random number generation since it has a large period, which is
what we want for MCMC simulation.
When compiling include -lgsl -lcblas -llapack .
*********************************************************************/
#ifndef __BASICRNG__
#define __BASICRNG__
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_sf.h>
#include <iostream>
#include <fstream>
#include <ctime>
#include <string>
#include <cmath>
using std::string;
using std::ofstream;
using std::ifstream;
//////////////////////////////////////////////////////////////////////
// RNG //
//////////////////////////////////////////////////////////////////////
class BasicRNG {
protected:
gsl_rng * r;
public:
// Constructors and destructors.
BasicRNG(unsigned long seed);
virtual ~BasicRNG()
{ gsl_rng_free (r); }
// Assignment=
BasicRNG& operator=(const BasicRNG& rng);
// Read / Write / Set
bool read (const string& filename);
bool write(const string& filename);
void set(unsigned long seed);
// Get rng -- be careful. Needed for other random variates.
gsl_rng* getrng() { return r; }
// Random variates.
double unif (); // Uniform
double expon_mean(double mean); // Exponential
double expon_rate(double rate); // Exponential
double chisq (double df); // Chisq
double norm (double sd); // Normal
double norm (double mean , double sd); // Normal
double gamma_scale (double shape, double scale); // Gamma_Scale
double gamma_rate (double shape, double rate); // Gamma_Rate
double igamma(double shape, double scale); // Inv-Gamma
double flat (double a=0 , double b=1 ); // Flat
double beta (double a=1.0, double b=1.0); // Beta
int bern (double p); // Bernoulli
// CDF
static double p_norm (double x, int use_log=0);
static double p_gamma_rate(double x, double shape, double rate, int use_log=0);
// Density
static double d_beta(double x, double a, double b);
// Utility
static double Gamma (double x, int use_log=0);
}; // BasicRNG
#endif
////////////////////////////////////////////////////////////////////////////////
// APPENDIX //
////////////////////////////////////////////////////////////////////////////////
// If you make everything inline within the same translation unit then that
// function will not be callable from anohter translation unit. You can see
// that the function is missing by using the nm command.
| {
"alphanum_fraction": 0.5768485184,
"avg_line_length": 32.2410714286,
"ext": "h",
"hexsha": "7f4e4d2325ee598eba308e62c0838fc9f64856cb",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-18T21:31:01.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-18T21:31:01.000Z",
"max_forks_repo_head_hexsha": "d63dff8af7523fc1e8e11d2c2906daa16aaff4dc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "TeoGiane/SPMIX",
"max_forks_repo_path": "src/polyagamma/GRNG.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "d63dff8af7523fc1e8e11d2c2906daa16aaff4dc",
"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": "TeoGiane/SPMIX",
"max_issues_repo_path": "src/polyagamma/GRNG.h",
"max_line_length": 82,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "d63dff8af7523fc1e8e11d2c2906daa16aaff4dc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "TeoGiane/SPMIX",
"max_stars_repo_path": "src/polyagamma/GRNG.h",
"max_stars_repo_stars_event_max_datetime": "2020-12-22T09:35:09.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-12-22T09:35:09.000Z",
"num_tokens": 791,
"size": 3611
} |
#include <pygsl/solver.h>
#include <gsl/gsl_roots.h>
const char * filename = __FILE__;
PyObject *module = NULL;
static const char root_f_type_name[] = "F-RootSolver";
static const char root_fdf_type_name[] = "FdF-RootSolver";
static const char root_f_root_doc[] = "Get the value of F";
static const char root_set_f_doc[] = "";
static const char root_set_fdf_doc[] = "";
static const char root_fdf_root_doc[] = "";
static const char root_x_lower_doc [] = "Get the lower bound of x";
static const char root_x_upper_doc [] = "Get the upper bound of x";
static PyObject*
PyGSL_root_f_root(PyGSL_solver *self, PyObject *args)
{
return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_root_fsolver_root);
}
static PyObject*
PyGSL_root_fdf_root(PyGSL_solver *self, PyObject *args)
{
return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_root_fdfsolver_root);
}
static PyObject*
PyGSL_root_x_lower(PyGSL_solver *self, PyObject *args)
{
return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_root_fsolver_x_lower);
}
static PyObject*
PyGSL_root_x_upper(PyGSL_solver *self, PyObject *args)
{
return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_root_fsolver_x_upper);
}
static PyObject*
PyGSL_root_solver_test_interval(PyGSL_solver * self, PyObject *args)
{
double epsabs, epsrel;
gsl_root_fsolver *s = (gsl_root_fsolver *) self->solver;
if(!PyArg_ParseTuple(args, "dd", &epsabs, &epsrel))
return NULL;
return PyInt_FromLong(gsl_root_test_interval(s->x_lower, s->x_upper, epsabs, epsrel));
}
static PyObject*
PyGSL_root_set_f(PyGSL_solver *self, PyObject *args, PyObject *kw)
{
return PyGSL_solver_set_f(self, args, kw, (void *)gsl_root_fsolver_set, 0);
}
static PyObject*
PyGSL_root_set_fdf(PyGSL_solver *self, PyObject *args, PyObject *kw)
{
return PyGSL_solver_set_f(self, args, kw, (void *)gsl_root_fdfsolver_set, 1);
}
static PyMethodDef PyGSL_root_fmethods[] = {
{"root", (PyCFunction)PyGSL_root_f_root, METH_NOARGS, (char *)root_f_root_doc},
{"x_lower", (PyCFunction)PyGSL_root_x_lower, METH_NOARGS, (char *)root_x_lower_doc},
{"x_upper", (PyCFunction)PyGSL_root_x_upper, METH_NOARGS, (char *)root_x_upper_doc},
{"set", (PyCFunction)PyGSL_root_set_f, METH_VARARGS|METH_KEYWORDS, (char *)root_set_f_doc},
{"test_interval",(PyCFunction)PyGSL_root_solver_test_interval, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL} /* sentinel */
};
static PyMethodDef PyGSL_root_fdfmethods[] = {
{"root", (PyCFunction)PyGSL_root_fdf_root, METH_NOARGS, (char *)root_fdf_root_doc},
{"set", (PyCFunction)PyGSL_root_set_fdf, METH_VARARGS|METH_KEYWORDS, (char *)root_set_fdf_doc},
{NULL, NULL, 0, NULL} /* sentinel */
};
const struct _SolverStatic
root_solver_f = {{(void_m_t) gsl_root_fsolver_free,
/* gsl_multimin_fminimizer_restart */ (void_m_t) NULL,
(name_m_t) gsl_root_fsolver_name,
(int_m_t) gsl_root_fsolver_iterate},
1, PyGSL_root_fmethods, root_f_type_name},
root_solver_fdf = {{(void_m_t) gsl_root_fdfsolver_free,
/* gsl_multimin_fminimizer_restart */ (void_m_t) NULL,
(name_m_t) gsl_root_fdfsolver_name,
(int_m_t) gsl_root_fdfsolver_iterate},
3, PyGSL_root_fdfmethods, root_fdf_type_name};
static PyObject*
PyGSL_root_f_init(PyObject *self, PyObject *args,
const gsl_root_fsolver_type * type)
{
PyObject *tmp=NULL;
solver_alloc_struct s = {type, (void_an_t) gsl_root_fsolver_alloc,
&root_solver_f};
FUNC_MESS_BEGIN();
tmp = PyGSL_solver_dn_init(self, args, &s, 0);
FUNC_MESS_END();
return tmp;
}
static PyObject*
PyGSL_root_fdf_init(PyObject *self, PyObject *args,
const gsl_root_fdfsolver_type * type)
{
PyObject *tmp=NULL;
solver_alloc_struct s = {type, (void_an_t) gsl_root_fdfsolver_alloc,
&root_solver_fdf};
FUNC_MESS_BEGIN();
tmp = PyGSL_solver_dn_init(self, args, &s, 0);
FUNC_MESS_END();
return tmp;
}
#define AROOT_F(name) \
static PyObject* PyGSL_root_init_ ## name (PyObject *self, PyObject *args)\
{ \
PyObject *tmp = NULL; \
FUNC_MESS_BEGIN(); \
tmp = PyGSL_root_f_init(self, args, gsl_root_fsolver_ ## name); \
if (tmp == NULL){ \
PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \
} \
FUNC_MESS_END(); \
return tmp; \
}
#define AROOT_FDF(name) \
static PyObject* PyGSL_root_init_ ## name (PyObject *self, PyObject *args)\
{ \
PyObject *tmp = NULL; \
FUNC_MESS_BEGIN(); \
tmp = PyGSL_root_fdf_init(self, args, gsl_root_fdfsolver_ ## name); \
if (tmp == NULL){ \
PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \
} \
FUNC_MESS_END(); \
return tmp; \
}
AROOT_F(bisection)
AROOT_F(falsepos)
AROOT_F(brent)
AROOT_FDF(newton)
AROOT_FDF(secant)
AROOT_FDF(steffenson)
static PyObject*
PyGSL_root_test_delta(PyObject * self, PyObject *args)
{
double x_lower, x_upper, epsabs, epsrel;
if(!PyArg_ParseTuple(args, "dddd", &x_lower, &x_upper, &epsabs, &epsrel))
return NULL;
return PyInt_FromLong(gsl_root_test_delta(x_lower, x_upper, epsabs, epsrel));
}
static PyObject*
PyGSL_root_test_interval(PyObject * self, PyObject *args)
{
double x_lower, x_upper, epsabs, epsrel;
if(!PyArg_ParseTuple(args, "dddd", &x_lower, &x_upper, &epsabs, &epsrel))
return NULL;
return PyInt_FromLong(gsl_root_test_interval(x_lower, x_upper, epsabs, epsrel));
}
static const char PyGSL_roots_module_doc [] = "XXX Missing ";
static PyMethodDef mMethods[] = {
/* solver */
{"bisection", PyGSL_root_init_bisection, METH_NOARGS, NULL},
{"falsepos", PyGSL_root_init_falsepos, METH_NOARGS, NULL},
{"brent", PyGSL_root_init_brent, METH_NOARGS, NULL},
{"newton", PyGSL_root_init_newton, METH_NOARGS, NULL},
{"secant", PyGSL_root_init_secant, METH_NOARGS, NULL},
{"steffenson", PyGSL_root_init_steffenson, METH_NOARGS, NULL},
/* functions */
{"test_delta", PyGSL_root_test_delta, METH_VARARGS, NULL},
{"test_interval", PyGSL_root_test_interval, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL}
};
void
initroots(void)
{
PyObject* m, *dict, *item;
FUNC_MESS_BEGIN();
m=Py_InitModule("roots", mMethods);
module = m;
assert(m);
dict = PyModule_GetDict(m);
if(!dict)
goto fail;
init_pygsl()
import_pygsl_solver();
assert(PyGSL_API);
if (!(item = PyString_FromString((char*)PyGSL_roots_module_doc))){
PyErr_SetString(PyExc_ImportError,
"I could not generate module doc string!");
goto fail;
}
if (PyDict_SetItemString(dict, "__doc__", item) != 0){
PyErr_SetString(PyExc_ImportError,
"I could not init doc string!");
goto fail;
}
FUNC_MESS_END();
fail:
FUNC_MESS("FAIL");
return;
}
| {
"alphanum_fraction": 0.6100732138,
"avg_line_length": 36.1735159817,
"ext": "c",
"hexsha": "5f29e10765bf97c63bf5c7096aefd9ca23eaa7f8",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z",
"max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "juhnowski/FishingRod",
"max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/roots.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "juhnowski/FishingRod",
"max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/roots.c",
"max_line_length": 112,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "juhnowski/FishingRod",
"max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/roots.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2076,
"size": 7922
} |
/******************************************************************************
(c) 2017 - 2019 Scientific Computation Research Center,
Rensselaer Polytechnic Institute. All rights reserved.
This work is open source software, licensed under the terms of the
BSD license as described in the LICENSE file in the top-level directory.
*******************************************************************************/
#ifndef MSI_PETSC_H
#define MSI_PETSC_H
#include "msi.h"
#include "msi_solver.h"
#include <pumi.h>
#include <petsc.h>
#include <map>
#include <vector>
// Added for the synchronization function
// TODO : make it so these are not necessary
#include "apfFieldData.h"
#include "apfNew.h"
#include "apfNumbering.h"
#include "apfNumberingClass.h"
#include "apfShape.h"
int copyField2PetscVec(pField f, Vec& petscVec);
int copyPetscVec2Field(Vec& petscVec, pField f, bool);
void printMemStat( );
// NOTE: all field related interaction is done through msi api rather than apf
class msi_matrix
{
public:
msi_matrix(pField f);
virtual ~msi_matrix( );
virtual int initialize( ) = 0; // create a matrix and solver object
int destroy( ); // delete a matrix and solver object
int set_value(msi_int row,
msi_int col,
int operation,
double real_val,
double imag_val); // insertion/addition with global numbering
// values use column-wise, size * size block
int add_values(msi_int rsize,
msi_int* rows,
msi_int csize,
msi_int* columns,
double* values);
int get_values(std::vector<msi_int>& rows,
std::vector<msi_int>& n_columns,
std::vector<msi_int>& columns,
std::vector<double>& values);
void set_status(int s) { mat_status = s; }
int get_status( ) { return mat_status; }
int get_scalar_type( )
{
#ifdef MSI_COMPLEX
return 1;
#else
return 0;
#endif
}
pField get_field( ) { return field; }
int write(const char* file_name);
virtual int get_type( ) const = 0;
virtual int assemble( ) = 0;
virtual int setupMat( ) = 0;
virtual int preAllocate( ) = 0;
virtual int flushAssembly( );
int printInfo( );
// PETSc data structures
Mat* A;
protected:
int setupSeqMat( );
int setupParaMat( );
int preAllocateSeqMat( );
int preAllocateParaMat( );
int mat_status;
pField field; // the field that provide numbering
};
class matrix_mult : public msi_matrix
{
public:
matrix_mult(pField f) : msi_matrix(f), localMat(1) { initialize( ); }
virtual int initialize( );
void set_mat_local(bool flag) { localMat = flag; }
int is_mat_local( ) { return localMat; }
int multiply(pField in_f, pField out_f, bool sync = true);
virtual int get_type( ) const { return 0; } // MSI_MULTIPLY; }
virtual int assemble( );
virtual int setupMat( );
virtual int preAllocate( );
private:
bool localMat;
};
class matrix_solve : public msi_matrix
{
public:
matrix_solve(pField f);
virtual int initialize( );
virtual ~matrix_solve( );
int solve(pField rhs, pField sol, bool sync = true);
int set_bc(msi_int row);
int set_row(msi_int row, msi_int numVals, msi_int* colums, double* vals);
int add_blockvalues(msi_int rbsize,
msi_int* rows,
msi_int cbsize,
msi_int* columns,
double* values);
virtual int get_type( ) const { return 1; }
virtual int assemble( );
virtual int setupMat( );
virtual int preAllocate( );
int iterNum;
private:
int setUpRemoteAStruct( );
int setUpRemoteAStructParaMat( );
int setKspType( );
int kspSet;
KSP* ksp;
Mat remoteA;
std::set<int> remotePidOwned;
std::map<int, std::map<int, int> >
remoteNodeRow; // <pid, <locnode>, numAdj >
std::map<int, int> remoteNodeRowSize;
};
#endif
| {
"alphanum_fraction": 0.6284837637,
"avg_line_length": 31.0396825397,
"ext": "h",
"hexsha": "be42f64936537807b64c7740de6ff11ef2a6aa77",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2018-04-19T18:31:27.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-01-09T19:00:36.000Z",
"max_forks_repo_head_hexsha": "0eb22b50c313f63b336a98988c2777b7b2d65197",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "SCOREC/msi",
"max_forks_repo_path": "include/msi_petsc.h",
"max_issues_count": 20,
"max_issues_repo_head_hexsha": "0eb22b50c313f63b336a98988c2777b7b2d65197",
"max_issues_repo_issues_event_max_datetime": "2019-11-21T16:38:35.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-04-18T19:33:33.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "SCOREC/msi",
"max_issues_repo_path": "include/msi_petsc.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "0eb22b50c313f63b336a98988c2777b7b2d65197",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "SCOREC/msi",
"max_stars_repo_path": "include/msi_petsc.h",
"max_stars_repo_stars_event_max_datetime": "2020-10-10T11:50:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-10T11:50:23.000Z",
"num_tokens": 1021,
"size": 3911
} |
#include <sys/time.h>
#include <cblas.h>
#include "kadbg.h"
#include "matrix.h"
#include "kalas.h"
#define MAX_BUF_SIZE 128*1024*1024
#define NUM_OF_STEPS 1024
void test_sgemm( KalasState *state)
{
int rowA, colA, rowB, colB, rowC, colC;
Matrix *matA = NULL, *matB = NULL, *matC1 = NULL, *matC2 = NULL;
float alpha = 1.0, beta = 0.0, e;
struct timeval t;
double ts, te;
for ( rowA = NUM_OF_STEPS; rowA <= MAX_BUF_SIZE / NUM_OF_STEPS
/ sizeof(float);
rowA += NUM_OF_STEPS) {
for ( colA = NUM_OF_STEPS; rowA * colA <= MAX_BUF_SIZE / sizeof(float);
colA += NUM_OF_STEPS) {
rowB = colA;
rowC = rowA;
for ( colB = NUM_OF_STEPS; rowB * colB <= MAX_BUF_SIZE / sizeof(float);
colB += NUM_OF_STEPS) {
colC = colB;
if ( rowC * colC > MAX_BUF_SIZE / sizeof(float)) break;
if ( IS_FAILED( ( matA = matrixNew( rowA, colA, colA,
sizeof(float), true)) != NULL))
break;
if ( IS_FAILED( ( matB = matrixNew( rowB, colB, colB,
sizeof(float), true)) != NULL))
break;
if ( IS_FAILED( ( matC1 = matrixNew( rowC, colC, colC,
sizeof(float), true)) != NULL))
break;
if ( IS_FAILED( ( matC2 = matrixNew( rowC, colC, colC,
sizeof(float), true)) != NULL))
break;
printf( "(%d,%d)(%d,%d)=(%d,%d) ",
rowA, colA, rowB, colB, rowC, colC);
gettimeofday( &t, NULL);
ts = t.tv_sec + (double)(t.tv_usec) / 1000000.0;
cblas_sgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,
matC1->row, matC1->col, matA->col,
alpha, matA->elm, matA->col,
matB->elm, matB->col, beta,
matC1->elm, matC1->col);
gettimeofday( &t, NULL);
te = t.tv_sec + (double)(t.tv_usec) / 1000000.0;
printf( "%f s %f GFlops ", (te - ts),
(double)rowA * (double)colA * (double)colB * 2.0
/ ( te - ts) / 1000000000.0);
gettimeofday( &t, NULL);
ts = t.tv_sec + (double)(t.tv_usec) / 1000000.0;
kalasSgemm( state, clblasRowMajor, clblasNoTrans, clblasNoTrans,
matC2->row, matC2->col, matA->col,
alpha, matA->elm, matA->ld,
matB->elm, matB->ld, beta,
matC2->elm, matC2->ld);
gettimeofday( &t, NULL);
te = t.tv_sec + (double)(t.tv_usec) / 1000000.0;
printf( "%f s %f GFlops ", (te - ts),
(double)rowA * (double)colA * (double)colB * 2.0
/ ( te - ts) / 1000000000.0);
printf( "%e err", matrixCalcDiff( matC1, matC2));
putchar( '\n');
matrixDelete( matA); matA = NULL;
matrixDelete( matB); matB = NULL;
matrixDelete( matC1); matC1 = NULL;
matrixDelete( matC2); matC2 = NULL;
}
}
}
}
void test_dgemm( KalasState *state)
{
int rowA, colA, rowB, colB, rowC, colC;
Matrix *matA = NULL, *matB = NULL, *matC1 = NULL, *matC2 = NULL;
double alpha = 1.0, beta = 0.0, e;
struct timeval t;
double ts, te;
for ( rowA = NUM_OF_STEPS; rowA <= MAX_BUF_SIZE / NUM_OF_STEPS
/ sizeof(double);
rowA += NUM_OF_STEPS) {
for ( colA = NUM_OF_STEPS; rowA * colA <= MAX_BUF_SIZE / sizeof(double);
colA += NUM_OF_STEPS) {
rowB = colA;
rowC = rowA;
for ( colB = NUM_OF_STEPS; rowB * colB <= MAX_BUF_SIZE / sizeof(double);
colB += NUM_OF_STEPS) {
colC = colB;
if ( rowC * colC > MAX_BUF_SIZE / sizeof(double)) break;
if ( IS_FAILED( ( matA = matrixNew( rowA, colA, colA,
sizeof(double), true)) != NULL))
break;
if ( IS_FAILED( ( matB = matrixNew( rowB, colB, colB,
sizeof(double), true)) != NULL))
break;
if ( IS_FAILED( ( matC1 = matrixNew( rowC, colC, colC,
sizeof(double), true)) != NULL))
break;
if ( IS_FAILED( ( matC2 = matrixNew( rowC, colC, colC,
sizeof(double), true)) != NULL))
break;
printf( "(%d,%d)(%d,%d)=(%d,%d) ",
rowA, colA, rowB, colB, rowC, colC);
gettimeofday( &t, NULL);
ts = t.tv_sec + (double)(t.tv_usec) / 1000000.0;
cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans,
matC1->row, matC1->col, matA->col,
alpha, matA->elm, matA->col,
matB->elm, matB->col, beta,
matC1->elm, matC1->col);
gettimeofday( &t, NULL);
te = t.tv_sec + (double)(t.tv_usec) / 1000000.0;
printf( "%f s %f GFlops ", (te - ts),
(double)rowA * (double)colA * (double)colB * 2.0
/ ( te - ts) / 1000000000.0);
gettimeofday( &t, NULL);
ts = t.tv_sec + (double)(t.tv_usec) / 1000000.0;
kalasDgemm( state, clblasRowMajor, clblasNoTrans, clblasNoTrans,
matC2->row, matC2->col, matA->col,
alpha, matA->elm, matA->ld,
matB->elm, matB->ld, beta,
matC2->elm, matC2->ld);
gettimeofday( &t, NULL);
te = t.tv_sec + (double)(t.tv_usec) / 1000000.0;
printf( "%f s %f GFlops ", (te - ts),
(double)rowA * (double)colA * (double)colB * 2.0
/ ( te - ts) / 1000000000.0);
printf( "%e err", matrixCalcDiff( matC1, matC2));
putchar( '\n');
matrixDelete( matA); matA = NULL;
matrixDelete( matB); matB = NULL;
matrixDelete( matC1); matC1 = NULL;
matrixDelete( matC2); matC2 = NULL;
}
}
}
}
int main( void)
{
KalasState *state;
state = kalasStateNew();
test_sgemm( state);
test_dgemm( state);
kalasStateDelete( state);
return 0;
}
| {
"alphanum_fraction": 0.5595281976,
"avg_line_length": 29.9779005525,
"ext": "c",
"hexsha": "f8a80572598dce504363cf8d5ad40acea8b8ae85",
"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": "acb6ec90876383e3763768976ab9380d32ab59d2",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "kalab1998e/kalas",
"max_forks_repo_path": "src/test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "acb6ec90876383e3763768976ab9380d32ab59d2",
"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": "kalab1998e/kalas",
"max_issues_repo_path": "src/test.c",
"max_line_length": 75,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "acb6ec90876383e3763768976ab9380d32ab59d2",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "kalab1998e/kalas",
"max_stars_repo_path": "src/test.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1905,
"size": 5426
} |
/// \file linalg.h
/// \brief Wrapper for including CBLAS and LAPACKE
#ifndef LINALG_H
#define LINALG_H
#define LAPACK_DISABLE_NAN_CHECK
#ifdef USE_MKL
#include <mkl_cblas.h>
#include <mkl_lapacke.h>
#else
// generic include
#include <cblas.h>
#include <lapacke.h>
#endif
#endif
| {
"alphanum_fraction": 0.7335640138,
"avg_line_length": 12.0416666667,
"ext": "h",
"hexsha": "c905c047ff1e4dfb86b30e0c496adf52029e0499",
"lang": "C",
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-08-17T19:31:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-04-08T13:10:47.000Z",
"max_forks_repo_head_hexsha": "da47a4699b1efcd6d5854760564f1b8b3c4b094b",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "cmendl/tensor_networks",
"max_forks_repo_path": "include/linalg.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "da47a4699b1efcd6d5854760564f1b8b3c4b094b",
"max_issues_repo_issues_event_max_datetime": "2022-02-18T00:16:55.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-02-18T00:16:55.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "cmendl/tensor_networks",
"max_issues_repo_path": "include/linalg.h",
"max_line_length": 50,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "da47a4699b1efcd6d5854760564f1b8b3c4b094b",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "cmendl/tensor_networks",
"max_stars_repo_path": "include/linalg.h",
"max_stars_repo_stars_event_max_datetime": "2021-08-17T19:31:31.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-28T19:11:08.000Z",
"num_tokens": 87,
"size": 289
} |
/* this program is in the public domain */
#include "bench-user.h"
#include <math.h>
#ifdef HAVE_GSL_GSL_VERSION_H
#include <gsl/gsl_version.h>
#endif
static const char *mkvers(void)
{
#ifdef HAVE_GSL_GSL_VERSION_H
return gsl_version;
#else
return "unknown"
#endif
}
BEGIN_BENCH_DOC
BENCH_DOC("name", NAME)
BENCH_DOC("package", "GNU Scientific Library (GSL)")
BENCH_DOC("author", "Brian Gough")
BENCH_DOC("year", "2002")
BENCH_DOC("url", "http://sources.redhat.com/gsl")
BENCH_DOC("url-was-valid-on", "Thu Jul 26 07:48:45 EDT 2001")
BENCH_DOC("copyright",
"Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough\n"
"\n"
"This program is free software; you can redistribute it and/or modify\n"
"it under the terms of the GNU General Public License as published by\n"
"the Free Software Foundation; either version 2 of the License, or (at\n"
"your option) any later version.\n")
BENCH_DOC("language", "C")
BENCH_DOCF("version", mkvers)
END_BENCH_DOC
#define CAT0(a, b) a ## b
#define CAT(a, b) CAT0(a, b)
#ifdef BENCHFFT_SINGLE
#include <gsl/gsl_fft_complex_float.h>
#include <gsl/gsl_fft_real_float.h>
#include <gsl/gsl_fft_halfcomplex_float.h>
#define C(x) CAT(gsl_fft_complex_float_, P(x))
#define R(x) CAT(gsl_fft_real_float_radix2_, x)
#define H(x) CAT(gsl_fft_halfcomplex_float_radix2_, x)
#else
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_fft_real.h>
#include <gsl/gsl_fft_halfcomplex.h>
#define C(x) CAT(gsl_fft_complex_, P(x))
#define R(x) CAT(gsl_fft_real_radix2_, x)
#define H(x) CAT(gsl_fft_halfcomplex_radix2_, x)
#endif
int can_do(struct problem *p)
{
return (p->rank == 1 &&
#ifdef DO_COMPLEX
p->kind == PROBLEM_COMPLEX
#else
p->kind == PROBLEM_REAL
#endif
&& problem_power_of_two(p, 1));
}
void copy_h2c(struct problem *p, bench_complex *out)
{
copy_h2c_1d_halfcomplex(p, out, -1.0);
}
void copy_c2h(struct problem *p, bench_complex *in)
{
copy_c2h_1d_halfcomplex(p, in, -1.0);
}
void setup(struct problem *p)
{
BENCH_ASSERT(can_do(p));
/* nothing to do */
}
void doit(int iter, struct problem *p)
{
int i;
int n = p->n[0];
void *in = p->in;
if (p->kind == PROBLEM_COMPLEX) {
#ifdef DO_COMPLEX
if (p->sign == -1) {
for (i = 0; i < iter; ++i)
C(forward)(in, 1, n);
} else {
for (i = 0; i < iter; ++i)
C(backward)(in, 1, n);
}
#endif
} else {
#ifdef DO_REAL
if (p->sign == -1) {
for (i = 0; i < iter; ++i)
R(transform)(in, 1, n);
} else {
for (i = 0; i < iter; ++i)
H(transform)(in, 1, n);
}
#endif
}
}
void done(struct problem *p)
{
UNUSED(p);
}
| {
"alphanum_fraction": 0.653092006,
"avg_line_length": 22.4745762712,
"ext": "c",
"hexsha": "2c4e1619d15f88069eeb19a7f0741e90e7e8b136",
"lang": "C",
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2022-01-26T11:50:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-06-02T08:44:13.000Z",
"max_forks_repo_head_hexsha": "6c754dca9f53f16886a71744199a0bbce40b3e1a",
"max_forks_repo_licenses": [
"ImageMagick"
],
"max_forks_repo_name": "mreineck/benchfft",
"max_forks_repo_path": "benchees/gsl/doit2.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "6c754dca9f53f16886a71744199a0bbce40b3e1a",
"max_issues_repo_issues_event_max_datetime": "2022-01-21T21:39:55.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-01T18:15:43.000Z",
"max_issues_repo_licenses": [
"ImageMagick"
],
"max_issues_repo_name": "mreineck/benchfft",
"max_issues_repo_path": "benchees/gsl/doit2.c",
"max_line_length": 75,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "6c754dca9f53f16886a71744199a0bbce40b3e1a",
"max_stars_repo_licenses": [
"ImageMagick"
],
"max_stars_repo_name": "mreineck/benchfft",
"max_stars_repo_path": "benchees/gsl/doit2.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-18T01:31:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-08-11T02:13:09.000Z",
"num_tokens": 856,
"size": 2652
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "mersenne.h"
#include <complex.h>
#include <lapacke.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846264338327
#endif
/* Lattice size and dimensions */
#define NT 48
#define NX 6
#define ND 2
#define NDIRS (2*ND)
#define TUP 0
#define XUP 1
#define TDN 2
#define XDN 3
#define VOLUME (NT*NX)
//One staggered fermion
#define Nf 2
//#define ANTISYMMETRIC //Antisymmetric boundaries
//#define SYMMETRIC //implemented in Thirring_hop
#define OPENX //open in space, (anti)symmetric in time
#define CG_ACCURACY 1e-30
#define CG_MAX_ITER 10000
/* Simulation parameters */
double m;
double g;
double mu;
/* Neighbour index arrays, to be filled at the beginning
*/
int *tup,*xup,*tdn,*xdn;
double ***A;
int ***eta; //Staggered eta matrix
/* Functions for fetching neighboring coordinates */
static inline int tdir(int t, int dir){
if( dir == TUP ) return tup[t];
if( dir == TDN ) return tdn[t];
return(t);
}
static inline int xdir(int x, int dir){
if( dir == XUP ) return xup[x];
if( dir == XDN ) return xdn[x];
return(x);
}
/* Opposite of a direction */
static inline int opp_dir(int dir){
return ( dir + ND ) % NDIRS;
}
double gauge_action(){
double S = 0;
for( int t=0;t<NT;t++) for( int x=0;x<NX;x++) for( int dir=0; dir<ND; dir++ ) {
S+= 1.-cos(A[t][x][dir]);
}
return Nf/g*S;
}
void update_gauge(){
for( int t=0;t<NT;t++) for( int x=0;x<NX;x++) for( int dir=0; dir<ND; dir++ ) {
double s1 = -Nf/g*cos(A[t][x][dir]);
double new = 2*M_PI*mersenne()-M_PI;
double s2 = -Nf/g*cos(new);
double edS = exp(-s2+s1);
//printf("New A=%f at (%d,%d), direction %d, exp(-deltaS)=%g\n", A[t][x][dir],t,x,dir, edS);
if( mersenne() < edS ) {
A[t][x][dir] = new;
//printf("Accepted\n");
}
}
}
void fermion_matrix( _Complex double * M ){
static double expmu, expmmu;
static int init=1;
if(init){
expmu = exp(mu);
expmmu = exp(-mu);
init = 0;
}
for( int i=0;i<VOLUME*VOLUME;i++) M[i] = 0;
for( int t=0;t<NT;t++) for( int x=0;x<NX;x++){
M[(NX*t + x) + (NX*t+x)*VOLUME] = m;
int t2 = tup[t];
int index = (NX*t + x) + (NX*t2+x)*VOLUME;
double sA = sin(A[t][x][0]);
double cA = cos(A[t][x][0]);
if( t2 > t ) M[index] = 0.5 * (cA + sA*I) * eta[t][x][0] * expmu ;
else M[index] = -0.5 * (cA + sA*I) * eta[t][x][0] * expmu ;
t2 = tdn[t];
sA = sin(A[t2][x][0]);
cA = cos(A[t2][x][0]);
index = (NX*t + x) + (NX*t2+x)*VOLUME;
if( t2 > t ) M[index] = 0.5 * (cA - sA*I) * eta[t2][x][0] * expmmu ;
else M[index] = -0.5 * (cA - sA*I) * eta[t2][x][0] * expmmu ;
int x2 = xup[x];
index = (NX*t + x) + (NX*t+x2)*VOLUME;
sA = sin(A[t][x][1]);
cA = cos(A[t][x][1]);
if( x2 > x ) M[index] = 0.5 * (cA + sA*I) * eta[t][x][1] ;
else M[index] = -0.5 * (cA + sA*I) * eta[t][x][1] ;
x2 = xdn[x];
index = (NX*t + x) + (NX*t+x2)*VOLUME;
sA = sin(A[t][x2][1]);
cA = cos(A[t][x2][1]);
if( x2 > x ) M[index] = 0.5 * (cA - sA*I) * eta[t][x2][1] ;
else M[index] = -0.5 * (cA - sA*I) * eta[t][x2][1] ;
}
}
double complex determinant(){
double complex * M; //The matrix
M = (_Complex double *)malloc( VOLUME*VOLUME*sizeof(_Complex double) );
fermion_matrix(M);
int n=VOLUME;
int info;
int *ipiv;
ipiv = malloc( n*sizeof(int) );
double complex det = 1;
/*for( int i=0;i<VOLUME;i++) { for( int j=0;j<VOLUME;j++){
printf(" %4.2f ", creal( M[i+j*VOLUME] ) );
}
printf("\n");
}
printf("\n");
*/
LAPACK_zgetrf( &n, &n, M, &n, ipiv, &info );
if( info > 0 ) printf("error %d\n", info);
for(int i=0; i<n; i++) {
det *= M[i*n+i];
if( ipiv[i] != i+1 ) det*=-1;
}
/*
int lwork=n*n;
_Complex double *work;
work = malloc( lwork*sizeof(_Complex double) );
LAPACK_zgetri(&n, M, &n, ipiv, work, &lwork, &info);
free(work);
for( int i=0;i<VOLUME;i++) { for( int j=0;j<VOLUME;j++){
printf(" %4.2f ", creal( M[i+j*VOLUME] ) );
}
printf("\n");
}
printf("\n");
*/
free(M);
free(ipiv);
return( det );
}
int n_average;
void measure(){
/* Measurements */
static int n=0;
static double M = 0;
static double complex det = 0;
static double sign = 1;
double complex this_det = determinant();
det += this_det;
double this_sign = (creal(this_det) > 0) ? 1 : -1;
sign += this_sign;
for( int t=0;t<NT;t++) for( int x=0;x<NX;x++) for( int dir=0; dir<ND; dir++) {
M += this_sign*A[t][x][dir];
}
n++;
if(n%n_average == 0){
printf("Magnetisation %g\n",M/(n_average*VOLUME));
printf("Determinant Re %g Im %g\n",creal(det)/(n_average),cimag(det)/(n_average));
printf("Sign %g\n",sign/(n_average));
sign = 0; det = 0; M = 0;
}
}
int main(void){
#ifdef DEBUG
feenableexcept(FE_INVALID | FE_OVERFLOW);
#endif
long seed;
int n_loops, n_measure;
/* Read in the input */
printf(" Number of updates : ");
scanf("%d",&n_loops);
printf(" Updates / measurement : ");
scanf("%d",&n_measure);
printf(" Average over configurations : ");
scanf("%d",&n_average);
printf(" m : ");
scanf("%lf",&m);
printf(" g : ");
scanf("%lf",&g);
printf(" mu : ");
scanf("%lf",&mu);
printf(" Random number : ");
scanf("%ld",&seed);
seed_mersenne( seed );
/* "Warm up" the rng generator */
for ( int i=0; i<543210; i++) mersenne();
printf(" \n++++++++++++++++++++++++++++++++++++++++++\n");
printf(" 2D quenched Thirring model, ( %d , %d ) lattice\n", NT, NX );
printf(" %d updates per measurements\n", n_measure );
printf(" m %f \n", m);
printf(" g %f \n", g);
printf(" mu %f \n", mu);
printf(" Random seed %ld\n", seed );
eta = malloc( NT*sizeof(int *) );
A = malloc( NT*sizeof(double *) );
for (int t=0; t<NT; t++){
A[t] = malloc( (NX+1)*sizeof(double *) );
eta[t] = malloc( (NX+1)*sizeof(int *) );
for (int x=0; x<NX+1; x++) {
eta[t][x] = malloc( ND*sizeof(int) );
A[t][x] = malloc( ND*sizeof(double) );
}
}
xup = malloc( (NX+1)*sizeof(int) );
xdn = malloc( (NX+1)*sizeof(int) );
tup = malloc( NT*sizeof(int) );
tdn = malloc( NT*sizeof(int) );
/* fill up the index array */
for ( int i=0; i<NT; i++ ) {
tup[i] = (i+1) % NT;
tdn[i] = (i-1+NT) % NT;
}
for (int i=0; i<NX+1; i++) {
xup[i] = (i+1) % NX;
xdn[i] = (i-1+NX) % NX;
}
for (int t=0; t<NT; t++) for (int x=0; x<NX; x++) {
for( int dir=0; dir<ND; dir++ ) A[t][x][dir] = 0;
eta[t][x][1] = 1;
if( x%2 == 0 ){
eta[t][x][0] = 1;
} else {
eta[t][x][0] = -1;
}
#ifdef OPENX
eta[t][NX][0] = eta[t][NX][1] = 0;
#endif
}
for (int i=1; i<n_loops+1; i++) {
update_gauge();
//printf("Updated gauge\n");
//printf("Action %g\n", gauge_action());
if((i%n_measure)==0){
/* Statistics */
measure();
}
}
return 0;
}
| {
"alphanum_fraction": 0.5132989834,
"avg_line_length": 20.6350574713,
"ext": "c",
"hexsha": "a2f0ed1db155fe0280a3d0f672a6d0aec3b7db4c",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-07-18T10:21:16.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-07-18T10:21:16.000Z",
"max_forks_repo_head_hexsha": "38251013d554584df39aec18b841b4ec431abfc7",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "rantahar/Thirring2D",
"max_forks_repo_path": "quenched.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "38251013d554584df39aec18b841b4ec431abfc7",
"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": "rantahar/Thirring2D",
"max_issues_repo_path": "quenched.c",
"max_line_length": 100,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "38251013d554584df39aec18b841b4ec431abfc7",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "rantahar/Thirring2D",
"max_stars_repo_path": "quenched.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2582,
"size": 7181
} |
/*
This code derives from the R wavelets package and it is modified by Davide
Albanese <albanese@fbk.it>.
The Python interface is written by Davide Albanese <albanese@fbk.it>.
(C) 2009 mlpy Developers.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Python.h>
#include <numpy/arrayobject.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_wavelet.h>
#include <gsl/gsl_math.h>
#define SQRT_2 1.4142135623730951
void
uwt_forward (double *V, int n, int j,
double *h, double *g, int l,
double *Wj, double *Vj)
{
int t, k, z;
double k_div;
for(t = 0; t < n; t++)
{
k = t;
Wj[t] = h[0] * V[k];
Vj[t] = g[0] * V[k];
for(z = 1; z < l; z++)
{
k -= (int) pow(2, (j - 1));
k_div = -k / (double) n;
if(k < 0)
k += (int) ceil(k_div) * n;
Wj[t] += h[z] * V[k];
Vj[t] += g[z] * V[k];
}
}
}
void
uwt_backward (double *W, double *V, int j,
int n, double *h, double *g,
int l, double *Vj)
{
int t, k, z;
double k_div;
for(t = 0; t < n; t++)
{
k = t;
Vj[t] = h[0] * W[k] + g[0] * V[k];
for(z = 1; z < l; z++)
{
k += (int) pow(2, (j - 1));
k_div = (double) k / (double) n;
if(k >= n)
k -= (int) floor(k_div) * n;
Vj[t] += h[z] * W[k] + g[z] * V[k];
}
}
}
static PyObject *uwt_uwt(PyObject *self, PyObject *args, PyObject *keywds)
{
PyObject *x = NULL; PyObject *xa = NULL;
PyObject *Xa = NULL;
int levels = 0;
char wf;
int i, k, j, n, J;
double *_x;
double *_X;
double *v;
double *wj, *vj;
double *h, *g;
npy_intp Xa_dims[2];
gsl_wavelet *wave;
/* Parse Tuple*/
static char *kwlist[] = {"x", "wf", "k", "levels", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds, "Oci|i", kwlist, &x, &wf, &k, &levels))
return NULL;
xa = PyArray_FROM_OTF(x, NPY_DOUBLE, NPY_IN_ARRAY);
if (xa == NULL) return NULL;
n = (int) PyArray_DIM(xa, 0);
_x = (double *) PyArray_DATA(xa);
switch (wf)
{
case 'd':
wave = gsl_wavelet_alloc (gsl_wavelet_daubechies_centered, k);
break;
case 'h':
wave = gsl_wavelet_alloc (gsl_wavelet_haar_centered, k);
break;
case 'b':
wave = gsl_wavelet_alloc (gsl_wavelet_bspline_centered, k);
break;
default:
PyErr_SetString(PyExc_ValueError, "wavelet family is not valid");
return NULL;
}
h = (double *) malloc(wave->nc * sizeof(double));
g = (double *) malloc(wave->nc * sizeof(double));
for(i=0; i<wave->nc; i++)
{
h[i] = wave->h1[i] / SQRT_2;
g[i] = wave->g1[i] / SQRT_2;
}
if (levels == 0)
J = (int) floor(log(((n-1) / (wave->nc-1)) + 1) / log(2));
else
J = levels;
Xa_dims[0] = (npy_intp) (2 * J);
Xa_dims[1] = PyArray_DIM(xa, 0);
Xa = PyArray_SimpleNew(2, Xa_dims, NPY_DOUBLE);
_X = (double *) PyArray_DATA(Xa);
v = _x;
for(j=0; j<J; j++)
{
wj = _X +(j * n);
vj = _X +((j + J) * n);
uwt_forward(v, n, j+1, g, h, wave->nc, wj, vj);
v = vj;
}
gsl_wavelet_free(wave);
free(h);
free(g);
Py_DECREF(xa);
return Py_BuildValue("N", Xa);
}
static PyObject *uwt_iuwt(PyObject *self, PyObject *args, PyObject *keywds)
{
PyObject *X = NULL; PyObject *Xa = NULL;
PyObject *xa = NULL;
char wf;
int i, k, n, J;
double *w1, *v1;
double *_X;
double *_x;
double *h, *g;
npy_intp xa_dims[1];
gsl_wavelet *wave;
/* Parse Tuple*/
static char *kwlist[] = {"X", "wf", "k", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds, "Oci", kwlist, &X, &wf, &k))
return NULL;
Xa = PyArray_FROM_OTF(X, NPY_DOUBLE, NPY_IN_ARRAY);
if (Xa == NULL) return NULL;
n = (int) PyArray_DIM(Xa, 1);
J = ((int) PyArray_DIM(Xa, 0)) / 2;
_X = (double *) PyArray_DATA(Xa);
switch (wf)
{
case 'd':
wave = gsl_wavelet_alloc (gsl_wavelet_daubechies, k);
break;
case 'h':
wave = gsl_wavelet_alloc (gsl_wavelet_haar, k);
break;
case 'b':
wave = gsl_wavelet_alloc (gsl_wavelet_bspline, k);
break;
default:
PyErr_SetString(PyExc_ValueError, "wavelet family is not valid");
return NULL;
}
h = (double *) malloc(wave->nc * sizeof(double));
g = (double *) malloc(wave->nc * sizeof(double));
for(i=0; i<wave->nc; i++)
{
h[i] = wave->h2[i] / SQRT_2;
g[i] = wave->g2[i] / SQRT_2;
}
w1 = _X;
v1 = _X + (J * n);
xa_dims[0] = (npy_intp) n;
xa = PyArray_SimpleNew(1, xa_dims, NPY_DOUBLE);
_x = (double *) PyArray_DATA(xa);
uwt_backward (w1, v1, 1, n, g, h, wave->nc, _x);
gsl_wavelet_free(wave);
free(h);
free(g);
Py_DECREF(Xa);
return Py_BuildValue("N", xa);
}
/* Doc strings: */
static char module_doc[] = "Undecimated Wavelet Transform Module";
static char uwt_uwt_doc[] =
"Undecimated Wavelet Tranform\n\n"
":Parameters:\n"
" x : 1d array_like object (the length is restricted to powers of two)\n"
" data\n"
" wf : string ('d': daubechies, 'h': haar, 'b': bspline)\n"
" wavelet family\n"
" k : int\n"
" member of the wavelet family\n\n"
" * daubechies: k = 4, 6, ..., 20 with k even\n"
" * haar: the only valid choice of k is k = 2\n"
" * bspline: k = 103, 105, 202, 204, 206, 208, 301, 303, 305 307, 309\n\n"
" levels : int\n"
" level of the decomposition (J).\n"
" If levels = 0 this is the value J such that the length of X\n"
" is at least as great as the length of the level J wavelet filter,\n"
" but less than the length of the level J+1 wavelet filter.\n"
" Thus, j <= log_2((n-1)/(l-1)+1), where n is the length of x\n\n"
":Returns:\n"
" X : 2d numpy array (2J * len(x))\n"
" misaligned scaling and wavelet coefficients::\n\n"
" [[wavelet coefficients W_1]\n"
" [wavelet coefficients W_2]\n"
" :\n"
" [wavelet coefficients W_J]\n"
" [scaling coefficients V_1]\n"
" [scaling coefficients V_2]\n"
" :\n"
" [scaling coefficients V_J]]"
;
static char uwt_iuwt_doc[] =
"Inverse Undecimated Wavelet Tranform\n\n"
":Parameters:\n"
" X : 2d array_like object (the length is restricted to powers of two)\n"
" misaligned scaling and wavelet coefficients\n"
" wf : string ('d': daubechies, 'h': haar, 'b': bspline)\n"
" wavelet family\n"
" k : int\n"
" member of the wavelet family\n\n"
" * daubechies: k = 4, 6, ..., 20 with k even\n"
" * haar: the only valid choice of k is k = 2\n"
" * bspline: k = 103, 105, 202, 204, 206, 208, 301, 303, 305 307, 309\n\n"
":Returns:\n"
" x : 1d numpy array\n"
" data"
;
/* Method table */
static PyMethodDef uwt_methods[] = {
{"uwt",
(PyCFunction)uwt_uwt,
METH_VARARGS | METH_KEYWORDS,
uwt_uwt_doc},
{"iuwt",
(PyCFunction)uwt_iuwt,
METH_VARARGS | METH_KEYWORDS,
uwt_iuwt_doc},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_uwt",
module_doc,
-1,
uwt_methods,
NULL, NULL, NULL, NULL
};
PyObject *PyInit__uwt(void)
{
PyObject *m;
m = PyModule_Create(&moduledef);
if (!m) {
return NULL;
}
import_array();
return m;
}
#else
PyMODINIT_FUNC init_uwt(void)
{
PyObject *m;
m = Py_InitModule3("_uwt", uwt_methods, module_doc);
if (m == NULL) {
return;
}
import_array();
}
#endif
| {
"alphanum_fraction": 0.5466959843,
"avg_line_length": 23.8044077135,
"ext": "c",
"hexsha": "03afb7a8f4cbc849c8e61b02f3c832fd22ee7004",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "e52a6e88d4469284a071c0b96d009f6684dbb2ea",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "TonyZPW/CRC4Docker",
"max_forks_repo_path": "src/mlpy-3.5.0/mlpy/wavelet/uwt.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e52a6e88d4469284a071c0b96d009f6684dbb2ea",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "TonyZPW/CRC4Docker",
"max_issues_repo_path": "src/mlpy-3.5.0/mlpy/wavelet/uwt.c",
"max_line_length": 89,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5ee26f9a590b727693202d8ad3b6460970304bd9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "xuanxiaoliqu/CRC4Docker",
"max_stars_repo_path": "src/mlpy-3.5.0/mlpy/wavelet/uwt.c",
"max_stars_repo_stars_event_max_datetime": "2020-10-26T12:02:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-26T12:02:08.000Z",
"num_tokens": 2852,
"size": 8641
} |
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef _MSC_VER /* identifies this as a Microsoft compiler */
#define _USE_MATH_DEFINES /* added RX2011 */
#endif
#include <math.h>
#include <time.h>
#include <limits.h>
#include <gsl/gsl_multimin.h>
//#include "/Users/tischler/dev/GNU/include/gsl/gsl_multimin.h"
#include "Euler.h"
#ifdef DEBUG_ON
#define DEBUG 1 /* a value of 5 gets everything */
#endif
#define MIN(A,B) ( (A)<(B)?(A):(B) )
#define MAX(A,B) ( (A)>(B)?(A):(B) )
double my_f (const gsl_vector *v, void *params);
/******************************************************************************************
* return the error between a lattice rotated by Euler angles and the measured spots
* thus the returned value is a minimum for the optimimal Euler angles
*/
double my_f(
const gsl_vector *v, /* vector with current value of Euler angles */
void *pattern) /* pointer to the parameters, in this case a pointer to the pattern structure */
{
double G[3]; /* calculated G vector for each hkl */
double recip[3][3]; /* reciprocal space */
double M_Euler[3][3]; /* an Euler matrix */
size_t N; /* local copy of number of measured spots to check */
double a,b,g; /* local copy of the Euler angles */
struct patternOfOneGrain *p; /* local value of pattern */
double rms; /* rms value of error, the returned value */
size_t i; /* loop index */
double hkl[3]; /* float value of hkl */
double dot;
/* p = pattern; */
p = (struct patternOfOneGrain *)pattern;
N = p->Ni; /* local value for convenience */
a = gsl_vector_get(v,0); /* the Euler angles */
b = gsl_vector_get(v,1);
g = gsl_vector_get(v,2);
MatrixCopy33(recip,p->xtal.recip); /* copy unrotated reciprocal lattice into recip */
EulerMatrix(a,b,g,M_Euler); /* make the rotation matrix M_Euler from Euler angles */
MatrixMultiply33(M_Euler,recip,recip); /* rotate recip by Euler angles */
for (i=0,rms=0.0;i<N;i++) {
VECTOR_COPY3(hkl,p->hkls[i]); /* convert integer hkl to float for following MatrixMultiply31 */
if (hkl[0]!=hkl[0]) {
fprintf(stderr,"hkl[0] is NaN\n");
}
MatrixMultiply31(recip,hkl,G);
if (G[0]!=G[0]) {
fprintf(stderr,"G[0] is NaN\n");
}
normalize3(G); /* normalized gvec of hkl[i] rotated by Euler angles */
dot = dot3(G,p->Ghat[i]);
dot = MIN(dot,1.0);
rms += 1. - dot; /* (1-dot) ~ 0.5*(delta angle)^2*/
}
rms = sqrt(rms/(double)N); /* rms of angle errors */
return rms;
}
/* When calling optimizeEulerAngles(), be sure to set pattern.xtal:
e.g.
pattern.xtal.a = pattern.xtal.b = pattern.xtal.c = 4.05; // just default to Al for now
pattern.xtal.alpha = pattern.xtal.beta = pattern.xtal.gamma = M_PI/2.0;
then call:
FillRecipInLattice(&(pattern.lattice));
to set the reciprocal lattice in the lattice structure
*/
/* this routine optimizes approximate Euler angles using the gsl simplex method. */
int optimizeEulerAngles(
double startStep, /* starting step size (radians), make this a bit larger than the error */
double epsAbs, /* tolerance on the answer (=0.001) */
long maxIter, /* maximum number of iterations, stop after this many regardless, perhaps 100 */
struct patternOfOneGrain *pattern) /* provides G^'s and hkl's for one fitted pattern, and the lattice parameters */
{
size_t np = 3; /* number of dimensions of the function, 3 Euler angles */
/* T tells what kind of minimizer we are using, select the simplex method */
const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
gsl_multimin_fminimizer *s = NULL; /* this is the minimizer */
gsl_vector *ss, *x; /* pointers to vectors, ss is stepsize, x is point */
gsl_multimin_function minex_func; /* struct defining parts needed for minimizing */
size_t iter=0, i;
int status; /* status of returned gsl function, 0 is OK */
double size; /* size of minimizer, sort of maximum error */
double G[3]; /* calculated G vector for each hkl */
double recip[3][3]; /* reciprocal space */
double M_Euler[3][3]; /* an Euler matrix */
double hkl[3]; /* float value of hkl */
double dot;
if (!pattern) { fprintf(stderr,"pattern in NULL on entry to optimizeEulerAngles()\n"); return 1; }
if (pattern->Ni<3) { fprintf(stderr,"less than 3 pairs of Ghat & hkls on entry to optimizeEulerAngles()\n"); return 1; }
if (!(pattern->Ghat) || !(pattern->hkls)) { fprintf(stderr,"Ghat or hkls are NULL on entry to optimizeEulerAngles()\n"); return 1; }
if ((pattern->xtal.a)<=0 || (pattern->xtal.b)<=0 || (pattern->xtal.c)<=0) { fprintf(stderr,"invalid lattice in optimizeEulerAngles()\n"); return 1; }
/* Initial vertex step size vector */
ss = gsl_vector_alloc(np); /* step sizes in x and y */
/* Set all step sizes to startStep, the starting step size */
gsl_vector_set_all(ss, startStep); /* set ss[0] = ss[1] = ss[2] = startStep (radian) */
/* Starting point */
x = gsl_vector_alloc(np); /* allocate space for a vector of length 3 */
gsl_vector_set(x, 0, pattern->alpha); /* set to starting guess, input (alpha,beta,gamma) */
gsl_vector_set(x, 1, pattern->beta);
gsl_vector_set(x, 2, pattern->gamma);
/* Initialize the minimizer */
minex_func.f = &my_f; /* the function that returns the value */
minex_func.n = np; /* number of parameters */
minex_func.params = (void *)pattern; /* a generic pointer that points to something with info for my_f() */
/* Note: my_func.df, and my_func.fdf are not needed since simplex method does not use derivatives */
s = gsl_multimin_fminimizer_alloc(T, np); /* allocate for a 2d simplex minimizer named 's' */
/* Set starting point for the minimizer:
for the minimizer 's',
working on a function 'minex_func'
starting from the initial guess x[2]
using step sizes of ss[2] */
gsl_multimin_fminimizer_set(s, &minex_func, x, ss);
#if (DEBUG) /******************************************************************************/
fprintf(fout, "start minimization with Euler angles (%15.10f, %15.10f, %15.10f) (deg.)\n", \
pattern->alpha*180/M_PI,pattern->beta*180/M_PI,pattern->gamma*180/M_PI);
#endif /******************************************************************************/
/* Iterate the minimizer. This looop iterates the minimization method until it is good enough */
iter = 0;
do {
iter++;
status = gsl_multimin_fminimizer_iterate(s); /* do one iteration of the minimizer */
if (status) break; /* status=0 is OK, check here for an error */
size = gsl_multimin_fminimizer_size (s); /* get 'size' of minimizer */
status = gsl_multimin_test_size (size, epsAbs); /* test size against epsAbs */
#if (DEBUG>1) /******************************************************************************/
fprintf(fout,"%5ld f(", iter);
for (i=0; i<np; i++) {
fprintf(fout,"%.8f", gsl_vector_get(s->x, i));
if (i<np-1) fprintf(fout,", ");
}
fprintf(fout,") = %15.8g size = %.5g\n", s->fval, size);
#endif /******************************************************************************/
} while (status == GSL_CONTINUE && iter < (size_t)maxIter); /* stop after maxIter regardless of size */
#if (DEBUG) /******************************************************************************/
if (status == GSL_SUCCESS) fprintf(fout,"converged to minimum successfully\n");
else fprintf(fout,"did not converge successfully, status = %d\n",status);
fprintf(fout, " optimization changed Euler angles by (%15.10f, %15.10f, %15.10f) (deg.)\n", \
(gsl_vector_get(s->x,0)-pattern->alpha)*180/M_PI, (gsl_vector_get(s->x,1)-pattern->beta)*180/M_PI, \
(gsl_vector_get(s->x,2)-pattern->gamma)*180/M_PI);
#endif /******************************************************************************/
pattern->alpha = gsl_vector_get(s->x,0); /* set to final values, resultant (alpha,beta,gamma) returned */
pattern->beta = gsl_vector_get(s->x,1);
pattern->gamma = gsl_vector_get(s->x,2);
#if (DEBUG) /******************************************************************************/
fprintf(fout, "after minimization, Euler angles are (%15.10f, %15.10f, %15.10f) (deg.)\n", \
pattern->alpha*180/M_PI,pattern->beta*180/M_PI,pattern->gamma*180/M_PI);
#endif /******************************************************************************/
/* recalculate the err[] list in pattern */
MatrixCopy33(recip,pattern->xtal.recip); /* copy unrotated reciprocal lattice into recip */
EulerMatrix(pattern->alpha,pattern->beta,pattern->gamma,M_Euler);/* rotation matrix from Euler angles */
MatrixMultiply33(M_Euler,recip,recip); /* rotate recip by Euler angles */
for (i=0;i<(size_t)(pattern->Ni);i++) {
VECTOR_COPY3(hkl,pattern->hkls[i]); /* convert integer hkl to float for following MatrixMultiply31 */
MatrixMultiply31(recip,hkl,G);
normalize3(G); /* normalized gvec of hkl[i] rotated by Euler angles */
dot = dot3(G,pattern->Ghat[i]); /* note, Ghat here is the measured, not calculated G */
(pattern->err)[i] = acos(MIN(dot,1.0));
}
gsl_vector_free(x); /* free vector of x,y positions */
gsl_vector_free(ss); /* free vector of step sizes */
gsl_multimin_fminimizer_free (s); /* free the minimizer */
return status;
}
| {
"alphanum_fraction": 0.6159139785,
"avg_line_length": 44.4976076555,
"ext": "c",
"hexsha": "eae7205bce48cc7a5caeafe76854a6322096eee4",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-01-21T17:48:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-21T17:48:28.000Z",
"max_forks_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "carterbox/cold",
"max_forks_repo_path": "legacy/Euler3/source/optimize.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T10:34:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2022-01-21T17:14:55.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "carterbox/cold",
"max_issues_repo_path": "legacy/Euler3/source/optimize.c",
"max_line_length": 150,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2738e6e9ccfd13007ac4fd987bf1a75656d358bd",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "carterbox/cold",
"max_stars_repo_path": "legacy/Euler3/source/optimize.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2536,
"size": 9300
} |
// MIT License
//
// Copyright (c) 2020 SunnyCase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include "chinodef.h"
#include <atomic>
#include <chino/error.h>
#include <chino/result.h>
#include <gsl/gsl-lite.hpp>
#include <string_view>
namespace chino::io
{
enum class std_handles
{
in,
out,
err
};
enum class create_disposition
{
create_always = 2,
create_new = 1,
open_always = 4,
open_existing = 3,
truncate_existing = 5
};
result<void, error_code> alloc_console() noexcept;
handle_t get_std_handle(std_handles type) noexcept;
result<handle_t, error_code> open(const insert_lookup_object_options &options, create_disposition create_disp = create_disposition::open_existing) noexcept;
result<size_t, error_code> read(handle_t file, gsl::span<gsl::byte> buffer) noexcept;
result<void, error_code> write(handle_t file, gsl::span<const gsl::byte> buffer) noexcept;
result<void, error_code> close(handle_t file) noexcept;
}
| {
"alphanum_fraction": 0.7572427572,
"avg_line_length": 35.75,
"ext": "h",
"hexsha": "a4c2e8130c2ea694462fd0cbf6a1fee2735ac9c9",
"lang": "C",
"max_forks_count": 20,
"max_forks_repo_forks_event_max_datetime": "2021-09-13T10:14:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-05-18T03:54:08.000Z",
"max_forks_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dotnetGame/chino-os",
"max_forks_repo_path": "src/api/include/chino/io.h",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2",
"max_issues_repo_issues_event_max_datetime": "2020-04-30T14:46:51.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-05-15T02:15:33.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "dotnetGame/chino-os",
"max_issues_repo_path": "src/api/include/chino/io.h",
"max_line_length": 156,
"max_stars_count": 137,
"max_stars_repo_head_hexsha": "e4b444983a059231636b81dc5f33206e16a859c2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "chino-os/chino-os",
"max_stars_repo_path": "src/api/include/chino/io.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-10T11:42:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-04-28T09:50:17.000Z",
"num_tokens": 461,
"size": 2002
} |
#ifndef TEST_ALL
#define TEST_ALL
//#include <cblas.h>
#include "test_matrix_util.h"
#include "test_spn.h"
int test_all(int result);
#endif
| {
"alphanum_fraction": 0.7361111111,
"avg_line_length": 12,
"ext": "h",
"hexsha": "79d8595c6f9039f25cb9a04ae775d1d6ab7bd944",
"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": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ThayaFluss/cnl",
"max_forks_repo_path": "src/cy_fde/test_all.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733",
"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": "ThayaFluss/cnl",
"max_issues_repo_path": "src/cy_fde/test_all.h",
"max_line_length": 29,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "485345e730a4cbf5cff6dbdeeb5e1fb7c4283733",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ThayaFluss/cnl",
"max_stars_repo_path": "src/cy_fde/test_all.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 37,
"size": 144
} |
#include <gsl/gsl_math.h>
#include <gsl/gsl_cblas.h>
#include "cblas.h"
void
cblas_ssyr2k (const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo,
const enum CBLAS_TRANSPOSE Trans, const int N, const int K,
const float alpha, const float *A, const int lda,
const float *B, const int ldb, const float beta, float *C,
const int ldc)
{
#define BASE float
#include "source_syr2k_r.h"
#undef BASE
}
| {
"alphanum_fraction": 0.6600441501,
"avg_line_length": 28.3125,
"ext": "c",
"hexsha": "2cbafb35756ca909b1c32cb468d4985380736039",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/cblas/ssyr2k.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/cblas/ssyr2k.c",
"max_line_length": 73,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/cblas/ssyr2k.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": 126,
"size": 453
} |
/**
* Copyright 2019 José Manuel Abuín Mosquera <josemanuel.abuin@usc.es>
*
* This file is part of Matrix Market Suite.
*
* Matrix Market Suite 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.
*
* Matrix Market Suite 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 Matrix Market Suite. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <cblas.h>
#include "ConjugateGradient.h"
#include "ConjugateGradientSolver.h"
#include "ConjugateGradientSolverBasic.h"
/* Include redundant execution header. */
#include "../../../include/ourRMTlib.h"
void usageConjugateGradient(){
fprintf(stderr, "\n");
fprintf(stderr, "Usage: MM-Suite ConjugateGradient [options] <input-matrix> <input-vector>\n");
fprintf(stderr, "Algorithm options:\n\n");
fprintf(stderr, " -i INT Iteration number. Default: number of matrix rows * 2\n");
fprintf(stderr, " -b Uses basic operations instead of optimized BLAS libraries. Default: False\n");
fprintf(stderr, "\nInput/output options:\n\n");
fprintf(stderr, " -o STR Output file name. Default: stdout\n");
fprintf(stderr, " -r Input format is row per line. Default: False\n");
fprintf(stderr, "\nPerformance options:\n\n");
fprintf(stderr, " -t INT Number of threads to use in OpenBLAS. Default: 1\n");
fprintf(stderr, "\n");
}
//int ConjugateGradient(int argc, char *argv[]) {
int main(int argc, char *argv[]) {
int ret_code;
int option;
unsigned long *II;
unsigned long *J;
double *A;
unsigned long M;
unsigned long N;
unsigned long long nz;
double *b;
unsigned long M_Vector;
unsigned long N_Vector;
unsigned long long nz_vector;
char *outputFileName = NULL;
int iterationNumber = 0;
char *inputMatrixFile = NULL;
char *inputVectorFile = NULL;
int numThreads = 1;
int inputFormatRow = 0;
int basicOps = 0;
int F=0;
while ((option = getopt(argc, argv,"bro:i:t:f:")) >= 0) {
switch (option) {
case 'o' :
//free(outputFileName);
outputFileName = (char *) malloc(sizeof(char)*strlen(optarg)+1);
strcpy(outputFileName,optarg);
break;
case 'i' :
iterationNumber = atoi(optarg);
break;
case 'r':
inputFormatRow = 1;
break;
case 'b':
basicOps = 1;
break;
case 't':
numThreads = atoi(optarg);
break;
case 'f':
F = atoi(optarg);
break;
default: break;
}
}
if ((optind + 2 > argc) || (optind + 3 <= argc)) {
usageConjugateGradient();
return -1;
}
//openblas_set_num_threads(numThreads);
if(outputFileName == NULL) {
outputFileName = (char *) malloc(sizeof(char)*7);
sprintf(outputFileName,"stdout");
}
start_timer();
inputMatrixFile = (char *)malloc(sizeof(char)*strlen(argv[optind])+1);
inputVectorFile = (char *)malloc(sizeof(char)*strlen(argv[optind+1])+1);
strcpy(inputMatrixFile,argv[optind]);
strcpy(inputVectorFile,argv[optind+1]);
//Read matrix
//Read matrix
if(inputFormatRow){
if(!readDenseCoordinateMatrixRowLine(inputMatrixFile,&II,&J,&A,&M,&N,&nz)){
fprintf(stderr, "[%s] Can not read Matrix\n",__func__);
return -1;
}
//writeDenseVector("stdout",values,M,N,nz);
}
else {
if(!readDenseCoordinateMatrix(inputMatrixFile,&II,&J,&A,&M,&N,&nz)){
fprintf(stderr, "[%s] Can not read Matrix\n",__func__);
return -1;
}
}
//Read vector
if(!readDenseVector(inputVectorFile, &b,&M_Vector,&N_Vector,&nz_vector)){
fprintf(stderr, "[%s] Can not read Vector\n",__func__);
return -1;
}
//double *y=(double *) malloc(nz_vector * sizeof(double));
fprintf(stderr,"[%s] Solving system using conjugate gradient method\n",__func__);
double t_real = realtime();
// Vector to store result
double *x=(double *) calloc(nz_vector,sizeof(double));
if(basicOps){
ret_code = ConjugateGradientSolverBasic(II,J,A,M,N,nz,b,M_Vector,N_Vector,nz_vector, x, iterationNumber);
}
else{
# ifdef ENABLE_RMT
activateRMT("f-L-lp-lp-2d-l-l-l-1dC-l-l-l-1dC-i-i-ipC", &ConjugateGradientSolver, 14, II, J, A, M, N, M, N, nz , b, N, M_Vector, N_Vector,
nz_vector, x, nz_vector, iterationNumber, F, &ret_code);
# else
ret_code = ConjugateGradientSolver(II,J,A,M,N,nz,b,M_Vector,N_Vector,nz_vector, x, iterationNumber, F, &ret_code);
# endif
}
fprintf(stderr, "\n[%s] Time spent in Conjugate Gradient: %.6f sec\n", __func__, realtime() - t_real);
if(ret_code){
writeDenseVector(outputFileName, x,M_Vector,N_Vector,nz_vector);
}
else{
fprintf(stderr,"[%s] Error executing ConjugateGradientSolver\n",__func__);
return -1;
}
end_timer();
return 0;
}
| {
"alphanum_fraction": 0.6538753799,
"avg_line_length": 25.8039215686,
"ext": "c",
"hexsha": "a25b8c09483d5e78e95914b2ad8e3f3e652f9c01",
"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": "8e7ab9d3491e40d9e5e77f67956752cc1178b1b4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sanemarslan/RMTLib",
"max_forks_repo_path": "applications/others/sscg/ConjugateGradient.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8e7ab9d3491e40d9e5e77f67956752cc1178b1b4",
"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": "sanemarslan/RMTLib",
"max_issues_repo_path": "applications/others/sscg/ConjugateGradient.c",
"max_line_length": 144,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8e7ab9d3491e40d9e5e77f67956752cc1178b1b4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sanemarslan/RMTLib",
"max_stars_repo_path": "applications/others/sscg/ConjugateGradient.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1463,
"size": 5264
} |
/*
* @Description : Phase Class store the information of a phase in a temperature period
*/
#ifndef PHASES_H
#define PHASES_H
#include <string>
#include "VTypes.h"
#include <gsl/gsl_spline.h>
typedef std::vector<gsl_spline*> VSP;
class Phase
{
private:
static int NPhases;
int key; // Phase ID
int DimX; // Dimension of X
int DimData; // Dimension of T
VVD X; // Store the Field information at every temperature
VD T; // Temperature
VVD dXdT; // The derivative of X respect to Temperature
SI low_trans;
SI high_trans;
gsl_interp_accel *acc;
VSP inters;
public:
Phase();
Phase(int _key, VVD _X, VD _T, VVD _dXdT);
Phase(const Phase &Ph);
Phase(const Phase &ph1, const Phase &ph2); //Merge two phases // ! When using this constructor, please make sure one of the two phases are redundant. We don't do such check
~Phase();
void SetPhase(int _key, VVD _X, VD _T, VVD _dXdT);
void SetUpInterpolation();
void FreeInterpolation();
VD valAt(double _T);
int GetKey() const {return key;}
double GetTmin() const {return T.front();}
double GetTmax() const {return T.back();}
VD GetXatTmin() const {VD Xmin; for(int i = 0; i < DimX; i++ ) {Xmin.push_back(X[i].front());} return Xmin;}
VD GetXatTmax() const {VD Xmax; for(int i = 0; i < DimX; i++ ) {Xmax.push_back(X[i].back());} return Xmax;}
void addLowTrans(int _key) {low_trans.insert(_key);}
void eraseLowTrans(int _key) {low_trans.erase(_key);}
void addHighTrans(int _key) {high_trans.insert(_key);}
void eraseHighTrans(int _key) {high_trans.erase(_key);}
void addLinkFrom(Phase *other_phase);
std::string repr();
std::string repr_full();
VVD GetX() const {return X;}
VVD GetdXdT() const {return dXdT;}
VD GetT() const {return T;}
SI GetLowTrans() const {return low_trans;}
SI GetHighTrans() const {return high_trans;}
static int GetNPhases() {return NPhases;}
};
#endif | {
"alphanum_fraction": 0.6651469098,
"avg_line_length": 32.9,
"ext": "h",
"hexsha": "20cfd909f1f6c71d0de28b0543ad361451e68b48",
"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": "76bee3915b26025a607a71c372005ea88b3d1389",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ycwu1030/PhaseTransitions",
"max_forks_repo_path": "include/Phases.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "76bee3915b26025a607a71c372005ea88b3d1389",
"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": "ycwu1030/PhaseTransitions",
"max_issues_repo_path": "include/Phases.h",
"max_line_length": 176,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "76bee3915b26025a607a71c372005ea88b3d1389",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ycwu1030/PhaseTransitions",
"max_stars_repo_path": "include/Phases.h",
"max_stars_repo_stars_event_max_datetime": "2020-06-05T22:59:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-05T22:59:34.000Z",
"num_tokens": 582,
"size": 1974
} |
/**
* \file include/shg/numalg.h
* Numerical algorithms.
*/
#ifndef SHG_NUMALG_H
#define SHG_NUMALG_H
#include <functional>
#include <limits>
#include <stdexcept>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_multimin.h>
#include <shg/fcmp.h>
#include <shg/matrix.h>
#include <shg/vector.h>
namespace SHG {
/**
* Degree of polynomial in one variable.
*
* \returns \f$\max \{i: a_i \neq 0, i = 0, \ldots, m - 1 \}\f$ if it
* exists, otherwise -1.
*
* \throws std::invalid_argument if a.size() == 0 or a.size() > 32768.
*/
template <template <class> class Indexed_container, class T>
int degree_of_polynomial(const Indexed_container<T>& a, T eps);
/**
* Calculates real roots of polynomial a[n] x^n + ... + a[2] x^2 +
* a[1] x^1 + a[0]. Calculated roots are put in x[0] < x[1] < ... <
* x[m - 1], where m = x.size().
*
* \throws std::invalid_argument if degree of polynomial is less than
* 1
* \throws std::runtime_error if the GSL routine fails
*/
void real_roots(const Vecdouble& a, Vecdouble& x);
template <template <class> class Indexed_container, class T>
int degree_of_polynomial(const Indexed_container<T>& a, T eps) {
static_assert(std::numeric_limits<int>::max() >= 32767,
"According to the standard, INT_MAX must be at "
"least 32767.");
auto k = a.size();
if (k == 0 || k > 32768u)
throw std::invalid_argument(
"invalid polynomial in degree_of_polynomial");
while (k-- > 0)
if (fane(a[k], T(0), eps))
return k;
return -1;
}
/**
* Solves the equation \f$a_0 + a_1x + \ldots + a_{n - 1}x^{n - 1} =
* 0\f$, \f$n \geq 1\f$.
*/
void solve_polynomial(const Vecdouble& a, Veccomplex& x);
/**
* Solves system of linear equations.
*/
void solve_linear(Matdouble& a, Vecdouble& x);
/** Light wrapper for GSL minimizer. */
class Minimizer_base {
public:
Minimizer_base(const gsl_min_fminimizer_type* T);
Minimizer_base(const Minimizer_base&) = delete;
Minimizer_base& operator=(const Minimizer_base&) = delete;
virtual ~Minimizer_base();
gsl_min_fminimizer* get() const;
private:
gsl_min_fminimizer* s_;
};
/** Wrapper for GSL minimizer. */
class Minimizer : Minimizer_base {
public:
Minimizer(const gsl_min_fminimizer_type* T);
Minimizer(const Minimizer&) = delete;
Minimizer& operator=(const Minimizer&) = delete;
bool is_set() const { return is_set_; }
void set(gsl_function* f, double x_minimum, double x_lower,
double x_upper);
int iterate(int max_iter, double epsabs, double epsrel);
int iter() const { return iter_; }
double x_minimum() const { return x_minimum_; }
double x_lower() const { return x_lower_; }
double x_upper() const { return x_upper_; }
double f_minimum() const { return f_minimum_; }
double f_lower() const { return f_lower_; }
double f_upper() const { return f_upper_; }
private:
gsl_min_fminimizer* s_{get()};
int iter_{0};
bool is_set_{false};
double x_minimum_{};
double x_lower_{};
double x_upper_{};
double f_minimum_{};
double f_lower_{};
double f_upper_{};
};
/**
* Uniform search for minimum of the function of one variable.
*
* The method search() searches uniformly the interval \f$[a, b]\f$
* for minima of the function \f$f\f$. The method is inspired by
* \cite bronsztejn-siemiendiajew-musiol-muhlig-2004, section
* 18.2.4.1, point 1, page 946.
*
* First, \f$n\f$ is calculated as \f[ n = \min \{ 2, \lceil
* \frac{2}{\epsilon} (b - a) \rceil \}, \f] and then the interval
* \f$[a, b]\f$ is divided into \f$n\f$ intervals \f$[x_k, x_{k +
* 1}]\f$, \f$k = 0, \ldots n - 1\f$, where \f$x_k = a + kh\f$, \f$h =
* (b - a) / n\f$. The values of \f$f\f$ are calculated in each
* \f$x_k\f$ and all values \f[ (x_k, x_{k + 1}, x_{k + 2}, f(x_k),
* f(x_{k + 1}), f(x_{k + 2})) \f] such that \f[ f(x_k) > f(x_{k + 1})
* < f(x_{k + 2}) \f] are reported in \f$\var{result}\f$. The length
* of the interval \f$[x_k, x_{k + 2}]\f$ is not greater than
* \f$\epsilon\f$. The function is evaluated \f$n + 1\f$times.
*
* \throws std::invalid_argument if on entry \f$a \geq b\f$ or
* \f$\epsilon \leq 0\f$.
*/
struct Uniform_search_for_minimum {
struct Result {
double x_lower;
double x_minimum;
double x_upper;
double f_lower;
double f_minimum;
double f_upper;
};
std::vector<Result> result{};
void search(std::function<double(double)> f, double a, double b,
double eps);
};
/** Light wrapper for GSL minimizer for functions of several
variables. */
class Multimin_fminimizer_base {
public:
Multimin_fminimizer_base(const gsl_multimin_fminimizer_type* T,
size_t n);
Multimin_fminimizer_base(const Multimin_fminimizer_base&) =
delete;
Multimin_fminimizer_base& operator=(
const Multimin_fminimizer_base&) = delete;
virtual ~Multimin_fminimizer_base();
gsl_multimin_fminimizer* get() const;
private:
gsl_multimin_fminimizer* s_;
};
/** Wrapper for GSL minimizer for functions of several variables. */
class Multimin_fminimizer : public Multimin_fminimizer_base {
public:
Multimin_fminimizer(const gsl_multimin_fminimizer_type* T,
size_t n);
Multimin_fminimizer(const Multimin_fminimizer&) = delete;
Multimin_fminimizer& operator=(const Multimin_fminimizer&) =
delete;
virtual ~Multimin_fminimizer();
bool is_set() const { return is_set_; }
int iter() const { return iter_; }
void set(gsl_multimin_function* f, const std::vector<double>& x,
const std::vector<double>& step);
int iterate(int max_iter, double eps);
const std::vector<double>& x_minimum() const {
return x_minimum_;
}
double f_minimum() const { return f_minimum_; }
private:
gsl_multimin_fminimizer* s_{get()};
int iter_{0};
bool is_set_{false};
std::size_t n_;
gsl_vector* x_;
gsl_vector* ss_;
std::vector<double> x_minimum_;
double f_minimum_;
};
} // namespace SHG
#endif
| {
"alphanum_fraction": 0.6347133758,
"avg_line_length": 30.1923076923,
"ext": "h",
"hexsha": "19a99c2b76aecdddc7d8de0ee96460c8897e86c3",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-08-18T12:35:22.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-05-21T04:14:44.000Z",
"max_forks_repo_head_hexsha": "0318d0126cf12c3236183447d130969c468a02fa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "shgalus/shg",
"max_forks_repo_path": "include/shg/numalg.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "0318d0126cf12c3236183447d130969c468a02fa",
"max_issues_repo_issues_event_max_datetime": "2015-05-21T05:31:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-05-21T05:31:04.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "shgalus/shg",
"max_issues_repo_path": "include/shg/numalg.h",
"max_line_length": 70,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "0318d0126cf12c3236183447d130969c468a02fa",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "shgalus/shg",
"max_stars_repo_path": "include/shg/numalg.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-31T17:15:15.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-21T04:14:50.000Z",
"num_tokens": 1781,
"size": 6280
} |
/* randist/shuffle.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 <stdlib.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* Inline swap and copy functions for moving objects around */
static inline
void swap (void * base, size_t size, size_t i, size_t j)
{
register char * a = size * i + (char *) base ;
register char * b = size * j + (char *) base ;
register size_t s = size ;
if (i == j)
return ;
do
{
char tmp = *a;
*a++ = *b;
*b++ = tmp;
}
while (--s > 0);
}
static inline void
copy (void * dest, size_t i, void * src, size_t j, size_t size)
{
register char * a = size * i + (char *) dest ;
register char * b = size * j + (char *) src ;
register size_t s = size ;
do
{
*a++ = *b++;
}
while (--s > 0);
}
/* Randomly permute (shuffle) N indices
Supply an array x[N] with nmemb members, each of size size and on
return it will be shuffled into a random order. The algorithm is
from Knuth, SemiNumerical Algorithms, v2, p139, who cites Moses and
Oakford, and Durstenfeld */
void
gsl_ran_shuffle (const gsl_rng * r, void * base, size_t n, size_t size)
{
size_t i ;
for (i = n - 1; i > 0; i--)
{
size_t j = gsl_rng_uniform_int(r, i+1); /* originally (i + 1) * gsl_rng_uniform (r) */
swap (base, size, i, j) ;
}
}
int
gsl_ran_choose (const gsl_rng * r, void * dest, size_t k, void * src,
size_t n, size_t size)
{
size_t i, j = 0;
/* Choose k out of n items, return an array x[] of the k items.
These items will prevserve the relative order of the original
input -- you can use shuffle() to randomize the output if you
wish */
if (k > n)
{
GSL_ERROR ("k is greater than n, cannot sample more than n items",
GSL_EINVAL) ;
}
for (i = 0; i < n && j < k; i++)
{
if ((n - i) * gsl_rng_uniform (r) < k - j)
{
copy (dest, j, src, i, size) ;
j++ ;
}
}
return GSL_SUCCESS;
}
void
gsl_ran_sample (const gsl_rng * r, void * dest, size_t k, void * src,
size_t n, size_t size)
{
size_t i, j = 0;
/* Choose k out of n items, with replacement */
for (i = 0; i < k; i++)
{
j = gsl_rng_uniform_int (r, n); /* originally n * gsl_rng_uniform (r) */
copy (dest, i, src, j, size) ;
}
}
| {
"alphanum_fraction": 0.5450692286,
"avg_line_length": 28.312,
"ext": "c",
"hexsha": "1e45420a9c0ad4302b765ebc4bd28e2e8b791708",
"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/shuffle.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/shuffle.c",
"max_line_length": 92,
"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/shuffle.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": 959,
"size": 3539
} |
/** @file */
#ifndef __CCL_CORE_H_INCLUDED__
#define __CCL_CORE_H_INCLUDED__
#include <stdbool.h>
#include <stdio.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_interp2d.h>
#include <gsl/gsl_spline2d.h>
CCL_BEGIN_DECLS
/**
* Struct containing the parameters defining a cosmology
*/
typedef struct ccl_parameters {
// Densities: CDM, baryons, total matter, neutrinos, curvature
double Omega_c; /**< Density of CDM relative to the critical density*/
double Omega_b; /**< Density of baryons relative to the critical density*/
double Omega_m; /**< Density of all matter relative to the critical density*/
double Omega_k; /**< Density of curvature relative to the critical density*/
double sqrtk; /**< Square root of the magnitude of curvature, k */ //TODO check
int k_sign; /**<Sign of the curvature k */
// Dark Energy
double w0;
double wa;
// Hubble parameters
double H0;
double h;
// Neutrino properties
double Neff; // Effective number of relativistic neutrino species in the early universe.
int N_nu_mass; // Number of species of neutrinos which are nonrelativistic today
double N_nu_rel; // Number of species of neutrinos which are relativistic today
double *mnu; // total mass of massive neutrinos (This is a pointer so that it can hold multiple masses.)
double sum_nu_masses; // sum of the neutrino masses.
double Omega_n_mass; // Omega_nu for MASSIVE neutrinos
double Omega_n_rel; // Omega_nu for MASSLESS neutrinos
//double Neff_partial[CCL_MAX_NU_SPECIES];
//double mnu[CCL_MAX_NU_SPECIES];
// Primordial power spectra
double A_s;
double n_s;
// Radiation parameters
double Omega_g;
double T_CMB;
// BCM baryonic model parameters
double bcm_log10Mc;
double bcm_etab;
double bcm_ks;
// Derived parameters
double sigma8;
double Omega_l;
double z_star;
//Modified growth rate
bool has_mgrowth;
int nz_mgrowth;
double *z_mgrowth;
double *df_mgrowth;
} ccl_parameters;
/**
* Struct containing references to gsl splines for distance and acceleration calculations
*/
typedef struct ccl_data{
// These are all functions of the scale factor a.
// Distances are defined in Mpc
double growth0;
gsl_spline * chi;
gsl_spline * growth;
gsl_spline * fgrowth;
gsl_spline * E;
gsl_spline * achi;
// All these splines use the same accelerator so that
// if one calls them successively with the same a value
// they will be much faster.
gsl_interp_accel *accelerator;
gsl_interp_accel *accelerator_achi;
gsl_interp_accel *accelerator_m;
gsl_interp_accel *accelerator_d;
//TODO: it seems like we're not really using this accelerator, and we should
gsl_interp_accel *accelerator_k;
// Function of Halo mass M
gsl_spline * logsigma;
gsl_spline * dlnsigma_dlogm;
// splines for halo mass function
gsl_spline * alphahmf;
gsl_spline * betahmf;
gsl_spline * gammahmf;
gsl_spline * phihmf;
gsl_spline * etahmf;
// These are all functions of the wavenumber k and the scale factor a.
gsl_spline2d * p_lin;
gsl_spline2d * p_nl;
double k_min_lin; //k_min [1/Mpc] <- minimum wavenumber that the power spectrum has been computed to
double k_min_nl;
double k_max_lin;
double k_max_nl;
} ccl_data;
/**
* Sturct containing references to instances of the above structs, and boolean flags of precomputed values.
*/
typedef struct ccl_cosmology
{
ccl_parameters params;
ccl_configuration config;
ccl_data data;
bool computed_distances;
bool computed_growth;
bool computed_power;
bool computed_sigma;
bool computed_hmfparams;
int status;
//this is optional - less tedious than tracking all numerical values for status in error handler function
char status_message[500];
// other flags?
} ccl_cosmology;
// Label for whether you are passing a pointer to a sum of neutrino masses or a pointer to a list of 3 masses.
typedef enum ccl_mnu_convention {
ccl_mnu_list=0, // you pass a list of three neutrino masses
ccl_mnu_sum =1, // sum, defaults to splitting with normal hierarchy
ccl_mnu_sum_inverted = 2, //sum, split with inverted hierarchy
ccl_mnu_sum_equal = 3, //sum, split into equal masses
// More options could be added here
} ccl_mnu_convention;
// Initialization and life cycle of objects
void ccl_cosmology_read_config(void);
ccl_cosmology * ccl_cosmology_create(ccl_parameters params, ccl_configuration config);
/* Internal function to set the status message safely. */
void ccl_cosmology_set_status_message(ccl_cosmology * cosmo, const char * status_message, ...);
// User-facing creation routines
/**
* Create a cosmology
* @param Omega_c Omega_c
* @param Omega_b Omega_b
* @param Omega_k Omega_k
* @param Neff Number of relativistic neutrino species in the early universe
* @param mnu neutrino mass, either sum or list of length 3
* @param mnu_type determines neutrino mass convention (ccl_mnu_list, ccl_mnu_sum, ccl_mnu_sum_inverted, ccl_mnu_sum_equal)
* @param w0 Dark energy EoS parameter
* @param wa Dark energy EoS parameter
* @param h Hubble constant in units of 100 km/s/Mpc
* @param norm_pk the normalization of the power spectrum, either A_s or sigma8
* @param n_s the power-law index of the power spectrum
* @param bcm_log10Mc log10 cluster mass, one of the parameters of the BCM model
* @param bcm_etab ejection radius parameter, one of the parameters of the BCM model
* @param bcm_ks wavenumber for the stellar profile, one of the parameters of the BCM model
* @param nz_mgrowth the number of redshifts where the modified growth is provided
* @param zarr_mgrowth the array of redshifts where the modified growth is provided
* @param dfarr_mgrowth the modified growth function vector provided
* @param status Status flag. 0 if there are no errors, nonzero otherwise.
* For specific cases see documentation for ccl_error.c
* @return void
*/
ccl_parameters ccl_parameters_create(double Omega_c, double Omega_b, double Omega_k,
double Neff, double* mnu, ccl_mnu_convention mnu_type,
double w0, double wa, double h, double norm_pk,
double n_s, double bcm_log10Mc, double bcm_etab, double bcm_ks,
int nz_mgrowth,double *zarr_mgrowth,
double *dfarr_mgrowth, int *status);
/* ------- ROUTINE: ccl_parameters_create_flat_lcdm --------
INPUT: some cosmological parameters needed to create a flat LCDM model
TASK: call ccl_parameters_create to produce an LCDM model
*/
ccl_parameters ccl_parameters_create_flat_lcdm(double Omega_c, double Omega_b, double h,
double norm_pk, double n_s, int *status);
/**
* Free a parameters struct
* @param params ccl_parameters struct
* @return void
*/
void ccl_parameters_free(ccl_parameters * params);
/**
* Write a cosmology parameters object to a file in yaml format, .
* @param params Cosmological parameters
* @param filename Name of file to create and write
* @param status Status flag. 0 if there are no errors, nonzero otherwise.
* @return void
*/
void ccl_parameters_write_yaml(ccl_parameters * params, const char * filename, int * status);
/**
* Read a cosmology parameters object from a file in yaml format, .
* @param filename Name of existing file to read from
* @param status Status flag. 0 if there are no errors, nonzero otherwise.
* @return cosmo Cosmological parameters
*/
ccl_parameters ccl_parameters_read_yaml(const char * filename, int *status);
/**
* Free a cosmology struct
* @param cosmo Cosmological parameters
* @return void
*/
void ccl_cosmology_free(ccl_cosmology * cosmo);
CCL_END_DECLS
#endif
| {
"alphanum_fraction": 0.742875817,
"avg_line_length": 32.6923076923,
"ext": "h",
"hexsha": "95931ac9334caaa481968a0ab4f593cc4166d32f",
"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": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Russell-Jones-OxPhys/CCL",
"max_forks_repo_path": "include/ccl_core.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"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": "Russell-Jones-OxPhys/CCL",
"max_issues_repo_path": "include/ccl_core.h",
"max_line_length": 123,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "1cdc4ecb8ae6fb23806540b39799cc3317473e71",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Russell-Jones-OxPhys/CCL",
"max_stars_repo_path": "include/ccl_core.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1958,
"size": 7650
} |
/* */
/* rt - retention time (predictor) v4.0.20160301 */
/* */
/* (c) Magnus Palmblad, Division of Ion Physics, Uppsala University, 2002- */
/* */
/* */
/* Version 4.0 of rt now also accepts pepXML input instead of just tab-delimited files, recognizes */
/* the input format automatically and can generate output (retention coefficients) either as a tab- */
/* delimited text file or an XML structure. Known bugs: This version does not extract modifications */
/* from the pepXML files and only works with the pepXML files generated from PeptideProphet. */
/* The program does not perform detailed checks on the input, i.e. peptide lengths and syntax errors. */
/* */
/* Usage: rt -i <training set in tab delimited or pepXML format> [-f <tab>|<XML> output format)]> */
/* */
/* compile with gcc -o rt rt3.c -lgsl -lgslcblas -lpepXML -LpepXMLLib */
/* */
/* */
/* The mzIdentML support is extremely "quick-and-dirty" but work with tested idconvert-ed pepXML */
/* */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_multifit.h>
#include "pepXMLLib/pepXMLReader.h"
#define AMINO_ACIDS "ARNDCEQGHILKMFPSTWYVmsty"
#define MAX_PEPTIDE_LENGTH 100
int main(int argc, char *argv[])
{
char line[250];
char infile[85], outfile[85]; /* for reading input and writing output */
char slask[85];
typedef struct {
char sequence[MAX_PEPTIDE_LENGTH];
int composition[24];
float retention;
} training_set_type;
training_set_type *training_set;
char output[256];
char output_format[256];
char input_format[20];
char *p, q[100], **PEP;
pmsms_pipeline_analysis pepXML_file;
pdelegate_list dlgl;
pdelegate_type dlg;
FILE *inp, *outp;
int a, b, i, j, k, l, m, n, seqlen, n_training,length;
double xi, yi, ei, chisq;
gsl_matrix *X, *cov;
gsl_vector *y, *w, *c;
gsl_multifit_linear_workspace *work;
/* parsing command line parameters */
if ((argc<2)||(argc>5))
{
printf("usage: rt -i <training set in tab delimited or PeptideProphet pepXML format> [-f <tab>|<XML> output format)] (type rt --help for more information\n");
return -1;
}
if( (strcmp(argv[1],"--help")==0) || (strcmp(argv[1],"-help")==0) || (strcmp(argv[1],"-h")==0) ) /* want help? */
{
printf("rt - (c) Magnus Palmblad 2002-2012\n\nusage: rt -i <training set in tab-delimited or pepXML format (after PeptideProphet)> [-f <tab>|<XML> output format)]\nrt trains a linear model for predicting retention time, or in fact any additive property as function of amino acid composition. The input should either be a tab-delimited text file with peptide sequences in the first column and a numerical value (retention time) in the second column, or a pepXML file generated by PeptideProphet in the Trans-Proteomic Pipeline. For more information, see http://www.ms-utils.org/rt or e-mail magnus.palmblad@gmail.com\n");
return 0;
}
for(i=1;i<argc;i++) {
if( (argv[i][0]=='-') && (argv[i][1]=='i') ) strcpy(infile,&argv[strlen(argv[i])>2?i:i+1][strlen(argv[i])>2?2:0]);
if( (argv[i][0]=='-') && (argv[i][1]=='f') ) strcpy(output_format,&argv[strlen(argv[i])>2?i:i+1][strlen(argv[i])>2?2:0]);
}
if( (toupper(output_format[0])!='T') && (toupper(output_format[0])!='X') && (toupper(output_format[0])!='C') ) {
printf("usage: rt -i <training set in tab delimited or pepXML format> [-f <tab>|<XML> output format)]\n");
return -1;
}
strcpy(input_format,"tab"); /* default to tab-delimited input */
/* reading training set file */
//printf("checking input format and scanning training set in file %s...", infile); fflush(stdout);
n=0;
if ((inp = fopen(infile, "r"))==NULL) {printf("error opening training set file\n");return -1;}
fgets(line, 250, inp);
if(line[0]=='<') {strcpy(input_format,"pepXML"); n++;}
fgets(line, 250, inp);
while(line[i]) {line[i]=toupper(line[i]); i++;}
if(strstr(line,"MZIDENTML")!=NULL) {strcpy(input_format,"mzIdentML"); n++;}
while (fgets(line, 250, inp) != NULL) n++;
PEP=(char**)malloc(sizeof(char*)*n);
for(i=0;i<10000;i++) PEP[i]=(char*)malloc(sizeof(char)*200);
if(strcmp(input_format,"tab")==0)
{
n_training=n;
// printf("done\nallocating memory for %i peptides in training set...", n_training); fflush(stdout);
training_set=(training_set_type*)malloc(sizeof(training_set_type)*n_training);
// printf("done\nreading training set in tab delimited format (peptide tab retention time) from file %s...", infile); fflush(stdout);
if ((inp = fopen(infile, "r"))==NULL) {printf("error opening training set file\n");return -1;}
n=0;
while (fgets(line, 250, inp) != NULL)
{
sscanf(line,"%s\t%f",training_set[n].sequence,&(training_set[n].retention));
n++;
}
n_training=n;
fclose(inp);
// printf("done\n");
}
if(strcmp(input_format,"pepXML")==0)
{
// printf("done\nscanning training set in pepXML format from file %s...", infile); fflush(stdout);
n=0;
pepXML_file = read_pepxml_file(infile, 0, 0, NULL);
for (i=0; i<pepXML_file->run_summary_count; i++) {
for (j=0; j<pepXML_file->run_summary_array[i].spectrum_query_count; j++) n++;
}
n_training=n;
// printf("done\nallocating memory for %i peptides in training set...", n_training); fflush(stdout);
training_set=(training_set_type*)malloc(sizeof(training_set_type)*n_training);
n=0;
// printf("reading training set in pepXML format from file %s...", infile); fflush(stdout);
for (i=0; i<pepXML_file->run_summary_count; i++) {
for (j=0; j<pepXML_file->run_summary_array[i].spectrum_query_count; j++) {
strcpy(training_set[n].sequence, pepXML_file->run_summary_array[i].spectrum_query_array[j].search_result_array[0].search_hit_array[0].peptide);
training_set[n].retention = pepXML_file->run_summary_array[i].spectrum_query_array[j].retention_time_sec;
n++;
}
}
}
if(strcmp(input_format,"mzIdentML")==0)
{
//printf("done\nscanning training set in mzIdentML format from file %s...", infile); fflush(stdout);
n=0;
if ((inp = fopen(infile, "r"))==NULL) {printf("error opening training set file\n");return -1;}
while (fgets(line, 250, inp) != NULL)
{
if(strstr(line,"PeptideEvidence")!=NULL) break;
if(strstr(line,"<Peptide id")!=NULL)
{
//PEP[a]=(char*)malloc(sizeof(char)*strlen(q));
p=strtok(line,"\""); p=strtok('\0',"\"");
a=atoi(p+4);
//printf("\n%i = ",a); fflush(stdout);
p=strtok('\0',"\"");
if(strstr(p,"<PeptideSequence>")!=NULL)
{
p=strchr(p+10,'>')+1;
i=strspn(p,AMINO_ACIDS);
strncpy(q,p,i); q[i]='\0';
// printf("PEP_%i=%s\n",a,q); fflush(stdout);
strcpy(PEP[a],q);
}
n++;
}
}
n_training=n;
// printf("done\nallocating memory for %i peptides in training set...", n_training); fflush(stdout);
training_set=(training_set_type*)malloc(sizeof(training_set_type)*n_training*10);
n=0;
while (fgets(line, 250, inp) != NULL)
{
if(strstr(line,"peptide_ref")!=NULL)
{
p=strstr(line,"peptide_ref");
a=atoi(strtok(p+17,"\""));
}
if(strstr(line,"name=\"scan start time\" value")!=NULL)
{
p=strstr(line,"name=\"scan start time\" value");
i=strcspn(p+31,"\"");
strncpy(q,p+30,i); q[i]='\0';
// if(strlen(PEP[a])>6) {printf("%i, %s, %s\n",a,PEP[a],q); fflush(stdout);}
if(strlen(PEP[a])>6) {strcpy(training_set[n].sequence,PEP[a]); training_set[n].retention=atof(q); n++;}
}
}
}
n_training=n;
//return 0;
/* allocating memory for training */
X=gsl_matrix_alloc(n_training,25); /* 20 normal amino acids, pS, pT, pY, oxidized M and V0 */
y=gsl_vector_alloc(n_training);
w=gsl_vector_alloc(n_training);
c=gsl_vector_alloc(25);
cov=gsl_matrix_alloc(25,25);
for(i=0;i<25;i++) gsl_vector_set(c,i,1.0);
/* calculate training set X matrix (amino acid composition for each peptide in training set) */
for(n=0;n<n_training;n++)
{
gsl_vector_set(y,n,training_set[n].retention);
gsl_vector_set(w,n,0.36);
for(i=0;i<24;i++) training_set[n].composition[i]=0;
{
for(i=0;i<strlen(training_set[n].sequence);i++)
{
a=24-strlen(strchr(AMINO_ACIDS,training_set[n].sequence[i]));
training_set[n].composition[a]++;
}
}
for(i=0;i<24;i++) gsl_matrix_set(X,n,i,training_set[n].composition[i]);
gsl_matrix_set(X,n,24,1); /* to get V0 - the "offset" between runs */
}
work=gsl_multifit_linear_alloc(n_training,25);
gsl_multifit_wlinear(X,w,y,c,cov,&chisq,work);
gsl_multifit_linear_free(work);
if(toupper(output_format[0])=='T') /* output as tab-delimited text */
{
// printf("\nbest fit to experimental retention data:\n");
for(i=0;i<24;i++) printf("%c\t%f\n",AMINO_ACIDS[i],gsl_vector_get(c,(i)));
printf("O\t%f\n\n",gsl_vector_get(c,(24)));
return 0;
}
if(toupper(output_format[0])=='C') /* output CSV */
{
// printf("\nbest fit to experimental retention data:\n");
for(i=0;i<24;i++) printf("%c,%f\n",AMINO_ACIDS[i],gsl_vector_get(c,(i)));
printf("O,%f\n\n",gsl_vector_get(c,(24)));
return 0;
}
if(toupper(output_format[0])=='X') /* output XML */
{
// printf("\nretenion model in XML structure:\n\n"); /* comment out in deployed versions */
printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
printf("<rt_model training_file=\"%s\" rt_version=\"4.0\" input_format=\"%s\">\n",infile,input_format);
for(i=0;i<19;i++) printf(" <retention_coefficient amino_acid=\"%c\" value=\"%f\"/>\n",AMINO_ACIDS[i],gsl_vector_get(c,(i)));
printf(" <retention_coefficient amino_acid=\"m\" modification=\"oxidation\" value=\"%f\"/>\n",gsl_vector_get(c,(19)));
for(i=21;i<24;i++) printf(" <retention_coefficient amino_acid=\"%c\" modification=\"phosphorylation\" value=\"%f\"/>\n",AMINO_ACIDS[i],gsl_vector_get(c,(i)));
printf(" <retention_coefficient amino_acid=\"O\" modification=\"constant offset\" value=\"%f\"/>\n",gsl_vector_get(c,(24)));
printf("</rt_model>\n");
return 0;
}
}
| {
"alphanum_fraction": 0.5622380015,
"avg_line_length": 41.7464285714,
"ext": "c",
"hexsha": "215da43b61368a858c1520e11857c4f57304986f",
"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": "0f3afed032d28f71fc94e420ab1464e70daadac6",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "veitveit/Automatic-Workflow-Composition",
"max_forks_repo_path": "Use_case_1-amino_acid_index/rt4/rt4.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0f3afed032d28f71fc94e420ab1464e70daadac6",
"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": "veitveit/Automatic-Workflow-Composition",
"max_issues_repo_path": "Use_case_1-amino_acid_index/rt4/rt4.c",
"max_line_length": 627,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0f3afed032d28f71fc94e420ab1464e70daadac6",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "veitveit/Automatic-Workflow-Composition",
"max_stars_repo_path": "Use_case_1-amino_acid_index/rt4/rt4.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3079,
"size": 11689
} |
/*
* 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 json_58ea0e36_7aaa_49a1_b466_3bbbb2483c5b_h
#define json_58ea0e36_7aaa_49a1_b466_3bbbb2483c5b_h
#include <gslib/std.h>
__gslib_begin__
enum json_tag
{
jst_array,
jst_table,
jst_pair,
jst_value,
};
class json_node_value;
class __gs_novtable json_node abstract
{
public:
virtual ~json_node() {}
virtual json_tag get_tag() const = 0;
virtual const string& get_name() const = 0;
virtual json_node* duplicate() const = 0; /* delete */
};
struct json_node_hash
#if defined(_MSC_VER) && (_MSC_VER < 1914)
: public std::unary_function<json_node*, size_t>
#endif
{
public:
size_t operator()(const json_node* p) const
{
assert(p);
return string_hash(p->get_name());
}
};
struct json_node_equalto
#if defined(_MSC_VER) && (_MSC_VER < 1914)
: public std::binary_function<json_node*, json_node*, bool>
#endif
{
public:
bool operator()(const json_node* p1, const json_node* p2) const
{
assert(p1 && p2);
return p1->get_name() == p2->get_name();
}
};
typedef unordered_set<json_node*, json_node_hash, json_node_equalto> json_node_map;
typedef vector<json_node*> json_node_list;
class json_node_array:
public json_node
{
public:
virtual ~json_node_array();
virtual json_tag get_tag() const override { return jst_array; }
virtual const string& get_name() const override { return _name; }
virtual json_node* duplicate() const override;
protected:
string _name;
json_node_list _array;
public:
void set_name(const gchar* str) { _name.assign(str); }
void set_name(const gchar* str, int len) { _name.assign(str, len); }
void set_name(const string& str) { _name = str; }
bool is_empty() const { return _array.empty(); }
int get_childs() const { return (int)_array.size(); }
json_node* at(int i) const { return _array.at(i); }
int parse(const gchar* src, int len);
json_node_list& get_container() { return _array; }
};
class json_node_table:
public json_node
{
public:
virtual ~json_node_table();
virtual json_tag get_tag() const override { return jst_table; }
virtual const string& get_name() const override { return _name; }
virtual json_node* duplicate() const override;
protected:
string _name;
json_node_map _table;
public:
void set_name(const gchar* str) { _name.assign(str); }
void set_name(const gchar* str, int len) { _name.assign(str, len); }
void set_name(const string& str) { _name = str; }
bool is_empty() const { return _table.empty(); }
int get_childs() const { return (int)_table.size(); }
json_node* find(const string& name) const;
int parse(const gchar* src, int len);
json_node_map& get_container() { return _table; }
};
class json_node_value:
public json_node
{
public:
virtual json_tag get_tag() const override { return jst_value; }
virtual const string& get_name() const override { return _strval; }
virtual json_node* duplicate() const override;
protected:
string _strval;
public:
void set_value_string(const gchar* str) { _strval.assign(str); }
void set_value_string(const gchar* str, int len) { _strval.assign(str, len); }
void set_value_string(const string& str) { _strval = str; }
int parse(const gchar* src, int len);
};
class json_node_pair:
public json_node
{
public:
virtual json_tag get_tag() const override { return jst_pair; }
virtual const string& get_name() const override { return _name; }
virtual json_node* duplicate() const override;
protected:
string _name;
json_node_value _value;
public:
void set_name(const gchar* str) { _name.assign(str); }
void set_name(const gchar* str, int len) { _name.assign(str, len); }
void set_name(const string& str) { _name = str; }
void set_value(const gchar* str) { _value.set_value_string(str); }
void set_value(const gchar* str, int len) { _value.set_value_string(str, len); }
void set_value(const string& str) { _value.set_value_string(str); }
const json_node_value& get_value() const { return _value; }
const string& get_value_string() const { return _value.get_name(); }
int parse(const gchar* src, int len);
};
class json_key:
public json_node_pair
{
public:
json_key(const string& name) { _name = name; }
json_key(const gchar* str) { _name.assign(str); }
json_key(const gchar* str, int len) { _name.assign(str, len); }
};
class json_parser
{
public:
json_parser() { _root = nullptr; }
~json_parser() { destroy(); }
bool parse(const gchar* src, int len);
bool parse(const gchar* filename);
void destroy();
json_node* get_root() const { return _root; }
protected:
json_node* _root;
};
__gslib_end__
#endif
| {
"alphanum_fraction": 0.6709244771,
"avg_line_length": 31.472361809,
"ext": "h",
"hexsha": "a4445799968219ae1a57324b6ef9b680618e4112",
"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/json.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/json.h",
"max_line_length": 85,
"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/json.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": 1541,
"size": 6263
} |
#ifndef MCMC_AWAKE
#define MCMC_AWAKE
#include <stdarg.h>
#include <gbpRNG.h>
#include <gsl/gsl_linalg.h>
#define MCMC_COVERAGE_LINEAR 0
#define MCMC_COVERAGE_LOG 1
#define MCMC_NAME_SIZE 256
#define MCMC_MODE_SERIAL 1
#define MCMC_MODE_PARALLEL 2
#define MCMC_MODE_AUTOTUNE 8
#define MCMC_MODE_NO_MAP_WRITE 16
#define MCMC_MODE_REPORT_PROPS 32
#define MCMC_MODE_REFLECT_PRIORS 64
#define MCMC_MODE_MINIMIZE_IO 128
#define MCMC_MODE_AUTOTUNE_REINIT_TEMP 256
#define MCMC_MODE_ANALYZE_ALL_RUNS 512
#define MCMC_MODE_DEFAULT MCMC_MODE_AUTOTUNE | MCMC_MODE_SERIAL
#define MCMC_MAP_RETURN_GOOD 0
#define MCMC_MAP_RETURN_BAD 1
#define MCMC_DEFAULT_SUCCESS_TARGET 35.
#define MCMC_DEFAULT_SUCCESS_THRESH 5.
#define MCMC_DEFAULT_COVARIANCE_THRESH 10.
#define MCMC_DEFAULT_N_AUTOTUNE 1
#define MCMC_DEFAULT_N_AUTOTUNE_RANDOMIZE 0
#define MCMC_DEFAULT_N_AUTOTUNE_TEMPERATURE 100
#define MCMC_DEFAULT_N_AUTOTUNE_COVMTX (10 * MCMC->n_P * MCMC->n_P * (1 + (int)(100. / MCMC->success_target)))
#define MCMC_AUTOTUNE_CONVERGENCE_THRESH 1e-6
typedef struct MCMC_DS_info MCMC_DS_info;
struct MCMC_DS_info {
char name[MCMC_NAME_SIZE];
int n_D;
int * D;
int n_M;
double * M_target;
double * dM_target;
double ** array;
char ** array_name;
void * params;
int n_arrays;
double * M_best;
double * M_best_parameters;
double * M_peak_parameters;
double * M_min;
double * M_max;
double * M_lo_68;
double * M_hi_68;
double * M_lo_95;
double * M_hi_95;
double * M_avg;
double * dM_avg;
MCMC_DS_info *next;
};
typedef struct MCMC_info MCMC_info;
struct MCMC_info {
SID_Comm *comm;
char filename_output_root[SID_MAX_FILENAME_LENGTH];
char filename_output_dir[SID_MAX_FILENAME_LENGTH];
char problem_name[MCMC_NAME_SIZE];
int (*map_P_to_M)(double *, MCMC_info *, double **);
void (*compute_MCMC_ln_likelihood)(MCMC_info *MCMC,
double ** M,
double * P,
double * ln_likeliood_DS,
int * n_DoF_DS,
double * ln_likeliood_all,
int * n_DoF_all);
int my_chain;
int n_chains;
void * params;
char ** P_names;
double * P_init;
double * P_new;
double * P_last;
double * P_chain;
double * P_limit_min;
double * P_limit_max;
double * P_min;
double * P_max;
double * P_avg;
double * dP_avg;
double * P_best;
double * P_peak;
double * P_lo_68;
double * P_hi_68;
double * P_lo_95;
double * P_hi_95;
double ln_Pr_new;
double ln_Pr_last;
double ln_Pr_chain;
int * n_M;
double ** M_new;
double ** M_last;
int n_arrays;
char ** array_name;
double ** array;
double * V;
gsl_matrix * m;
gsl_vector * b;
int n_P;
int n_DS;
int n_M_total;
double temperature;
int n_avg;
int n_avg_covariance;
int n_iterations;
int n_iterations_burn;
int n_thin;
int coverage_size;
int flag_autocor_on;
int flag_no_map_write;
int flag_integrate_on;
int flag_analysis_on;
int flag_init_chain;
int first_map_call;
int first_link_call;
size_t n_map_calls;
int mode;
int n_success;
int n_fail;
int n_propositions;
double success_target;
double success_threshold;
double covariance_threshold;
int n_autotune;
int n_autotune_randomize;
int n_autotune_temperature;
int n_autotune_covariance;
int first_parameter_call;
int first_chain_call;
int first_likelihood_call;
double ln_likelihood_last;
double ln_likelihood_new;
double ln_likelihood_best;
double ln_likelihood_peak;
double ln_likelihood_chain;
double * ln_likelihood_DS;
double * ln_likelihood_DS_best;
double * ln_likelihood_DS_peak;
int * n_DoF_DS;
int * n_DoF_DS_best;
int * n_DoF_DS_peak;
int n_DoF;
int n_DoF_best;
int n_DoF_peak;
int P_name_length;
char P_name_format[8];
int seed;
RNG_info * RNG;
double * P;
MCMC_DS_info *DS;
MCMC_DS_info *last;
// This stuff is used when MCMC_MODE_MINIMIZE_IO is on
char * flag_success_buffer;
double *ln_likelihood_new_buffer;
double *P_new_buffer;
double *M_new_buffer;
};
#ifdef __cplusplus
extern "C" {
#endif
void init_MCMC(MCMC_info * MCMC,
const char *problem_name,
void * params,
int (*f)(double *, MCMC_info *, double **),
int n_P,
double *P_init,
char ** P_names,
double *P_limit_min,
double *P_limit_max,
int n_arrays,
...);
void init_MCMC_DS(MCMC_DS_info **new_DS, const char *name, int n_D, int *D, double *DS, double *dDS, void *params, int n_arrays, va_list vargs);
void start_loop_MCMC(MCMC_info *MCMC);
void end_loop_MCMC(MCMC_info *MCMC);
void restart_MCMC(MCMC_info *MCMC);
void init_MCMC_arrays(MCMC_info *MCMC);
void free_MCMC_DS(MCMC_info *MCMC);
void free_MCMC_arrays(MCMC_info *MCMC);
void free_MCMC_covariance(MCMC_info *MCMC);
void free_MCMC(MCMC_info *MCMC);
void add_MCMC_DS(MCMC_info *MCMC, const char *name, int n_D, int *D, double *DS, double *dDS, void *params, int n_arrays, ...);
void autotune_MCMC(MCMC_info *MCMC);
void autotune_MCMC_randomize(MCMC_info *MCMC);
void autotune_MCMC_temperature(MCMC_info *MCMC);
void autotune_MCMC_covariance(MCMC_info *MCMC);
void compute_MCMC_ln_likelihood_default(MCMC_info *MCMC,
double ** M,
double * P,
double * ln_likeliood_DS,
int * n_DoF_DS,
double * ln_likeliood_all,
int * n_DoF_all);
void compute_MCMC_chain_stats(double **x,
int n_x,
int n_avg,
double * x_min,
double * x_bar_in,
double * x_max,
double * x_sigma,
double **auto_cor,
double * slopes,
double * dP_sub,
double * ln_likelihood_in,
double * ln_likelihood_min,
double * ln_likelihood_avg,
double * ln_likelihood_max);
void compute_MCMC(MCMC_info *MCMC);
void analyze_MCMC(MCMC_info *MCMC);
void set_MCMC_covariance(MCMC_info *MCMC, double *V);
void set_MCMC_temperature(MCMC_info *MCMC, double temperature);
void set_MCMC_iterations(MCMC_info *MCMC, int n_avg, int n_thin, int n_burn, int n_integrate);
void set_MCMC_coverage_size(MCMC_info *MCMC, int coverage_size);
void set_MCMC_likelihood_function(MCMC_info *MCMC, void (*likelihood_function)(MCMC_info *, double **, double *, double *, int *, double *, int *));
void set_MCMC_directory(MCMC_info *MCMC, const char *directory);
void set_MCMC_mode(MCMC_info *MCMC, int mode);
void set_MCMC_autotune(MCMC_info *MCMC,
double success_target,
double success_threshold,
double covariance_threshold,
int n_autotune,
int n_autotune_randomize,
int n_autotune_temperature,
int n_autotune_covariance);
void read_MCMC_covariance(MCMC_info *MCMC, char *filename);
void read_MCMC_state(MCMC_info *MCMC);
void read_MCMC_configuration(MCMC_info *MCMC, char *filename_output_dir, int chain);
void rm_MCMC_directory(MCMC_info *MCMC);
int generate_MCMC_chain(MCMC_info *MCMC);
void generate_MCMC_proposition(MCMC_info *MCMC, int flag_chain_init);
void generate_MCMC_parameters(MCMC_info *MCMC);
#ifdef __cplusplus
}
#endif
#endif
| {
"alphanum_fraction": 0.5735195531,
"avg_line_length": 36.5306122449,
"ext": "h",
"hexsha": "75197212881b70d1ea21a38d54f0963e6a64ced3",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpMath/gbpMCMC/gbpMCMC.h",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpMath/gbpMCMC/gbpMCMC.h",
"max_line_length": 148,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpMath/gbpMCMC/gbpMCMC.h",
"max_stars_repo_stars_event_max_datetime": "2015-10-20T11:39:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-20T11:39:53.000Z",
"num_tokens": 2301,
"size": 8950
} |
/*
C code for actionAngle calculations
*/
#ifndef __GALPY_ACTIONANGLE_H__
#define __GALPY_ACTIONANGLE_H__
#include <gsl/gsl_roots.h>
#include <gsl/gsl_spline.h>
#include "interp_2d.h"
/*
Macro for dealing with potentially unused variables due to OpenMP
*/
/* If we're not using GNU C, elide __attribute__ if it doesn't exist*/
#ifndef __has_attribute // Compatibility with non-clang compilers.
#define __has_attribute(x) 0
#endif
#if defined(__GNUC__) || __has_attribute(unused)
# define UNUSED __attribute__((unused))
#else
# define UNUSED /*NOTHING*/
#endif
/*
Structure declarations
*/
struct actionAngleArg{ //I think this isn't used JB 06/24/14
double (*potentialEval)(double R, double Z, double phi, double t,
int nargs, double * args);
int nargs;
double * args;
interp_2d * i2d;
gsl_interp_accel * acc;
};
struct pragmasolver{
gsl_root_fsolver *s;
};
/*
Function declarations
*/
double evaluatePotentials(double,double,int, struct potentialArg *);
void parse_actionAngleArgs(int,struct potentialArg *,int *,double *);
#endif /* actionAngle.h */
| {
"alphanum_fraction": 0.7362132353,
"avg_line_length": 26.5365853659,
"ext": "h",
"hexsha": "a06f93f2df2279c66d90a17bf62b29232a8e4c25",
"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": "93a1b6fc8d138899922127086cc66184919c8cba",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "fardal/galpy",
"max_forks_repo_path": "galpy/actionAngle_src/actionAngle_c_ext/actionAngle.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba",
"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": "fardal/galpy",
"max_issues_repo_path": "galpy/actionAngle_src/actionAngle_c_ext/actionAngle.h",
"max_line_length": 72,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "fardal/galpy",
"max_stars_repo_path": "galpy/actionAngle_src/actionAngle_c_ext/actionAngle.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 281,
"size": 1088
} |
#pragma once
#include "ShaderCompiler.h"
#include "BgfxCallback.h"
#include <Babylon/JsRuntime.h>
#include <Babylon/JsRuntimeScheduler.h>
#include <GraphicsImpl.h>
#include <NativeWindow.h>
#include <napi/napi.h>
#include <bgfx/bgfx.h>
#include <bgfx/platform.h>
#include <bimg/bimg.h>
#include <bx/allocator.h>
#include <gsl/gsl>
#include <assert.h>
#include <arcana/containers/weak_table.h>
#include <arcana/threading/cancellation.h>
#include <unordered_map>
namespace Babylon
{
class ClearState final
{
public:
void UpdateColor(float r, float g, float b, float a)
{
const bool needToUpdate = r != Red || g != Green || b != Blue || a != Alpha;
if (needToUpdate)
{
Red = r;
Green = g;
Blue = b;
Alpha = a;
Update();
}
}
void UpdateFlags(const Napi::CallbackInfo& info)
{
const auto flags = static_cast<uint16_t>(info[0].As<Napi::Number>().Uint32Value());
Flags = flags;
Update();
}
void UpdateDepth(const Napi::CallbackInfo& info)
{
const auto depth = info[0].As<Napi::Number>().FloatValue();
const bool needToUpdate = Depth != depth;
if (needToUpdate)
{
Depth = depth;
Update();
}
}
void UpdateStencil(const Napi::CallbackInfo& info)
{
const auto stencil = static_cast<uint8_t>(info[0].As<Napi::Number>().Int32Value());
const bool needToUpdate = Stencil != stencil;
if (needToUpdate)
{
Stencil = stencil;
Update();
}
}
arcana::weak_table<std::function<void()>>::ticket AddUpdateCallback(std::function<void()> callback)
{
return m_callbacks.insert(std::move(callback));
}
void Update()
{
m_callbacks.apply_to_all([](std::function<void()>& callback) {
callback();
});
}
uint32_t Color() const
{
uint32_t color = 0x0;
color += static_cast<uint8_t>(Red * std::numeric_limits<uint8_t>::max());
color = color << 8;
color += static_cast<uint8_t>(Green * std::numeric_limits<uint8_t>::max());
color = color << 8;
color += static_cast<uint8_t>(Blue * std::numeric_limits<uint8_t>::max());
color = color << 8;
color += static_cast<uint8_t>(Alpha * std::numeric_limits<uint8_t>::max());
return color;
}
float Red{68.f / 255.f};
float Green{51.f / 255.f};
float Blue{85.f / 255.f};
float Alpha{1.f};
float Depth{1.f};
uint16_t Flags{BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH};
uint8_t Stencil{0};
private:
arcana::weak_table<std::function<void()>> m_callbacks{};
};
class ViewClearState final
{
public:
ViewClearState(uint16_t viewId, ClearState& clearState)
: m_viewId{viewId}
, m_clearState{clearState}
, m_callbackTicket{m_clearState.AddUpdateCallback([this]() { Update(); })}
{
}
void UpdateColor(float r, float g, float b, float a = 1.f)
{
m_clearState.UpdateColor(r, g, b, a);
}
void UpdateColor(const Napi::CallbackInfo& info)
{
const auto r = info[0].As<Napi::Number>().FloatValue();
const auto g = info[1].As<Napi::Number>().FloatValue();
const auto b = info[2].As<Napi::Number>().FloatValue();
const auto a = info[3].IsUndefined() ? 1.f : info[3].As<Napi::Number>().FloatValue();
m_clearState.UpdateColor(r, g, b, a);
}
void UpdateFlags(const Napi::CallbackInfo& info)
{
m_clearState.UpdateFlags(info);
}
void UpdateDepth(const Napi::CallbackInfo& info)
{
m_clearState.UpdateDepth(info);
}
void UpdateStencil(const Napi::CallbackInfo& info)
{
m_clearState.UpdateStencil(info);
}
void UpdateViewId(uint16_t viewId)
{
m_viewId = viewId;
Update();
}
private:
void Update() const
{
bgfx::setViewClear(m_viewId, m_clearState.Flags, m_clearState.Color(), m_clearState.Depth, m_clearState.Stencil);
// discard any previous set state
bgfx::discard();
}
uint16_t m_viewId{};
ClearState& m_clearState;
arcana::weak_table<std::function<void()>>::ticket m_callbackTicket;
};
struct FrameBufferData final
{
private:
std::unique_ptr<ClearState> m_clearState{};
public:
FrameBufferData(bgfx::FrameBufferHandle frameBuffer, uint16_t viewId, uint16_t width, uint16_t height, bool actAsBackBuffer = false)
: m_clearState{std::make_unique<ClearState>()}
, FrameBuffer{frameBuffer}
, ViewId{viewId}
, ViewClearState{ViewId, *m_clearState}
, Width{width}
, Height{height}
, ActAsBackBuffer{actAsBackBuffer}
{
assert(ViewId < bgfx::getCaps()->limits.maxViews);
}
FrameBufferData(bgfx::FrameBufferHandle frameBuffer, uint16_t viewId, ClearState& clearState, uint16_t width, uint16_t height, bool actAsBackBuffer = false)
: m_clearState{}
, FrameBuffer{frameBuffer}
, ViewId{viewId}
, ViewClearState{ViewId, clearState}
, Width{width}
, Height{height}
, ActAsBackBuffer{actAsBackBuffer}
{
assert(ViewId < bgfx::getCaps()->limits.maxViews);
}
FrameBufferData(FrameBufferData&) = delete;
~FrameBufferData()
{
bgfx::destroy(FrameBuffer);
}
void UseViewId(uint16_t viewId)
{
ViewId = viewId;
ViewClearState.UpdateViewId(ViewId);
}
void SetUpView(uint16_t viewId)
{
bgfx::setViewFrameBuffer(viewId, FrameBuffer);
UseViewId(viewId);
bgfx::setViewRect(ViewId, 0, 0, Width, Height);
}
bgfx::FrameBufferHandle FrameBuffer{bgfx::kInvalidHandle};
bgfx::ViewId ViewId{};
Babylon::ViewClearState ViewClearState;
uint16_t Width{};
uint16_t Height{};
// When a FrameBuffer acts as a back buffer, it means it will not be used as a texture in a shader.
// For example as a post process. It will be used as-is in a swapchain or for direct rendering (XR)
// When this flag is true, projection matrix will not be flipped for API that would normaly need it.
// Namely Direct3D and Metal.
bool ActAsBackBuffer{false};
};
struct FrameBufferManager final
{
FrameBufferManager()
{
m_boundFrameBuffer = m_backBuffer = new FrameBufferData(BGFX_INVALID_HANDLE, GetNewViewId(), bgfx::getStats()->width, bgfx::getStats()->height);
}
FrameBufferData* CreateNew(bgfx::FrameBufferHandle frameBufferHandle, uint16_t width, uint16_t height)
{
return new FrameBufferData(frameBufferHandle, GetNewViewId(), width, height);
}
FrameBufferData* CreateNew(bgfx::FrameBufferHandle frameBufferHandle, ClearState& clearState, uint16_t width, uint16_t height, bool actAsBackBuffer)
{
return new FrameBufferData(frameBufferHandle, GetNewViewId(), clearState, width, height, actAsBackBuffer);
}
void Bind(FrameBufferData* data)
{
m_boundFrameBuffer = data;
// TODO: Consider doing this only on bgfx::reset(); the effects of this call don't survive reset, but as
// long as there's no reset this doesn't technically need to be called every time the frame buffer is bound.
m_boundFrameBuffer->SetUpView(GetNewViewId());
// bgfx::setTexture()? Why?
// TODO: View order?
m_renderingToTarget = !m_boundFrameBuffer->ActAsBackBuffer;
}
FrameBufferData& GetBound() const
{
return *m_boundFrameBuffer;
}
void Unbind(FrameBufferData* data)
{
// this assert is commented because of an issue with XR described here : https://github.com/BabylonJS/BabylonNative/issues/344
//assert(m_boundFrameBuffer == data);
(void)data;
m_boundFrameBuffer = m_backBuffer;
m_renderingToTarget = false;
}
uint16_t GetNewViewId()
{
m_nextId++;
assert(m_nextId < bgfx::getCaps()->limits.maxViews);
return m_nextId;
}
void Reset()
{
m_nextId = 0;
}
bool IsRenderingToTarget() const
{
return m_renderingToTarget;
}
private:
FrameBufferData* m_boundFrameBuffer{nullptr};
FrameBufferData* m_backBuffer{nullptr};
uint16_t m_nextId{0};
bool m_renderingToTarget{false};
};
struct TextureData final
{
~TextureData()
{
if (bgfx::isValid(Handle))
{
bgfx::destroy(Handle);
}
}
bgfx::TextureHandle Handle{bgfx::kInvalidHandle};
uint32_t Width{0};
uint32_t Height{0};
uint32_t Flags{0};
uint8_t AnisotropicLevel{0};
};
struct ImageData final
{
~ImageData()
{
if (Image)
{
bimg::imageFree(Image.get());
}
}
std::unique_ptr<bimg::ImageContainer> Image;
};
struct UniformInfo final
{
uint8_t Stage{};
bgfx::UniformHandle Handle{bgfx::kInvalidHandle};
bool YFlip{false};
};
struct ProgramData final
{
ProgramData() = default;
ProgramData(const ProgramData&) = delete;
ProgramData(ProgramData&&) = delete;
~ProgramData()
{
bgfx::destroy(Program);
}
std::unordered_map<std::string, uint32_t> VertexAttributeLocations{};
std::unordered_map<std::string, UniformInfo> VertexUniformInfos{};
std::unordered_map<std::string, UniformInfo> FragmentUniformInfos{};
bgfx::ProgramHandle Program{};
struct UniformValue
{
std::vector<float> Data{};
uint16_t ElementLength{};
bool YFlip{false};
};
std::unordered_map<uint16_t, UniformValue> Uniforms{};
void SetUniform(bgfx::UniformHandle handle, gsl::span<const float> data, bool YFlip, size_t elementLength = 1)
{
UniformValue& value = Uniforms[handle.idx];
value.Data.assign(data.begin(), data.end());
value.ElementLength = static_cast<uint16_t>(elementLength);
value.YFlip = YFlip;
}
};
class IndexBufferData;
class VertexBufferData;
struct VertexArray final
{
~VertexArray()
{
for (auto& vertexBuffer : vertexBuffers)
{
bgfx::destroy(vertexBuffer.vertexLayoutHandle);
}
}
struct IndexBuffer
{
const IndexBufferData* data{};
};
IndexBuffer indexBuffer{};
struct VertexBuffer
{
const VertexBufferData* data{};
uint32_t startVertex{};
bgfx::VertexLayoutHandle vertexLayoutHandle{};
};
std::vector<VertexBuffer> vertexBuffers{};
};
class NativeEngine final : public Napi::ObjectWrap<NativeEngine>
{
static constexpr auto JS_CLASS_NAME = "_NativeEngine";
static constexpr auto JS_ENGINE_CONSTRUCTOR_NAME = "Engine";
static constexpr auto JS_AUTO_RENDER_PROPERTY_NAME = "_AUTO_RENDER";
public:
NativeEngine(const Napi::CallbackInfo& info);
NativeEngine(const Napi::CallbackInfo& info, JsRuntime& runtime, Plugins::Internal::NativeWindow& nativeWindow);
~NativeEngine();
static void Initialize(Napi::Env, bool autoRender);
FrameBufferManager& GetFrameBufferManager();
void Dispatch(std::function<void()>);
void ScheduleRender();
const bool AutomaticRenderingEnabled{};
JsRuntimeScheduler RuntimeScheduler;
private:
void Dispose();
void Dispose(const Napi::CallbackInfo& info);
Napi::Value GetEngine(const Napi::CallbackInfo& info); // TODO: Hack, temporary method. Remove as part of the change to get rid of NapiBridge.
void RequestAnimationFrame(const Napi::CallbackInfo& info);
Napi::Value CreateVertexArray(const Napi::CallbackInfo& info);
void DeleteVertexArray(const Napi::CallbackInfo& info);
void BindVertexArray(const Napi::CallbackInfo& info);
Napi::Value CreateIndexBuffer(const Napi::CallbackInfo& info);
void DeleteIndexBuffer(const Napi::CallbackInfo& info);
void RecordIndexBuffer(const Napi::CallbackInfo& info);
void UpdateDynamicIndexBuffer(const Napi::CallbackInfo& info);
Napi::Value CreateVertexBuffer(const Napi::CallbackInfo& info);
void DeleteVertexBuffer(const Napi::CallbackInfo& info);
void RecordVertexBuffer(const Napi::CallbackInfo& info);
void UpdateDynamicVertexBuffer(const Napi::CallbackInfo& info);
Napi::Value CreateProgram(const Napi::CallbackInfo& info);
Napi::Value GetUniforms(const Napi::CallbackInfo& info);
Napi::Value GetAttributes(const Napi::CallbackInfo& info);
void SetProgram(const Napi::CallbackInfo& info);
void SetState(const Napi::CallbackInfo& info);
void SetZOffset(const Napi::CallbackInfo& info);
Napi::Value GetZOffset(const Napi::CallbackInfo& info);
void SetDepthTest(const Napi::CallbackInfo& info);
Napi::Value GetDepthWrite(const Napi::CallbackInfo& info);
void SetDepthWrite(const Napi::CallbackInfo& info);
void SetColorWrite(const Napi::CallbackInfo& info);
void SetBlendMode(const Napi::CallbackInfo& info);
void SetMatrix(const Napi::CallbackInfo& info);
void SetInt(const Napi::CallbackInfo& info);
void SetIntArray(const Napi::CallbackInfo& info);
void SetIntArray2(const Napi::CallbackInfo& info);
void SetIntArray3(const Napi::CallbackInfo& info);
void SetIntArray4(const Napi::CallbackInfo& info);
void SetFloatArray(const Napi::CallbackInfo& info);
void SetFloatArray2(const Napi::CallbackInfo& info);
void SetFloatArray3(const Napi::CallbackInfo& info);
void SetFloatArray4(const Napi::CallbackInfo& info);
void SetMatrices(const Napi::CallbackInfo& info);
void SetMatrix3x3(const Napi::CallbackInfo& info);
void SetMatrix2x2(const Napi::CallbackInfo& info);
void SetFloat(const Napi::CallbackInfo& info);
void SetFloat2(const Napi::CallbackInfo& info);
void SetFloat3(const Napi::CallbackInfo& info);
void SetFloat4(const Napi::CallbackInfo& info);
Napi::Value CreateTexture(const Napi::CallbackInfo& info);
Napi::Value CreateDepthTexture(const Napi::CallbackInfo& info);
void LoadTexture(const Napi::CallbackInfo& info);
void LoadCubeTexture(const Napi::CallbackInfo& info);
void LoadCubeTextureWithMips(const Napi::CallbackInfo& info);
Napi::Value GetTextureWidth(const Napi::CallbackInfo& info);
Napi::Value GetTextureHeight(const Napi::CallbackInfo& info);
void SetTextureSampling(const Napi::CallbackInfo& info);
void SetTextureWrapMode(const Napi::CallbackInfo& info);
void SetTextureAnisotropicLevel(const Napi::CallbackInfo& info);
void SetTexture(const Napi::CallbackInfo& info);
void DeleteTexture(const Napi::CallbackInfo& info);
Napi::Value CreateFrameBuffer(const Napi::CallbackInfo& info);
void DeleteFrameBuffer(const Napi::CallbackInfo& info);
void BindFrameBuffer(const Napi::CallbackInfo& info);
void UnbindFrameBuffer(const Napi::CallbackInfo& info);
void DrawIndexed(const Napi::CallbackInfo& info);
void Draw(const Napi::CallbackInfo& info);
void Clear(const Napi::CallbackInfo& info);
void ClearColor(const Napi::CallbackInfo& info);
void ClearStencil(const Napi::CallbackInfo& info);
void ClearDepth(const Napi::CallbackInfo& info);
Napi::Value GetRenderWidth(const Napi::CallbackInfo& info);
Napi::Value GetRenderHeight(const Napi::CallbackInfo& info);
void SetViewPort(const Napi::CallbackInfo& info);
void GetFramebufferData(const Napi::CallbackInfo& info);
Napi::Value GetRenderAPI(const Napi::CallbackInfo& info);
void UpdateSize(size_t width, size_t height);
template<typename SchedulerT>
arcana::task<void, std::exception_ptr> GetRequestAnimationFrameTask(SchedulerT&);
bool m_isRenderScheduled{false};
arcana::cancellation_source m_cancelSource{};
ShaderCompiler m_shaderCompiler;
ProgramData* m_currentProgram{nullptr};
arcana::weak_table<std::unique_ptr<ProgramData>> m_programDataCollection{};
JsRuntime& m_runtime;
Graphics::Impl& m_graphicsImpl;
bx::DefaultAllocator m_allocator;
uint64_t m_engineState;
FrameBufferManager m_frameBufferManager{};
Plugins::Internal::NativeWindow::NativeWindow::OnResizeCallbackTicket m_resizeCallbackTicket;
template<int size, typename arrayType>
void SetTypeArrayN(const Napi::CallbackInfo& info);
template<int size>
void SetFloatN(const Napi::CallbackInfo& info);
template<int size>
void SetMatrixN(const Napi::CallbackInfo& info);
// Scratch vector used for data alignment.
std::vector<float> m_scratch{};
Napi::FunctionReference m_requestAnimationFrameCallback{};
// webgl/opengl draw call parameters allow to set first index and number of indices used for that call
// but with bgfx, those parameters must be set when binding the index buffer
// at the time of webgl binding, we don't know those values yet
// so a pointer to the to-bind buffer is kept and the buffer is bound to bgfx at the time of the drawcall
const IndexBufferData* m_currentBoundIndexBuffer{};
};
}
| {
"alphanum_fraction": 0.6135237385,
"avg_line_length": 34.6254612546,
"ext": "h",
"hexsha": "a6170cc44ebc39bd7096566876eb43b70b8c62f8",
"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": "e81f65f129e5f93a343ab79e0fc93a18f4f10899",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "syntheticmagus/BabylonNative",
"max_forks_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e81f65f129e5f93a343ab79e0fc93a18f4f10899",
"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": "syntheticmagus/BabylonNative",
"max_issues_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h",
"max_line_length": 164,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e81f65f129e5f93a343ab79e0fc93a18f4f10899",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "syntheticmagus/BabylonNative",
"max_stars_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4245,
"size": 18767
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.