Search is not available for this dataset
text string | meta dict |
|---|---|
/////////////////////////////////////////////////////////////////////
// = NMatrix
//
// A linear algebra library for scientific computation in Ruby.
// NMatrix is part of SciRuby.
//
// NMatrix was originally inspired by and derived from NArray, by
// Masahiro Tanaka: http://narray.rubyforge.org
//
// == Copyright Information
//
// SciRuby is Copyright (c) 2010 - 2014, Ruby Science Foundation
// NMatrix is Copyright (c) 2012 - 2014, John Woods and the Ruby Science Foundation
//
// Please see LICENSE.txt for additional copyright notices.
//
// == Contributing
//
// By contributing source code to SciRuby, you agree to be bound by
// our Contributor Agreement:
//
// * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement
//
// == gemv.h
//
// Header file for interface with ATLAS's CBLAS gemv functions and
// native templated version of LAPACK's gemv function.
//
#ifndef GEMV_H
# define GEMV_H
extern "C" { // These need to be in an extern "C" block or you'll get all kinds of undefined symbol errors.
#if defined HAVE_CBLAS_H
#include <cblas.h>
#elif defined HAVE_ATLAS_CBLAS_H
#include <atlas/cblas.h>
#endif
}
namespace nm { namespace math {
/*
* GEneral Matrix-Vector multiplication: based on dgemv.f from Netlib.
*
* This is an extremely inefficient algorithm. Recommend using ATLAS' version instead.
*
* Template parameters: LT -- long version of type T. Type T is the matrix dtype.
*/
template <typename DType>
inline bool gemv(const enum CBLAS_TRANSPOSE Trans, const int M, const int N, const DType* alpha, const DType* A, const int lda,
const DType* X, const int incX, const DType* beta, DType* Y, const int incY) {
int lenX, lenY, i, j;
int kx, ky, iy, jx, jy, ix;
typename LongDType<DType>::type temp;
// Test the input parameters
if (Trans < 111 || Trans > 113) {
rb_raise(rb_eArgError, "GEMV: TransA must be CblasNoTrans, CblasTrans, or CblasConjTrans");
return false;
} else if (lda < std::max(1, N)) {
fprintf(stderr, "GEMV: N = %d; got lda=%d", N, lda);
rb_raise(rb_eArgError, "GEMV: Expected lda >= max(1, N)");
return false;
} else if (incX == 0) {
rb_raise(rb_eArgError, "GEMV: Expected incX != 0\n");
return false;
} else if (incY == 0) {
rb_raise(rb_eArgError, "GEMV: Expected incY != 0\n");
return false;
}
// Quick return if possible
if (!M or !N or (*alpha == 0 and *beta == 1)) return true;
if (Trans == CblasNoTrans) {
lenX = N;
lenY = M;
} else {
lenX = M;
lenY = N;
}
if (incX > 0) kx = 0;
else kx = (lenX - 1) * -incX;
if (incY > 0) ky = 0;
else ky = (lenY - 1) * -incY;
// Start the operations. In this version, the elements of A are accessed sequentially with one pass through A.
if (*beta != 1) {
if (incY == 1) {
if (*beta == 0) {
for (i = 0; i < lenY; ++i) {
Y[i] = 0;
}
} else {
for (i = 0; i < lenY; ++i) {
Y[i] *= *beta;
}
}
} else {
iy = ky;
if (*beta == 0) {
for (i = 0; i < lenY; ++i) {
Y[iy] = 0;
iy += incY;
}
} else {
for (i = 0; i < lenY; ++i) {
Y[iy] *= *beta;
iy += incY;
}
}
}
}
if (*alpha == 0) return false;
if (Trans == CblasNoTrans) {
// Form y := alpha*A*x + y.
jx = kx;
if (incY == 1) {
for (j = 0; j < N; ++j) {
if (X[jx] != 0) {
temp = *alpha * X[jx];
for (i = 0; i < M; ++i) {
Y[i] += A[j+i*lda] * temp;
}
}
jx += incX;
}
} else {
for (j = 0; j < N; ++j) {
if (X[jx] != 0) {
temp = *alpha * X[jx];
iy = ky;
for (i = 0; i < M; ++i) {
Y[iy] += A[j+i*lda] * temp;
iy += incY;
}
}
jx += incX;
}
}
} else { // TODO: Check that indices are correct! They're switched for C.
// Form y := alpha*A**DType*x + y.
jy = ky;
if (incX == 1) {
for (j = 0; j < N; ++j) {
temp = 0;
for (i = 0; i < M; ++i) {
temp += A[j+i*lda]*X[j];
}
Y[jy] += *alpha * temp;
jy += incY;
}
} else {
for (j = 0; j < N; ++j) {
temp = 0;
ix = kx;
for (i = 0; i < M; ++i) {
temp += A[j+i*lda] * X[ix];
ix += incX;
}
Y[jy] += *alpha * temp;
jy += incY;
}
}
}
return true;
} // end of GEMV
#if (defined(HAVE_CBLAS_H) || defined(HAVE_ATLAS_CBLAS_H))
template <>
inline bool gemv(const enum CBLAS_TRANSPOSE Trans, const int M, const int N, const float* alpha, const float* A, const int lda,
const float* X, const int incX, const float* beta, float* Y, const int incY) {
cblas_sgemv(CblasRowMajor, Trans, M, N, *alpha, A, lda, X, incX, *beta, Y, incY);
return true;
}
template <>
inline bool gemv(const enum CBLAS_TRANSPOSE Trans, const int M, const int N, const double* alpha, const double* A, const int lda,
const double* X, const int incX, const double* beta, double* Y, const int incY) {
cblas_dgemv(CblasRowMajor, Trans, M, N, *alpha, A, lda, X, incX, *beta, Y, incY);
return true;
}
template <>
inline bool gemv(const enum CBLAS_TRANSPOSE Trans, const int M, const int N, const Complex64* alpha, const Complex64* A, const int lda,
const Complex64* X, const int incX, const Complex64* beta, Complex64* Y, const int incY) {
cblas_cgemv(CblasRowMajor, Trans, M, N, alpha, A, lda, X, incX, beta, Y, incY);
return true;
}
template <>
inline bool gemv(const enum CBLAS_TRANSPOSE Trans, const int M, const int N, const Complex128* alpha, const Complex128* A, const int lda,
const Complex128* X, const int incX, const Complex128* beta, Complex128* Y, const int incY) {
cblas_zgemv(CblasRowMajor, Trans, M, N, alpha, A, lda, X, incX, beta, Y, incY);
return true;
}
#endif
}} // end of namespace nm::math
#endif // GEMM_H
| {
"alphanum_fraction": 0.5555370801,
"avg_line_length": 27.9720930233,
"ext": "h",
"hexsha": "88d3f3c513b2a528f11fd8963e30bec1465d3cfa",
"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": "de9c8ea1d42da57b0a23ce1c2ab9614fa2a65e6d",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "cjfuller/nmatrix",
"max_forks_repo_path": "ext/nmatrix/math/gemv.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "de9c8ea1d42da57b0a23ce1c2ab9614fa2a65e6d",
"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": "cjfuller/nmatrix",
"max_issues_repo_path": "ext/nmatrix/math/gemv.h",
"max_line_length": 137,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "de9c8ea1d42da57b0a23ce1c2ab9614fa2a65e6d",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "cjfuller/nmatrix",
"max_stars_repo_path": "ext/nmatrix/math/gemv.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1932,
"size": 6014
} |
#pragma once
#include <memory>
#include <iterator>
#include <cstddef>
#include <gsl/gsl>
namespace dr {
/// \brief round `s` up to the nearest multiple of n
template<typename T>
T round_up(T s, unsigned int n) { return ((s + n - 1) / n) * n; }
template<typename T, typename Allocator = std::allocator<T>>
struct gap_buffer {
using value_type = T;
using allocator_type = Allocator;
using size_type = std::size_t;
using difference_type = ptrdiff_t;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = typename std::allocator_traits<Allocator>::pointer;
using const_pointer = typename std::allocator_traits<Allocator>::const_pointer;
struct const_iterator;
struct iterator {
using self_type = iterator;
using container_type = gap_buffer;
using value_type = container_type::value_type;
using difference_type = container_type::difference_type;
using reference = container_type::reference;
using pointer = container_type::pointer;
using iterator_category = std::random_access_iterator_tag;
explicit iterator(gap_buffer* container = nullptr, difference_type offset = 0)
: container(container), offset(offset) { }
operator const_iterator() const {
return const_iterator(container, offset);
}
reference operator [](difference_type i) const {
return (*container)[offset + i];
}
reference operator *() const {
return (*container)[offset];
}
pointer operator ->() const {
return &(*container)[offset];
}
self_type& operator ++() {
offset++;
return *this;
}
self_type operator ++(int) {
self_type retval = *this;
this->operator ++();
return retval;
}
self_type& operator --() {
offset--;
return *this;
}
self_type operator --(int) {
self_type retval = *this;
this->operator --();
return retval;
}
bool operator ==(const self_type& other) const {
return container == other.container && offset == other.offset;
}
bool operator !=(const self_type& other) const {
return !(*this == other);
}
bool operator <(const self_type& other) const {
Expects(container == other.container);
return offset < other.offset;
}
bool operator >(const self_type& other) const {
return other < *this;
}
bool operator <=(const self_type& other) const {
return !(other < *this);
}
bool operator >=(const self_type& other) const {
return !(*this < other);
}
self_type& operator +=(difference_type n) {
offset += n;
return *this;
}
friend
self_type operator +(self_type it, difference_type n) {
it.offset += n;
return it;
}
friend
self_type operator +(difference_type n, self_type it) {
it.offset += n;
return it;
}
self_type& operator -=(difference_type n) {
offset -= n;
return *this;
}
self_type operator -(difference_type n) const {
return self_type(container, offset - n);
}
difference_type operator -(const self_type& other) const {
Expects(container == other.container);
return offset - other.offset;
}
friend class gap_buffer;
private:
gap_buffer* container;
difference_type offset;
};
// Here we repeat ourselves, that is, DRY principle is violated.
// We can get rid of the repetition with CRTP. But let's keep it
// as is.
struct const_iterator {
using self_type = const_iterator;
using container_type = gap_buffer;
using value_type = container_type::value_type;
using difference_type = container_type::difference_type;
using reference = container_type::const_reference;
using pointer = container_type::const_pointer;
using iterator_category = std::random_access_iterator_tag;
explicit const_iterator(const gap_buffer* container = nullptr, difference_type offset = 0)
: container(container),
offset(offset) { }
reference operator [](difference_type i) const {
return (*container)[offset + i];
}
reference operator *() const {
return (*container)[offset];
}
pointer operator ->() const {
return &(*container)[offset];
}
self_type& operator ++() {
offset++;
return *this;
}
self_type operator ++(int) {
self_type retval = *this;
this->operator ++();
return retval;
}
self_type& operator --() {
offset--;
return *this;
}
self_type operator --(int) {
self_type retval = *this;
this->operator --();
return retval;
}
bool operator ==(const self_type& other) const {
return container == other.container && offset == other.offset;
}
bool operator !=(const self_type& other) const {
return !(*this == other);
}
bool operator <(const self_type& other) const {
Expects(container == other.container);
return offset < other.offset;
}
bool operator >(const self_type& other) const {
return other < *this;
}
bool operator <=(const self_type& other) const {
return !(other < *this);
}
bool operator >=(const self_type& other) const {
return !(*this < other);
}
self_type& operator +=(difference_type n) {
offset += n;
return *this;
}
friend
self_type operator +(self_type it, difference_type n) {
it.offset += n;
return it;
}
friend
self_type operator +(difference_type n, self_type it) {
it.offset += n;
return it;
}
self_type& operator -=(difference_type n) {
offset -= n;
return *this;
}
self_type operator -(difference_type n) const {
return self_type(container, offset - n);
}
difference_type operator -(const self_type& other) const {
Expects(container == other.container);
return offset - other.offset;
}
friend class gap_buffer;
private:
const gap_buffer* container;
difference_type offset;
};
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
private:
static constexpr float incremental_factor = 0.2;
static constexpr size_type default_size = 8;
static constexpr size_type alignment = 8;
public:
explicit gap_buffer(size_type count = default_size) {
if (count == 0) {
start = finish = gap_start = nullptr;
gap_size = 0;
}
else {
count = round_up(count, alignment);
start = allocate_and_construct(count);
finish = start + count;
gap_start = start;
gap_size = count;
}
}
gap_buffer(size_type count, const T& value)
: gap_buffer(count) {
for (size_type i = 0; i < count; ++i) push_back(value);
}
template<typename InputIt>
gap_buffer(InputIt first, InputIt last) {
difference_type n = std::distance(first, last);
size_type len = round_up(std::max(default_size, size_type(n)), alignment);
start = data_allocator.allocate(len);
finish = start + len;
int except_flag = 0;
try {
gap_start = std::uninitialized_copy(first, last, start);
except_flag = 1;
std::uninitialized_default_construct(gap_start, finish);
}
catch (...) {
switch (except_flag) {
case 1:
std::destroy(start, start + n);
// FALL THROUGH
case 0:
data_allocator.deallocate(start, finish - start);
default:;// DO NOTHING
}
throw;
}
gap_size = len - n;
}
gap_buffer(const gap_buffer& rhs)
: gap_buffer(rhs.begin(), rhs.end()) { }
gap_buffer(gap_buffer&& rhs) noexcept
: gap_buffer(0) { swap(rhs); }
gap_buffer(std::initializer_list<T> ilist)
: gap_buffer(ilist.begin(), ilist.end()) { }
gap_buffer& operator =(const gap_buffer& rhs) {
gap_buffer temp(rhs);
swap(temp);
return *this;
}
gap_buffer& operator =(gap_buffer&& rhs) noexcept {
swap(rhs);
return *this;
}
~gap_buffer() {
destroy_and_deallocate(start, finish);
start = finish = gap_start = nullptr;
gap_size = 0;
}
void swap(gap_buffer& rhs) {
using std::swap;
swap(start, rhs.start);
swap(finish, rhs.finish);
swap(gap_start, rhs.gap_start);
swap(gap_size, rhs.gap_size);
}
void assign(size_type count, const T& value) { *this = gap_buffer(count, value); }
template<typename InputIt>
void assign(InputIt first, InputIt last) { *this = gap_buffer(first, last); }
void assign(std::initializer_list<T> ilist) { *this = gap_buffer(ilist); }
allocator_type get_allocator() const { return data_allocator; }
// ------ basis START HERE ------
const_reference operator [](size_type pos) const {
if (start + pos < gap_start) return *(start + pos);
else return *(start + gap_size + pos);
}
iterator erase(const_iterator first, const_iterator last) {
Expects(first.container == this && last.container == this);
difference_type num_to_erase = std::distance(first, last);
relocate_gap(first.offset);
std::fill_n(gap_start + gap_size, num_to_erase, T{});
gap_size += num_to_erase;
return iterator(this, first.offset);
}
/// \return iterator to the first inserted element
template<class InputIt>
iterator insert(const_iterator pos, InputIt first, InputIt last) {
Expects(this == pos.container && pos <= end());
difference_type num_to_insert = std::distance(first, last);
if (gap_size >= num_to_insert) {
relocate_gap(pos.offset);
std::copy(first, last, gap_start);
gap_start += num_to_insert;
gap_size -= num_to_insert;
return iterator(this, pos.offset);
}
else {
size_type old_size = size();
size_type old_capacity = capacity();
auto default_delta = size_type(old_capacity * incremental_factor);
size_type delta = round_up(std::max(default_delta, num_to_insert - gap_size), alignment);
size_type new_capacity = std::max(old_capacity + delta, default_size);
gap_buffer temp(new_capacity);
relocate_gap(pos.offset);
auto cursor = std::copy(start, gap_start, temp.start);
cursor = std::copy(first, last, cursor);
std::copy(gap_start + gap_size, finish, cursor);
swap(temp);
gap_start = start + old_size + num_to_insert;
gap_size = finish - gap_start;
return iterator(this, pos.offset);
}
}
void reserve(size_type new_cap = 0) {
if (capacity() >= new_cap) return;
if (new_cap > max_size()) throw std::length_error("new_cap should be less than max_size()");
size_type old_size = size();
size_type new_capacity = round_up(new_cap, alignment);
gap_buffer temp(new_capacity);
auto cursor = std::copy(start, gap_start, temp.start);
std::copy(gap_start + gap_size, finish, cursor);
swap(temp);
gap_start = start + old_size;
gap_size = finish - gap_start;
}
size_type size() const noexcept { return finish - start - gap_size; }
size_type max_size() const noexcept { return size_type(1 << 31); }
size_type capacity() const noexcept { return finish - start; }
// ------ basis END HERE ------
reference operator [](size_type pos) {
return const_cast<reference>(
static_cast<const gap_buffer&>(*this)[pos]
);
}
const_reference at(size_type pos) const {
if (pos >= size()) throw std::out_of_range("index out of range");
return (*this)[pos];
}
reference at(size_type pos) {
return const_cast<reference>(
static_cast<const gap_buffer&>(*this).at(pos)
);
}
const_reference front() const { return (*this)[0]; }
reference front() {
return const_cast<reference>(
static_cast<const gap_buffer&>(*this).front()
);
}
const_reference back() const { return (*this)[size() - 1]; }
reference back() {
return const_cast<reference>(
static_cast<const gap_buffer&>(*this).back()
);
}
T* data() noexcept = delete;
const T* data() const noexcept = delete;
[[nodiscard]] bool empty() const noexcept { return size() == 0; }
void shrink_to_fit() {
gap_buffer temp(begin(), end());
swap(temp);
}
void clear() { erase(begin(), end()); }
void resize(size_type count, const value_type& value = value_type{}) {
if (count < size())
erase(begin() + count, end());
else
insert(end(), count - size(), value);
}
iterator insert(const_iterator pos, const T& value) {
return insert(pos, &value, &value + 1);
}
iterator insert(const_iterator pos, T&& value) {
return insert(pos, std::make_move_iterator(&value), std::make_move_iterator(&value + 1));
}
iterator insert(const_iterator pos, size_type count, const T& value) {
for (size_type i = 0; i < count; ++i)
pos = insert(pos, value);
return iterator(this, pos.offset);
}
iterator insert(const_iterator pos, std::initializer_list<T> ilist) {
return insert(pos, ilist.begin(), ilist.end());
}
void erase(const_iterator pos) { erase(pos, pos + 1); }
template<typename ... Args>
iterator emplace(const_iterator pos, Args&& ... args) {
return insert(pos, T(std::forward<Args>(args)...));
}
template<typename ... Args>
reference emplace_back(Args&& ... args) {
return *emplace(end(), std::forward<Args>(args)...);
}
void push_back(const T& value) { insert(end(), &value, &value + 1); }
void push_back(T&& value) { insert(end(), std::make_move_iterator(&value), std::make_move_iterator(&value + 1)); }
void pop_back() { erase(end() - 1); }
const_iterator begin() const noexcept { return const_iterator(this); }
const_iterator cbegin() const noexcept { return begin(); }
const_iterator end() const noexcept { return const_iterator(this, size()); }
const_iterator cend() const noexcept { return end(); }
iterator begin() noexcept { return iterator(this); }
iterator end() noexcept { return iterator(this, size()); }
const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator(end()); }
const_reverse_iterator crbegin() const noexcept { return rbegin(); }
const_reverse_iterator rend() const noexcept { return const_reverse_iterator(begin()); }
const_reverse_iterator crend() const noexcept { return rend(); }
reverse_iterator rbegin() noexcept { return reverse_iterator(end()); }
reverse_iterator rend() noexcept { return reverse_iterator(begin()); }
friend
bool operator ==(const gap_buffer& lhs, const gap_buffer& rhs) {
return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
friend
bool operator !=(const gap_buffer& lhs, const gap_buffer& rhs) {
return !(lhs == rhs);
}
friend
bool operator <(const gap_buffer& lhs, const gap_buffer& rhs) {
auto[left, right] = std::mismatch(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
if (right == rhs.end()) return false;
else if (left == lhs.end()) return true;
else return *left < *right;
}
friend
bool operator >(const gap_buffer& lhs, const gap_buffer& rhs) {
return rhs < lhs;
}
friend
bool operator <=(const gap_buffer& lhs, const gap_buffer& rhs) {
return !(rhs < lhs);
}
friend
bool operator >=(const gap_buffer& lhs, const gap_buffer& rhs) {
return !(lhs < rhs);
}
// additional
template<typename InputIt>
void append(InputIt first, InputIt last) {
insert(end(), first, last);
}
void append(const T& value) { push_back(value); }
void append(T&& value) { push_back(std::move(value)); }
template<typename InputIt>
void replace(const_iterator f1, const_iterator l1, InputIt f2, InputIt l2) {
auto cursor = erase(f1, l1);
insert(cursor, f2, l2);
}
template<typename InputIt>
void replace(const_iterator pos, InputIt first, InputIt last) {
replace(pos, pos + 1, first, last);
}
gap_buffer substr(const_iterator first, const_iterator last) const {
return substr_impl<gap_buffer>(first, last);
}
protected:
template<typename U>
U substr_impl(const_iterator first, const_iterator last) const {
return U(first, last);
}
void relocate_gap(difference_type offset) {
if (gap_start != start + offset) {
if (gap_start < start + offset)
std::move(gap_start /**/ + gap_size,
start + offset + gap_size,
gap_start);
else
std::move_backward(start + offset,
gap_start,
gap_start + gap_size);
gap_start = start + offset;
}
}
pointer allocate_and_construct(size_type n) {
pointer result = data_allocator.allocate(n);
std::uninitialized_default_construct_n(result, n);
return result;
}
void destroy_and_deallocate(pointer start, pointer finish) {
std::destroy(start, finish);
if (start)
data_allocator.deallocate(start, finish - start);
}
private:
Allocator data_allocator;
pointer start;
pointer finish;
pointer gap_start;
size_type gap_size;
};
template<typename T, typename Allocator>
void swap(gap_buffer<T, Allocator>& lhs, gap_buffer<T, Allocator>& rhs) {
lhs.swap(rhs);
}
}
| {
"alphanum_fraction": 0.6386515816,
"avg_line_length": 26.9424572317,
"ext": "h",
"hexsha": "30128633a412da2b11f1833ec52d0b0e2c142bc9",
"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": "b6b3d621430029d989ebed8a672eee769c214ea5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lie-yan/gapbuffer",
"max_forks_repo_path": "include/gap_buffer.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b6b3d621430029d989ebed8a672eee769c214ea5",
"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": "lie-yan/gapbuffer",
"max_issues_repo_path": "include/gap_buffer.h",
"max_line_length": 116,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "b6b3d621430029d989ebed8a672eee769c214ea5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lie-yan/gapbuffer",
"max_stars_repo_path": "include/gap_buffer.h",
"max_stars_repo_stars_event_max_datetime": "2018-04-02T09:33:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-02-28T12:41:19.000Z",
"num_tokens": 4130,
"size": 17324
} |
#include <jni.h>
#include <assert.h>
#include <lapacke.h>
/* Cholesky */
JNIEXPORT jint Java_JAMAJni_CholeskyDecomposition_dpotrf (JNIEnv *env, jclass klass, jint matrix_layout, jchar uplo, jint n, jdoubleArray a, jint lda){
double *aElems;
int info;
aElems = (*env)-> GetDoubleArrayElements (env, a, NULL);
assert(aElems);
info = LAPACKE_dpotrf((int) matrix_layout, (char) uplo, (lapack_int) n, aElems, (lapack_int) lda);
(*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0);
return info;
}
JNIEXPORT jint Java_JAMAJni_CholeskyDecomposition_dpotri(JNIEnv *env, jclass klass, jint matrix_layout, jchar uplo, jint n, jdoubleArray a, jint lda){
double *aElems;
int info;
aElems = (*env)-> GetDoubleArrayElements (env, a, NULL);
assert(aElems);
info = LAPACKE_dpotri((int) matrix_layout, (char) uplo, (lapack_int) n, aElems, (lapack_int) lda);
(*env)-> ReleaseDoubleArrayElements (env, a, aElems, 0);
return info;
}
JNIEXPORT jint Java_JAMAJni_CholeskyDecomposition_dpotrs (JNIEnv *env, jclass klass, jint matrix_layout, jchar uplo, jint n, jint nrhs, jdoubleArray a, jint lda, jdoubleArray b, jint ldb){
double *aElems, *bElems;
int info;
aElems = (*env)-> GetDoubleArrayElements (env, a, NULL);
bElems = (*env)-> GetDoubleArrayElements (env, b, NULL);
assert(aElems && bElems);
info = LAPACKE_dpotrs ((int) matrix_layout, (char) uplo, (lapack_int) n, (lapack_int) nrhs, aElems, (lapack_int) lda, bElems, (lapack_int) ldb);
(*env)-> ReleaseDoubleArrayElements (env, a, aElems, JNI_ABORT);
(*env)-> ReleaseDoubleArrayElements (env, b, bElems, 0);
return info;
}
| {
"alphanum_fraction": 0.6555429864,
"avg_line_length": 27.625,
"ext": "c",
"hexsha": "5991416a298f2a82eaf39f493b9a64fd5f901da3",
"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": "2e7cb4e16bacffa965e49d905a87043e31a8a718",
"max_forks_repo_licenses": [
"AAL"
],
"max_forks_repo_name": "dw6ja/JAMAJni",
"max_forks_repo_path": "src/jni_lapacke/c/CholeskyDecomposition.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"AAL"
],
"max_issues_repo_name": "dw6ja/JAMAJni",
"max_issues_repo_path": "src/jni_lapacke/c/CholeskyDecomposition.c",
"max_line_length": 188,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2e7cb4e16bacffa965e49d905a87043e31a8a718",
"max_stars_repo_licenses": [
"AAL"
],
"max_stars_repo_name": "dw6ja/JAMAJni",
"max_stars_repo_path": "src/jni_lapacke/c/CholeskyDecomposition.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 553,
"size": 1768
} |
static char help[] =
"Solves time-dependent heat equation in 2D using TS. Option prefix -ht_.\n"
"Equation is u_t = D_0 laplacian u + f. Domain is (0,1) x (0,1).\n"
"Boundary conditions are non-homogeneous Neumann in x and periodic in y.\n"
"Energy is conserved (for these particular conditions/source) and an extra\n"
"'monitor' is demonstrated. Discretization is by centered finite differences.\n"
"Converts the PDE into a system X_t = G(t,X) (PETSc type 'nonlinear') by\n"
"method of lines. Uses backward Euler time-stepping by default.\n";
#include <petsc.h>
typedef struct {
PetscReal D0; // conductivity
} HeatCtx;
static PetscReal f_source(PetscReal x, PetscReal y) {
return 3.0 * PetscExpReal(-25.0 * (x-0.6) * (x-0.6))
* PetscSinReal(2.0*PETSC_PI*y);
}
static PetscReal gamma_neumann(PetscReal y) {
return PetscSinReal(6.0 * PETSC_PI * y);
}
extern PetscErrorCode Spacings(DMDALocalInfo*, PetscReal*, PetscReal*);
extern PetscErrorCode EnergyMonitor(TS, PetscInt, PetscReal, Vec, void*);
extern PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo*, PetscReal, PetscReal**,
PetscReal**, HeatCtx*);
extern PetscErrorCode FormRHSJacobianLocal(DMDALocalInfo*, PetscReal, PetscReal**,
Mat, Mat, HeatCtx*);
int main(int argc,char **argv) {
PetscErrorCode ierr;
HeatCtx user;
TS ts;
Vec u;
DM da;
DMDALocalInfo info;
PetscReal t0, tf;
PetscBool monitorenergy = PETSC_FALSE;
ierr = PetscInitialize(&argc,&argv,NULL,help); if (ierr) return ierr;
user.D0 = 1.0;
ierr = PetscOptionsBegin(PETSC_COMM_WORLD, "ht_", "options for heat", ""); CHKERRQ(ierr);
ierr = PetscOptionsReal("-D0","constant thermal diffusivity",
"heat.c",user.D0,&user.D0,NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-monitor","also display total heat energy at each step",
"heat.c",monitorenergy,&monitorenergy,NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
//STARTDMDASETUP
ierr = DMDACreate2d(PETSC_COMM_WORLD,
DM_BOUNDARY_NONE, DM_BOUNDARY_PERIODIC, DMDA_STENCIL_STAR,
5,4,PETSC_DECIDE,PETSC_DECIDE, // default to hx=hx=0.25 grid
1,1, // degrees of freedom, stencil width
NULL,NULL,&da); CHKERRQ(ierr);
ierr = DMSetFromOptions(da); CHKERRQ(ierr);
ierr = DMSetUp(da); CHKERRQ(ierr);
ierr = DMCreateGlobalVector(da,&u); CHKERRQ(ierr);
//ENDDMDASETUP
//STARTTSSETUP
ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);
ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);
ierr = TSSetDM(ts,da); CHKERRQ(ierr);
ierr = TSSetApplicationContext(ts,&user); CHKERRQ(ierr);
ierr = DMDATSSetRHSFunctionLocal(da,INSERT_VALUES,
(DMDATSRHSFunctionLocal)FormRHSFunctionLocal,&user); CHKERRQ(ierr);
ierr = DMDATSSetRHSJacobianLocal(da,
(DMDATSRHSJacobianLocal)FormRHSJacobianLocal,&user); CHKERRQ(ierr);
if (monitorenergy) {
ierr = TSMonitorSet(ts,EnergyMonitor,&user,NULL); CHKERRQ(ierr);
}
ierr = TSSetType(ts,TSBDF); CHKERRQ(ierr);
ierr = TSSetTime(ts,0.0); CHKERRQ(ierr);
ierr = TSSetMaxTime(ts,0.1); CHKERRQ(ierr);
ierr = TSSetTimeStep(ts,0.001); CHKERRQ(ierr);
ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);
ierr = TSSetFromOptions(ts);CHKERRQ(ierr);
//ENDTSSETUP
// report on set up
ierr = TSGetTime(ts,&t0); CHKERRQ(ierr);
ierr = TSGetMaxTime(ts,&tf); CHKERRQ(ierr);
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"solving on %d x %d grid for t0=%g to tf=%g ...\n",
info.mx,info.my,t0,tf); CHKERRQ(ierr);
// solve
ierr = VecSet(u,0.0); CHKERRQ(ierr); // initial condition
ierr = TSSolve(ts,u); CHKERRQ(ierr);
VecDestroy(&u); TSDestroy(&ts); DMDestroy(&da);
return PetscFinalize();
}
PetscErrorCode Spacings(DMDALocalInfo *info, PetscReal *hx, PetscReal *hy) {
if (hx) *hx = 1.0 / (PetscReal)(info->mx-1);
if (hy) *hy = 1.0 / (PetscReal)(info->my); // periodic direction
return 0;
}
//STARTMONITOR
PetscErrorCode EnergyMonitor(TS ts, PetscInt step, PetscReal time, Vec u,
void *ctx) {
PetscErrorCode ierr;
HeatCtx *user = (HeatCtx*)ctx;
PetscReal lenergy = 0.0, energy, dt, hx, hy, **au;
PetscInt i,j;
MPI_Comm com;
DM da;
DMDALocalInfo info;
ierr = TSGetDM(ts,&da); CHKERRQ(ierr);
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
ierr = DMDAVecGetArrayRead(da,u,&au); CHKERRQ(ierr);
for (j = info.ys; j < info.ys + info.ym; j++) {
for (i = info.xs; i < info.xs + info.xm; i++) {
if ((i == 0) || (i == info.mx-1))
lenergy += 0.5 * au[j][i];
else
lenergy += au[j][i];
}
}
ierr = DMDAVecRestoreArrayRead(da,u,&au); CHKERRQ(ierr);
ierr = Spacings(&info,&hx,&hy); CHKERRQ(ierr);
lenergy *= hx * hy;
ierr = PetscObjectGetComm((PetscObject)(da),&com); CHKERRQ(ierr);
ierr = MPI_Allreduce(&lenergy,&energy,1,MPIU_REAL,MPIU_SUM,com); CHKERRQ(ierr);
ierr = TSGetTimeStep(ts,&dt); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD," energy = %9.2e nu = %8.4f\n",
energy,user->D0*dt/(hx*hy)); CHKERRQ(ierr);
return 0;
}
//ENDMONITOR
//STARTRHSFUNCTION
PetscErrorCode FormRHSFunctionLocal(DMDALocalInfo *info,
PetscReal t, PetscReal **au,
PetscReal **aG, HeatCtx *user) {
PetscErrorCode ierr;
PetscInt i, j, mx = info->mx;
PetscReal hx, hy, x, y, ul, ur, uxx, uyy;
ierr = Spacings(info,&hx,&hy); CHKERRQ(ierr);
for (j = info->ys; j < info->ys + info->ym; j++) {
y = hy * j;
for (i = info->xs; i < info->xs + info->xm; i++) {
x = hx * i;
// apply Neumann b.c.s
ul = (i == 0) ? au[j][i+1] + 2.0 * hx * gamma_neumann(y)
: au[j][i-1];
ur = (i == mx-1) ? au[j][i-1] : au[j][i+1];
uxx = (ul - 2.0 * au[j][i]+ ur) / (hx*hx);
// DMDA is periodic in y
uyy = (au[j-1][i] - 2.0 * au[j][i]+ au[j+1][i]) / (hy*hy);
aG[j][i] = user->D0 * (uxx + uyy) + f_source(x,y);
}
}
return 0;
}
//ENDRHSFUNCTION
//STARTRHSJACOBIAN
PetscErrorCode FormRHSJacobianLocal(DMDALocalInfo *info,
PetscReal t, PetscReal **au,
Mat J, Mat P, HeatCtx *user) {
PetscErrorCode ierr;
PetscInt i, j, ncols;
const PetscReal D = user->D0;
PetscReal hx, hy, hx2, hy2, v[5];
MatStencil col[5],row;
ierr = Spacings(info,&hx,&hy); CHKERRQ(ierr);
hx2 = hx * hx; hy2 = hy * hy;
for (j = info->ys; j < info->ys+info->ym; j++) {
row.j = j; col[0].j = j;
for (i = info->xs; i < info->xs+info->xm; i++) {
// set up a standard 5-point stencil for the row
row.i = i;
col[0].i = i;
v[0] = - 2.0 * D * (1.0 / hx2 + 1.0 / hy2);
col[1].j = j-1; col[1].i = i; v[1] = D / hy2;
col[2].j = j+1; col[2].i = i; v[2] = D / hy2;
col[3].j = j; col[3].i = i-1; v[3] = D / hx2;
col[4].j = j; col[4].i = i+1; v[4] = D / hx2;
ncols = 5;
// if at the boundary, edit the row back to 4 nonzeros
if (i == 0) {
ncols = 4;
col[3].j = j; col[3].i = i+1; v[3] = 2.0 * D / hx2;
} else if (i == info->mx-1) {
ncols = 4;
col[3].j = j; col[3].i = i-1; v[3] = 2.0 * D / hx2;
}
ierr = MatSetValuesStencil(P,1,&row,ncols,col,v,INSERT_VALUES); CHKERRQ(ierr);
}
}
ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
if (J != P) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
//ENDRHSJACOBIAN
| {
"alphanum_fraction": 0.5781021898,
"avg_line_length": 38.7735849057,
"ext": "c",
"hexsha": "14129d6a45631dd80feeee0364de1c56e2a0574c",
"lang": "C",
"max_forks_count": 46,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z",
"max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "thw1021/p4pdes",
"max_forks_repo_path": "c/ch5/heat.c",
"max_issues_count": 52,
"max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "thw1021/p4pdes",
"max_issues_repo_path": "c/ch5/heat.c",
"max_line_length": 91,
"max_stars_count": 115,
"max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "thw1021/p4pdes",
"max_stars_repo_path": "c/ch5/heat.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z",
"num_tokens": 2642,
"size": 8220
} |
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multiroots.h>
struct rparams
{
double a;
double b;
};
int
rosenbrock_f (const gsl_vector * x, void *params, gsl_vector * f)
{
double a = ((struct rparams *) params)->a;
double b = ((struct rparams *) params)->b;
double x0 = gsl_vector_get (x, 0);
double x1 = gsl_vector_get (x, 1);
double y0 = a * (1 - x0);
double y1 = b * (x1 - x0 * x0);
gsl_vector_set (f, 0, y0);
gsl_vector_set (f, 1, y1);
return GSL_SUCCESS;
}
#ifdef DERIV
int
rosenbrock_df (const gsl_vector * x, void *params, gsl_matrix * df)
{
double a = ((struct rparams *) params)->a;
double b = ((struct rparams *) params)->b;
double x0 = gsl_vector_get (x, 0);
double df00 = -a;
double df01 = 0;
double df10 = -2 * b * x0;
double df11 = b;
gsl_matrix_set (df, 0, 0, df00);
gsl_matrix_set (df, 0, 1, df01);
gsl_matrix_set (df, 1, 0, df10);
gsl_matrix_set (df, 1, 1, df11);
return GSL_SUCCESS;
}
int
rosenbrock_fdf (const gsl_vector * x, void *params,
gsl_vector * f, gsl_matrix * df)
{
rosenbrock_f (x, params, f);
rosenbrock_df (x, params, df);
return GSL_SUCCESS;
}
#endif
#ifdef DERIV
#define SOLVER gsl_multiroot_fdfsolver
#define SOLVER_TYPE gsl_multiroot_fdfsolver_type
#else
#define SOLVER gsl_multiroot_fsolver
#define SOLVER_TYPE gsl_multiroot_fsolver_type
#endif
int
main (void)
{
const SOLVER_TYPE *T;
SOLVER *s;
int status;
size_t i, iter = 0;
const size_t n = 2;
struct rparams p = {1.0, 10.0};
#ifdef DERIV
gsl_multiroot_function_fdf f = {&rosenbrock_f, &rosenbrock_df, &rosenbrock_fdf, n, &p};
#else
gsl_multiroot_function f = {&rosenbrock_f, n, &p};
#endif
double x_init[2] = {-10.0, -5.0};
gsl_vector *x = gsl_vector_alloc (n);
gsl_vector_set (x, 0, x_init[0]);
gsl_vector_set (x, 1, x_init[1]);
#ifdef DERIV
T = gsl_multiroot_fdfsolver_gnewton;
s = gsl_multiroot_fdfsolver_alloc (T, &f, x);
#else
T = gsl_multiroot_fsolver_hybrids;
s = gsl_multiroot_fsolver_alloc (T, &f, x);
#endif
print_state (iter, s);
do
{
iter++;
#ifdef DERIV
status = gsl_multiroot_fdfsolver_iterate (s);
#else
status = gsl_multiroot_fsolver_iterate (s);
#endif
print_state (iter, s);
if (status)
break;
status = gsl_multiroot_test_residual (s->f, 0.0000001);
}
while (status == GSL_CONTINUE && iter < 1000);
printf ("status = %s\n", gsl_strerror (status));
#ifdef DERIV
gsl_multiroot_fdfsolver_free (s);
#else
gsl_multiroot_fsolver_free (s);
#endif
gsl_vector_free (x);
}
int
print_state (size_t iter, SOLVER * s)
{
printf ("iter = %3u x = % 15.8f % 15.8f f(x) = % .3e % .3e\n",
iter,
gsl_vector_get (s->x, 0), gsl_vector_get (s->x, 1),
gsl_vector_get (s->f, 0), gsl_vector_get (s->f, 1));
}
| {
"alphanum_fraction": 0.6459930314,
"avg_line_length": 20.0699300699,
"ext": "c",
"hexsha": "0f8c0500fb4377fe00398fa2ccdbb0f6b0c6abdc",
"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/multiroots/demo.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/multiroots/demo.c",
"max_line_length": 89,
"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/multiroots/demo.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": 984,
"size": 2870
} |
static char help[] =
"Simple ODE system to test implicit and IMEX methods when *both* RHSFunction()\n"
"and IFunction() are supplied. Jacobians are supplied as well. The problem\n"
"has form\n"
" F(t,u,dudt) = G(t,u)\n"
"where u(t) = (x(t),y(t)) and dF/d(dudt) is invertible, so the problem is a\n"
"2D ODE IVP. Functions F (IFunction) and G (RHSFunction) are actually linear,\n"
"but the ProblemType is set to TS_NONLINEAR type. By default the system is\n"
" x' + y' + x + 2y = x + 8y\n"
" y' + 3x + 4y = 4x + 4y\n"
"The implicit methods like BEULER, THETA, CN, BDF should be able to handle\n"
"this system. Apparently ROSW can also handle it. However, ARKIMEX and EIMEX\n"
"require dF/d(dudt) to be the identity. (But consider option\n"
"-ts_arkimex_fully_implicit.) If option -identity_in_F is given then an\n"
"equivalent system is formed,\n"
" x' + x + 2y = 8y\n"
" y' + 3x + 4y = 4x + 4y\n"
"Both of these systems are trivial transformations of the system\n"
"x'=6y-x, y'=x. With the initial conditions chosen below, x(0)=1 and y(0)=3,\n"
"the exact solution to the above systems is x(t) = -3 e^{-3t} + 4 e^{2t},\n"
"y(t) = e^{-3t} + 2 e^{2t}, and we compute the final numerical error\n"
"accordingly. Default type is BDF. See the manual pages for the various\n"
"methods (e.g. TSROSW, TSARKIMEX, TSEIMEX, ...) for further information.\n\n";
#include <petsc.h>
typedef struct {
PetscBool identity_in_F;
} Ctx;
extern PetscErrorCode FormIFunction(TS,PetscReal,Vec,Vec,Vec F,void*);
extern PetscErrorCode FormIJacobian(TS,PetscReal,Vec,Vec,PetscReal,Mat,Mat,void*);
extern PetscErrorCode FormRHSFunction(TS,PetscReal,Vec,Vec,void*);
extern PetscErrorCode FormRHSJacobian(TS,PetscReal,Vec,Mat,Mat,void*);
int main(int argc,char **argv)
{
PetscErrorCode ierr;
TS ts;
Vec u, uexact;
Mat JF,JG;
Ctx user;
PetscReal tf,xf,yf,errnorm;
PetscInt steps;
PetscInitialize(&argc,&argv,(char*)0,help);
user.identity_in_F = PETSC_FALSE;
ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"",
"Simple F(t,u,u')=G(t,u) ODE system.","TS"); CHKERRQ(ierr);
ierr = PetscOptionsBool("-identity_in_F","set up system so the dF/d(dudt) = I",
"ex54.c",user.identity_in_F,&(user.identity_in_F),NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
ierr = VecCreate(PETSC_COMM_WORLD,&u); CHKERRQ(ierr);
ierr = VecSetSizes(u,PETSC_DECIDE,2); CHKERRQ(ierr);
ierr = VecSetFromOptions(u); CHKERRQ(ierr);
ierr = MatCreate(PETSC_COMM_WORLD,&JF); CHKERRQ(ierr);
ierr = MatSetSizes(JF,PETSC_DECIDE,PETSC_DECIDE,2,2); CHKERRQ(ierr);
ierr = MatSetFromOptions(JF); CHKERRQ(ierr);
ierr = MatSetUp(JF); CHKERRQ(ierr);
ierr = MatDuplicate(JF,MAT_DO_NOT_COPY_VALUES,&JG); CHKERRQ(ierr);
ierr = TSCreate(PETSC_COMM_WORLD,&ts); CHKERRQ(ierr);
ierr = TSSetApplicationContext(ts,&user); CHKERRQ(ierr);
ierr = TSSetIFunction(ts,NULL,FormIFunction,&user); CHKERRQ(ierr);
ierr = TSSetIJacobian(ts,JF,JF,FormIJacobian,&user); CHKERRQ(ierr);
ierr = TSSetRHSFunction(ts,NULL,FormRHSFunction,&user); CHKERRQ(ierr);
ierr = TSSetRHSJacobian(ts,JG,JG,FormRHSJacobian,&user); CHKERRQ(ierr);
ierr = TSSetProblemType(ts,TS_NONLINEAR); CHKERRQ(ierr);
// helps with ARKIMEX if you also set -ts_arkimex_fully_implicit:
// ierr = TSSetEquationType(ts,TS_EQ_IMPLICIT); CHKERRQ(ierr);
ierr = TSSetType(ts,TSBDF); CHKERRQ(ierr);
ierr = TSSetTime(ts,0.0); CHKERRQ(ierr);
ierr = TSSetMaxTime(ts,1.0); CHKERRQ(ierr);
ierr = TSSetTimeStep(ts,0.01); CHKERRQ(ierr);
ierr = TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); CHKERRQ(ierr);
ierr = TSSetFromOptions(ts);CHKERRQ(ierr);
ierr = VecSetValue(u,0,1.0,INSERT_VALUES); CHKERRQ(ierr);
ierr = VecSetValue(u,1,3.0,INSERT_VALUES); CHKERRQ(ierr);
ierr = VecAssemblyBegin(u); CHKERRQ(ierr);
ierr = VecAssemblyEnd(u); CHKERRQ(ierr);
ierr = TSSolve(ts,u); CHKERRQ(ierr);
ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr);
ierr = TSGetTime(ts,&tf); CHKERRQ(ierr);
xf = -3.0 * PetscExpReal(-3.0*tf) + 4.0 * PetscExpReal(2.0*tf);
yf = PetscExpReal(-3.0*tf) + 2.0 * PetscExpReal(2.0*tf);
//ierr = PetscPrintf(PETSC_COMM_WORLD,
// "xf = %.6f, yf = %.6f\n",xf,yf); CHKERRQ(ierr);
ierr = VecDuplicate(u,&uexact); CHKERRQ(ierr);
ierr = VecSetValue(uexact,0,xf,INSERT_VALUES); CHKERRQ(ierr);
ierr = VecSetValue(uexact,1,yf,INSERT_VALUES); CHKERRQ(ierr);
ierr = VecAssemblyBegin(uexact); CHKERRQ(ierr);
ierr = VecAssemblyEnd(uexact); CHKERRQ(ierr);
ierr = VecAXPY(u,-1.0,uexact); CHKERRQ(ierr); // u <- u + (-1.0) uexact
ierr = VecNorm(u,NORM_2,&errnorm); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"error norm at tf = %.6f from %d steps: |u-u_exact| = %.5e\n",
tf,steps,errnorm); CHKERRQ(ierr);
VecDestroy(&u); VecDestroy(&uexact);
MatDestroy(&JF); MatDestroy(&JG);
TSDestroy(&ts);
return PetscFinalize();
}
PetscErrorCode FormIFunction(TS ts, PetscReal t, Vec u, Vec dudt,
Vec F, void *user) {
PetscErrorCode ierr;
const PetscReal *au, *adudt;
PetscReal *aF;
PetscBool flag = ((Ctx*)user)->identity_in_F;
ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);
ierr = VecGetArrayRead(dudt,&adudt); CHKERRQ(ierr);
ierr = VecGetArray(F,&aF);
if (flag) {
aF[0] = adudt[0] + au[0] + 2.0 * au[1];
aF[1] = adudt[1] + 3.0 * au[0] + 4.0 * au[1];
} else {
aF[0] = adudt[0] + adudt[1] + au[0] + 2.0 * au[1];
aF[1] = adudt[1] + 3.0 * au[0] + 4.0 * au[1];
}
ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr);
ierr = VecRestoreArrayRead(dudt,&adudt); CHKERRQ(ierr);
ierr = VecRestoreArray(F,&aF); CHKERRQ(ierr);
return 0;
}
// computes J = dF/du + a dF/d(dudt)
PetscErrorCode FormIJacobian(TS ts, PetscReal t, Vec u, Vec dudt,
PetscReal a, Mat J, Mat P, void *user) {
PetscErrorCode ierr;
PetscInt row[2] = {0, 1}, col[2] = {0, 1};
PetscReal v[4];
PetscBool flag = ((Ctx*)user)->identity_in_F;
if (flag) {
v[0] = a + 1.0; v[1] = 2.0;
v[2] = 3.0; v[3] = a + 4.0;
} else {
v[0] = a + 1.0; v[1] = a + 2.0;
v[2] = 3.0; v[3] = a + 4.0;
}
ierr = MatSetValues(P,2,row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);
ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
if (J != P) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
PetscErrorCode FormRHSFunction(TS ts, PetscReal t, Vec u,
Vec G, void *user) {
PetscErrorCode ierr;
const PetscReal *au;
PetscReal *aG;
PetscBool flag = ((Ctx*)user)->identity_in_F;
ierr = VecGetArrayRead(u,&au); CHKERRQ(ierr);
ierr = VecGetArray(G,&aG); CHKERRQ(ierr);
if (flag) {
aG[0] = 8.0 * au[1];
aG[1] = 4.0 * au[0] + 4.0 * au[1];
} else {
aG[0] = au[0] + 8.0 * au[1];
aG[1] = 4.0 * au[0] + 4.0 * au[1];
}
ierr = VecRestoreArrayRead(u,&au); CHKERRQ(ierr);
ierr = VecRestoreArray(G,&aG); CHKERRQ(ierr);
return 0;
}
PetscErrorCode FormRHSJacobian(TS ts, PetscReal t, Vec u, Mat J, Mat P,
void *user) {
PetscErrorCode ierr;
PetscInt row[2] = {0, 1}, col[2] = {0, 1};
PetscReal v[4];
PetscBool flag = ((Ctx*)user)->identity_in_F;
if (flag) {
v[0] = 0.0; v[1] = 8.0;
v[2] = 4.0; v[3] = 4.0;
} else {
v[0] = 1.0; v[1] = 8.0;
v[2] = 4.0; v[3] = 4.0;
}
ierr = MatSetValues(P,2,row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);
ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
if (J != P) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
| {
"alphanum_fraction": 0.6225908758,
"avg_line_length": 39.6038647343,
"ext": "c",
"hexsha": "008d1953f4fed75ebcf691d67d764f2a2b2a9924",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bueler/p4pdes-next",
"max_forks_repo_path": "c/fix-arkimex/ex54.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "bueler/p4pdes-next",
"max_issues_repo_path": "c/fix-arkimex/ex54.c",
"max_line_length": 82,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "eb5c6113b0d52e3cb98f24dbb30203e22f7a7766",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bueler/p4pdes-next",
"max_stars_repo_path": "c/fix-arkimex/ex54.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2813,
"size": 8198
} |
#include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cblas.h>
#include "tests.h"
void
test_spr (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int uplo = 121;
int N = 2;
float alpha = -0.3f;
float Ap[] = { -0.764f, -0.257f, -0.064f };
float X[] = { 0.455f, -0.285f };
int incX = -1;
float Ap_expected[] = { -0.788367f, -0.218097f, -0.126108f };
cblas_sspr(order, uplo, N, alpha, X, incX, Ap);
{
int i;
for (i = 0; i < 3; i++) {
gsl_test_rel(Ap[i], Ap_expected[i], flteps, "sspr(case 1426)");
}
};
};
{
int order = 101;
int uplo = 122;
int N = 2;
float alpha = -0.3f;
float Ap[] = { -0.764f, -0.257f, -0.064f };
float X[] = { 0.455f, -0.285f };
int incX = -1;
float Ap_expected[] = { -0.788367f, -0.218097f, -0.126108f };
cblas_sspr(order, uplo, N, alpha, X, incX, Ap);
{
int i;
for (i = 0; i < 3; i++) {
gsl_test_rel(Ap[i], Ap_expected[i], flteps, "sspr(case 1427)");
}
};
};
{
int order = 102;
int uplo = 121;
int N = 2;
float alpha = -0.3f;
float Ap[] = { -0.764f, -0.257f, -0.064f };
float X[] = { 0.455f, -0.285f };
int incX = -1;
float Ap_expected[] = { -0.788367f, -0.218097f, -0.126108f };
cblas_sspr(order, uplo, N, alpha, X, incX, Ap);
{
int i;
for (i = 0; i < 3; i++) {
gsl_test_rel(Ap[i], Ap_expected[i], flteps, "sspr(case 1428)");
}
};
};
{
int order = 102;
int uplo = 122;
int N = 2;
float alpha = -0.3f;
float Ap[] = { -0.764f, -0.257f, -0.064f };
float X[] = { 0.455f, -0.285f };
int incX = -1;
float Ap_expected[] = { -0.788367f, -0.218097f, -0.126108f };
cblas_sspr(order, uplo, N, alpha, X, incX, Ap);
{
int i;
for (i = 0; i < 3; i++) {
gsl_test_rel(Ap[i], Ap_expected[i], flteps, "sspr(case 1429)");
}
};
};
{
int order = 101;
int uplo = 121;
int N = 2;
double alpha = -1;
double Ap[] = { 0.819, 0.175, -0.809 };
double X[] = { -0.645, -0.222 };
int incX = -1;
double Ap_expected[] = { 0.769716, 0.03181, -1.225025 };
cblas_dspr(order, uplo, N, alpha, X, incX, Ap);
{
int i;
for (i = 0; i < 3; i++) {
gsl_test_rel(Ap[i], Ap_expected[i], dbleps, "dspr(case 1430)");
}
};
};
{
int order = 101;
int uplo = 122;
int N = 2;
double alpha = -1;
double Ap[] = { 0.819, 0.175, -0.809 };
double X[] = { -0.645, -0.222 };
int incX = -1;
double Ap_expected[] = { 0.769716, 0.03181, -1.225025 };
cblas_dspr(order, uplo, N, alpha, X, incX, Ap);
{
int i;
for (i = 0; i < 3; i++) {
gsl_test_rel(Ap[i], Ap_expected[i], dbleps, "dspr(case 1431)");
}
};
};
{
int order = 102;
int uplo = 121;
int N = 2;
double alpha = -1;
double Ap[] = { 0.819, 0.175, -0.809 };
double X[] = { -0.645, -0.222 };
int incX = -1;
double Ap_expected[] = { 0.769716, 0.03181, -1.225025 };
cblas_dspr(order, uplo, N, alpha, X, incX, Ap);
{
int i;
for (i = 0; i < 3; i++) {
gsl_test_rel(Ap[i], Ap_expected[i], dbleps, "dspr(case 1432)");
}
};
};
{
int order = 102;
int uplo = 122;
int N = 2;
double alpha = -1;
double Ap[] = { 0.819, 0.175, -0.809 };
double X[] = { -0.645, -0.222 };
int incX = -1;
double Ap_expected[] = { 0.769716, 0.03181, -1.225025 };
cblas_dspr(order, uplo, N, alpha, X, incX, Ap);
{
int i;
for (i = 0; i < 3; i++) {
gsl_test_rel(Ap[i], Ap_expected[i], dbleps, "dspr(case 1433)");
}
};
};
}
| {
"alphanum_fraction": 0.4997261774,
"avg_line_length": 22.2682926829,
"ext": "c",
"hexsha": "36891bdb2f1c6425989e329ad8adecf8facf74c0",
"lang": "C",
"max_forks_count": 224,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T00:57:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-12T21:17:03.000Z",
"max_forks_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "utdsimmons/ohpc",
"max_forks_repo_path": "tests/libs/gsl/tests/cblas/test_spr.c",
"max_issues_count": 1096,
"max_issues_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T21:48:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-11-12T09:08:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "utdsimmons/ohpc",
"max_issues_repo_path": "tests/libs/gsl/tests/cblas/test_spr.c",
"max_line_length": 70,
"max_stars_count": 692,
"max_stars_repo_head_hexsha": "70dc728926a835ba049ddd3f4627ef08db7c95a0",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "utdsimmons/ohpc",
"max_stars_repo_path": "tests/libs/gsl/tests/cblas/test_spr.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T03:45:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-11-12T13:56:43.000Z",
"num_tokens": 1512,
"size": 3652
} |
/*
FRACTAL - A program growing fractals to benchmark parallelization and drawing
libraries.
Copyright 2009-2021, Javier Burguete Tolosa.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Javier Burguete Tolosa ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL Javier Burguete Tolosa OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file main.c
* \brief Source file to define the main function.
* \author Javier Burguete Tolosa.
* \copyright Copyright 2009-2021, Javier Burguete Tolosa.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <unistd.h>
#include <libintl.h>
#include <gsl/gsl_rng.h>
#include <glib.h>
#include <png.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include <gtk/gtk.h>
#include <GL/glew.h>
#if HAVE_FREEGLUT
#include <GL/freeglut.h>
#elif HAVE_SDL
#include <SDL.h>
#elif HAVE_GLFW
#include <GLFW/glfw3.h>
#endif
#include "config.h"
#include "fractal.h"
#include "image.h"
#include "text.h"
#include "graphic.h"
#include "draw.h"
#include "simulator.h"
#if HAVE_SDL
SDL_Window *window; ///< SDL window.
#elif HAVE_GLFW
GLFWwindow *window; ///< GLFW window.
#endif
/**
* Function to do one main loop iteration.
*/
void
main_iteration ()
{
GMainContext *context;
context = g_main_context_default ();
while (g_main_context_pending (context))
g_main_context_iteration (context, 0);
}
/**
* Function to do the main loop.
*/
void
main_loop ()
{
#if HAVE_FREEGLUT
// Passing the GTK+ signals to the FreeGLUT main loop
glutIdleFunc (main_iteration);
// Setting our draw resize function as the FreeGLUT reshape function
glutReshapeFunc (draw_resize);
// Setting our draw function as the FreeGLUT display function
glutDisplayFunc (draw);
// FreeGLUT main loop
glutMainLoop ();
#elif HAVE_SDL
SDL_Event event[1];
while (1)
{
main_iteration ();
while (SDL_PollEvent (event))
{
if (event->type == SDL_QUIT)
return;
if (event->type == SDL_WINDOWEVENT
&& event->window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
draw_resize (event->window.data1, event->window.data2);
}
draw ();
}
#elif HAVE_GLFW
while (!glfwWindowShouldClose (window))
{
main_iteration ();
glfwPollEvents ();
draw ();
}
#else
g_main_loop_run (dialog_simulator->loop);
g_main_loop_unref (dialog_simulator->loop);
#endif
}
/**
* Main function.
*
* \return 0 on success.
*/
int
main (int argn, ///< Arguments number.
char **argc) ///< Array of arguments.
{
if (argn > 2)
{
printf ("Bad arguments number\n");
return 1;
}
// PARALELLIZING INIT
nthreads = threads_number ();
// END
// Initing locales
#if DEBUG
printf ("Initing locales\n");
fflush (stdout);
#endif
bindtextdomain ("fractal", "./po");
bind_textdomain_codeset ("fractal", "UTF-8");
textdomain ("fractal");
// Initing graphic window
#if HAVE_FREEGLUT
#if DEBUG
printf ("Initing FreeGLUT window\n");
fflush (stdout);
#endif
glutInit (&argn, argc);
glutInitDisplayMode (GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowSize (window_width, window_height);
glutCreateWindow ("fractal");
#elif HAVE_SDL
#if DEBUG
printf ("Initing SDL window\n");
fflush (stdout);
#endif
SDL_Init (SDL_INIT_VIDEO);
window = SDL_CreateWindow ("fractal",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
window_width, window_height,
SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL);
if (!window)
{
printf ("ERROR! unable to create the window: %s\n", SDL_GetError ());
return 1;
}
SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2);
if (!SDL_GL_CreateContext (window))
{
printf ("ERROR! SDL_GL_CreateContext: %s\n", SDL_GetError ());
return 1;
}
#elif HAVE_GLFW
#if DEBUG
printf ("Initing GLFW window\n");
fflush (stdout);
#endif
if (!glfwInit ())
{
printf ("ERROR! unable to init GLFW\n");
return 1;
}
window
= glfwCreateWindow (window_width, window_height, "fractal", NULL, NULL);
if (!window)
{
printf ("ERROR! unable to open the window\n");
glfwTerminate ();
return 1;
}
glfwMakeContextCurrent (window);
#endif
// Initing GTK+
#if DEBUG
printf ("Initing GTK+\n");
fflush (stdout);
#endif
#if !GTK4
gtk_init (&argn, &argc);
#else
gtk_init ();
#endif
// Creating the main GTK+ window
#if DEBUG
printf ("Creating simulator dialog\n");
fflush (stdout);
#endif
dialog_simulator_create ();
#if !HAVE_GTKGLAREA
// Initing drawing data
#if DEBUG
printf ("Initing drawing data\n");
fflush (stdout);
#endif
if (!graphic_init (graphic, "logo.png"))
return 1;
#endif
// Opening input file
if (argn == 2 && !fractal_input (argc[1]))
return 1;
// Updating view
if (argn == 2)
fractal ();
dialog_simulator_update ();
// Main loop
#if DEBUG
printf ("Main loop\n");
fflush (stdout);
#endif
main_loop ();
// Freeing memory
#if HAVE_GLFW
glfwDestroyWindow (window);
glfwTerminate ();
#endif
graphic_destroy (graphic);
return 0;
}
| {
"alphanum_fraction": 0.6777108434,
"avg_line_length": 23.0218978102,
"ext": "c",
"hexsha": "0bd54742e6280c7d7799d360aa5ced7bf6310349",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "jburguete/fractal",
"max_forks_repo_path": "3.4.15/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "jburguete/fractal",
"max_issues_repo_path": "3.4.15/main.c",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "95d711dcb7b385556fb77794bc01737b21e99774",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "jburguete/fractal",
"max_stars_repo_path": "3.4.15/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1571,
"size": 6308
} |
//This takes univariate X, windows X with W, applies the 1D FFT to each frame,
//takes power, transforms with T mat to B cfs, and then compresses power with log.
//Then the cepstral coeffs (CCs) are obtained by the 1D DCT-II of each frame,
//followed by a lifter (weighting in the cepstral domain).
//This is equivalent to : spectrogram -> get_ccs.
//which is equivalent to: spectrogram -> dct -> lifter.
//which is equivalent to: stft -> apply_spectrogram_T_mat -> pow_compress -> dct -> lifter.
//which is equivalent to: window_univar -> fft_squared -> apply_spectrogram_T_mat -> pow_compress -> dct -> lifter.
//which is equivalent to: window_univar -> fft_hc -> hc_square -> apply_spectrogram_T_mat -> pow_compress -> dct -> lifter.
//which is equivalent to: frame_univar -> apply_win -> fft_hc -> hc_square -> apply_spectrogram_T_mat -> pow_compress -> dct -> lifter.
#include <stdio.h>
#include <float.h>
#include <math.h>
#include <cblas.h>
#include <fftw3.h>
#ifndef M_PIf
#define M_PIf 3.141592653589793238462643383279502884f
#endif
#ifndef M_PI
#define M_PI 3.141592653589793238462643383279502884
#endif
#ifdef __cplusplus
namespace ov {
extern "C" {
#endif
int mfccs_s (float *Y, const int iscolmajor, const int R, const int C, const float *X, const int N, const float *W, const int L, const float *H, const int B, const int dim, const int c0, const float stp, const int mn0, const int nfft, const float preg, const int ndct, const float Q, const int K);
int mfccs_d (double *Y, const int iscolmajor, const int R, const int C, const double *X, const int N, const double *W, const int L, const double *H, const int B, const int dim, const int c0, const double stp, const int mn0, const int nfft, const double preg, const int ndct, const double Q, const int K);
//int mfccs_s (float *Y, sigi Yi, const float *X, const sigi Xi, const float *W, const sigi Wi, const float *H, const sigi H, const int dim, const int c0, const float stp, const float preg, const int ndct, const float Q)
int mfccs_s (float *Y, const int iscolmajor, const int R, const int C, const float *X, const int N, const float *W, const int L, const float *H, const int B, const int dim, const int c0, const float stp, const int mn0, const int nfft, const float preg, const int ndct, const float Q, const int K)
{
const float z = 0.0f, o = 1.0f;
const float Q2 = 0.5f*Q, PQ = M_PIf/Q;
//const int normalize_H = 0;
const int F = nfft/2 + 1; //num non-negative FFT freqs
const int F2 = F-1+nfft%2; //for square loop below
const int Lpre = L/2; //nsamps before center samp
int ss = c0 - Lpre; //start samp of current frame
int r, c, f, b, k;
float *X1, *Y1, *X1d, *Y1d; //, *freqs, *cfs, *H;
fftwf_plan fft_plan, dct_plan;
//struct timespec tic, toc;
//Checks
if (N<1) { fprintf(stderr,"error in mfccs_s: N (length X) must be positive\n"); return 1; }
if (R<1) { fprintf(stderr,"error in mfccs_s: R (nrows Y) must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in mfccs_s: C (ncols Y) must be positive\n"); return 1; }
if (L<1) { fprintf(stderr,"error in mfccs_s: L (winlength) must be positive\n"); return 1; }
if (c0<0) { fprintf(stderr,"error in mfccs_s: c0 (center samp of 1st frame) must be nonnegative\n"); return 1; }
if (c0>N-1) { fprintf(stderr,"error in mfccs_s: c0 (center samp of 1st frame) must be < N (length X)\n"); return 1; }
if (L>=N) { fprintf(stderr,"error in mfccs_s: L (winlength) must be < N (length X)\n"); return 1; }
if (stp<=0.0f) { fprintf(stderr,"error in mfccs_s: stp (step size) must be positive\n"); return 1; }
if (nfft<L) { fprintf(stderr,"error in mfccs_s: nfft must be >= L (winlength)\n"); return 1; }
if (preg!=preg || preg<0.0f) { fprintf(stderr,"error in mfccs_s: preg must be nonnegative\n"); return 1; }
if (Q<0.0f) { fprintf(stderr,"error in mfccs_s: Q must be positive (or 0 to skip lifter)\n"); return 1; }
if (K<1) { fprintf(stderr,"error in mfccs_s: K must be positive\n"); return 1; }
if (K>ndct) { fprintf(stderr,"error in mfccs_s: K must be <= ndct>\n"); return 1; }
//Initialize fftwf for FFT
X1 = fftwf_alloc_real((size_t)nfft);
Y1 = fftwf_alloc_real((size_t)nfft);
fft_plan = fftwf_plan_r2r_1d(nfft,X1,Y1,FFTW_R2HC,FFTW_ESTIMATE);
if (!fft_plan) { fprintf(stderr,"error in mfccs_s: problem creating fftw plan for fft\n"); return 1; }
cblas_scopy(nfft,&z,0,&X1[0],1); //zero-pad
//Initialize fftwf for DCT
X1d = fftwf_alloc_real((size_t)ndct);
Y1d = fftwf_alloc_real((size_t)ndct);
dct_plan = fftwf_plan_r2r_1d(ndct,X1d,Y1d,FFTW_REDFT10,FFTW_ESTIMATE);
if (!dct_plan) { fprintf(stderr,"error in mfccs_s: problem creating fftw plan for dct\n"); return 1; }
cblas_scopy(ndct,&z,0,&X1d[0],1); //zero-pad
//Get frequencies and H
//if (get_stft_freqs_s(&freqs[0],F,fs,nfft)) { fprintf(stderr,"error in mfccs_s: problem getting STFT freqs\n"); return 1; }
//if (get_cfs_T_s(&cfs[0],B,fs,'mel')) { fprintf(stderr,"error in mfccs_s: problem getting Mel cfs\n"); return 1; }
//if (get_spectrogram_T_mat_s(&H[0],iscolmajor,&freqs[0],F,&cfs[0],B,normalize_H))
//{ fprintf(stderr,"error in mfccs_s: problem getting STFT freq -> Mel cfs transform matrix\n"); return 1; }
//clock_gettime(CLOCK_REALTIME,&tic);
//Initialize lifter
//float *lift; int n;
//if (!(lift=(float *)malloc((size_t)K*sizeof(float)))) { fprintf(stderr,"error in get_ccs_s: problem with malloc for lifter. "); perror("malloc"); return 1; }
//for (k=0; k<K; k++) { lift[k] = fmaf(Q2,sinf(k*PQ),1.0f); }
if (dim==0)
{
if (iscolmajor)
{
for (c=0; c<C; c++)
{
//Window
ss = (int)(roundf(c*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_scopy(-ss,&z,0,&X1[0],1);
cblas_ssbmv(CblasColMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_ssbmv(CblasColMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
}
else if (ss<N)
{
cblas_ssbmv(CblasColMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_scopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftwf_execute(fft_plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_sgemv(CblasColMajor,CblasNoTrans,B,F,1.0f,&H[0],B,&Y1[0],1,0.0f,&X1d[0],1);
//Power compress
for (b=0; b<B; b++) { X1d[b] = logf(X1d[b]+preg); }
//DCT
fftwf_execute(dct_plan);
cblas_scopy(K,&Y1d[0],1,&Y[c*K],1);
//cblas_ssbmv(CblasColMajor,CblasUpper,K,0,1.0f,&lift[0],1,&Y1d[0],1,0.0f,&Y[c*K],1);
//for (k=0; k<K; k++) { Y[k+c*K] = lift[k]*Y1d[k]; }
}
//Lifter
if (Q>FLT_EPSILON) { for (k=0; k<K; k++) { cblas_sscal(C,fmaf(Q2,sinf(PQ*k),1.0f),&Y[k],K); } }
}
else
{
for (c=0; c<C; c++)
{
//Window
ss = (int)(roundf(c*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_scopy(-ss,&z,0,&X1[0],1);
cblas_ssbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_ssbmv(CblasRowMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
}
else if (ss<N)
{
cblas_ssbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_scopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftwf_execute(fft_plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_sgemv(CblasRowMajor,CblasNoTrans,B,F,1.0f,&H[0],F,&Y1[0],1,0.0f,&X1d[0],1);
//Power compress
for (b=0; b<B; b++) { X1d[b] = logf(X1d[b]+preg); }
//DCT
fftwf_execute(dct_plan);
cblas_scopy(K,&Y1d[0],1,&Y[c],C);
}
//Lifter
if (Q>FLT_EPSILON) { for (k=0; k<K; k++) { cblas_sscal(C,fmaf(Q2,sinf(PQ*k),1.0f),&Y[k*C],1); } }
}
}
else if (dim==1)
{
if (iscolmajor)
{
for (r=0; r<R; r++)
{
//Window
ss = (int)(roundf(r*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_scopy(-ss,&z,0,&X1[0],1);
cblas_ssbmv(CblasColMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_ssbmv(CblasColMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
}
else if (ss<N)
{
cblas_ssbmv(CblasColMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_scopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftwf_execute(fft_plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_sgemv(CblasColMajor,CblasNoTrans,B,F,1.0f,&H[0],B,&Y1[0],1,0.0f,&X1d[0],1);
//Power compress
for (b=0; b<B; b++) { X1d[b] = logf(X1d[b]+preg); }
//DCT
fftwf_execute(dct_plan);
cblas_scopy(K,&Y1d[0],1,&Y[r],R);
}
//Lifter
if (Q>FLT_EPSILON) { for (k=0; k<K; k++) { cblas_sscal(R,fmaf(Q2,sinf(PQ*k),1.0f),&Y[k*R],1); } }
}
else
{
for (r=0; r<R; r++)
{
//Window
ss = (int)(roundf(r*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_scopy(-ss,&z,0,&X1[0],1);
cblas_ssbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0f,&W[-ss],1,&X[0],1,0.0f,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_ssbmv(CblasRowMajor,CblasUpper,L,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
}
else if (ss<N)
{
cblas_ssbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0f,&W[0],1,&X[ss],1,0.0f,&X1[0],1);
cblas_scopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_scopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_saxpy(L,-cblas_sdot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftwf_execute(fft_plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_sgemv(CblasRowMajor,CblasNoTrans,B,F,1.0f,&H[0],F,&Y1[0],1,0.0f,&X1d[0],1);
//Power compress
for (b=0; b<B; b++) { X1d[b] = logf(X1d[b]+preg); }
//DCT
fftwf_execute(dct_plan);
cblas_scopy(K,&Y1d[0],1,&Y[r*K],1);
}
//Lifter
if (Q>FLT_EPSILON) { for (k=0; k<K; k++) { cblas_sscal(R,fmaf(Q2,sinf(PQ*k),1.0f),&Y[k],K); } }
}
}
else
{
fprintf(stderr,"error in mfccs_s: dim must be 0 or 1.\n"); return 1;
}
//clock_gettime(CLOCK_REALTIME,&toc); fprintf(stderr,"elapsed time = %f ms\n",(toc.tv_sec-tic.tv_sec)*1e3+(toc.tv_nsec-tic.tv_nsec)/1e6);
//Exit
fftwf_destroy_plan(fft_plan); fftwf_free(X1); fftwf_free(Y1);
fftwf_destroy_plan(dct_plan); fftwf_free(X1d); fftwf_free(Y1d);
return 0;
}
int mfccs_d (double *Y, const int iscolmajor, const int R, const int C, const double *X, const int N, const double *W, const int L, const double *H, const int B, const int dim, const int c0, const double stp, const int mn0, const int nfft, const double preg, const int ndct, const double Q, const int K)
{
const double z = 0.0, o = 1.0;
const double Q2 = 0.5*Q, PQ = M_PI/Q;
const int F = nfft/2 + 1; //num non-negative FFT freqs
const int F2 = F-1+nfft%2; //for square loop below
const int Lpre = L/2; //nsamps before center samp
int ss = c0 - Lpre; //start samp of current frame
int r, c, f, b, k;
double *X1, *Y1, *X1d, *Y1d;
fftw_plan fft_plan, dct_plan;
//Checks
if (N<1) { fprintf(stderr,"error in mfccs_d: N (length X) must be positive\n"); return 1; }
if (R<1) { fprintf(stderr,"error in mfccs_d: R (nrows Y) must be positive\n"); return 1; }
if (C<1) { fprintf(stderr,"error in mfccs_d: C (ncols Y) must be positive\n"); return 1; }
if (L<1) { fprintf(stderr,"error in mfccs_d: L (winlength) must be positive\n"); return 1; }
if (c0<0) { fprintf(stderr,"error in mfccs_d: c0 (center samp of 1st frame) must be nonnegative\n"); return 1; }
if (c0>N-1) { fprintf(stderr,"error in mfccs_d: c0 (center samp of 1st frame) must be < N (length X)\n"); return 1; }
if (L>=N) { fprintf(stderr,"error in mfccs_d: L (winlength) must be < N (length X)\n"); return 1; }
if (stp<=0.0) { fprintf(stderr,"error in mfccs_d: stp (step size) must be positive\n"); return 1; }
if (nfft<L) { fprintf(stderr,"error in mfccs_d: nfft must be >= L (winlength)\n"); return 1; }
if (preg!=preg || preg<0.0) { fprintf(stderr,"error in mfccs_d: preg must be nonnegative\n"); return 1; }
if (Q<0.0) { fprintf(stderr,"error in mfccs_d: Q must be positive (or 0 to skip lifter)\n"); return 1; }
if (K<1) { fprintf(stderr,"error in mfccs_d: K must be positive\n"); return 1; }
if (K>ndct) { fprintf(stderr,"error in mfccs_d: K must be <= ndct>\n"); return 1; }
//Initialize fftw for FFT
X1 = fftw_alloc_real((size_t)nfft);
Y1 = fftw_alloc_real((size_t)nfft);
fft_plan = fftw_plan_r2r_1d(nfft,X1,Y1,FFTW_R2HC,FFTW_ESTIMATE);
if (!fft_plan) { fprintf(stderr,"error in mfccs_d: problem creating fftw plan for fft\n"); return 1; }
cblas_dcopy(nfft,&z,0,&X1[0],1); //zero-pad
//Initialize fftw for DCT
X1d = fftw_alloc_real((size_t)ndct);
Y1d = fftw_alloc_real((size_t)ndct);
dct_plan = fftw_plan_r2r_1d(ndct,X1d,Y1d,FFTW_REDFT10,FFTW_ESTIMATE);
if (!dct_plan) { fprintf(stderr,"error in mfccs_d: problem creating fftw plan for dct\n"); return 1; }
cblas_dcopy(ndct,&z,0,&X1d[0],1); //zero-pad
if (dim==0)
{
if (iscolmajor)
{
for (c=0; c<C; c++)
{
//Window
ss = (int)(round(c*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_dcopy(-ss,&z,0,&X1[0],1);
cblas_dsbmv(CblasColMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_dsbmv(CblasColMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
}
else if (ss<N)
{
cblas_dsbmv(CblasColMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_dcopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftw_execute(fft_plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_dgemv(CblasColMajor,CblasNoTrans,B,F,1.0,&H[0],B,&Y1[0],1,0.0,&X1d[0],1);
//Power compress
for (b=0; b<B; b++) { X1d[b] = log(X1d[b]+preg); }
//DCT
fftw_execute(dct_plan);
cblas_dcopy(K,&Y1d[0],1,&Y[c*K],1);
}
//Lifter
if (Q>DBL_EPSILON) { for (k=0; k<K; k++) { cblas_dscal(C,fma(Q2,sin(PQ*k),1.0),&Y[k],K); } }
}
else
{
for (c=0; c<C; c++)
{
//Window
ss = (int)(round(c*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_dcopy(-ss,&z,0,&X1[0],1);
cblas_dsbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_dsbmv(CblasRowMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
}
else if (ss<N)
{
cblas_dsbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_dcopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftw_execute(fft_plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_dgemv(CblasRowMajor,CblasNoTrans,B,F,1.0,&H[0],F,&Y1[0],1,0.0,&X1d[0],1);
//Power compress
for (b=0; b<B; b++) { X1d[b] = log(X1d[b]+preg); }
//DCT
fftw_execute(dct_plan);
cblas_dcopy(K,&Y1d[0],1,&Y[c],C);
}
//Lifter
if (Q>DBL_EPSILON) { for (k=0; k<K; k++) { cblas_dscal(C,fma(Q2,sin(PQ*k),1.0),&Y[k*C],1); } }
}
}
else if (dim==1)
{
if (iscolmajor)
{
for (r=0; r<R; r++)
{
//Window
ss = (int)(round(r*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_dcopy(-ss,&z,0,&X1[0],1);
cblas_dsbmv(CblasColMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_dsbmv(CblasColMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
}
else if (ss<N)
{
cblas_dsbmv(CblasColMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_dcopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftw_execute(fft_plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_dgemv(CblasColMajor,CblasNoTrans,B,F,1.0,&H[0],B,&Y1[0],1,0.0,&X1d[0],1);
//Power compress
for (b=0; b<B; b++) { X1d[b] = log(X1d[b]+preg); }
//DCT
fftw_execute(dct_plan);
cblas_dcopy(K,&Y1d[0],1,&Y[r],R);
}
//Lifter
if (Q>DBL_EPSILON) { for (k=0; k<K; k++) { cblas_dscal(R,fma(Q2,sin(PQ*k),1.0),&Y[k*R],1); } }
}
else
{
for (r=0; r<R; r++)
{
//Window
ss = (int)(round(r*stp)) + c0 - Lpre;
if (ss<0)
{
cblas_dcopy(-ss,&z,0,&X1[0],1);
cblas_dsbmv(CblasRowMajor,CblasUpper,L+ss,0,1.0,&W[-ss],1,&X[0],1,0.0,&X1[-ss],1);
}
else if (ss+L<=N)
{
cblas_dsbmv(CblasRowMajor,CblasUpper,L,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
}
else if (ss<N)
{
cblas_dsbmv(CblasRowMajor,CblasUpper,N-ss,0,1.0,&W[0],1,&X[ss],1,0.0,&X1[0],1);
cblas_dcopy(L-N+ss,&z,0,&X1[N-ss],1);
}
else
{
cblas_dcopy(L,&z,0,&X1[0],1);
}
//Subtract mean
if (mn0) { cblas_daxpy(L,-cblas_ddot(L,&X1[0],1,&o,0)/L,&o,0,&X1[0],1); }
//FFT
fftw_execute(fft_plan);
//Power
for (f=0; f<nfft; f++) { Y1[f] *= Y1[f]; }
for (f=1; f<F2; f++) { Y1[f] += Y1[nfft-f]; }
//Transform freq scale
cblas_dgemv(CblasRowMajor,CblasNoTrans,B,F,1.0,&H[0],F,&Y1[0],1,0.0,&X1d[0],1);
//Power compress
for (b=0; b<B; b++) { X1d[b] = log(X1d[b]+preg); }
//DCT
fftw_execute(dct_plan);
cblas_dcopy(K,&Y1d[0],1,&Y[r*K],1);
}
//Lifter
if (Q>DBL_EPSILON) { for (k=0; k<K; k++) { cblas_dscal(R,fma(Q2,sin(PQ*k),1.0),&Y[k],K); } }
}
}
else
{
fprintf(stderr,"error in mfccs_d: dim must be 0 or 1.\n"); return 1;
}
//Exit
fftw_destroy_plan(fft_plan); fftw_free(X1); fftw_free(Y1);
fftw_destroy_plan(dct_plan); fftw_free(X1d); fftw_free(Y1d);
return 0;
}
#ifdef __cplusplus
}
}
#endif
| {
"alphanum_fraction": 0.4745436669,
"avg_line_length": 41.6245551601,
"ext": "c",
"hexsha": "0843a8a90bb5abcfc78f8b5497f3d65afb23172b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "erikedwards4/aud",
"max_forks_repo_path": "c/mfccs.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "erikedwards4/aud",
"max_issues_repo_path": "c/mfccs.c",
"max_line_length": 304,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ee7adeb3b65d4ec45ad026cc915196b92c4b1c2b",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "erikedwards4/aud",
"max_stars_repo_path": "c/mfccs.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7851,
"size": 23393
} |
/**
*
* @file core_dpotrf.c
*
* PLASMA core_blas kernel
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* @version 2.6.0
* @author Hatem Ltaief
* @author Mathieu Faverge
* @author Jakub Kurzak
* @date 2010-11-15
* @generated d Tue Jan 7 11:44:45 2014
*
**/
#include <lapacke.h>
#include "common.h"
/***************************************************************************//**
*
* @ingroup CORE_double
*
* CORE_dpotrf - Computes the Cholesky factorization of a symmetric positive definite
* (or Hermitian positive definite in the complex case) matrix A.
* The factorization has the form
*
* \f[ A = \{_{L\times L^H, if uplo = PlasmaLower}^{U^H\times U, if uplo = PlasmaUpper} \f]
*
* where U is an upper triangular matrix and L is a lower triangular matrix.
*
*******************************************************************************
*
* @param[in] uplo
* = PlasmaUpper: Upper triangle of A is stored;
* = PlasmaLower: Lower triangle of A is stored.
*
* @param[in] N
* The order of the matrix A. N >= 0.
*
* @param[in,out] A
* On entry, the symmetric positive definite (or Hermitian) matrix A.
* If uplo = PlasmaUpper, the leading N-by-N upper triangular part of A
* contains the upper triangular part of the matrix A, and the strictly
* lower triangular part of A is not referenced.
* If UPLO = 'L', the leading N-by-N lower triangular part of A
* contains the lower triangular part of the matrix A, and the strictly
* upper triangular part of A is not referenced.
* On exit, if return value = 0, the factor U or L from the Cholesky
* factorization A = U**T*U or A = L*L**T.
*
* @param[in] LDA
* The leading dimension of the array A. LDA >= max(1,N).
*
* @param[out] info
* - 0 on successful exit
* - <0 if -i, the i-th argument had an illegal value
* - >0 if i, the leading minor of order i of A is not positive
* definite, so the factorization could not be completed, and the
* solution has not been computed.
*
******************************************************************************/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_dpotrf = PCORE_dpotrf
#define CORE_dpotrf PCORE_dpotrf
#endif
void CORE_dpotrf(PLASMA_enum uplo, int N, double *A, int LDA, int *info)
{
*info = LAPACKE_dpotrf_work(
LAPACK_COL_MAJOR,
lapack_const(uplo),
N, A, LDA );
}
| {
"alphanum_fraction": 0.576614444,
"avg_line_length": 34.8933333333,
"ext": "c",
"hexsha": "8c16a7735cac30daafa7060de3e125d6f2939fff",
"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_dpotrf.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_dpotrf.c",
"max_line_length": 94,
"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_dpotrf.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 682,
"size": 2617
} |
/**
* @file batchf_zgemv.c
*
* Part of API test for Batched BLAS routines.
*
* @author Samuel D. Relton
* @author Pedro V. Lara
* @author Mawussi Zounon
* @date 2016-06-01
*
* @precisions normal z -> c d s
*
**/
#include <cblas.h>
#include "bblas.h"
#define COMPLEX
void batchf_zgemv(
const enum BBLAS_TRANS trans,
const int m, const int n,
const BBLAS_Complex64_t alpha,
const BBLAS_Complex64_t **arrayA, const int lda,
const BBLAS_Complex64_t **arrayx, const int incx,
const BBLAS_Complex64_t beta,
BBLAS_Complex64_t **arrayy, const int incy,
const int batch_count, int info)
{
/* Local variables */
int first_index = 0;
int batch_iter = 0;
char func_name[15] = "batchf_zgemv";
/* Check input arguments */
if (batch_count < 0)
{
xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1);
}
if ((trans != BblasTrans) &&
(trans != BblasNoTrans) &&
(trans != BblasConjTrans))
{
xerbla_batch(func_name, BBLAS_ERR_TRANS, first_index);
info = BBLAS_ERR_TRANS;
}
if (m < 0)
{
xerbla_batch(func_name, BBLAS_ERR_M, first_index);
info = BBLAS_ERR_M;
}
if (n < 0)
{
xerbla_batch(func_name, BBLAS_ERR_N, first_index);
info = BBLAS_ERR_N;
}
/* Column major */
if ((lda < 1) && (lda < m))
{
xerbla_batch(func_name, BBLAS_ERR_LDA, first_index);
info = BBLAS_ERR_LDA;
}
if (incx < 1)
{
xerbla_batch(func_name, BBLAS_ERR_INCX, first_index);
info = BBLAS_ERR_INCX;
}
if (incy < 1)
{
xerbla_batch(func_name, BBLAS_ERR_INCY, first_index);
info = BBLAS_ERR_INCY;
}
/* Call CBLAS */
for (batch_iter = 0; batch_iter < batch_count; batch_iter++)
{
cblas_zgemv(
BblasColMajor,
trans,
m, n,
CBLAS_SADDR( alpha ),
arrayA[batch_iter], lda,
arrayx[batch_iter], incx,
CBLAS_SADDR( beta ),
arrayy[batch_iter], incy);
} /* End fixed size for loop */
/* Successful */
info = BBLAS_SUCCESS;
}
#undef COMPLEX
| {
"alphanum_fraction": 0.6737064414,
"avg_line_length": 19.7291666667,
"ext": "c",
"hexsha": "37efa1c32dc2f7bcb3146db0d92bc94c55135950",
"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": "117f3538b3ab43ade0ad53950ecac25c1a192bc7",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "sdrelton/bblas_api_test",
"max_forks_repo_path": "src/batchf_zgemv.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7",
"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": "sdrelton/bblas_api_test",
"max_issues_repo_path": "src/batchf_zgemv.c",
"max_line_length": 61,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "mawussi/BBLAS-group",
"max_stars_repo_path": "src/batchf_zgemv.c",
"max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z",
"num_tokens": 650,
"size": 1894
} |
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include <time.h>
#include <gsl/gsl_math.h>
#include "cosmocalc.h"
void test_nonlinear_corrfunc(void)
{
double lnrmin = log(1e-5);
double lnrmax = log(3e2);
int N = 10000;
double r,dlnr = (lnrmax - lnrmin)/N;
int i;
FILE *fp;
double a;
a = 1.0;
fp = fopen("xinltest.txt","w");
for(i=0;i<N;++i)
{
r = exp(dlnr*i + lnrmin);
fprintf(fp,"%.20e\t%.20e\t%.20e\n",r,nonlinear_corrfunc(r,a),linear_corrfunc(r,a));
}
fclose(fp);
}
void test_nonlinear_powspec(void)
{
double lnkmin = log(1e-4);
double lnkmax = log(1e2);
double dlnk,k;
int N = 10000,i;
FILE *fp;
double a = 1.0;
dlnk = (lnkmax - lnkmin)/N;
a = 1.0;
fp = fopen("pknltest.txt","w");
for(i=0;i<N;++i)
{
k = exp(dlnk*i + lnkmin);
fprintf(fp,"%.20e\t%.20e\t%.20e\n",k,nonlinear_powspec(k,a),linear_powspec(k,a));
}
fclose(fp);
a = 1.0/(1.0 + 0.5);
fp = fopen("pknltest1.txt","w");
for(i=0;i<N;++i)
{
k = exp(dlnk*i + lnkmin);
fprintf(fp,"%.20e\t%.20e\t%.20e\n",k,nonlinear_powspec(k,a),linear_powspec(k,a));
}
fclose(fp);
a = 1.0/(1.0 + 1.0);
fp = fopen("pknltest2.txt","w");
for(i=0;i<N;++i)
{
k = exp(dlnk*i + lnkmin);
fprintf(fp,"%.20e\t%.20e\t%.20e\n",k,nonlinear_powspec(k,a),linear_powspec(k,a));
}
fclose(fp);
a = 1.0/(1.0 + 2.00);
fp = fopen("pknltest3.txt","w");
for(i=0;i<N;++i)
{
k = exp(dlnk*i + lnkmin);
fprintf(fp,"%.20e\t%.20e\t%.20e\n",k,nonlinear_powspec(k,a),linear_powspec(k,a));
}
fclose(fp);
a = 1.0/(1.0 + 3.00);
fp = fopen("pknltest4.txt","w");
for(i=0;i<N;++i)
{
k = exp(dlnk*i + lnkmin);
fprintf(fp,"%.20e\t%.20e\t%.20e\n",k,nonlinear_powspec(k,a),linear_powspec(k,a));
}
fclose(fp);
}
void test_linxi_fftlog(void)
{
double rmin;
long i,N = 2048;
double dlnr;
FILE *fp;
double r;
double a = 1.0;
double *pk,*xi;
double k0,L,q,r0,k;
double kmin = 1e-7;
double kmax = 1e7;
double dlnk = log(kmax/kmin)/N;
L = log(kmax/kmin);
k0 = exp(log(kmin) + L/2.0);
q = 0.0;
pk = (double*)malloc(sizeof(double)*N);
assert(pk != NULL);
xi = (double*)malloc(sizeof(double)*N);
assert(xi != NULL);
for(i=0;i<N;++i)
{
k = exp(i*dlnk + log(kmin));
pk[i] = linear_powspec_exact(k,a);
}
r0 = 1.0;
compute_discrete_spherical_fft(pk,N,k0,L,q,xi,&r0);
if(0)
{
for(i=0;i<N;++i)
xi[i] = xi[i]/pow(2.0*M_PI,3.0);
compute_discrete_spherical_fft(xi,N,r0,L,q,pk,&k0);
kmin = exp(log(k0)-L/2.0);
//fprintf(stderr,"k0 = %e, kmin = %e, L = %f, N = %ld\n",k0,kmin,L,N);
fp = fopen("linxitest.txt","w");
for(i=0;i<N;++i)
{
k = exp(i*dlnk + log(kmin));
//fprintf(stderr,"k = %e, pk in,out = %e|%e\n",k,linear_powspec(k,a),pk[i]);
fprintf(fp,"%.20e \t %.20e \t %.20e \n",k,pk[i],linear_powspec_exact(k,a));
}
fclose(fp);
return;
}
rmin = exp(log(r0)-L/2.0);
dlnr = dlnk;
fp = fopen("linxitest.txt","w");
for(i=0;i<N;++i)
{
r = exp(i*dlnr + log(rmin));
xi[i] = xi[i]/pow(2.0*M_PI,3.0);
//fprintf(stderr,"%.20e \t %.20e \t %.20e \n",r,xi[i],linear_corrfunc_exact(r,a));
fprintf(fp,"%.20e \t %.20e \t %.20e \n",r,xi[i],linear_corrfunc_exact(r,a));
}
fclose(fp);
}
void test_linxi(void)
{
double rmin=1e-9;
double rmax=1e5;
long i,Ntest = 1000;
double dlnr = log(rmax/rmin)/Ntest;
FILE *fp;
double r;
double a = 1.0;
fp = fopen("linxitest.txt","w");
for(i=0;i<Ntest;++i)
{
r = exp(i*dlnr + log(rmin));
//fprintf(stderr,"%.20e \t %.20e \t %.20e \n",r,linear_corrfunc_exact(r,a),linear_corrfunc_exact(r,a));
fprintf(fp,"%.20e \t %.20e \t %.20e \n",r,linear_corrfunc(r,a),linear_corrfunc_exact(r,a));
}
fclose(fp);
}
void test_biasfunc(void)
{
FILE *fp;
double m,lgm;
double mmin = 6.0;
double mmax = 16.0;
double dm = 0.01;
double a = 1.0;
fp = fopen("btest.txt","w");
lgm = mmax;
while(lgm >= mmin)
{
m = pow(10.0,lgm);
fprintf(fp,"%.20e \t %.20e \n",1.686/sigmaMtophat(m,a),bias_function(m,a));
lgm -= dm;
}
fclose(fp);
}
void test_massfunc(void)
{
FILE *fp;
double m,lgm;
double mmin = 10.0;
double mmax = 16.0;
double dm = 0.01;
double a = 1.0;
fp = fopen("mftest.txt","w");
lgm = mmax;
while(lgm >= mmin)
{
m = pow(10.0,lgm);
fprintf(fp,"%.20e \t %.20e \n",m,mass_function(m,a)*m*m/RHO_CRIT/cosmoData.OmegaM);
lgm -= dm;
}
fclose(fp);
}
void test_peakheight(void)
{
FILE *fp;
double r;
double rmin = 1e-40;
double rmax = 1e3;
double dr = 0.99;
double a = 1.0;
double numin = 0.15;
double numax = 6.0;
double dnu = 0.99;
double nu;
double kmin=1e-10;
double kmax=1e10;
long i,Ntest = 1000;
double dlnk = log(kmax/kmin)/Ntest;
double k,p = 1e-6;
fp = fopen("phtest_integ.txt","w");
for(i=0;i<Ntest;++i)
{
k = (i*dlnk + log(kmin));
fprintf(fp,"%.20e \t %.20e \n",exp(k),tophatradnorm_linear_powspec_exact_nonorm_lnk_integ_funct_I0(k,&p));
}
fclose(fp);
fp = fopen("phtest.txt","w");
r = rmax;
while(r >= rmin)
{
fprintf(fp,"%.20e \t %.20e \t %.20e \n",r,sigmaRtophat(r,a),sigmaRtophat_exact(r,a));
r *= dr;
}
fclose(fp);
fp = fopen("phtestrev.txt","w");
nu = numax;
while(nu >= numin)
{
fprintf(fp,"%.20e \t %.20e \n",inverse_nuRtophat(nu,a),DELTAC/nu);
nu *= dnu;
}
fclose(fp);
}
void test_gf(void)
{
FILE *fp;
double a;
double amin = 0.1;
double amax = 1.0;
double da = 0.0001;
fp = fopen("gftest.txt","w");
a = amax;
while(a >= amin)
{
fprintf(fp,"%.20e \t %.20e \t %.20e \n",a,growth_function(a),growth_function_exact(a));
a -= da;
}
fclose(fp);
}
void test_linpk(void)
{
double kmin=1e-8;
double kmax=1e40;
long i,Ntest = 10000;
double dlnk = log(kmax/kmin)/Ntest;
FILE *fp;
double k;
double a = 1.0;
fp = fopen("pktest.txt","w");
for(i=0;i<Ntest;++i)
{
k = exp(i*dlnk + log(kmin));
fprintf(fp,"%.20e \t %.20e \t %.20e \n",k,linear_powspec(k,a),linear_powspec_exact(k,a));
}
fclose(fp);
}
void test_transfunct(void)
{
double kmin=1e-8;
double kmax=1e30;
long i,Ntest = 10000;
double dlnk = log(kmax/kmin)/Ntest;
FILE *fp;
double k;
fp = fopen("tftest.txt","w");
for(i=0;i<Ntest;++i)
{
k = exp(i*dlnk + log(kmin));
fprintf(fp,"%.20e \t %.20e \t %.20e \n",k,transfer_function(k),transfunct_eh98(k));
}
fclose(fp);
cosmoData.OmegaM = 0.2;
cosmoData.h = 0.5;
cosmoData.OmegaB = cosmoData.OmegaM*0.5;
cosmoData.cosmoNum = 2;
fp = fopen("tftest_highb.txt","w");
for(i=0;i<Ntest;++i)
{
k = exp(i*dlnk + log(kmin));
fprintf(fp,"%.20e \t %.20e \t %.20e \n",k,transfer_function(k),transfunct_eh98(k));
}
fclose(fp);
}
void test_distances(void)
{
FILE *fp;
double amin = 0.1;
double amax = 1.0;
double da = 0.0001;
double dmin = 0.0;
double dmax = 3000.0;
double dd = 1.0;
double a,d;
fp = fopen("disttest_a2d.txt","w");
a = amax;
while(a >= amin)
{
fprintf(fp,"%.20e \t %.20e \t %.20e \n",a,comvdist(a),comvdist_exact(a));
a -= da;
}
fclose(fp);
fp = fopen("disttest_d2a.txt","w");
d = dmin;
while(d <= dmax)
{
a = acomvdist(d);
fprintf(fp,"%.20e \t %.20e \t %.20e \n",d,a,comvdist_exact(a));
d += dd;
}
fclose(fp);
}
| {
"alphanum_fraction": 0.5484381178,
"avg_line_length": 21.075,
"ext": "c",
"hexsha": "4d9322b9b257f3c97ab77f0b288cb939e6127d19",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2017-08-11T17:31:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-07-14T12:17:31.000Z",
"max_forks_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "beckermr/cosmocalc",
"max_forks_repo_path": "src/test_code.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_issues_repo_issues_event_max_datetime": "2016-04-05T19:36:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-05T19:10:45.000Z",
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "beckermr/cosmocalc",
"max_issues_repo_path": "src/test_code.c",
"max_line_length": 112,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "aa7d7cb58f05a36d446e02b45a9117d93eb16556",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "beckermr/cosmocalc",
"max_stars_repo_path": "src/test_code.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3004,
"size": 7587
} |
#pragma once
#include <winrt\Windows.Foundation.h>
#include <d3d11.h>
#include <gsl\gsl>
namespace Library
{
class DepthStencilStates final
{
public:
inline static winrt::com_ptr<ID3D11DepthStencilState> DefaultDepthCulling;
inline static winrt::com_ptr<ID3D11DepthStencilState> NoDepthCulling;
static void Initialize(gsl::not_null<ID3D11Device*> direct3DDevice);
static void Shutdown();
DepthStencilStates() = delete;
DepthStencilStates(const DepthStencilStates&) = delete;
DepthStencilStates& operator=(const DepthStencilStates&) = delete;
DepthStencilStates(DepthStencilStates&&) = delete;
DepthStencilStates& operator=(DepthStencilStates&&) = delete;
~DepthStencilStates() = default;
};
}
| {
"alphanum_fraction": 0.7780859917,
"avg_line_length": 27.7307692308,
"ext": "h",
"hexsha": "b28d367ac27c45a153adea9768ca3f9726d0c8da",
"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/DepthStencilStates.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/DepthStencilStates.h",
"max_line_length": 76,
"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/DepthStencilStates.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 190,
"size": 721
} |
/* permutation/gsl_permutation.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004 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_PERMUTATION_H__
#define __GSL_PERMUTATION_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_check_range.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
struct gsl_permutation_struct
{
size_t size;
size_t *data;
};
typedef struct gsl_permutation_struct gsl_permutation;
GSL_EXPORT gsl_permutation *gsl_permutation_alloc (const size_t n);
GSL_EXPORT gsl_permutation *gsl_permutation_calloc (const size_t n);
GSL_EXPORT void gsl_permutation_init (gsl_permutation * p);
GSL_EXPORT void gsl_permutation_free (gsl_permutation * p);
GSL_EXPORT int gsl_permutation_memcpy (gsl_permutation * dest, const gsl_permutation * src);
GSL_EXPORT int gsl_permutation_fread (FILE * stream, gsl_permutation * p);
GSL_EXPORT int gsl_permutation_fwrite (FILE * stream, const gsl_permutation * p);
GSL_EXPORT int gsl_permutation_fscanf (FILE * stream, gsl_permutation * p);
GSL_EXPORT int gsl_permutation_fprintf (FILE * stream, const gsl_permutation * p, const char *format);
GSL_EXPORT size_t gsl_permutation_size (const gsl_permutation * p);
GSL_EXPORT size_t * gsl_permutation_data (const gsl_permutation * p);
GSL_EXPORT size_t gsl_permutation_get (const gsl_permutation * p, const size_t i);
GSL_EXPORT int gsl_permutation_swap (gsl_permutation * p, const size_t i, const size_t j);
GSL_EXPORT int gsl_permutation_valid (gsl_permutation * p);
GSL_EXPORT void gsl_permutation_reverse (gsl_permutation * p);
GSL_EXPORT int gsl_permutation_inverse (gsl_permutation * inv, const gsl_permutation * p);
GSL_EXPORT int gsl_permutation_next (gsl_permutation * p);
GSL_EXPORT int gsl_permutation_prev (gsl_permutation * p);
GSL_EXPORT int gsl_permutation_mul (gsl_permutation * p, const gsl_permutation * pa, const gsl_permutation * pb);
GSL_EXPORT int gsl_permutation_linear_to_canonical (gsl_permutation * q, const gsl_permutation * p);
GSL_EXPORT int gsl_permutation_canonical_to_linear (gsl_permutation * p, const gsl_permutation * q);
GSL_EXPORT size_t gsl_permutation_inversions (const gsl_permutation * p);
GSL_EXPORT size_t gsl_permutation_linear_cycles (const gsl_permutation * p);
GSL_EXPORT size_t gsl_permutation_canonical_cycles (const gsl_permutation * q);
#ifdef HAVE_INLINE
extern inline
size_t
gsl_permutation_get (const gsl_permutation * p, const size_t i)
{
#if GSL_RANGE_CHECK
if (i >= p->size)
{
GSL_ERROR_VAL ("index out of range", GSL_EINVAL, 0);
}
#endif
return p->data[i];
}
#endif /* HAVE_INLINE */
__END_DECLS
#endif /* __GSL_PERMUTATION_H__ */
| {
"alphanum_fraction": 0.7847065463,
"avg_line_length": 35.797979798,
"ext": "h",
"hexsha": "50227a3c882fc46fca294f0cbdb4aff72e47cb42",
"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_permutation.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_permutation.h",
"max_line_length": 113,
"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_permutation.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 926,
"size": 3544
} |
/* randist/fdist.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 James Theiler, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <config.h>
#include <math.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
/* The F distribution has the form
p(x) dx = (nu1^(nu1/2) nu2^(nu2/2) Gamma((nu1 + nu2)/2) /
Gamma(nu1/2) Gamma(nu2/2)) *
x^(nu1/2 - 1) (nu2 + nu1 * x)^(-nu1/2 -nu2/2) dx
The method used here is the one described in Knuth */
double
gsl_ran_fdist (const gsl_rng * r, const double nu1, const double nu2)
{
double Y1 = gsl_ran_gamma (r, nu1 / 2, 2.0);
double Y2 = gsl_ran_gamma (r, nu2 / 2, 2.0);
double f = (Y1 * nu2) / (Y2 * nu1);
return f;
}
double
gsl_ran_fdist_pdf (const double x, const double nu1, const double nu2)
{
if (x < 0)
{
return 0 ;
}
else
{
double p;
double lglg = (nu1 / 2) * log (nu1) + (nu2 / 2) * log (nu2) ;
double lg12 = gsl_sf_lngamma ((nu1 + nu2) / 2);
double lg1 = gsl_sf_lngamma (nu1 / 2);
double lg2 = gsl_sf_lngamma (nu2 / 2);
p = exp (lglg + lg12 - lg1 - lg2)
* pow (x, nu1 / 2 - 1) * pow (nu2 + nu1 * x, -nu1 / 2 - nu2 / 2);
return p;
}
}
| {
"alphanum_fraction": 0.6345044573,
"avg_line_length": 28.0441176471,
"ext": "c",
"hexsha": "ef532fffc747278982f2f7054d07472f36cbf5c1",
"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/randist/fdist.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/randist/fdist.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/randist/fdist.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": 646,
"size": 1907
} |
// Copyright (c) 2022 SmartPolarBear.
//
// 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.
//
// Created by cleve on 2/1/2022.
//
#pragma once
#include "types.h"
#include <utility>
#include <cstdint>
#include <string_view>
#include <bit>
#include <gsl/gsl>
namespace jpeg_lite::decoder::transform
{
[[nodiscard]] FORCE_INLINE gsl::index coordinate_to_zigzag(gsl::index x, gsl::index y);
[[nodiscard]] FORCE_INLINE std::pair<gsl::index, gsl::index> zigzag_to_coordinate(gsl::index zigzag);
[[nodiscard, maybe_unused]] int16_t binary_string_to_int16(std::string_view sv);
[[nodiscard]] static inline FORCE_INLINE constexpr int16_t value_category(int16_t val)
{
if (val == 0x0000)
return 0;
return std::bit_width(static_cast<uint16_t>(val > 0 ? val : -val));
}
} | {
"alphanum_fraction": 0.753485778,
"avg_line_length": 36.5918367347,
"ext": "h",
"hexsha": "dc4796d2b834a558c022b460dd5a2cb2e4c01c9b",
"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": "e450d01fe90d710381f53d16b5141a85dabd56d1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SmartPolarBear/jpeg-lite",
"max_forks_repo_path": "include/decoder/transform.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e450d01fe90d710381f53d16b5141a85dabd56d1",
"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": "SmartPolarBear/jpeg-lite",
"max_issues_repo_path": "include/decoder/transform.h",
"max_line_length": 101,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e450d01fe90d710381f53d16b5141a85dabd56d1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SmartPolarBear/jpeg-lite",
"max_stars_repo_path": "include/decoder/transform.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 419,
"size": 1793
} |
//============================================================================
// Name : main.c
// Author : Cesare De Cal
// Version :
// Copyright : Cesare De Cal
// Description : Exercise 7 - System of Linear Equations
//============================================================================
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
// Useful: https://gist.github.com/bjd2385/7f4685e703f7437e513608f41c65bbd7 (LU decomposition)
// Useful: https://github.com/rwinlib/gsl/blob/master/include/gsl/gsl_linalg.h#L173 (GEPP)
gsl_matrix *createMatrix(int size) {
gsl_matrix *matrix = gsl_matrix_alloc(size, size);
gsl_matrix_set_zero(matrix);
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= size; j++) {
// Fill diagonal
if (i == j) {
if ((i+1) % 3 == 0) {
double value = (2.0*(i+1))/3;
gsl_matrix_set(matrix, i-1, j-1, value);
} else {
gsl_matrix_set(matrix, i-1, j-1, 1);
}
// Fill adjacent lower diagonal
} else if (i == j+1) {
gsl_matrix_set(matrix, i-1, j-1, 1);
// Fill adjacent upper diagonal
} else if (i+1 == j) {
gsl_matrix_set(matrix, i-1, j-1, -1);
}
}
}
return matrix;
}
// Helper methods
void printVectorContents(gsl_vector *vector) {
for (int i = 0; i < vector->size; i++) {
printf("%.9e\\\\\n", gsl_vector_get(vector, i));
}
printf("\n");
}
void printMatrixContents(gsl_matrix *matrix) {
for (int i = 0; i < matrix->size1; ++i) {
for (int j = 0; j < matrix->size2; ++j) {
printf("%.9e ", gsl_matrix_get(matrix, i, j));
if (j == matrix->size2-1) {
printf("\\\\");
} else {
printf("& ");
}
}
printf("\n");
}
printf("\n");
}
void computeForOrder(int size, int shouldPrintVerboseOutput) {
gsl_matrix *matrixA = createMatrix(size);
if (shouldPrintVerboseOutput) {
printf("Creating matrix A:\n");
printMatrixContents(matrixA);
}
// Right-hand side vector y
gsl_vector *bVector = gsl_vector_alloc(matrixA->size2);
gsl_vector_set_zero(bVector);
// Fill element at index 0 with 1
gsl_vector_set(bVector, 0, 1);
if (shouldPrintVerboseOutput) {
printf("Creating vector y (b):\n");
printVectorContents(bVector);
}
// Solve system using LU decomposition
gsl_matrix *luMatrix = gsl_matrix_alloc(matrixA->size1, matrixA->size2);
gsl_permutation *permutation = gsl_permutation_alloc(matrixA->size1);
int signum; // Sign of the permutation
// Copy A over newly created matrixA
gsl_matrix_memcpy(luMatrix, matrixA);
// Compute LU decomposition
gsl_linalg_LU_decomp(luMatrix, permutation, &signum);
if (shouldPrintVerboseOutput) {
printf("LU decomposition of A:\n");
printMatrixContents(luMatrix);
}
// Result vector v
gsl_vector *xVector = gsl_vector_alloc(matrixA->size2);
gsl_vector_set_zero(xVector);
gsl_linalg_LU_solve(luMatrix, permutation, bVector, xVector);
if (shouldPrintVerboseOutput) {
printf("Solutions x vector:\n");
printVectorContents(xVector);
}
// Calculate condition number
// There is no function in GSL to directly compute this number
// the condition number is given by taking the absolute value of the ratio of the largest singular value and the smallest singular value
// cond(A) = abs( largest_sing_val / smallest_sing_val )
gsl_matrix *matrixV = gsl_matrix_alloc(matrixA->size1, matrixA->size2);
gsl_vector *vectorS = gsl_vector_alloc(matrixA->size1);
gsl_vector *vectorWorkspace = gsl_vector_alloc(matrixA->size1);
gsl_linalg_SV_decomp(matrixA, matrixV, vectorS, vectorWorkspace);
if (shouldPrintVerboseOutput) {
printf("Singular diagonal vector:\n");
printVectorContents(vectorS);
}
double minSingularValue, maxSingularValue;
gsl_vector_minmax(vectorS, &minSingularValue, &maxSingularValue);
if (shouldPrintVerboseOutput) {
printf("Max: %.9e, min: %.9e\n", maxSingularValue, minSingularValue);
}
double conditionNumber = fabs(maxSingularValue/minSingularValue);
double x1 = gsl_vector_get(xVector, 0);
double error = (M_E - 2) - x1;
printf("%d & %.9e & %.9e & %.9e \\\\", size, x1, error, conditionNumber);
// Free memory space
gsl_matrix_free(matrixA);
gsl_vector_free(bVector);
gsl_matrix_free(luMatrix);
gsl_permutation_free(permutation);
gsl_vector_free(xVector);
gsl_matrix_free(matrixV);
gsl_vector_free(vectorS);
gsl_vector_free(vectorWorkspace);
}
int main() {
printf("This program is going to generate a LaTeX friendly output to be used in the report table.\n");
printf("------------------------------\n");
printf("n, x1, error, condition number\n");
for (int n = 1; n <= 50; n++) {
computeForOrder(n, 0);
printf("\n");
}
printf("------------------------------\n");
return 0;
}
| {
"alphanum_fraction": 0.6348851393,
"avg_line_length": 30.5527950311,
"ext": "c",
"hexsha": "25a2c6f22761b9df3833e63da1bba0c882ffd997",
"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": "ac2d64ea235d7bee9cf0de8bbe42d06a3986bd5a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "csr/MATLAB-Scientific-Programming",
"max_forks_repo_path": "Linear Systems/CesareDeCal_Exercise7/exercise7/main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ac2d64ea235d7bee9cf0de8bbe42d06a3986bd5a",
"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": "csr/MATLAB-Scientific-Programming",
"max_issues_repo_path": "Linear Systems/CesareDeCal_Exercise7/exercise7/main.c",
"max_line_length": 138,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ac2d64ea235d7bee9cf0de8bbe42d06a3986bd5a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "csr/MATLAB-Scientific-Programming",
"max_stars_repo_path": "Linear Systems/CesareDeCal_Exercise7/exercise7/main.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1358,
"size": 4919
} |
/**
* Copyright 2016 BitTorrent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <scraps/config.h>
#include <scraps/Byte.h>
#if SCRAPS_APPLE
#include <scraps/apple/SHA256.h>
namespace scraps { using SHA256 = apple::SHA256; }
#else
#include <scraps/sodium/SHA256.h>
namespace scraps { using SHA256 = sodium::SHA256; }
#endif
#include <gsl.h>
namespace scraps {
template <typename BaseByteType>
struct SHA256ByteTag {};
template <typename BaseByteType>
using SHA256Byte = StrongByte<SHA256ByteTag<BaseByteType>>;
template <typename ByteT, std::ptrdiff_t N>
std::array<SHA256Byte<std::remove_const_t<ByteT>>, SHA256::kHashSize>
GetSHA256(gsl::span<ByteT, N> data) {
std::array<SHA256Byte<std::remove_const_t<ByteT>>, SHA256::kHashSize> ret;
SHA256 sha256;
sha256.update(data.data(), data.size());
sha256.finish(ret.data());
return ret;
}
} // namespace scraps
| {
"alphanum_fraction": 0.7314685315,
"avg_line_length": 26.9811320755,
"ext": "h",
"hexsha": "8752d9df521db540619179c02eb642c141df8b81",
"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": "78925a738540415ec04b9cbe23cb319421f44978",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "carlbrown/scraps",
"max_forks_repo_path": "include/scraps/SHA256.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978",
"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": "carlbrown/scraps",
"max_issues_repo_path": "include/scraps/SHA256.h",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "78925a738540415ec04b9cbe23cb319421f44978",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "carlbrown/scraps",
"max_stars_repo_path": "include/scraps/SHA256.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 368,
"size": 1430
} |
/*
* Copyright 2008-2009 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*! \file defs.h
* \brief CBLAS utility definitions for interface routines
*/
#pragma once
#include <cblas.h>
namespace cusp
{
namespace system
{
namespace cpp
{
namespace detail
{
namespace cblas
{
struct cblas_format {};
struct upper : public cblas_format {};
struct lower : public cblas_format {};
struct unit : public cblas_format {};
struct nonunit : public cblas_format {};
struct cblas_row_major { const static CBLAS_ORDER order = CblasRowMajor; };
struct cblas_col_major { const static CBLAS_ORDER order = CblasColMajor; };
template< typename LayoutFormat >
struct Orientation : thrust::detail::eval_if<
thrust::detail::is_same<LayoutFormat, cusp::row_major>::value,
thrust::detail::identity_<cblas_row_major>,
thrust::detail::identity_<cblas_col_major>
>
{};
} // end namespace cblas
} // end namespace detail
} // end namespace cpp
} // end namespace system
} // end namespace cusp
| {
"alphanum_fraction": 0.6935881628,
"avg_line_length": 27.0333333333,
"ext": "h",
"hexsha": "e5e6a885a9d67a34afd810c4d4b6fdb6b79567cb",
"lang": "C",
"max_forks_count": 106,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T13:55:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-27T19:30:58.000Z",
"max_forks_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "njh19/cusplibrary",
"max_forks_repo_path": "cusp/system/cpp/detail/cblas/defs.h",
"max_issues_count": 41,
"max_issues_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a",
"max_issues_repo_issues_event_max_datetime": "2022-02-27T02:37:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-08T18:07:42.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "njh19/cusplibrary",
"max_issues_repo_path": "cusp/system/cpp/detail/cblas/defs.h",
"max_line_length": 86,
"max_stars_count": 270,
"max_stars_repo_head_hexsha": "99dcde05991ef59cbc4546aeced6eb3bd49c90c9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Raman-sh/cusplibrary",
"max_stars_repo_path": "cusp/system/cpp/detail/cblas/defs.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-28T00:58:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-12T19:40:50.000Z",
"num_tokens": 369,
"size": 1622
} |
/*
cp ../../../../native_ref/<target binary> libnetlib.so
gcc-mp-4.8 -O3 dgemmtest.c common.c -o dgemmtest -L. -lnetlib -I../../../../netlib/CBLAS
./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-CBLAS.csv
gcc-mp-4.8 -O3 dgemmtest.c common.c -o dgemmtest -I/System/Library/Frameworks/vecLib.framework/Headers -framework veclib
./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-veclib.csv
gcc-mp-4.8 -O3 dgemmtest.c common.c -o dgemmtest -I/opt/local/include /opt/local/lib/libatlas.a /opt/local/lib/libcblas.a /opt/local/lib/liblapack.a /opt/local/lib/libf77blas.a -lgfortran
./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-atlas.csv
gcc-mp-4.8 -O3 dgemmtest.c common.c -o dgemmtest -I../../../../netlib/CBLAS -L/opt/intel/composerxe/mkl/lib -lmkl_rt
export DYLD_LIBRARY_PATH=/opt/intel/composerxe/mkl/lib:/opt/intel/composerxe/lib/
./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-mkl.csv
gcc-mp-4.8 -O3 dgemmtest.c cudawrapper.c common.c -o dgemmtest -I../../../../netlib/CBLAS -I/usr/local/cuda/include/ -L/usr/local/cuda/lib -lcublas
export DYLD_LIBRARY_PATH=/usr/local/cuda/lib
./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-cuda.csv
CLB=/Users/samuel/Documents/Projects/clBLAS/src
gcc-mp-4.8 -O3 dgemmtest.c clwrapper.c common.c -o dgemmtest -I../../../../netlib/CBLAS -I$CLB -I$CLB/include -L. -lclBLAS -framework OpenCL
./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-clblas.csv
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cblas.h>
#include "common.h"
// does AB == C ? If not, complain on stderr
void test(int m, double* a, double *b, double *c) {
int i, j, k, exact = 0, wrong = 0;
double diff;
double* d = calloc(m * m, sizeof(double));
for (i = 0 ; i < m ; i++) {
for (j = 0 ; j < m ; j++) {
for (k = 0 ; k < m ; k++) {
d[i + j * m] += a[i + k * m] * b[j * m + k];
}
}
}
for (i = 0 ; i < m ; i++) {
for (j = 0 ; j < m ; j++) {
diff = c[i * m + j] - d[i * m + j];
if (diff != 0.0) {
exact++;
}
if (abs(diff) > 0.000001) {
wrong++;
}
}
}
free(d);
if (wrong > 0) {
fprintf(stderr, "not exact = %d, wrong = %d\n", exact, wrong);
}
}
long benchmark(int size) {
int m = sqrt(size);
long requestStart, requestEnd;
double* a = random_array(m * m);
double* b = random_array(m * m);
double* c = calloc(m * m, sizeof(double));
requestStart = currentTimeNanos();
cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, m, m, 1, a, m, b, m, 0, c, m);
requestEnd = currentTimeNanos();
#ifdef __TEST__
test(m, a, b, c);
#endif
free(a);
free(b);
free(c);
return (requestEnd - requestStart);
}
main()
{
srand(time(NULL));
double factor = 6.0 / 100.0;
int i, j;
for (i = 0 ; i < 10 ; i++) {
for (j = 1 ; j <= 100 ; j++) {
int size = (int) pow(10.0, factor * j);
if (size < 10) continue;
long took = benchmark(size);
printf("\"%d\",\"%lu\"\n", size, took);
fflush(stdout);
}
}
} | {
"alphanum_fraction": 0.5945945946,
"avg_line_length": 29.4563106796,
"ext": "c",
"hexsha": "4589c1685d468d181e6e83a75a6229be0344400c",
"lang": "C",
"max_forks_count": 154,
"max_forks_repo_forks_event_max_datetime": "2021-09-07T04:58:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-03T22:48:26.000Z",
"max_forks_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3",
"max_forks_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_forks_repo_name": "debasish83/netlib-java",
"max_forks_repo_path": "perf/src/main/c/dgemmtest.c",
"max_issues_count": 59,
"max_issues_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3",
"max_issues_repo_issues_event_max_datetime": "2017-07-24T14:20:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-01T10:34:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_issues_repo_name": "debasish83/netlib-java",
"max_issues_repo_path": "perf/src/main/c/dgemmtest.c",
"max_line_length": 187,
"max_stars_count": 624,
"max_stars_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3",
"max_stars_repo_licenses": [
"BSD-3-Clause-Open-MPI"
],
"max_stars_repo_name": "debasish83/netlib-java",
"max_stars_repo_path": "perf/src/main/c/dgemmtest.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-26T22:06:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-01-10T02:29:22.000Z",
"num_tokens": 1077,
"size": 3034
} |
/*System includes*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
/*GSL includes*/
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
#include <gsl/gsl_statistics_double.h>
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_complex_math.h>
#include <gsl/gsl_multimin.h>
#include <pthread.h>
/*User includes*/
#include "../Lib/FileUtils.h"
#include "../Lib/MatrixUtils.h"
#include "MetroLogStudent.h"
static char *usage[] = {"MetroLogStudent - Samples the Poisson Log-Student distn to SADs\n",
"Required parameters:\n",
" -out filestub output file stub\n",
" -in filename parameter file \n",
"Optional:\n",
" -s integer generate integer mcmc samples\n",
" -seed long seed random number generator\n",
" -sigmaM float std. dev. of mean prop. distn\n",
" -sigmaV float \n",
" -sigmaN float \n",
" -sigmaS float \n",
" -v verbose\n"};
static int nLines = 11;
static int verbose = FALSE;
int main(int argc, char* argv[])
{
int i = 0, nNA = 0;
t_Params tParams;
t_Data tData;
gsl_vector* ptX = gsl_vector_alloc(4); /*parameter estimates*/
t_MetroInit atMetroInit[3];
gsl_rng_env_setup();
gsl_set_error_handler_off();
/*get command line params*/
getCommandLineParams(&tParams, argc, argv);
/*read in abundance distribution*/
readAbundanceData(tParams.szInputFile, &tData);
/*set initial estimates for parameters*/
gsl_vector_set(ptX, 0, INIT_M);
gsl_vector_set(ptX, 1, INIT_V);
gsl_vector_set(ptX, 2, INIT_N);
gsl_vector_set(ptX, 3, tData.nL*2);
printf("D = %d L = %d Chao = %f\n",tData.nL, tData.nJ, chao(&tData));
minimiseSimplex(ptX, 4, (void*) &tData, &nLogLikelihood);
outputResults(ptX, &tData);
if(tParams.nIter > 0){
mcmc(&tParams, &tData, ptX);
}
/*free up allocated memory*/
gsl_vector_free(ptX);
freeAbundanceData(&tData);
exit(EXIT_SUCCESS);
}
void writeUsage(FILE* ofp)
{
int i = 0;
char *line;
for(i = 0; i < nLines; i++){
line = usage[i];
fputs(line,ofp);
}
}
char *extractParameter(int argc, char **argv, char *param,int when)
{
int i = 0;
while((i < argc) && (strcmp(param,argv[i]))){
i++;
}
if(i < argc - 1){
return(argv[i + 1]);
}
if((i == argc - 1) && (when == OPTION)){
return "";
}
if(when == ALWAYS){
fprintf(stdout,"Can't find asked option %s\n",param);
}
return (char *) NULL;
}
void getCommandLineParams(t_Params *ptParams,int argc,char *argv[])
{
char *szTemp = NULL;
char *cError = NULL;
/*get parameter file name*/
ptParams->szInputFile = extractParameter(argc,argv, INPUT_FILE,ALWAYS);
if(ptParams->szInputFile == NULL)
goto error;
/*get out file stub*/
ptParams->szOutFileStub = extractParameter(argc,argv,OUT_FILE_STUB,ALWAYS);
if(ptParams->szOutFileStub == NULL)
goto error;
/*get out file stub*/
szTemp = extractParameter(argc,argv,SEED,OPTION);
if(szTemp != NULL){
ptParams->lSeed = strtol(szTemp,&cError,10);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->lSeed = 0;
}
/*verbosity*/
szTemp = extractParameter(argc, argv, VERBOSE, OPTION);
if(szTemp != NULL){
verbose = TRUE;
}
szTemp = extractParameter(argc,argv,SIGMA_M,OPTION);
if(szTemp != NULL){
ptParams->dSigmaM = strtod(szTemp,&cError);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->dSigmaM = DEF_SIGMA;
}
szTemp = extractParameter(argc,argv,SIGMA_V,OPTION);
if(szTemp != NULL){
ptParams->dSigmaV = strtod(szTemp,&cError);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->dSigmaV = DEF_SIGMA;
}
szTemp = extractParameter(argc,argv,SIGMA_N,OPTION);
if(szTemp != NULL){
ptParams->dSigmaN = strtod(szTemp,&cError);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->dSigmaN = DEF_SIGMA;
}
szTemp = extractParameter(argc,argv,SIGMA_S,OPTION);
if(szTemp != NULL){
ptParams->dSigmaS = strtod(szTemp,&cError);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->dSigmaS = DEF_SIGMA_S;
}
szTemp = extractParameter(argc,argv,SAMPLE,OPTION);
if(szTemp != NULL){
ptParams->nIter = strtol(szTemp,&cError,10);
if(*cError != '\0'){
goto error;
}
}
else{
ptParams->nIter = 0;
}
return;
error:
writeUsage(stdout);
exit(EXIT_FAILURE);
}
void readAbundanceData(const char *szFile, t_Data *ptData)
{
int **aanAbund = NULL;
int i = 0, nNA = 0, nA = 0, nC = 0;
int nL = 0, nJ = 0;
char szLine[MAX_LINE_LENGTH];
FILE* ifp = NULL;
ifp = fopen(szFile, "r");
if(ifp){
char* szTok = NULL;
char* pcError = NULL;
fgets(szLine, MAX_LINE_LENGTH, ifp);
szTok = strtok(szLine, DELIM);
nNA = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
aanAbund = (int **) malloc(nNA*sizeof(int*));
for(i = 0; i < nNA; i++){
aanAbund[i] = (int *) malloc(sizeof(int)*2);
fgets(szLine, MAX_LINE_LENGTH, ifp);
szTok = strtok(szLine, DELIM);
nA = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
szTok = strtok(NULL, DELIM);
nC = strtol(szTok,&pcError,10);
if(*pcError != '\0'){
goto formatError;
}
nL += nC;
nJ += nC*nA;
aanAbund[i][0] = nA;
aanAbund[i][1] = nC;
}
}
else{
fprintf(stderr, "Failed to open abundance data file %s aborting\n", szFile);
fflush(stderr);
exit(EXIT_FAILURE);
}
ptData->nJ = nJ;
ptData->nL = nL;
ptData->aanAbund = aanAbund;
ptData->nNA = nNA;
return;
formatError:
fprintf(stderr, "Incorrectly formatted abundance data file\n");
fflush(stderr);
exit(EXIT_FAILURE);
}
int compare_doubles(const void* a, const void* b)
{
double* arg1 = (double *) a;
double* arg2 = (double *) b;
if( *arg1 < *arg2 ) return -1;
else if( *arg1 == *arg2 ) return 0;
else return 1;
}
double chao(t_Data *ptData)
{
double n1 = 0.0, n2 = 0.0;
int **aanAbund = ptData->aanAbund;
if(aanAbund[0][0] == 1 && aanAbund[1][0] == 2){
n1 = (double) aanAbund[0][1]; n2 = (double) aanAbund[1][1];
return ((double) ptData->nL) + 0.5*((n1*n1)/n2);
}
else{
return -1.0;
}
}
double f1(double x, void *pvParams)
{
t_LSParams *ptLSParams = (t_LSParams *) pvParams;
double dMDash = ptLSParams->dMDash, dV = ptLSParams->dV, dNu = ptLSParams->dNu;
int n = ptLSParams->n;
double t = ((x - dMDash)*(x - dMDash))/dV;
double dExp = x*((double) n) - exp(x);
double dF = pow(1.0 + t/dNu, -0.5*(dNu + 1.0));
return exp(dExp)*dF;
}
double f1Log(double x, void *pvParams)
{
t_LNParams *ptLNParams = (t_LNParams *) pvParams;
double dMDash = ptLNParams->dMDash, dV = ptLNParams->dV;
int n = ptLNParams->n;
double dTemp = (x - dMDash);
double dExp = x*((double) n) - exp(x) - 0.5*((dTemp*dTemp)/dV);
double dRet = exp(dExp);
return dRet;
}
double derivExponent(double x, void *pvParams)
{
t_LNParams *ptLNParams = (t_LNParams *) pvParams;
double dMDash = ptLNParams->dMDash, dV = ptLNParams->dV, n = ptLNParams->n;
double dTemp = (x - dMDash)/dV, dRet = 0.0;
dRet = ((double) n) - exp(x) - dTemp;
return dRet;
}
double logStirlingsGamma(double dZ)
{
return 0.5*log(2.0*M_PI) + (dZ - 0.5)*log(dZ) - dZ;
}
double logLikelihoodQuad(int n, double dMDash, double dV, double dNu)
{
gsl_integration_workspace *ptGSLWS =
gsl_integration_workspace_alloc(1000);
double dLogFac1 = 0.0, dLogFacN = 0.0;
double dN = (double) n, dResult = 0.0, dError = 0.0, dPrecision = 0.0;
gsl_function tGSLF;
t_LSParams tLSParams;
double dEst = dMDash + ((double)n)*dV, dA = 0.0, dB = 0.0;
tLSParams.n = n; tLSParams.dMDash = dMDash; tLSParams.dV = dV; tLSParams.dNu = dNu;
tGSLF.function = &f1;
tGSLF.params = (void *) &tLSParams;
if(dNu < MAX_MU_GAMMA){
dLogFac1 = gsl_sf_lngamma(0.5*(dNu + 1.0)) - gsl_sf_lngamma(0.5*dNu) - 0.5*log(M_PI*dNu);
}
else{
dLogFac1 = 0.5*dNu*(log(0.5*(dNu + 1.0)) - log(0.5*dNu)) -0.5*log(2.0*M_PI) - 0.5;
}
if(n < 50){
dLogFacN = gsl_sf_fact(n);
dLogFacN = log(dLogFacN);
}
else if(n < 100){
dLogFacN = gsl_sf_lngamma(dN + 1.0);
}
else{
dLogFacN = logStirlingsGamma(dN + 1.0);
}
dA = -100.0; dB = 100.0;
if(n < 10){
dPrecision = HI_PRECISION;
}
else{
dPrecision = LO_PRECISION;
}
gsl_integration_qag(&tGSLF, dA, dB, dPrecision, 0.0, 1000, GSL_INTEG_GAUSS61, ptGSLWS, &dResult, &dError);
//printf("%f %f\n", dResult, dError);
gsl_integration_workspace_free(ptGSLWS);
return log(dResult) - dLogFacN + dLogFac1 - 0.5*log(dV);
}
int solveF(double x_lo, double x_hi, double (*f)(double, void*),
void* params, double tol, double *xsolve)
{
int status, iter = 0, max_iter = 100;
const gsl_root_fsolver_type *T;
gsl_root_fsolver *s;
double r = 0;
gsl_function F;
t_LNParams *ptLNParams = (t_LNParams *) params;
F.function = f;
F.params = params;
//printf("%f %f %d %f %f\n",ptLNParams->dMDash, ptLNParams->dV, ptLNParams->n, x_lo, x_hi);
T = gsl_root_fsolver_brent;
s = gsl_root_fsolver_alloc (T);
gsl_root_fsolver_set (s, &F, x_lo, x_hi);
do{
iter++;
status = gsl_root_fsolver_iterate (s);
r = gsl_root_fsolver_root (s);
x_lo = gsl_root_fsolver_x_lower (s);
x_hi = gsl_root_fsolver_x_upper (s);
status = gsl_root_test_interval (x_lo, x_hi, 0, tol);
}
while (status == GSL_CONTINUE && iter < max_iter);
(*xsolve) = gsl_root_fsolver_root (s);
gsl_root_fsolver_free (s);
return status;
}
double logLikelihoodLNQuad(int n, double dMDash, double dV)
{
gsl_integration_workspace *ptGSLWS =
gsl_integration_workspace_alloc(1000);
double dLogFac1 = 0.0, dLogFacN = 0.0;
double dResult = 0.0, dError = 0.0, dPrecision = 0.0;
gsl_function tGSLF;
t_LNParams tLNParams;
double dEst = dMDash + ((double)n)*dV, dA = 0.0, dB = 0.0;
tLNParams.n = n; tLNParams.dMDash = dMDash; tLNParams.dV = dV;
tGSLF.function = &f1Log;
tGSLF.params = (void *) &tLNParams;
dLogFac1 = log(2.0*M_PI*dV);
if(n < 50){
dLogFacN = gsl_sf_fact(n);
dLogFacN = log(dLogFacN);
}
else{
dLogFacN = gsl_sf_lngamma(((double) n) + 1.0);
}
if(dEst > dV){
double dMax = 0.0;
double dUpper = (((double) n) + (dMDash/dV) - 1.0)/(1.0 + 1.0/dV);
double dVar = 0.0;
if(fabs(dUpper) > 1.0e-7){
solveF(0.0, dUpper, derivExponent, (void *) &tLNParams, 1.0e-5, &dMax);
}
dVar = sqrt(1.0/((1.0/dV) + exp(dMax)));
dA = dMax - V_MULT*dVar; dB = dMax + V_MULT*dVar;
}
else{
double dMax = 0.0;
double dLower = dEst - dV;
double dUpper = (((double) n) + (dMDash/dV) - 1.0)/(1.0 + 1.0/dV);
double dVar = 0.0;
if(fabs(dUpper - dLower) > 1.0e-7){
solveF(dLower, dUpper, derivExponent, (void *) &tLNParams, 1.0e-5, &dMax);
}
else{
dMax = 0.5*(dLower + dUpper);
}
dVar = sqrt(1.0/((1.0/dV) + exp(dMax)));
dA = dMax - V_MULT*dVar; dB = dMax + V_MULT*dVar;
}
if(n < 10){
dPrecision = HI_PRECISION;
}
else{
dPrecision = LO_PRECISION;
}
gsl_integration_qag(&tGSLF, dA, dB, dPrecision, 0.0, 1000, GSL_INTEG_GAUSS61, ptGSLWS, &dResult, &dError);
gsl_integration_workspace_free(ptGSLWS);
return log(dResult) - dLogFacN -0.5*dLogFac1;
}
double logLikelihoodLNRampal(int n, double dMDash, double dV)
{
double dN = (double) n;
double dLogLik = 0.0, dTemp = gsl_pow_int(log(dN) - dMDash,2), dTemp3 = gsl_pow_int(log(dN) - dMDash,3);
dLogLik = -0.5*log(2.0*M_PI*dV) - log(dN) - (dTemp/(2.0*dV));
dLogLik += log(1.0 + 1.0/(2.0*dN*dV)*(dTemp/dV + log(dN) - dMDash - 1.0)
+ 1.0/(6.0*dN*dN*dV*dV*dV)*(3.0*dV*dV - (3.0*dV - 2.0*dV*dV)*(dMDash - log(dN))
- 3.0*dV*dTemp + dTemp3));
return dLogLik;
}
double logLikelihoodRampal(int n, double dMDash, double dV, double dNu)
{
double dGamma = 0.5*(dNu + 1.0), dN = (double) n, dRN = 1.0/dN, dRSV = 1.0/(sqrt(dV)*sqrt(dNu));
double dZ = (log(dN) - dMDash)*dRSV;
double dDZDX = dRN*dRSV, dDZDX2 = -dRN*dRN*dRSV;
double dF = (1.0 + dZ*dZ);
double dA = 0.0, dB = 0.0, dTemp = 0.0;
double dLogFac1 = 0.0;
if(dNu < MAX_MU_GAMMA){
dLogFac1 = gsl_sf_lngamma(0.5*(dNu + 1.0)) - gsl_sf_lngamma(0.5*dNu) - 0.5*log(M_PI*dNu);
}
else{
dLogFac1 = 0.5*dNu*(log(0.5*(dNu + 1.0)) - log(0.5*dNu)) -0.5*log(2.0*M_PI) - 0.5;
}
dA = 4.0*dZ*dZ*dDZDX*dDZDX*dGamma*(dGamma + 1.0);
dA /= dF*dF;
dB = -2.0*dGamma*(dDZDX*dDZDX + dZ*dDZDX2);
dB /= dF;
dTemp = dRN + dA + dB;
return -dGamma*log(dF) + log(dTemp) + dLogFac1 - 0.5*log(dV);
}
double nLogLikelihood(const gsl_vector * x, void * params)
{
double dMDash = gsl_vector_get(x,0), dV = gsl_vector_get(x,1);
double dNu = gsl_vector_get(x,2);
int nS = (int) floor(gsl_vector_get(x, 3));
t_Data *ptData = (t_Data *) params;
int i = 0;
double dLogNot0 = 0.0, dLogL = 0.0;
double dLog0 = 0.0, dLog1 = 0.0, dLog2 = 0.0, dLog3 = 0.0;
if(dV <= 0.0 || dNu < 1.0){
return PENALTY;
}
for(i = 0; i < ptData->nNA; i++){
double dLogP = 0.0;
int nA = ptData->aanAbund[i][0];
if(nA < MAX_QUAD){
dLogP = logLikelihoodQuad(nA, dMDash, dV, dNu);
}
else{
dLogP = logLikelihoodRampal(nA, dMDash, dV, dNu);
}
dLogL += ((double) ptData->aanAbund[i][1])*dLogP;
dLogL -= gsl_sf_lnfact(ptData->aanAbund[i][1]);
}
dLog0 = logLikelihoodQuad(0, dMDash, dV, dNu);
dLog1 = (nS - ptData->nL)*dLog0;
dLog2 = - gsl_sf_lnfact(nS - ptData->nL);
dLog3 = gsl_sf_lnfact(nS);
dLogL += dLog1 + dLog2 + dLog3;
/*return*/
return -dLogL;
}
double negLogLikelihood(double dMDash, double dV, double dNu, int nS, void * params)
{
t_Data *ptData = (t_Data *) params;
int i = 0;
double dLogNot0 = 0.0, dLogL = 0.0;
double dLog0 = 0.0, dLog1 = 0.0, dLog2 = 0.0, dLog3 = 0.0;
if(dV <= 0.0 || dNu < 1.0){
return PENALTY;
}
for(i = 0; i < ptData->nNA; i++){
double dLogP = 0.0;
int nA = ptData->aanAbund[i][0];
if(nA < MAX_QUAD){
dLogP = logLikelihoodQuad(nA, dMDash, dV, dNu);
}
else{
dLogP = logLikelihoodRampal(nA, dMDash, dV, dNu);
}
dLogL += ((double) ptData->aanAbund[i][1])*dLogP;
dLogL -= gsl_sf_lnfact(ptData->aanAbund[i][1]);
}
dLog0 = logLikelihoodQuad(0, dMDash, dV, dNu);
dLog1 = (nS - ptData->nL)*dLog0;
dLog2 = - gsl_sf_lnfact(nS - ptData->nL);
dLog3 = gsl_sf_lnfact(nS);
dLogL += dLog1 + dLog2 + dLog3;
/*return*/
return -dLogL;
}
int minimiseSimplex(gsl_vector* ptX, size_t nP, void* pvData, double (*f)(const gsl_vector*, void* params))
{
const gsl_multimin_fminimizer_type *T =
gsl_multimin_fminimizer_nmsimplex;
gsl_multimin_fminimizer *s = NULL;
gsl_vector *ss;
gsl_multimin_function minex_func;
size_t iter = 0;
int i = 0, status;
double size;
/* Initial vertex size vector */
ss = gsl_vector_alloc (nP);
/* Set all step sizes to default constant */
for(i = 0; i < nP; i++){
gsl_vector_set(ss, i,INIT_SIMPLEX_SIZE*fabs(gsl_vector_get(ptX,i)));
}
/* Initialize method and iterate */
minex_func.f = f;
minex_func.n = nP;
minex_func.params = pvData;
s = gsl_multimin_fminimizer_alloc (T, nP);
gsl_multimin_fminimizer_set(s, &minex_func, ptX, ss);
do{
iter++;
status = gsl_multimin_fminimizer_iterate(s);
if(status)
break;
size = gsl_multimin_fminimizer_size(s);
status = gsl_multimin_test_size(size, MIN_SIMPLEX_SIZE);
if(status == GSL_SUCCESS){
for(i = 0; i < nP; i++){
gsl_vector_set(ptX, i, gsl_vector_get(s->x, i));
}
if(verbose) printf("converged to minimum at\n");
}
if(verbose){
printf ("%5d ", iter);
for (i = 0; i < nP; i++) printf("%10.3e ", gsl_vector_get(s->x, i));
printf("f() = %7.3f size = %.3f\n", s->fval, size);
}
}
while(status == GSL_CONTINUE && iter < MAX_SIMPLEX_ITER);
for(i = 0; i < nP; i++){
gsl_vector_set(ptX, i, gsl_vector_get(s->x, i));
}
gsl_vector_free(ss);
gsl_multimin_fminimizer_free (s);
return status;
}
void freeAbundanceData(t_Data *ptData)
{
int i = 0;
for(i = 0; i < ptData->nNA; i++){
free(ptData->aanAbund[i]);
}
free(ptData->aanAbund);
}
void getProposal(gsl_rng *ptGSLRNG, gsl_vector *ptXDash, gsl_vector *ptX, int* pnSDash, int nS, t_Params *ptParams)
{
double dDeltaS = gsl_ran_gaussian(ptGSLRNG, ptParams->dSigmaS);
double dDeltaM = gsl_ran_gaussian(ptGSLRNG, ptParams->dSigmaM);
double dDeltaV = gsl_ran_gaussian(ptGSLRNG, ptParams->dSigmaV);
double dDeltaN = gsl_ran_gaussian(ptGSLRNG, ptParams->dSigmaN);
int nSDash = 0;
gsl_vector_set(ptXDash, 0, gsl_vector_get(ptX,0) + dDeltaM);
gsl_vector_set(ptXDash, 1, gsl_vector_get(ptX,1) + dDeltaV);
gsl_vector_set(ptXDash, 2, gsl_vector_get(ptX,2) + dDeltaN);
//printf("%e %e %e\n",dDeltaA,dDeltaB,dDeltaG);
nSDash = nS + (int) floor(dDeltaS);
if(nSDash < 1){
nSDash = 1;
}
(*pnSDash) = nSDash;
}
void outputResults(gsl_vector *ptX, t_Data *ptData)
{
double dAlpha = 0.0, dBeta = 0.0, dGamma = 0.0, dS = 0.0, dL = 0.0;
dAlpha = gsl_vector_get(ptX, 0);
dBeta = gsl_vector_get(ptX, 1);
dGamma = gsl_vector_get(ptX, 2);
dS = gsl_vector_get(ptX, 3);
dL = nLogLikelihood(ptX, ptData);
printf("\nML simplex: M = %.2f V = %.2f Nu = %.2f S = %.2f NLL = %.2f\n",dAlpha, dBeta, dGamma, dS, dL);
}
void* metropolis (void * pvInitMetro)
{
t_MetroInit *ptMetroInit = (t_MetroInit *) pvInitMetro;
gsl_vector *ptX = ptMetroInit->ptX;
t_Data *ptData = ptMetroInit->ptData;
t_Params *ptParams = ptMetroInit->ptParams;
gsl_vector *ptXDash = gsl_vector_alloc(4); /*proposal*/
char *szSampleFile = (char *) malloc(MAX_LINE_LENGTH*sizeof(char));
const gsl_rng_type *T;
gsl_rng *ptGSLRNG;
FILE *sfp = NULL;
int nS = 0, nSDash = 0, nIter = 0;
double dRand = 0.0, dNLL = 0.0;
void *pvRet = NULL;
/*set up random number generator*/
T = gsl_rng_default;
ptGSLRNG = gsl_rng_alloc (T);
nS = (int) floor(gsl_vector_get(ptX,3));
dNLL = negLogLikelihood(gsl_vector_get(ptX,0), gsl_vector_get(ptX,1), gsl_vector_get(ptX,2), nS,(void*) ptData);
sprintf(szSampleFile,"%s_%d%s", ptParams->szOutFileStub, ptMetroInit->nThread, SAMPLE_FILE_SUFFIX);
sfp = fopen(szSampleFile, "w");
if(!sfp){
exit(EXIT_FAILURE);
}
/*seed random number generator*/
gsl_rng_set(ptGSLRNG, ptMetroInit->lSeed);
/*now perform simple Metropolis algorithm*/
while(nIter < ptParams->nIter){
double dA = 0.0, dNLLDash = 0.0;
getProposal(ptGSLRNG, ptXDash, ptX, &nSDash, nS, ptParams);
dNLLDash = negLogLikelihood(gsl_vector_get(ptXDash,0), gsl_vector_get(ptXDash,1), gsl_vector_get(ptXDash,2), nSDash, (void*) ptData);
//printf("X' %e %e %e %d %f\n", gsl_vector_get(ptXDash,0), gsl_vector_get(ptXDash,1), gsl_vector_get(ptXDash,2), nSDash, dNLLDash);
//printf("X %e %e %e %d %f\n", gsl_vector_get(ptX,0), gsl_vector_get(ptX,1), gsl_vector_get(ptX,2), nS, dNLL);
dA = exp(dNLL - dNLLDash);
if(dA > 1.0){
dA = 1.0;
}
dRand = gsl_rng_uniform(ptGSLRNG);
if(dRand < dA){
gsl_vector_memcpy(ptX, ptXDash);
nS = nSDash;
dNLL = dNLLDash;
ptMetroInit->nAccepted++;
}
if(nIter % SLICE == 0){
fprintf(sfp, "%d,%.10e,%.10e,%.10e,%d,%f\n",nIter,gsl_vector_get(ptX, 0), gsl_vector_get(ptX, 1), gsl_vector_get(ptX, 2), nS, dNLL);
fflush(sfp);
}
nIter++;
}
fclose(sfp);
/*free up allocated memory*/
gsl_vector_free(ptXDash);
free(szSampleFile);
gsl_rng_free(ptGSLRNG);
return pvRet;
}
void writeThread(t_MetroInit *ptMetroInit)
{
gsl_vector *ptX = ptMetroInit->ptX;
printf("%d: a = %.2f b = %.2f g = %.2f S = %.2f\n", ptMetroInit->nThread,
gsl_vector_get(ptX, 0),
gsl_vector_get(ptX, 1),
gsl_vector_get(ptX, 2),
gsl_vector_get(ptX, 3));
}
void mcmc(t_Params *ptParams, t_Data *ptData, gsl_vector* ptX)
{
pthread_t thread1, thread2, thread3;
int iret1 , iret2 , iret3;
gsl_vector *ptX1 = gsl_vector_alloc(4),
*ptX2 = gsl_vector_alloc(4),
*ptX3 = gsl_vector_alloc(4);
t_MetroInit atMetroInit[3];
printf("\nMCMC iter = %d sigmaM = %.2f sigmaV = %.2f sigmaN = %.2f sigmaS = %.2f\n",
ptParams->nIter, ptParams->dSigmaM, ptParams->dSigmaV, ptParams->dSigmaN, ptParams->dSigmaS);
gsl_vector_memcpy(ptX1, ptX);
gsl_vector_set(ptX2, 0, gsl_vector_get(ptX,0) + 2.0*ptParams->dSigmaM);
gsl_vector_set(ptX2, 1, gsl_vector_get(ptX,1) + 2.0*ptParams->dSigmaV);
gsl_vector_set(ptX2, 2, gsl_vector_get(ptX,2) + 2.0*ptParams->dSigmaN);
gsl_vector_set(ptX2, 3, gsl_vector_get(ptX,3) + 2.0*ptParams->dSigmaS);
gsl_vector_set(ptX3, 0, gsl_vector_get(ptX,0) - 2.0*ptParams->dSigmaM);
gsl_vector_set(ptX3, 1, gsl_vector_get(ptX,1) - 2.0*ptParams->dSigmaV);
gsl_vector_set(ptX3, 2, gsl_vector_get(ptX,2) - 2.0*ptParams->dSigmaN);
if(gsl_vector_get(ptX,3) - 2.0*ptParams->dSigmaS > (double) ptData->nL){
gsl_vector_set(ptX3, 3, gsl_vector_get(ptX,3) - 2.0*ptParams->dSigmaS); }
else{
gsl_vector_set(ptX3, 3, (double) ptData->nL); }
atMetroInit[0].ptParams = ptParams;
atMetroInit[0].ptData = ptData;
atMetroInit[0].ptX = ptX1;
atMetroInit[0].nThread = 0;
atMetroInit[0].lSeed = ptParams->lSeed;
atMetroInit[0].nAccepted = 0;
atMetroInit[1].ptParams = ptParams;
atMetroInit[1].ptData = ptData;
atMetroInit[1].ptX = ptX2;
atMetroInit[1].nThread = 1;
atMetroInit[1].lSeed = ptParams->lSeed + 1;
atMetroInit[1].nAccepted = 0;
atMetroInit[2].ptParams = ptParams;
atMetroInit[2].ptData = ptData;
atMetroInit[2].ptX = ptX3;
atMetroInit[2].nThread = 2;
atMetroInit[2].lSeed = ptParams->lSeed + 2;
atMetroInit[2].nAccepted = 0;
writeThread(&atMetroInit[0]);
writeThread(&atMetroInit[1]);
writeThread(&atMetroInit[2]);
iret1 = pthread_create(&thread1, NULL, metropolis, (void*) &atMetroInit[0]);
iret2 = pthread_create(&thread2, NULL, metropolis, (void*) &atMetroInit[1]);
iret3 = pthread_create(&thread3, NULL, metropolis, (void*) &atMetroInit[2]);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
printf("%d: accept. ratio %d/%d = %f\n", atMetroInit[0].nThread,
atMetroInit[0].nAccepted, ptParams->nIter,((double) atMetroInit[0].nAccepted)/((double) ptParams->nIter));
printf("%d: accept. ratio %d/%d = %f\n", atMetroInit[1].nThread,
atMetroInit[1].nAccepted, ptParams->nIter,((double) atMetroInit[1].nAccepted)/((double) ptParams->nIter));
printf("%d: accept. ratio %d/%d = %f\n", atMetroInit[2].nThread,
atMetroInit[2].nAccepted, ptParams->nIter, ((double) atMetroInit[2].nAccepted)/((double) ptParams->nIter));
gsl_vector_free(ptX1); gsl_vector_free(ptX2); gsl_vector_free(ptX3);
}
| {
"alphanum_fraction": 0.61850891,
"avg_line_length": 25.9812154696,
"ext": "c",
"hexsha": "5eb57acb596630090fb1b7093cea841a4e1ebb8f",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "chrisquince/DiversityEstimates",
"max_forks_repo_path": "MetroLogStudent/MetroLogStudent.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "chrisquince/DiversityEstimates",
"max_issues_repo_path": "MetroLogStudent/MetroLogStudent.c",
"max_line_length": 142,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "chrisquince/DiversityEstimates",
"max_stars_repo_path": "MetroLogStudent/MetroLogStudent.c",
"max_stars_repo_stars_event_max_datetime": "2019-03-19T13:22:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-18T17:56:16.000Z",
"num_tokens": 8722,
"size": 23513
} |
/* multifit_nlinear/gsl_multifit_nlinear.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
* Copyright (C) 2015, 2016 Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_MULTIFIT_NLINEAR_H__
#define __GSL_MULTIFIT_NLINEAR_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permutation.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 enum
{
GSL_MULTIFIT_NLINEAR_FWDIFF,
GSL_MULTIFIT_NLINEAR_CTRDIFF
} gsl_multifit_nlinear_fdtype;
/* Definition of vector-valued functions and gradient with parameters
based on gsl_vector */
typedef struct
{
int (* f) (const gsl_vector * x, void * params, gsl_vector * f);
int (* df) (const gsl_vector * x, void * params, gsl_matrix * df);
int (* fvv) (const gsl_vector * x, const gsl_vector * v, void * params,
gsl_vector * fvv);
size_t n; /* number of functions */
size_t p; /* number of independent variables */
void * params; /* user parameters */
size_t nevalf; /* number of function evaluations */
size_t nevaldf; /* number of Jacobian evaluations */
size_t nevalfvv; /* number of fvv evaluations */
} gsl_multifit_nlinear_fdf;
/* trust region subproblem method */
typedef struct
{
const char *name;
void * (*alloc) (const void * params, const size_t n, const size_t p);
int (*init) (const void * vtrust_state, void * vstate);
int (*preloop) (const void * vtrust_state, void * vstate);
int (*step) (const void * vtrust_state, const double delta,
gsl_vector * dx, void * vstate);
int (*preduction) (const void * vtrust_state, const gsl_vector * dx,
double * pred, void * vstate);
void (*free) (void * vstate);
} gsl_multifit_nlinear_trs;
/* scaling matrix specification */
typedef struct
{
const char *name;
int (*init) (const gsl_matrix * J, gsl_vector * diag);
int (*update) (const gsl_matrix * J, gsl_vector * diag);
} gsl_multifit_nlinear_scale;
/*
* linear least squares solvers - there are three steps to
* solving a least squares problem using a trust region
* method:
*
* 1. init: called once per iteration when a new Jacobian matrix
* is computed; perform factorization of Jacobian (qr,svd)
* or form normal equations matrix (cholesky)
* 2. presolve: called each time a new LM parameter value mu is available;
* used for cholesky method in order to factor
* the (J^T J + mu D^T D) matrix
* 3. solve: solve the least square system for a given rhs
*/
typedef struct
{
const char *name;
void * (*alloc) (const size_t n, const size_t p);
int (*init) (const void * vtrust_state, void * vstate);
int (*presolve) (const double mu, const void * vtrust_state, void * vstate);
int (*solve) (const gsl_vector * f, gsl_vector * x,
const void * vtrust_state, void * vstate);
int (*rcond) (double * rcond, void * vstate);
void (*free) (void * vstate);
} gsl_multifit_nlinear_solver;
/* tunable parameters */
typedef struct
{
const gsl_multifit_nlinear_trs *trs; /* trust region subproblem method */
const gsl_multifit_nlinear_scale *scale; /* scaling method */
const gsl_multifit_nlinear_solver *solver; /* solver method */
gsl_multifit_nlinear_fdtype fdtype; /* finite difference method */
double factor_up; /* factor for increasing trust radius */
double factor_down; /* factor for decreasing trust radius */
double avmax; /* max allowed |a|/|v| */
double h_df; /* step size for finite difference Jacobian */
double h_fvv; /* step size for finite difference fvv */
} gsl_multifit_nlinear_parameters;
typedef struct
{
const char *name;
void * (*alloc) (const gsl_multifit_nlinear_parameters * params,
const size_t n, const size_t p);
int (*init) (void * state, const gsl_vector * wts,
gsl_multifit_nlinear_fdf * fdf, const gsl_vector * x,
gsl_vector * f, gsl_matrix * J, gsl_vector * g);
int (*iterate) (void * state, const gsl_vector * wts,
gsl_multifit_nlinear_fdf * fdf, gsl_vector * x,
gsl_vector * f, gsl_matrix * J, gsl_vector * g,
gsl_vector * dx);
int (*rcond) (double * rcond, void * state);
double (*avratio) (void * state);
void (*free) (void * state);
} gsl_multifit_nlinear_type;
/* current state passed to low-level trust region algorithms */
typedef struct
{
const gsl_vector * x; /* parameter values x */
const gsl_vector * f; /* residual vector f(x) */
const gsl_vector * g; /* gradient J^T f */
const gsl_matrix * J; /* Jacobian J(x) */
const gsl_vector * diag; /* scaling matrix D */
const gsl_vector * sqrt_wts; /* sqrt(diag(W)) or NULL for unweighted */
const double *mu; /* LM parameter */
const gsl_multifit_nlinear_parameters * params;
void *solver_state; /* workspace for linear least squares solver */
gsl_multifit_nlinear_fdf * fdf;
double *avratio; /* |a| / |v| */
} gsl_multifit_nlinear_trust_state;
typedef struct
{
const gsl_multifit_nlinear_type * type;
gsl_multifit_nlinear_fdf * fdf ;
gsl_vector * x; /* parameter values x */
gsl_vector * f; /* residual vector f(x) */
gsl_vector * dx; /* step dx */
gsl_vector * g; /* gradient J^T f */
gsl_matrix * J; /* Jacobian J(x) */
gsl_vector * sqrt_wts_work; /* sqrt(W) */
gsl_vector * sqrt_wts; /* ptr to sqrt_wts_work, or NULL if not using weights */
size_t niter; /* number of iterations performed */
gsl_multifit_nlinear_parameters params;
void *state;
} gsl_multifit_nlinear_workspace;
gsl_multifit_nlinear_workspace *
gsl_multifit_nlinear_alloc (const gsl_multifit_nlinear_type * T,
const gsl_multifit_nlinear_parameters * params,
size_t n, size_t p);
void gsl_multifit_nlinear_free (gsl_multifit_nlinear_workspace * w);
gsl_multifit_nlinear_parameters gsl_multifit_nlinear_default_parameters(void);
int
gsl_multifit_nlinear_init (const gsl_vector * x,
gsl_multifit_nlinear_fdf * fdf,
gsl_multifit_nlinear_workspace * w);
int gsl_multifit_nlinear_winit (const gsl_vector * x,
const gsl_vector * wts,
gsl_multifit_nlinear_fdf * fdf,
gsl_multifit_nlinear_workspace * w);
int
gsl_multifit_nlinear_iterate (gsl_multifit_nlinear_workspace * w);
double
gsl_multifit_nlinear_avratio (const gsl_multifit_nlinear_workspace * w);
int
gsl_multifit_nlinear_driver (const size_t maxiter,
const double xtol,
const double gtol,
const double ftol,
void (*callback)(const size_t iter, void *params,
const gsl_multifit_nlinear_workspace *w),
void *callback_params,
int *info,
gsl_multifit_nlinear_workspace * w);
gsl_matrix *
gsl_multifit_nlinear_jac (const gsl_multifit_nlinear_workspace * w);
const char *
gsl_multifit_nlinear_name (const gsl_multifit_nlinear_workspace * w);
gsl_vector *
gsl_multifit_nlinear_position (const gsl_multifit_nlinear_workspace * w);
gsl_vector *
gsl_multifit_nlinear_residual (const gsl_multifit_nlinear_workspace * w);
size_t
gsl_multifit_nlinear_niter (const gsl_multifit_nlinear_workspace * w);
int
gsl_multifit_nlinear_rcond (double *rcond, const gsl_multifit_nlinear_workspace * w);
const char *
gsl_multifit_nlinear_trs_name (const gsl_multifit_nlinear_workspace * w);
int gsl_multifit_nlinear_eval_f(gsl_multifit_nlinear_fdf *fdf,
const gsl_vector *x,
const gsl_vector *swts,
gsl_vector *y);
int gsl_multifit_nlinear_eval_df(const gsl_vector *x,
const gsl_vector *f,
const gsl_vector *swts,
const double h,
const gsl_multifit_nlinear_fdtype fdtype,
gsl_multifit_nlinear_fdf *fdf,
gsl_matrix *df, gsl_vector *work);
int
gsl_multifit_nlinear_eval_fvv(const double h,
const gsl_vector *x,
const gsl_vector *v,
const gsl_vector *f,
const gsl_matrix *J,
const gsl_vector *swts,
gsl_multifit_nlinear_fdf *fdf,
gsl_vector *yvv, gsl_vector *work);
/* covar.c */
int
gsl_multifit_nlinear_covar (const gsl_matrix * J, const double epsrel,
gsl_matrix * covar);
/* convergence.c */
int
gsl_multifit_nlinear_test (const double xtol, const double gtol,
const double ftol, int *info,
const gsl_multifit_nlinear_workspace * w);
/* fdjac.c */
int
gsl_multifit_nlinear_df(const double h, const gsl_multifit_nlinear_fdtype fdtype,
const gsl_vector *x, const gsl_vector *wts,
gsl_multifit_nlinear_fdf *fdf,
const gsl_vector *f, gsl_matrix *J, gsl_vector *work);
/* fdfvv.c */
int
gsl_multifit_nlinear_fdfvv(const double h, const gsl_vector *x, const gsl_vector *v,
const gsl_vector *f, const gsl_matrix *J,
const gsl_vector *swts, gsl_multifit_nlinear_fdf *fdf,
gsl_vector *fvv, gsl_vector *work);
/* top-level algorithms */
GSL_VAR const gsl_multifit_nlinear_type * gsl_multifit_nlinear_trust;
/* trust region subproblem methods */
GSL_VAR const gsl_multifit_nlinear_trs * gsl_multifit_nlinear_trs_lm;
GSL_VAR const gsl_multifit_nlinear_trs * gsl_multifit_nlinear_trs_lmaccel;
GSL_VAR const gsl_multifit_nlinear_trs * gsl_multifit_nlinear_trs_dogleg;
GSL_VAR const gsl_multifit_nlinear_trs * gsl_multifit_nlinear_trs_ddogleg;
GSL_VAR const gsl_multifit_nlinear_trs * gsl_multifit_nlinear_trs_subspace2D;
/* scaling matrix strategies */
GSL_VAR const gsl_multifit_nlinear_scale * gsl_multifit_nlinear_scale_levenberg;
GSL_VAR const gsl_multifit_nlinear_scale * gsl_multifit_nlinear_scale_marquardt;
GSL_VAR const gsl_multifit_nlinear_scale * gsl_multifit_nlinear_scale_more;
/* linear solvers */
GSL_VAR const gsl_multifit_nlinear_solver * gsl_multifit_nlinear_solver_cholesky;
GSL_VAR const gsl_multifit_nlinear_solver * gsl_multifit_nlinear_solver_qr;
GSL_VAR const gsl_multifit_nlinear_solver * gsl_multifit_nlinear_solver_svd;
__END_DECLS
#endif /* __GSL_MULTIFIT_NLINEAR_H__ */
| {
"alphanum_fraction": 0.6497015915,
"avg_line_length": 39.6842105263,
"ext": "h",
"hexsha": "4e1828c1f5f08775b11e4847e3310edcd7fbb717",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-06-13T05:31:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-12-20T16:50:58.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/multifit_nlinear/gsl_multifit_nlinear.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/multifit_nlinear/gsl_multifit_nlinear.h",
"max_line_length": 92,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "0ad5e82b49a973cf710f85daa9dffc45261b36ae",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Tjoppen/fmigo",
"max_stars_repo_path": "3rdparty/wingsl/include/gsl/gsl_multifit_nlinear.h",
"max_stars_repo_stars_event_max_datetime": "2021-05-14T07:38:05.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-18T16:35:21.000Z",
"num_tokens": 3004,
"size": 12064
} |
/* Copyright (c) 2014, Giuseppe Argentieri <giuseppe.argentieri@ts.infn.it>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
/*
*
*
* Filename: initial.h
*
* Description: Initial values
*
* Version: 1.0
* Created: 16/05/2014 00:44:34
* Revision: none
* License: BSD
*
* Author: Giuseppe Argentieri (ga), giuseppe.argentieri@ts.infn.it
* Organization: Università degli Studi di Trieste
*
*
*/
#include <gsl/gsl_const_mksa.h>
#define BOLTZ GSL_CONST_MKSA_BOLTZMANN /* Boltzmann constant */
#define HBAR GSL_CONST_MKSA_PLANCKS_CONSTANT_HBAR /* hbar */
const double omega_c = 1000 ; /* critical ohmic frequency */
const double alpha = 5e-3 ; /* coupling strength */
const double Delta = 8.0e+9 ; /* pumping amplitude (GHz) */
double T = .1 ; /*
* The real temperature is given by
* temp = T*HBAR*Delta/BOLTZ
*
* HBAR*Delta/BOLTZ = 0.061
*
*/
const double D = 1 ; /* normalized delta */
double OMEGA = 2 ; /* normalized pumping frequency */
const double gamma0 = 0.05 ; /* energy hopping between sites */
const double t_end = 200 ; /* time end */
const double STEP = .01 ; /* time step */
const double R[] = { 1, 0, 0.5, -0.4 } ; /* initial state: |z,-> */
/* const double R[] = { 1, 0, 0.5, -0.4 } ; */ /* initial state with neg. e.p. */
/* const double r[] = { 1, 0, 1, 0 } ; initial state with pos. t.d. */
| {
"alphanum_fraction": 0.6688264939,
"avg_line_length": 36.0779220779,
"ext": "h",
"hexsha": "d248cb3ee03b45b7c141d794e3d3c5613dd5fefc",
"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": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "j-silver/quantum_dots",
"max_forks_repo_path": "initial.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"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": "j-silver/quantum_dots",
"max_issues_repo_path": "initial.h",
"max_line_length": 81,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "54132a3c7dd0e83e27375f6c5f6ec154065a9695",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "j-silver/quantum_dots",
"max_stars_repo_path": "initial.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 739,
"size": 2778
} |
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mpi.h>
#include <gsl/gsl_sf_gamma.h>
#include "allvars.h"
#include "proto.h"
#ifdef COSMIC_RAYS
#include "cosmic_rays.h"
#endif
#ifdef CS_MODEL
#include "cs_metals.h"
#endif
#ifdef MACHNUM
#ifdef COSMIC_RAYS
#define h All.HubbleParam
#define cm (h/All.UnitLength_in_cm)
#define s (h/All.UnitTime_in_s)
#define LightSpeed (2.9979e10*cm/s)
#define c2 ( LightSpeed * LightSpeed )
#endif
#endif
/*! \file init.c
* \brief code for initialisation of a simulation from initial conditions
*/
/*! This function reads the initial conditions, and allocates storage for the
* tree(s). Various variables of the particle data are initialised and An
* intial domain decomposition is performed. If SPH particles are present,
* the inial SPH smoothing lengths are determined.
*/
void init(void)
{
int i, j;
double a3, atime;
#ifdef COSMIC_RAYS
int CRpop;
#endif
#if defined(COSMIC_RAYS) && defined(MACHNUM)
double Pth1, PCR1[NUMCRPOP], rBeta[NUMCRPOP], C_phys[NUMCRPOP], q_phys[NUMCRPOP];
#endif
#ifdef CR_INITPRESSURE
double cr_pressure, q_phys, C_phys[NUMCRPOP];
#endif
#ifdef BLACK_HOLES
int count_holes = 0;
#endif
#ifdef CHEMISTRY
int ifunc;
double min_t_cool, max_t_cool;
double min_t_elec, max_t_elec;
double a_start, a_end;
#endif
#ifdef EULERPOTENTIALS
double a0, a1, a2;
double b0, b1, b2;
#endif
#ifdef START_WITH_EXTRA_NGBDEV
double MaxNumNgbDeviationMerk;
#endif
#ifdef DISTORTIONTENSORPS
int i1, i2;
#endif
All.Time = All.TimeBegin;
if(RestartFlag == 3 && RestartSnapNum < 0)
{
if(ThisTask == 0)
printf("Need to give the snapshot number if FOF/SUBFIND is selected for output\n");
endrun(0);
}
if(RestartFlag == 4 && RestartSnapNum < 0)
{
if(ThisTask == 0)
printf("Need to give the snapshot number if snapshot should be converted\n");
endrun(0);
}
switch (All.ICFormat)
{
case 1:
case 2:
case 3:
case 4:
if(RestartFlag >= 2 && RestartSnapNum >= 0)
{
char fname[1000];
if(All.NumFilesPerSnapshot > 1)
sprintf(fname, "%s/snapdir_%03d/%s_%03d", All.OutputDir, RestartSnapNum, All.SnapshotFileBase,
RestartSnapNum);
else
sprintf(fname, "%s%s_%03d", All.OutputDir, All.SnapshotFileBase, RestartSnapNum);
read_ic(fname);
if(RestartFlag == 4)
{
sprintf(All.SnapshotFileBase, "%s_converted", All.SnapshotFileBase);
if(ThisTask == 0)
printf("Start writing file %s\n", All.SnapshotFileBase);
printf("RestartSnapNum %d\n", RestartSnapNum);
savepositions(RestartSnapNum);
endrun(0);
}
}
else
{
if(All.ICFormat == 4)
read_ic_cluster(All.InitCondFile);
else
read_ic(All.InitCondFile);
}
break;
default:
if(ThisTask == 0)
printf("ICFormat=%d not supported.\n", All.ICFormat);
endrun(0);
}
All.Time = All.TimeBegin;
#ifdef COOLING
#ifdef CS_MODEL
if(RestartFlag == 0)
XH = HYDROGEN_MASSFRAC;
#endif
IonizeParams();
#endif
#ifdef CHEMISTRY
InitChem();
#endif
if(All.ComovingIntegrationOn)
{
All.Timebase_interval = (log(All.TimeMax) - log(All.TimeBegin)) / TIMEBASE;
All.Ti_Current = 0;
a3 = All.Time * All.Time * All.Time;
atime = All.Time;
}
else
{
All.Timebase_interval = (All.TimeMax - All.TimeBegin) / TIMEBASE;
All.Ti_Current = 0;
a3 = 1;
atime = 1;
}
#ifdef RADTRANSFER
All.Radiation_Ti_begstep = 0;
#endif
set_softenings();
All.NumCurrentTiStep = 0; /* setup some counters */
All.SnapshotFileCount = 0;
if(RestartFlag == 2)
{
if(RestartSnapNum < 0)
All.SnapshotFileCount = atoi(All.InitCondFile + strlen(All.InitCondFile) - 3) + 1;
else
All.SnapshotFileCount = RestartSnapNum + 1;
}
#ifdef OUTPUTLINEOFSIGHT
All.Ti_nextlineofsight = (int) (log(All.TimeFirstLineOfSight / All.TimeBegin) / All.Timebase_interval);
if(RestartFlag == 2)
endrun(78787);
#endif
All.TotNumOfForces = 0;
All.NumForcesSinceLastDomainDecomp = 0;
#if defined(MAGNETIC) && defined(BSMOOTH)
#ifdef SETMAINTIMESTEPCOUNT
All.MainTimestepCounts = All.MainTimestepCountIni;
#else
All.MainTimestepCounts = 0;
#endif
#endif
All.TopNodeAllocFactor = 0.008;
All.TreeAllocFactor = 0.7;
All.Cadj_Cost = 1.0e-30;
All.Cadj_Cpu = 1.0e-3;
if(All.ComovingIntegrationOn)
if(All.PeriodicBoundariesOn == 1)
check_omega();
All.TimeLastStatistics = All.TimeBegin - All.TimeBetStatistics;
#ifdef BLACK_HOLES
All.TimeNextBlackHoleCheck = All.TimeBegin;
#endif
#ifdef BUBBLES
if(All.ComovingIntegrationOn)
All.TimeOfNextBubble = 1. / (1. + All.FirstBubbleRedshift);
else
All.TimeOfNextBubble = All.TimeBegin + All.BubbleTimeInterval / All.UnitTime_in_Megayears;
if(ThisTask == 0)
printf("Initial time: %g and first bubble time %g \n", All.TimeBegin, All.TimeOfNextBubble);
if(RestartFlag == 2 && All.TimeBegin > All.TimeOfNextBubble)
{
printf("Restarting from the snapshot file with the wrong FirstBubbleRedshift! \n");
endrun(0);
}
#endif
#ifdef MULTI_BUBBLES
if(All.ComovingIntegrationOn)
All.TimeOfNextBubble = 1. / (1. + All.FirstBubbleRedshift);
else
All.TimeOfNextBubble = All.TimeBegin + All.BubbleTimeInterval / All.UnitTime_in_Megayears;
if(ThisTask == 0)
printf("Initial time: %g and time of the first bubbles %g \n", All.TimeBegin, All.TimeOfNextBubble);
if(RestartFlag == 2 && All.TimeBegin > All.TimeOfNextBubble)
{
printf("Restarting from the snapshot file with the wrong FirstBubbleRedshift! \n");
endrun(0);
}
#endif
if(All.ComovingIntegrationOn) /* change to new velocity variable */
{
for(i = 0; i < NumPart; i++)
for(j = 0; j < 3; j++)
P[i].Vel[j] *= sqrt(All.Time) * All.Time;
}
#ifdef REINIT_AT_TURNAROUND
double turnaround_radius_local=0.0, turnaround_radius_global=0.0, v_part, r_part;
/* get local turnaroundradius */
for (i = 0; i < NumPart; i++)
{
r_part = sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]);
v_part = (P[i].Pos[0]*P[i].Vel[0]+P[i].Pos[1]*P[i].Vel[1]+P[i].Pos[2]*P[i].Vel[2]);
if ((v_part < 0.0) && (r_part > turnaround_radius_local)) turnaround_radius_local = r_part;
}
/* find global turnaround radius by taking maximum of all CPUs */
MPI_Allreduce(&turnaround_radius_local, &turnaround_radius_global, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
All.CurrentTurnaroundRadius = turnaround_radius_global;
if (ThisTask == 0)
{
printf("REINIT_AT_TURNAROUND: current (initial) turnaround radius = %g\n", All.CurrentTurnaroundRadius);
fflush(stdout);
}
#endif
for(i = 0; i < NumPart; i++) /* start-up initialization */
{
for(j = 0; j < 3; j++)
P[i].g.GravAccel[j] = 0;
#ifdef DISTORTIONTENSORPS
/*init tidal tensor for first output (this is not used for any calculation) */
for(i1 = 0; i1 < 3; i1++)
for(i2 = 0; i2 < 3; i2++)
P[i].tidal_tensorps[i1][i2] = 0.0;
/* find caustics on the fly by sign analysis of configuration space distortion */
P[i].last_stream_determinant = 1.0;
#ifdef DISTORTION_READALL
MyDouble product_matrix[3][3];
product_matrix[0][0] = P[i].distortion_tensorps[0][0] +
P[i].distortion_tensorps[0][3] * P[i].V_matrix[0][0] +
P[i].distortion_tensorps[0][4] * P[i].V_matrix[1][0] +
P[i].distortion_tensorps[0][5] * P[i].V_matrix[2][0];
product_matrix[0][1] = P[i].distortion_tensorps[0][1] +
P[i].distortion_tensorps[0][3] * P[i].V_matrix[0][1] +
P[i].distortion_tensorps[0][4] * P[i].V_matrix[1][1] +
P[i].distortion_tensorps[0][5] * P[i].V_matrix[2][1];
product_matrix[0][2] = P[i].distortion_tensorps[0][2] +
P[i].distortion_tensorps[0][3] * P[i].V_matrix[0][2] +
P[i].distortion_tensorps[0][4] * P[i].V_matrix[1][2] +
P[i].distortion_tensorps[0][5] * P[i].V_matrix[2][2];
product_matrix[1][0] = P[i].distortion_tensorps[1][0] +
P[i].distortion_tensorps[1][3] * P[i].V_matrix[0][0] +
P[i].distortion_tensorps[1][4] * P[i].V_matrix[1][0] +
P[i].distortion_tensorps[1][5] * P[i].V_matrix[2][0];
product_matrix[1][1] = P[i].distortion_tensorps[1][1] +
P[i].distortion_tensorps[1][3] * P[i].V_matrix[0][1] +
P[i].distortion_tensorps[1][4] * P[i].V_matrix[1][1] +
P[i].distortion_tensorps[1][5] * P[i].V_matrix[2][1];
product_matrix[1][2] = P[i].distortion_tensorps[1][2] +
P[i].distortion_tensorps[1][3] * P[i].V_matrix[0][2] +
P[i].distortion_tensorps[1][4] * P[i].V_matrix[1][2] +
P[i].distortion_tensorps[1][5] * P[i].V_matrix[2][2];
product_matrix[2][0] = P[i].distortion_tensorps[2][0] +
P[i].distortion_tensorps[2][3] * P[i].V_matrix[0][0] +
P[i].distortion_tensorps[2][4] * P[i].V_matrix[1][0] +
P[i].distortion_tensorps[2][5] * P[i].V_matrix[2][0];
product_matrix[2][1] = P[i].distortion_tensorps[2][1] +
P[i].distortion_tensorps[2][3] * P[i].V_matrix[0][1] +
P[i].distortion_tensorps[2][4] * P[i].V_matrix[1][1] +
P[i].distortion_tensorps[2][5] * P[i].V_matrix[2][1];
product_matrix[2][2] = P[i].distortion_tensorps[2][2] +
P[i].distortion_tensorps[2][3] * P[i].V_matrix[0][2] +
P[i].distortion_tensorps[2][4] * P[i].V_matrix[1][2] +
P[i].distortion_tensorps[2][5] * P[i].V_matrix[2][2];
/* this determinant will change sign when we pass through a caustic -> criterion for caustics */
P[i].last_stream_determinant = ((product_matrix[0][0]) * (product_matrix[1][1]) * (product_matrix[2][2]) +
(product_matrix[0][1]) * (product_matrix[1][2]) * (product_matrix[2][0]) +
(product_matrix[0][2]) * (product_matrix[1][0]) * (product_matrix[2][1]) -
(product_matrix[0][2]) * (product_matrix[1][1]) * (product_matrix[2][0]) -
(product_matrix[0][0]) * (product_matrix[1][2]) * (product_matrix[2][1]) -
(product_matrix[0][1]) * (product_matrix[1][0]) * (product_matrix[2][2]));
#endif
#ifdef ANNIHILATION_RADIATION
/* integrated annihilation rate */
P[i].annihilation = 0.0;
P[i].rho_normed_cutoff_current = 1.0;
P[i].rho_normed_cutoff_last = 1.0;
P[i].stream_density = P[i].init_density;
P[i].analytic_caustics = 0.0;
#endif
#ifdef REINIT_AT_TURNAROUND
All.SIM_epsilon = REINIT_AT_TURNAROUND;
/* no phase-space analysis for particles that are initially within the turnaround radius */
if (sqrt(P[i].Pos[0]*P[i].Pos[0] + P[i].Pos[1]*P[i].Pos[1] + P[i].Pos[2]*P[i].Pos[2]) < All.CurrentTurnaroundRadius)
#ifdef DISTORTION_READALL
P[i].turnaround_flag = 1;
#else
P[i].turnaround_flag = -1;
#endif
else
P[i].turnaround_flag = 0;
#endif
#ifdef OUTPUT_LAST_CAUSTIC
/* all entries zero -> no caustic yet */
P[i].lc_Time = 0.0;
P[i].lc_Pos[0] = 0.0;
P[i].lc_Pos[1] = 0.0;
P[i].lc_Pos[2] = 0.0;
P[i].lc_Vel[0] = 0.0;
P[i].lc_Vel[1] = 0.0;
P[i].lc_Vel[2] = 0.0;
P[i].lc_rho_normed_cutoff = 0.0;
P[i].lc_Dir_x[0] = 0.0;
P[i].lc_Dir_x[1] = 0.0;
P[i].lc_Dir_x[2] = 0.0;
P[i].lc_Dir_y[0] = 0.0;
P[i].lc_Dir_y[1] = 0.0;
P[i].lc_Dir_y[2] = 0.0;
P[i].lc_Dir_z[0] = 0.0;
P[i].lc_Dir_z[1] = 0.0;
P[i].lc_Dir_z[2] = 0.0;
P[i].lc_smear_x = 0.0;
P[i].lc_smear_y = 0.0;
P[i].lc_smear_z = 0.0;
#endif
#ifdef PMGRID
/* long range tidal field init */
P[i].tidal_tensorpsPM[0][0] = 0;
P[i].tidal_tensorpsPM[0][1] = 0;
P[i].tidal_tensorpsPM[0][2] = 0;
P[i].tidal_tensorpsPM[1][0] = 0;
P[i].tidal_tensorpsPM[1][1] = 0;
P[i].tidal_tensorpsPM[1][2] = 0;
P[i].tidal_tensorpsPM[2][0] = 0;
P[i].tidal_tensorpsPM[2][1] = 0;
P[i].tidal_tensorpsPM[2][2] = 0;
#endif
#ifndef DISTORTION_READALL
/*6D phase space distortion tensor equals unity in the beginning */
/*
* Distortion tensor D' (comoving) equals unity in the beginning
* So the initial stream density is given by |det(D')|*mean density
*/
/* cold dark matter => velocity dispersion=0 => d/dtD' = 0 => Z'=0 (comoving) */
for(i1 = 0; i1 < 6; i1++)
for(i2 = 0; i2 < 6; i2++)
{
if((i1 == i2))
{
P[i].distortion_tensorps[i1][i2] = 1.0;
}
else
{
P[i].distortion_tensorps[i1][i2] = 0.0;
}
}
#endif
#endif
#ifdef KEEP_DM_HSML_AS_GUESS
if(RestartFlag != 1)
P[i].DM_Hsml = -1;
#endif
#ifdef PMGRID
for(j = 0; j < 3; j++)
P[i].GravPM[j] = 0;
#endif
P[i].Ti_begstep = 0;
P[i].Ti_current = 0;
P[i].TimeBin = 0;
if(header.flag_ic_info != FLAG_SECOND_ORDER_ICS)
P[i].OldAcc = 0; /* Do not zero in 2lpt case as masses are stored here */
P[i].GravCost = 1;
#if defined(EVALPOTENTIAL) || defined(COMPUTE_POTENTIAL_ENERGY)
P[i].p.Potential = 0;
#endif
#ifdef STELLARAGE
if(RestartFlag == 0)
P[i].StellarAge = 0;
#endif
#ifdef METALS
#ifndef CS_MODEL
if(RestartFlag == 0)
P[i].Metallicity = 0;
#else
if(RestartFlag == 0)
{
for(j = 0; j < 12; j++)
{
P[i].Zm[j] = 0;
P[i].ZmReservoir[j] = 0;
}
P[i].Zm[6] = HYDROGEN_MASSFRAC * (P[i].Mass);
P[i].Zm[0] = (1 - HYDROGEN_MASSFRAC) * (P[i].Mass);
/* Order of chemical elements: He, Carbon,Mg,O,Fe,Si,H,N,Ne,S,Ca,Zn */
PPP[i].Hsml = 0;
#ifdef CS_FEEDBACK
PPP[i].EnergySN = 0;
PPP[i].EnergySNCold = 0;
#endif
}
#endif
#endif
#ifdef BLACK_HOLES
if(P[i].Type == 5)
{
count_holes++;
if(RestartFlag == 0)
P[i].BH_Mass = All.SeedBlackHoleMass;
#ifdef BH_BUBBLES
if(RestartFlag == 0)
{
P[i].BH_Mass_bubbles = All.SeedBlackHoleMass;
P[i].BH_Mass_ini = All.SeedBlackHoleMass;
#ifdef UNIFIED_FEEDBACK
P[i].BH_Mass_radio = All.SeedBlackHoleMass;
#endif
}
#endif
}
#endif
}
#ifdef BLACK_HOLES
MPI_Allreduce(&count_holes, &All.TotBHs, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
#endif
for(i = 0; i < TIMEBINS; i++)
TimeBinActive[i] = 1;
reconstruct_timebins();
#ifdef PMGRID
All.PM_Ti_endstep = All.PM_Ti_begstep = 0;
#endif
#ifdef CONDUCTION
All.Conduction_Ti_endstep = All.Conduction_Ti_begstep = 0;
#endif
#ifdef CR_DIFFUSION
All.CR_Diffusion_Ti_endstep = All.CR_Diffusion_Ti_begstep = 0;
#endif
for(i = 0; i < N_gas; i++) /* initialize sph_properties */
{
for(j = 0; j < 3; j++)
{
SphP[i].VelPred[j] = P[i].Vel[j];
SphP[i].a.HydroAccel[j] = 0;
}
SphP[i].e.DtEntropy = 0;
#ifdef CHEMISTRY
SphP[i].Gamma = GAMMA; /* set universal value */
SphP[i].t_cool = 0;
SphP[i].t_elec = 0;
#endif
#ifdef CS_MODEL
SphP[i].DensityOld = 0;
#endif
#ifdef CS_FEEDBACK
SphP[i].da.DensityAvg = 0;
SphP[i].ea.EntropyAvg = 0;
SphP[i].DensPromotion = 0;
SphP[i].TempPromotion = 0;
SphP[i].HotHsml = 0;
#endif
if(RestartFlag == 0)
{
#ifndef READ_HSML
PPP[i].Hsml = 0;
#endif
SphP[i].d.Density = -1;
#ifdef VOLUME_CORRECTION
SphP[i].DensityOld = 1;
#endif
#ifdef COOLING
SphP[i].Ne = 1.0;
#endif
SphP[i].v.DivVel = 0;
}
#ifdef WINDS
SphP[i].DelayTime = 0;
#endif
#ifdef SFR
SphP[i].Sfr = 0;
#endif
#ifdef MAGNETIC
#ifdef BINISET
SphP[i].BPred[0] = All.BiniX;
SphP[i].BPred[1] = All.BiniY;
SphP[i].BPred[2] = All.BiniZ;
#ifdef EULERPOTENTIALS
if(All.BiniY == 0 && All.BiniZ == 0)
{
a0 = 0;
a1 = All.BiniX;
a2 = 0;
b0 = 0;
b1 = 1;
b2 = 1;
}
else
{
if(All.BiniX != 0 && (All.BiniY != 0 || All.BiniZ != 0))
{
b0 = -(All.BiniZ + All.BiniY) / All.BiniX;
b1 = 1;
b2 = 1;
a0 = 0;
a1 = -All.BiniZ / b0;
a2 = All.BiniY / b0;
}
else
{
a0 = a1 = a2 = b0 = b1 = b2 = 0;
if(ThisTask == 0)
{
printf("Can not reconstruct Euler potentials from Bini values !\n");
endrun(6723);
}
}
}
SphP[i].EulerA = (a0 * P[i].Pos[0] + a1 * P[i].Pos[1] + a2 * P[i].Pos[2]) * atime * All.HubbleParam;
SphP[i].EulerB = (b0 * P[i].Pos[0] + b1 * P[i].Pos[1] + b2 * P[i].Pos[2]) * atime * All.HubbleParam;
#endif
#endif
#ifndef EULERPOTENTIALS
for(j = 0; j < 3; j++)
{
SphP[i].DtB[j] = 0;
SphP[i].B[j] = SphP[i].BPred[j];
}
#endif
#ifdef TIME_DEP_MAGN_DISP
#ifdef HIGH_MAGN_DISP_START
SphP[i].Balpha = All.ArtMagDispConst;
#else
SphP[i].Balpha = All.ArtMagDispMin;
#endif
SphP[i].DtBalpha = 0.0;
#endif
#ifdef DIVBCLEANING_DEDNER
SphP[i].Phi = SphP[i].PhiPred = SphP[i].DtPhi = 0;
#endif
#endif
#ifdef TIME_DEP_ART_VISC
#ifdef HIGH_ART_VISC_START
if(HIGH_ART_VISC_START == 0)
SphP[i].alpha = All.ArtBulkViscConst;
if(HIGH_ART_VISC_START > 0)
if(P[i].Pos[0] > HIGH_ART_VISC_START)
SphP[i].alpha = All.ArtBulkViscConst;
else
SphP[i].alpha = All.AlphaMin;
if(HIGH_ART_VISC_START < 0)
if(P[i].Pos[0] < -HIGH_ART_VISC_START)
SphP[i].alpha = All.ArtBulkViscConst;
else
SphP[i].alpha = All.AlphaMin;
#else
SphP[i].alpha = All.AlphaMin;
#endif
SphP[i].Dtalpha = 0.0;
#endif
#if defined(BH_THERMALFEEDBACK) || defined(BH_KINETICFEEDBACK)
SphP[i].i.Injected_BH_Energy = 0;
#endif
}
#ifdef TWODIMS
for(i = 0; i < NumPart; i++)
{
P[i].Pos[2] = 0;
P[i].Vel[2] = 0;
}
#endif
#ifdef ASSIGN_NEW_IDS
assign_unique_ids();
#endif
#ifndef NOTEST_FOR_IDUNIQUENESS
test_id_uniqueness();
#endif
All.NumForcesSinceLastDomainDecomp = (long long) (1 + All.TotNumPart * All.TreeDomainUpdateFrequency);
Flag_FullStep = 1; /* to ensure that Peano-Hilber order is done */
TreeReconstructFlag = 1;
domain_Decomposition(); /* do initial domain decomposition (gives equal numbers of particles) */
set_softenings();
/* will build tree */
ngb_treebuild();
All.Ti_Current = 0;
#ifdef START_WITH_EXTRA_NGBDEV
MaxNumNgbDeviationMerk = All.MaxNumNgbDeviation;
All.MaxNumNgbDeviation = All.MaxNumNgbDeviationStart;
#endif
if(RestartFlag != 3)
setup_smoothinglengths();
#ifdef VORONOI
for(i = 0; i < N_gas; i++)
SphP[i].MaxDelaunayRadius = SphP[i].Hsml;
voronoi_mesh();
#ifdef MESHRELAX_DENSITY_IN_INPUT
if(RestartFlag == 0)
for(i = 0; i < N_gas; i++)
P[i].Mass *= SphP[i].Volume;
#endif
#ifdef VORONOI_MESHRELAX
double mass, masstot, egy, egytot;
for(i = 0, mass = 0, egy = 0; i < N_gas; i++)
{
mass += P[i].Mass;
egy += P[i].Mass * SphP[i].Entropy;
SphP[i].Pressure = GAMMA_MINUS1 * SphP[i].Entropy * P[i].Mass / SphP[i].Volume;
}
MPI_Allreduce(&mass, &masstot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(&egy, &egytot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
All.MeanMass = masstot / All.TotN_gas;
#ifdef TWODIMS
All.MeanPressure = GAMMA_MINUS1 * egytot / (boxSize_X * boxSize_Y);
#else
All.MeanPressure = GAMMA_MINUS1 * egytot / (boxSize_X * boxSize_Y * boxSize_Z);
#endif
#endif
voronoi_density();
myfree(List_P);
myfree(ListExports);
myfree(DT);
myfree(DP - 5);
myfree(VF);
#endif
#ifdef START_WITH_EXTRA_NGBDEV
All.MaxNumNgbDeviation = MaxNumNgbDeviationMerk;
#endif
#ifdef HEALPIX
//this should be readed in the parameterfile
All.Nside=8;
//
if(ThisTask==0)
printf(" First calculation of Healpix %i with %i \n",All.Nside,NSIDE2NPIX(All.Nside));
// initialize the healpix array (just in case)
All.healpixmap=(float *) malloc(NSIDE2NPIX(All.Nside) * sizeof(float));
for(i=0;i<NSIDE2NPIX(All.Nside);i++)All.healpixmap[i]=0;
healpix_halo(All.healpixmap);
#endif
/* at this point, the entropy variable actually contains the
* internal energy, read in from the initial conditions file.
* Once the density has been computed, we can convert to entropy.
*/
for(i = 0; i < N_gas; i++) /* initialize sph_properties */
{
if(header.flag_entropy_instead_u == 0)
{
if(ThisTask == 0 && i == 0)
printf("Converting u -> entropy !\n");
#ifndef EOS_DEGENERATE
#ifndef VORONOI_MESHRELAX
SphP[i].Entropy = GAMMA_MINUS1 * SphP[i].Entropy / pow(SphP[i].d.Density / a3, GAMMA_MINUS1);
#endif
#else
SphP[i].Entropy *= All.UnitEnergy_in_cgs;
/* call eos with physical units, energy and entropy are always stored in physical units */
#ifdef EOS_ENERGY
SphP[i].temp = 1.0;
eos_calc_egiven2(SphP[i].d.Density * All.UnitDensity_in_cgs, SphP[i].xnuc, SphP[i].Entropy,
&SphP[i].temp, &SphP[i].Pressure);
SphP[i].Pressure /= All.UnitPressure_in_cgs;
#else
SphP[i].u = SphP[i].Entropy;
eos_calc_egiven(SphP[i].d.Density * All.UnitDensity_in_cgs, SphP[i].xnuc, SphP[i].Entropy,
&SphP[i].temp, &SphP[i].Entropy);
/* get pressure */
eos_calc_sgiven(SphP[i].d.Density * All.UnitDensity_in_cgs, SphP[i].xnuc, SphP[i].Entropy,
&SphP[i].temp, &SphP[i].Pressure, &SphP[i].u);
SphP[i].Pressure /= All.UnitPressure_in_cgs;
#endif
#endif
}
SphP[i].e.DtEntropy = 0;
SphP[i].v.DivVel = 0;
#ifdef MACHNUM
SphP[i].Shock_MachNumber = 1.0;
#ifdef COSMIC_RAYS
Pth1 = SphP[i].Entropy * pow(SphP[i].d.Density / a3, GAMMA);
#ifdef CR_IC_PHYSICAL
for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)
{
C_phys[CRpop] = SphP[i].CR_C0[CRpop];
q_phys[CRpop] = SphP[i].CR_q0[CRpop];
}
#else
for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)
{
C_phys[CRpop] = SphP[i].CR_C0[CRpop] * pow(SphP[i].d.Density, (All.CR_Alpha[CRpop] - 1.0) / 3.0);
q_phys[CRpop] = SphP[i].CR_q0[CRpop] * pow(SphP[i].d.Density, 1.0 / 3.0);
}
#endif
SphP[i].PreShock_XCR = 0.0;
for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)
{
rBeta[CRpop] = gsl_sf_beta((All.CR_Alpha[CRpop] - 2.0) * 0.5, (3.0 - All.CR_Alpha[CRpop]) * 0.5) *
gsl_sf_beta_inc((All.CR_Alpha[CRpop] - 2.0) * 0.5, (3.0 - All.CR_Alpha[CRpop]) * 0.5,
1.0 / (1.0 + q_phys[CRpop] * q_phys[CRpop]));
PCR1[CRpop] = C_phys[CRpop] * c2 * SphP[i].d.Density * rBeta[CRpop] / 6.0;
PCR1[CRpop] *= pow(atime, -3.0 * GAMMA);
SphP[i].PreShock_XCR += PCR1[CRpop] / Pth1;
}
SphP[i].PreShock_PhysicalDensity = SphP[i].d.Density / a3;
SphP[i].PreShock_PhysicalEnergy =
SphP[i].Entropy / GAMMA_MINUS1 * pow(SphP[i].d.Density / a3, GAMMA_MINUS1);
SphP[i].Shock_DensityJump = 1.0001;
SphP[i].Shock_EnergyJump = 1.0;
#endif /* COSMIC_RAYS */
#ifdef OUTPUT_PRESHOCK_CSND
Pth1 = SphP[i].Entropy * pow(SphP[i].d.Density / a3, GAMMA);
SphP[i].PreShock_PhysicalSoundSpeed =
sqrt(GAMMA * Pth1 / SphP[i].d.Density) * pow(atime, -3. / 2. * GAMMA_MINUS1);
SphP[i].PreShock_PhysicalDensity = SphP[i].d.Density / a3;
#endif /* OUTPUT_PRESHOCK_CSND */
#endif /* MACHNUM */
#ifdef REIONIZATION
All.not_yet_reionized = 1;
#endif
#ifdef CR_IC_PHYSICAL
/* Scale CR variables so that values from IC file are now the
* physical values, not the adiabatic invariants
*/
for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)
{
SphP[i].CR_C0[CRpop] *= pow(SphP[i].d.Density, (1.0 - All.CR_Alpha[CRpop]) / 3.0);
SphP[i].CR_q0[CRpop] *= pow(SphP[i].d.Density, -1.0 / 3.0);
}
#endif
#ifdef CR_INITPRESSURE
cr_pressure = CR_INITPRESSURE * SphP[i].Entropy * pow(SphP[i].d.Density / a3, GAMMA);
SphP[i].Entropy *= (1 - CR_INITPRESSURE);
q_phys = 1.685;
for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)
{
C_phys[CRpop] =
cr_pressure / (SphP[i].d.Density / a3 * CR_Tab_Beta(q_phys, CRpop) * (C / All.UnitVelocity_in_cm_per_s) *
(C / All.UnitVelocity_in_cm_per_s) / 6.0);
SphP[i].CR_C0[CRpop] = C_phys[CRpop] * pow(SphP[i].d.Density, (1.0 - All.CR_Alpha[CRpop]) / 3.0);
SphP[i].CR_q0[CRpop] = q_phys * pow(SphP[i].d.Density, -1.0 / 3.0);
}
#endif
}
if(RestartFlag == 3)
{
#ifdef FOF
fof_fof(RestartSnapNum);
#endif
endrun(0);
}
#ifdef CHEMISTRY
if(ThisTask == 0)
{
printf("Initial abundances: \n");
printf("HI=%g, HII=%g, HeI=%g, HeII=%g, HeIII=%g \n",
SphP[1].HI, SphP[1].HII, SphP[1].HeI, SphP[1].HeII, SphP[1].HeIII);
printf("HM=%g, H2I=%g, H2II=%g, elec=%g, %d\n",
SphP[1].HM, SphP[1].H2I, SphP[1].H2II, SphP[1].elec, P[1].ID);
printf("x=%g, y=%g, z=%g, vx=%g, vy=%g, vz=%g, density=%g, entropy=%g\n",
P[N_gas - 1].Pos[0], P[N_gas - 1].Pos[1], P[N_gas - 1].Pos[2], P[N_gas - 1].Vel[0],
P[N_gas - 1].Vel[1], P[N_gas - 1].Vel[2], SphP[N_gas - 1].Density, SphP[N_gas - 1].Entropy);
}
/* need predict the cooling time and elec_dot here */
min_t_cool = min_t_elec = 1.0e30;
max_t_cool = max_t_elec = -1.0e30;
for(i = 0; i < N_gas; i++)
{
a_start = All.Time;
a_end = All.Time + 0.001; /* 0.001 as an arbitrary value */
ifunc = compute_abundances(0, i, a_start, a_end);
if(fabs(SphP[i].t_cool) < min_t_cool)
min_t_cool = fabs(SphP[i].t_cool);
if(fabs(SphP[i].t_cool) > max_t_cool)
max_t_cool = fabs(SphP[i].t_cool);
if(fabs(SphP[i].t_elec) < min_t_elec)
min_t_elec = fabs(SphP[i].t_elec);
if(fabs(SphP[i].t_elec) > max_t_elec)
max_t_elec = fabs(SphP[i].t_elec);
}
fprintf(stdout, "PE %d t_cool min= %g, max= %g in yrs \n", ThisTask, min_t_cool, max_t_cool);
fflush(stdout);
fprintf(stdout, "PE %d t_elec min= %g, max= %g in yrs \n", ThisTask, min_t_elec, max_t_elec);
fflush(stdout);
#endif
}
/*! This routine computes the mass content of the box and compares it to the
* specified value of Omega-matter. If discrepant, the run is terminated.
*/
void check_omega(void)
{
double mass = 0, masstot, omega;
int i;
for(i = 0; i < NumPart; i++)
mass += P[i].Mass;
MPI_Allreduce(&mass, &masstot, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
omega =
masstot / (All.BoxSize * All.BoxSize * All.BoxSize) / (3 * All.Hubble * All.Hubble / (8 * M_PI * All.G));
#ifdef TIMEDEPGRAV
omega *= All.Gini / All.G;
#endif
if(fabs(omega - All.Omega0) > 1.0e-3)
{
if(ThisTask == 0)
{
printf("\n\nI've found something odd!\n");
printf
("The mass content accounts only for Omega=%g,\nbut you specified Omega=%g in the parameterfile.\n",
omega, All.Omega0);
printf("\nI better stop.\n");
fflush(stdout);
}
endrun(1);
}
}
/*! This function is used to find an initial smoothing length for each SPH
* particle. It guarantees that the number of neighbours will be between
* desired_ngb-MAXDEV and desired_ngb+MAXDEV. For simplicity, a first guess
* of the smoothing length is provided to the function density(), which will
* then iterate if needed to find the right smoothing length.
*/
void setup_smoothinglengths(void)
{
int i, no, p;
if(RestartFlag == 0)
{
for(i = 0; i < N_gas; i++)
{
no = Father[i];
while(10 * All.DesNumNgb * P[i].Mass > Nodes[no].u.d.mass)
{
p = Nodes[no].u.d.father;
if(p < 0)
break;
no = p;
}
#ifndef READ_HSML
#ifndef TWODIMS
PPP[i].Hsml =
pow(3.0 / (4 * M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 3) * Nodes[no].len;
#else
PPP[i].Hsml =
pow(1.0 / (M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 2) * Nodes[no].len;
#endif
if(PPP[i].Hsml > 200.0 * All.SofteningTable[0])
PPP[i].Hsml = All.SofteningTable[0];
#endif
}
}
#ifdef BLACK_HOLES
if(RestartFlag == 0 || RestartFlag == 2)
{
for(i = 0; i < NumPart; i++)
if(P[i].Type == 5)
PPP[i].Hsml = All.SofteningTable[5];
}
#endif
#ifdef RADTRANSFER
if(RestartFlag == 0 || RestartFlag == 2)
{
for(i = 0; i < NumPart; i++)
if(P[i].Type == 4)
PPP[i].Hsml = All.SofteningTable[4];
}
#endif
density();
#if defined(MAGNETIC) && defined(BFROMROTA)
if(RestartFlag == 0)
{
if(ThisTask == 0)
printf("Converting: Vector Potential -> Bfield\n");
rot_a();
}
#endif
}
void assign_unique_ids(void)
{
int i, *numpartlist;
MyIDType idfirst;
numpartlist = mymalloc(NTask * sizeof(int));
MPI_Allgather(&NumPart, 1, MPI_INT, numpartlist, 1, MPI_INT, MPI_COMM_WORLD);
idfirst = 1;
for(i = 0; i < ThisTask; i++)
idfirst += numpartlist[i];
for(i = 0; i < NumPart; i++)
{
P[i].ID = idfirst;
idfirst++;
}
myfree(numpartlist);
}
void test_id_uniqueness(void)
{
int i;
double t0, t1;
MyIDType *ids, *ids_first;
if(ThisTask == 0)
{
printf("Testing ID uniqueness...\n");
fflush(stdout);
}
if(NumPart == 0)
{
printf("need at least one particle per cpu\n");
endrun(8);
}
t0 = second();
#ifndef SPH_BND_PARTICLES
ids = (MyIDType *) mymalloc(NumPart * sizeof(MyIDType));
ids_first = (MyIDType *) mymalloc(NTask * sizeof(MyIDType));
for(i = 0; i < NumPart; i++)
ids[i] = P[i].ID;
parallel_sort(ids, NumPart, sizeof(MyIDType), compare_IDs);
for(i = 1; i < NumPart; i++)
if(ids[i] == ids[i - 1])
{
#ifdef LONGIDS
printf("non-unique ID=%d%09d found on task=%d (i=%d NumPart=%d)\n",
(int) (ids[i] / 1000000000), (int) (ids[i] % 1000000000), ThisTask, i, NumPart);
#else
printf("non-unique ID=%d found on task=%d (i=%d NumPart=%d)\n", (int) ids[i], ThisTask, i, NumPart);
#endif
endrun(12);
}
MPI_Allgather(&ids[0], sizeof(MyIDType), MPI_BYTE, ids_first, sizeof(MyIDType), MPI_BYTE, MPI_COMM_WORLD);
if(ThisTask < NTask - 1)
if(ids[NumPart - 1] == ids_first[ThisTask + 1])
{
printf("non-unique ID=%d found on task=%d\n", (int) ids[NumPart - 1], ThisTask);
endrun(13);
}
myfree(ids_first);
myfree(ids);
#endif
t1 = second();
if(ThisTask == 0)
{
printf("success. took=%g sec\n", timediff(t0, t1));
fflush(stdout);
}
}
int compare_IDs(const void *a, const void *b)
{
if(*((MyIDType *) a) < *((MyIDType *) b))
return -1;
if(*((MyIDType *) a) > *((MyIDType *) b))
return +1;
return 0;
}
| {
"alphanum_fraction": 0.6022528079,
"avg_line_length": 27.2860938884,
"ext": "c",
"hexsha": "b8bd40b062016f1d32bbd5b56dc522fe98d8fc7b",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "egpbos/egp",
"max_forks_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/init.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "egpbos/egp",
"max_issues_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/init.c",
"max_line_length": 123,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5e82c2de9e6884795b4ee89f2b15ed5dde70388f",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "egpbos/egp",
"max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/init.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 10764,
"size": 30806
} |
static const char help[] =
"Solves a 2D dam-saturation problem. No options.\n"
"The exact soluution is not known, but\n"
"a coarse-grid discrete solution can be checked against that source.\n"
"Note Poisson2DFunctionLocal() sets-up this unconstrained problem:\n"
" - u_xx - u_yy = - 1\n"
"while we want this complementarity problem:\n"
" F(u) = - u_xx - u_yy + 1 >= 0\n"
" u >= 0\n"
" u F(u) = 0.\n"
"As with obstacle.c, this is solved (default) by -snes_type vinewtonrsls.\n"
"Reference: pages 667-668 of Brandt & Cryer (1983).\n\n";
/*
note PFAS is not implemented in PETSc, but the following runs for X = 1,2,3,4,5,6
quickly solve the same problems as in Brandt & Cryer Table 4.2:
s ./dam -snes_monitor -pc_type mg -snes_grid_sequence X
on ed-galago I can go up to X = 11 giving 4097 x 6145 grid and serial runtime of 297 seconds
(the next step runs out of memory)
on parallel I am getting error messages with vinewtonrsls + mg:
mpiexec -n 4 ./dam -snes_converged_reason -snes_grid_sequence 5 -snes_type vinewtonrsls -pc_type mg
but this works with either vinewtonssls or another PC (gamg or bjacobi+ilu or asm+lu or etc.)
run as:
./dam -da_refine 1 -snes_view_solution :foo.m:ascii_matlab -snes_converged_reason -snes_rtol 1.0e-12
Nonlinear solve converged due to CONVERGED_FNORM_RELATIVE iterations 4
done on 5 x 7 grid
then in Matlab/Octave you can compare to Brandt & Cryer Table 4.1:
>> foo
>> format long g
>> u = flipud(reshape(Vec_0x84000000_0,5,7)') % use loaded name here
u =
0 0 0 0 0
8 2.53716015237691 0 0 0
32 18.148640609503 6.78414305345868 0 0
72 47.2732592321936 24.9879316043211 7.91201621181146 0
128 89.9564647149903 53.982307919772 22.6601332428759 0
200 146.570291707977 94.3247021169195 44.7462088399388 0
288 218 148 78 8
regarding computing seepage face height, runs
./dam -snes_converged_reason -pc_type mg -snes_rtol 1.0e-8 -snes_grid_sequence X
gives:
X grid height
6 129x193 8.8750000
7 257x385 8.7500000
8 513x769 8.7500000
9 1025x1537 8.7343750
10 2049x3073 8.7187500
11 4097x6145 8.7109375
but note these numbers depend (at the second digit, even) on the value of
"wetthreshold" in GetSeepageFaceHeight()
*/
#include <petsc.h>
#include "../../ch6/poissonfunctions.h"
typedef struct {
double a, y1, y2;
} DamCtx;
double g_fcn(double x, double y, double z, void *ctx) {
PoissonCtx *user = (PoissonCtx*)ctx;
DamCtx *dctx = (DamCtx*)(user->addctx);
const double a = dctx->a,
y1 = dctx->y1,
y2 = dctx->y2,
tol = a * 1.0e-8;
// see (4.2) in Brandt & Cryer for following:
if (x < tol) {
return (y1 - y) * (y1 - y) / 2.0; // AB
} else if (x > a - tol) {
if (y < y2) {
return (y2 - y) * (y2 - y) / 2.0; // CD
} else {
return 0.0; // DF
}
} else if (y < tol) {
return (y1 * y1 * (a - x) + y2 * y2 * x) / (2.0 * a); // BC
} else if (y > y1 - tol) {
return 0.0; // FA
} else {
return NAN;
}
}
double f_fcn(double x, double y, double z, void *ctx) {
return -1.0;
}
extern PetscErrorCode FormBounds(SNES, Vec, Vec);
extern PetscErrorCode GetSeepageFaceHeight(DMDALocalInfo*, Vec, double*, DamCtx*);
int main(int argc,char **argv) {
PetscErrorCode ierr;
DM da, da_after;
SNES snes;
Vec u;
PoissonCtx user;
DamCtx dctx;
DMDALocalInfo info;
double height;
PetscInitialize(&argc,&argv,NULL,help);
dctx.a = 16.0; // a, y1, y2 from Brandt & Cryer
dctx.y1 = 24.0;
dctx.y2 = 4.0;
user.cx = 1.0;
user.cy = 1.0;
user.cz = 1.0;
user.g_bdry = &g_fcn;
user.f_rhs = &f_fcn;
user.addctx = &dctx;
ierr = DMDACreate2d(PETSC_COMM_WORLD,
DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, DMDA_STENCIL_STAR,
3,4, // override with -da_refine or -da_grid_x,_y
PETSC_DECIDE,PETSC_DECIDE, // num of procs in each dim
1,1,NULL,NULL, // dof = 1 and stencil width = 1
&da);CHKERRQ(ierr);
ierr = DMSetFromOptions(da); CHKERRQ(ierr);
ierr = DMSetUp(da); CHKERRQ(ierr);
ierr = DMDASetUniformCoordinates(da,0.0,dctx.a,0.0,dctx.y1,-1.0,-1.0);CHKERRQ(ierr);
ierr = DMSetApplicationContext(da,&user);CHKERRQ(ierr);
ierr = SNESCreate(PETSC_COMM_WORLD,&snes);CHKERRQ(ierr);
ierr = SNESSetDM(snes,da);CHKERRQ(ierr);
ierr = SNESSetApplicationContext(snes,&user);CHKERRQ(ierr);
ierr = SNESSetType(snes,SNESVINEWTONRSLS);CHKERRQ(ierr);
ierr = SNESVISetComputeVariableBounds(snes,&FormBounds);CHKERRQ(ierr);
ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,
(DMDASNESFunction)Poisson2DFunctionLocal,&user); CHKERRQ(ierr);
ierr = DMDASNESSetJacobianLocal(da,
(DMDASNESJacobian)Poisson2DJacobianLocal,&user); CHKERRQ(ierr);
ierr = SNESSetFromOptions(snes);CHKERRQ(ierr);
ierr = DMCreateGlobalVector(da,&u);CHKERRQ(ierr);
// initial iterate has u=g on boundary and u=0 in interior
ierr = InitialState(da, ZEROS, PETSC_TRUE, u, &user); CHKERRQ(ierr);
/* solve */
ierr = SNESSolve(snes,NULL,u);CHKERRQ(ierr);
ierr = VecDestroy(&u); CHKERRQ(ierr);
ierr = DMDestroy(&da); CHKERRQ(ierr);
// report seepage face
ierr = SNESGetSolution(snes,&u); CHKERRQ(ierr); /* do not destroy u */
ierr = SNESGetDM(snes,&da_after); CHKERRQ(ierr);
ierr = DMDAGetLocalInfo(da_after,&info); CHKERRQ(ierr);
ierr = GetSeepageFaceHeight(&info,u,&height,&dctx); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"done on %3d x %3d grid; computed seepage face height = %.7f\n",
info.mx,info.my,height); CHKERRQ(ierr);
SNESDestroy(&snes);
return PetscFinalize();
}
// for call-back: tell SNESVI we want 0 <= u < +infinity
PetscErrorCode FormBounds(SNES snes, Vec Xl, Vec Xu) {
PetscErrorCode ierr;
ierr = VecSet(Xl,0.0);CHKERRQ(ierr);
ierr = VecSet(Xu,PETSC_INFINITY);CHKERRQ(ierr);
return 0;
}
PetscErrorCode GetSeepageFaceHeight(DMDALocalInfo *info, Vec u, double *height, DamCtx *dctx) {
PetscErrorCode ierr;
MPI_Comm comm;
const double dy = dctx->y1 / (PetscReal)(info->my-1),
wetthreshhold = 1.0e-6; // what does "u>0" mean?
int j;
double **au, locwetmax = - PETSC_INFINITY;
ierr = DMDAVecGetArrayRead(info->da,u,&au); CHKERRQ(ierr);
if (info->xs+info->xm == info->mx) { // do we even own (part of) the x=a side of the rectangle?
for (j=info->ys; j<info->ys+info->ym; j++) {
if (au[j][info->mx-2] > wetthreshhold) { // is the first inter point wet?
locwetmax = PetscMax(j*dy,locwetmax);
}
}
}
ierr = DMDAVecRestoreArrayRead(info->da,u,&au); CHKERRQ(ierr);
ierr = PetscObjectGetComm((PetscObject)(info->da),&comm); CHKERRQ(ierr);
ierr = MPI_Allreduce(&locwetmax,height,1,MPI_DOUBLE,MPI_MAX,comm); CHKERRQ(ierr);
*height -= dctx->y2; // height is segment ED in figure
return 0;
}
| {
"alphanum_fraction": 0.6039708802,
"avg_line_length": 38.7435897436,
"ext": "c",
"hexsha": "2d1d6dbd4bb8b0e1cc3b9c253a5dae42cca3700d",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mapengfei-nwpu/p4pdes",
"max_forks_repo_path": "c/ch12/solns/dam.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "mapengfei-nwpu/p4pdes",
"max_issues_repo_path": "c/ch12/solns/dam.c",
"max_line_length": 104,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mapengfei-nwpu/p4pdes",
"max_stars_repo_path": "c/ch12/solns/dam.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2445,
"size": 7555
} |
#ifndef PyGSL_RNG_H
#define PyGSL_RNG_H 1
#include <pygsl/intern.h>
#include <gsl/gsl_rng.h>
typedef struct {
PyObject_HEAD
gsl_rng * rng;
} PyGSL_rng;
/*
* Get a gsl_rng object from a PyGSL rng wrapper.
*/
PyGSL_API_EXTERN gsl_rng *
PyGSL_gsl_rng_from_pyobject(PyObject * object);
#ifndef _PyGSL_API_MODULE
#define PyGSL_gsl_rng_from_pyobject \
(*(gsl_rng * (*) (PyObject *)) PyGSL_API[PyGSL_gsl_rng_from_pyobject_NUM])
#endif /* _PyGSL_API_MODULE */
#define PyGSL_RNG_Check(op) \
((op)->ob_type == (PyTypeObject *)PyGSL_API[PyGSL_RNG_ObjectType_NUM])
#define import_pygsl_rng() \
{ \
PyObject *pygsl = NULL, *c_api = NULL, *md = NULL; \
if ( \
(pygsl = PyImport_ImportModule("pygsl.rng")) != NULL && \
(md = PyModule_GetDict(pygsl)) != NULL && \
(c_api = PyDict_GetItemString(md, "_PYGSL_RNG_API")) != NULL && \
(PyCObject_Check(c_api)) \
) { \
PyGSL_API = (void **)PyCObject_AsVoidPtr(c_api); \
} else { \
PyGSL_API = NULL; \
} \
/* fprintf(stderr, "PyGSL_API points to %p\n", (void *) PyGSL_API); */ \
}
#endif /* PyGSL_RNG_H */
| {
"alphanum_fraction": 0.6183206107,
"avg_line_length": 25.085106383,
"ext": "h",
"hexsha": "d2b2f62c815cf54982eb71a55d8c2cb2b4ea901d",
"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/Include/pygsl/rng.h",
"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/Include/pygsl/rng.h",
"max_line_length": 75,
"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/Include/pygsl/rng.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 371,
"size": 1179
} |
#pragma once
#include <functional>
#include <memory>
#include <vector>
#include <gsl/gsl-lite.hpp> // gsl::span
#include <QObject>
#include "HypCommands.h" // Hyperion::RECORD_LENGTH
class DeviceLink;
class Recording;
class HypReader : public QObject
{
Q_OBJECT
public:
explicit HypReader(std::function<void(const QString&)> msgCBck,
std::function<void(size_t)> finishedCBck,
QObject* parent = nullptr);
void DownloadFromDevice();
void EraseDevice();
bool LoadFromFile(const QString& filePath);
bool SaveToFile (const QString& filePath);
size_t GetNumRecordings() const; // { return m_recordings.size(); }
const Recording& GetRecording(size_t idx) const;
Hyperion::DeviceType GetDeviceType() const;
int GetFirmwareVersionX100() const;
signals:
void SeriesEnded();
void DownloadFinish(bool success);
private:
void EndSeries();
void FinishDownload(bool success);
// These get called from DeviceLink worker thread.
// They emit the data to be processed on UI thread.
void MarkSeriesEnd();
void DownloadFinished(bool success);
void ReceiveDataChunk(const gsl::span<uint8_t>& data);
//data:
std::function<void(const QString&)> m_msgCBck;
std::function<void(size_t)> m_finishedCBck;
std::unique_ptr<DeviceLink> m_deviceReader;
std::vector<std::vector<uint8_t>> m_downloadedRawData;
std::vector<Recording> m_recordings;
public:
static const QString BS;
};
| {
"alphanum_fraction": 0.6536069652,
"avg_line_length": 26.3606557377,
"ext": "h",
"hexsha": "d033d4399ae0d1cd1f91b84ffc35ec6002cb8b68",
"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": "105124530364cdf9f625a03046b5edba140c9114",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bsergeev/HyperionEmeter2",
"max_forks_repo_path": "src/HypReader.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114",
"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": "bsergeev/HyperionEmeter2",
"max_issues_repo_path": "src/HypReader.h",
"max_line_length": 72,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bsergeev/HyperionEmeter2",
"max_stars_repo_path": "src/HypReader.h",
"max_stars_repo_stars_event_max_datetime": "2021-04-01T08:01:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-01T08:01:08.000Z",
"num_tokens": 355,
"size": 1608
} |
/* histogram/gsl_histogram2d.h
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __GSL_HISTOGRAM2D_H__
#define __GSL_HISTOGRAM2D_H__
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
typedef struct {
size_t nx, ny ;
double * xrange ;
double * yrange ;
double * bin ;
} gsl_histogram2d ;
typedef struct {
size_t nx, ny ;
double * xrange ;
double * yrange ;
double * sum ;
} gsl_histogram2d_pdf ;
GSL_EXPORT gsl_histogram2d * gsl_histogram2d_alloc (const size_t nx, const size_t ny);
GSL_EXPORT gsl_histogram2d * gsl_histogram2d_calloc (const size_t nx, const size_t ny);
GSL_EXPORT gsl_histogram2d * gsl_histogram2d_calloc_uniform (const size_t nx, const size_t ny,
const double xmin, const double xmax,
const double ymin, const double ymax);
GSL_EXPORT void gsl_histogram2d_free (gsl_histogram2d * h);
GSL_EXPORT int gsl_histogram2d_increment (gsl_histogram2d * h, double x, double y);
GSL_EXPORT int gsl_histogram2d_accumulate (gsl_histogram2d * h,
double x, double y, double weight);
GSL_EXPORT int gsl_histogram2d_find (const gsl_histogram2d * h,
const double x, const double y, size_t * i, size_t * j);
GSL_EXPORT double gsl_histogram2d_get (const gsl_histogram2d * h, const size_t i, const size_t j);
GSL_EXPORT int gsl_histogram2d_get_xrange (const gsl_histogram2d * h, const size_t i,
double * xlower, double * xupper);
GSL_EXPORT int gsl_histogram2d_get_yrange (const gsl_histogram2d * h, const size_t j,
double * ylower, double * yupper);
GSL_EXPORT double gsl_histogram2d_xmax (const gsl_histogram2d * h);
GSL_EXPORT double gsl_histogram2d_xmin (const gsl_histogram2d * h);
GSL_EXPORT size_t gsl_histogram2d_nx (const gsl_histogram2d * h);
GSL_EXPORT double gsl_histogram2d_ymax (const gsl_histogram2d * h);
GSL_EXPORT double gsl_histogram2d_ymin (const gsl_histogram2d * h);
GSL_EXPORT size_t gsl_histogram2d_ny (const gsl_histogram2d * h);
GSL_EXPORT void gsl_histogram2d_reset (gsl_histogram2d * h);
GSL_EXPORT
gsl_histogram2d *
gsl_histogram2d_calloc_range(size_t nx, size_t ny,
double *xrange, double *yrange);
GSL_EXPORT
int
gsl_histogram2d_set_ranges_uniform (gsl_histogram2d * h,
double xmin, double xmax,
double ymin, double ymax);
GSL_EXPORT
int
gsl_histogram2d_set_ranges (gsl_histogram2d * h,
const double xrange[], size_t xsize,
const double yrange[], size_t ysize);
GSL_EXPORT
int
gsl_histogram2d_memcpy(gsl_histogram2d *dest, const gsl_histogram2d *source);
GSL_EXPORT
gsl_histogram2d *
gsl_histogram2d_clone(const gsl_histogram2d * source);
GSL_EXPORT
double
gsl_histogram2d_max_val(const gsl_histogram2d *h);
GSL_EXPORT
void
gsl_histogram2d_max_bin (const gsl_histogram2d *h, size_t *i, size_t *j);
GSL_EXPORT
double
gsl_histogram2d_min_val(const gsl_histogram2d *h);
GSL_EXPORT
void
gsl_histogram2d_min_bin (const gsl_histogram2d *h, size_t *i, size_t *j);
GSL_EXPORT
double
gsl_histogram2d_xmean (const gsl_histogram2d * h);
GSL_EXPORT
double
gsl_histogram2d_ymean (const gsl_histogram2d * h);
GSL_EXPORT
double
gsl_histogram2d_xsigma (const gsl_histogram2d * h);
GSL_EXPORT
double
gsl_histogram2d_ysigma (const gsl_histogram2d * h);
GSL_EXPORT
double
gsl_histogram2d_cov (const gsl_histogram2d * h);
GSL_EXPORT
double
gsl_histogram2d_sum (const gsl_histogram2d *h);
GSL_EXPORT
int
gsl_histogram2d_equal_bins_p(const gsl_histogram2d *h1,
const gsl_histogram2d *h2) ;
GSL_EXPORT
int
gsl_histogram2d_add(gsl_histogram2d *h1, const gsl_histogram2d *h2);
GSL_EXPORT
int
gsl_histogram2d_sub(gsl_histogram2d *h1, const gsl_histogram2d *h2);
GSL_EXPORT
int
gsl_histogram2d_mul(gsl_histogram2d *h1, const gsl_histogram2d *h2);
GSL_EXPORT
int
gsl_histogram2d_div(gsl_histogram2d *h1, const gsl_histogram2d *h2);
GSL_EXPORT
int
gsl_histogram2d_scale(gsl_histogram2d *h, double scale);
GSL_EXPORT
int
gsl_histogram2d_shift(gsl_histogram2d *h, double shift);
GSL_EXPORT int gsl_histogram2d_fwrite (FILE * stream, const gsl_histogram2d * h) ;
GSL_EXPORT int gsl_histogram2d_fread (FILE * stream, gsl_histogram2d * h);
GSL_EXPORT int gsl_histogram2d_fprintf (FILE * stream, const gsl_histogram2d * h,
const char * range_format,
const char * bin_format);
GSL_EXPORT int gsl_histogram2d_fscanf (FILE * stream, gsl_histogram2d * h);
GSL_EXPORT gsl_histogram2d_pdf * gsl_histogram2d_pdf_alloc (const size_t nx, const size_t ny);
GSL_EXPORT int gsl_histogram2d_pdf_init (gsl_histogram2d_pdf * p, const gsl_histogram2d * h);
GSL_EXPORT void gsl_histogram2d_pdf_free (gsl_histogram2d_pdf * p);
GSL_EXPORT int gsl_histogram2d_pdf_sample (const gsl_histogram2d_pdf * p,
double r1, double r2,
double * x, double * y);
__END_DECLS
#endif /* __GSL_HISTOGRAM2D_H__ */
| {
"alphanum_fraction": 0.7131423083,
"avg_line_length": 31.8724489796,
"ext": "h",
"hexsha": "99798bac24dd88d8c01de5b1252beaa54fc489f4",
"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_histogram2d.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_histogram2d.h",
"max_line_length": 99,
"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_histogram2d.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1647,
"size": 6247
} |
#pragma once
#include <petsc.h>
#include <memory>
#include "partition/rank_subset.h"
namespace TimeSteppingScheme
{
namespace NestedMatVecUtility
{
//! from a Petsc Vec with nested type (nestedVec) create a new Petsc Vec (singleVec) that contains all values at once. If the singleVec already exists, do not create again, only copy the values.
void createVecFromNestedVec(Vec nestedVec, Vec &singleVec, std::shared_ptr<Partition::RankSubset> rankSubset);
//! copy the values from a singleVec back to the nested Petsc Vec (nestedVec)
void fillNestedVec(Vec singleVec, Vec nestedVec);
//! from a Petsc Mat with nested type (nestedMat) create a new Petsc Mat (singleMat) that contains all values at once. If the singleMat already exists, do not create again, only copy the values.
void createMatFromNestedMat(Mat nestedMat, Mat &singleMat, std::shared_ptr<Partition::RankSubset> rankSubset);
}
} // namespace
| {
"alphanum_fraction": 0.7781420765,
"avg_line_length": 36.6,
"ext": "h",
"hexsha": "cc65045eee19286f85d58bf4bec932406b6a197f",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-05-28T13:24:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-10-17T12:18:10.000Z",
"max_forks_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "maierbn/opendihu",
"max_forks_repo_path": "core/src/specialized_solver/multidomain_solver/nested_mat_vec_utility.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0",
"max_issues_repo_issues_event_max_datetime": "2020-12-29T15:29:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-11-12T15:15:58.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "maierbn/opendihu",
"max_issues_repo_path": "core/src/specialized_solver/multidomain_solver/nested_mat_vec_utility.h",
"max_line_length": 194,
"max_stars_count": 17,
"max_stars_repo_head_hexsha": "577650e2f6b36a7306766b0f4176f8124458cbf0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "maierbn/opendihu",
"max_stars_repo_path": "core/src/specialized_solver/multidomain_solver/nested_mat_vec_utility.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-20T04:46:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-25T19:29:34.000Z",
"num_tokens": 218,
"size": 915
} |
/*
* BIG_DATA.c
*
* Created on: 3 Sep 2020
* Author: heine
*/
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_linalg.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "kalman_filter.h"
#include "particle_filters.h"
#define N_SETTINGS 10
#define N_SCALES 11
void init_with_zeros(double* array, long length);
void scale_sample_sizes(double scaler, long sample_size_collection[N_SETTINGS][2], int n_settings);
void particle_allocation_time_matching(int bpf_sample_size, double std_sig, double obs_std, int Nobs, int data_length, double x0, double *y, double *Rinv1, double *Rinv0, gsl_matrix *R);
int main(void) {
gsl_rng * rng = gsl_rng_alloc(gsl_rng_taus);
gsl_rng_set(rng,clock());
double scaler;
int N_top = 50;
int N_bpf = 250;
int run_time_matching = 0;
int data_length = 50;
int Nobs = 500;
double sig_std = .1;
double obs_std = 1;
double x0 = 0;
double p0 = sig_std * sig_std;
double sample_size_coeff = (double)68000 / (double) 250;
/* -----------------------------------------------------------------------------------
*
* Create data
*
-----------------------------------------------------------------------------------*/
double *x = (double*) malloc(data_length * sizeof(double));
double *y = (double*) malloc(data_length * Nobs * sizeof(double));
double *noise = (double*) malloc(Nobs * sizeof(double));
gsl_matrix * A;
double x_prev = 0;
/* Create the measurement covariance square root */
A = gsl_matrix_alloc(Nobs, Nobs);
for (int i = 0; i < Nobs; i++) {
for (int j = 0; j < Nobs; j++) {
/* Uncomment for identity matrix */
/*
* if (i == j) {
* gsl_matrix_set(A, i, j, 1);
* } else {
* gsl_matrix_set(A, i, j, 0);
} */
// gsl_matrix_set(A, i, j, gsl_ran_gaussian(rng, 1));
gsl_matrix_set(A, i, j, gsl_rng_uniform(rng));
}
}
/* Calculate the observation covariance */
gsl_matrix * R = gsl_matrix_alloc(Nobs, Nobs);
double tmp;
double decay = 2; // Decay of correlations
FILE * R_out = fopen("R_matrix.txt", "w");
for (int i = 0; i < Nobs; i++) {
for (int j = 0; j < Nobs; j++) {
tmp = 0;
for (int k = 0; k < Nobs; k++) {
tmp += gsl_matrix_get(A, i, k) * gsl_matrix_get(A, j, k);
}
tmp = obs_std * obs_std * exp(-decay * (double) abs(i - j)) * tmp;
gsl_matrix_set(R, i, j, tmp);
fprintf(R_out, "%e ", tmp);
}
fprintf(R_out, "\n");
}
fclose(R_out);
// Copy R to A
for (int i = 0; i < Nobs; i++) {
for (int j = 0; j < Nobs; j++) {
gsl_matrix_set(A, i, j, gsl_matrix_get(R, i, j));
}
}
gsl_linalg_cholesky_decomp1(A);
printf("Obsevation covariance written in R_matrix.txt\n");
/* Main loop for generating the signal and the data */
FILE *data_file = fopen("data.txt", "w");
for (int n = 0; n < data_length; n++) {
x[n] = x_prev + gsl_ran_gaussian(rng, sig_std);
x_prev = x[n];
fprintf(data_file, "%i %e", n, x[n]);
/* Uncorrelated observation noise */
for (int i = 0; i < Nobs; i++) {
noise[i] = gsl_ran_gaussian(rng, obs_std);
}
/* Make the noise correlated by multiplying by A */
for (int i = 0; i < Nobs; i++) {
y[n * Nobs + i] = x[n];
for (int j = 0; j <= i; j++)
y[n * Nobs + i] += gsl_matrix_get(A, i, j) * noise[j];
fprintf(data_file, " %e,", y[n * Nobs + i]);
}
fprintf(data_file, "\n");
}
fclose(data_file);
printf("Signal and data of length %i generated and written in data.txt\n", data_length);
/*
* Calculate the inverse observation covariances
*/
printf("Computing the observation covariance inverse...\n");
fflush(stdout);
clock_t start = clock();
/* Observation noise covariance */
gsl_vector * eval = gsl_vector_alloc(Nobs);
gsl_matrix * evec = gsl_matrix_alloc(Nobs, Nobs);
double * Rinv1 = (double*) malloc(Nobs * Nobs * sizeof(double));
gsl_eigen_symmv_workspace * workspace = gsl_eigen_symmv_alloc(Nobs);
/* Compute the eigen decomposition of R to get the inverse */
gsl_eigen_symmv(R, eval, evec, workspace);
FILE* rinv_out = fopen("R_inv.txt", "w");
for (int i = 0; i < Nobs; i++) {
for (int k = 0; k < Nobs; k++) {
tmp = 0;
for (int j = 0; j < Nobs; j++) {
tmp += gsl_matrix_get(evec, i, j) * gsl_matrix_get(evec, k, j)
/ gsl_vector_get(eval, j);
}
Rinv1[i * Nobs + k] = tmp;
fprintf(rinv_out, "%e, ", tmp);
}
fprintf(rinv_out, "\n");
}
fclose(rinv_out);
printf("Observation covariance inverse computed and written in R_inv.txt\n");
gsl_matrix_free(evec);
gsl_vector_free(eval);
gsl_eigen_symmv_free(workspace);
/* Limit the observation correlation to a band and ... */
int band = 0; // Note we only consider diagonal, i.e. band = 0.
gsl_matrix * R_low = gsl_matrix_alloc(Nobs, Nobs);
for (int i = 0; i < Nobs; i++) {
for (int j = 0; j < Nobs; j++) {
tmp = abs(i - j) <= band ? gsl_matrix_get(R, i, j) : 0;
gsl_matrix_set(R_low, i, j, tmp);
}
}
/* ...take inverse */
gsl_vector * eval_low = gsl_vector_alloc(Nobs);
gsl_matrix * evec_low = gsl_matrix_alloc(Nobs, Nobs);
gsl_eigen_symmv_workspace * workspace_low = gsl_eigen_symmv_alloc(Nobs);
double * Rinv0 = (double*) malloc(Nobs * Nobs * sizeof(double));
gsl_eigen_symmv(R_low, eval_low, evec_low, workspace_low);
FILE * band_R_out = fopen("R_band_inv.txt", "w");
for (int i = 0; i < Nobs; i++) {
for (int k = 0; k < Nobs; k++) {
tmp = 0;
for (int j = 0; j < Nobs; j++) {
tmp += gsl_matrix_get(evec_low, i, j) * gsl_matrix_get(evec_low, k, j)
/ gsl_vector_get(eval_low, j);
}
Rinv0[i * Nobs + k] = tmp;
fprintf(band_R_out, "%e ", tmp);
}
fprintf(band_R_out, "\n");
}
fclose(band_R_out);
printf(
"Inverse of the diagonal covariance approximation computed and written in R_band_inv.txt\n");
gsl_matrix_free(evec_low);
gsl_vector_free(eval_low);
gsl_eigen_symmv_free(workspace_low);
printf("elapsed %5.2f sec\n", (double) (clock() - start) / CLOCKS_PER_SEC);
if (run_time_matching == 1) {
/*
* Particle allocation time matching
*
* This part of the code should be run when trying to find the correct N0 sample sizes to match
* the BPF running time
*/
particle_allocation_time_matching(N_bpf, sig_std, obs_std, Nobs, data_length, x0, y, Rinv1, Rinv0, R);
printf("Particle allocation time matching done! Exiting...\n");
return 0; // the code exits
}
/* ------------------------------------------------------------
* Kalman filter
* --------------------------------------------------------- */
double *x_hat = (double*) malloc(data_length * sizeof(double));
double *p_hat = (double*) malloc(data_length * sizeof(double));
kalman_filter(x, y, Rinv1, sig_std, obs_std, x_hat, p_hat, data_length, x0, p0, Nobs);
/* Write KF results in a file */
FILE *kf_out = fopen("kf_out.txt", "w");
for (int i = 0; i < data_length; i++)
fprintf(kf_out, "%i %f %f %f\n", i, x[i], x_hat[i], p_hat[i]);
fclose(kf_out);
/*
* Top level loop
* */
double scalers[N_SCALES] = {0.5,1,2,3,4,5,6,7,8,9,10};
short N_levels = 2;
long sample_sizes[2] = {0,0};
long sample_size[1] = { N_bpf }; // This is for one level BPF
double *x_hat_bpf = (double*) malloc(data_length * sizeof(double));
double *errors = (double *) malloc((N_SETTINGS + 1) * sizeof(double));
double *times = (double *) malloc((N_SETTINGS + 1) * sizeof(double));
init_with_zeros(errors, N_SETTINGS + 1);
init_with_zeros(times, N_SETTINGS + 1);
double error;
FILE * error_out = fopen("error.txt", "w");
double filtering_time[4];
double worst_case_sign_ratio[1] = { 100 }; // This is basically sustitute for "Inf"
long unilevel_sample_size = N_bpf;
long error_matched_unilevel_sample_size = 7 * N_bpf;
int N1, N0;
double step;
/*
* MAIN LOOP FOR TOP LEVEL MONTE CARLO
*/
for (int i = 0; i < N_top; i++) {
printf("Top level iteration %i\n", i);
for (int k = 0; k < N_SCALES; k++) {
scaler = scalers[k];
printf("Scaler %f\n", scaler);
/* Run the basic BPF (time matched) */
sample_size[0] = (long) round(unilevel_sample_size * scaler);
bootstrapfilter(y, sig_std, obs_std, data_length, x0, Nobs, sample_size[0],
x_hat_bpf, filtering_time, Rinv1, 1);
/* Sum of squared errors over the whole signal */
error = 0;
for (int n = 0; n < data_length; n++) {
error += (x_hat[n] - x_hat_bpf[n]) * (x_hat[n] - x_hat_bpf[n]);
}
fprintf(error_out, "%e %i %lu %f %i %e %e %f %e %f\n",
error / (double) data_length, 0, sample_size[0], filtering_time[0], 0,
filtering_time[1], filtering_time[2], worst_case_sign_ratio[0],
filtering_time[3], scaler);
fflush(error_out);
if(scaler < 8) {
/* Run the basic BPF (error matched) */
sample_size[0] = (long) round(error_matched_unilevel_sample_size * scaler);
bootstrapfilter(y, sig_std, obs_std, data_length, x0, Nobs, sample_size[0],
x_hat_bpf, filtering_time, Rinv1, 1);
/* Sum of squared errors over the whole signal */
error = 0;
for (int n = 0; n < data_length; n++) {
error += (x_hat[n] - x_hat_bpf[n]) * (x_hat[n] - x_hat_bpf[n]);
}
fprintf(error_out, "%e %i %lu %f %i %e %e %f %e %f\n",
error / (double) data_length, 0, sample_size[0], filtering_time[0], -1,
filtering_time[1], filtering_time[2], worst_case_sign_ratio[0],
filtering_time[3], scaler);
fflush(error_out);
}
/* Iterate over different configurations */
N1 = 0;
for (int j = 0; j < N_SETTINGS; j++) {
step = (double)(N_bpf - 5) / (double)(N_SETTINGS-1);
N1 = (int) j * step;
N0 = (int) floor((N_bpf-N1)*sample_size_coeff);
worst_case_sign_ratio[0] = 100;
sample_sizes[0] = N0 * scaler;
sample_sizes[1] = N1 * scaler;
printf("N0 = %lu, N1 = %lu, N = %lu\n", sample_sizes[0], sample_sizes[1], sample_sizes[0]+sample_sizes[1]);
MLbootstrapfilter(y, sig_std, obs_std, data_length, x0, Nobs, N_levels,
sample_sizes, x_hat_bpf, filtering_time, Rinv0, Rinv1,
worst_case_sign_ratio);
/* Sum of squared errors over the whole signal */
error = 0;
for (int n = 0; n < data_length; n++) {
error += (x_hat[n] - x_hat_bpf[n]) * (x_hat[n] - x_hat_bpf[n]);
}
fprintf(error_out, "%e %lu %lu %f %i %e %e %f %e %f\n",
error / (double) data_length, sample_sizes[0],
sample_sizes[1], filtering_time[0], j+1, filtering_time[1],
filtering_time[2], worst_case_sign_ratio[0], filtering_time[3], scaler);
}
fflush(error_out);
}
}
fclose(error_out);
printf("Results of all BPF runs written in error.txt\n");
printf("Error summary written in error_summary.txt\n");
return 0;
}
void init_with_zeros(double *array, long length) {
for (int i = 0; i < length; i++)
array[i] = 0;
}
void scale_sample_sizes(double scaler, long sample_size_collection[N_SETTINGS][2], int n_settings) {
for (int i = 0; i < n_settings; i++)
for (int j = 0; j < 1; j++)
sample_size_collection[i][j] = (long) round(scaler * sample_size_collection[i][j]);
}
void particle_allocation_time_matching(int bpf_sample_size, double std_sig, double obs_std, int Nobs, int data_length, double x0, double *y, double *Rinv1, double *Rinv0, gsl_matrix *R) {
int N1_step = 20;
int N0_step = 10000;
int N0_init = 10;
int N_top = 5;
double time_per_iteration;
double time_tolerance = 1.00; //
double filtering_time[1];
double worst_case_sign_ratio[1] = { 100 };
double *x_hat_bpf = (double*) malloc(data_length * sizeof(double));
/* Find the reference time per iteration for BPF */
double bpf_time_per_iteration = 0;
for(int nmc = 0; nmc < N_top; nmc++) {
bootstrapfilter(y, std_sig, obs_std, data_length, x0, Nobs, bpf_sample_size,
x_hat_bpf, filtering_time, Rinv1, 1);
bpf_time_per_iteration += filtering_time[0] / (double) N_top;
}
printf("Time per iteration (BPF): %0.5f\n",bpf_time_per_iteration);
fflush(stdout);
long sample_sizes[2] = {0,0};
int N0;
short direction;
FILE* out = fopen("time_matched_sample_sizes.txt","w");
/* For given L0 mesh, iterate over N1 */
for(int N1 = 0; N1 <= bpf_sample_size ; N1 = N1 + N1_step) {
N0 = N0_init;
N0_step = 10000;
/* For given L0 mesh and N1 iterate over increasing N0 until MLBPF time per iteration exceeds
BPF time per iteration */
time_per_iteration = 0;
direction = 1; // up
while(1) {
sample_sizes[0] = N0;
sample_sizes[1] = N1;
/* Estimate the time per iteration by averaging N_top runs */
time_per_iteration = 0;
for(int nmc = 0; nmc < N_top; nmc++) {
MLbootstrapfilter(y, std_sig, obs_std, data_length, x0, Nobs, 2,
sample_sizes, x_hat_bpf, filtering_time, Rinv0, Rinv1,
worst_case_sign_ratio);
time_per_iteration += filtering_time[0] / (double) N_top;
}
if (direction == 1 && time_per_iteration > bpf_time_per_iteration * time_tolerance && N0_step > 10) {
direction = -1; // start going down
N0_step /= 2; // halve the step
} else if (direction == -1 && time_per_iteration < bpf_time_per_iteration * 1.00 && N0_step > 10) {
direction = 1;
N0_step /= 2;
} else if (N0_step < 10) {
break;
}
N0 = N0 + direction * N0_step;
if(N0 < 1) { // Make sure N0 remains positive and go up if this happens
N0 = 1;
direction = 1;
}
}
fprintf(out,"%i %i %i %i\n",N0-N0_step,N1,0,0);
fflush(out);
}
fclose(out);
free(x_hat_bpf);
}
| {
"alphanum_fraction": 0.5787518062,
"avg_line_length": 32.6584269663,
"ext": "c",
"hexsha": "7b6419ed1a8ff5fdcecbfc7c7257fc90689d3493",
"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": "92805b7ba34496271628f745e44eb4984329fb4a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "heinekmp/MLBPF",
"max_forks_repo_path": "BIG_DATA/BIG_DATA.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a",
"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": "heinekmp/MLBPF",
"max_issues_repo_path": "BIG_DATA/BIG_DATA.c",
"max_line_length": 187,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "92805b7ba34496271628f745e44eb4984329fb4a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "heinekmp/MLBPF",
"max_stars_repo_path": "BIG_DATA/BIG_DATA.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4324,
"size": 14533
} |
/* -*- mode: C; c-basic-offset: 4 -*- */
/* ex: set shiftwidth=4 tabstop=4 expandtab: */
/*
* Copyright (c) 2011, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Neil T. Dantam <ntd@gatech.edu>
* Georgia Tech Humanoid Robotics Lab
* Under Direction of Prof. Mike Stilman <mstilman@cc.gatech.edu>
*
*
* This file is provided under the following "BSD-style" License:
*
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <amino.h>
#include <cblas.h>
#include "reflex.h"
#define SYMM_PART CblasUpper
#define SYMM_PARTC "U"
AA_API void rfx_lqg_kf_predict_cov( size_t n, const double *A, const double *V, double *P )
{
// P = A * P * A**T + V
int ni = (int)n;
double *T = (double*)aa_mem_region_local_tmpalloc( 2 * n*n * sizeof(P[0]) );
// T := A*P
cblas_dsymm( CblasColMajor, CblasRight, SYMM_PART,
ni, ni,
1.0, P, ni,
A, ni,
0.0, T, ni );
// P := (A*P) * A**T + V
dlacpy_( SYMM_PARTC, &ni, &ni,
V, &ni,
P, &ni );
cblas_dgemm( CblasColMajor, CblasNoTrans, CblasTrans,
ni, ni, ni,
1.0, T, ni,
A, ni,
1.0, P, ni );
}
int rfx_lqg_kf_correct_gain
( size_t n_x, size_t n_z, const double *C, const double *P, const double *W, double *K )
{
int nxi = (int)n_x;
int nzi = (int)n_z;
double *ptr = (double*) aa_mem_region_local_alloc( sizeof(ptr[0]) *
(n_z*n_x + n_z*n_z) );
double *CP = ptr;
double *Kp = &ptr[n_z*n_x];
// P is symmetric, so P*C^T == (C*P^T)^T == (C*P)^T
// Kp := C * P * C**T + W = C*(C*P)^T
// Kp^T := C*(C * P)^T
cblas_dsymm( CblasColMajor, CblasRight, SYMM_PART,
nzi, nxi,
1.0, P, nxi,
C, nzi,
0.0, CP, nzi );
dlacpy_( SYMM_PARTC, &nzi, &nzi,
W, &nzi,
Kp, &nzi );
cblas_dgemm( CblasColMajor, CblasNoTrans, CblasTrans,
nzi, nzi, nxi,
1.0, C, nzi,
CP, nzi,
1.0, Kp, nzi );
// K := P * C**T * Kp^-1
// K Kp := P * C**T
// CP = Kp^T K^T
// Kp is symmetric
// CP = Kp K^T
int info;
// Cholesky
dpotrf_( SYMM_PARTC, &nzi,
Kp, &nzi,
&info );
// Solve it!
dpotrs_( SYMM_PARTC, &nzi, &nxi,
Kp, &nzi,
CP, &nzi,
&info );
// Transpose
for( size_t j = 0; j < n_z; j ++ )
for( size_t i = 0; i < n_x; i ++ )
K[j*n_x+i] = CP[i*n_z+j];
int i = 0;
return i;
}
void rfx_lqg_kf_correct_cov
( size_t n_x, size_t n_z, const double *C, double *P, double *K )
{
int nxi = (int)n_x;
int nzi = (int)n_z;
double *ptr = (double*)aa_mem_region_local_tmpalloc( 2 * n_x*n_x * sizeof(P[0]) );
double *KC = ptr;
double *P1 = &ptr[n_x*n_x];
// P := (I - K*C) * P
cblas_dgemm( CblasColMajor, CblasNoTrans, CblasNoTrans,
nxi, nxi, nzi,
-1.0, K, nxi,
C, nzi,
0.0, KC, nxi );
// KC += I
for( size_t i = 0; i < n_x*n_x; i = i + n_x + 1 )
KC[i] += 1;
cblas_dsymm( CblasColMajor, CblasRight, SYMM_PART,
nxi, nxi,
1.0, P, nxi,
KC, nxi,
0.0, P1, nxi );
dlacpy_( SYMM_PARTC, &nxi, &nxi, P1, &nxi, P, &nxi );
}
int rfx_lqg_ekf_predict
( void *cx, size_t n_x, double *x, const double *u, double *P, const double *V,
rfx_lqg_ekf_process_fun process )
{
double F[n_x*n_x];
int i = process( cx, x, u, F );
rfx_lqg_kf_predict_cov( n_x, F, V, P );
return i;
}
int rfx_lqg_ekf_correct
( void *cx, size_t n_x, size_t n_z, double *x, const double *z, double *P, const double *W,
rfx_lqg_ekf_measure_fun measure, rfx_lqg_ekf_innovate_fun innovate, rfx_lqg_ekf_update_fun update )
{
int i;
double H[n_z*n_x];
double K[n_x*n_z];
{
double y[n_z];
i = measure(cx, x, y, H);
if(i) return i;
i = rfx_lqg_kf_correct_gain( n_x, n_z, H, P, W, K );
if(i) return i;
i = innovate(cx, x, z, y);
if(i) return i;
{
double Ky[n_x];
cblas_dgemv( CblasColMajor, CblasNoTrans,
(int)n_x, (int)n_z,
1.0, K, (int)n_x,
y, 1,
0.0, Ky, 1 );
i = update(cx, x, Ky);
}
}
rfx_lqg_kf_correct_cov( n_x, n_z, H, P, K );
return i;
}
AA_API void rfx_lqg_init( rfx_lqg_t *lqg, size_t n_x, size_t n_u, size_t n_z ) {
memset( lqg, 0, sizeof(*lqg) );
lqg->n_x = n_x;
lqg->n_u = n_u;
lqg->n_z = n_z;
lqg->x = AA_NEW0_AR( double, lqg->n_x );
lqg->u = AA_NEW0_AR( double, lqg->n_u );
lqg->z = AA_NEW0_AR( double, lqg->n_z );
lqg->A = AA_NEW0_AR( double, lqg->n_x * lqg->n_x );
lqg->B = AA_NEW0_AR( double, lqg->n_x * lqg->n_u );
lqg->C = AA_NEW0_AR( double, lqg->n_z * lqg->n_x );
lqg->P = AA_NEW0_AR( double, lqg->n_x * lqg->n_x );
lqg->V = AA_NEW0_AR( double, lqg->n_x * lqg->n_x );
lqg->W = AA_NEW0_AR( double, lqg->n_z * lqg->n_z );
lqg->Q = AA_NEW0_AR( double, lqg->n_x * lqg->n_x );
lqg->R = AA_NEW0_AR( double, lqg->n_u * lqg->n_u );
lqg->K = AA_NEW0_AR( double, lqg->n_z * lqg->n_x );
lqg->L = AA_NEW0_AR( double, lqg->n_u * lqg->n_x );
}
AA_API void rfx_lqg_destroy( rfx_lqg_t *lqg ) {
free(lqg->x);
free(lqg->u);
free(lqg->z);
free(lqg->A);
free(lqg->B);
free(lqg->C);
free(lqg->Q);
free(lqg->R);
free(lqg->L);
free(lqg->K);
}
/*
* X = op(A)*op(B)*op(C) + beta*X
*
* m*n = (m*k) * (k*n)
*
* X: m*n
* op(A): m*k
* op(B): k*p
* op(C): p*n
*/
static inline void matmul3( size_t m, size_t n, size_t k, size_t p,
enum CBLAS_TRANSPOSE transA,
enum CBLAS_TRANSPOSE transB,
enum CBLAS_TRANSPOSE transC,
const double *A, size_t lda,
const double *B, size_t ldb,
const double *C, size_t ldc,
double beta, double *X, size_t ldx) {
double T[m*p];
// T := A*B
cblas_dgemm( CblasColMajor, transA, transB,
(int)m, (int)p, (int)k,
1.0, A, (int)lda,
B, (int)ldb,
0.0, T, (int)m );
// X := (A*B) * C + beta*X
cblas_dgemm( CblasColMajor, CblasNoTrans, transC,
(int)m, (int)n, (int)p,
1.0, T, (int)m,
C, (int)ldc,
beta, X, (int)ldx );
}
static void kf_innovate( rfx_lqg_t *lqg, double *xh ) {
// xh = x + K * (z - C*x)
// T := z - C*x
double T[lqg->n_z];
memcpy(T, lqg->z, sizeof(T));
cblas_dgemv( CblasColMajor, CblasNoTrans,
(int)lqg->n_z, (int)lqg->n_x,
-1.0, lqg->C, (int)lqg->n_z,
lqg->x, 1,
1.0, T, 1 );
// xh = K * (z - C*x) + xh
cblas_dgemv( CblasColMajor, CblasNoTrans,
(int)lqg->n_x, (int)lqg->n_z,
1.0, lqg->K, (int)lqg->n_x,
T, 1,
1.0, xh, 1 );
}
AA_API void rfx_lqg_kf_predict( rfx_lqg_t *lqg ) {
// x = A*x + B*u
{
double x[lqg->n_x];
aa_lsim_dstep( lqg->n_x, lqg->n_u,
lqg->A, lqg->B,
lqg->x, lqg->u,
x );
memcpy(lqg->x, x, sizeof(x));
}
// P = A * P * A**T + V
rfx_lqg_kf_predict_cov( lqg->n_x, lqg->A, lqg->V, lqg->P );
}
AA_API void rfx_lqg_kf_correct( rfx_lqg_t *lqg ) {
rfx_lqg_kf_correct_gain( lqg->n_x, lqg->n_z,
lqg->C, lqg->P, lqg->W, lqg->K );
// x = x + K * (z - C*x)
kf_innovate( lqg, lqg->x );
// P = (I - K*C) * P
rfx_lqg_kf_correct_cov( lqg->n_x, lqg->n_z,
lqg->C, lqg->P, lqg->K );
}
// kalman-bucy gain
void rfx_lqg_kbf_gain( rfx_lqg_t *lqg )
{
rfx_lqg_kbf_gain_work( lqg->n_x, lqg->n_z,
lqg->A, lqg->C, lqg->V, lqg->W, lqg->P, lqg->K );
}
// kalman-bucy gain
void rfx_lqg_kbf_gain_work
( size_t n_x, size_t n_z,
const double *A, const double *C, const double *V, const double *W, double *P, double *K )
{
// dP = A*P + P*A' - P*C'*W^{-1}*C*P + V
// K = P * C' * W^{-1}
double Winv[n_z*n_z];
memcpy(Winv, W, sizeof(Winv));
aa_la_inv( n_z, Winv);
{
double ric_B[n_x*n_x];
// ric_B := C' * W^{-1} * C
matmul3( n_x, n_x, n_z, n_z,
CblasTrans, CblasNoTrans, CblasNoTrans,
C, n_z,
Winv, n_z,
C, n_z,
0.0, ric_B, n_x );
double ric_A[n_x*n_x];
aa_la_transpose2(n_x, n_x, A, ric_A );
// solve ARE with dP = 0, result is P
//aa_tick("laub: ");
aa_la_care_laub( n_x, n_x, n_x,
ric_A, ric_B, V, P );
//aa_tock();
}
// K = P * C' * W^{-1}
matmul3( n_x, n_z, n_x, n_z,
CblasNoTrans, CblasTrans, CblasNoTrans,
P, n_x,
C, n_z,
Winv, n_z,
0.0, K, n_x );
}
void rfx_lqg_lqr_gain( rfx_lqg_t *lqg ) {
// A'*S + S*A - S*B*R^{-1}*B'*S + Q = 0
double Rinv[lqg->n_u*lqg->n_u];
memcpy(Rinv, lqg->R, sizeof(Rinv));
aa_la_inv( lqg->n_u, Rinv);
double S[lqg->n_x*lqg->n_x];
{
double ric_B[lqg->n_x*lqg->n_x];
// ric_B := B * R^{-1} * B'
matmul3( lqg->n_x, lqg->n_x, lqg->n_u, lqg->n_u,
CblasNoTrans, CblasNoTrans, CblasTrans,
lqg->B, lqg->n_x,
Rinv, lqg->n_u,
lqg->B, lqg->n_x,
0.0, ric_B, lqg->n_x );
// solve ARE with dS = 0, result is S
aa_la_care_laub( lqg->n_x, lqg->n_x, lqg->n_x,
lqg->A, ric_B, lqg->Q, S );
}
// L = R^{-1}*B'*S
matmul3( lqg->n_u, lqg->n_x, lqg->n_u, lqg->n_x,
CblasNoTrans, CblasTrans, CblasNoTrans,
Rinv, lqg->n_u,
lqg->B, lqg->n_x,
S, lqg->n_x,
0.0, lqg->L, lqg->n_u );
}
static void kbf_step_fun( const void *cx,
double t, const double *restrict x,
double *restrict dx ) {
// dx = A*x + B*u + K(z-Cx)
(void)t;
rfx_lqg_t *lqg = (rfx_lqg_t*)cx;
// dx := A*x + B*u
aa_lsim_dstep( lqg->n_x, lqg->n_u,
lqg->A, lqg->B,
x, lqg->u,
dx );
// dx := K * (z - C*x) + dx
kf_innovate( lqg, dx );
}
void rfx_lqg_kbf_step1( rfx_lqg_t *lqg, double dt ) {
// dx = A*x + B*u + K(z-Cx)
double dx[lqg->n_x];
kbf_step_fun( lqg, 0, lqg->x, dx );
// x := dt*dx + x
cblas_daxpy( (int)lqg->n_x, dt, dx, 1, lqg->x, 1 );
}
void rfx_lqg_kbf_step4( rfx_lqg_t *lqg, double dt ) {
double x1[lqg->n_x];
// runge-kutta 4
aa_odestep_rk4( lqg->n_x, kbf_step_fun, lqg,
0, dt, lqg->x, x1 );
memcpy( lqg->x, x1, sizeof(x1) );
}
AA_API void rfx_lqg_lqr_ctrl( rfx_lqg_t *lqg ) {
cblas_dgemv( CblasColMajor, CblasNoTrans,
(int)lqg->n_u, (int)lqg->n_x,
-1.0, lqg->L, (int)lqg->n_u,
lqg->x, 1,
0.0, lqg->u, 1 );
}
void rfx_lqg_sys( const void *cx,
double t, const double *restrict x,
double *restrict dx ) {
rfx_lqg_t * lqg = (rfx_lqg_t*)cx;
(void)t;
aa_lsim_dstep( lqg->n_x, lqg->n_u,
lqg->A, lqg->B,
x, lqg->u,
dx );
}
//AA_API void rfx_lqg_observe_euler( rfx_lqg_t *lqg, double dt, aa_mem_region_t *reg ) {
// --- calculate kalman gain ---
// --- predict from previous input ---
// dx = A*x + B*u + K * ( z - C*xh )
//double *dx = (double*)aa_mem_region_alloc(reg, sizeof(double)*lqg->n_x);
// zz := z
//double *zz = (double*)aa_mem_region_alloc(reg, sizeof(double)*lqg->n_z);
// x = x + dx * dt
//aa_la_axpy( lqg->n_x, dt, dx, lqg->x );
//}
//AA_API void rfx_lqg_ctrl( rfx_lqg_t *lqg, double dt, aa_mem_region_t *reg ) {
// compute optimal gain
// -dS = A'*S + S*A - S*B*R^{-1}*B' + Q
// solve ARE, result is S
// L = R^{-1} * B' * S : (nu*nu) * (nu*nx) * (nx*nx)
// compute current input
// u = -Lx
//}
/* int rfx_lqg_duqu_predict */
/* ( double dt, double *S, double *dx, double *P, const double *V ) */
/* { */
/* return 0; */
/* } */
| {
"alphanum_fraction": 0.5015538918,
"avg_line_length": 27.5447470817,
"ext": "c",
"hexsha": "05377a441dd0bd8a1a6d9aa14ce81b18c0d5482a",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2021-05-05T12:58:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-23T18:09:25.000Z",
"max_forks_repo_head_hexsha": "a6df1ee7f101a1545186997401b200bbbbebcc64",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "golems/reflex",
"max_forks_repo_path": "src/lqg/lqg.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a6df1ee7f101a1545186997401b200bbbbebcc64",
"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": "golems/reflex",
"max_issues_repo_path": "src/lqg/lqg.c",
"max_line_length": 101,
"max_stars_count": 8,
"max_stars_repo_head_hexsha": "a6df1ee7f101a1545186997401b200bbbbebcc64",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "golems/reflex",
"max_stars_repo_path": "src/lqg/lqg.c",
"max_stars_repo_stars_event_max_datetime": "2021-03-29T10:12:01.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-11-29T02:12:02.000Z",
"num_tokens": 5140,
"size": 14158
} |
/* -----------------------------------------------------------------------------
* Copyright 2021 Jonathan Haigh
* SPDX-License-Identifier: MIT
* ---------------------------------------------------------------------------*/
#ifndef SQ_INCLUDE_GUARD_parser_FilterSpec_h_
#define SQ_INCLUDE_GUARD_parser_FilterSpec_h_
#include "core/Primitive.h"
#include "core/typeutil.h"
#include <compare>
#include <gsl/gsl>
#include <iosfwd>
#include <optional>
#include <variant>
namespace sq::parser {
/**
* Represents the lack of a filter specification for a field access.
*/
struct NoFilterSpec {
SQ_ND auto operator<=>(const NoFilterSpec &) const = default;
};
std::ostream &operator<<(std::ostream &os, NoFilterSpec nlfs);
/**
* Represents access of an indexed element in a list of results for a field
* access.
*/
struct ElementAccessSpec {
gsl::index index_;
SQ_ND auto operator<=>(const ElementAccessSpec &) const = default;
};
std::ostream &operator<<(std::ostream &os, ElementAccessSpec leas);
/**
* Represents a Python-style slice of a list of results for a field access.
*/
struct SliceSpec {
std::optional<gsl::index> start_;
std::optional<gsl::index> stop_;
std::optional<gsl::index> step_;
SQ_ND auto operator<=>(const SliceSpec &) const = default;
};
std::ostream &operator<<(std::ostream &os, SliceSpec lss);
enum class ComparisonOperator {
GreaterThanOrEqualTo,
GreaterThan,
LessThanOrEqualTo,
LessThan,
Equals
};
/**
* Represents a comparison to determine whether to keep a field or not.
*/
struct ComparisonSpec {
std::string member_;
ComparisonOperator op_;
Primitive value_;
SQ_ND auto operator<=>(const ComparisonSpec &) const = default;
};
std::ostream &operator<<(std::ostream &os, const ComparisonOperator &op);
std::ostream &operator<<(std::ostream &os, const ComparisonSpec &cs);
using FilterSpec =
std::variant<NoFilterSpec, ElementAccessSpec, SliceSpec, ComparisonSpec>;
} // namespace sq::parser
#endif // SQ_INCLUDE_GUARD_parser_FilterSpec_h_
| {
"alphanum_fraction": 0.6770524233,
"avg_line_length": 26.6052631579,
"ext": "h",
"hexsha": "af58e43b58ba955b0520a3f5a140e6d3e5f5043b",
"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": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jonathanhaigh/sq",
"max_forks_repo_path": "src/parser/include/parser/FilterSpec.h",
"max_issues_count": 44,
"max_issues_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_issues_repo_issues_event_max_datetime": "2021-04-05T18:51:38.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-02-08T19:17:57.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jonathanhaigh/sq",
"max_issues_repo_path": "src/parser/include/parser/FilterSpec.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "6ca366b86ff6436620c36eabb1f0103cab88722b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jonathanhaigh/sq",
"max_stars_repo_path": "src/parser/include/parser/FilterSpec.h",
"max_stars_repo_stars_event_max_datetime": "2020-11-12T16:21:41.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-11-12T16:21:41.000Z",
"num_tokens": 457,
"size": 2022
} |
#if !defined(DECAY_H)
#define DECAY_H
#include "SM.h"
#include "THDM.h"
#include <complex>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_integration.h>
using namespace std;
/**
* @brief Calculates the decay modes of 2HDM Higgs bosons
*
* Given a THDM object, a DecayTable can be generated. From this table, the
* Higgs boson decay widths and branching ratios are obtained. For the complete
* list of available decay modes, we refer to the complete documentation, or
* the list of member methods below.
*/
class DecayTable {
public:
/**
* @brief Default constructor
*
* This default constructor takes a THDM object as argument for which
* the decays are to be calculated. %SM properties are taken from the SM
* object in the THDM.
*
* @param mod Two-Higgs doublet model for which to calculate decay modes
*/
DecayTable(THDM mod);
/**
* @brief Sets underlying 2HDM
*
* This method sets the THDM underlying the DecayTable.
*
* @param model Two-Higgs doublet model for which to calculate decay modes
*/
void set_model(THDM model);
/**
* @brief Underlying 2HDM
*
* Use to obtain the underlying THDM object
*
* @returns The THDM object on which this DecayTable operates
*/
THDM get_model();
/**
* @brief Decay width \f$\Gamma(h\to u_1\overline{u}_2) \f$
*
* This method calculates the on-shell decay width for the decay of Higgs
* boson \a h to a pair of up-type quarks. QCD corrections have been included.
*
* @param h Index of Higgs boson (1,2,3 = h,H,A)
* @param u1 Index of up-type quark (1,2,3 = \f$ u,c,t \f$)
* @param u2 Index of up-type antiquark (1,2,3 = \f$ \bar{u},\bar{c},\bar{t} \f$)
*
* @returns The decay width in GeV
*/
double get_gamma_huu(int h, int u1, int u2);
/**
* @brief Decay width \f$ \Gamma(h\to d_1\overline{d}_2) \f$
*
* This method calculates the on-shell decay width for the decay of Higgs
* boson \a h to a pair of down-type quarks. QCD corrections have been included.
*
* @param h Index of Higgs boson (1,2,3 = h,H,A)
* @param d1 Index of down-type quark (1,2,3 = \f$ d,s,b \f$)
* @param d2 Index of down-type antiquark (1,2,3 = \f$ \bar{d},\bar{s},\bar{b} \f$)
*
* @returns The decay width in GeV
*/
double get_gamma_hdd(int h, int d1, int d2);
/**
* @brief Decay width \f$ \Gamma(h\to l_1\overline{l}_2) \f$
*
* This method calculates the on-shell decay width for the decay of Higgs
* boson \a h to a pair of charged leptons.
*
* @param h Index of Higgs boson (1,2,3 = h,H,A)
* @param l1 Index of lepton (1,2,3 = \f$ e,\mu,\tau \f$)
* @param l2 Index of antilepton (1,2,3 = \f$ \bar{e},\bar{\mu},\bar{\tau} \f$)
*
* @returns The decay width in GeV
*/
double get_gamma_hll(int h, int l1, int l2);
/**
* @brief Decay width \f$ \Gamma(h\to u\overline{d}) \f$
*
* This method calculates the on-shell decay width for the decay of Higgs
* boson \a h to a pair of quarks. QCD corrections have been included.
*
* @param h Index of Higgs boson (4 = H+)
* @param d Index of down-type antiquark (1,2,3 = \f$ \bar{d},\bar{s},\bar{b} \f$)
* @param u Index of up-type quark (1,2,3 = \f$ u,c,t \f$)
*
* @returns The decay width in GeV
*/
double get_gamma_hdu(int h, int d, int u);
/**
* @brief Decay width \f$ \Gamma(h\to l\overline{\nu}_{l'}) \f$
*
* This method calculates the on-shell decay width for the decay of Higgs
* boson \a h to lepton-neutrino.
*
* @param h Index of Higgs boson (4 = H+)
* @param l Index of charged lepton (1,2,3 = \f$ e^+,\mu^+,\tau^+ \f$)
* @param n Index of neutrino (1,2,3 = \f$ \nu_e,\nu_\mu,\nu_\tau \f$)
*
* @returns The decay width in GeV
*/
double get_gamma_hln(int h, int l, int n);
/**
* @brief Decay width \f$ \Gamma(h\to H_1 H_2) \f$
*
* This method calculates the on-shell decay width for the decay of Higgs
* boson \a h to a pair of Higgs bosons
*
* @param h Index of decaying Higgs boson (1,2,3,4 = h,H,A,H+)
* @param h1 Index of first Higgs boson (1,2,3,4 = h,H,A,H+)
* @param h2 Index of second Higgs boson (1,2,3,4 = h,H,A,H+)
*
* @returns The decay width in GeV
*/
double get_gamma_hhh(int h, int h1, int h2);
/**
* @brief Decay width \f$ \Gamma(h\to VV) \f$
*
* This method calculates the decay width for the Higgs boson \a h
* to a pair of vector bosons. The decay mode with one vector
* boson off-shell is included.
*
* @param h Index of decaying Higgs boson (1,2,3,4 = h,H,A,H+)
* @param v Index of vector bosons (1,2,3 = \f$\gamma \f$,Z,W)
*
* @returns The decay width in GeV
*/
double get_gamma_hvv(int h, int v);
/**
* @brief Decay width \f$ \Gamma(h\to VH) \f$
*
* This method calculates the decay width for the Higgs boson \a h
* to one massive vector and one Higgs boson. Decay with the vector
* boson off-shell is included.
*
* @param h Index of decaying Higgs boson (1,2,3,4 = h,H,A,H+)
* @param V Index of vector boson (2,3 = \f$\gamma \f$,Z,W)
* @param H Index of final-state Higgs boson (1,2,3,4 = h,H,A,H+)
*
* @returns The decay width in GeV
*/
double get_gamma_hvh(int H, int V, int h);
/**
* @brief Decay width \f$ \Gamma(h\to gg) \f$
*
* This method calculates the decay width for the Higgs boson \a h
* to a pair of gluons. LO QCD corrections are included.
*
* @param h Index of decaying Higgs boson (1,2,3,4 = h,H,A,H+)
*
* @returns The decay width in GeV
*/
double get_gamma_hgg(int h);
/**
* @brief Decay width \f$ \Gamma(h\to \gamma\gamma) \f$
*
* This method calculates the decay width for the neutral
* Higgs boson \a h to a pair of photons.
*
* @param h Index of decaying Higgs boson (1,2,3 = h,H,A)
*
* @returns The decay width in GeV
*/
double get_gamma_hgaga(int h);
/**
* @brief Decay width \f$ \Gamma(h\to Z\gamma) \f$
*
* This method calculates the decay width for the neutral
* Higgs boson \a h to a Z and a photon.
*
* @param h Index of decaying Higgs boson (1,2,3 = h,H,A)
*
* @returns The decay width in GeV
*/
double get_gamma_hZga(int h);
/**
* @brief Decay width \f$ \Gamma(h\to WZ) \f$
*
* This method calculates the decay width for the neutral
* Higgs boson \a h to a Z and a photon.
*
* @param h Index of decaying Higgs boson (4 = H+-)
*
* @returns The decay width in GeV
*/
double get_gamma_hWZ(int h);
/**
* @brief Decay width \f$ \Gamma(h\to W\gamma) \f$
*
* This method calculates the decay width for the neutral
* Higgs boson \a h to a Z and a photon.
*
* @param h Index of decaying Higgs boson (4 = H+-)
*
* @returns The decay width in GeV
*/
double get_gamma_hWga(int h);
/**
* @brief Total width \f$ \Gamma_h \f$
*
* Calculates the total decay width of Higgs boson \a h
*
* @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)
*
* @returns Total width in GeV
*/
double get_gammatot_h(int h);
/**
* @brief Total width \f$ \Gamma_V \f$
*
* Returns the total decay width of vector boson \a v
*
* @param v Index of vector boson (2,3 = Z,W)
*
* @returns Total width in GeV
*/
double get_gammatot_v(int v);
/**
* @brief Total width \f$ \Gamma_t \f$
*
* Returns the total decay width of the top quark
*
* @returns Total width in GeV
*/
double get_gammatot_top();
/**
* @brief Decay width for \f$ t \to H^+X \f$
*
* Returns the decay width of the top quark in the charged Higgs mode
*
* @returns Decay width in GeV
*
* @param u Index of decaying quark (1,2,3 = \f$ u,c,t \f$)
* @param h Index of Higgs boson (4 = H+)
* @param d Index of down-type quark (1,2,3 = \f$ d,s,b \f$)
*/
double get_gamma_uhd(int u, int h, int d);
double get_gamma_uhu(int u1, int h, int u2);
/**
* @brief Prints the decay modes of a Higgs boson
*
* The decay modes of Higgs boson \a h are printed to stdout
*
* @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)
*/
void print_decays(int h);
/**
* @brief Prints the total width of a Higgs boson
*
* The total decay width of Higgs boson \a h are printed to stdout
*
* @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)
*/
void print_width(int h);
/**
* @brief Prints the decay modes of the top quark
*
* The decay modes of the top quark are printed to stdout
*/
void print_top_decays();
/**
* @brief Prints decay information for a Higgs boson in LesHouches format
*
* The decay information for Higgs boson \a h are printed to a file in
* LesHouches format
*
* @param output The name of the output file to write
* @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)
* @param full If \a true, all decay modes are printed, if \a false only the total width
*/
void print_decays_LesHouches(FILE* output, int h, bool full);
/**
* @brief Prints decay information for the top quark in LesHouches format
*
* The decay information for the top quark are printed to a file in
* LesHouches format
*
* @param output The name of the output file to write
* @param full If \a true, all decay modes are printed, if \a false only the total width
*/
void print_top_decays_LesHouches(FILE* output, bool full);
/**
* @brief Turns QCD corrections on or off
*
* This method is used to turn QCD corrections on or off. If the output is
* meant to be used with the MadGraph/MadEvent 2HDMC model
* QCD corrections should be turned off to get a consistent result.
*
* @param set If \a true QCD corrections are turned on,
* if \a false QCD corrections are turned off
*/
void set_qcd(bool set);
static double DHp(double ui, double uj, double xi, double xj, double sqL);
static double DHm(double ui, double uj, double xi, double xj, double sqL);
static double BHp(double ui, double uj, double xi, double xj, double sqL);
private:
THDM model;
SM sm;
complex <double> F_sf(double t);
complex <double> F_pf(double t);
complex <double> F_0(double t);
complex <double> F_1(double t);
complex <double> ftau(double t);
complex <double> gtau(double t);
complex <double> I_1(double tau, double lambda);
complex <double> I_2(double tau, double lambda);
complex <double> FF_s(double tau, double lambda);
complex <double> FF_p(double tau, double lambda);
complex <double> FW(double tau, double lambda);
complex <double> FHp(double tau, double lambda);
double gammatot_h[5];
double gamma_uhd[5][5][5];
double gamma_uhu[5][5][5];
double gamma_hdd[5][5][5];
double gamma_huu[5][5][5];
double gamma_hdu[5][5][5];
double gamma_hll[5][5][5];
double gamma_hln[5][5][5];
double gamma_hgg[5];
double gamma_hgaga[5];
double gamma_hZga[5];
double gamma_hWga[5]; // For H+- only
double gamma_hWZ[5]; // For H+- only
double gamma_hvv[5][5];
double gamma_hvh[5][5][5];
double gamma_hhh[5][5][5];
double br(double dG, double G);
double hvv_onshell(int h, int V, double M);
double hvv_offshell(int h, int V, double M);
double hvv_all(int h, int V, double M);
double hff_onshell(double M, double m1, double m1run, double m2, double m2run, complex<double> cs, complex<double> cp, int Nc, int h, bool tt);
double hpff_onshell(double M, double m1, double m1run, double m2, double m2run, complex<double> cs, complex<double> cp, int Nc, int h);
double htt_onshell(double M, double m1, double m2, int Nc, int h);
double htt_offshell(double M, double m1, double m2, int Nc, int h);
double htb_offshell(double M, double m1, double m1run, double m2, double m2run, complex<double> cs, complex<double> cp, int Nc);
double hvh_onshell(int H, int V, int h, double M);
double hvh_offshell(int H, int V, int h, double M);
double hdu_offshell(int h, int d, int u, double M);
double hgaga(int h);
double hZga(int h);
double hWga(int h);
double hWZ(int h);
double hgg(int h);
double PS2(double M, double m1, double m2);
double LAM(double m12, double m22, double m32);
double interp(double R, double x, double y, double c);
bool qcd_on;
int err_code;
void print_decay_LesHouches(FILE* output, double br, int id1, int id2);
void print_decay(const char *h, const char *id1, const char *id2, double g, double br);
void print_decays(FILE* output, int h, bool full, bool lh);
};
#endif
| {
"alphanum_fraction": 0.641011236,
"avg_line_length": 29.7374701671,
"ext": "h",
"hexsha": "190d626ad1d7e028bbe0c73eb95d4ff1dcb55687",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-11-27T14:59:29.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-11-27T14:59:29.000Z",
"max_forks_repo_head_hexsha": "2202e80479749b521a384f68aee27611b323dc74",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ycwu1030/2HDMC-NLO",
"max_forks_repo_path": "src/DecayTable.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2202e80479749b521a384f68aee27611b323dc74",
"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/2HDMC-NLO",
"max_issues_repo_path": "src/DecayTable.h",
"max_line_length": 146,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2202e80479749b521a384f68aee27611b323dc74",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ycwu1030/2HDMC-NLO",
"max_stars_repo_path": "src/DecayTable.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4235,
"size": 12460
} |
/* Easel's interfaces to the GNU Scientific Library
*/
#ifdef HAVE_LIBGSL
#include "esl_config.h"
#include <stdlib.h>
#include "easel/easel.h"
#include "easel/dmatrix.h"
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_eigen.h>
int
esl_GSL_MatrixInversion(ESL_DMATRIX *A, ESL_DMATRIX **ret_Ai)
{
ESL_DMATRIX *Ai; /* RETURN: A^{-1} */
gsl_matrix_view Av; /* gsl view of matrix A */
gsl_matrix *LU; /* LU decomposition of A */
gsl_matrix *Aiv; /* gsl version of A^{-1} */
gsl_permutation *permute;
int signum;
int i,j;
Ai = esl_dmx_Alloc(A->n, A->m);
/* Invert U to get Ui, using LU decomposition.
*/
Av = gsl_matrix_view_array(A->mx[0], A->n, A->n);
LU = gsl_matrix_alloc(A->n, A->n);
Aiv = gsl_matrix_alloc(A->n, A->n); /* U^{-1}: inverse of U */
permute = gsl_permutation_alloc(A->n);
gsl_matrix_memcpy(LU, &Av.matrix);
if (gsl_linalg_LU_decomp(LU, permute, &signum) != 0) ESL_EXCEPTION(eslEUNKNOWN, "gsl failed");
if (gsl_linalg_LU_invert(LU, permute, Aiv) != 0) ESL_EXCEPTION(eslEUNKNOWN, "gsl failed");
gsl_matrix_free(LU);
gsl_permutation_free(permute);
/* recover the matrix from gsl.
*/
for (i = 0; i < A->n; i++)
for (j = 0; j < A->n; j++)
Ai->mx[i][j] = gsl_matrix_get(Aiv, i, j);
gsl_matrix_free(Aiv);
ret->Ai = Ai;
return eslOK;
}
#endif /*HAVE_LIBGSL*/
/*****************************************************************
* @LICENSE@
*
* SVN $Id$
* SVN $URL$
*****************************************************************/
| {
"alphanum_fraction": 0.5477031802,
"avg_line_length": 27.8360655738,
"ext": "c",
"hexsha": "bda7c3a27bb833dbe72d6963bced2dae2106f380",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-06-05T08:02:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-05T07:40:20.000Z",
"max_forks_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-",
"max_forks_repo_path": "src/metaspades/ext/src/easel/interface_gsl.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b",
"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": "STRIDES-Codes/Exploring-the-Microbiome-",
"max_issues_repo_path": "src/metaspades/ext/src/easel/interface_gsl.c",
"max_line_length": 96,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "bd29c8c74d8f40a58b63db28815acb4081f20d6b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "STRIDES-Codes/Exploring-the-Microbiome-",
"max_stars_repo_path": "src/metaspades/ext/src/easel/interface_gsl.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 515,
"size": 1698
} |
/*
* 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 scene_048bb735_09b4_43d2_9ff5_5e40441c230b_h
#define scene_048bb735_09b4_43d2_9ff5_5e40441c230b_h
#include <gslib/std.h>
#include <ariel/config.h>
#include <ariel/rendersys.h>
#include <ariel/framesys.h>
#include <ariel/widget.h>
__ariel_begin__
class rose;
class stage;
typedef list<stage*> stages;
class __gs_novtable stage abstract:
public frame_listener
{
public:
stage();
virtual ~stage() {}
virtual const gchar* get_name() const = 0;
virtual bool setup() = 0;
virtual void draw() = 0;
public:
template<class _sty> inline
_sty* as() { return static_cast<_sty*>(this); }
template<class _sty> inline
const _sty* as_const() const { return static_cast<const _sty*>(this); }
protected:
stage* _prev_presentation_stage;
stage* _next_presentation_stage;
stage* _prev_notification_stage;
stage* _next_notification_stage;
protected:
void on_next_draw();
void on_next_frame_start();
void on_next_frame_end();
bool on_next_event(const frame_event& event);
public:
stage* prev_presentation_stage() const { return _prev_presentation_stage; }
stage* next_presentation_stage() const { return _next_presentation_stage; }
stage* prev_notification_stage() const { return _prev_notification_stage; }
stage* next_notification_stage() const { return _next_notification_stage; }
public:
static void connect_presentation_order(stage* stg1, stage* stg2);
static void connect_notification_order(stage* stg1, stage* stg2);
static void connect_presentation_order(stage* stg1, stage* stg2, stage* stg3);
static void connect_notification_order(stage* stg1, stage* stg2, stage* stg3);
};
class ui_stage:
public stage
{
public:
ui_stage(rose* r) { _rose = r; }
virtual const gchar* get_name() const override { return _t("ui"); }
virtual bool setup() override;
virtual void draw() override;
virtual void on_frame_start() override { on_next_frame_start(); }
virtual void on_frame_end() override { on_next_frame_end(); }
virtual bool on_frame_event(const frame_event& event) override;
public:
wsys_manager* get_wsys_manager() { return &_wsys_manager; }
protected:
rose* _rose;
wsys_manager _wsys_manager;
private:
void setup_draw();
};
class scene:
public frame_listener
{
public:
static scene* get_singleton_ptr()
{
static scene inst;
return &inst;
}
private:
scene();
public:
~scene();
stage* get_stage(const gchar* name);
wsys_manager* get_ui_system() const { return _uisys; }
fontsys* get_fontsys() const { return _fontsys; }
rendersys* get_rendersys() const { return _rendersys; }
void set_rendersys(rendersys* rsys) { _rendersys = rsys; }
void set_rose(rose* ptr) { _rose = ptr; }
void set_fontsys(fontsys* fsys);
void setup();
void destroy();
void destroy_all_stages();
void add_stage(stage* stg) { _stages.push_back(stg); }
void set_presentation_before(stage* pos, stage* tar);
void set_presentation_after(stage* pos, stage* tar);
void set_notification_before(stage* pos, stage* tar);
void set_notification_after(stage* pos, stage* tar);
protected:
rendersys* _rendersys;
rose* _rose;
stages _stages;
wsys_manager* _uisys;
fontsys* _fontsys;
stage* _notify;
stage* _present;
protected:
void draw();
public:
virtual void on_frame_start() override;
virtual void on_frame_end() override;
virtual bool on_frame_event(const frame_event& event) override;
};
__ariel_end__
#endif
| {
"alphanum_fraction": 0.6799375488,
"avg_line_length": 32.2264150943,
"ext": "h",
"hexsha": "8d4c8c9053e9db1b5d4eff49a8c71b097d54894a",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z",
"max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lymastee/gslib",
"max_forks_repo_path": "include/ariel/scene.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "lymastee/gslib",
"max_issues_repo_path": "include/ariel/scene.h",
"max_line_length": 83,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lymastee/gslib",
"max_stars_repo_path": "include/ariel/scene.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": 1228,
"size": 5124
} |
/* histogram/test_trap.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 <stdio.h>
#include <gsl/gsl_histogram.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_ieee_utils.h>
#define N 397
void my_error_handler (const char *reason, const char *file,
int line, int err);
int status = 0;
int
main (void)
{
gsl_histogram *h;
double result, lower, upper;
size_t i;
gsl_set_error_handler (&my_error_handler);
gsl_ieee_env_setup ();
status = 0;
h = gsl_histogram_calloc (0);
gsl_test (!status, "gsl_histogram_calloc traps zero-length histogram");
gsl_test (h != 0,
"gsl_histogram_calloc returns NULL for zero-length histogram");
status = 0;
h = gsl_histogram_calloc_uniform (0, 0.0, 1.0);
gsl_test (!status,
"gsl_histogram_calloc_uniform traps zero-length histogram");
gsl_test (h != 0,
"gsl_histogram_calloc_uniform returns NULL for zero-length histogram");
status = 0;
h = gsl_histogram_calloc_uniform (10, 1.0, 1.0);
gsl_test (!status,
"gsl_histogram_calloc_uniform traps equal endpoints");
gsl_test (h != 0,
"gsl_histogram_calloc_uniform returns NULL for equal endpoints");
status = 0;
h = gsl_histogram_calloc_uniform (10, 2.0, 1.0);
gsl_test (!status,
"gsl_histogram_calloc_uniform traps invalid range");
gsl_test (h != 0,
"gsl_histogram_calloc_uniform returns NULL for invalid range");
h = gsl_histogram_calloc_uniform (N, 0.0, 1.0);
status = gsl_histogram_accumulate (h, 1.0, 10.0);
gsl_test (status != GSL_EDOM, "gsl_histogram_accumulate traps x at xmax");
status = gsl_histogram_accumulate (h, 2.0, 100.0);
gsl_test (status != GSL_EDOM, "gsl_histogram_accumulate traps x above xmax");
status = gsl_histogram_accumulate (h, -1.0, 1000.0);
gsl_test (status != GSL_EDOM, "gsl_histogram_accumulate traps x below xmin");
status = gsl_histogram_increment (h, 1.0);
gsl_test (status != GSL_EDOM, "gsl_histogram_increment traps x at xmax");
status = gsl_histogram_increment (h, 2.0);
gsl_test (status != GSL_EDOM, "gsl_histogram_increment traps x above xmax");
status = gsl_histogram_increment (h, -1.0);
gsl_test (status != GSL_EDOM, "gsl_histogram_increment traps x below xmin");
result = gsl_histogram_get (h, N);
gsl_test (result != 0, "gsl_histogram_get traps index at n");
result = gsl_histogram_get (h, N + 1);
gsl_test (result != 0, "gsl_histogram_get traps index above n");
status = gsl_histogram_get_range (h, N, &lower, &upper);
gsl_test (status != GSL_EDOM,
"gsl_histogram_get_range traps index at n");
status = gsl_histogram_get_range (h, N + 1, &lower, &upper);
gsl_test (status != GSL_EDOM,
"gsl_histogram_get_range traps index above n");
status = 0;
gsl_histogram_find (h, -0.01, &i);
gsl_test (status != GSL_EDOM, "gsl_histogram_find traps x below xmin");
status = 0;
gsl_histogram_find (h, 1.0, &i);
gsl_test (status != GSL_EDOM, "gsl_histogram_find traps x at xmax");
status = 0;
gsl_histogram_find (h, 1.1, &i);
gsl_test (status != GSL_EDOM, "gsl_histogram_find traps x above xmax");
gsl_histogram_free (h);
exit (gsl_test_summary ());
}
void
my_error_handler (const char *reason, const char *file, int line, int err)
{
if (0)
printf ("(caught [%s:%d: %s (%d)])\n", file, line, reason, err);
status = 1;
}
| {
"alphanum_fraction": 0.7058823529,
"avg_line_length": 30.9323308271,
"ext": "c",
"hexsha": "f1136384a7e8b5597f6e1244952b2861c6c9df53",
"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/histogram/test_trap.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/histogram/test_trap.c",
"max_line_length": 79,
"max_stars_count": 14,
"max_stars_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "ICML14MoMCompare/spectral-learn",
"max_stars_repo_path": "code/em/treba/gsl-1.0/histogram/test_trap.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": 1181,
"size": 4114
} |
// Use the geodesic solver code to create a gsl implementation so you can
// compare the speeds. The template needs to get close to ,ideally better than,
// exactly to the gsl run times
#include <stdio.h>
#include <iostream>
#include <chrono>
#include <math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv2.h>
const double alpha = 1.32754125e20;
int odefunc (double x, const double y[], double f[], void *params)
{
f[0] = y[3];
f[1] = y[4];
f[2] = y[5];
double r = sqrt(y[0]*y[0]+y[1]*y[1]+y[2]*y[2]);
f[3] = -(alpha*y[0]) / (r*r*r);
f[4] = -(alpha*y[1]) / (r*r*r);
f[5] = -(alpha*y[2]) / (r*r*r);
return GSL_SUCCESS;
}
int main ()
{
double AU = 1.496e11; // astronomical unit
double V = 30000.0; // initial velocity
// initial conditions
double y0[] = {0.0,AU,0.0,-V,0.0,0.0};
double T0 = 0.0;
double Tf = 7.2e6;
double hi = 7.2e3/3;
int dim = 6;
gsl_odeiv2_system sys = {odefunc, NULL, dim, NULL};
gsl_odeiv2_driver * d = gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rkf45, hi, 1e-5, 0.0);
auto Nruns = 5000;
auto totalDuration = 0;
auto t1 = std::chrono::high_resolution_clock::now();
double T;
for (int i = 1; i <= Nruns; i++)
{
T0 = 0.0;
T = Tf;
y0[0]=0.0;
y0[1] = AU;
y0[2] = 0.0;
y0[3] = -V;
y0[4] = 0.0;
y0[5] = 0.0;
gsl_odeiv2_driver_apply (d, &T0, T, y0);
}
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
totalDuration += duration;
std::cout << "GSL runs" << std::endl;
std::cout << totalDuration/Nruns << std::endl;
for(int j = 0 ; j < 6 ; j++)
{
std::cout << y0[j] << ",";
}
std::cout << std::endl;
gsl_odeiv2_driver_free (d);
return 0;
} | {
"alphanum_fraction": 0.5611660593,
"avg_line_length": 27.4428571429,
"ext": "c",
"hexsha": "0ea776fb8b030e6e2d3cf0474496ae4e6a38d8b3",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-03-30T17:13:40.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-03-30T17:13:40.000Z",
"max_forks_repo_head_hexsha": "6a591ea283d22aa687ab97d760bfdd21b2a55a2d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jman27182818/RKF45",
"max_forks_repo_path": "gccExample/newton.c",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "6a591ea283d22aa687ab97d760bfdd21b2a55a2d",
"max_issues_repo_issues_event_max_datetime": "2021-03-05T00:55:14.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-06-28T22:42:42.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "jman27182818/RKF45",
"max_issues_repo_path": "gccExample/newton.c",
"max_line_length": 103,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6a591ea283d22aa687ab97d760bfdd21b2a55a2d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jman27182818/RKF45",
"max_stars_repo_path": "gccExample/newton.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 701,
"size": 1921
} |
/* integration/jacobi.c
*
* Copyright (C) 2017 Konrad Griessinger, Patrick Alken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/*
* The code in this module is based on IQPACK, specifically the LGPL
* implementation found in HERMITE_RULE:
* https://people.sc.fsu.edu/~jburkardt/c_src/hermite_rule/hermite_rule.html
*/
#include <stdio.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_integration.h>
#include <gsl/gsl_sf_gamma.h>
static int
jacobi_check(const size_t n, const gsl_integration_fixed_params * params)
{
(void) n;
if (fabs(params->b - params->a) <= GSL_DBL_EPSILON)
{
GSL_ERROR("|b - a| too small", GSL_EDOM);
}
else if (params->a >= params->b)
{
GSL_ERROR("lower integration limit must be smaller than upper limit", GSL_EDOM);
}
else if (params->alpha <= -1.0 || params->beta <= -1.0)
{
GSL_ERROR("alpha and beta must be > -1", GSL_EDOM);
}
else
{
return GSL_SUCCESS;
}
}
static int
jacobi_init(const size_t n, double * diag, double * subdiag, gsl_integration_fixed_params * params)
{
const double absum = params->beta + params->alpha;
const double abdiff = params->beta - params->alpha;
const double a2b2 = absum * abdiff; /* beta^2 - alpha^2 */
size_t i;
/* construct the diagonal and subdiagonal elements of Jacobi matrix */
diag[0] = abdiff/(absum + 2.0);
subdiag[0] = 2.0*sqrt((params->alpha + 1.0)*(params->beta + 1.0)/(absum + 3.0))/(absum + 2.0);
for (i = 1; i < n; i++)
{
diag[i] = a2b2 / ( (absum + 2.0*i) * (absum + 2.0*i + 2.0) );
subdiag[i] = sqrt ( 4.0*(i + 1.0) * (params->alpha + i + 1.0) * (params->beta + i + 1.0) * (absum + i + 1.0) / ( pow((absum + 2.0*i + 2.0), 2.0) - 1.0 ) ) / ( absum + 2.0*i + 2.0 );
}
params->zemu = pow(2.0, absum + 1.0) * gsl_sf_gamma(params->alpha + 1.0) * gsl_sf_gamma(params->beta + 1.0) / gsl_sf_gamma(absum + 2.0);
params->shft = 0.5*(params->b + params->a);
params->slp = 0.5*(params->b - params->a);
params->al = params->alpha;
params->be = params->beta;
return GSL_SUCCESS;
}
static const gsl_integration_fixed_type jacobi_type =
{
jacobi_check,
jacobi_init
};
const gsl_integration_fixed_type *gsl_integration_fixed_jacobi = &jacobi_type;
| {
"alphanum_fraction": 0.6617996604,
"avg_line_length": 33.4659090909,
"ext": "c",
"hexsha": "0c0637b05976fe844f2b141a3bfa796982d22479",
"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/integration/jacobi.c",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e",
"max_issues_repo_issues_event_max_datetime": "2019-12-22T00:00:16.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-16T17:41:24.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "Brian-ning/HMNE",
"max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/integration/jacobi.c",
"max_line_length": 187,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ielomariala/Hex-Game",
"max_stars_repo_path": "gsl-2.6/integration/jacobi.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": 926,
"size": 2945
} |
////
//
// Copyright (c) 2010-
// NAKASATO, Naohito
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 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 AUTHOR OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE.
//
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <malloc.h>
#include <string.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <cblas.h>
#include "accllib.h"
#include "kernel_TN.h"
#include "kernel_NN.h"
#include "kernel_NT.h"
#include "kernel_TT.h"
int dev = 0;
double e_time(void)
{
static struct timeval now;
gettimeofday(&now, NULL);
return (double)(now.tv_sec + now.tv_usec/1000000.0);
}
double *tmp_A, *tmp_B, *tmp_C, *tmp_D, *tmp_E;
void get_matrix(int dev, double *src, int isrc, double *dma, int idma, int s)
{
ACCLmemcpy(dev, isrc, idma);
memcpy(src, dma, s);
}
void set_matrix(int dev, double *src, int isrc, double *dma, int idma, int s)
{
memcpy(dma, src, s);
ACCLmemcpy(dev, idma, isrc);
}
void my_dgemm(int dev, int mod, int n)
{
set_matrix(dev, tmp_A, 0, tmp_E, 6, sizeof(double)*n*n);
set_matrix(dev, tmp_B, 1, tmp_E, 6, sizeof(double)*n*n);
set_matrix(dev, tmp_C, 2, tmp_E, 6, sizeof(double)*n*n);
ACCLrun_on_domain(dev, mod, n/4, n/4);
get_matrix(dev, tmp_C, 2, tmp_E, 6, sizeof(double)*n*n);
}
void check(double *p1, double *p2, int n)
{
double norm = 0.0;
for(int i = 0; i < n*n; i++) {
double dx = fabs(p1[i] - p2[i]);
if (dx > norm) {
norm = dx;
}
}
printf("N = %5i : norm %e\t", n, norm);
}
void out(int n, double t_noio, double t_io, int niter)
{
fprintf(stdout, "%g %g %g %g\n",
t_noio/niter, niter*(double)n*(double)n*(double)n*2.0/t_noio/1.0e9,
t_io/niter, niter*(double)n*(double)n*(double)n*2.0/t_io/1.0e9
);
}
int main(int narg, char **argv)
{
int n;
int ss;
int flag = 0;
int test_mode = 0;
int mod;
double alpha, beta;
ACCLopen();
ACCLallocate(dev);
if ( ACCLloadkernel(dev, 0, d_TN, 2) < 0) exit(-1);
if ( ACCLloadkernel(dev, 1, d_NN, 2) < 0) exit(-1);
if ( ACCLloadkernel(dev, 2, d_NT, 2) < 0) exit(-1);
if ( ACCLloadkernel(dev, 3, d_TT, 2) < 0) exit(-1);
if (narg == 1) {
n = 512;
} else {
n = atoi(argv[1]);
}
if (n % 64 != 0) {
printf("N is not multiple of 64! Error!\n");
exit(-1);
}
if (narg >= 3) {
test_mode = atoi(argv[2]);
switch(test_mode) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
default:
printf("Error!!!!\n");
exit(-1);
}
}
if (narg == 4) flag = 1;
alpha = 1.0;
beta = 1.0;
ss = n*n;
mod = test_mode;
ACCLallocatememory(dev, mod, 0, ACCL_DOUBLE_2_2DIM_GPU, n/2, n);
ACCLallocatememory(dev, mod, 1, ACCL_DOUBLE_2_2DIM_GPU, n/2, n);
ACCLallocatememory(dev, mod, 2, ACCL_DOUBLE_2_2DIM_GPU | ACCL_GLOBAL_BUFFER, n/2, n);
ACCLallocateresource0(dev, 3, ACCL_FLOAT_4_1DIM_WRITE, 1, 1);
ACCLrebindmemory(dev, mod, 3, "cb0");
ACCLallocateresource0(dev, 4, ACCL_INT_4_1DIM_WRITE, 1, 1);
ACCLrebindmemory(dev, mod, 4, "cb1");
ACCLallocateresource0(dev, 5, ACCL_DOUBLE_2_1DIM_WRITE, 1, 1);
ACCLrebindmemory(dev, mod, 5, "cb2");
srand(time(NULL));
tmp_A = (double *)memalign(256, ss*sizeof(double));
tmp_B = (double *)memalign(256, ss*sizeof(double));
tmp_C = (double *)memalign(256, ss*sizeof(double));
tmp_D = (double *)memalign(256, ss*sizeof(double));
tmp_E = (double *)memalign(256, ss*sizeof(double));
ACCLallocateresource_pinned(dev, 6, ACCL_DOUBLE_2_2DIM_CPU, n/2, n, tmp_E, ss*sizeof(double));
for(int i = 0; i < ss; i++) {
tmp_A[i] = (double)rand()/(RAND_MAX);
tmp_B[i] = (double)rand()/(RAND_MAX);
tmp_C[i] = (double)rand()/(RAND_MAX);
}
if (flag == 1) {
memcpy(tmp_D, tmp_C, ss*sizeof(double));
switch(test_mode) {
case 0:
cblas_dgemm(CblasRowMajor, CblasTrans, CblasNoTrans, n, n, n, alpha, tmp_A, n, tmp_B, n, beta, tmp_D, n);
break;
case 1:
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, n, n, alpha, tmp_A, n, tmp_B, n, beta, tmp_D, n);
break;
case 2:
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, n, n, n, alpha, tmp_A, n, tmp_B, n, beta, tmp_D, n);
break;
case 3:
cblas_dgemm(CblasRowMajor, CblasTrans, CblasTrans, n, n, n, alpha, tmp_A, n, tmp_B, n, beta, tmp_D, n);
break;
}
}
float cb[4] = {(float)(n/2), (float)n, 0.0, 0.0};
ACCLwritememory_float(dev, 3, 4, cb);
int cb1[4] = {0, n/2, n, 3*n/2};
ACCLwritememory_int(dev, 4, 4, cb1);
double cb2[2] = {beta, alpha};
ACCLwritememory_double(dev, 5, 2, cb2);
my_dgemm(dev, mod, n);
if (flag == 1) {
check(tmp_D, tmp_C, n);
}
{
const int ccc = 5;
double dum = e_time();
for(int i = 0; i < ccc; i++) {
ACCLrun_on_domain(dev, mod, n/4, n/4);
}
dum = e_time() - dum;
double dum2 = e_time();
for(int i = 0; i < ccc; i++) my_dgemm(dev, mod, n);
dum2 = e_time() - dum2;
out(n, dum, dum2, ccc);
}
ACCLcleanup(dev);
return 0;
}
| {
"alphanum_fraction": 0.6373590982,
"avg_line_length": 27.8475336323,
"ext": "c",
"hexsha": "c7bef86108064ede6f5bfc54f1d137c80f0e4ea7",
"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": "dbe13de39a0bccc236a433222c883deae20a01dc",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "dadeba/dgemm_cypress",
"max_forks_repo_path": "main.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "dbe13de39a0bccc236a433222c883deae20a01dc",
"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": "dadeba/dgemm_cypress",
"max_issues_repo_path": "main.c",
"max_line_length": 113,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "dbe13de39a0bccc236a433222c883deae20a01dc",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "dadeba/dgemm_cypress",
"max_stars_repo_path": "main.c",
"max_stars_repo_stars_event_max_datetime": "2018-03-08T06:51:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-03T04:37:18.000Z",
"num_tokens": 2139,
"size": 6210
} |
#ifndef __RNG_H
#define __RNG_H
// #include <Rcpp.h>
#include <RcppGSL.h>
#include <gsl/gsl_rng.h>
// [[Rcpp::depends(RcppGSL)]]
using namespace Rcpp;
// Setup RNG for GSL
extern gsl_rng *r_RNG;
unsigned long int random_seed();
//' Generate one sample from a Dirichlet distribution.
//'
//' ## RNG
//'
//' this function uses GSL's RNG seed, unaffected by R's RNG.
//'
//' @param alpha the Dirichlet hyperparameter
//' @param seed the RNG seed: if 0 (default), generate a time-based seed
//' @return a numeric vector
//' @export
//' @family RNG functions
// [[Rcpp::export]]
Rcpp::NumericVector rdirichlet_cpp(const Rcpp::NumericVector &alpha, const unsigned long int seed = 0);
//' Generate from a Dirichlet distribution using the stick breaking definition (safer).
//'
//' ## RNG
//'
//' this function uses R's RNG seed.
//'
//' @param n how many samples to generate
//' @param alpha the Dirichlet hyperparameter, with p entries
//' @return a numeric matrix, n*p
//' @export
//' @family RNG functions
// [[Rcpp::export]]
Rcpp::NumericMatrix rdirichlet_beta_cpp(const unsigned int n, Rcpp::NumericVector alpha);
//' Generate a Dirichlet-Dirichlet-Gamma population (unsafe).
//'
//' Generate samples from m sources and p parameters, n sample per source.
//' The between-source alpha hyperparameter used to generate the source parameters is mandatory.
//'
//' ## RNG
//'
//' this function uses GSL's RNG seed, unaffected by R's RNG.
//'
//' @param n number of samples per source
//' @param m number of sources
//' @param alpha_0 between-source Gamma hyperparameter, a scalar
//' @param beta_0 between-source Gamma hyperparameter, a scalar
//' @param nu_0 between-source Dirichlet hyperparameter, a numeric vector
//' @export
//' @return a matrix with n*m rows
//' @inheritParams rdirichlet_cpp
//' @family RNG functions
// [[Rcpp::export]]
RcppGSL::Matrix rdirdirgamma_cpp(
const unsigned int &n, const unsigned int &m,
const double &alpha_0, const double &beta_0,
const Rcpp::NumericVector &nu_0,
const unsigned int seed = 0
);
//' Generate a Dirichlet-Dirichlet-Gamma population (safer).
//'
//' Generate samples from m sources and p parameters, n sample per source.
//' The between-source alpha hyperparameter used to generate the source parameters is mandatory.
//'
//' ## RNG
//'
//' this function uses R's RNG seed.
//'
//' @export
//' @return a matrix with n*m rows
//' @inheritParams rdirdirgamma_cpp
//' @family RNG functions
// [[Rcpp::export]]
Rcpp::NumericMatrix rdirdirgamma_beta_cpp(
const unsigned int &n, const unsigned int &m,
const double &alpha_0, const double &beta_0,
const Rcpp::NumericVector nu_0
);
#endif
| {
"alphanum_fraction": 0.7049180328,
"avg_line_length": 27.9583333333,
"ext": "h",
"hexsha": "9c97e77936f89728b39e01afcdf1cfc611ffe9e4",
"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": "f3087f0a81c9e4b08ff56efcc260873eaa16232d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lgaborini/rdirdirgamma",
"max_forks_repo_path": "src/rng.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f3087f0a81c9e4b08ff56efcc260873eaa16232d",
"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": "lgaborini/rdirdirgamma",
"max_issues_repo_path": "src/rng.h",
"max_line_length": 103,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f3087f0a81c9e4b08ff56efcc260873eaa16232d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "lgaborini/rdirdirgamma",
"max_stars_repo_path": "src/rng.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 703,
"size": 2684
} |
#include <math.h>
#include <lapacke.h>
#include <complex.h>
//#include "WignerD_fftw.h"
#include <stdio.h>
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
#define min(x,y) (((x) < (y)) ? (x) : (y))
#define MAXFILENAME 100
lapack_complex_double *Iy_Matrix(lapack_int Ndim)
{
double J = (Ndim-1)/2.;
lapack_complex_double *AB = calloc(Ndim*2,sizeof(lapack_complex_double));
lapack_complex_double zero = lapack_make_complex_double(0.0,0.0);
lapack_complex_double myimag = lapack_make_complex_double(0.0,1.0);
//prepare the upper triangle of Iy
//the array is computed in FORTRAN style (transposed)
double m;
for (int i=0; i<Ndim; i++){
m = i-J;
AB[2*i] = sqrt((J+m)*(J-m+1.)) / 2.*(-myimag);
AB[2*i+1] = zero;
//printf("Hal %f \n" , cimag(AB[i]));
}
return AB;
}
lapack_complex_double *Iy_Eigsystem_Lapacke(lapack_int Ndim)
{
char JOBZ, UPLO;
lapack_int KD, LDAB, LDZ, INFO;
JOBZ='V'; //= 'V': Compute eigenvalues and eigenvectors.
UPLO='U'; // = 'U': Upper triangle of A is stored;
KD=1; //number of superdiagonals
LDAB=KD+1; //The leading dimension of the array AB = 2
LDZ=max(1,Ndim); //The leading dimension of the array eigenvectors
//int rworksize=max(1,3*Ndim-2);
//Initialize the array that holds the eigenvalues
double *Eigenvalue;
lapack_complex_double *Eigenvec, *WORK; //AB is transposed because of FORTRAN array struct.
Eigenvec = calloc(Ndim*Ndim,sizeof(lapack_complex_double));
WORK = calloc(Ndim,sizeof(lapack_complex_double));
Eigenvalue = calloc(Ndim,sizeof(double));
lapack_complex_double *AB = Iy_Matrix(Ndim); //Create the upper triangle matrix
INFO = LAPACKE_zhbev(LAPACK_COL_MAJOR, JOBZ, UPLO, Ndim,
KD, AB,
LDAB, Eigenvalue, Eigenvec,
LDZ );
free(AB);
free(Eigenvalue);
free(WORK);
return Eigenvec;
}
void PrecalculateEigenvec(int Ndim)
{
lapack_complex_double *Eigenvec = Iy_Eigsystem_Lapacke(Ndim);
char filename[MAXFILENAME+1];
snprintf(filename, MAXFILENAME, "../../Calculated/Eigenvectors/EigenvectorsD%d.dat", Ndim);
FILE* file = fopen(filename, "wb");
if (file == NULL){
printf("CANNOT OPEN FILE FOR WRITING: %s\n",filename);
abort();
}
//else printf("WRITING TO FILE: %s\n",filename);
const int size = sizeof(lapack_complex_double);
const int fftdim = 2*(Ndim-1)+1;
for (int m=0; m<Ndim; m++){
for (int mu=0; mu<Ndim; mu++){
if (fwrite(&Eigenvec[m + Ndim*mu], 1, size, file) != size){
printf("ERROR WHILE WRITING TO FILE: %s\n",filename);
abort();
}
}}
free(Eigenvec);
fclose(file);
}
int main(){
int MAXDIM = 120;
for (int Ndim=2; Ndim<=MAXDIM; Ndim++){
PrecalculateEigenvec(Ndim);
printf("Eigenvectors calculated for dimension %d\n", Ndim);
}
return 0;
} | {
"alphanum_fraction": 0.6097879282,
"avg_line_length": 25.1229508197,
"ext": "c",
"hexsha": "7ad86fb032e40b8fbb8009ffce95ee2bb3c55edc",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-03-19T23:09:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-18T00:50:01.000Z",
"max_forks_repo_head_hexsha": "a63fcd3769ce429a9a9180ca64a91b9ceee1b509",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "BalintKoczor/fast-spherical-phase-space",
"max_forks_repo_path": "src/Precalculate_Eigenvectors/Precalculate_Eigenvectors.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "a63fcd3769ce429a9a9180ca64a91b9ceee1b509",
"max_issues_repo_issues_event_max_datetime": "2021-01-26T06:10:40.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-26T06:10:40.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "BalintKoczor/fast-spherical-phase-space",
"max_issues_repo_path": "src/Precalculate_Eigenvectors/Precalculate_Eigenvectors.c",
"max_line_length": 93,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "a63fcd3769ce429a9a9180ca64a91b9ceee1b509",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "BalintKoczor/fast-spherical-phase-space",
"max_stars_repo_path": "src/Precalculate_Eigenvectors/Precalculate_Eigenvectors.c",
"max_stars_repo_stars_event_max_datetime": "2021-02-03T11:07:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-08-18T00:49:59.000Z",
"num_tokens": 938,
"size": 3065
} |
/*****************************************************************\
__
/ /
/ / __ __
/ /______ _______ / / / / ________ __ __
/ ______ \ /_____ \ / / / / / _____ | / / / /
/ / | / _______| / / / / / / /____/ / / / / /
/ / / / / _____ / / / / / / _______/ / / / /
/ / / / / /____/ / / / / / / |______ / |______/ /
/_/ /_/ |________/ / / / / \_______/ \_______ /
/_/ /_/ / /
/ /
/_/
---------------------------------------------------------------
Copyright (c) 2007-2011 - Rodrigo Braz Monteiro.
This file is subject to the terms of halley_license.txt.
\*****************************************************************/
#pragma once
#include <gsl/gsl>
#include "halley/maths/vector2.h"
#include "halley/text/halleystring.h"
#include "halley/resources/resource.h"
#include "halley/file/path.h"
#include "halley/maths/rect.h"
#include "halley/maths/colour.h"
namespace Halley {
class ResourceDataStatic;
class ResourceLoader;
class Image final : public Resource {
public:
enum class Format {
Undefined,
Indexed,
RGB,
RGBA,
RGBAPremultiplied,
SingleChannel
};
Image(Format format = Format::RGBA, Vector2i size = {});
Image(gsl::span<const gsl::byte> bytes, Format format = Format::Undefined);
explicit Image(const ResourceDataStatic& data);
Image(const ResourceDataStatic& data, const Metadata& meta);
Image(Image&& other);
~Image();
std::unique_ptr<Image> clone();
void setSize(Vector2i size);
void load(gsl::span<const gsl::byte> bytes, Format format = Format::Undefined);
Bytes savePNGToBytes(bool allowDepthReduce = true) const;
Bytes saveQOIToBytes() const;
static Vector2i getImageSize(gsl::span<const gsl::byte> bytes);
static Format getImageFormat(gsl::span<const gsl::byte> bytes);
static bool isQOI(gsl::span<const gsl::byte> bytes);
static bool isPNG(gsl::span<const gsl::byte> bytes);
gsl::span<unsigned char> getPixelBytes();
gsl::span<const unsigned char> getPixelBytes() const;
gsl::span<const unsigned char> getPixelBytesRow(int x0, int x1, int y) const;
int getPixel4BPP(Vector2i pos) const;
int getPixelAlpha(Vector2i pos) const;
gsl::span<int> getPixels4BPP();
gsl::span<const int> getPixels4BPP() const;
gsl::span<const int> getPixelRow4BPP(int x0, int x1, int y) const;
size_t getByteSize() const;
static unsigned int convertRGBAToInt(unsigned int r, unsigned int g, unsigned int b, unsigned int a=255);
static void convertIntToRGBA(unsigned int col, unsigned int& r, unsigned int& g, unsigned int& b, unsigned int& a);
static Colour4c convertIntToColour(unsigned int col);
unsigned int getWidth() const { return w; }
unsigned int getHeight() const { return h; }
Vector2i getSize() const { return Vector2i(int(w), int(h)); }
int getBytesPerPixel() const;
Format getFormat() const;
Rect4i getTrimRect() const;
Rect4i getRect() const;
void clear(int colour);
void blitFrom(Vector2i pos, gsl::span<const unsigned char> buffer, size_t width, size_t height, size_t pitch, size_t srcBpp);
void blitFromRotated(Vector2i pos, gsl::span<const unsigned char> buffer, size_t width, size_t height, size_t pitch, size_t bpp);
void blitFrom(Vector2i pos, const Image& srcImg, bool rotated = false);
void blitFrom(Vector2i pos, const Image& srcImg, Rect4i srcArea, bool rotated = false);
void blitDownsampled(Image& src, int scale);
void drawImageAlpha(const Image& src, Vector2i pos, uint8_t opacity = 255);
void drawImageAdd(const Image& src, Vector2i pos, uint8_t opacity = 255);
void drawImageLighten(const Image& src, Vector2i pos, uint8_t opacity = 255);
static std::unique_ptr<Image> loadResource(ResourceLoader& loader);
constexpr static AssetType getAssetType() { return AssetType::Image; }
void reload(Resource&& resource) override;
Image& operator=(const Image& o) = delete;
Image& operator=(Image&& o) = default;
void serialize(Serializer& s) const;
void deserialize(Deserializer& s);
void preMultiply();
ResourceMemoryUsage getMemoryUsage() const override;
private:
std::unique_ptr<unsigned char, void(*)(unsigned char*)> px;
size_t dataLen = 0;
unsigned int w = 0;
unsigned int h = 0;
Format format = Format::Undefined;
};
template <>
struct EnumNames<Image::Format> {
constexpr std::array<const char*, 6> operator()() const {
return{{
"undefined",
"indexed",
"rgb",
"rgba",
"rgba_premultiplied",
"single_channel"
}};
}
};
}
| {
"alphanum_fraction": 0.6267515924,
"avg_line_length": 33.8848920863,
"ext": "h",
"hexsha": "969ba4c00327b968f8a70f4d6d11543385053890",
"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/utils/include/halley/file_formats/image.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/utils/include/halley/file_formats/image.h",
"max_line_length": 131,
"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/utils/include/halley/file_formats/image.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1274,
"size": 4710
} |
#ifndef SmtkMatcher_h
#define SmtkMatcher_h
/**
* @file
* $Revision: 1.1 $
* $Date: 2009/09/09 23:42:41 $
*
* Unless noted otherwise, the portions of Isis written by the USGS are
* public domain. See individual third-party library and package descriptions
* for intellectual property information, user agreements, and related
* information.
*
* Although Isis has been used by the USGS, no warranty, expressed or
* implied, is made by the USGS as to the accuracy and functioning of such
* software and related material nor shall the fact of distribution
* constitute any such warranty, and no responsibility is assumed by the
* USGS in connection therewith.
*
* For additional information, launch
* $ISISROOT/doc//documents/Disclaimers/Disclaimers.html
* in a browser or see the Privacy & Disclaimers page on the Isis website,
* http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on
* http://www.usgs.gov/privacy.html.
*/
#include <memory>
#include <QSharedPointer>
#include "SmtkStack.h"
#include "Gruen.h"
#include "SmtkPoint.h"
#include "GSLUtility.h"
#include <gsl/gsl_rng.h>
namespace Isis {
/**
* @brief Workhorse of stereo matcher
*
* This class provides stereo matching functionality to the SMTK toolkit. It
* registers points, clones them by adjusting parameters to nearby point
* locations and manages point selection processes.
*
* The Gruen algorithm is initialized here and maintained for use in the
* stereo matching process.
*
* @author 2011-05-28 Kris Becker
*
* @internal
* @history 2012-12-20 Debbie A. Cook - Removed unused Projection.h
* References #775.
* @history 2017-08-18 Summer Stapleton, Ian Humphrey, Tyler Wilson -
* Changed auto_ptr reference to QSharedPointer
* so this class compiles under C++14.
* References #4809.
*/
class SmtkMatcher {
public:
SmtkMatcher();
SmtkMatcher(const QString ®def);
SmtkMatcher(const QString ®def, Cube *lhImage, Cube *rhImage);
SmtkMatcher(Cube *lhImage, Cube *rhImage);
~SmtkMatcher();
void setImages(Cube *lhImage, Cube *rhImage);
void setGruenDef(const QString ®def);
bool isValid(const Coordinate &pnt);
bool isValid(const SmtkPoint &spnt);
/** Return pattern chip */
Chip *PatternChip() const {
validate();
return (m_gruen->PatternChip());
}
/** Return search chip */
Chip *SearchChip() const {
validate();
return (m_gruen->SearchChip());
}
/** Returns the fit chip */
Chip *FitChip() const {
validate();
return (m_gruen->FitChip());
}
void setWriteSubsearchChipPattern(const QString &fileptrn = "SmtkMatcher");
SmtkQStackIter FindSmallestEV(SmtkQStack &stack);
SmtkQStackIter FindExpDistEV(SmtkQStack &stack, const double &seedsample,
const double &minEV, const double &maxEV);
SmtkPoint Register(const Coordinate &lpnt,
const AffineRadio &affrad = AffineRadio());
SmtkPoint Register(const PointPair &pnts,
const AffineRadio &affrad = AffineRadio());
SmtkPoint Register(const SmtkPoint &spnt,
const AffineRadio &affrad = AffineRadio());
SmtkPoint Register(const PointGeometry &lpg, const PointGeometry &rpg,
const AffineRadio &affrad = AffineRadio());
SmtkPoint Create(const Coordinate &left, const Coordinate &right);
SmtkPoint Clone(const SmtkPoint &point, const Coordinate &left);
inline BigInt OffImageErrorCount() const { return (m_offImage); }
inline BigInt SpiceErrorCount() const { return (m_spiceErr); }
/** Return Gruen template parameters */
PvlGroup RegTemplate() { return (m_gruen->RegTemplate()); }
/** Return Gruen registration statistics */
Pvl RegistrationStatistics() { return (m_gruen->RegistrationStatistics()); }
private:
SmtkMatcher &operator=(const SmtkMatcher &matcher); // Assignment disabled
SmtkMatcher(const SmtkMatcher &matcher); // Copy const disabled
Cube *m_lhCube; // Left image cube (not owned)
Cube *m_rhCube; // Right image cube (not owned)
QSharedPointer<Gruen> m_gruen; // Gruen matcher
BigInt m_offImage; // Offimage counter
BigInt m_spiceErr; // SPICE distance error
bool m_useAutoReg; // Select AutoReg features
const gsl_rng_type * T; // GSL random number type
gsl_rng * r; // GSL random number generator
void randomNumberSetup();
bool validate(const bool &throwError = true) const;
inline Camera &lhCamera() { return (*m_lhCube->camera()); }
inline Camera &rhCamera() { return (*m_rhCube->camera()); }
Coordinate getLineSample(Camera &camera, const Coordinate &geom);
Coordinate getLatLon(Camera &camera, const Coordinate &pnt);
bool inCube(const Camera &camera, const Coordinate &point) const;
SmtkPoint makeRegisteredPoint(const PointGeometry &left,
const PointGeometry &right, Gruen *gruen);
};
} // namespace Isis
#endif
| {
"alphanum_fraction": 0.6565201052,
"avg_line_length": 35.7181208054,
"ext": "h",
"hexsha": "2ced22b4869ac2f165d895935f2b775b93a96cbf",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-07-12T06:05:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-12T06:05:03.000Z",
"max_forks_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108",
"max_forks_repo_licenses": [
"Unlicense"
],
"max_forks_repo_name": "ihumphrey-usgs/ISIS3_old",
"max_forks_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Unlicense"
],
"max_issues_repo_name": "ihumphrey-usgs/ISIS3_old",
"max_issues_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108",
"max_stars_repo_licenses": [
"Unlicense"
],
"max_stars_repo_name": "ihumphrey-usgs/ISIS3_old",
"max_stars_repo_path": "isis/src/base/objs/SmtkMatcher/SmtkMatcher.h",
"max_stars_repo_stars_event_max_datetime": "2019-10-13T15:31:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-10-13T15:31:33.000Z",
"num_tokens": 1305,
"size": 5322
} |
/*
Copyright (c) 2003-2008 Rudi Cilibrasi, Rulers of the RHouse
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the University nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE RULERS 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 RULERS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
#include <glib.h>
#include <libintl.h>
#include <locale.h>
#include "complearn/newcomplearn.h"
#include "complearn/clconfig.h"
#define _(O) gettext(O)
#define clStringstackPush(a,v) {void*_u=(void*)v;g_array_append(a,_u);}while(0)
GString *complearn_matrix_prettyprint_text(LabeledMatrix *result) {
int i, j;
int html = complearn_ncd_get_html_output(complearn_ncd_top());
char *rowstart = "", *rowend = "\n", *numstart = "", *numend = "", *labstart = "", *labend = " ", *lastcellstart="", *lastcellend ="";
GString *toWrite = g_string_new("");
CompLearnNcd *top = complearn_ncd_top();
gsl_matrix *goodmat =gsl_matrix_alloc(result->mat->size1, result->mat->size2);
gsl_matrix_memcpy(goodmat, result->mat);
if (html) {
g_string_append(toWrite, "<table cellpadding='0' cellspacing='0'>\n");
rowstart = "<tr>\n"; rowend = "</tr>\n";
lastcellstart = "<td style='font-family: sans-serif; padding: 7px; border: 0px gray solid; border-bottom-width: 1px; border-right-style: dashed; border-right-width:1px; border-left-style: dashed; border-left-width:1px;'>"; lastcellend = "</td>";
numstart = "<td style='font-family: sans-serif; padding: 7px; border: 0px gray solid; border-bottom-width: 1px; border-left-style: dashed; border-left-width:1px;'>"; numend = "</td>";
labstart = "<td style='color: green; font-weight: bold; padding: 7px; border: 0px gray solid; border-bottom-width: 1px;'>"; labend = "</td>";
}
for (j = 0; j < goodmat->size2; j += 1) {
g_string_append(toWrite, rowstart);
if (complearn_ncd_get_show_labels(top)) {
g_string_append(toWrite, labstart);
if (result->labels2[j] == NULL)
g_error("bad labels2 %d with mat size2 %d", j, goodmat->size2);
g_string_append(toWrite, result->labels2[j]);
g_string_append(toWrite, labend);
}
for (i = 0; i < goodmat->size1; i += 1) {
char buf[256];
sprintf(buf, "%f ", gsl_matrix_get(goodmat, i, j));
g_string_append(toWrite, i == goodmat->size1-1 ? lastcellstart : numstart);
g_string_append(toWrite, buf);
g_string_append(toWrite, i == goodmat->size1-1 ? lastcellend : numend);
}
g_string_append(toWrite, rowend);
}
if (html)
g_string_append(toWrite, "</table>\n");
gsl_matrix_free(goodmat);
return toWrite;
}
#include <complearn/complearn.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlwriter.h>
#include <libxml/encoding.h>
#define MY_ENCODING "ISO-8859-1"
#include <gsl/gsl_linalg.h>
#define PWD_RDY 1
#define UTS_RDY 1
#ifndef __MINGW32__
#if PWD_RDY
#include <pwd.h>
#endif
#if UTS_RDY
#include <sys/utsname.h>
#endif
#endif
GArray *clDefaultLabels(int i);
static void complearn_handle_string_list(xmlDocPtr doc, xmlNodePtr node, GArray *ss,
const char *tagname) {
node = node->xmlChildrenNode;
while (node != NULL) {
if (strcmp(tagname, (char *) node->name) == 0) {
guchar *v = xmlNodeListGetString(doc, node->xmlChildrenNode,1);
g_array_append_val(ss, v);
}
node = node->next;
}
}
static void handleDM(xmlDocPtr doc, xmlNodePtr node, GArray *ss,
struct CLDistMatrix *result) {
result->title = (char *) xmlGetProp(node, (unsigned char *) "title");
result->creationTime = (char *) xmlGetProp(node, (unsigned char *) "creationtime");
node = node->xmlChildrenNode;
GArray *numa, *lab1a, *lab2a;
numa = result->numa;
lab1a = result->labels1a;
lab2a = result->labels2a;
while (node != NULL) {
do {
if (strcmp("entries", (char *) node->name) == 0) {
complearn_handle_string_list(doc, node, numa, "number");
continue;
}
if (strcmp((char *) node->name, "axis1") == 0) {
complearn_handle_string_list(doc, node, lab1a, "name");
continue;
}
if (strcmp((char *) node->name, "axis2") == 0) {
complearn_handle_string_list(doc, node, lab2a, "name");
continue;
}
} while(0);
node = node->next;
}
}
static void complearn_write_string_list(xmlTextWriterPtr tw, char **ss, const char *topname, const char *itemname) {
int rc;
int i;
rc = xmlTextWriterStartElement(tw, (unsigned char *) topname);
for (i = 0; i < complearn_count_strings((const char * const * )ss); i += 1)
rc = xmlTextWriterWriteElement(tw, (unsigned char *) itemname, (unsigned char *) ss[i]);
rc = xmlTextWriterEndElement(tw);
}
static char *getTimestrNow(void)
{
static char buf[32];
sprintf(buf, "%lu", (unsigned long) time(NULL));
return buf;
}
static struct CLDistMatrix *fill_in_blanks(struct CLDistMatrix *clb)
{
if (clb->m == NULL) {
g_error(_("Cannot write NULL gsl_matrix, exitting."));
}
if (clb->m->mat->size1 < 1 || clb->m->mat->size2 < 1) {
g_error(_("Invalid gsl_matrix size, cannot write. Exitting."));
}
if (clb->fileverstr == NULL)
clb->fileverstr = g_strdup("1.0");
if (clb->cllibver == NULL)
clb->cllibver = g_strdup(complearn_package_version);
if (clb->username == NULL)
clb->username = g_strdup(g_get_user_name());
if (clb->hostname == NULL)
clb->hostname = g_strdup(complearn_get_hostname());
if (clb->title == NULL)
clb->title = g_strdup(_("untitled"));
if (clb->compressor == NULL)
clb->compressor = g_strdup(_("unknown"));
if (clb->creationTime == NULL)
clb->creationTime = g_strdup(getTimestrNow());
return clb;
}
struct CLDistMatrix *complearn_clone_cldm(struct CLDistMatrix *clb)
{
struct CLDistMatrix *r = calloc(sizeof(*r), 1);
if (clb->m == NULL) {
g_error(_("Cannot write NULL gsl_matrix, exitting."));
}
#define DUPSTR(s) if (clb->s) r->s = g_strdup(clb->s)
DUPSTR(cllibver);
DUPSTR(username);
DUPSTR(hostname);
DUPSTR(title);
DUPSTR(compressor);
DUPSTR(creationTime);
r->m = calloc(sizeof(*(r->m)), 1);
r->m->mat = gsl_matrix_alloc(clb->m->mat->size1, clb->m->mat->size2);
gsl_matrix_memcpy(r->m->mat, clb->m->mat);
r->m->labels1 = complearn_dupe_strings((const char * const *)clb->m->labels1);
r->m->labels2 = complearn_dupe_strings((const char * const *)clb->m->labels2);
r->cmds = complearn_dupe_strings((const char * const *)clb->cmds);
r->cmdtimes = complearn_dupe_strings((const char * const *)clb->cmdtimes);
return r;
}
void complearn_free_cldm(struct CLDistMatrix *clb)
{
if (clb->cllibver) g_free(clb->cllibver);
if (clb->username) g_free(clb->username);
if (clb->hostname) g_free(clb->hostname);
if (clb->title) g_free(clb->title);
if (clb->compressor) g_free(clb->compressor);
if (clb->creationTime) g_free(clb->creationTime);
if (clb->m->mat) gsl_matrix_free(clb->m->mat);
g_strfreev(clb->m->labels1);
g_strfreev(clb->m->labels2);
g_strfreev(clb->cmdtimes);
g_strfreev(clb->cmds);
g_free(clb->m);
memset(clb, 0, sizeof(*clb));
g_free(clb);
}
static char *clXMLQuoteStr(char *inp)
{
int i, c, j;
static char *outstr;
if (outstr != NULL)
g_free(outstr);
outstr = calloc(strlen(inp) * 10, 1);
j = 0;
for (i = 0; inp[i]; i += 1) {
c = inp[i];
switch(c) {
case '&':
outstr[j++] = '&'; outstr[j++] = 'a'; outstr[j++] = 'm';
outstr[j++] = 'p'; outstr[j++] = ';'; break;
case '>':
outstr[j++] = '&'; outstr[j++] = 'g'; outstr[j++] = 't';
outstr[j++] = ';'; break;
case '<':
outstr[j++] = '&'; outstr[j++] = 'l'; outstr[j++] = 't';
outstr[j++] = ';'; break;
case '"':
outstr[j++] = '&'; outstr[j++] = 'q'; outstr[j++] = 'o';
outstr[j++] = 'o'; outstr[j++] = 't'; outstr[j++] = ';'; break;
case '\'':
outstr[j++] = '&'; outstr[j++] = 'a'; outstr[j++] = 'p';
outstr[j++] = 'o'; outstr[j++] = 's'; outstr[j++] = ';'; break;
// case '\\':
// case '#':
// outstr[j++] = '\\'; outstr[j++] = c; break;
default:
outstr[j++] = c;
}
}
outstr[j++] = 0;
return outstr;
}
static GString *clRealWriteCLBDistMatrix(struct CLDistMatrix *clb)
{
int rc;
GString *result, *cres;
int dim1, dim2, i, j;
gsl_matrix *m = clb->m->mat;
xmlBufferPtr b;
xmlTextWriterPtr tw;
clb = fill_in_blanks(complearn_clone_cldm(clb));
b = xmlBufferCreate();
tw =xmlNewTextWriterMemory(b, 0);
rc = xmlTextWriterStartDocument(tw, NULL, MY_ENCODING, NULL);
rc = xmlTextWriterStartElement(tw, (unsigned char *) "clb");
rc = xmlTextWriterWriteAttribute(tw, (unsigned char *) "version", (unsigned char *) clb->fileverstr);
rc = xmlTextWriterWriteElement(tw, (unsigned char *) "cllibver", (unsigned char *) clb->cllibver);
rc = xmlTextWriterWriteElement(tw, (unsigned char *) "username", (unsigned char *) clb->username);
rc = xmlTextWriterWriteElement(tw, (unsigned char *) "hostname", (unsigned char *) clb->hostname);
rc = xmlTextWriterWriteElement(tw, (unsigned char *) "compressor", (unsigned char *) clb->compressor);
rc = xmlTextWriterStartElement(tw,(unsigned char *) "distmatrix");
rc = xmlTextWriterWriteAttribute(tw,(unsigned char *) "creationtime", (unsigned char *) clb->creationTime);
rc = xmlTextWriterWriteAttribute(tw, (unsigned char *) "title",(unsigned char *) clb->title);
complearn_write_string_list(tw, clb->m->labels1, "axis1", "name");
complearn_write_string_list(tw, clb->m->labels2, "axis2", "name");
dim1 = complearn_count_strings((const char * const *) clb->m->labels1);
dim2 = complearn_count_strings((const char * const *) clb->m->labels2);
rc = xmlTextWriterStartElement(tw,(unsigned char *) "entries");
for (i = 0; i < dim1; i += 1) {
for (j = 0; j < dim2; j += 1) {
double g = gsl_matrix_get(m, i, j);
xmlTextWriterWriteFormatElement(tw, (unsigned char *) "number", (char *) "%f", g);
}
}
rc = xmlTextWriterEndElement(tw);
rc = xmlTextWriterEndElement(tw);
if (clb->cmds) {
char *str;
rc = xmlTextWriterStartElement(tw,(unsigned char *) "commands");
for (i = 0; i < complearn_count_strings((const char * const *) clb->cmds); i += 1) {
char *t = clb->cmdtimes ? (clb->cmdtimes[i]) : NULL;
rc = xmlTextWriterStartElement(tw,(unsigned char *) "cmdstring");
if (t)
rc = xmlTextWriterWriteAttribute(tw,(unsigned char *) "creationtime", (unsigned char *) t);
str = clb->cmds[i];
xmlTextWriterWriteRaw(tw, (unsigned char *) clXMLQuoteStr(str));
rc = xmlTextWriterEndElement(tw);
}
rc = xmlTextWriterEndElement(tw);
}
rc = xmlTextWriterEndElement(tw);
rc = xmlTextWriterEndDocument(tw);
xmlFreeTextWriter(tw);
result = g_string_new((char *) b->content);
xmlBufferFree(b);
/* TODO: remove more mem leaks from above func */
complearn_free_cldm(clb);
CompLearnRealCompressor *bz = COMPLEARN_REAL_COMPRESSOR(complearn_environment_get_nameable("bzlib"));
if (bz == NULL)
g_error(_("Cannot load bzlib"));
cres = real_compressor_compress(bz, result);
g_string_free(result, TRUE);
return cres;
}
gsl_matrix *complearn_clb_dist_matrix(const GString *db)
{
return complearn_read_clb_dist_matrix(db)->m->mat;
}
struct CLDistMatrix *complearn_read_clb_dist_matrix(const GString *udb)
{
struct CLDistMatrix *result = calloc(sizeof(struct CLDistMatrix), 1);
GArray *ents = g_array_new(FALSE, TRUE, sizeof(gpointer));
GString *db;
int dim1, dim2;
xmlDocPtr doc;
xmlNodePtr node;
CompLearnRealCompressor *bz = COMPLEARN_REAL_COMPRESSOR(complearn_environment_get_nameable("bzlib"));
if (bz == NULL)
g_error(_("Cannot load bzlib compressor."));
if (real_compressor_is_decompressible(bz, udb))
db = real_compressor_decompress(bz, udb);
else
db = g_string_new_len(udb->str, udb->len);
if (db == NULL || db->len < 1)
return NULL;
if (db->str[0] != '<')
return NULL;
result->fileverstr = "";
result->username = "";
result->title = "";
result->creationTime = "";
result->cmdsa = g_array_new(FALSE, TRUE, sizeof(gpointer));
result->cmdtimesa = g_array_new(FALSE, TRUE, sizeof(gpointer));
result->labels1a = g_array_new(FALSE, TRUE, sizeof(gpointer));
result->labels2a = g_array_new(FALSE, TRUE, sizeof(gpointer));
result->numa = g_array_new(FALSE, TRUE, sizeof(gpointer));
result->m = calloc(sizeof(*result->m), 1);
doc = xmlReadMemory((char *)db->str, db->len, "noname.xml",
NULL, 0);
if (doc == NULL) {
g_error(_("Failed to parse document."));
g_string_free(db, TRUE);
free(result);
return NULL;
}
node = doc->children;
if (strcmp((char *) node->name, "clb") != 0) {
free(result);
g_string_free(db, TRUE);
return NULL;
}
result->fileverstr = (char *) xmlGetProp(node, (unsigned char *) "version");
node = node->xmlChildrenNode;
while (node != NULL) {
do {
if (strcmp((char *) node->name, "commands") == 0) {
complearn_handle_string_list(doc, node, result->cmdsa, "cmdstring");
continue;
}
if (strcmp((char *) node->name, "distmatrix") == 0) {
handleDM(doc, node, ents, result);
result->m->mat = gsl_matrix_alloc(result->labels1a->len, result->labels2a->len);
int i, x=0, y=0;
for (i = 0; i < result->numa->len; i += 1) {
gsl_matrix_set(result->m->mat,x,y,atof(g_array_index(result->numa, char *, i)));
g_assert(y < result->m->mat->size2);
x += 1;
if (x == result->m->mat->size1) {
x = 0; y += 1;
}
}
continue;
}
if (strcmp((char *) node->name, "cllibver") == 0) {
result->cllibver = (char *) g_strdup((char *) xmlNodeListGetString(doc, node->xmlChildrenNode, 1));
continue;
}
if (strcmp((char *) node->name, "compressor") == 0) {
result->compressor = (char *) g_strdup((char *) xmlNodeListGetString(doc, node->xmlChildrenNode, 1));
continue;
}
if (strcmp((char *) node->name, "username") == 0) {
result->username = (char *) g_strdup((char *) xmlNodeListGetString(doc, node->xmlChildrenNode, 1));
continue;
}
} while (0);
node = node->next;
}
dim1 = result->labels1a->len;
if (dim1 <= 0) {
g_error(_("Error, no labels for dimension 1."));
exit(1);
}
dim2 = result->labels2a->len;
if (dim2 <= 0) {
g_error(_("Error, no labels for dimension 2."));
exit(1);
}
g_array_free(ents, TRUE);
g_string_free(db, TRUE);
result->m->labels1 = calloc(result->labels1a->len+1, sizeof(gpointer));
result->m->labels2 = calloc(result->labels2a->len+1, sizeof(gpointer));
memcpy(result->m->labels1, result->labels1a->data, sizeof(gpointer)*(result->labels1a->len));
memcpy(result->m->labels2, result->labels2a->data, sizeof(gpointer)*(result->labels2a->len));
return result;
}
const char *complearn_complearn_get_hostname(void)
{
static char hostname[1024];
#ifdef __MINGW32__
strcpy(hostname, "localhost");
#else
gethostname(hostname, 1024);
#endif
return hostname;
}
const char *complearn_get_uts_name(void)
{
static char utsname[1024];
#if UTS_RDY
#ifdef __MINGW32__
strcpy(utsname, "mingw32");
#else
struct utsname uts;
uname(&uts);
sprintf(utsname, "[%s (%s), %s]", uts.sysname, uts.release, uts.machine);
#endif
#else
strcpy(utsname, "[unknown]");
#endif
return utsname;
}
GString *complearn_matrix_prettyprint_clb(LabeledMatrix *dm) {
struct CLDistMatrix inp;
memset(&inp, 0, sizeof(inp));
inp.m = dm;
char *old_locale = setlocale(LC_NUMERIC, NULL);
setlocale(LC_NUMERIC, "C");
GString *result = clRealWriteCLBDistMatrix(&inp);
setlocale(LC_NUMERIC, old_locale);
return result;
}
LabeledMatrix *complearn_load_any_matrix(const GString *inp)
{
complearn_environment_top();
if (complearn_is_nexus_file(inp))
return complearn_load_nexus_matrix(inp);
struct CLDistMatrix *cld;
cld = complearn_read_clb_dist_matrix(inp);
if (cld) {
return cld->m;
}
if (complearn_is_text_matrix(inp)) {
return complearn_load_text_matrix(inp);
}
return NULL;
}
| {
"alphanum_fraction": 0.6504893036,
"avg_line_length": 35.5789473684,
"ext": "c",
"hexsha": "9bb8ea6eec65b4a576173a9b59646fb1e752eef7",
"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": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "rudi-cilibrasi/classic-complearn",
"max_forks_repo_path": "src/cloutput.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66",
"max_issues_repo_issues_event_max_datetime": "2017-03-15T18:30:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-05-10T12:56:52.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "rudi-cilibrasi/classic-complearn",
"max_issues_repo_path": "src/cloutput.c",
"max_line_length": 251,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "c70ac5ad7bcfe3af80a2a8f087ee6f5904820a66",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "rudi-cilibrasi/classic-complearn",
"max_stars_repo_path": "src/cloutput.c",
"max_stars_repo_stars_event_max_datetime": "2018-06-08T11:13:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-03-14T13:52:31.000Z",
"num_tokens": 5210,
"size": 17576
} |
#ifndef SPC_UTILS_H
#define SPC_UTILS_H
void init_search (const char *string); /* Pbmsrch.C */
char *strsearch (const char *string); /* Pbmsrch.C */
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <gsl/gsl_version.h>
#include <gsl/gsl_nan.h>
#include <gsl/gsl_sys.h>
#include <gsl/gsl_vector.h>
#include "aXe_errors.h"
#include "aXe_grism.h"
#define LAMBDACENTRAL 8000.0
#define COLNAMELENGTH 12
#define MAXCOLS 200
/**
* Structure: sexcol
* Structure for a column header
*/
typedef struct sexcol
{
char name[COLNAMELENGTH];
int number;
}
sexcol;
/**
* Structure: colinfo
* Structure for the table header
*/
typedef struct colinfo
{
int numcols;
sexcol columns[MAXCOLS];
}
colinfo;
extern int
is_valid_entry(double mag);
extern int
get_valid_entries(const gsl_vector *magnitudes);
extern int
check_worldcoo_input(const colinfo * actcatinfo, const int thsky);
extern int
check_imagecoo_input(const colinfo * actcatinfo);
extern void
make_GOL_header(FILE *fout, const colinfo * actcatinfo,
const gsl_vector * waves, const gsl_vector * cnums,
const px_point backwin_cols, const px_point modinfo_cols);
extern colinfo *
get_sex_col_descr (char *filename);
extern double
get_col_value (const colinfo * actcatinfo, const char key[],
gsl_vector * v, int fatal);
extern double
get_col_value2 (const colinfo * actcatinfo, const char key[],
gsl_vector * v, int fatal);
extern int
line_is_valid (const colinfo * actcatinfo, char line[]);
extern int
get_magauto_col(const gsl_vector *wavelength, const gsl_vector *colnums,
const double lambda_mark);
extern int
has_magnitudes(const colinfo * actcatinfo);
extern px_point
has_backwindow(const colinfo * actcatinfo);
extern px_point
has_modelinfo(const colinfo * actcatinfo);
extern int
get_magcols(const colinfo * actcatinfo, gsl_vector *wavelength,
gsl_vector *colnums);
extern int
resolve_colname(const char colname[]);
extern void
get_columname(const colinfo * actcatinfo, const int colnum, char colname[]);
extern int
get_columnumber(const char cname[], const colinfo * actcatinfo);
extern char *
rmlead (char *str);
extern char *
stptok (const char *s, char *tok, size_t toklen, char *brk);
#define strMove(d,s) memmove(d,s,strlen(s)+1)
extern void
lv1ws (char *str);
extern int
isnum2(char *string);
extern gsl_vector *
string_to_gsl_array (char *str);
extern void
check_libraries (void);
extern observation *
load_dummy_observation (void);
#endif
| {
"alphanum_fraction": 0.7252167358,
"avg_line_length": 20.2519083969,
"ext": "h",
"hexsha": "8068bc2b1ca2e1e6d23100ca0dcf80740460c92d",
"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_utils.h",
"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_utils.h",
"max_line_length": 76,
"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_utils.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 698,
"size": 2653
} |
#pragma once
#include "NativeDataStream.h"
#include "PerFrameValue.h"
#include "ShaderCompiler.h"
#include "VertexArray.h"
#include <Babylon/JsRuntime.h>
#include <Babylon/JsRuntimeScheduler.h>
#include <GraphicsImpl.h>
#include <BgfxCallback.h>
#include <FrameBuffer.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 <arcana/threading/cancellation.h>
#include <unordered_map>
namespace Babylon
{
struct UniformInfo final
{
UniformInfo(uint8_t stage, bgfx::UniformHandle handle) :
Stage{stage},
Handle{handle}
{
}
uint8_t Stage{};
bgfx::UniformHandle Handle{bgfx::kInvalidHandle};
};
struct ProgramData final
{
ProgramData() = default;
ProgramData(ProgramData&& other) = delete;
ProgramData(const ProgramData&) = delete;
ProgramData& operator=(ProgramData&& other) = delete;
ProgramData& operator=(const ProgramData& other) = delete;
~ProgramData()
{
Dispose();
}
void Dispose()
{
if (!Disposed && bgfx::isValid(Handle))
{
bgfx::destroy(Handle);
}
Disposed = true;
}
std::unordered_map<std::string, uint32_t> VertexAttributeLocations{};
std::unordered_map<std::string, UniformInfo> UniformInfos{};
bgfx::ProgramHandle Handle{bgfx::kInvalidHandle};
bool Disposed{false};
struct UniformValue
{
std::vector<float> Data{};
uint16_t ElementLength{};
};
std::unordered_map<uint16_t, UniformValue> Uniforms{};
void SetUniform(bgfx::UniformHandle handle, gsl::span<const float> data, size_t elementLength = 1)
{
UniformValue& value = Uniforms[handle.idx];
value.Data.assign(data.begin(), data.end());
value.ElementLength = static_cast<uint16_t>(elementLength);
}
};
class NativeEngine final : public Napi::ObjectWrap<NativeEngine>
{
static constexpr auto JS_CLASS_NAME = "_NativeEngine";
static constexpr auto JS_CONSTRUCTOR_NAME = "Engine";
public:
NativeEngine(const Napi::CallbackInfo& info);
NativeEngine(const Napi::CallbackInfo& info, JsRuntime& runtime);
~NativeEngine();
static void Initialize(Napi::Env env);
private:
void Dispose();
void Dispose(const Napi::CallbackInfo& info);
void RequestAnimationFrame(const Napi::CallbackInfo& info);
Napi::Value CreateVertexArray(const Napi::CallbackInfo& info);
void DeleteVertexArray(NativeDataStream::Reader& data);
void BindVertexArray(NativeDataStream::Reader& data);
Napi::Value CreateIndexBuffer(const Napi::CallbackInfo& info);
void DeleteIndexBuffer(NativeDataStream::Reader& data);
void RecordIndexBuffer(const Napi::CallbackInfo& info);
void UpdateDynamicIndexBuffer(const Napi::CallbackInfo& info);
Napi::Value CreateVertexBuffer(const Napi::CallbackInfo& info);
void DeleteVertexBuffer(NativeDataStream::Reader& data);
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(NativeDataStream::Reader& data);
void DeleteProgram(NativeDataStream::Reader& data);
void SetState(NativeDataStream::Reader& data);
void SetZOffset(NativeDataStream::Reader& data);
void SetZOffsetUnits(NativeDataStream::Reader& data);
void SetDepthTest(NativeDataStream::Reader& data);
void SetDepthWrite(NativeDataStream::Reader& data);
void SetColorWrite(NativeDataStream::Reader& data);
void SetBlendMode(NativeDataStream::Reader& data);
void SetMatrix(NativeDataStream::Reader& data);
void SetInt(NativeDataStream::Reader& data);
void SetIntArray(NativeDataStream::Reader& data);
void SetIntArray2(NativeDataStream::Reader& data);
void SetIntArray3(NativeDataStream::Reader& data);
void SetIntArray4(NativeDataStream::Reader& data);
void SetFloatArray(NativeDataStream::Reader& data);
void SetFloatArray2(NativeDataStream::Reader& data);
void SetFloatArray3(NativeDataStream::Reader& data);
void SetFloatArray4(NativeDataStream::Reader& data);
void SetMatrices(NativeDataStream::Reader& data);
void SetMatrix3x3(NativeDataStream::Reader& data);
void SetMatrix2x2(NativeDataStream::Reader& data);
void SetFloat(NativeDataStream::Reader& data);
void SetFloat2(NativeDataStream::Reader& data);
void SetFloat3(NativeDataStream::Reader& data);
void SetFloat4(NativeDataStream::Reader& data);
Napi::Value CreateTexture(const Napi::CallbackInfo& info);
void LoadTexture(const Napi::CallbackInfo& info);
void CopyTexture(const Napi::CallbackInfo& info);
void LoadRawTexture(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(NativeDataStream::Reader& data);
void SetTextureWrapMode(NativeDataStream::Reader& data);
void SetTextureAnisotropicLevel(NativeDataStream::Reader& data);
void SetTexture(NativeDataStream::Reader& data);
void DeleteTexture(const Napi::CallbackInfo& info);
Napi::Value CreateFrameBuffer(const Napi::CallbackInfo& info);
void DeleteFrameBuffer(NativeDataStream::Reader& data);
void BindFrameBuffer(NativeDataStream::Reader& data);
void UnbindFrameBuffer(NativeDataStream::Reader& data);
void DrawIndexed(NativeDataStream::Reader& data);
void Draw(NativeDataStream::Reader& data);
void Clear(NativeDataStream::Reader& data);
Napi::Value GetRenderWidth(const Napi::CallbackInfo& info);
Napi::Value GetRenderHeight(const Napi::CallbackInfo& info);
void SetViewPort(const Napi::CallbackInfo& info);
Napi::Value GetHardwareScalingLevel(const Napi::CallbackInfo& info);
void SetHardwareScalingLevel(const Napi::CallbackInfo& info);
Napi::Value CreateImageBitmap(const Napi::CallbackInfo& info);
Napi::Value ResizeImageBitmap(const Napi::CallbackInfo& info);
void GetFrameBufferData(const Napi::CallbackInfo& info);
void SetStencil(NativeDataStream::Reader& data);
void SetCommandDataStream(const Napi::CallbackInfo& info);
void SubmitCommands(const Napi::CallbackInfo& info);
void DrawInternal(bgfx::Encoder* encoder, uint32_t fillMode);
std::string ProcessShaderCoordinates(const std::string& vertexSource);
GraphicsImpl::UpdateToken& GetUpdateToken();
FrameBuffer& GetBoundFrameBuffer(bgfx::Encoder& encoder);
std::shared_ptr<arcana::cancellation_source> m_cancellationSource{};
ShaderCompiler m_shaderCompiler{};
ProgramData* m_currentProgram{nullptr};
JsRuntime& m_runtime;
GraphicsImpl& m_graphicsImpl;
JsRuntimeScheduler m_runtimeScheduler;
std::optional<GraphicsImpl::UpdateToken> m_updateToken{};
void ScheduleRequestAnimationFrameCallbacks();
bool m_requestAnimationFrameCallbacksScheduled{};
bx::DefaultAllocator m_allocator{};
uint64_t m_engineState{BGFX_STATE_DEFAULT};
uint32_t m_stencilState{BGFX_STENCIL_TEST_ALWAYS | BGFX_STENCIL_FUNC_REF(0) | BGFX_STENCIL_FUNC_RMASK(0xFF) | BGFX_STENCIL_OP_FAIL_S_KEEP | BGFX_STENCIL_OP_FAIL_Z_KEEP | BGFX_STENCIL_OP_PASS_Z_REPLACE};
template<int size, typename arrayType>
void SetTypeArrayN(const UniformInfo& uniformInfo, const uint32_t elementLength, const arrayType& array);
template<int size>
void SetIntArrayN(NativeDataStream::Reader& data);
template<int size>
void SetFloatArrayN(NativeDataStream::Reader& data);
template<int size>
void SetFloatN(NativeDataStream::Reader& data);
template<int size>
void SetMatrixN(NativeDataStream::Reader& data);
// Scratch vector used for data alignment.
std::vector<float> m_scratch{};
std::vector<Napi::FunctionReference> m_requestAnimationFrameCallbacks{};
VertexArray* m_boundVertexArray{};
FrameBuffer m_defaultFrameBuffer;
FrameBuffer* m_boundFrameBuffer{};
PerFrameValue<bool> m_boundFrameBufferNeedsRebinding;
// TODO: This should be changed to a non-owning ref once multi-update is available.
NativeDataStream* m_commandStream{};
};
}
| {
"alphanum_fraction": 0.6872136155,
"avg_line_length": 40.0262008734,
"ext": "h",
"hexsha": "3141cfdf5f2b0dd47f733493c7ef1c168237d80e",
"lang": "C",
"max_forks_count": 114,
"max_forks_repo_forks_event_max_datetime": "2022-03-11T21:13:27.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-10T18:07:19.000Z",
"max_forks_repo_head_hexsha": "1ee73a8e80b2a71d40e7bee8a4012b066a55b814",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "olidum/Babylon",
"max_forks_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h",
"max_issues_count": 593,
"max_issues_repo_head_hexsha": "1ee73a8e80b2a71d40e7bee8a4012b066a55b814",
"max_issues_repo_issues_event_max_datetime": "2022-03-31T19:25:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-05-31T23:56:36.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "olidum/Babylon",
"max_issues_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h",
"max_line_length": 210,
"max_stars_count": 474,
"max_stars_repo_head_hexsha": "1ee73a8e80b2a71d40e7bee8a4012b066a55b814",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "olidum/Babylon",
"max_stars_repo_path": "Plugins/NativeEngine/Source/NativeEngine.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T12:09:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-05-29T09:41:22.000Z",
"num_tokens": 2025,
"size": 9166
} |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <gbpLib.h>
#include <gbpMath.h>
#include <gbpCosmo_core.h>
#include <gbpCosmo_NFW_etc.h>
#include <gsl/gsl_sf_expint.h>
double V2_circ(double M, double r) {
return (G_NEWTON * M / r);
}
| {
"alphanum_fraction": 0.7003891051,
"avg_line_length": 19.7692307692,
"ext": "c",
"hexsha": "1ec669f4b7eade0499ab511780c31f739eb1967d",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2016-08-01T08:14:24.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T00:50:40.000Z",
"max_forks_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbpoole/gbpCode",
"max_forks_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/V2_circ.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_issues_repo_issues_event_max_datetime": "2019-06-18T00:40:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-07-30T11:10:49.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "gbpoole/gbpCode",
"max_issues_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/V2_circ.c",
"max_line_length": 36,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5157d2e377edbd4806258d1c16b329373186d43a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbpoole/gbpCode",
"max_stars_repo_path": "src/gbpAstro/gbpCosmo/NFW_etc/V2_circ.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": 85,
"size": 257
} |
// Copyright © Matt Jones and Contributors. Licensed under the MIT Licence (MIT). See LICENCE.md in the repository root
// for more information.
#ifndef NOVELRT_GRAPHICS_H
#define NOVELRT_GRAPHICS_H
// Graphics dependencies
#include "NovelRT/EngineConfig.h"
#include "NovelRT/Maths/Maths.h"
#include "NovelRT/ResourceManagement/ResourceManagement.h"
#include "NovelRT/SceneGraph/SceneGraph.h"
#include "NovelRT/Threading/Threading.h"
#include "NovelRT/Utilities/Event.h"
#include "NovelRT/Utilities/Lazy.h"
#include "NovelRT/Utilities/Misc.h"
#include "RGBAColour.h"
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <gsl/span>
#include <list>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <typeindex>
#include <utility>
#include <vector>
/**
* @brief The experimental Graphics plugin API. Comes with built-in support for the ECS.
*/
namespace NovelRT::Graphics
{
enum class ShaderProgramKind : uint32_t;
enum class GraphicsResourceAccess : uint32_t;
enum class GraphicsSurfaceKind : uint32_t;
enum class GraphicsTextureAddressMode : uint32_t;
enum class GraphicsPipelineBlendFactor : uint32_t;
enum class GraphicsPipelineInputElementKind : uint32_t;
enum class GraphicsPipelineResourceKind : uint32_t;
enum class ShaderProgramVisibility : uint32_t;
enum class GraphicsTextureKind : uint32_t;
enum class GraphicsMemoryRegionAllocationFlags : uint32_t;
enum class GraphicsMemoryRegionAllocationFlags : uint32_t;
enum class GraphicsBufferKind : uint32_t;
enum class TexelFormat : uint32_t;
struct GraphicsMemoryAllocatorSettings;
class GraphicsDeviceObject;
class IGraphicsSurface;
class GraphicsAdapter;
class GraphicsDevice;
class GraphicsResource;
class GraphicsBuffer;
class GraphicsTexture;
class ShaderProgram;
class GraphicsPipeline;
class GraphicsPipelineSignature;
class GraphicsPipelineInput;
class GraphicsPipelineResource;
class GraphicsPipelineInputElement;
class GraphicsContext;
class GraphicsFence;
class GraphicsPrimitive;
class GraphicsProvider;
class GraphicsMemoryAllocator;
class IGraphicsAdapterSelector;
class GraphicsMemoryBlockCollection;
class GraphicsMemoryBlock;
class GraphicsMemoryBudget;
class GraphicsSurfaceContext;
class GraphicsResourceManager;
}
// Graphics types
// clang-format off
#include "ShaderProgramKind.h"
#include "GraphicsAdapter.h"
#include "GraphicsDeviceObject.h"
#include "GraphicsContext.h"
#include "GraphicsFence.h"
#include "GraphicsMemoryAllocatorSettings.h"
#include "GraphicsMemoryRegion.h"
#include "IGraphicsMemoryRegionCollection.h"
#include "GraphicsMemoryRegionAllocationFlags.h"
#include "TexelFormat.h"
#include "GraphicsMemoryAllocator.h"
#include "GraphicsMemoryBlockCollection.h"
#include "GraphicsMemoryBudget.h"
#include "GraphicsMemoryBlock.h"
#include "GraphicsResourceAccess.h"
#include "GraphicsSurfaceKind.h"
#include "GraphicsTextureKind.h"
#include "IGraphicsSurface.h"
#include "GraphicsSurfaceContext.h"
#include "GraphicsDevice.h"
#include "GraphicsResource.h"
#include "GraphicsBufferKind.h"
#include "GraphicsBuffer.h"
#include "GraphicsTextureAddressMode.h"
#include "GraphicsTexture.h"
#include "IGraphicsAdapterSelector.h"
#include "ShaderProgram.h"
#include "GraphicsPipelineBlendFactor.h"
#include "GraphicsPipeline.h"
#include "GraphicsPipelineSignature.h"
#include "GraphicsPrimitive.h"
#include "GraphicsProvider.h"
#include "GraphicsPipelineInput.h"
#include "GraphicsPipelineInputElement.h"
#include "GraphicsPipelineInputElementKind.h"
#include "GraphicsPipelineResource.h"
#include "GraphicsPipelineResourceKind.h"
#include "ShaderProgramVisibility.h"
#include "GraphicsResourceManager.h"
// clang-format on
#endif // !NOVELRT_GRAPHICS_H
| {
"alphanum_fraction": 0.7934980494,
"avg_line_length": 31.7768595041,
"ext": "h",
"hexsha": "e913241987e384d172a96a0750e8d021f70d624e",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "53e341a79db9e84b47f80e12e1d7049a6874811d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Shidesu/NovelRT",
"max_forks_repo_path": "include/NovelRT/Graphics/Graphics.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "53e341a79db9e84b47f80e12e1d7049a6874811d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Shidesu/NovelRT",
"max_issues_repo_path": "include/NovelRT/Graphics/Graphics.h",
"max_line_length": 119,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "53e341a79db9e84b47f80e12e1d7049a6874811d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Shidesu/NovelRT",
"max_stars_repo_path": "include/NovelRT/Graphics/Graphics.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 820,
"size": 3845
} |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
* All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <chrono>
#include <functional>
#include <vector>
#include <immintrin.h>
#ifdef USE_BLAS
#if __APPLE__
// not sure whether need to differentiate TARGET_OS_MAC or TARGET_OS_IPHONE,
// etc.
#include <Accelerate/Accelerate.h>
#else
#include <cblas.h>
#endif
#endif
#ifdef _OPENMP
#include <omp.h>
#endif
#ifdef USE_MKL
#include <mkl.h>
#endif
#include "./AlignedVec.h"
#include "fbgemm/FbgemmBuild.h"
#include "fbgemm/FbgemmPackMatrixB.h"
#include "src/RefImplementations.h"
namespace fbgemm {
template <typename T>
void randFill(aligned_vector<T>& vec, T low, T high);
void llc_flush(std::vector<char>& llc);
// Same as omp_get_max_threads() when OpenMP is available, otherwise 1
int fbgemm_get_max_threads();
// Same as omp_get_num_threads() when OpenMP is available, otherwise 1
int fbgemm_get_num_threads();
// Same as omp_get_thread_num() when OpenMP is available, otherwise 0
int fbgemm_get_thread_num();
template <typename T>
NOINLINE float cache_evict(const T& vec) {
auto const size = vec.size();
auto const elemSize = sizeof(typename T::value_type);
auto const dataSize = size * elemSize;
const char* data = reinterpret_cast<const char*>(vec.data());
constexpr int CACHE_LINE_SIZE = 64;
// Not having this dummy computation significantly slows down the computation
// that follows.
float dummy = 0.0f;
for (std::size_t i = 0; i < dataSize; i += CACHE_LINE_SIZE) {
dummy += data[i] * 1.0f;
_mm_mfence();
#ifndef _MSC_VER
asm volatile("" ::: "memory");
#endif
_mm_clflush(&data[i]);
}
return dummy;
}
/**
* Parse application command line arguments
*
*/
int parseArgumentInt(
int argc,
const char* argv[],
const char* arg,
int non_exist_val,
int def_val);
bool parseArgumentBool(
int argc,
const char* argv[],
const char* arg,
bool def_val);
namespace {
struct empty_flush {
void operator()() const {}
};
} // namespace
/**
* @param Fn functor to execute
* @param Fe data eviction functor
*/
template <class Fn, class Fe = std::function<void()>>
double measureWithWarmup(
Fn&& fn,
int warmupIterations,
int measuredIterations,
const Fe& fe = empty_flush(),
bool useOpenMP = false) {
for (int i = 0; i < warmupIterations; ++i) {
// Evict data first
fe();
fn();
}
double ttot = 0.0;
#ifdef _OPENMP
#pragma omp parallel if (useOpenMP)
{
#endif
for (int i = 0; i < measuredIterations; ++i) {
int thread_id = 0;
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
#ifdef _OPENMP
if (useOpenMP) {
thread_id = omp_get_thread_num();
}
#endif
if (thread_id == 0) {
fe();
}
#ifdef _OPENMP
if (useOpenMP) {
#pragma omp barrier
}
#endif
start = std::chrono::high_resolution_clock::now();
fn();
#ifdef _OPENMP
if (useOpenMP) {
#pragma omp barrier
}
#endif
end = std::chrono::high_resolution_clock::now();
auto dur =
std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);
if (thread_id == 0) {
// TODO: measure load imbalance
ttot += dur.count();
}
}
#ifdef _OPENMP
}
#endif
return ttot / 1e9 / measuredIterations;
}
/*
* @brief Out-of-place transposition for M*N matrix ref.
* @param M number of rows in input
* @param K number of columns in input
*/
template <typename T>
void transpose_matrix(
int M,
int N,
const T* src,
int ld_src,
T* dst,
int ld_dst) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
dst[i * ld_dst + j] = src[i + j * ld_src];
}
} // for each output row
}
/*
* @brief In-place transposition for nxk matrix ref.
* @param n number of rows in input (number of columns in output)
* @param k number of columns in input (number of rows in output)
*/
template <typename T>
void transpose_matrix(T* ref, int n, int k) {
std::vector<T> local(n * k);
transpose_matrix(n, k, ref, k, local.data(), n);
memcpy(ref, local.data(), n * k * sizeof(T));
}
#if defined(USE_MKL)
void test_xerbla(char* srname, const int* info, int);
#endif
#define dataset 1
template <typename btype>
void performance_test(
int num_instances,
bool flush,
int repetitions,
bool is_mkl) {
#if defined(USE_MKL)
mkl_set_xerbla((XerblaEntry)test_xerbla);
#endif
float alpha = 1.f, beta = 1.f;
matrix_op_t btran = matrix_op_t::Transpose;
#if dataset == 1
const int NITER = (flush) ? 10 : 100;
std::vector<std::vector<int>> shapes;
for (auto m = 1; m < 120; m++) {
// shapes.push_back({m, 128, 512});
shapes.push_back({m, 512, 512});
}
#elif dataset == 2
const int NITER = (flush) ? 10 : 100;
#include "shapes_dataset.h"
#else
flush = false;
constexpr int NITER = 1;
std::vector<std::vector<int>> shapes;
std::random_device r;
std::default_random_engine generator(r());
std::uniform_int_distribution<int> dm(1, 100);
std::uniform_int_distribution<int> dnk(1, 1024);
for (int i = 0; i < 1000; i++) {
int m = dm(generator);
int n = dnk(generator);
int k = dnk(generator);
shapes.push_back({m, n, k});
}
#endif
std::string type;
double gflops, gbs, ttot;
for (auto s : shapes) {
int m = s[0];
int n = s[1];
int k = s[2];
// initialize with small numbers
aligned_vector<int> Aint(m * k);
randFill(Aint, 0, 4);
std::vector<aligned_vector<float>> A;
for (int i = 0; i < num_instances; ++i) {
A.push_back(aligned_vector<float>(Aint.begin(), Aint.end()));
}
aligned_vector<int> Bint(k * n);
randFill(Bint, 0, 4);
aligned_vector<float> B(Bint.begin(), Bint.end());
std::vector<std::unique_ptr<PackedGemmMatrixB<btype>>> Bp;
for (int i = 0; i < num_instances; ++i) {
Bp.emplace_back(std::unique_ptr<PackedGemmMatrixB<btype>>(
new PackedGemmMatrixB<btype>(btran, k, n, alpha, B.data())));
}
auto kAligned = ((k * sizeof(float) + 64) & ~63) / sizeof(float);
auto nAligned = ((n * sizeof(float) + 64) & ~63) / sizeof(float);
std::vector<aligned_vector<float>> Bt(num_instances);
auto& Bt_ref = Bt[0];
if (btran == matrix_op_t::Transpose) {
Bt_ref.resize(k * nAligned);
for (auto row = 0; row < k; ++row) {
for (auto col = 0; col < n; ++col) {
Bt_ref[row * nAligned + col] = alpha * B[col * k + row];
}
}
} else {
Bt_ref.resize(kAligned * n);
for (auto row = 0; row < k; ++row) {
for (auto col = 0; col < n; ++col) {
Bt_ref[col * kAligned + row] = alpha * B[col * k + row];
}
}
}
for (auto i = 1; i < num_instances; ++i) {
Bt[i] = Bt_ref;
}
std::vector<aligned_vector<float>> C_ref;
std::vector<aligned_vector<float>> C_fb;
if (beta != 0.0f) {
aligned_vector<int> Cint(m * n);
randFill(Cint, 0, 4);
for (int i = 0; i < num_instances; ++i) {
C_ref.push_back(aligned_vector<float>(Cint.begin(), Cint.end()));
C_fb.push_back(aligned_vector<float>(Cint.begin(), Cint.end()));
}
} else {
for (int i = 0; i < num_instances; ++i) {
C_ref.push_back(aligned_vector<float>(m * n, 1.f));
C_fb.push_back(aligned_vector<float>(m * n, NAN));
}
}
double nflops = 2.0 * m * n * k;
double nbytes = 4.0 * m * k + sizeof(btype) * 1.0 * k * n + 4.0 * m * n;
// warm up MKL and fbgemm
// check correctness at the same time
for (auto w = 0; w < 3; w++) {
#if defined(USE_MKL) || defined(USE_BLAS)
cblas_sgemm(
CblasRowMajor,
CblasNoTrans,
CblasNoTrans, // B is pretransposed, if required by operation
m,
n,
k,
1.0, // Mutliplication by Alpha is done during transpose of B
A[0].data(),
k,
Bt[0].data(),
btran == matrix_op_t::NoTranspose ? kAligned : nAligned,
beta,
C_ref[0].data(),
n);
#else
cblas_sgemm_ref(
matrix_op_t::NoTranspose,
matrix_op_t::NoTranspose,
m,
n,
k,
1.0,
A[0].data(),
k,
Bt[0].data(),
(btran == matrix_op_t::NoTranspose) ? kAligned : nAligned,
beta,
C_ref[0].data(),
n);
#endif
#ifdef _OPENMP
#pragma omp parallel if (num_instances == 1)
#endif
{
int num_threads = num_instances == 1 ? fbgemm_get_num_threads() : 1;
int tid = num_instances == 1 ? fbgemm_get_thread_num() : 0;
cblas_gemm_compute(
matrix_op_t::NoTranspose,
m,
A[0].data(),
*Bp[0],
beta,
C_fb[0].data(),
tid,
num_threads);
}
#if defined(USE_MKL) || defined(USE_BLAS)
// Compare results
for (auto i = 0; i < C_ref[0].size(); i++) {
if (std::abs(C_ref[0][i] - C_fb[0][i]) > 1e-3) {
fprintf(
stderr,
"Error: too high diff between fp32 ref %f and fp16 %f at %d\n",
C_ref[0][i],
C_fb[0][i],
i);
return;
}
}
#endif
}
#if defined(USE_MKL)
if (is_mkl) {
// Gold via MKL sgemm
type = "MKL_FP32";
#elif defined(USE_BLAS)
type = "BLAS_FP32";
#else
type = "REF_FP32";
#endif
ttot = measureWithWarmup(
[&]() {
int copy = num_instances == 1 ? 0 : fbgemm_get_thread_num();
for (int i = 0; i < repetitions; ++i) {
#if defined(USE_MKL) || defined(USE_BLAS)
cblas_sgemm(
CblasRowMajor,
CblasNoTrans,
CblasNoTrans,
m,
n,
k,
1.0,
A[copy].data(),
k,
Bt[copy].data(),
btran == matrix_op_t::NoTranspose ? kAligned : nAligned,
beta,
C_ref[copy].data(),
n);
#else
cblas_sgemm_ref(
matrix_op_t::NoTranspose,
matrix_op_t::NoTranspose,
m,
n,
k,
1.0,
A[copy].data(),
k,
Bt[copy].data(),
(btran == matrix_op_t::NoTranspose) ? kAligned : nAligned,
beta,
C_ref[copy].data(),
n);
#endif
}
},
3,
NITER,
[&]() {
if (flush) {
int copy = num_instances == 1 ? 0 : fbgemm_get_thread_num();
cache_evict(A[copy]);
cache_evict(Bt[copy]);
cache_evict(C_ref[copy]);
}
},
// Use OpenMP if num instances > 1
num_instances > 1);
gflops = nflops / ttot / 1e9;
gbs = nbytes / ttot / 1e9;
printf(
"\n%30s m = %5d n = %5d k = %5d Gflops = %8.4lf GBytes = %8.4lf\n",
type.c_str(),
m,
n,
k,
gflops * repetitions,
gbs * repetitions);
#ifdef USE_MKL
}
#endif
type = "FBP_" + std::string(typeid(btype).name());
ttot = measureWithWarmup(
[&]() {
// When executing in data decomposition (single-instance) mode
// Different threads will access different regions of the same
// matrices. Thus, copy to be used is always 0. The numbers of
// threads would be the as number of threads in the parallel
// region.
// When running in functional decomposition (multi-instance) mode
// different matrices are used. The copy to be used selected by
// thread_id (thread_num), and the number of threads performance
// the compute of the same instance is 1.
int copy = num_instances == 1 ? 0 : fbgemm_get_thread_num();
int num_threads = num_instances == 1 ? fbgemm_get_num_threads() : 1;
int tid = num_instances == 1 ? fbgemm_get_thread_num() : 0;
for (int i = 0; i < repetitions; ++i) {
cblas_gemm_compute(
matrix_op_t::NoTranspose,
m,
A[copy].data(),
*Bp[copy],
beta,
C_fb[copy].data(),
tid,
num_threads);
}
},
3,
NITER,
[&]() {
if (flush) {
int copy = num_instances == 1 ? 0 : fbgemm_get_thread_num();
cache_evict(A[copy]);
cache_evict(*Bp[copy]);
cache_evict(C_fb[copy]);
}
},
true /*useOpenMP*/);
gflops = nflops / ttot / 1e9;
gbs = nbytes / ttot / 1e9;
printf(
"%30s m = %5d n = %5d k = %5d Gflops = %8.4lf GBytes = %8.4lf\n",
type.c_str(),
m,
n,
k,
gflops * repetitions,
gbs * repetitions);
}
}
} // namespace fbgemm
| {
"alphanum_fraction": 0.54993965,
"avg_line_length": 26.1459566075,
"ext": "h",
"hexsha": "8ce0bfc3b536667aee5d31bc7751292f0ddbffe5",
"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": "c52008892732932d63829802403b54f551d1560f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "joe7hu/FBGEMM",
"max_forks_repo_path": "bench/BenchUtils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c52008892732932d63829802403b54f551d1560f",
"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": "joe7hu/FBGEMM",
"max_issues_repo_path": "bench/BenchUtils.h",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c52008892732932d63829802403b54f551d1560f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "joe7hu/FBGEMM",
"max_stars_repo_path": "bench/BenchUtils.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3729,
"size": 13256
} |
/* matrix/gsl_matrix_long_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_LONG_DOUBLE_H__
#define __GSL_MATRIX_LONG_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_long_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;
long double * data;
gsl_block_long_double * block;
int owner;
} gsl_matrix_long_double;
typedef struct
{
gsl_matrix_long_double matrix;
} _gsl_matrix_long_double_view;
typedef _gsl_matrix_long_double_view gsl_matrix_long_double_view;
typedef struct
{
gsl_matrix_long_double matrix;
} _gsl_matrix_long_double_const_view;
typedef const _gsl_matrix_long_double_const_view gsl_matrix_long_double_const_view;
/* Allocation */
GSL_FUN gsl_matrix_long_double *
gsl_matrix_long_double_alloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_long_double *
gsl_matrix_long_double_calloc (const size_t n1, const size_t n2);
GSL_FUN gsl_matrix_long_double *
gsl_matrix_long_double_alloc_from_block (gsl_block_long_double * b,
const size_t offset,
const size_t n1,
const size_t n2,
const size_t d2);
GSL_FUN gsl_matrix_long_double *
gsl_matrix_long_double_alloc_from_matrix (gsl_matrix_long_double * m,
const size_t k1,
const size_t k2,
const size_t n1,
const size_t n2);
GSL_FUN gsl_vector_long_double *
gsl_vector_long_double_alloc_row_from_matrix (gsl_matrix_long_double * m,
const size_t i);
GSL_FUN gsl_vector_long_double *
gsl_vector_long_double_alloc_col_from_matrix (gsl_matrix_long_double * m,
const size_t j);
GSL_FUN void gsl_matrix_long_double_free (gsl_matrix_long_double * m);
/* Views */
GSL_FUN _gsl_matrix_long_double_view
gsl_matrix_long_double_submatrix (gsl_matrix_long_double * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_long_double_view
gsl_matrix_long_double_row (gsl_matrix_long_double * m, const size_t i);
GSL_FUN _gsl_vector_long_double_view
gsl_matrix_long_double_column (gsl_matrix_long_double * m, const size_t j);
GSL_FUN _gsl_vector_long_double_view
gsl_matrix_long_double_diagonal (gsl_matrix_long_double * m);
GSL_FUN _gsl_vector_long_double_view
gsl_matrix_long_double_subdiagonal (gsl_matrix_long_double * m, const size_t k);
GSL_FUN _gsl_vector_long_double_view
gsl_matrix_long_double_superdiagonal (gsl_matrix_long_double * m, const size_t k);
GSL_FUN _gsl_vector_long_double_view
gsl_matrix_long_double_subrow (gsl_matrix_long_double * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_long_double_view
gsl_matrix_long_double_subcolumn (gsl_matrix_long_double * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_long_double_view
gsl_matrix_long_double_view_array (long double * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_long_double_view
gsl_matrix_long_double_view_array_with_tda (long double * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_long_double_view
gsl_matrix_long_double_view_vector (gsl_vector_long_double * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_long_double_view
gsl_matrix_long_double_view_vector_with_tda (gsl_vector_long_double * v,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_long_double_const_view
gsl_matrix_long_double_const_submatrix (const gsl_matrix_long_double * m,
const size_t i, const size_t j,
const size_t n1, const size_t n2);
GSL_FUN _gsl_vector_long_double_const_view
gsl_matrix_long_double_const_row (const gsl_matrix_long_double * m,
const size_t i);
GSL_FUN _gsl_vector_long_double_const_view
gsl_matrix_long_double_const_column (const gsl_matrix_long_double * m,
const size_t j);
GSL_FUN _gsl_vector_long_double_const_view
gsl_matrix_long_double_const_diagonal (const gsl_matrix_long_double * m);
GSL_FUN _gsl_vector_long_double_const_view
gsl_matrix_long_double_const_subdiagonal (const gsl_matrix_long_double * m,
const size_t k);
GSL_FUN _gsl_vector_long_double_const_view
gsl_matrix_long_double_const_superdiagonal (const gsl_matrix_long_double * m,
const size_t k);
GSL_FUN _gsl_vector_long_double_const_view
gsl_matrix_long_double_const_subrow (const gsl_matrix_long_double * m, const size_t i,
const size_t offset, const size_t n);
GSL_FUN _gsl_vector_long_double_const_view
gsl_matrix_long_double_const_subcolumn (const gsl_matrix_long_double * m, const size_t j,
const size_t offset, const size_t n);
GSL_FUN _gsl_matrix_long_double_const_view
gsl_matrix_long_double_const_view_array (const long double * base,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_long_double_const_view
gsl_matrix_long_double_const_view_array_with_tda (const long double * base,
const size_t n1,
const size_t n2,
const size_t tda);
GSL_FUN _gsl_matrix_long_double_const_view
gsl_matrix_long_double_const_view_vector (const gsl_vector_long_double * v,
const size_t n1,
const size_t n2);
GSL_FUN _gsl_matrix_long_double_const_view
gsl_matrix_long_double_const_view_vector_with_tda (const gsl_vector_long_double * v,
const size_t n1,
const size_t n2,
const size_t tda);
/* Operations */
GSL_FUN void gsl_matrix_long_double_set_zero (gsl_matrix_long_double * m);
GSL_FUN void gsl_matrix_long_double_set_identity (gsl_matrix_long_double * m);
GSL_FUN void gsl_matrix_long_double_set_all (gsl_matrix_long_double * m, long double x);
GSL_FUN int gsl_matrix_long_double_fread (FILE * stream, gsl_matrix_long_double * m) ;
GSL_FUN int gsl_matrix_long_double_fwrite (FILE * stream, const gsl_matrix_long_double * m) ;
GSL_FUN int gsl_matrix_long_double_fscanf (FILE * stream, gsl_matrix_long_double * m);
GSL_FUN int gsl_matrix_long_double_fprintf (FILE * stream, const gsl_matrix_long_double * m, const char * format);
GSL_FUN int gsl_matrix_long_double_memcpy(gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);
GSL_FUN int gsl_matrix_long_double_swap(gsl_matrix_long_double * m1, gsl_matrix_long_double * m2);
GSL_FUN int gsl_matrix_long_double_tricpy(CBLAS_UPLO_t Uplo, CBLAS_DIAG_t Diag, gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);
GSL_FUN int gsl_matrix_long_double_swap_rows(gsl_matrix_long_double * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_long_double_swap_columns(gsl_matrix_long_double * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_long_double_swap_rowcol(gsl_matrix_long_double * m, const size_t i, const size_t j);
GSL_FUN int gsl_matrix_long_double_transpose (gsl_matrix_long_double * m);
GSL_FUN int gsl_matrix_long_double_transpose_memcpy (gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);
GSL_FUN int gsl_matrix_long_double_transpose_tricpy (CBLAS_UPLO_t Uplo_src, CBLAS_DIAG_t Diag, gsl_matrix_long_double * dest, const gsl_matrix_long_double * src);
GSL_FUN long double gsl_matrix_long_double_max (const gsl_matrix_long_double * m);
GSL_FUN long double gsl_matrix_long_double_min (const gsl_matrix_long_double * m);
GSL_FUN void gsl_matrix_long_double_minmax (const gsl_matrix_long_double * m, long double * min_out, long double * max_out);
GSL_FUN void gsl_matrix_long_double_max_index (const gsl_matrix_long_double * m, size_t * imax, size_t *jmax);
GSL_FUN void gsl_matrix_long_double_min_index (const gsl_matrix_long_double * m, size_t * imin, size_t *jmin);
GSL_FUN void gsl_matrix_long_double_minmax_index (const gsl_matrix_long_double * m, size_t * imin, size_t * jmin, size_t * imax, size_t * jmax);
GSL_FUN int gsl_matrix_long_double_equal (const gsl_matrix_long_double * a, const gsl_matrix_long_double * b);
GSL_FUN int gsl_matrix_long_double_isnull (const gsl_matrix_long_double * m);
GSL_FUN int gsl_matrix_long_double_ispos (const gsl_matrix_long_double * m);
GSL_FUN int gsl_matrix_long_double_isneg (const gsl_matrix_long_double * m);
GSL_FUN int gsl_matrix_long_double_isnonneg (const gsl_matrix_long_double * m);
GSL_FUN int gsl_matrix_long_double_add (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);
GSL_FUN int gsl_matrix_long_double_sub (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);
GSL_FUN int gsl_matrix_long_double_mul_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);
GSL_FUN int gsl_matrix_long_double_div_elements (gsl_matrix_long_double * a, const gsl_matrix_long_double * b);
GSL_FUN int gsl_matrix_long_double_scale (gsl_matrix_long_double * a, const double x);
GSL_FUN int gsl_matrix_long_double_scale_rows (gsl_matrix_long_double * a, const gsl_vector_long_double * x);
GSL_FUN int gsl_matrix_long_double_scale_columns (gsl_matrix_long_double * a, const gsl_vector_long_double * x);
GSL_FUN int gsl_matrix_long_double_add_constant (gsl_matrix_long_double * a, const double x);
GSL_FUN int gsl_matrix_long_double_add_diagonal (gsl_matrix_long_double * a, const double x);
/***********************************************************************/
/* The functions below are obsolete */
/***********************************************************************/
GSL_FUN int gsl_matrix_long_double_get_row(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t i);
GSL_FUN int gsl_matrix_long_double_get_col(gsl_vector_long_double * v, const gsl_matrix_long_double * m, const size_t j);
GSL_FUN int gsl_matrix_long_double_set_row(gsl_matrix_long_double * m, const size_t i, const gsl_vector_long_double * v);
GSL_FUN int gsl_matrix_long_double_set_col(gsl_matrix_long_double * m, const size_t j, const gsl_vector_long_double * v);
/***********************************************************************/
/* inline functions if you are using GCC */
GSL_FUN INLINE_DECL long double gsl_matrix_long_double_get(const gsl_matrix_long_double * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL void gsl_matrix_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long double x);
GSL_FUN INLINE_DECL long double * gsl_matrix_long_double_ptr(gsl_matrix_long_double * m, const size_t i, const size_t j);
GSL_FUN INLINE_DECL const long double * gsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * m, const size_t i, const size_t j);
#ifdef HAVE_INLINE
INLINE_FUN
long double
gsl_matrix_long_double_get(const gsl_matrix_long_double * 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_long_double_set(gsl_matrix_long_double * m, const size_t i, const size_t j, const long 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
long double *
gsl_matrix_long_double_ptr(gsl_matrix_long_double * 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 (long double *) (m->data + (i * m->tda + j)) ;
}
INLINE_FUN
const long double *
gsl_matrix_long_double_const_ptr(const gsl_matrix_long_double * 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 long double *) (m->data + (i * m->tda + j)) ;
}
#endif
__END_DECLS
#endif /* __GSL_MATRIX_LONG_DOUBLE_H__ */
| {
"alphanum_fraction": 0.700400534,
"avg_line_length": 40.9289617486,
"ext": "h",
"hexsha": "b14c07900ae0a519faf6e811b49cbd4015802b34",
"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_long_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_long_double.h",
"max_line_length": 162,
"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_long_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": 3572,
"size": 14980
} |
/* 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 UKF_PARAMETER_NDIM_H
#define UKF_PARAMETER_NDIM_H
#include <gsl/gsl_linalg.h> // For the Cholesky decomposition
#include <gsl/gsl_math.h>
#include <gsl/gsl_blas.h>
#include "ukf_types.h"
namespace ukf
{
namespace parameter
{
/**
* @short Allocation of the vectors/matrices and initialization
*
*/
void ukf_init(ukf_param &p, ukf_state &s)
{
// Init the lambda
p.lambda = p.alpha * p.alpha * (p.n + p.kpa) - p.n;
p.gamma = sqrt(p.n + p.lambda);
p.nbSamples = 2 * p.n + 1;
// Init the matrices used to iterate
s.Kk = gsl_matrix_alloc(p.n,p.no); // Kalman gain
gsl_matrix_set_zero(s.Kk);
s.Kk_T = gsl_matrix_alloc(p.no,p.n);
gsl_matrix_set_zero(s.Kk_T);
s.Pwdk = gsl_matrix_alloc(p.n,p.no);
gsl_matrix_set_zero(s.Pwdk);
// Whatever the type of evolution noise, its covariance is set to evolution_noise
s.Prrk = gsl_matrix_alloc(p.n,p.n);
p.evolution_noise->init(p,s);
// Whatever the type of observation noise, its covariance is set to observation_noise
s.Peek = gsl_matrix_alloc(p.no,p.no);
gsl_matrix_set_identity(s.Peek);
gsl_matrix_scale(s.Peek, p.observation_noise);
s.Pddk = gsl_matrix_alloc(p.no, p.no); // Covariance of the output
gsl_matrix_set_zero(s.Pddk);
s.w = gsl_vector_alloc(p.n); // Parameter vector
gsl_vector_set_zero(s.w);
s.wk = gsl_vector_alloc(p.n); // Vector holding one sigma point
gsl_vector_set_zero(s.wk);
s.Pk = gsl_matrix_alloc(p.n,p.n); // Covariance matrix
gsl_matrix_set_identity(s.Pk);
gsl_matrix_scale(s.Pk,p.prior_pi);
s.Sk = gsl_matrix_alloc(p.n,p.n); // Matrix holding the cholesky decomposition of Pk
// Initialize Sk to the cholesky decomposition of Pk
gsl_matrix_memcpy(s.Sk, s.Pk);
gsl_linalg_cholesky_decomp(s.Sk);
// Set all the elements of Lpi strictly above the diagonal to zero
for(int k = 0 ; k < p.n ; k++)
for(int j = 0 ; j < k ; j++)
gsl_matrix_set(s.Sk,j,k,0.0);
s.cSk = gsl_vector_alloc(p.n); // Vector holding one column of Lpi
gsl_vector_set_zero(s.cSk);
s.wm = gsl_vector_alloc(p.nbSamples); // Weights used to compute the mean of the sigma points images
s.wc = gsl_vector_alloc(p.nbSamples); // Weights used to update the covariance matrices
// Set the weights
gsl_vector_set(s.wm, 0, p.lambda / (p.n + p.lambda));
gsl_vector_set(s.wc, 0, p.lambda / (p.n + p.lambda) + (1.0 - p.alpha*p.alpha + p.beta));
for(int j = 1 ; j < p.nbSamples; j ++)
{
gsl_vector_set(s.wm, j, 1.0 / (2.0 * (p.n + p.lambda)));
gsl_vector_set(s.wc, j, 1.0 / (2.0 * (p.n + p.lambda)));
}
s.dk = gsl_matrix_alloc(p.no, p.nbSamples); // Holds the image of the sigma points
gsl_matrix_set_zero(s.dk);
s.ino_dk = gsl_vector_alloc(p.no); // Holds the inovation
gsl_vector_set_zero(s.ino_dk);
s.d_mean = gsl_vector_alloc(p.no); // Holds the mean of the sigma points images
gsl_vector_set_zero(s.d_mean);
s.sigmaPoints = gsl_matrix_alloc(p.n,p.nbSamples); // Holds the sigma points in the columns
gsl_matrix_set_zero(s.sigmaPoints);
// Temporary vectors/matrices
s.vec_temp_n = gsl_vector_alloc(p.n);
s.vec_temp_output = gsl_vector_alloc(p.no);
s.mat_temp_n_1 = gsl_matrix_alloc(p.n,1);
s.mat_temp_n_output = gsl_matrix_alloc(p.n, p.no);
s.mat_temp_output_n = gsl_matrix_alloc(p.no, p.n);
s.mat_temp_1_output = gsl_matrix_alloc(1,p.no);
s.mat_temp_output_1 = gsl_matrix_alloc(p.no, 1);
s.mat_temp_output_output = gsl_matrix_alloc(p.no, p.no);
s.mat_temp_n_n = gsl_matrix_alloc(p.n, p.n);
}
/**
* @short Free of memory allocation
*
*/
void ukf_free(ukf_param &p, ukf_state &s)
{
gsl_matrix_free(s.Kk);
gsl_matrix_free(s.Kk_T);
gsl_matrix_free(s.Pwdk);
gsl_matrix_free(s.Pddk);
gsl_matrix_free(s.Peek);
gsl_matrix_free(s.Prrk);
gsl_vector_free(s.w);
gsl_vector_free(s.wk);
gsl_matrix_free(s.Pk);
gsl_matrix_free(s.Sk);
gsl_vector_free(s.cSk);
gsl_vector_free(s.wm);
gsl_vector_free(s.wc);
gsl_matrix_free(s.dk);
gsl_vector_free(s.ino_dk);
gsl_vector_free(s.d_mean);
gsl_matrix_free(s.sigmaPoints);
gsl_vector_free(s.vec_temp_n);
gsl_vector_free(s.vec_temp_output);
gsl_matrix_free(s.mat_temp_n_1);
gsl_matrix_free(s.mat_temp_n_output);
gsl_matrix_free(s.mat_temp_output_n);
gsl_matrix_free(s.mat_temp_1_output);
gsl_matrix_free(s.mat_temp_output_1);
gsl_matrix_free(s.mat_temp_output_output);
gsl_matrix_free(s.mat_temp_n_n);
}
/**
* @short Iteration for the statistical linearization
*
*/
template<typename GFUNC>
void ukf_iterate(ukf_param &p, ukf_state &s,
GFUNC g,
gsl_vector * xk, gsl_vector* dk)
{
// Here, we implement the UKF for parameter estimation in the vectorial case
// The notations follow p93 of the PhD thesis of Van Der Merwe, "Sigma-Point Kalman Filters for Probabilistic Inference in Dynamic State-Space Models"
// ************************************************** //
// ************ Time update equations ************ //
// ************************************************** //
// Add the evolution noise to the parameter covariance Eq 3.137
gsl_matrix_add(s.Pk, s.Prrk);
// ************************************************** //
// ************ Compute the sigma points ************ //
// ************************************************** //
// Equations 3.138
// w_k^j = w_(k-1) <-- this is here denoted s.w
// w_k^j = w_(k-1) + gamma Sk_j for 1 <= j <= n
// w_k^j = w_(k-1) - gamma Sk_j for n+1 <= j <= 2n
// Perform a cholesky decomposition of Pk
gsl_matrix_memcpy(s.Sk, s.Pk);
gsl_linalg_cholesky_decomp(s.Sk);
// Set all the elements of Lpi strictly above the diagonal to zero
for(int k = 0 ; k < p.n ; ++k)
for(int j = 0 ; j < k ; ++j)
gsl_matrix_set(s.Sk,j,k,0.0);
gsl_matrix_set_col(s.sigmaPoints,0, s.w);
for(int j = 1 ; j < p.n+1 ; ++j)
for(int i = 0 ; i < p.n ; ++i)
gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) + p.gamma * gsl_matrix_get(s.Sk,i,j-1));
for(int j = p.n+1 ; j < p.nbSamples ; ++j)
for(int i = 0 ; i < p.n ; ++i)
gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) - p.gamma * gsl_matrix_get(s.Sk,i,j-(p.n+1)));
/**************************************************/
/***** Compute the images of the sigma points *****/
/**************************************************/
// Compute the images of the sigma points
// and the mean of the dk
gsl_vector_set_zero(s.d_mean);
for(int j = 0 ; j < p.nbSamples ; j++)
{
// Equation 3.129
gsl_matrix_get_col(s.wk, s.sigmaPoints,j);
g(s.wk,xk, s.vec_temp_output);
gsl_matrix_set_col(s.dk, j, s.vec_temp_output);
// Equation 3.140
// Update the mean : y_mean = sum_[j=0..2n] w_j y_j
gsl_vector_scale(s.vec_temp_output, gsl_vector_get(s.wm,j));
gsl_vector_add(s.d_mean, s.vec_temp_output);
}
/**************************************************/
/************** Update the statistics *************/
/**************************************************/
gsl_matrix_set_zero(s.Pwdk);
gsl_matrix_memcpy(s.Pddk, s.Peek); // Add R^e_k to Pddk, Eq 3.142
for(int j = 0 ; j < p.nbSamples ; ++j)
{
// Update of Pwdk
// (wk - w)
gsl_matrix_get_col(s.wk, s.sigmaPoints,j);
gsl_vector_sub(s.wk, s.w);
gsl_matrix_set_col(s.mat_temp_n_1, 0, s.wk);
// (dk - d_mean)
gsl_matrix_get_col(s.vec_temp_output, s.dk, j);
gsl_vector_sub(s.vec_temp_output, s.d_mean);
gsl_matrix_set_col(s.mat_temp_output_1, 0, s.vec_temp_output);
// compute wc_j . (wk - w_mean) * (dk - d_mean)^T
gsl_blas_dgemm(CblasNoTrans, CblasTrans, gsl_vector_get(s.wc,j) , s.mat_temp_n_1, s.mat_temp_output_1, 0.0, s.mat_temp_n_output);
// Equation 3.142
// And add it to Pwdk
gsl_matrix_add(s.Pwdk, s.mat_temp_n_output);
// Equation 3.143
// Update of Pddk
gsl_matrix_get_col(s.vec_temp_output, s.dk, j);
gsl_vector_sub(s.vec_temp_output, s.d_mean);
gsl_matrix_set_col(s.mat_temp_output_1, 0, s.vec_temp_output);
gsl_blas_dgemm(CblasNoTrans, CblasTrans, gsl_vector_get(s.wc,j) , s.mat_temp_output_1, s.mat_temp_output_1, 0.0, s.mat_temp_output_output);
gsl_matrix_add(s.Pddk, s.mat_temp_output_output);
}
// ************************************************** //
// ******* Kalman gain and parameters update ******** //
// ************************************************** //
//*** Ki = Pwdk Pddk^-1
// Compute the inverse of Pddk
gsl_matrix_memcpy(s.mat_temp_output_output, s.Pddk);
gsl_linalg_cholesky_decomp(s.mat_temp_output_output);
gsl_linalg_cholesky_invert(s.mat_temp_output_output);
// Compute the product : Pwdk . Pddk^-1
// Equation 3.144
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0 , s.Pwdk, s.mat_temp_output_output, 0.0, s.Kk);
// Update of the parameters
// wk = w_(k-1) + Kk * (dk - d_mean)
// Equation 3.145
// Set the inovations
/*for(int i = 0 ; i < p.no; ++i)
s.ino_dk->data[i] = dk->data[i] - s.d_mean->data[i];
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0 , s.Kk, &gsl_matrix_view_array(s.ino_dk->data,p.no,1).matrix, 0.0, s.mat_temp_n_1);
gsl_matrix_get_col(s.vec_temp_n, s.mat_temp_n_1, 0);
gsl_vector_add(s.w, s.vec_temp_n);*/
for(int i = 0 ; i < p.no; ++i)
s.ino_dk->data[i] = dk->data[i] - s.d_mean->data[i];
gsl_blas_dgemv(CblasNoTrans, 1.0, s.Kk, s.ino_dk, 1.0, s.w);
// Update of the parameter covariance
// Pk = P_(k-1) - Kk Pddk Kk^T
// Equation 3.146
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0 , s.Kk, s.Pddk, 0.0, s.mat_temp_n_output);
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, s.mat_temp_n_output , s.Kk, 0.0, s.mat_temp_n_n);
gsl_matrix_sub(s.Pk, s.mat_temp_n_n);
// Update of the evolution noise
p.evolution_noise->updateEvolutionNoise(p, s);
}
/**
* @short Evaluation of the output from the sigma points
*
*/
void ukf_evaluate(ukf_param &p, ukf_state &s,
void(*g)(gsl_vector*, gsl_vector*, gsl_vector*),
gsl_vector * xk, gsl_vector * dk)
{
// ************************************************** //
// ************ Compute the sigma points ************ //
// ************************************************** //
// Equations 3.138
// w_k^j = w_(k-1) <-- this is here denoted s.w
// w_k^j = w_(k-1) + gamma Sk_j for 1 <= j <= n
// w_k^j = w_(k-1) - gamma Sk_j for n+1 <= j <= 2n
// Perform a cholesky decomposition of Pk
gsl_matrix_memcpy(s.mat_temp_n_n, s.Pk);
gsl_linalg_cholesky_decomp(s.mat_temp_n_n);
// Set all the elements of Lpi strictly above the diagonal to zero
for(int k = 0 ; k < p.n ; ++k)
for(int j = 0 ; j < k ; ++j)
gsl_matrix_set(s.mat_temp_n_n,j,k,0.0);
gsl_matrix_set_col(s.sigmaPoints,0, s.w);
for(int j = 1 ; j < p.n+1 ; ++j)
for(int i = 0 ; i < p.n ; ++i)
gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) + p.gamma * gsl_matrix_get(s.mat_temp_n_n,i,j-1));
for(int j = p.n+1 ; j < p.nbSamples ; ++j)
for(int i = 0 ; i < p.n ; ++i)
gsl_matrix_set(s.sigmaPoints, i, j, gsl_vector_get(s.w, i) - p.gamma * gsl_matrix_get(s.mat_temp_n_n,i,j-(p.n+1)));
/**************************************************/
/***** Compute the images of the sigma points *****/
/**************************************************/
// Compute the images of the sigma points
// and the mean of the dk
gsl_vector_set_zero(dk);
for(int j = 0 ; j < p.nbSamples ; j++)
{
// Equation 3.129
gsl_matrix_get_col(s.wk, s.sigmaPoints,j);
g(s.wk,xk, s.vec_temp_output);
gsl_matrix_set_col(s.dk, j, s.vec_temp_output);
// Equation 3.140
// Update the mean : y_mean = sum_[j=0..2n] w_j y_j
gsl_vector_scale(s.vec_temp_output, gsl_vector_get(s.wm,j));
gsl_vector_add(dk, s.vec_temp_output);
}
}
/**
* @short Returns a set of sigma points
*/
void getSigmaPoints(ukf_param &p, ukf_state &s, gsl_matrix * sigmaPoints)
{
//gsl_matrix * sigmaPoints = gsl_matrix_alloc(p.n, p.nbSamples);
// ************************************************** //
// ************ Compute the sigma points ************ //
// ************************************************** //
// Equations 3.138
// w_k^j = w_(k-1) <-- this is here denoted s.w
// w_k^j = w_(k-1) + gamma Sk_j for 1 <= j <= n
// w_k^j = w_(k-1) - gamma Sk_j for n+1 <= j <= 2n
// Perform a cholesky decomposition of Pk
gsl_matrix_memcpy(s.mat_temp_n_n, s.Pk);
gsl_linalg_cholesky_decomp(s.mat_temp_n_n);
// Set all the elements of Lpi strictly above the diagonal to zero
for(int k = 0 ; k < p.n ; ++k)
for(int j = 0 ; j < k ; ++j)
gsl_matrix_set(s.mat_temp_n_n,j,k,0.0);
gsl_matrix_set_col(sigmaPoints,0, s.w);
for(int j = 1 ; j < p.n+1 ; ++j)
for(int i = 0 ; i < p.n ; ++i)
gsl_matrix_set(sigmaPoints, i, j, gsl_vector_get(s.w, i) + p.gamma * gsl_matrix_get(s.mat_temp_n_n,i,j-1));
for(int j = p.n+1 ; j < p.nbSamples ; ++j)
for(int i = 0 ; i < p.n ; ++i)
gsl_matrix_set(sigmaPoints, i, j, gsl_vector_get(s.w, i) - p.gamma * gsl_matrix_get(s.mat_temp_n_n,i,j-(p.n+1)));
}
} // parameter
} // ukf
#endif // SL_PARAMETER_NDIM_H
| {
"alphanum_fraction": 0.5240070459,
"avg_line_length": 43.2407862408,
"ext": "h",
"hexsha": "464ef3d67ccc1dba6318fdbb4cf073b02cec2402",
"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/ukf_parameter_ndim.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/ukf_parameter_ndim.h",
"max_line_length": 162,
"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/ukf_parameter_ndim.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": 4406,
"size": 17599
} |
/*******************************************************************************
*
* This file is part of the General Hidden Markov Model Library,
* GHMM version __VERSION__, see http://ghmm.org
*
* Filename: ghmm/ghmm/matrixop.c
* Authors: Christoph Hafemeister
*
* Copyright (C) 2007-2008 Alexander Schliep
* Copyright (C) 2007-2008 Max-Planck-Institut fuer Molekulare Genetik,
* Berlin
*
* Contact: schliep@ghmm.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*******************************************************************************/
#ifdef HAVE_CONFIG_H
# include "../config.h"
#endif
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <string.h>
#include "matrixop.h"
#ifdef DO_WITH_GSL
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#endif
#ifdef DO_WITH_ATLAS
#include <clapack.h>
#endif
/*============================================================================*/
int ighmm_invert_det(double *sigmainv, double *det, int length, double *cov)
{
#define CUR_PROC "invert_det"
#ifdef DO_WITH_GSL
int i, j, s;
gsl_matrix *tmp;
gsl_matrix *inv;
tmp = gsl_matrix_alloc(length, length);
inv = gsl_matrix_alloc(length, length);
gsl_permutation *permutation = gsl_permutation_calloc(length);
for (i=0; i<length; ++i) {
for (j=0; j<length; ++j) {
#ifdef DO_WITH_GSL_DIAGONAL_HACK
if (i == j){
gsl_matrix_set(tmp, i, j, cov[i*length+j]);
}else{
gsl_matrix_set(tmp, i, j, 0.0);
}
#else
gsl_matrix_set(tmp, i, j, cov[i*length+j]);
#endif
}
}
gsl_linalg_LU_decomp(tmp, permutation, &s);
gsl_linalg_LU_invert(tmp, permutation, inv);
*det = gsl_linalg_LU_det(tmp, s);
gsl_matrix_free(tmp);
gsl_permutation_free(permutation);
for (i=0; i<length; ++i) {
for (j=0; j<length; ++j) {
sigmainv[i*length+j] = gsl_matrix_get(inv, i, j);
}
}
gsl_matrix_free(inv);
#elif defined HAVE_CLAPACK_DGETRF && HAVE_CLAPACK_DGETRI
char sign;
int info, i;
int *ipiv;
double det_tmp;
ipiv = malloc(length * sizeof *ipiv);
/* copy cov. matrix entries to result matrix, the rest is done in-place */
memcpy(sigmainv, cov, length * length * sizeof *cov);
/* perform in-place LU factorization of covariance matrix */
info = clapack_dgetrf(CblasRowMajor, length, length, sigmainv, length, ipiv);
/* determinant */
sign = 1;
for( i=0; i<length; ++i)
if( ipiv[i]!=i )
sign *= -1;
det_tmp = sigmainv[0];
for( i=length+1; i<(length*length); i+=length+1 )
det_tmp *= sigmainv[i];
*det = det_tmp * sign;
/* use the LU factorization to get inverse */
info = clapack_dgetri(CblasRowMajor, length, sigmainv, length, ipiv);
free(ipiv);
#else
*det = ighmm_determinant(cov, length);
ighmm_inverse(cov, length, *det, sigmainv);
#endif
return 0;
#undef CUR_PROC
}
/*============================================================================*/
/* calculate determinant of a square matrix */
double ighmm_determinant(double *cov, int n)
{
int j1, i, j, jm;
double * m;
double det;
if (n == 1)
return cov[0];
if (n == 2)
return cov[0] * cov[3] - cov[1] * cov[2];
/* matrix dimension is bigger than 2 - we have to do some work */
det = 0;
for (j1=0;j1<n;j1++) {
m = malloc((n-1)*(n-1)*sizeof(double));
for (i=1;i<n;i++) {
jm = 0;
for (j=0;j<n;j++) {
if (j == j1)
continue;
m[(i-1)*(n-1)+jm] = cov[i*n+j];
jm++;
}
}
det += pow(-1.0,1.0+j1+1.0) * cov[j1] * ighmm_determinant(m,n-1);
free(m);
}
return det;
}
/*============================================================================*/
/*
The inverse of a square matrix A with a non zero determinant is the adjoint
matrix divided by the determinant.
The adjoint matrix is the transpose of the cofactor matrix.
The cofactor matrix is the matrix of determinants of the minors Aij
multiplied by -1^(i+j).
The i,j'th minor of A is the matrix A without the i'th column or
the j'th row.
*/
int ighmm_inverse(double *cov, int n, double det, double *inv)
{
int i, j, ic, jc, actrow, actcol;
double * m;
if (n == 1) {
inv[0] = 1/cov[0];
return 0;
}
if (n == 2) {
inv[0] = cov[3] / (cov[0]*cov[3] - cov[1]*cov[2]);
inv[1] = - cov[1] / (cov[0]*cov[3] - cov[1]*cov[2]);
inv[2] = - cov[2] / (cov[0]*cov[3] - cov[1]*cov[2]);
inv[3] = cov[0] / (cov[0]*cov[3] - cov[1]*cov[2]);
return 0;
}
for (i=0;i<n;i++) {
for (j=0;j<n;j++) {
/* calculate minor i,j */
m = malloc((n-1)*(n-1)*sizeof(double));
actrow = 0;
for (ic=0;ic<n;ic++) {
if (ic == i)
continue;
actcol = 0;
for (jc=0;jc<n;jc++) {
if (jc == j)
continue;
m[actrow*(n-1)+actcol] = cov[ic*n+jc];
actcol++;
}
actrow++;
}
/* cofactor i,j is determinant of m times -1^(i+j) */
inv[j*n+i] = pow(-1.0,i+j+2.0) * ighmm_determinant(m,n-1) / det;
free(m);
}
}
return 0;
}
/*============================================================================*/
int ighmm_cholesky_decomposition (double *sigmacd, int dim, double *cov) {
#ifdef DO_WITH_GSL
int i, j;
gsl_matrix *tmp = gsl_matrix_alloc(dim, dim);
/* temp matrix */
for (i=0;i<dim;i++) {
for (j=0;j<dim;j++) {
gsl_matrix_set(tmp, i, j, cov[i*dim+j]);
}
}
/* cholesky decomposition of temp matrix */
gsl_linalg_cholesky_decomp(tmp);
/* copy to sigmacd and set upper triangular to 0 */
for (i=0;i<dim;i++) {
for (j=0;j<dim;j++) {
if (j>i)
sigmacd[i*dim+j] = 0;
else
sigmacd[i*dim+j] = gsl_matrix_get(tmp, i, j);
}
}
gsl_matrix_free(tmp);
#elif defined HAVE_CLAPACK_DPOTRF
int info;
/* copy cov. matrix entries to result matrix, the rest is done in-place */
memcpy(sigmacd, cov, dim * dim * sizeof *cov);
info = clapack_dpotrf(CblasRowMajor, CblasUpper, dim, sigmacd, dim);
#else
int row, j, k;
double sum;
/* copy cov to sigmacd */
for (row=0; row<dim; row++) {
for (j=0; j<dim; j++) {
sigmacd[row*dim+j] = cov[row*dim+j];
}
}
for (row=0; row<dim; row++) {
/* First compute U[row][row] */
sum = cov[row*dim+row];
for (j=0; j<(row-1); j++) sum -= sigmacd[j*dim+row]*sigmacd[j*dim+row];
if (sum > DBL_MIN) {
sigmacd[row*dim+row] = sqrt(sum);
/* Now find elements sigmacd[row*dim+k], k > row. */
for (k=(row+1); k<dim; k++) {
sum = cov[row*dim+k];
for (j=0; j<(row-1); j++)
sum -= sigmacd[j*dim+row]*sigmacd[j*dim+k];
sigmacd[row*dim+k] = sum/sigmacd[row*dim+row];
}
}
else { /* blast off the entire row. */
for (k=row; k<dim; k++) sigmacd[row*dim+k] = 0.0;
}
}
#endif
return 0;
}
| {
"alphanum_fraction": 0.5546229508,
"avg_line_length": 27.9304029304,
"ext": "c",
"hexsha": "88bcf39a9e84327d8a37df9054010932b61fdf49",
"lang": "C",
"max_forks_count": 25,
"max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z",
"max_forks_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "ruslankuzmin/julia",
"max_forks_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/matrixop.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "ruslankuzmin/julia",
"max_issues_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/matrixop.c",
"max_line_length": 80,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "2ad5bfb9c9684b1c800e96732a9e2f1e844b856f",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "ruslankuzmin/julia",
"max_stars_repo_path": "Trash/sandbox/hmm/ghmm-0.9-rc3/ghmm/matrixop.c",
"max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z",
"num_tokens": 2359,
"size": 7625
} |
/*
* This file is part of MXE.
* See index.html for further information.
*/
#include <stdio.h>
#include <gsl/gsl_sf_bessel.h>
int main(int argc, char *argv[])
{
double x, y;
(void)argc;
(void)argv;
x = 5.0;
y = gsl_sf_bessel_J0 (x);
printf ("J0(%g) = %.18e\n", x, y);
return 0;
}
| {
"alphanum_fraction": 0.5650793651,
"avg_line_length": 15,
"ext": "c",
"hexsha": "00ac9a8ba8cab8d904aca5668bf5b7e4e9493428",
"lang": "C",
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2018-11-24T12:40:31.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-04T00:24:38.000Z",
"max_forks_repo_head_hexsha": "3451656eb93f3f31ab24f388409aadef6bcafcaf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ChristianFrisson/mxe",
"max_forks_repo_path": "src/gsl-test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3451656eb93f3f31ab24f388409aadef6bcafcaf",
"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": "ChristianFrisson/mxe",
"max_issues_repo_path": "src/gsl-test.c",
"max_line_length": 42,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "3451656eb93f3f31ab24f388409aadef6bcafcaf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ChristianFrisson/mxe",
"max_stars_repo_path": "src/gsl-test.c",
"max_stars_repo_stars_event_max_datetime": "2019-10-08T13:21:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-12T08:03:47.000Z",
"num_tokens": 107,
"size": 315
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C header for structures representing a waveform as a list of modes in amplitude/phase form.
*
*/
#ifndef _STRUCT_H
#define _STRUCT_H
#define _XOPEN_SOURCE 500
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#if defined(__cplusplus)
extern "C" {
#elif 0
} /* so that editors will match preceding brace */
#endif
/***************************************************/
/*************** Type definitions ******************/
/* Type for real functions */
typedef double (*RealFunctionPtr)(double);
typedef double (*RealObjectFunctionPtr)(const void *, double);
/* Type for real functions that reference an object */
typedef struct tagObjectFunction
{
const void * object;
RealObjectFunctionPtr function;
} ObjectFunction ;
double ObjectFunctionCall(const ObjectFunction*,double);
/* Complex frequency series in amplitude and phase representation (for one mode) */
typedef struct tagCAmpPhaseFrequencySeries
{
gsl_vector* freq;
gsl_vector* amp_real; /* We authorize complex amplitudes - will be used for the LISA response */
gsl_vector* amp_imag; /* We authorize complex amplitudes - will be used for the LISA response */
gsl_vector* phase;
} CAmpPhaseFrequencySeries;
/* GSL splines for complex amplitude and phase representation (for one mode) */
typedef struct tagCAmpPhaseGSLSpline
{
gsl_vector* freq;
gsl_spline* spline_amp_real; /* We authorize complex amplitudes - will be used for the LISA response */
gsl_spline* spline_amp_imag; /* We authorize complex amplitudes - will be used for the LISA response */
gsl_spline* spline_phase;
gsl_interp_accel* accel_amp_real;
gsl_interp_accel* accel_amp_imag;
gsl_interp_accel* accel_phase;
} CAmpPhaseGSLSpline;
/* Splines in matrix form for complex amplitude and phase representation (for one mode) */
typedef struct tagCAmpPhaseSpline
{
gsl_matrix* spline_amp_real; /* We authorize complex amplitudes - will be used for the LISA response */
gsl_matrix* spline_amp_imag; /* We authorize complex amplitudes - will be used for the LISA response */
gsl_matrix* quadspline_phase;
} CAmpPhaseSpline;
/* Complex frequency series in real/imaginary part representation (for one mode, or their sum) */
typedef struct tagReImFrequencySeries
{
gsl_vector* freq;
gsl_vector* h_real;
gsl_vector* h_imag;
} ReImFrequencySeries;
/* Complex frequency series in real/imaginary part representation (for one mode, or their sum) */
/* NOTE: for now, exact duplicata of ReImFrequencySeries - differentiated for readability of the code */
typedef struct tagReImTimeSeries
{
gsl_vector* times;
gsl_vector* h_real;
gsl_vector* h_imag;
} ReImTimeSeries;
/* Complex frequency series in amplitude/phase representation (representing one mode) */
/* NOTE: for now, exact duplicata of ReImFrequencySeries - differentiated for readability of the code */
typedef struct tagAmpPhaseTimeSeries
{
gsl_vector* times;
gsl_vector* h_amp;
gsl_vector* h_phase;
} AmpPhaseTimeSeries;
/* Real time series */
/* NOTE: could change the h to something more general, like values - also used for TD 22 amplitude, for instance */
typedef struct tagRealTimeSeries
{
gsl_vector* times;
gsl_vector* h;
} RealTimeSeries;
/* List structure, for a list of modes, each in amplitude and phase form */
typedef struct tagListmodesCAmpPhaseFrequencySeries
{
CAmpPhaseFrequencySeries* freqseries; /* The frequencies series with amplitude and phase */
int l; /* Node mode l */
int m; /* Node submode m */
struct tagListmodesCAmpPhaseFrequencySeries* next; /* Next pointer */
} ListmodesCAmpPhaseFrequencySeries;
/* List structure, for a list of modes, each with interpolated splines in amplitude and phase form */
typedef struct tagListmodesCAmpPhaseSpline
{
CAmpPhaseSpline* splines; /* The frequencies series with amplitude and phase */
int l; /* Node mode l */
int m; /* Node submode m */
struct tagListmodesCAmpPhaseSpline* next; /* Next pointer */
} ListmodesCAmpPhaseSpline;
/**************************************************************/
/* Functions computing the max and min between two int */
int max (int a, int b);
int min (int a, int b);
/**************************************************************/
/************** GSL error handling and I/O ********************/
/* GSL error handler */
void Err_Handler(const char *reason, const char *file, int line, int gsl_errno);
/* Functions to read/write data from files */
int Read_Vector(const char dir[], const char fname[], gsl_vector *v);
int Read_Matrix(const char dir[], const char fname[], gsl_matrix *m);
int Read_Text_Vector(const char dir[], const char fname[], gsl_vector *v);
int Read_Text_Matrix(const char dir[], const char fname[], gsl_matrix *m);
int Write_Vector(const char dir[], const char fname[], gsl_vector *v);
int Write_Matrix(const char dir[], const char fname[], gsl_matrix *m);
int Write_Text_Vector(const char dir[], const char fname[], gsl_vector *v);
int Write_Text_Matrix(const char dir[], const char fname[], gsl_matrix *m);
/**********************************************************/
/**************** Internal functions **********************/
/* Functions for list manipulations */
ListmodesCAmpPhaseFrequencySeries* ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(
ListmodesCAmpPhaseFrequencySeries* appended, /* List structure to prepend to */
CAmpPhaseFrequencySeries* freqseries, /* data to contain */
int l, /*< major mode number */
int m /*< minor mode number */
);
ListmodesCAmpPhaseFrequencySeries* ListmodesCAmpPhaseFrequencySeries_GetMode(
ListmodesCAmpPhaseFrequencySeries* const list, /* List structure to get a particular mode from */
int l, /*< major mode number */
int m /*< minor mode number */
);
void ListmodesCAmpPhaseFrequencySeries_Destroy(
ListmodesCAmpPhaseFrequencySeries* list /* List structure to destroy; notice that the data is destroyed too */
);
ListmodesCAmpPhaseSpline* ListmodesCAmpPhaseSpline_AddModeNoCopy(
ListmodesCAmpPhaseSpline* appended, /* List structure to prepend to */
CAmpPhaseSpline* freqseries, /* data to contain */
int l, /*< major mode number */
int m /*< minor mode number */
);
ListmodesCAmpPhaseSpline* ListmodesCAmpPhaseSpline_GetMode(
ListmodesCAmpPhaseSpline* const list, /* List structure to get a particular mode from */
int l, /*< major mode number */
int m /*< minor mode number */
);
void ListmodesCAmpPhaseSpline_Destroy(
ListmodesCAmpPhaseSpline* list /* List structure to destroy; notice that the data is destroyed too */
);
/* Functions to initialize and clean up data structure */
void CAmpPhaseFrequencySeries_Init(
CAmpPhaseFrequencySeries** freqseries, /* double pointer for initialization */
const int n ); /* length of the frequency series */
void CAmpPhaseFrequencySeries_Cleanup(CAmpPhaseFrequencySeries* freqseries);
void CAmpPhaseSpline_Init(
CAmpPhaseSpline** splines, /* double pointer for initialization */
const int n ); /* length of the frequency series setting the splines */
void CAmpPhaseSpline_Cleanup(CAmpPhaseSpline* splines);
void CAmpPhaseGSLSpline_Init(
CAmpPhaseGSLSpline** splines, /* double pointer for initialization */
const int n ); /* length of the frequency series setting the splines */
void CAmpPhaseGSLSpline_Cleanup(CAmpPhaseGSLSpline* splines);
void ReImFrequencySeries_Init(
ReImFrequencySeries** freqseries, /* double pointer for initialization */
const int n ); /* length of the frequency series */
void ReImFrequencySeries_Cleanup(ReImFrequencySeries* freqseries);
void ReImTimeSeries_Init(
ReImTimeSeries** timeseries, /* double pointer for initialization */
const int n ); /* length of the time series */
void ReImTimeSeries_Cleanup(ReImTimeSeries* timeseries);
void AmpPhaseTimeSeries_Init(
AmpPhaseTimeSeries** timeseries, /* double pointer for initialization */
const int n ); /* length of the time series */
void AmpPhaseTimeSeries_Cleanup(AmpPhaseTimeSeries* timeseries);
void RealTimeSeries_Init(
RealTimeSeries** timeseries, /* double pointer for initialization */
const int n ); /* length of the time series */
void RealTimeSeries_Cleanup(RealTimeSeries* timeseries);
/***********************************************************************/
/**************** I/O functions for internal structures ****************/
/* Note: at the moment, requires external input for the number of lines in the data */
int Read_RealTimeSeries(RealTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary);
int Read_AmpPhaseTimeSeries(AmpPhaseTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary);
int Read_ReImTimeSeries(ReImTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary);
int Write_ReImFrequencySeries(const char dir[], const char file[], ReImFrequencySeries* freqseries, const int binary);
int Write_RealTimeSeries(const char dir[], const char file[], RealTimeSeries* timeseries, int binary);
int Write_AmpPhaseTimeSeries(const char dir[], const char file[], AmpPhaseTimeSeries* timeseries, int binary);
int Write_ReImTimeSeries(const char dir[], const char file[], ReImTimeSeries* timeseries, int binary);
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif /* _STRUCT_H */
| {
"alphanum_fraction": 0.6952622344,
"avg_line_length": 42.2139917695,
"ext": "h",
"hexsha": "fad94798f994e19e3695d54c956140b6ba9af4d3",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2020-07-20T02:56:30.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-09-20T14:19:13.000Z",
"max_forks_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "tools/struct.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "titodalcanton/flare",
"max_issues_repo_path": "tools/struct.h",
"max_line_length": 135,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "tools/struct.h",
"max_stars_repo_stars_event_max_datetime": "2020-07-20T02:56:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-26T15:21:13.000Z",
"num_tokens": 2296,
"size": 10258
} |
/*
STOCHASTIC LOTKA-VOLTERRA MODEL WITH MULTIDIMENSIONAL NICHE SPACES
by Tommaso Biancalani <tommasob@mit.edu>
Supporting Material to the paper:
"Framework for analyzing ecological trait-based models in multidimensional niche spaces" - Phys. Rev. E 91, 052107
ABSTRACT
We develop a theoretical framework for analyzing ecological models with a multidimensional niche space. Our approach relies on the fact that ecological niches are described by sequences of symbols, which allows us to include multiple phenotypic traits. Ecological drivers, such as competitive exclusion, are modeled by introducing the Hamming distance between two sequences. We show that a suitable transform diagonalizes the community interaction matrix of these models, making it possible to predict the conditions for niche differentiation and, close to the instability onset, the asymptotically long time population distributions of niches. We exemplify our method using the Lotka-Volterra equations with an exponential competition kernel.
INSTALL
The code requires the GSL (GNU Scientific Library). On linux, I simply compile it with:
$ gcc lotka-volterra.c -lgsl -lgslcblas -lm -Wall -o "lotka-volterra"
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include <time.h>
#include <sys/select.h>
#include <math.h>
// Headers for special functions
#include <gsl/gsl_math.h>
#include <gsl/gsl_sf_exp.h>
// Headers for Mersenne-Twister random generator
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
// Global variables
#define R_CONST 1. // Competition kernel length scale
#define SIGMA 2 // Competition kernel exponent
#define V_CONST 100. // System size of single compartment
#define T_SAMP 1. // Sampling time (outputs every T_SAMP)
#define TOT_TIME 100. // Evolve the system until t/V = TOT_TIME
// Sequence space definitions (sequences are called 'genomes')
typedef char GENOME_S;
typedef unsigned int GENOME_N;
#define C_CONST 5.52486 // Competition kernel normalization constant
#define L 3 // Phenotype length
#define NUM_GENOMES 54 // Total number of genome in the systems
const int DELTA[L] = {3,9,2}; // It specifies the sequence space
GENOME_S *genome_0 = "000";
GENOME_S genome_db[NUM_GENOMES][L+1];
#define A(k1,k2) (k1)+2*(k2) // reaction k1 in genome k2
FILE *out;
unsigned int *org; // org[I]: number of organisms with genome I
// GSL rn definitions (Mersenne-Twister)
const gsl_rng_type * rgT;
gsl_rng * rg;
double rn;
unsigned long int seed;
/**********************************************************/
GENOME_S *genome_num2str(GENOME_N I)
{
/*
Helper for converting genomes from numbers (GENOME_N) to string (GENOME_S).
Return converted genome in string format.
*/
int l;
GENOME_S *tbl = "0123456789abcdefghijklmnopqrstuvwxyz";
GENOME_S *out;
out = (GENOME_S *) malloc(sizeof(GENOME_S)*L);
memcpy(out, genome_0, sizeof(GENOME_S)*L);
int len = L-1;
for(l=0; 1; l++)
{
out[len--] = tbl[I % DELTA[l]];
if((I /= DELTA[l]) == 0)
break;
}
return out;
}
unsigned int Hamming_dist(GENOME_S *genome_I, GENOME_S *genome_J)
{
/*
Return Hamming distance between genomes I and J
*/
int l;
unsigned int ham_dist=L;
for(l=0; l<L; l++)
if(genome_I[l] - genome_J[l] == 0)
ham_dist--;
return ham_dist;
}
double G_IJ(GENOME_S *genome_I, GENOME_S *genome_J) {
/*
Return competition rate G on genome I due to genome J.
*/
double arg, ham_dist;
ham_dist = ((double)Hamming_dist(genome_I, genome_J)) / R_CONST;
arg = gsl_pow_int(ham_dist, SIGMA);
return gsl_sf_exp(-arg);
}
int gillespie_evolve()
{
/*
Print model dynamic on standard output. Dynamic is computed using Gillespie's algorithm. Return zero when time reaches TOT_TIME.
*/
GENOME_N I, J; // Genome indexes
int k; // Reaction index
long int step; // Time iteration index
int sample_step; // Sampled time iteration index
double tau, t; // Stochastic times
double *T_rates; // Transition rates
double T_sum, Tr2, T_tmp;
double rn; // rand number
// Allocate memory for transition rates
T_rates = (double *)malloc(sizeof(double) * NUM_GENOMES * 2);
// Main Loop
t=0.; step=0; sample_step=0;
while(t < TOT_TIME)
{
// Output as time reaches next sampled time
if(t > (double) (T_SAMP * sample_step))
{
for(I=0; I<NUM_GENOMES; I++)
fprintf(out, "%.3f ", org[I]/V_CONST);
fprintf(out, "\n");
sample_step++;
}
// Compute transiton rates
for (I=0; I<NUM_GENOMES; I++)
{
T_rates[A(0, I)] = org[I]; // reaction 0 = birth
T_rates[A(1, I)] = 0.; // reaction 1 = death
for(J=0; J<NUM_GENOMES; J++)
T_rates[A(1,I)] += G_IJ(genome_db[I], genome_db[J]) * org[J];
T_rates[A(1,I)] *= org[I] / (V_CONST * C_CONST);
}
// Compute total transition rate
T_sum = 0.;
for(I=0; I<NUM_GENOMES; I++)
T_sum += T_rates[A(0, I)] + T_rates[A(1, I)];
// Generate next reaction time (tau)
rn = gsl_rng_uniform_pos(rg);
tau = (1./T_sum) * log(1./rn);
// Update time
t += tau;
// Generate what reaction occurs and on which species
Tr2 = gsl_rng_uniform_pos(rg) * T_sum;
T_tmp = 0.;
for (I=0; I<NUM_GENOMES; I++)
{
for(k=0; k<2; k++)
{
T_tmp += T_rates[A(k,I)];
if(T_tmp >= Tr2) goto gotten; // this is a fine use of goto :-)
}
}
gotten:
// Execute reaction i on species k
switch(k) // Wich reaction?
{
// BIRTH
case 0:
org[I]++;
break;
// DEATH
case 1:
org[I]--;
break;
}
// update step
step = step+1;
} // main loop
return 0;
} // gillespe_evolve()
int main(int argc, char * argv[])
{
/*
Main function. Arguments are not processed. The model parameters are set by the constants and globals defined at the beginning of the code.
*/
GENOME_N I; // Genome index
// Initialize random generator
srand(time(NULL));
seed = (unsigned long int)rand();
rgT = gsl_rng_default; // default = Mersenne Twister
rg = gsl_rng_alloc (rgT);
gsl_rng_set (rg, seed);
// Initialize organisms, e.g. org[23] = number of organisms with genome 23
org = (unsigned int *)malloc(sizeof(unsigned int) * NUM_GENOMES);
// Initialize system around homogeneous state
for (I=0; I<NUM_GENOMES; I++)
org[I] = V_CONST;
// Set file descriptor for output
out = stdout;
// Initialize genome space
for(I=0; I<NUM_GENOMES; I++)
strcpy(genome_db[I], genome_num2str(I));
// Compute model dynamic
gillespie_evolve();
// Free descriptors and quit
fclose(out);
gsl_rng_free(rg);
return 0;
} // main()
| {
"alphanum_fraction": 0.6871212121,
"avg_line_length": 28.3261802575,
"ext": "c",
"hexsha": "6ee470e2e7166efa1295e30fd2ec4a0d715fb2f1",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-04-15T02:31:20.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-04-15T02:31:20.000Z",
"max_forks_repo_head_hexsha": "9d4947ddc837741f5316a0202b290081e7a6b8d6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Llewlyn/Stochastic-multidimensional-LV",
"max_forks_repo_path": "lotka-volterra.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9d4947ddc837741f5316a0202b290081e7a6b8d6",
"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": "Llewlyn/Stochastic-multidimensional-LV",
"max_issues_repo_path": "lotka-volterra.c",
"max_line_length": 744,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "9d4947ddc837741f5316a0202b290081e7a6b8d6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Llewlyn/Stochastic-multidimensional-LV",
"max_stars_repo_path": "lotka-volterra.c",
"max_stars_repo_stars_event_max_datetime": "2020-09-28T15:24:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-25T23:46:03.000Z",
"num_tokens": 1936,
"size": 6600
} |
//
// ePDF
//
#pragma once
#include "ePDF/ndistributions.h"
#include <yaml-cpp/yaml.h>
#include <complex>
#include <vector>
#include <memory>
#include <gsl/gsl_integration.h>
#include <functional>
namespace ePDF
{
/**
* @brief The "evol_params" structure contains the evolution
* parameters.
*/
struct evol_params
{
double x;
double Q;
int id;
std::shared_ptr<NDistributions> Ndist;
evol_params operator = (evol_params const& p)
{
x = p.x;
Q = p.Q;
id = p.id;
Ndist = p.Ndist;
return *this;
}
};
/**
* @brief The "xDistribution" class
*/
class xDistributions
{
public:
/**
* @brief The "xDistribution" constructor.
* @param config: the YAML:Node with the parameters
*/
xDistributions(YAML::Node const& config);
/**
* @brief The "xDistribution" destructor.
*/
~xDistributions();
/**
* @brief Function that returns the PDFs in x space.
* @param x: Bjorken x
* @param Q: the final scale
*/
std::vector<double> Evolve(double const& x, double const& Q);
/**
* @brief Interfaces to the integrand functions according to the
* path chosen to perform the inverse Mellin transform.
*/
std::vector<double> integrand(double const& y) const;
std::vector<double> talbot(double const& y) const;
std::vector<double> straight(double const& y) const;
/**
* @brief Integrators functions
*/
std::vector<double> trapezoid(double const& a, double const& b) const;
std::vector<double> gauss(double const& a, double const& b) const;
std::vector<double> gaussGSL(double const& a, double const& b);
/**
* @brief Function that returns the N-th (complex) moment of PDFs.
* @param N: moment
* @param Q: the final scale
*/
std::vector<std::complex<double>> Moments(std::complex<double> const& N, double const& Q) const;
/**
* @brief Function that sets the parameter structure externally
* @param p: the input structure
*/
void SetParameters(evol_params const& p) { _p = p; };
private:
std::string const _contour;
std::string const _integrator;
double const _eps;
evol_params _p;
gsl_integration_workspace *_w;
};
}
| {
"alphanum_fraction": 0.5829248366,
"avg_line_length": 24.9795918367,
"ext": "h",
"hexsha": "e6e209603cbd1fe76c06e99b093180a36d28368f",
"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": "e9ffa1fd977bb67e8212b84e5cea297b7604f9b8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gstagnit/ePDF",
"max_forks_repo_path": "inc/ePDF/xdistributions.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e9ffa1fd977bb67e8212b84e5cea297b7604f9b8",
"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": "gstagnit/ePDF",
"max_issues_repo_path": "inc/ePDF/xdistributions.h",
"max_line_length": 100,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "e9ffa1fd977bb67e8212b84e5cea297b7604f9b8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "vbertone/ePDF",
"max_stars_repo_path": "inc/ePDF/xdistributions.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-04T17:37:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-01T16:50:25.000Z",
"num_tokens": 618,
"size": 2448
} |
/* poly/zsolve.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* zsolve.c - finds the complex roots of = 0 */
#include <config.h>
#include <math.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_poly.h>
/* C-style matrix elements */
#define MAT(m,i,j,n) ((m)[(i)*(n) + (j)])
/* Fortran-style matrix elements */
#define FMAT(m,i,j,n) ((m)[((i)-1)*(n) + ((j)-1)])
#include "companion.c"
#include "balance.c"
#include "qr.c"
int
gsl_poly_complex_solve (const double *a, size_t n,
gsl_poly_complex_workspace * w,
gsl_complex_packed_ptr z)
{
int status;
double *m;
if (n == 0)
{
GSL_ERROR ("number of terms must be a positive integer", GSL_EINVAL);
}
if (n == 1)
{
GSL_ERROR ("cannot solve for only one term", GSL_EINVAL);
}
if (a[n - 1] == 0)
{
GSL_ERROR ("leading term of polynomial must be non-zero", GSL_EINVAL) ;
}
if (w->nc != n - 1)
{
GSL_ERROR ("size of workspace does not match polynomial", GSL_EINVAL);
}
m = w->matrix;
set_companion_matrix (a, n - 1, m);
balance_companion_matrix (m, n - 1);
status = qr_companion (m, n - 1, z);
if (status)
{
GSL_ERROR("root solving qr method failed to converge", GSL_EFAILED);
}
return GSL_SUCCESS;
}
| {
"alphanum_fraction": 0.6450704225,
"avg_line_length": 24.7674418605,
"ext": "c",
"hexsha": "aac231cc4c68d08557d66247665496b2022977d8",
"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/poly/zsolve.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/poly/zsolve.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/poly/zsolve.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": 594,
"size": 2130
} |
#define _GNU_SOURCE
#include <stdio.h>
#include <stdarg.h>
#include <math.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_odeiv2.h>
/* don't check ranges in Matrix operations and make Matrix call inline */
#define GSL_RANGE_CHECK_OFF
//#define HAVE_INLINE
#define FALSE 0
#define TRUE 1
#ifndef M_PI
#define M_PI 3.141592653589793238462643383280 /* pi */
#endif
#define LN2PI 1.837877066409345339
#define ODEdriver gsl_odeiv2_driver_alloc_y_new
#define rkf45 gsl_odeiv2_step_rkf45
#define rk8pd gsl_odeiv2_step_rk8pd
#define rkck gsl_odeiv2_step_rkck
#define rk2 gsl_odeiv2_step_rk2
#define EOL -1
#define max(A, B) ((A) > (B) ? (A) : (B))
#define min(A, B) ((A) < (B) ? (A) : (B))
#define MIN(A, B) ((A) < (B) ? (A) : (B))
#define MAX(A, B) ((A) > (B) ? (A) : (B))
#define V(x) (x)*(x)
#define FIT_TIME_POINT(x) (x->mode == FIT)
#define RECORD_TIME_POINT(x, u) (x->mode == OUTPUT || (x->mode == FIT && u == x->t[x->i]))
#define NEXT_TIME_POINT(x) if (x->mode == FIT) x->i++
#define RESET_TIME_POINT(x) x->i = 0
enum {FIT, OUTPUT};
enum {SUCCESS=0, FAIL=1, ERROR1=1, ERROR2, ERROR3, ERROR4, ERROR5, ERROR6,
ERROR7, ERROR8, ERROR9, ERROR10};
typedef uint boolean;
// for internal use
// type of parameter
enum {NOTUSED=0, DERIVED=21, FITTED=22, CONSTANT=23, AUXILLARY=24, INDIVIDUAL_CONSTANT=28};
// whether a fitted or auxillary parameter has a hyperparameter associated with it
enum {HYPER=26};
// prior of a fitted parameter that does not have a hyperparameters
enum {NOTAPPLICABLE=0, NORMAL=1, GAMMA=2, SICHI2=3, UNIFORM=4, PARETO=5,
TRUNCNORMAL=6, EXPONENTIAL=7, BINOMIAL=8, POISSON=9, INVGAMMA=10,
UNIFORM0=11, BETA=12, NORMALMEAN=13, CATEGORICAL=14, GEOMETRIC=15,
USERDEFINED=16, AUXILLARY_HYPER=27, CIRCULAR=29};
// number type of the parameter
enum {REAL=17, INTEGER=18, CATEGORY=19, INT = INTEGER};
// type of data
enum {NOT_AVAILABLE=0, ABOVE_DETECTION=1, BELOW_DETECTION=2, MEASURED=3};
// for use in model files
// prior or type of the declared parameter
enum {Normal =NORMAL,
Gamma =GAMMA,
Sichi2 =SICHI2,
Uniform =UNIFORM,
Circular =CIRCULAR,
Pareto =PARETO,
TruncNormal =TRUNCNORMAL,
Exponential =EXPONENTIAL,
Binomial =BINOMIAL,
Poisson =POISSON,
InvGamma =INVGAMMA,
Uniform0 =UNIFORM0,
Beta =BETA,
NormalMean =NORMALMEAN,
Categorical =CATEGORICAL,
Geometric =GEOMETRIC,
UserDefined =USERDEFINED,
HyperP =HYPER,
Constant =CONSTANT,
Auxillary =AUXILLARY,
Auxillary_Hyper =AUXILLARY_HYPER,
Derived =DERIVED,
Individual_Constant=INDIVIDUAL_CONSTANT};
enum {Nor =NORMAL,
Gam =GAMMA,
Sic =SICHI2,
Unif =UNIFORM,
Circ =CIRCULAR,
Pare =PARETO,
TNorm =TRUNCNORMAL,
Exp =EXPONENTIAL,
Bin =BINOMIAL,
Poi =POISSON,
IGam =INVGAMMA,
Unif0 =UNIFORM0,
Be =BETA,
NorM =NORMALMEAN,
Cat =CATEGORICAL,
Geom =GEOMETRIC,
UD =USERDEFINED,
Hyp =HYPER,
Cst =CONSTANT,
Aux =AUXILLARY,
Aux_Hyp =AUXILLARY_HYPER,
Der =DERIVED,
IndCst =INDIVIDUAL_CONSTANT};
// number type of the parameter
enum {Real=REAL, Integer=INTEGER, Category=CATEGORY, Int=INTEGER};
// type of data
enum {NA=0, Above_Detection=1, Below_Detection=2, Measured=3};
typedef struct {
uint mode, n, i;
double *t;
} TimePoints;
struct line {
int n;
double *x;
double *y;
double *m;
double *c;
};
struct data_individual {
int n;
int np;
uint **value;
double **Y;
double saturated;
};
struct data_treatment {
int nind;
int *usevar;
char levels[1000];
struct data_individual *Individual;
};
struct data {
int ntrt;
int nvar;
int maxnind;
int maxnp;
char filename[100];
struct data_treatment *Treatment;
};
typedef struct treatmentlist {
int n;
int *treatment;
} Treatments;
typedef struct hyperblock {
/* set in CreateBlock */
int use;
/* set in AddHyperToTreatment */
int nhypers_used;
int *hyper_used;
int **nhypers_with_treatment;
int ***hyper_with_treatment;
int nassociated_pars;
int *associated_par;
int *ntreatments_with_parameter;
int **treatment_with_parameter;
/* set in Bayes */
int hdistribution;
int pdistribution;
int *dependent_block;
} Hyperblock;
struct hyper {
int index;
int use;
int parno;
int hdist;
int number;
char name[100];
double location;
double scale;
double shape;
};
typedef struct allhypers {
int init;
int ntrt;
int *nind;
int *trtused;
int nhyper_parameters;
struct hyper *H;
int nblocks;
Hyperblock *block;
double *hyper; //used for initialisation of thread hyper values
double **hyper_store;
} Hyperparameters;
struct variable {
int index;
char name[100];
};
struct variables {
int variables;
double scaletime;
struct variable *W;
};
struct parameter {
int index;
int number;
int distribution;
int circular;
int type;
int hashyper;
int hyper_location_block_index;
int hyper_shape_block_index;
int hyper_scale_block_index;
int ncategories;
double *p; // used for categorical parameters
double location;
double scale;
double shape;
char name[100];
double (*(*link))(double);
};
struct blocks {
int nblocks;
int **pblock;
};
struct parameterset {
int pass;
int parameters; // maximum parameter index
int npar; // number of fitted parameters
int ninteger;
int *integer;
int nauxillary;
int *auxillary;
struct parameter *P;
struct blocks Blocks;
};
struct parameter_block {
int categorical;
int done;
int npar;
int *pblock;
int covfinal;
int covstart;
int inrange;
int storeno;
int error;
double accept; /*mcmc acceptances*/
double proposed; /*mcmc iterations*/
double covscale; /*covariance matrix scaling factor*/
// double **L; /*covariance matrix*/
gsl_matrix *L;
double **theta_store;
};
struct chain {
int done; /*if current individual is ready for next phase*/
int loop;
/* parameters for threads */
double logmaxL;
double logL;
double *logP;
double logpost;
double *theta; /*current parameter values*/
double minlogL;
double prop_logL;
double prop_logP;
double prop_logpost;
int storeno;
int laststoreno;
double accept; /*mcmc acceptances*/
double proposed; /*mcmc iterations*/
double **theta_store;
double *logLstore;
double *logpoststore;
double exchangeaccept; /*mcmc acceptances*/
double exchangeproposed; /*mcmc iterations*/
struct parameter_block *PB;
};
struct sim_individual {
int done;
int chains;
int *chainno;
double *temp;
struct chain *Chain;
struct parameterset Q;
};
typedef struct {
int n;
int m;
int **a;
} Matrix;
struct sim_treatment {
struct sim_individual *Individual;
};
struct thread {
double *hyper;
struct sim_treatment *Treatment;
gsl_rng *stream;
};
typedef struct simulation {
Hyperparameters HP;
int *trtused;
int **indused;
int ntp; // individual with most parameters
int nrp; // individual with most parameters
int rdp;
int sim;
int maxc;
int seed;
int thin;
int mcmc;
int popd;
int marg;
int maxnp;
int error;
int range;
int chains;
int notime;
int copyind;
int threads;
int verbose; /* 0: no output, 1: output chain 0+lowest exchangerate,
2: all chains*/
int derived;
int discard;
int samples;
int storeno;
int gsl_error;
int population;
int covsamples;
int growthcurves;
int parsperblock;
int phase1adjust;
int phase2adjust;
int mincovsamples;
int ignorewarning;
int usehypermeans;
int sample_parameters;
char expno[50];
char outexpno[50];
char *parsfile;
char *tempfile;
char logfile[1000];
char factors[1000];
double xrate;
double timeend;
double lowrate;
double highrate;
double minprior;
double initscale;
double covthresh;
double timestart;
double scalefactor;
double saturatedlogL;
double minexchangerate;
struct sim_individual Sample;
struct sim_treatment *Treatment;
struct variables V;
} Simulation;
extern char expno[];
extern int* integervector( int );
extern uint* uintegervector( int );
extern uint** uintegermatrix( int, int );
extern double* doublevector( int );
extern double** doublematrix( int, int );
extern double*** doublematrix3( int, int, int );
extern double**** doublematrix4( int, int, int, int );
extern char* charvector( int );
extern char** charmatrix( int, int );
extern double factln( int );
extern double gammln( double );
extern void binorm( double*, double, double, double, double, double );
extern long int lrint(double);
extern double pow10(double);
extern double round(double);
extern double rtnewt(void(*)(double, double*, double*, double*),
double, double, double, double*);
extern double rtbis( double (*)(double, double*), double, double,
double, int*, double*);
extern void *malloc(size_t);
extern void exit(int);
extern void free(void*);
extern void Error(char*);
extern void ReadParam( char*, void*, char* ) ;
extern uint binomialRNG(uint, double, const gsl_rng*);
extern void multinomialRNG(uint, const double*, size_t, unsigned int*, const gsl_rng*);
extern int poissonRNG(double, const gsl_rng*);
extern int uniform_intRNG(int, int, const gsl_rng*);
extern double normalRNG(double, double, const gsl_rng*);
extern double betaRNG(double, double, const gsl_rng*);
extern double chisqRNG(double, const gsl_rng*);
extern double scaleinvchisqRNG(double, double, const gsl_rng*);
extern double invgammaRNG(double, double, const gsl_rng*);
extern double gammaRNG(double, double, const gsl_rng*);
extern double uniformRNG(double, double, const gsl_rng*);
extern double paretoRNG(double, double, const gsl_rng*);
extern void dirichlet_multinomialRNG(uint, const double*, size_t, uint*, const gsl_rng*);
extern void dirichletRNG(const double*, size_t, double*, const gsl_rng*);
extern uint beta_binomialRNG(uint, double, double, const gsl_rng*);
extern uint negative_binomialRNG(double, double, const gsl_rng*);
extern uint beta_negative_binomialRNG(uint, double, double, const gsl_rng*);
/* Matrix *wishartRNG(int, int, Matrix*, Matrix*, const gsl_rng*); */
/* void MVNRNG(int, Matrix*, Matrix*, Matrix*, const gsl_rng*); */
extern double poissonCMF(const double, const double, int);
extern double gamma_scalePDF(const double, const double, const double);
extern double betaPDF(const double, const double, const double);
extern double exponentialPDF(const double, const double);
extern double poissonPMF(const double, const double);
extern double geometricPDF(const double, const double);
extern double trnormalPDF(const double, const double, const double);
extern double normalCDF(const double, const double, const double, int);
extern double normalPDF(const double, const double, const double);
extern double binomialPMF(const double, const double, const double);
extern double multinomialPMF(const unsigned int, const double*, const double*);
extern double uniformPDF(const double, const double, const double);
extern double logisticPDF(const double, const double, const double);
extern double betabinomialPMF(const double, const double, const double, const double);
//extern double MVNPDF(Matrix*, Matrix*, Matrix*, const double, int);
extern double von_mises_cdf ( double x, double a, double b );
extern double von_mises_cdf_inv ( double cdf, double a, double b );
extern Matrix *MatrixInit(Matrix*, int, int, int*);
extern Matrix *MatrixDestroy(Matrix*);
extern double identity(double);
extern double logit(double);
extern double invlogit(double);
int function(int, int, double*, double*, double*, TimePoints*);
int Model(const uint, const uint, const uint, double*, double**,
TimePoints*);
//int Model(int, int, int, double*, double**);
void Block(struct parameterset*, int, ...);
void Par(struct parameterset*, int, int, char*, int, ...);
void Create(Hyperparameters *H, int *h, int block, int par,
Matrix M, char *name, int type, double p1, double p2);
void Hyper(Hyperparameters *HP, int index, int number, char *name, int distribution,
double shape_or_loc, double scale);
void CreateHyperBlock(Hyperparameters *HP, int index);
void AddHyperToATreatment(Hyperparameters *HP, int index, int h, int pindex,
int treatment);
void AddHyperToTreatments(Hyperparameters *HP, int index, int h, int pindex, ...);
void HyperParameters(Treatments, Hyperparameters*);
void Var(struct variables*, int, char*);
void GlobalParameters(void);
void Variables(struct variables*);
void OutputModel(int, int, double*, double*);
void OutputData(int, int, double*, double*, double*, uint*);
void DerivedHyperParameters(int trt, double *p);
void DerivedParameters(int, int, int, double*, double**, TimePoints*);
void Parameters(int, int, double*, struct parameterset*);
void PredictData(int, int, double*, double*, double*, gsl_rng*);
void SimulateData(int, int, double*, double*, double*, double*, uint*, gsl_rng*);
void SaturatedModel(int, int, double*, double*, double*, uint*);
void Residual(int, int, double*, double*, double*, double*, uint*);
void Equations(double*, double*, int, double*, double*, int, double);
double timestep(void);
double logLikelihood(const uint, const uint, const double*,
const double*, const double*, const uint*);
double logLikelihoodI(const uint trt, const uint ind, const double *p,
double **V, double *Data, const uint *value,
const uint N);
void WAIC(int trt, int ind, double *lnL, double *V,
double *p, double *Data, uint *value);
//double logLikelihood(int, int, double*, double*, double*, int*);
double UserPDF(double);
void ScaleTime(struct variables*, double);
| {
"alphanum_fraction": 0.6835186351,
"avg_line_length": 29.0081135903,
"ext": "h",
"hexsha": "9e2538924837c4f6a2953ba18679ed23ce68dee0",
"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": "24418e397cca4ffa9b17d1d17b1ff59f3f49c87c",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "nicksavill/bayesian-dynamical-model-inference",
"max_forks_repo_path": "model.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "24418e397cca4ffa9b17d1d17b1ff59f3f49c87c",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "nicksavill/bayesian-dynamical-model-inference",
"max_issues_repo_path": "model.h",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "24418e397cca4ffa9b17d1d17b1ff59f3f49c87c",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "nicksavill/bayesian-dynamical-model-inference",
"max_stars_repo_path": "model.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3945,
"size": 14301
} |
static char help[] =
"1D Stokes problem with DMDA and SNES. Option prefix -wel_.\n\n";
// show solution (staggered):
// ./well -snes_monitor -snes_converged_reason -da_refine 7 -snes_monitor_solution draw -draw_pause 1
// try:
// -ksp_type preonly -pc_type svd [default]
// -ksp_type minres -pc_type none -ksp_converged_reason
// -ksp_type gmres -pc_type none -ksp_converged_reason
// and fieldsplit below
// Jacobian is correct and symmetric:
// ./well -snes_monitor -da_refine 3 -snes_type test
// ./well -snes_monitor -da_refine 3 -mat_is_symmetric
// generate matrix in matlab
// ./well -snes_converged_reason -da_refine 1 -mat_view ascii:foo.m:ascii_matlab
// then:
// >> M = [whos to get name]
// >> A = M(1:2:end,1:2:end); BT = M(1:2:end,2:2:end); B = M(2:2:end,1:2:end); C = M(2:2:end,2:2:end); T = [A BT; B C]
/* Schur-complement preconditioning:
./well -snes_converged_reason -snes_monitor -da_refine 7 -ksp_type fgmres -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type lower -fieldsplit_pressure_pc_type none -ksp_converged_reason
* see snes example ex70.c
* note these -ksp_type also work: gmres, cgs, richardson
* above is same as -fieldsplit_velocity_pc_type ilu
with minres need positive definite preconditioner so use -pc_fieldsplit_schur_fact_type diag (see http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/PC/PCFieldSplitSetSchurFactType.html):
./well -snes_converged_reason -snes_monitor -da_refine 7 -ksp_type minres -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type diag -fieldsplit_pressure_pc_type none -ksp_converged_reason
quote from http://www.mcs.anl.gov/petsc/petsc-current/docs/manualpages/PC/PCFieldSplitSetSchurFactType.html:
If applied exactly, FULL factorization is a direct solver. The preconditioned
operator with LOWER or UPPER has all eigenvalues equal to 1 and minimal polynomial
of degree 2, so KSPGMRES converges in 2 iterations. If the iteration count is very
low, consider using KSPFGMRES or KSPGCR which can use one less preconditioner
application in this case. Note that the preconditioned operator may be highly
non-normal, so such fast convergence may not be observed in practice. With DIAG,
the preconditioned operator has three distinct nonzero eigenvalues and minimal
polynomial of degree at most 4, so KSPGMRES converges in at most 4 iterations.
* indeed we see FULL converge in 1 iterations ... it IS a direct solver like SVD
* and LOWER/UPPER + GMRES give convergence in 2 iterations as advertised
* Murphy, Golub, Wathen (2000) explains final comment re DIAG and gmres
* in practice DIAG + GMRES
schur as direct solver:
./well -snes_converged_reason -snes_monitor -da_refine 7 -ksp_type preonly -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type full -fieldsplit_pressure_pc_type none -ksp_converged_reason
view all matrices (both interlaced and blocks) as dense with fieldsplit:
./well -snes_converged_reason -snes_monitor -da_refine 1 -ksp_type preonly -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type full -fieldsplit_pressure_pc_type none -mat_view ::ascii_dense
put diagonal blocks only in matlab files foov.m, foop.m (off-diagonal: how?)
./well -snes_converged_reason -snes_monitor -da_refine 1 -ksp_type preonly -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type full -fieldsplit_pressure_pc_type none -fieldsplit_velocity_mat_view :foov.m:ascii_matlab -fieldsplit_pressure_mat_view :foop.m:ascii_matlab
40 second run (linux-c-opt) on 8 million grid points:
timer ./well -snes_converged_reason -snes_monitor -da_refine 22 -ksp_type gmres -pc_type fieldsplit -pc_fieldsplit_type schur -pc_fieldsplit_schur_fact_type diag -fieldsplit_pressure_pc_type none -ksp_converged_reason -fieldsplit_velocity_ksp_type cg -fieldsplit_velocity_pc_type icc
* also works with -ksp_type minres
* also in parallel (no speedup) if -fieldsplit_velocity_pc_type bjacobi -fieldsplit_velocity_sub_pc_type icc
*/
#include <petsc.h>
#include <time.h>
typedef enum {STAGGERED, REGULAR} SchemeType;
static const char *SchemeTypes[] = {"staggered","regular",
"SchemeType", "", NULL};
typedef struct {
double L, // length (height) of well (m)
rho, // density of water (kg m-3)
g, // acceleration of gravity (m s-2)
mu; // dynamic viscosity of water (Pa s)
SchemeType scheme;
} AppCtx;
typedef struct {
double u, p;
} Field;
PetscErrorCode ExactSolution(DMDALocalInfo *info, Vec X, AppCtx *user) {
PetscErrorCode ierr;
double h, x;
Field *aX;
int i;
h = user->L / (info->mx-1);
ierr = DMDAVecGetArray(info->da,X,&aX); CHKERRQ(ierr);
for (i=info->xs; i<info->xs+info->xm; i++) {
aX[i].u = 0.0;
if (user->scheme == STAGGERED)
x = h * (i + 0.5);
else
x = h * i;
if (i < info->mx - 1)
aX[i].p = user->rho * user->g * (user->L - x);
else
aX[i].p = 0.0;
}
ierr = DMDAVecRestoreArray(info->da,X,&aX); CHKERRQ(ierr);
return 0;
}
// the staggered version of residual evaluation F(X)
// grid has p at staggered locations "O" where incompressibility u_x=0 is enforced
// x_i-1 O x_i O x_i+1 O
// u_i-1 u_i u_i+1
// p_i-1 p_i p_i+1
PetscErrorCode FormFunctionStaggeredLocal(DMDALocalInfo *info, Field *X,
Field *F, AppCtx *user) {
const double h = user->L / (info->mx-1),
h2 = h * h;
int i;
for (i=info->xs; i<info->xs+info->xm; i++) {
if (i == 0) { // bottom of well
F[i].u = X[i].u; // u(0) = 0
F[i].p = - (X[i+1].u - 0.0) / h; // -u_x(0+1/2) = 0
} else if (i == 1) {
F[i].u = - user->mu * (X[i+1].u - 2 * X[i].u + 0.0) / h2 // -mu u_xx(x1) + p_x(x1) = - rho g
+ (X[i].p - X[i-1].p) / h
+ user->rho * user->g;
F[i].p = - (X[i+1].u - X[i].u) / h; // - u_x(x1+1/2) = 0
// generic cases: - mu u_xx(xi) + p_x(xi) = - rho g AND - u_x(xi+1/2) = 0
} else if (i > 1 && i < info->mx - 1) {
F[i].u = - user->mu * (X[i+1].u - 2 * X[i].u + X[i-1].u) / h2
+ (X[i].p - X[i-1].p) / h
+ user->rho * user->g;
F[i].p = - (X[i+1].u - X[i].u) / h;
} else if (i == info->mx - 1) { // top of well
F[i].u = - user->mu * (- 2 * X[i].u + 2 * X[i-1].u) / h2 // -mu u_xx(xm-1) + p_x(xm-1) = - rho g
+ (- 2 * X[i-1].p) / h + user->rho * user->g; // and u_x(xm-1) = 0 and p(xm-1) = 0
F[i].u /= 2; // for symmetry
F[i].p = X[i].p; // no actual d.o.f. here
} else {
SETERRQ(PETSC_COMM_WORLD,1,"no way to get here");
}
}
return 0;
}
PetscErrorCode FormFunctionRegularLocal(DMDALocalInfo *info, Field *X,
Field *F, AppCtx *user) {
const double h = user->L / (info->mx-1),
h2 = h * h;
int i;
for (i=info->xs; i<info->xs+info->xm; i++) {
if (i == 0) { // bottom of well
F[i].u = X[i].u; // u(0) = 0
F[i].p = - (X[i+1].u - 0.0) / (2 * h); // -u_x(0+1/2) = 0 (and / 2 for symmetry)
} else if (i == 1) {
F[i].u = - user->mu * (X[i+1].u - 2 * X[i].u + 0.0) / h2 // -mu u_xx(x1) + p_x(x1) = - rho g
+ (X[i+1].p - X[i-1].p) / (2 * h)
+ user->rho * user->g;
F[i].p = - (X[i+1].u - 0.0) / (2 * h); // - u_x(x1) = 0
// generic cases: - mu u_xx(xi) + p_x(xi) = - rho g AND - u_x(xi) = 0
//STARTREGFUNC
} else if (i > 1 && i < info->mx - 2) {
F[i].u = - user->mu * (X[i+1].u - 2 * X[i].u + X[i-1].u) / h2
+ (X[i+1].p - X[i-1].p) / (2 * h)
+ user->rho * user->g;
F[i].p = - (X[i+1].u - X[i-1].u) / (2 * h);
//ENDREGFUNC
} else if (i == info->mx - 2) {
F[i].u = - user->mu * (X[i+1].u - 2 * X[i].u + X[i-1].u) / h2 // -mu u_xx(xm-2) + p_x(xm-2) = - rho g
+ (0.0 - X[i-1].p) / (2 * h)
+ user->rho * user->g;
F[i].p = - (X[i+1].u - X[i-1].u) / (2 * h); // - u_x(xm-2) = 0
} else if (i == info->mx - 1) { // top of well
F[i].u = - user->mu * (- 2 * X[i].u + 2 * X[i-1].u) / h2 // -mu u_xx(xm-1) + p_x(xm-1) = - rho g
+ (- X[i-1].p) / h + user->rho * user->g; // and u_x(xm-1) = 0 and p(xm-1) = 0
F[i].u /= 2; // for symmetry
F[i].p = X[i].p; // p(xm-1) = 0
} else {
SETERRQ(PETSC_COMM_WORLD,1,"no way to get here");
}
}
return 0;
}
PetscErrorCode FormJacobianStaggeredLocal(DMDALocalInfo *info, double *X,
Mat J, Mat P, AppCtx *user) {
PetscErrorCode ierr;
MatStencil col[5],row;
double v[5];
const double h = user->L / (info->mx-1),
h2 = h * h;
int i;
for (i=info->xs; i<info->xs+info->xm; i++) {
row.i = i;
if (i == 0) {
row.c = 0; col[0].i = i; col[0].c = 0; v[0] = 1.0;
ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);
row.c = 1; col[0].i = i+1; col[0].c = 0; v[0] = - 1.0 / h;
ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);
} else if (i == 1) {
row.c = 0;
col[0].c = 0; col[0].i = i; v[0] = 2.0 * user->mu / h2;
col[1].c = 0; col[1].i = i+1; v[1] = - user->mu / h2;
col[2].c = 1; col[2].i = i; v[2] = 1.0 / h;
col[3].c = 1; col[3].i = i-1; v[3] = - 1.0 / h;
ierr = MatSetValuesStencil(P,1,&row,4,col,v,INSERT_VALUES); CHKERRQ(ierr);
row.c = 1;
col[0].c = 0; col[0].i = i; v[0] = 1.0 / h;
col[1].c = 0; col[1].i = i+1; v[1] = - 1.0 / h;
ierr = MatSetValuesStencil(P,1,&row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);
} else if (i > 1 && i < info->mx - 1) {
row.c = 0;
col[0].c = 0; col[0].i = i; v[0] = 2.0 * user->mu / h2;
col[1].c = 0; col[1].i = i-1; v[1] = - user->mu / h2;
col[2].c = 0; col[2].i = i+1; v[2] = - user->mu / h2;
col[3].c = 1; col[3].i = i; v[3] = 1.0 / h;
col[4].c = 1; col[4].i = i-1; v[4] = - 1.0 / h;
ierr = MatSetValuesStencil(P,1,&row,5,col,v,INSERT_VALUES); CHKERRQ(ierr);
row.c = 1;
col[0].c = 0; col[0].i = i; v[0] = 1.0 / h;
col[1].c = 0; col[1].i = i+1; v[1] = - 1.0 / h;
ierr = MatSetValuesStencil(P,1,&row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);
} else if (i == info->mx - 1) {
row.c = 0;
col[0].c = 0; col[0].i = i; v[0] = user->mu / h2;
col[1].c = 0; col[1].i = i-1; v[1] = - user->mu / h2;
col[2].c = 1; col[2].i = i-1; v[2] = - 1.0 / h;
ierr = MatSetValuesStencil(P,1,&row,3,col,v,INSERT_VALUES); CHKERRQ(ierr);
row.c = 1;
col[0].c = 1; col[0].i = i; v[0] = 1.0;
ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);
} else {
SETERRQ(PETSC_COMM_WORLD,1,"no way to get here");
}
}
ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
if (J != P) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
PetscErrorCode FormJacobianRegularLocal(DMDALocalInfo *info, double *X,
Mat J, Mat P, AppCtx *user) {
PetscErrorCode ierr;
MatStencil col[5],row;
double v[5];
const double h = user->L / (info->mx-1),
h2 = h * h;
int i;
for (i=info->xs; i<info->xs+info->xm; i++) {
row.i = i;
if (i == 0) {
row.c = 0; col[0].i = i; col[0].c = 0; v[0] = 1.0;
ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);
row.c = 1; col[0].i = i+1; col[0].c = 0; v[0] = - 1.0 / (2.0 * h);
ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);
} else if (i == 1) {
row.c = 0;
col[0].c = 0; col[0].i = i; v[0] = 2.0 * user->mu / h2;
col[1].c = 0; col[1].i = i+1; v[1] = - user->mu / h2;
col[2].c = 1; col[2].i = i+1; v[2] = 1.0 / (2.0 * h);
col[3].c = 1; col[3].i = i-1; v[3] = - 1.0 / (2.0 * h);
ierr = MatSetValuesStencil(P,1,&row,4,col,v,INSERT_VALUES); CHKERRQ(ierr);
row.c = 1;
col[0].c = 0; col[0].i = i+1; v[0] = - 1.0 / (2.0 * h);
ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);
//STARTREGMAT
} else if (i > 1 && i < info->mx - 2) {
row.c = 0;
col[0].c = 0; col[0].i = i; v[0] = 2.0 * user->mu / h2;
col[1].c = 0; col[1].i = i-1; v[1] = - user->mu / h2;
col[2].c = 0; col[2].i = i+1; v[2] = - user->mu / h2;
col[3].c = 1; col[3].i = i+1; v[3] = 1.0 / (2.0 * h);
col[4].c = 1; col[4].i = i-1; v[4] = - 1.0 / (2.0 * h);
ierr = MatSetValuesStencil(P,1,&row,5,col,v,INSERT_VALUES); CHKERRQ(ierr);
row.c = 1;
col[0].c = 0; col[0].i = i-1; v[0] = 1.0 / (2.0 * h);
col[1].c = 0; col[1].i = i+1; v[1] = - 1.0 / (2.0 * h);
ierr = MatSetValuesStencil(P,1,&row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);
//ENDREGMAT
} else if (i == info->mx - 2) {
row.c = 0;
col[0].c = 0; col[0].i = i; v[0] = 2.0 * user->mu / h2;
col[1].c = 0; col[1].i = i-1; v[1] = - user->mu / h2;
col[2].c = 0; col[2].i = i+1; v[2] = - user->mu / h2;
col[3].c = 1; col[3].i = i-1; v[3] = - 1.0 / (2.0 * h);
ierr = MatSetValuesStencil(P,1,&row,4,col,v,INSERT_VALUES); CHKERRQ(ierr);
row.c = 1;
col[0].c = 0; col[0].i = i-1; v[0] = 1.0 / (2.0 * h);
col[1].c = 0; col[1].i = i+1; v[1] = - 1.0 / (2.0 * h);
ierr = MatSetValuesStencil(P,1,&row,2,col,v,INSERT_VALUES); CHKERRQ(ierr);
} else if (i == info->mx - 1) {
row.c = 0;
col[0].c = 0; col[0].i = i; v[0] = user->mu / h2;
col[1].c = 0; col[1].i = i-1; v[1] = - user->mu / h2;
col[2].c = 1; col[2].i = i-1; v[2] = - 1.0 / (2.0 * h);
ierr = MatSetValuesStencil(P,1,&row,3,col,v,INSERT_VALUES); CHKERRQ(ierr);
row.c = 1;
col[0].c = 1; col[0].i = i; v[0] = 1.0;
ierr = MatSetValuesStencil(P,1,&row,1,col,v,INSERT_VALUES); CHKERRQ(ierr);
} else {
SETERRQ(PETSC_COMM_WORLD,1,"no way to get here");
}
}
ierr = MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
if (J != P) {
ierr = MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
}
return 0;
}
int main(int argc,char **args) {
PetscErrorCode ierr;
DM da;
SNES snes;
KSP ksp;
PC pc;
AppCtx user;
Vec X, Xexact;
PetscBool randominit = PETSC_FALSE, shorterrors = PETSC_FALSE;
double uerrnorm, perrnorm, pnorm, setol = 1.0e-8;
DMDALocalInfo info;
PetscInitialize(&argc,&args,NULL,help);
user.rho = 1000.0;
user.g = 9.81;
user.L = 10.0;
user.mu = 1.0; // Pa s; = 1.0 for corn syrup; = 10^-3 for liquid water
user.scheme = STAGGERED;
ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"well_","options for well",""); CHKERRQ(ierr);
ierr = PetscOptionsEnum("-scheme","finite difference scheme type",
"well.c",SchemeTypes,
(PetscEnum)user.scheme,(PetscEnum*)&user.scheme,NULL); CHKERRQ(ierr);
ierr = PetscOptionsBool("-randominit","initialize u,p with random",
"well.c",randominit,&randominit,NULL);CHKERRQ(ierr);
ierr = PetscOptionsBool("-shorterrors","abbreviated error output (e.g. for regression testing)",
"well.c",shorterrors,&shorterrors,NULL);CHKERRQ(ierr);
ierr = PetscOptionsEnd(); CHKERRQ(ierr);
ierr = DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,3,2,1,NULL,&da); CHKERRQ(ierr);
ierr = DMSetFromOptions(da); CHKERRQ(ierr);
ierr = DMSetUp(da); CHKERRQ(ierr);
ierr = DMSetApplicationContext(da,&user); CHKERRQ(ierr);
ierr = DMDAGetLocalInfo(da,&info); CHKERRQ(ierr);
ierr = DMDASetUniformCoordinates(da,0.0,user.L,0.0,1.0,0.0,1.0); CHKERRQ(ierr);
ierr = DMDASetCoordinateName(da,0,"x"); CHKERRQ(ierr);
ierr = DMDASetFieldName(da,0,"velocity"); CHKERRQ(ierr);
ierr = DMDASetFieldName(da,1,"pressure"); CHKERRQ(ierr);
ierr = DMCreateGlobalVector(da,&X); CHKERRQ(ierr);
ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);
ierr = SNESSetDM(snes,da); CHKERRQ(ierr);
if (user.scheme == STAGGERED) {
ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,
(DMDASNESFunction)FormFunctionStaggeredLocal,&user); CHKERRQ(ierr);
ierr = DMDASNESSetJacobianLocal(da,
(DMDASNESJacobian)FormJacobianStaggeredLocal,&user); CHKERRQ(ierr);
} else if (user.scheme == REGULAR) {
ierr = DMDASNESSetFunctionLocal(da,INSERT_VALUES,
(DMDASNESFunction)FormFunctionRegularLocal,&user); CHKERRQ(ierr);
ierr = DMDASNESSetJacobianLocal(da,
(DMDASNESJacobian)FormJacobianRegularLocal,&user); CHKERRQ(ierr);
} else {
SETERRQ(PETSC_COMM_WORLD,1,"no way to get here");
}
// set defaults to -ksp_type preonly -pc_type svd ... which does not scale or parallelize but is robust
ierr = SNESGetKSP(snes,&ksp); CHKERRQ(ierr);
ierr = KSPSetType(ksp,KSPPREONLY); CHKERRQ(ierr);
ierr = KSPGetPC(ksp,&pc); CHKERRQ(ierr);
ierr = PCSetType(pc,PCSVD); CHKERRQ(ierr);
ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);
if (randominit) {
PetscRandom rctx;
ierr = PetscRandomCreate(PETSC_COMM_WORLD,&rctx); CHKERRQ(ierr);
ierr = PetscRandomSetSeed(rctx,time(NULL)); CHKERRQ(ierr);
ierr = PetscRandomSeed(rctx); CHKERRQ(ierr);
ierr = VecSetRandom(X,rctx); CHKERRQ(ierr);
ierr = PetscRandomDestroy(&rctx); CHKERRQ(ierr);
} else {
ierr = VecSet(X,0.0); CHKERRQ(ierr);
}
//ierr = VecView(X,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
ierr = SNESSolve(snes,NULL,X); CHKERRQ(ierr);
ierr = VecDuplicate(X,&Xexact); CHKERRQ(ierr);
ierr = ExactSolution(&info,Xexact,&user); CHKERRQ(ierr);
//ierr = VecView(X,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
//ierr = VecView(Xexact,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
ierr = VecAXPY(X,-1.0,Xexact); CHKERRQ(ierr); // X <- X + (-1.0) Xexact
ierr = VecStrideNorm(X,0,NORM_INFINITY,&uerrnorm); CHKERRQ(ierr);
ierr = VecStrideNorm(X,1,NORM_INFINITY,&perrnorm); CHKERRQ(ierr);
ierr = VecStrideNorm(Xexact,1,NORM_INFINITY,&pnorm); CHKERRQ(ierr);
ierr = PetscPrintf(PETSC_COMM_WORLD,
"on %d point grid with h=%g and scheme = '%s':\n",
info.mx,user.L/(info.mx-1),SchemeTypes[user.scheme]); CHKERRQ(ierr);
if (shorterrors && uerrnorm < setol && perrnorm/pnorm < setol) {
ierr = PetscPrintf(PETSC_COMM_WORLD,
" |u-uexact|_inf < %.1e, |p-pexact|_inf / |pexact|_inf < %.1e\n",
setol,setol); CHKERRQ(ierr);
} else {
ierr = PetscPrintf(PETSC_COMM_WORLD,
" |u-uexact|_inf = %.3e, |p-pexact|_inf / |pexact|_inf = %.3e\n",
uerrnorm,perrnorm/pnorm); CHKERRQ(ierr);
}
VecDestroy(&X); VecDestroy(&Xexact);
SNESDestroy(&snes); DMDestroy(&da);
return PetscFinalize();
}
| {
"alphanum_fraction": 0.5346954327,
"avg_line_length": 49.058411215,
"ext": "c",
"hexsha": "ff7b21b1c4adbdf6f7e626290b33800ba744c8a1",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mapengfei-nwpu/p4pdes",
"max_forks_repo_path": "c/junk/ch13/well.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "mapengfei-nwpu/p4pdes",
"max_issues_repo_path": "c/junk/ch13/well.c",
"max_line_length": 292,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "706411c1e745d7f825f336dcab3a62852538eaa4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mapengfei-nwpu/p4pdes",
"max_stars_repo_path": "c/junk/ch13/well.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 7139,
"size": 20997
} |
/* movstat/qqracc.c
*
* Moving window QQR accumulator
*
* 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 qqracc_type_t;
typedef qqracc_type_t ringbuf_type_t;
#include "ringbuf.c"
typedef struct
{
qqracc_type_t *window; /* linear array for current window */
ringbuf *rbuf; /* ring buffer storing current window */
} qqracc_state_t;
static size_t
qqracc_size(const size_t n)
{
size_t size = 0;
size += sizeof(qqracc_state_t);
size += n * sizeof(qqracc_type_t);
size += ringbuf_size(n);
return size;
}
static int
qqracc_init(const size_t n, void * vstate)
{
qqracc_state_t * state = (qqracc_state_t *) vstate;
state->window = (qqracc_type_t *) ((unsigned char *) vstate + sizeof(qqracc_state_t));
state->rbuf = (ringbuf *) ((unsigned char *) state->window + n * sizeof(qqracc_type_t));
ringbuf_init(n, state->rbuf);
return GSL_SUCCESS;
}
static int
qqracc_insert(const qqracc_type_t x, void * vstate)
{
qqracc_state_t * state = (qqracc_state_t *) vstate;
/* add new element to ring buffer */
ringbuf_insert(x, state->rbuf);
return GSL_SUCCESS;
}
static int
qqracc_delete(void * vstate)
{
qqracc_state_t * state = (qqracc_state_t *) vstate;
if (!ringbuf_is_empty(state->rbuf))
ringbuf_pop_back(state->rbuf);
return GSL_SUCCESS;
}
/* FIXME XXX: this is inefficient - could be improved by maintaining a sorted ring buffer */
static int
qqracc_get(void * params, qqracc_type_t * result, const void * vstate)
{
const qqracc_state_t * state = (const qqracc_state_t *) vstate;
double q = *(double *) params;
size_t n = ringbuf_copy(state->window, state->rbuf);
double quant1, quant2;
gsl_sort(state->window, 1, n);
/* compute q-quantile and (1-q)-quantile */
quant1 = gsl_stats_quantile_from_sorted_data(state->window, 1, n, q);
quant2 = gsl_stats_quantile_from_sorted_data(state->window, 1, n, 1.0 - q);
/* compute q-quantile range */
*result = quant2 - quant1;
return GSL_SUCCESS;
}
static const gsl_movstat_accum qqr_accum_type =
{
qqracc_size,
qqracc_init,
qqracc_insert,
qqracc_delete,
qqracc_get
};
const gsl_movstat_accum *gsl_movstat_accum_qqr = &qqr_accum_type;
| {
"alphanum_fraction": 0.7215927485,
"avg_line_length": 25.9579831933,
"ext": "c",
"hexsha": "eb7cfcf9bc41f0aa17250c3eb243d3241bc1ced8",
"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/qqracc.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/qqracc.c",
"max_line_length": 92,
"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/qqracc.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": 877,
"size": 3089
} |
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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.
==============================================================================*/
// This is a set of different implementations for the basic matrix by matrix
// multiply function, commonly known as GEMM after the BLAS library's naming.
// Having a standard interface enables us to swap out implementations on
// different platforms, to make sure we're using the optimal version. They are
// implemented as C++ template functors, so they're easy to swap into all of the
// different kernels that use them.
#if !defined(EIGEN_USE_THREADS)
#error "EIGEN_USE_THREADS must be enabled by all .cc files including this."
#endif // EIGEN_USE_THREADS
#include <string.h>
#include <map>
#include <vector>
#include "tensorflow/core/common_runtime/threadpool_device.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_types.h"
// Apple provides an optimized BLAS library that is better than Eigen for their
// devices, so use that if possible.
#if defined(__APPLE__) && defined(USE_GEMM_FOR_CONV)
#include <Accelerate/Accelerate.h>
#define USE_CBLAS_GEMM
#endif // __APPLE__
// Older Raspberry Pi systems don't have NEON SIMD acceleration, so Eigen falls
// back to scalar code, but OpenBLAS has much faster support so prefer that.
#if defined(RASPBERRY_PI) && defined(USE_GEMM_FOR_CONV) && defined(USE_OPENBLAS)
#include <cblas.h>
#define USE_CBLAS_GEMM
#endif
// A readable but slow implementation of matrix multiplication, useful for
// debugging and understanding the algorithm. Use instead of FastGemmFunctor in
// the Im2ColConvFunctor template definition inside the op registration to
// enable. Assumes row-major ordering of the values in memory.
template <class T1, class T2, class T3>
class ReferenceGemmFunctor {
public:
void operator()(tensorflow::OpKernelContext* ctx, size_t m, size_t n,
size_t k, const T1* a, size_t lda, const T2* b, size_t ldb,
T3* c, size_t ldc) {
const size_t a_i_stride = lda;
const size_t a_l_stride = 1;
const size_t b_j_stride = 1;
const size_t b_l_stride = ldb;
const size_t c_i_stride = ldc;
const size_t c_j_stride = 1;
size_t i, j, l;
for (j = 0; j < n; j++) {
for (i = 0; i < m; i++) {
T3 total(0);
for (l = 0; l < k; l++) {
const size_t a_index = ((i * a_i_stride) + (l * a_l_stride));
const T1 a_value = a[a_index];
const size_t b_index = ((j * b_j_stride) + (l * b_l_stride));
const T2 b_value = b[b_index];
total += (a_value * b_value);
}
const size_t c_index = ((i * c_i_stride) + (j * c_j_stride));
c[c_index] = total;
}
}
}
};
// Uses the optimized EigenTensor library to implement the matrix multiplication
// required by the Im2ColConvFunctor class. We supply the two input and one
// output types so that the accumulator can potentially be higher-precision than
// the inputs, even though we don't currently take advantage of this.
template <class T1, class T2, class T3>
class FastGemmFunctor {
public:
void operator()(tensorflow::OpKernelContext* ctx, size_t m, size_t n,
size_t k, const T1* a, size_t lda, const T2* b, size_t ldb,
T3* c, size_t ldc) {
typename tensorflow::TTypes<const T1>::Matrix a_matrix(a, m, k);
typename tensorflow::TTypes<const T2>::Matrix b_matrix(b, k, n);
typename tensorflow::TTypes<T3>::Matrix c_matrix(c, m, n);
Eigen::array<Eigen::IndexPair<Eigen::DenseIndex>, 1> dim_pair;
dim_pair[0].first = 1;
dim_pair[0].second = 0;
c_matrix.device(ctx->eigen_device<Eigen::ThreadPoolDevice>()) =
a_matrix.contract(b_matrix, dim_pair);
}
};
// If we have a fast CBLAS library, use its implementation through a wrapper.
#if defined(USE_CBLAS_GEMM)
template <>
class FastGemmFunctor<float, float, float> {
public:
void operator()(tensorflow::OpKernelContext* ctx, size_t m, size_t n,
size_t k, const float* a, size_t lda, const float* b,
size_t ldb, float* c, size_t ldc) {
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0f, a,
lda, b, ldb, 0.0f, c, ldc);
}
};
#endif // USE_CBLAS_GEMM
| {
"alphanum_fraction": 0.688692797,
"avg_line_length": 40.9495798319,
"ext": "h",
"hexsha": "4b30c1f17fc8d6bb537316be1760ffae319cbf21",
"lang": "C",
"max_forks_count": 364,
"max_forks_repo_forks_event_max_datetime": "2022-03-27T12:58:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-01-22T02:11:16.000Z",
"max_forks_repo_head_hexsha": "7e8927e7af0c51ac20a63bd4eab6ff83df1a39ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "shrikunjsarda/tensorflow",
"max_forks_repo_path": "tensorflow/core/kernels/gemm_functors.h",
"max_issues_count": 133,
"max_issues_repo_head_hexsha": "7e8927e7af0c51ac20a63bd4eab6ff83df1a39ae",
"max_issues_repo_issues_event_max_datetime": "2019-10-15T11:39:26.000Z",
"max_issues_repo_issues_event_min_datetime": "2017-04-26T16:49:49.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "shrikunjsarda/tensorflow",
"max_issues_repo_path": "tensorflow/core/kernels/gemm_functors.h",
"max_line_length": 80,
"max_stars_count": 850,
"max_stars_repo_head_hexsha": "fb3ce0467766a8e91f1da0ad7ada7c24fde7a73a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "tianyapiaozi/tensorflow",
"max_stars_repo_path": "tensorflow/core/kernels/gemm_functors.h",
"max_stars_repo_stars_event_max_datetime": "2022-03-31T08:17:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-18T05:56:02.000Z",
"num_tokens": 1258,
"size": 4873
} |
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#include <tree_2k.h>
#include <tree_2k_utils.h>
#include "cl_params.h"
void tree_spatial_dims_alloc(Params params, double **center,
double **extent);
void tree_spatial_dims_free(double *center, double *extent);
void insert_points(tree_2k_t *tree, Params params);
int main(int argc, char *argv[]) {
tree_2k_err_t status;
double *center, *extent;
Params params;
initCL(¶ms);
parseCL(¶ms, &argc, &argv);
if (params.verbose)
dumpCL(stderr, "# ", ¶ms);
tree_spatial_dims_alloc(params, ¢er, &extent);
tree_2k_t * tree;
status = tree_2k_alloc(&tree, params.rank, center, extent,
params.nr_points, params.bucket_size);
if (status != TREE_2K_SUCCESS)
errx(EXIT_FAILURE, "can not allocate tree");
insert_points(tree, params);
status = tree_2k_fwrite(tree, stdout);
if (status != TREE_2K_SUCCESS)
errx(EXIT_FAILURE, "tree write failed");
tree_2k_free(&tree);
tree_spatial_dims_free(center, extent);
finalizeCL(¶ms);
return EXIT_SUCCESS;
}
void tree_spatial_dims_alloc(Params params, double **center,
double **extent) {
*center = (double *) malloc(params.rank*sizeof(double));
*extent = (double *) malloc(params.rank*sizeof(double));
if (*center == NULL || *extent == NULL)
errx(EXIT_FAILURE, "can not allocate center or extent");
for (int i = 0; i < params.rank; i++) {
(*center)[i] = 0.0;
(*extent)[i] = 1.0;
}
}
void tree_spatial_dims_free(double *center, double *extent) {
free(center);
free(extent);
}
void insert_points(tree_2k_t *tree, Params params) {
double *coords;
gsl_rng *rng;
gsl_rng_env_setup();
rng = gsl_rng_alloc(gsl_rng_default);
if ((coords = (double *) malloc(params.rank*sizeof(double))) == NULL)
errx(EXIT_FAILURE, "can not allocate coords");
for (int point_nr = 0; point_nr < params.nr_points; point_nr++) {
for (int i = 0; i < params.rank; i++)
coords[i] = 2.0*gsl_rng_uniform(rng) - 1.0;
tree_2k_err_t status = tree_2k_insert(tree, coords, NULL);
if (status != TREE_2K_SUCCESS)
errx(EXIT_FAILURE, "failed to insert point %d", point_nr);
}
gsl_rng_free(rng);
}
| {
"alphanum_fraction": 0.6315131305,
"avg_line_length": 32.8630136986,
"ext": "c",
"hexsha": "50a6617e0126b42d9c8e7de7cd7479de1a8a3b3e",
"lang": "C",
"max_forks_count": 59,
"max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z",
"max_forks_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "Gjacquenot/training-material",
"max_forks_repo_path": "C/Tree_2k/examples/visualization/visualization.c",
"max_issues_count": 56,
"max_issues_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "Gjacquenot/training-material",
"max_issues_repo_path": "C/Tree_2k/examples/visualization/visualization.c",
"max_line_length": 73,
"max_stars_count": 115,
"max_stars_repo_head_hexsha": "16b29962bf5683f97a1072d961dd9f31e7468b8d",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "Gjacquenot/training-material",
"max_stars_repo_path": "C/Tree_2k/examples/visualization/visualization.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z",
"num_tokens": 633,
"size": 2399
} |
#pragma once
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <tuple>
#include <type_traits>
#include <gsl/gsl>
#include "chainerx/array.h"
#include "chainerx/axes.h"
#include "chainerx/backend_util.h"
#include "chainerx/constant.h"
#include "chainerx/dtype.h"
#include "chainerx/indexer.h"
#include "chainerx/macro.h"
#include "chainerx/shape.h"
#include "chainerx/strides.h"
namespace chainerx {
namespace indexable_array_detail {
template <typename To, typename From>
using WithConstnessOf = dtype_detail::WithConstnessOf<To, From>;
static inline std::tuple<const uint8_t*, const uint8_t*> GetDataRange(const Array& a) {
std::tuple<int64_t, int64_t> range = chainerx::GetDataRange(a.shape(), a.strides(), a.GetItemSize());
int64_t lower = std::get<0>(range);
int64_t upper = std::get<1>(range);
const uint8_t* base = static_cast<const uint8_t*>(internal::GetRawOffsetData(a));
return std::tuple<const uint8_t*, const uint8_t*>{base + lower, base + upper};
}
} // namespace indexable_array_detail
template <typename T, int8_t kNdim = kDynamicNdim>
class IndexableArray {
public:
using ElementType = T;
private:
template <typename U>
using WithConstnessOfT = indexable_array_detail::WithConstnessOf<U, T>;
using VoidType = WithConstnessOfT<void>;
using DeviceStorageType = TypeToDeviceStorageType<T>;
public:
IndexableArray(VoidType* data, const Strides& strides) : data_{data} { std::copy(strides.begin(), strides.end(), strides_); }
IndexableArray(const Array& array, const Strides& strides) : IndexableArray{internal::GetRawOffsetData(array), strides} {
CHAINERX_ASSERT(TypeToDtype<T> == array.dtype());
#if CHAINERX_DEBUG
std::tie(first_, last_) = indexable_array_detail::GetDataRange(array);
#endif // CHAINERX_DEBUG
}
explicit IndexableArray(const Array& array) : IndexableArray{array, array.strides()} {}
CHAINERX_HOST_DEVICE int8_t ndim() const { return kNdim; }
CHAINERX_HOST_DEVICE const int64_t* strides() const { return strides_; }
CHAINERX_HOST_DEVICE VoidType* data() const { return data_; }
CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const int64_t* index) const {
auto data_ptr = static_cast<WithConstnessOfT<uint8_t>*>(data_);
for (int8_t dim = 0; dim < kNdim; ++dim) {
data_ptr += strides_[dim] * index[dim];
}
#if CHAINERX_DEBUG
CHAINERX_ASSERT(first_ == nullptr || first_ <= data_ptr);
CHAINERX_ASSERT(last_ == nullptr || data_ptr <= last_ - sizeof(T));
#endif // CHAINERX_DEBUG
return *static_cast<DeviceStorageType*>(static_cast<VoidType*>(data_ptr));
}
CHAINERX_HOST_DEVICE WithConstnessOfT<DeviceStorageType>& operator[](const IndexIterator<kNdim>& it) const {
return operator[](it.index());
}
// Permutes the axes.
//
// It is the caller's responsibility to ensure validity of permutation.
// If the permutation is invalid, the behavior is undefined.
IndexableArray<T, kNdim>& Permute(const Axes& axes) {
CHAINERX_ASSERT(axes.size() == static_cast<size_t>(kNdim));
int64_t c[kNdim]{};
std::copy(std::begin(strides_), std::end(strides_), c);
for (size_t i = 0; i < kNdim; ++i) {
strides_[i] = c[axes[i]];
}
return *this;
}
private:
WithConstnessOfT<void>* data_;
#if CHAINERX_DEBUG
const uint8_t* first_{nullptr};
const uint8_t* last_{nullptr};
#endif // CHAINERX_DEBUG
int64_t strides_[kNdim];
};
// Static 0-dimensional specialization.
template <typename T>
class IndexableArray<T, 0> {
public:
using ElementType = T;
private:
template <typename U>
using WithConstnessOfT = indexable_array_detail::WithConstnessOf<U, T>;
using VoidType = WithConstnessOfT<void>;
using DeviceStorageType = TypeToDeviceStorageType<T>;
public:
IndexableArray(VoidType* data, const Strides& strides) : data_{data} { CHAINERX_ASSERT(0 == strides.ndim()); }
IndexableArray(const Array& array, const Strides& strides) : IndexableArray{internal::GetRawOffsetData(array), strides} {
CHAINERX_ASSERT(TypeToDtype<T> == array.dtype());
}
explicit IndexableArray(const Array& array) : IndexableArray{array, array.strides()} {}
CHAINERX_HOST_DEVICE constexpr int8_t ndim() const { return 0; }
CHAINERX_HOST_DEVICE constexpr const int64_t* strides() const { return nullptr; }
CHAINERX_HOST_DEVICE VoidType* data() const { return data_; }
CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const int64_t* index) const {
CHAINERX_ASSERT(index == nullptr || index[0] == 0);
return *static_cast<WithConstnessOfT<DeviceStorageType>*>(data_);
}
CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const IndexIterator<0>& it) const { return operator[](it.index()); }
IndexableArray<T, 0>& Permute(const Axes& /*axes*/) {
// NOOP for 1-dimensional array.
return *this;
}
private:
WithConstnessOfT<void>* data_;
};
// Static 1-dimensional specialization.
template <typename T>
class IndexableArray<T, 1> {
public:
using ElementType = T;
private:
template <typename U>
using WithConstnessOfT = indexable_array_detail::WithConstnessOf<U, T>;
using VoidType = WithConstnessOfT<void>;
using DeviceStorageType = TypeToDeviceStorageType<T>;
public:
IndexableArray(VoidType* data, const Strides& strides) : data_{data}, stride_{strides[0]} { CHAINERX_ASSERT(1 == strides.ndim()); }
IndexableArray(const Array& array, const Strides& strides) : IndexableArray{internal::GetRawOffsetData(array), strides} {
CHAINERX_ASSERT(TypeToDtype<T> == array.dtype());
#if CHAINERX_DEBUG
std::tie(first_, last_) = indexable_array_detail::GetDataRange(array);
#endif // CHAINERX_DEBUG
}
explicit IndexableArray(const Array& array) : IndexableArray{array, array.strides()} {}
CHAINERX_HOST_DEVICE constexpr int8_t ndim() const { return 1; }
CHAINERX_HOST_DEVICE const int64_t* strides() const { return &stride_; }
CHAINERX_HOST_DEVICE VoidType* data() const { return data_; }
CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const int64_t* index) const {
auto data_ptr = reinterpret_cast<WithConstnessOfT<uint8_t>*>(data_) +
stride_ * index[0]; // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
#if CHAINERX_DEBUG
CHAINERX_ASSERT(first_ == nullptr || first_ <= data_ptr);
CHAINERX_ASSERT(last_ == nullptr || data_ptr <= last_ - sizeof(T));
#endif // CHAINERX_DEBUG
return *static_cast<DeviceStorageType*>(static_cast<VoidType*>(data_ptr));
}
CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const IndexIterator<1>& it) const { return operator[](it.index()); }
IndexableArray<T, 1>& Permute(const Axes& /*axes*/) {
// NOOP for 1-dimensional array.
return *this;
}
private:
WithConstnessOfT<void>* data_;
#if CHAINERX_DEBUG
const uint8_t* first_{nullptr};
const uint8_t* last_{nullptr};
#endif // CHAINERX_DEBUG
int64_t stride_{};
};
// Runtime determined dynamic dimension specialization.
template <typename T>
class IndexableArray<T, kDynamicNdim> {
public:
using ElementType = T;
private:
template <typename U>
using WithConstnessOfT = indexable_array_detail::WithConstnessOf<U, T>;
using VoidType = WithConstnessOfT<void>;
using DeviceStorageType = TypeToDeviceStorageType<T>;
public:
IndexableArray(WithConstnessOfT<void>* data, const Strides& strides) : data_{data}, ndim_{strides.ndim()} {
std::copy(strides.begin(), strides.end(), strides_);
}
IndexableArray(const Array& array, const Strides& strides) : IndexableArray{internal::GetRawOffsetData(array), strides} {
CHAINERX_ASSERT(TypeToDtype<T> == array.dtype());
#if CHAINERX_DEBUG
std::tie(first_, last_) = indexable_array_detail::GetDataRange(array);
#endif // CHAINERX_DEBUG
}
explicit IndexableArray(const Array& array) : IndexableArray{array, array.strides()} {}
CHAINERX_HOST_DEVICE int8_t ndim() const { return ndim_; }
CHAINERX_HOST_DEVICE const int64_t* strides() const { return strides_; }
CHAINERX_HOST_DEVICE VoidType* data() const { return data_; }
CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const int64_t* index) const {
auto data_ptr = static_cast<WithConstnessOfT<uint8_t>*>(data_);
for (int8_t dim = 0; dim < ndim_; ++dim) {
data_ptr += strides_[dim] * index[dim];
}
#if CHAINERX_DEBUG
CHAINERX_ASSERT(first_ == nullptr || first_ <= data_ptr);
CHAINERX_ASSERT(last_ == nullptr || data_ptr <= last_ - sizeof(T));
#endif // CHAINERX_DEBUG
return *static_cast<DeviceStorageType*>(static_cast<VoidType*>(data_ptr));
}
CHAINERX_HOST_DEVICE DeviceStorageType& operator[](const IndexIterator<kDynamicNdim>& it) const { return operator[](it.index()); }
// Permutes the axes.
//
// Given axes may be fewer than that held by the array.
// In that case, the axes in the array will be reduced.
//
// It is the caller's responsibility to ensure validity of permutation.
// If the permutation is invalid, the behavior is undefined.
IndexableArray<T, kDynamicNdim>& Permute(const Axes& axes) {
CHAINERX_ASSERT(axes.size() <= static_cast<size_t>(ndim_));
int64_t c[kMaxNdim]{};
std::copy(std::begin(strides_), std::end(strides_), c);
for (size_t i = 0; i < axes.size(); ++i) {
strides_[i] = c[axes[i]];
}
ndim_ = static_cast<int8_t>(axes.size());
return *this;
}
private:
WithConstnessOfT<void>* data_;
#if CHAINERX_DEBUG
const uint8_t* first_{nullptr};
const uint8_t* last_{nullptr};
#endif // CHAINERX_DEBUG
int64_t strides_[kMaxNdim];
int8_t ndim_;
};
} // namespace chainerx
| {
"alphanum_fraction": 0.6925940833,
"avg_line_length": 35.2411347518,
"ext": "h",
"hexsha": "0ae8d6d7a0ede574363436fda0101a69dffc14a1",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-05-28T22:43:34.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-05-28T22:43:34.000Z",
"max_forks_repo_head_hexsha": "8d776fcc1e848cb9d3800a6aab356eb91ae9d088",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nolfwin/chainer",
"max_forks_repo_path": "chainerx_cc/chainerx/indexable_array.h",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "8d776fcc1e848cb9d3800a6aab356eb91ae9d088",
"max_issues_repo_issues_event_max_datetime": "2018-06-26T08:16:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-26T08:16:09.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "nolfwin/chainer",
"max_issues_repo_path": "chainerx_cc/chainerx/indexable_array.h",
"max_line_length": 135,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "324a1bc1ea3edd63d225e4a87ed0a36af7fd712f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "hikjik/chainer",
"max_stars_repo_path": "chainerx_cc/chainerx/indexable_array.h",
"max_stars_repo_stars_event_max_datetime": "2019-02-14T09:18:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-02-14T09:18:32.000Z",
"num_tokens": 2591,
"size": 9938
} |
// Copyright 2021 atframework
// Created by owent on 2020-08-18
#pragma once
#include <gsl/select-gsl.h>
#include <config/atframe_utils_build_feature.h>
#include <config/compiler_features.h>
#include <design_pattern/nomovable.h>
#include <design_pattern/noncopyable.h>
#include <random/random_generator.h>
#include "atframe/atapp_conf.h"
namespace atapp {
struct LIBATAPP_MACRO_API_HEAD_ONLY etcd_discovery_action_t {
enum type {
EN_NAT_UNKNOWN = 0,
EN_NAT_PUT,
EN_NAT_DELETE,
};
};
class etcd_discovery_node {
public:
using on_destroy_fn_t = std::function<void(etcd_discovery_node &)>;
using ptr_t = std::shared_ptr<etcd_discovery_node>;
UTIL_DESIGN_PATTERN_NOCOPYABLE(etcd_discovery_node)
UTIL_DESIGN_PATTERN_NOMOVABLE(etcd_discovery_node)
public:
LIBATAPP_MACRO_API etcd_discovery_node();
LIBATAPP_MACRO_API ~etcd_discovery_node();
UTIL_FORCEINLINE const atapp::protocol::atapp_discovery &get_discovery_info() const { return node_info_; }
LIBATAPP_MACRO_API void copy_from(const atapp::protocol::atapp_discovery &input);
UTIL_FORCEINLINE const std::pair<uint64_t, uint64_t> &get_name_hash() const { return name_hash_; }
UTIL_FORCEINLINE void set_private_data_ptr(void *input) { private_data_ptr_ = input; }
UTIL_FORCEINLINE void *get_private_data_ptr() const { return private_data_ptr_; }
UTIL_FORCEINLINE void set_private_data_u64(uint64_t input) { private_data_u64_ = input; }
UTIL_FORCEINLINE uint64_t get_private_data_u64() const { return private_data_u64_; }
UTIL_FORCEINLINE void set_private_data_i64(int64_t input) { private_data_i64_ = input; }
UTIL_FORCEINLINE int64_t get_private_data_i64() const { return private_data_i64_; }
UTIL_FORCEINLINE void set_private_data_uptr(uintptr_t input) { private_data_uptr_ = input; }
UTIL_FORCEINLINE uintptr_t get_private_data_uptr() const { return private_data_uptr_; }
UTIL_FORCEINLINE void set_private_data_iptr(intptr_t input) { private_data_iptr_ = input; }
UTIL_FORCEINLINE intptr_t get_private_data_iptr() const { return private_data_iptr_; }
LIBATAPP_MACRO_API void set_on_destroy(on_destroy_fn_t fn);
LIBATAPP_MACRO_API const on_destroy_fn_t &get_on_destroy() const;
LIBATAPP_MACRO_API void reset_on_destroy();
LIBATAPP_MACRO_API const atapp::protocol::atapp_gateway &next_ingress_gateway() const;
LIBATAPP_MACRO_API int32_t get_ingress_size() const;
private:
atapp::protocol::atapp_discovery node_info_;
std::pair<uint64_t, uint64_t> name_hash_;
union {
void *private_data_ptr_;
uint64_t private_data_u64_;
int64_t private_data_i64_;
uintptr_t private_data_uptr_;
intptr_t private_data_iptr_;
};
on_destroy_fn_t on_destroy_fn_;
mutable int32_t ingress_index_;
mutable atapp::protocol::atapp_gateway ingress_for_listen_;
};
class etcd_discovery_set {
public:
using node_by_name_t = std::unordered_map<std::string, etcd_discovery_node::ptr_t>;
using node_by_id_t = std::unordered_map<uint64_t, etcd_discovery_node::ptr_t>;
using ptr_t = std::shared_ptr<etcd_discovery_set>;
struct node_hash_t {
enum { HASH_POINT_PER_INS = 80 };
etcd_discovery_node::ptr_t node;
std::pair<uint64_t, uint64_t> hash_code;
};
UTIL_DESIGN_PATTERN_NOCOPYABLE(etcd_discovery_set)
UTIL_DESIGN_PATTERN_NOMOVABLE(etcd_discovery_set)
public:
LIBATAPP_MACRO_API etcd_discovery_set();
LIBATAPP_MACRO_API ~etcd_discovery_set();
LIBATAPP_MACRO_API bool empty() const;
LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_id(uint64_t id) const;
LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_name(gsl::string_view name) const;
LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_consistent_hash(const void *buf, size_t bufsz) const;
LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_consistent_hash(uint64_t key) const;
LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_consistent_hash(int64_t key) const;
LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_consistent_hash(gsl::string_view key) const;
LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_random() const;
LIBATAPP_MACRO_API etcd_discovery_node::ptr_t get_node_by_round_robin() const;
LIBATAPP_MACRO_API const std::vector<etcd_discovery_node::ptr_t> &get_sorted_nodes() const;
LIBATAPP_MACRO_API std::vector<etcd_discovery_node::ptr_t>::const_iterator lower_bound_sorted_nodes(
uint64_t id, gsl::string_view name) const;
LIBATAPP_MACRO_API std::vector<etcd_discovery_node::ptr_t>::const_iterator upper_bound_sorted_nodes(
uint64_t id, gsl::string_view name) const;
LIBATAPP_MACRO_API void add_node(const etcd_discovery_node::ptr_t &node);
LIBATAPP_MACRO_API void remove_node(const etcd_discovery_node::ptr_t &node);
LIBATAPP_MACRO_API void remove_node(uint64_t id);
LIBATAPP_MACRO_API void remove_node(gsl::string_view name);
private:
void rebuild_cache() const;
void clear_cache() const;
private:
node_by_name_t node_by_name_;
node_by_id_t node_by_id_;
mutable std::vector<node_hash_t> hashing_cache_;
mutable std::vector<etcd_discovery_node::ptr_t> round_robin_cache_;
mutable util::random::xoshiro256_starstar random_generator_;
mutable size_t round_robin_index_;
};
} // namespace atapp
| {
"alphanum_fraction": 0.8069241012,
"avg_line_length": 39.2313432836,
"ext": "h",
"hexsha": "9b581491ce8dd2b20693a3291f4790b75a46697a",
"lang": "C",
"max_forks_count": 6,
"max_forks_repo_forks_event_max_datetime": "2020-04-19T10:06:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-08-04T06:14:12.000Z",
"max_forks_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "atframework/libatapp",
"max_forks_repo_path": "include/atframe/etcdcli/etcd_discovery.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80",
"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": "atframework/libatapp",
"max_issues_repo_path": "include/atframe/etcdcli/etcd_discovery.h",
"max_line_length": 113,
"max_stars_count": 16,
"max_stars_repo_head_hexsha": "54aae9e0972eb94c33a7c109bdd099ff3a89ee80",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "atframework/libatapp",
"max_stars_repo_path": "include/atframe/etcdcli/etcd_discovery.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-29T01:22:54.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-23T04:38:33.000Z",
"num_tokens": 1406,
"size": 5257
} |
// include all the libraries that are needed in our simulations
#include <iostream>
#include <vector>
#include <cmath>
#include <new>
#include <math.h>
#include <time.h>
#include <algorithm>
#include <fstream>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <string>
#include <sstream>
#include <string.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_statistics_double.h>
#include "theConstants.h"
using namespace std;
| {
"alphanum_fraction": 0.7142857143,
"avg_line_length": 20.72,
"ext": "h",
"hexsha": "5007b0c5653d0f2a0cbfec4b33f88ac4cf0a3b21",
"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": "8c1bb188434044d22aa16138b37f805e84e1205b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MattHartfield/FacSexBGSSims",
"max_forks_repo_path": "included-files.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8c1bb188434044d22aa16138b37f805e84e1205b",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MattHartfield/FacSexBGSSims",
"max_issues_repo_path": "included-files.h",
"max_line_length": 63,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8c1bb188434044d22aa16138b37f805e84e1205b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MattHartfield/FacSexBGSSims",
"max_stars_repo_path": "included-files.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 127,
"size": 518
} |
/* linalg/hh.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman, Brian Gough
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/* Author: G. Jungman */
#include <config.h>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_linalg.h>
#define REAL double
/* [Engeln-Mullges + Uhlig, Alg. 4.42]
*/
int
gsl_linalg_HH_solve (gsl_matrix * A, const gsl_vector * b, gsl_vector * x)
{
if (A->size1 > A->size2)
{
/* System is underdetermined. */
GSL_ERROR ("System is underdetermined", GSL_EINVAL);
}
else if (A->size2 != x->size)
{
GSL_ERROR ("matrix and vector sizes must be equal", GSL_EBADLEN);
}
else
{
int status ;
gsl_vector_memcpy (x, b);
status = gsl_linalg_HH_svx (A, x);
return status ;
}
}
int
gsl_linalg_HH_svx (gsl_matrix * A, gsl_vector * x)
{
if (A->size1 > A->size2)
{
/* System is underdetermined. */
GSL_ERROR ("System is underdetermined", GSL_EINVAL);
}
else if (A->size2 != x->size)
{
GSL_ERROR ("matrix and vector sizes must be equal", GSL_EBADLEN);
}
else
{
const size_t N = A->size1;
const size_t M = A->size2;
size_t i, j, k;
REAL *d = (REAL *) malloc (N * sizeof (REAL));
if (d == 0)
{
GSL_ERROR ("could not allocate memory for workspace", GSL_ENOMEM);
}
/* Perform Householder transformation. */
for (i = 0; i < N; i++)
{
const REAL aii = gsl_matrix_get (A, i, i);
REAL alpha;
REAL f;
REAL ak;
REAL max_norm = 0.0;
REAL r = 0.0;
for (k = i; k < M; k++)
{
REAL aki = gsl_matrix_get (A, k, i);
r += aki * aki;
}
if (r == 0.0)
{
/* Rank of matrix is less than size1. */
free (d);
GSL_ERROR ("matrix is rank deficient", GSL_ESING);
}
alpha = sqrt (r) * GSL_SIGN (aii);
ak = 1.0 / (r + alpha * aii);
gsl_matrix_set (A, i, i, aii + alpha);
d[i] = -alpha;
for (k = i + 1; k < N; k++)
{
REAL norm = 0.0;
f = 0.0;
for (j = i; j < M; j++)
{
REAL ajk = gsl_matrix_get (A, j, k);
REAL aji = gsl_matrix_get (A, j, i);
norm += ajk * ajk;
f += ajk * aji;
}
max_norm = GSL_MAX (max_norm, norm);
f *= ak;
for (j = i; j < M; j++)
{
REAL ajk = gsl_matrix_get (A, j, k);
REAL aji = gsl_matrix_get (A, j, i);
gsl_matrix_set (A, j, k, ajk - f * aji);
}
}
if (fabs (alpha) < 2.0 * GSL_DBL_EPSILON * sqrt (max_norm))
{
/* Apparent singularity. */
free (d);
GSL_ERROR("apparent singularity detected", GSL_ESING);
}
/* Perform update of RHS. */
f = 0.0;
for (j = i; j < M; j++)
{
f += gsl_vector_get (x, j) * gsl_matrix_get (A, j, i);
}
f *= ak;
for (j = i; j < M; j++)
{
REAL xj = gsl_vector_get (x, j);
REAL aji = gsl_matrix_get (A, j, i);
gsl_vector_set (x, j, xj - f * aji);
}
}
/* Perform back-substitution. */
for (i = N; i > 0 && i--;)
{
REAL xi = gsl_vector_get (x, i);
REAL sum = 0.0;
for (k = i + 1; k < N; k++)
{
sum += gsl_matrix_get (A, i, k) * gsl_vector_get (x, k);
}
gsl_vector_set (x, i, (xi - sum) / d[i]);
}
free (d);
return GSL_SUCCESS;
}
}
| {
"alphanum_fraction": 0.4869920447,
"avg_line_length": 25.8388888889,
"ext": "c",
"hexsha": "6530c96969f538aacc78a2a1a12b380fcc1d5e8c",
"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/linalg/hh.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/linalg/hh.c",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/linalg/hh.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": 1301,
"size": 4651
} |
#ifndef _PS_
#define _PS_
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <unistd.h>
#include "../Parameter_files/COSMOLOGY.H"
#include "../Parameter_files/INIT_PARAMS.H"
#include <gsl/gsl_interp.h>
#include <gsl/gsl_spline.h>
#include "cosmo_progs.c"
#include "misc.c"
#include "../Parameter_files/Variables.h"
/* New in v1.1 */
#define ERFC_NPTS (int) 75
#define ERFC_PARAM_DELTA (float) 0.1
static double log_erfc_table[ERFC_NPTS], erfc_params[ERFC_NPTS];
static gsl_interp_accel *erfc_acc;
static gsl_spline *erfc_spline;
#define NR_END 1
#define FREE_ARG char*
#define MM 7
#define NSTACK 50
#define FUNC(x,y,z,xx,yy) ((*func)(x,y,z,xx,yy))
#define FUNC2(x1,x2,x3,x4,x5,x6) ((*func)(x1,x2,x3,x4,x5,x6))
#define EPS2 3.0e-11
#define SWAP(a,b) tempr=(a);(a)=(b);(b)=tempr
#define NGaussLegendre 40 //defines the number of points in the Gauss-Legendre quadrature integration
#define SPLINE_NPTS (int) 250
#define NGLhigh 100
#define NGLlow 100
#define Nhigh 200
#define Nlow 100
#define NMass 200
static double log_MFspline_table[SPLINE_NPTS], MFspline_params[SPLINE_NPTS];
static double log_MFspline_table_densgtr1[SPLINE_NPTS], MFspline_params_densgtr1[SPLINE_NPTS];
static gsl_interp_accel *MFspline_acc, *MFspline_densgtr1_acc;
static gsl_spline *MF_spline, *MF_spline_densgtr1;
static double Fcoll_spline_params[SPLINE_NPTS], log_Fcoll_spline_table[SPLINE_NPTS];
static gsl_interp_accel *Fcoll_spline_acc;
static gsl_spline *Fcoll_spline;
struct parameters_gsl_int_{
double z_obs;
double Mval;
double M_Feed;
double alpha_pl;
double del_traj_1;
double del_traj_2;
};
struct parameters_gsl_ST_int_{
double z_obs;
double M_Feed;
double alpha_pl;
};
unsigned long *lvector(long nl, long nh);
void free_lvector(unsigned long *v, long nl, long nh);
float *vector(long nl, long nh);
void free_vector(float *v, long nl, long nh);
void spline(float x[], float y[], int n, float yp1, float ypn, float y2[]);
void splint(float xa[], float ya[], float y2a[], int n, float x, float *y);
void gauleg(float x1, float x2, float x[], float w[], int n);
double FgtrlnM_general(double lnM, void *params);
double FgtrM_general(float z, float M1, float M_Max, float M2, float MFeedback, float alpha, float delta1, float delta2);
float FgtrConditionalM_second(float z, float M1, float M2, float MFeedback, float alpha, float delta1, float delta2);
float dNdM_conditional_second(float z, float M1, float M2, float delta1, float delta2);
float FgtrConditionallnM(float M1, struct parameters_gsl_int_ parameters_gsl_int);
float GaussLegengreQuad_Fcoll(int n, float z, float M2, float MFeedback, float alpha, float delta1, float delta2);
float *Overdense_spline_gsl,*Overdense_spline_GL_high,*Fcoll_spline_gsl,*Fcoll_spline_GL_high,*xi_low,*xi_high,*wi_high,*wi_low;
float *second_derivs_low_GL,*second_derivs_high_GL,*Overdense_spline_GL_low,*Fcoll_spline_GL_low;
float *Mass_Spline, *Sigma_Spline, *dSigmadm_Spline, *second_derivs_sigma, *second_derivs_dsigma;
void initialiseSplinedSigmaM(float M_Min, float M_Max);
void initialiseGL_Fcoll(int n_low, int n_high, float M_Min, float M_Max);
void initialiseGL_FcollDblPl(int n_low, int n_high, float M_Min, float M_feedback, float M_Max);
void initialiseFcoll_spline(float z, float Mmin, float Mmax, float Mval, float MFeedback, float alphapl);
double dFdlnM_st_PL (double lnM, void *params);
double FgtrM_st_PL(double z, double Mmin, double MFeedback, double alpha_pl);
double sigma_norm, R, theta_cmb, omhh, z_equality, y_d, sound_horizon, alpha_nu, f_nu, f_baryon, beta_c, d2fact, R_CUTOFF, DEL_CURR, SIG_CURR;
/***** FUNCTION PROTOTYPES *****/
double init_ps(); /* initialize global variables, MUST CALL THIS FIRST!!! returns R_CUTOFF */
void free_ps(); /* deallocates the gsl structures from init_ps */
double splined_erfc(double); /* returns erfc for x>=0, using cubic spline in logy-x space */
double deltolindel(float del, float z); /* converts a non-linear overdensity, del, at z to a linear overdensity at z=0 */
double lindeltodel(float lindel, float z); /* converts a linear overdensity, del, at z=0 to a non-linear overdensity at redshift z */
double power_in_k(double k); /* Returns the value of the linear power spectrum density (i.e. <|delta_k|^2>/V) at a given k mode at z=0 */
double power_in_vcb(double k); /*JBM: Returns the value of the DM-b relative velocity power spectrum density (i.e. <|delta_k|^2>/V) at a given k mode at z=0 */
double RtoM(double); /* R in Mpc, M in Msun */
double MtoR(double); /* R in Mpc, M in Msun */
double M_J_WDM(); /* returns the "effective Jeans mass" corresponding to the gas analog of WDM ; eq. 10 in BHO 2001 */
double sheth_delc(double del, double sig);
double dNdM_st(double z, double M);
double dNdM(double z, double M);
double dnbiasdM(double M, float z, double M_o, float del_o); /* dnbiasdM */
double FgtrM(double z, double M); //calculates the fraction of mass contained in haloes with mass > M at redshift z
double FgtrM_st(double z, double M); //calculates the fraction of mass contained in haloes with mass > M at redshift z, with Sheth-Tormen correction
double FgtrM_bias(double z, double M, double del_bias, double sig_bias); //calculates the fraction of mass contained in haloes with mass > M at redshift z, in regions with a linear overdensity of del_bias, and standard deviation sig_bias
double sigmaparam_FgtrM_bias(float z, float sigsmallR, float del_bias, float sig_bias);/* Uses sigma parameters instead of Mass for scale */
double FgtrM_bias_BL08(double z, double M, double del_bias, double sig_bias); // as above, but this version uses the hybrid perscription of Barkana & Loeb 2004 (specifically the separate integral version of eq. 2 in Barkana & Loeb 2008)
double dicke(double z); //calculates the dicke growth function at redshift z
double ddickedz(double z); /* Redshift derivative of the growth function at z */
double ddickedt(double z); /* Time derivative of the growth function at z */
double sigma_z0(double M); //calculates sigma at z=0 (no dicke)
double dsigmasqdm_z0(double M); //calculates d(sigma^2)/dm at z=0 (i.e. does not include dicke growth)
double TFmdm(double k); //Eisenstien & Hu power spectrum transfer function
void TFset_parameters();
float get_R_c(); // returns R_CUTOFF
double get_M_min_ion(float z);
/***************************************/
/* Returns the minimum source mass for ionizing sources, according to user specifications */
double get_M_min_ion(float z){
double MMIN;
if (ION_M_MIN < 0){ // use the virial temperature for Mmin
if (ION_Tvir_MIN < 9.99999e3) // neutral IGM
MMIN = TtoM(z, ION_Tvir_MIN, 1.22);
else // ionized IGM
MMIN = TtoM(z, ION_Tvir_MIN, 0.6);
}
else if (ION_Tvir_MIN < 0){ // use the mass
MMIN = ION_M_MIN;
}
else{
fprintf(stderr, "You have to \"turn-off\" either the ION_M_MIN or \
the ION_Tvir_MIN option in ANAL_PARAMS.H\nAborting...\n");
return -1;
}
// check for WDM
if (P_CUTOFF && ( MMIN < M_J_WDM()))
MMIN = M_J_WDM();
// printf("Mmin is %e\n", MMIN);
return MMIN;
}
/* Returns the minimum source mass for x-ray sources, according to user specifications */
double get_M_min_xray(float z){
double MMIN;
if (X_RAY_Tvir_MIN < 9.99999e3) //neutral IGM
MMIN = TtoM(z, X_RAY_Tvir_MIN, 1.22);
else // ionized IGM
MMIN = TtoM(z, X_RAY_Tvir_MIN, 0.6);
// check for WDM
if (P_CUTOFF && ( MMIN < M_J_WDM()))
MMIN = M_J_WDM();
// printf("Mmin is %e\n", MMIN);
return MMIN;
}
/* returns the "effective Jeans mass" in Msun
corresponding to the gas analog of WDM ; eq. 10 in Barkana+ 2001 */
double M_J_WDM(){
double z_eq, fudge=60;
if (!P_CUTOFF)
return 0;
z_eq = 3600*(OMm-OMb)*hlittle*hlittle/0.15;
return fudge*3.06e8 * (1.5/g_x) * sqrt((OMm-OMb)*hlittle*hlittle/0.15) * pow(M_WDM, -4) * pow(z_eq/3000.0, 1.5);
}
/* converts a non-linear overdensity, del, at z to a linear overdensity at z=0 */
double deltolindel(float del, float z){
float onepdel = 1.0+del;
return ( 1.68647 - 1.35*pow(onepdel,-2/3.0) + 0.78785*pow(onepdel,-0.58661) - 1.12431*pow(onepdel,-0.5) )/dicke(z);
}
/* converts a linear overdensity, del, at z=0 to a non-linear overdensity at redshift z */
double lindeltodel(float lindel, float z){
float prev_lindelguess, delcrit, delguess;
float lindelguess, delmin, delmax, epsilon = 1.0e-7;
// set the critical density corresponding to virialization
// this will be maximum allowed del
delcrit = Deltac_nonlinear(z)*rho_critz(z)/(OMm*RHOcrit*pow(1+z, 3)) - 1;
delmin = -1;
delmax = 500;
prev_lindelguess = -1e10;
while (1){
delguess = 0.5*(delmax+delmin);
lindelguess = deltolindel(delguess, z);
//fprintf(stderr, "%e\t%e\n", delmin, delmax);
// fprintf(stderr, "%e\t%e\t%e\n\n", delguess, lindelguess, lindel);
if ((fabs((lindelguess-lindel)/lindel) < epsilon ) ||
(fabs(lindelguess-lindel) < epsilon ) ||
(fabs(prev_lindelguess - lindelguess) < TINY ))// close enough, or resolution loop
return delguess;
if (lindelguess > lindel)
delmax = delguess;
else
delmin = delguess;
// check if we are above delcrit (see above)
if (delmin > delcrit){
// printf("exced max at lindel=%e\n", lindel);
return delcrit;
}
prev_lindelguess = lindelguess;
}
}
/* R in Mpc, M in Msun */
double RtoM(double R){
// set M according to M<->R conversion defined by the filter type in ../Parameter_files/COSMOLOGY.H
if (FILTER == 0) //top hat M = (4/3) PI <rho> R^3
return (4.0/3.0)*PI*pow(R,3)*(OMm*RHOcrit);
else if (FILTER == 1) //gaussian: M = (2PI)^1.5 <rho> R^3
return pow(2*PI, 1.5) * OMm*RHOcrit * pow(R, 3);
else // filter not defined
fprintf(stderr, "No such filter = %i.\nResults are bogus.\n", FILTER);
return -1;
}
/* R in Mpc, M in Msun */
double MtoR(double M){
// set R according to M<->R conversion defined by the filter type in ../Parameter_files/COSMOLOGY.H
if (FILTER == 0) //top hat M = (4/3) PI <rho> R^3
return pow(3*M/(4*PI*OMm*RHOcrit), 1.0/3.0);
else if (FILTER == 1) //gaussian: M = (2PI)^1.5 <rho> R^3
return pow( M/(pow(2*PI, 1.5) * OMm * RHOcrit), 1.0/3.0 );
else // filter not defined
fprintf(stderr, "No such filter = %i.\nResults are bogus.\n", FILTER);
return -1;
}
/* equation (5) from jenkis et al. (2001) */
double f_jenkins(float del, double sigsq){
if (del < 0){ fprintf(stderr, "ERROR: In function f_jenkins del_o must be less than del_1 = del_crit/dicke(z)!\nAborting...\n"); return 0; }
// fprintf(stderr, "%f\t%f\n", del, sqrt(sigsq));
return sqrt(2/PI) * del/sqrt(sigsq) * pow(E, -0.5*del*del/sigsq);
}
float get_R_c(){
return R_CUTOFF;
}
/* sheth correction to delta crit */
double sheth_delc(double del, double sig){
return sqrt(SHETH_a)*del*(1 + SHETH_b*pow(sig*sig/(SHETH_a*del*del), SHETH_c));
}
/* dnbiasdM */
double dnbiasdM(double M, float z, double M_o, float del_o){
double sigsq, del, sig_one, sig_o;
if ((M_o-M) < TINY){
fprintf(stderr, "WARNING: In function dnbiasdM: M must be less than M_o!\nAborting...\n");
return -1;
}
del = Deltac/dicke(z) - del_o;
if (del < 0){ fprintf(stderr, "ERROR: In function dnbiasdM: del_o must be less than del_1 = del_crit/dicke(z)!\nAborting...\n"); return 0; }
sig_o = sigma_z0(M_o);
sig_one = sigma_z0(M);
sigsq = sig_one*sig_one - sig_o*sig_o;
return -(RHOcrit*OMm)/M /sqrt(2*PI) *del*pow(sigsq,-1.5)*pow(E, -0.5*del*del/sigsq)*dsigmasqdm_z0(M);
}
/*
FUNCTION dNdM(z, M)
Computes the Press_schechter mass function with Sheth-Torman correction for ellipsoidal collapse at
redshift z, and dark matter halo mass M (in solar masses).
The return value is the number density per unit mass of halos in the mass range M to M+dM in units of:
comoving Mpc^-3 Msun^-1
Reference: Sheth, Mo, Torman 2001
*/
double dNdM_st(double z, double M){
double sigma, dsigmadm, nuhat, dicke_growth;
dicke_growth = dicke(z);
sigma = sigma_z0(M) * dicke_growth;
dsigmadm = dsigmasqdm_z0(M) * dicke_growth*dicke_growth/(2.0*sigma);
// sigma = 1.0 * dicke_growth;
// dsigmadm = 1.0 * dicke_growth*dicke_growth/(2.0*sigma);
nuhat = sqrt(SHETH_a) * Deltac / sigma;
return (-OMm*RHOcrit/M) * (dsigmadm/sigma) * sqrt(2/PI)*SHETH_A * (1+ pow(nuhat, -2*SHETH_p)) * nuhat * pow(E, -nuhat*nuhat/2.0);
}
/*
FUNCTION dNdM(z, M)
Computes the Press_schechter mass function at
redshift z, and dark matter halo mass M (in solar masses).
The return value is the number density per unit mass of halos in the mass range M to M+dM in units of:
comoving Mpc^-3 Msun^-1
Reference: Padmanabhan, pg. 214
*/
double dNdM(double z, double M){
double sigma, dsigmadm, dicke_growth;
dicke_growth = dicke(z);
sigma = sigma_z0(M) * dicke_growth;
dsigmadm = dsigmasqdm_z0(M) * (dicke_growth*dicke_growth/(2*sigma));
return (-OMm*RHOcrit/M) * sqrt(2/PI) * (Deltac/(sigma*sigma)) * dsigmadm * pow(E, -(Deltac*Deltac)/(2*sigma*sigma));
}
/*
FUNCTION FgtrM_st(z, M)
Computes the fraction of mass contained in haloes with mass > M at redshift z
Uses Sheth-Torman correction
*/
double dFdlnM_st (double lnM, void *params){
double z = *(double *)params;
double M = exp(lnM);
return dNdM_st(z, M) * M * M;
}
double FgtrM_st(double z, double M){
// printf("Calculating ST coll fraction: M=%.2le, z=%.2le \n",M,z);
double result, error, lower_limit, upper_limit;
gsl_function F;
// double rel_tol = 0.001; //<- relative tolerance
double rel_tol = 0.01; //<- relative tolerance
gsl_integration_workspace * w
= gsl_integration_workspace_alloc (1000);
F.function = &dFdlnM_st;
F.params = &z;
lower_limit = log(M);
upper_limit = log(FMAX(1e16, M*100));
// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS61, w, &result, &error);
// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS51, w, &result, &error);
gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS41, w, &result, &error);
// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS31, w, &result, &error);
// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS21, w, &result, &error);
// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS15, w, &result, &error);
gsl_integration_workspace_free (w);
return result / (OMm*RHOcrit);
}
/*
FUNCTION FgtrM(z, M)
Computes the fraction of mass contained in haloes with mass > M at redshift z
*/
double FgtrM(double z, double M){
double del, sig;
del = Deltac/dicke(z); //regular spherical collapse delta
sig = sigma_z0(M);
return splined_erfc(del / (sqrt(2)*sig));
}
/*
calculates the fraction of mass contained in haloes with mass > M at redshift z, in regions with a linear overdensity of del_bias, and standard deviation sig_bias
*/
double FgtrM_bias(double z, double M, double del_bias, double sig_bias){
double del, sig, sigsmallR;
sigsmallR = sigma_z0(M);
if (!(sig_bias < sigsmallR)){ // biased region is smaller that halo!
// fprintf(stderr, "FgtrM_bias: Biased region is smaller than halo!\nResult is bogus.\n");
// return 0;
return 0.000001;
}
del = Deltac/dicke(z) - del_bias;
sig = sqrt(sigsmallR*sigsmallR - sig_bias*sig_bias);
return splined_erfc(del / (sqrt(2)*sig));
}
/* Uses sigma parameters instead of Mass for scale */
double sigmaparam_FgtrM_bias(float z, float sigsmallR, float del_bias, float sig_bias){
double del, sig;
if (!(sig_bias < sigsmallR)){ // biased region is smaller that halo!
// fprintf(stderr, "local_FgtrM_bias: Biased region is smaller than halo!\nResult is bogus.\n");
// return 0;
return 0.000001;
}
del = Deltac/dicke(z) - del_bias;
sig = sqrt(sigsmallR*sigsmallR - sig_bias*sig_bias);
return splined_erfc(del / (sqrt(2)*sig));
}
/*
Calculates the fraction of mass contained in haloes with mass > M at redshift z, in regions with a linear overdensity of del_bias, and standard deviation sig_bias.
This version uses the hybrid perscription of Barkana & Loeb 2004 (specifically the separate
integral version of eq. 2 in Barkana & Loeb 2008)
*/
double FgtrM_bias_BL08(double z, double M, double del_bias, double sig_bias){
return FgtrM_st(z, M) / FgtrM(z, M) * FgtrM_bias(z, M, del_bias, sig_bias);
}
/*
FUNCTION dicke(z)
Computes the dicke growth function at redshift z, i.e. the z dependance part of sigma
References: Peebles, "Large-Scale...", pg.53 (eq. 11.16). Includes omega<=1
Nonzero Lambda case from Liddle et al, astro-ph/9512102, eqs. 6-8.
and quintessence case from Wang et al, astro-ph/9804015
Normalized to dicke(z=0)=1
*/
double dicke(double z){
double omegaM_z, dick_z, dick_0, x, x_0;
double tiny = 1e-4;
if (fabs(OMm-1.0) < tiny){ //OMm = 1 (Einstein de-Sitter)
return 1.0/(1.0+z);
}
else if ( (OMl > (-tiny)) && (fabs(OMl+OMm+OMr-1.0) < 0.01) && (fabs(wl+1.0) < tiny) ){
//this is a flat, cosmological CONSTANT universe, with only lambda, matter and radiation
//it is taken from liddle et al.
omegaM_z = OMm*pow(1+z,3) / ( OMl + OMm*pow(1+z,3) + OMr*pow(1+z,4) );
dick_z = 2.5*omegaM_z / ( 1.0/70.0 + omegaM_z*(209-omegaM_z)/140.0 + pow(omegaM_z, 4.0/7.0) );
dick_0 = 2.5*OMm / ( 1.0/70.0 + OMm*(209-OMm)/140.0 + pow(OMm, 4.0/7.0) );
return dick_z / (dick_0 * (1.0+z));
}
else if ( (OMtot < (1+tiny)) && (fabs(OMl) < tiny) ){ //open, zero lambda case (peebles, pg. 53)
x_0 = 1.0/(OMm+0.0) - 1.0;
dick_0 = 1 + 3.0/x_0 + 3*log(sqrt(1+x_0)-sqrt(x_0))*sqrt(1+x_0)/pow(x_0,1.5);
x = fabs(1.0/(OMm+0.0) - 1.0) / (1+z);
dick_z = 1 + 3.0/x + 3*log(sqrt(1+x)-sqrt(x))*sqrt(1+x)/pow(x,1.5);
return dick_z/dick_0;
}
else if ( (OMl > (-tiny)) && (fabs(OMtot-1.0) < tiny) && (fabs(wl+1) > tiny) ){
fprintf(stderr, "IN WANG\n");
return -1;
}
fprintf(stderr, "No growth function!!! Output will be fucked up.");
return -1;
}
/* redshift derivative of the growth function at z */
double ddicke_dz(double z){
float dz = 1e-10;
double omegaM_z, ddickdz, dick_0, x, x_0, domegaMdz;
return (dicke(z+dz)-dicke(z))/dz;
}
/* Time derivative of the growth function at z */
double ddickedt(double z){
float dz = 1e-10;
double omegaM_z, ddickdz, dick_0, x, x_0, domegaMdz;
double tiny = 1e-4;
return (dicke(z+dz)-dicke(z))/dz/dtdz(z); // lazy non-analytic form getting
if (fabs(OMm-1.0) < tiny){ //OMm = 1 (Einstein de-Sitter)
return -pow(1+z,-2)/dtdz(z);
}
else if ( (OMl > (-tiny)) && (fabs(OMl+OMm+OMr-1.0) < 0.01) && (fabs(wl+1.0) < tiny) ){
//this is a flat, cosmological CONSTANT universe, with only lambda, matter and radiation
//it is taken from liddle et al.
omegaM_z = OMm*pow(1+z,3) / ( OMl + OMm*pow(1+z,3) + OMr*pow(1+z,4) );
domegaMdz = omegaM_z*3/(1+z) - OMm*pow(1+z,3)*pow(OMl + OMm*pow(1+z,3) + OMr*pow(1+z,4), -2) * (3*OMm*(1+z)*(1+z) + 4*OMr*pow(1+z,3));
dick_0 = OMm / ( 1.0/70.0 + OMm*(209-OMm)/140.0 + pow(OMm, 4.0/7.0) );
ddickdz = (domegaMdz/(1+z)) * (1.0/70.0*pow(omegaM_z,-2) + 1.0/140.0 + 3.0/7.0*pow(omegaM_z, -10.0/3.0)) * pow(1.0/70.0/omegaM_z + (209.0-omegaM_z)/140.0 + pow(omegaM_z, -3.0/7.0) , -2);
ddickdz -= pow(1+z,-2)/(1.0/70.0/omegaM_z + (209.0-omegaM_z)/140.0 + pow(omegaM_z, -3.0/7.0));
return ddickdz / dick_0 / dtdz(z);
}
fprintf(stderr, "No growth function!!! Output will be fucked up.");
return -1;
}
/*
JBM:
this function reads the z=0 matter (CDM+baryons) transfer function from CLASS
flag = 0 to initialize interpolator, flag = -1 to free memory, flag = else to interpolate.
similar to built-in function "double T_RECFAST(float z, int flag)"
*/
double TFm_CLASS(double k, int flag)
{
static double kclass[CLASS_LENGTH], Tmclass[CLASS_LENGTH];
static gsl_interp_accel *acc_class;
static gsl_spline *spline_class;
float trash, currk, currTm;
double ans;
int i;
FILE *F;
if (flag == 0) {// Initialize vectors and read file
if ( !(F=fopen(CLASS_FILENAME, "r")) ){
fprintf(stderr, "TFm_CLASS: Unable to open file: %s for reading\nAborting\n", CLASS_FILENAME);
return -1;
}
// for (i=(CLASS_LENGTH-1);i>=0;i--) {
for (i=0;i<CLASS_LENGTH;i++) {
fscanf(F, "%e %e %e ", &currk, &currTm, &trash);
kclass[i] = currk;
Tmclass[i] = currTm;// printf("k=%.1le Tm=%.1le \n", currk,currTm);
if(kclass[i]<=kclass[i-1] && i>0){
printf("WARNING, Tk table not ordered \n");
printf("k=%.1le kprev=%.1le \n\n",kclass[i],kclass[i-1]);
}
}
fclose(F);
// Set up spline table
acc_class = gsl_interp_accel_alloc ();
spline_class = gsl_spline_alloc (gsl_interp_cspline, CLASS_LENGTH);
gsl_spline_init(spline_class, kclass, Tmclass, CLASS_LENGTH);
return 0;
}
if (flag == -1) {
gsl_spline_free (spline_class);
gsl_interp_accel_free(acc_class);
return 0;
}
if (k > kclass[CLASS_LENGTH-1]) { // k>kmax
fprintf(stderr, "Called TFm_CLASS with k=%f, larger than kmax!\n", k);
return (Tmclass[CLASS_LENGTH]/kclass[CLASS_LENGTH-1]/kclass[CLASS_LENGTH-1]);
//JBM:we just set it to the last value, since sometimes it wants large k for R<<cell_size, which does not matter much.
}
else { // Do spline
ans = gsl_spline_eval (spline_class, k, acc_class);
}
return ans/k/k;
//JBM:we have to divide by k^2 to agree with the old-fashioned convention.
}
/*
JBM:
this function reads the z=zkin relative velocity transfer function from CLASS
same caveats as for Tfm_CLASS
*/
double TFvcb_CLASS(double k, int flag)
{
static double kclass_vcb[CLASS_LENGTH], Tvclass_vcb[CLASS_LENGTH];
static gsl_interp_accel *acc_vcb;
static gsl_spline *spline_vcb;
double trash, currk, currTv;
double ans;
int i;
FILE *F;
if (flag == 0) {
// Initialize vectors
if ( !(F=fopen(CLASS_FILENAME, "r")) ){
fprintf(stderr, "TFvcb_CLASS: Unable to open file: %s for reading\nAborting\n", CLASS_FILENAME);
return -1;
}
// for (i=(CLASS_LENGTH-1);i>=0;i--) {
for (i=0;i<CLASS_LENGTH;i++) {
fscanf(F, "%le %le %le ", &currk, &trash, &currTv);
kclass_vcb[i] = currk;
Tvclass_vcb[i] = currTv;
if(kclass_vcb[i]<=kclass_vcb[i-1] && i>0){
printf("WARNING, T_vcb table not ordered \n");
}
}
fclose(F);
// Set up spline table
acc_vcb = gsl_interp_accel_alloc ();
spline_vcb = gsl_spline_alloc (gsl_interp_cspline, CLASS_LENGTH);
gsl_spline_init(spline_vcb, kclass_vcb, Tvclass_vcb, CLASS_LENGTH);
return 0;
}
if (flag == -1) {
gsl_spline_free (spline_vcb);
gsl_interp_accel_free(acc_vcb);
return 0;
}
if (k > kclass_vcb[CLASS_LENGTH-1]) { // k>kmax
fprintf(stderr, "Called TFvcb_CLASS with k=%f, bailing out!\n", k);
return 0;
}
else { // Do spline
ans = gsl_spline_eval (spline_vcb, k, acc_vcb);
// printf("k=%.3le, T=%.1le \n", k, ans);
}
return ans/k/k;
//JBM:we have to divide by k^2 to agree with the old-fashioned convention.
}
/*
FUNCTION sigma_z0(M)
Returns the standard deviation of the normalized, density excess (delta(x)) field,
smoothed on the comoving scale of M (see filter definitions for M<->R conversion).
The sigma is evaluated at z=0, with the time evolution contained in the dicke(z) factor,
i.e. sigma(M,z) = sigma_z0(m) * dicke(z)
normalized so that sigma_z0(M->8/h Mpc) = SIGMA8 in ../Parameter_files/COSMOLOGY.H
NOTE: volume is normalized to = 1, so this is equvalent to the mass standard deviation
M is in solar masses
References: Padmanabhan, pg. 210, eq. 5.107
*/
double dsigma_dk(double k, void *params){
double p, w, T, gamma, q, aa, bb, cc, kR;
// get the power spectrum.. choice of 5:
if (POWER_SPECTRUM == 0){ // Eisenstein & Hu
T = TFmdm(k);
// check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function
if (P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v);
p = pow(k, POWER_INDEX) * T * T;
}
else if (POWER_SPECTRUM == 1){ // BBKS
gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);
q = k / (hlittle*gamma);
T = (log(1.0+2.34*q)/(2.34*q)) *
pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25);
p = pow(k, POWER_INDEX) * T * T;
}
else if (POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992)
gamma = 0.25;
aa = 6.4/(hlittle*gamma);
bb = 3.0/(hlittle*gamma);
cc = 1.7/(hlittle*gamma);
p = pow(k, POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 );
}
else if (POWER_SPECTRUM == 3){ // Peebles, pg. 626
gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);
aa = 8.0 / (hlittle*gamma);
bb = 4.7 / pow(hlittle*gamma, 2);
p = pow(k, POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2);
}
else if (POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52
gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);
aa = 1.7/(hlittle*gamma);
bb = 9.0/pow(hlittle*gamma, 1.5);
cc = 1.0/pow(hlittle*gamma, 2);
p = pow(k, POWER_INDEX) * 19400.0 / pow(1 + aa*k + bb*pow(k, 1.5) + cc*k*k, 2);
}
else if (POWER_SPECTRUM == 5){ // JBM: CLASS
T = TFm_CLASS(k, 1); //read from z=0 output of CLASS
//JBM: flag = 1 here always, since now we have to have initialized the interpolator for CLASS
p = pow(k, POWER_INDEX) * T * T;
}
else{
fprintf(stderr, "No such power spectrum defined: %i\nOutput is bogus.\n", POWER_SPECTRUM);
p = 0;
}
// now get the value of the window function
// NOTE: only use top hat for SIGMA8 normalization
kR = k*R;
if ( (FILTER == 0) || (sigma_norm < 0) ){ // top hat
if ( (kR) < 1.0e-4 ){ w = 1.0;} // w converges to 1 as (kR) -> 0
else { w = 3.0 * (sin(kR)/pow(kR, 3) - cos(kR)/pow(kR, 2));}
}
else if (FILTER == 1){ // gaussian of width 1/R
w = pow(E, -kR*kR/2.0);
}
else {
fprintf(stderr, "No such filter: %i\nOutput is bogus.\n", FILTER);
w=0;
}
return k*k*p*w*w;
}
double sigma_z0(double M){
double result, error, lower_limit, upper_limit;
gsl_function F;
//OLD: double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance
double rel_tol = 0.01; //<- relative tolerance
gsl_integration_workspace * w
= gsl_integration_workspace_alloc (1000);
double kstart, kend;
R = MtoR(M);
// printf("sigmaz0 -> R=%.2le, from M=%.2le \n",R, M);
// now lets do the integral for sigma and scale it with sigma_norm
kstart = FMAX(1.0e-99/R,KBOT);
//JBM:we stablish a maximum k of 10^3 Mpc-1, since the CLASS transfer function has a max!
kend = FMIN(350.0/R, KTOP);
lower_limit = kstart;//log(kstart);
upper_limit = kend;//log(kend);
F.function = &dsigma_dk;
// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS61, w, &result, &error);
// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS41, w, &result, &error);
gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS15, w, &result, &error);
gsl_integration_workspace_free (w);
return sigma_norm * sqrt(result);
}
/*
Returns the value of the linear power spectrum DENSITY (i.e. <|delta_k|^2>/V)
at a given k mode linearly extrapolated to z=0
*/
double power_in_k(double k){
double p, T, gamma, q, aa, bb, cc;
// get the power spectrum.. choice of 5:
if (POWER_SPECTRUM == 0){ // Eisenstein & Hu
T = TFmdm(k);
// check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function
if (P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v);
p = pow(k, POWER_INDEX) * T * T;
//p = pow(k, POWER_INDEX - 0.05*log(k/0.05)) * T * T; //running, alpha=0.05
}
else if (POWER_SPECTRUM == 1){ // BBKS
gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);
q = k / (hlittle*gamma);
T = (log(1.0+2.34*q)/(2.34*q)) *
pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25);
p = pow(k, POWER_INDEX) * T * T;
}
else if (POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992)
gamma = 0.25;
aa = 6.4/(hlittle*gamma);
bb = 3.0/(hlittle*gamma);
cc = 1.7/(hlittle*gamma);
p = pow(k, POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 );
}
else if (POWER_SPECTRUM == 3){ // Peebles, pg. 626
gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);
aa = 8.0 / (hlittle*gamma);
bb = 4.7 / pow(hlittle*gamma, 2);
p = pow(k, POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2);
}
else if (POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52
gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);
aa = 1.7/(hlittle*gamma);
bb = 9.0/pow(hlittle*gamma, 1.5);
cc = 1.0/pow(hlittle*gamma, 2);
p = pow(k, POWER_INDEX) * 19400.0 / pow(1 + aa*k + bb*pow(k, 1.5) + cc*k*k, 2);
}
else if (POWER_SPECTRUM == 5){ // JBM: CLASS
T = TFm_CLASS(k, 1); //read from z=0 output of CLASS
//JBM: flag = 1 here always, since now we have to have initialized the interpolator for CLASS
p = pow(k, POWER_INDEX) * T * T;
}
else{
fprintf(stderr, "No such power spectrum defined: %i\nOutput is bogus.\n", POWER_SPECTRUM);
p = 0;
}
return p*TWOPI*PI*sigma_norm*sigma_norm;
}
/*
JBM: Returns the value of the linear power spectrum of the DM-b relative velocity
at kinematic decoupling (which we set at zkin=1010)
*/
double power_in_vcb(double k){
double p, T, gamma, q, aa, bb, cc;
//only works if using CLASS
if (POWER_SPECTRUM == 5){ // CLASS
T = TFvcb_CLASS(k, 1.0); //read from CLASS file. flag=1 since we have initialized before
p = pow(k, POWER_INDEX) * T * T;
}
else{
fprintf(stderr, "Cannot get P_cb unless using CLASS: %i\n Set USE_RELATIVE_VELOCITIES 0 or use CLASS.\n", POWER_SPECTRUM);
p = 0;
}
return p*TWOPI*PI*sigma_norm*sigma_norm;
}
/*
FUNCTION dsigmasqdm_z0(M)
returns d/dm (sigma^2) (see function sigma), in units of Msun^-1
*/
double dsigmasq_dm(double k, void *params){
double p, w, T, gamma, q, aa, bb, cc, dwdr, drdm, kR;
// get the power spectrum.. choice of 5:
if (POWER_SPECTRUM == 0){ // Eisenstein & Hu ApJ, 1999, 511, 5
T = TFmdm(k);
// check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function
if (P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v);
p = pow(k, POWER_INDEX) * T * T;
//p = pow(k, POWER_INDEX - 0.05*log(k/0.05)) * T * T; //running, alpha=0.05
}
else if (POWER_SPECTRUM == 1){ // BBKS
gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);
q = k / (hlittle*gamma);
T = (log(1.0+2.34*q)/(2.34*q)) *
pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25);
p = pow(k, POWER_INDEX) * T * T;
}
else if (POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992)
gamma = 0.25;
aa = 6.4/(hlittle*gamma);
bb = 3.0/(hlittle*gamma);
cc = 1.7/(hlittle*gamma);
p = pow(k, POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 );
}
else if (POWER_SPECTRUM == 3){ // Peebles, pg. 626
gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);
aa = 8.0 / (hlittle*gamma);
bb = 4.7 / (hlittle*gamma);
p = pow(k, POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2);
}
else if (POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52
gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);
aa = 1.7/(hlittle*gamma);
bb = 9.0/pow(hlittle*gamma, 1.5);
cc = 1.0/pow(hlittle*gamma, 2);
p = pow(k, POWER_INDEX) * 19400.0 / pow(1 + aa*k + pow(bb*k, 1.5) + cc*k*k, 2);
}
else if (POWER_SPECTRUM == 5){ // JBM: CLASS
T = TFm_CLASS(k, 1); //read from z=0 output of CLASS
//JBM: flag = 1 here always, since now we have to have initialized the interpolator for CLASS
p = pow(k, POWER_INDEX) * T * T;
}
else{
fprintf(stderr, "No such power spectrum defined: %i\nOutput is bogus.\n", POWER_SPECTRUM);
p = 0;
}
// now get the value of the window function
kR = k * R;
if (FILTER == 0){ // top hat
if ( (kR) < 1.0e-4 ){ w = 1.0; }// w converges to 1 as (kR) -> 0
else { w = 3.0 * (sin(kR)/pow(kR, 3) - cos(kR)/pow(kR, 2));}
// now do d(w^2)/dm = 2 w dw/dr dr/dm
if ( (kR) < 1.0e-10 ){ dwdr = 0;}
else{ dwdr = 9*cos(kR)*k/pow(kR,3) + 3*sin(kR)*(1 - 3/(kR*kR))/(kR*R);}
//3*k*( 3*cos(kR)/pow(kR,3) + sin(kR)*(-3*pow(kR, -4) + 1/(kR*kR)) );}
// dwdr = -1e8 * k / (R*1e3);
drdm = 1.0 / (4.0*PI * OMm*RHOcrit * R*R);
}
else if (FILTER == 1){ // gaussian of width 1/R
w = pow(E, -kR*kR/2.0);
dwdr = - k*kR * w;
drdm = 1.0 / (pow(2*PI, 1.5) * OMm*RHOcrit * 3*R*R);
}
else {
fprintf(stderr, "No such filter: %i\nOutput is bogus.\n", FILTER);
w=0;
}
// printf("%e\t%e\t%e\t%e\t%e\t%e\t%e\n", k, R, p, w, dwdr, drdm, dsigmadk[1]);
// printf("k=%.1e and R=%.1e -> P=%.1e W(KR)=%.1e \n", k, R, p, w);
return k*k*p*2*w*dwdr*drdm * d2fact;
}
double dsigmasqdm_z0(double M){
double result, error, lower_limit, upper_limit;
gsl_function F;
//OLD: double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance
double rel_tol = 0.01; //<- relative tolerance
gsl_integration_workspace * w
= gsl_integration_workspace_alloc (3000);
double kstart, kend;
R = MtoR(M);
// now lets do the integral for sigma and scale it with sigma_norm
kstart = FMAX(1.0e-99/R,KBOT);
kend = FMIN(350.0/R, KTOP);
lower_limit = kstart;//log(kstart);
upper_limit = kend;//log(kend);
//OLD: d2fact = M*10000/sigma_z0(M);
d2fact = 1.0;
//JBM:This is an irrelevant scaling to make te integral converge that was in 21cmmc originally, but it can be set to one and it works better.
//printf("dsigma/dm -> R=%.2le, from M=%.2le \n",R, M);
long unsigned int trash;
F.function = &dsigmasq_dm;
// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS61, w, &result, &error);
//OLD: gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS15, w, &result, &error);
gsl_integration_qng (&F, lower_limit, upper_limit, 3000, rel_tol, &result, &error, &trash);
gsl_integration_workspace_free (w);
return sigma_norm * sigma_norm * result /d2fact;
}
/*
FUNCTION TFmdm is the power spectrum transfer function from Eisenstein & Hu ApJ, 1999, 511, 5
*/
double TFmdm(double k){
double q, gamma_eff, q_eff, TF_m, q_nu;
q = k*pow(theta_cmb,2)/omhh;
gamma_eff=sqrt(alpha_nu) + (1.0-sqrt(alpha_nu))/(1.0+pow(0.43*k*sound_horizon, 4));
q_eff = q/gamma_eff;
TF_m= log(E+1.84*beta_c*sqrt(alpha_nu)*q_eff);
TF_m /= TF_m + pow(q_eff,2) * (14.4 + 325.0/(1.0+60.5*pow(q_eff,1.11)));
q_nu = 3.92*q/sqrt(f_nu/N_nu);
TF_m *= 1.0 + (1.2*pow(f_nu,0.64)*pow(N_nu,0.3+0.6*f_nu)) /
(pow(q_nu,-1.6)+pow(q_nu,0.8));
// printf("%f %e %f %f %f %f\n",omhh,f_nu,f_baryon,N_nu,y_d,alpha_nu);
// printf("%f %f %f %f\n", beta_c,sound_horizon,theta_cmb,z_equality);
//printf("%f %e %f %f %f\n\n",q, k, gamma_eff, q_nu, TF_m);
return TF_m;
}
void TFset_parameters(){
double z_drag, R_drag, R_equality, p_c, p_cb, f_c, f_cb, f_nub, k_equality;
z_equality = 25000*omhh*pow(theta_cmb, -4) - 1.0;
k_equality = 0.0746*omhh/(theta_cmb*theta_cmb);
z_drag = 0.313*pow(omhh,-0.419) * (1 + 0.607*pow(omhh, 0.674));
z_drag = 1 + z_drag*pow(OMb*hlittle*hlittle, 0.238*pow(omhh, 0.223));
z_drag *= 1291 * pow(omhh, 0.251) / (1 + 0.659*pow(omhh, 0.828));
y_d = (1 + z_equality) / (1.0 + z_drag);
R_drag = 31.5 * OMb*hlittle*hlittle * pow(theta_cmb, -4) * 1000 / (1.0 + z_drag);
R_equality = 31.5 * OMb*hlittle*hlittle * pow(theta_cmb, -4) * 1000 / (1.0 + z_equality);
sound_horizon = 2.0/3.0/k_equality * sqrt(6.0/R_equality) *
log( (sqrt(1+R_drag) + sqrt(R_drag+R_equality)) / (1.0 + sqrt(R_equality)) );
p_c = -(5 - sqrt(1 + 24*(1 - f_nu-f_baryon)))/4.0;
p_cb = -(5 - sqrt(1 + 24*(1 - f_nu)))/4.0;
f_c = 1 - f_nu - f_baryon;
f_cb = 1 - f_nu;
f_nub = f_nu+f_baryon;
alpha_nu = (f_c/f_cb) * (2*(p_c+p_cb)+5)/(4*p_cb+5.0);
alpha_nu *= 1 - 0.553*f_nub+0.126*pow(f_nub,3);
alpha_nu /= 1-0.193*sqrt(f_nu)+0.169*f_nu;
alpha_nu *= pow(1+y_d, p_c-p_cb);
alpha_nu *= 1+ (p_cb-p_c)/2.0 * (1.0+1.0/(4.0*p_c+3.0)/(4.0*p_cb+7.0))/(1.0+y_d);
beta_c = 1.0/(1.0-0.949*f_nub);
}
double init_ps(){
double result, error, lower_limit, upper_limit;
gsl_function F;
// double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance
double rel_tol = 0.01; //<- relative tolerance
gsl_integration_workspace * w
= gsl_integration_workspace_alloc (1000);
double kstart, kend;
int i;
double x;
//JBM: we start the interpolator if using CLASS:
double temp_var;
if (POWER_SPECTRUM == 5){
temp_var = TFm_CLASS(1.0, 0);
temp_var = TFvcb_CLASS(1.0, 0);
}
// Set cuttoff scale for WDM (eq. 4 in Barkana et al. 2001) in comoving Mpc
R_CUTOFF = 0.201*pow((OMm-OMb)*hlittle*hlittle/0.15, 0.15)*pow(g_x/1.5, -0.29)*pow(M_WDM, -1.15);
// fprintf(stderr, "For M_DM = %.2e keV, R_CUTOFF is: %.2e comoving Mpc\n", M_WDM, R_CUTOFF);
if (!P_CUTOFF)
// fprintf(stderr, "But you have selected CDM, so this is ignored\n");
omhh = OMm*hlittle*hlittle;
theta_cmb = T_cmb / 2.7;
// Translate Parameters into forms GLOBALVARIABLES form
f_nu = OMn/OMm;
f_baryon = OMb/OMm;
if (f_nu < TINY) f_nu = 1e-10;
if (f_baryon < TINY) f_baryon = 1e-10;
TFset_parameters();
sigma_norm = -1;
R = 8.0/hlittle;
kstart = FMAX(1.0e-99/R, KBOT);
kend = FMIN(350.0/R, KTOP);
lower_limit = kstart;//log(kstart);
upper_limit = kend;//log(kend);
F.function = &dsigma_dk;
gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,
1000, GSL_INTEG_GAUSS61, w, &result, &error);
gsl_integration_workspace_free (w);
sigma_norm = SIGMA8/sqrt(result); //takes care of volume factor
/* initialize the lookup table for erfc */
/*
for (i=0; i<=ERFC_NPTS; i++){
erfc_params[i] = i*ERFC_PARAM_DELTA;
log_erfc_table[i] = log(erfcc(erfc_params[i]));
}
// Set up spline table
erfc_acc = gsl_interp_accel_alloc ();
erfc_spline = gsl_spline_alloc (gsl_interp_cspline, ERFC_NPTS);
gsl_spline_init(erfc_spline, erfc_params, log_erfc_table, ERFC_NPTS);
*/
return R_CUTOFF;
}
void free_ps(){
/* gsl_spline_free (erfc_spline);
gsl_interp_accel_free(erfc_acc);
*/
double temp_var;
//JBM: we free the interpolator if using CLASS:
if (POWER_SPECTRUM == 5){
temp_var = TFm_CLASS(1.0, -1);
temp_var = TFvcb_CLASS(1.0, -1);
}
return;
}
double splined_erfc(double x){
if (x < 0){
// fprintf(stderr, "WARNING: Negative value %e passed to splined_erfc. Returning 1\n", x);
return 1;
}
return erfcc(x); // the interpolation below doesn't seem to be stable in Ts.c
if (x > ERFC_PARAM_DELTA*(ERFC_NPTS-1))
return erfcc(x);
else
return exp(gsl_spline_eval(erfc_spline, x, erfc_acc));
}
float FgtrConditionalM_second(float z, float M1, float M2, float MFeedback, float alpha, float delta1, float delta2) {
return exp(M1)*pow(exp(M1)/MFeedback,alpha)*dNdM_conditional_second(z,M1,M2,delta1,delta2)/sqrt(2.*PI);
}
float dNdM_conditional_second(float z, float M1, float M2, float delta1, float delta2){
float sigma1, sigma2, dsigmadm, dicke_growth,dsigma_val;
M1 = exp(M1);
M2 = exp(M2);
dicke_growth = dicke(z);
splint(Mass_Spline-1,Sigma_Spline-1,second_derivs_sigma-1,(int)NMass,M1,&(sigma1));
splint(Mass_Spline-1,Sigma_Spline-1,second_derivs_sigma-1,(int)NMass,M2,&(sigma2));
sigma1 = sigma1*sigma1;
sigma2 = sigma2*sigma2;
splint(Mass_Spline-1,dSigmadm_Spline-1,second_derivs_dsigma-1,(int)NMass,M1,&(dsigma_val));
dsigmadm = -pow(10.,dsigma_val)/(2.0*sigma1); // This is actually sigma1^{2} as calculated above, however, it should just be sigma1. It cancels with the same factor below. Why I have decided to write it like that I don't know!
if((sigma1 > sigma2)) {
return -(( delta1 - delta2 )/dicke_growth)*( 2.*sigma1*dsigmadm )*( exp( - ( delta1 - delta2 )*( delta1 - delta2 )/( 2.*dicke_growth*dicke_growth*( sigma1 - sigma2 ) ) ) )/(pow( sigma1 - sigma2, 1.5));
}
else if(sigma1==sigma2) {
return -(( delta1 - delta2 )/dicke_growth)*( 2.*sigma1*dsigmadm )*( exp( - ( delta1 - delta2 )*( delta1 - delta2 )/( 2.*dicke_growth*dicke_growth*( 1.e-6 ) ) ) )/(pow( 1.e-6, 1.5));
}
else {
return 0.;
}
}
void gauleg(float x1, float x2, float x[], float w[], int n)
//Given the lower and upper limits of integration x1 and x2, and given n, this routine returns arrays x[1..n] and w[1..n] of length n,
//containing the abscissas and weights of the Gauss- Legendre n-point quadrature formula.
{
int m,j,i;
double z1,z,xm,xl,pp,p3,p2,p1;
m=(n+1)/2;
xm=0.5*(x2+x1);
xl=0.5*(x2-x1);
for (i=1;i<=m;i++) {
//High precision is a good idea for this routine.
//The roots are symmetric in the interval, so we only have to find half of them.
//Loop over the desired roots.
z=cos(3.141592654*(i-0.25)/(n+0.5));
//Starting with the above approximation to the ith root, we enter the main loop of refinement by Newton’s method.
do {
p1=1.0;
p2=0.0;
for (j=1;j<=n;j++) {
//Loop up the recurrence relation to get the Legendre polynomial evaluated at z.
p3=p2;
p2=p1;
p1=((2.0*j-1.0)*z*p2-(j-1.0)*p3)/j;
}
//p1 is now the desired Legendre polynomial. We next compute pp, its derivative, by a standard relation involving also p2,
//the polynomial of one lower order.
pp=n*(z*p1-p2)/(z*z-1.0);
z1=z;
z=z1-p1/pp;
} while (fabs(z-z1) > EPS2);
x[i]=xm-xl*z;
x[n+1-i]=xm+xl*z;
w[i]=2.0*xl/((1.0-z*z)*pp*pp);
w[n+1-i]=w[i];
}
}
void nrerror(char error_text[])
{
fprintf(stderr,"Numerical Recipes run-time error...\n");
fprintf(stderr,"%s\n",error_text);
fprintf(stderr,"...now exiting to system...\n");
exit(1);
}
float *vector(long nl, long nh)
/* allocate a float vector with subscript range v[nl..nh] */
{
float *v;
v = (float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
if(!v) nrerror("allocation failure in vector()");
return v - nl + NR_END;
}
void free_vector(float *v, long nl, long nh)
/* free a float vector allocated with vector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
void spline(float x[], float y[], int n, float yp1, float ypn, float y2[])
/*Given arrays x[1..n] and y[1..n] containing a tabulated function, i.e., yi = f(xi), with
x1 <x2 < :: : < xN, and given values yp1 and ypn for the first derivative of the interpolating
function at points 1 and n, respectively, this routine returns an array y2[1..n] that contains
the second derivatives of the interpolating function at the tabulated points xi. If yp1 and/or
ypn are equal to 1e30 or larger, the routine is signaled to set the corresponding boundary
condition for a natural spline, with zero second derivative on that boundary.*/
{
int i,k;
float p,qn,sig,un,*u;
int na,nb,check;
u=vector(1,n-1);
if (yp1 > 0.99e30) // The lower boundary condition is set either to be "natural"
y2[1]=u[1]=0.0;
else { // or else to have a specified first derivative.
y2[1] = -0.5;
u[1]=(3.0/(x[2]-x[1]))*((y[2]-y[1])/(x[2]-x[1])-yp1);
}
for (i=2;i<=n-1;i++) { //This is the decomposition loop of the tridiagonal algorithm.
sig=(x[i]-x[i-1])/(x[i+1]-x[i-1]); //y2 and u are used for temporary
na = 1;
nb = 1;
check = 0;
while(((float)(x[i+na*1]-x[i-nb*1])==(float)0.0)) {
check = check + 1;
if(check%2==0) {
na = na + 1;
}
else {
nb = nb + 1;
}
sig=(x[i]-x[i-1])/(x[i+na*1]-x[i-nb*1]);
}
p=sig*y2[i-1]+2.0; //storage of the decomposed
y2[i]=(sig-1.0)/p; // factors.
u[i]=(y[i+1]-y[i])/(x[i+1]-x[i]) - (y[i]-y[i-1])/(x[i]-x[i-1]);
u[i]=(6.0*u[i]/(x[i+1]-x[i-1])-sig*u[i-1])/p;
if(((float)(x[i+1]-x[i])==(float)0.0) || ((float)(x[i]-x[i-1])==(float)0.0)) {
na = 0;
nb = 0;
check = 0;
while((float)(x[i+na*1]-x[i-nb])==(float)(0.0) || ((float)(x[i+na]-x[i-nb*1])==(float)0.0)) {
check = check + 1;
if(check%2==0) {
na = na + 1;
}
else {
nb = nb + 1;
}
}
u[i]=(y[i+1]-y[i])/(x[i+na*1]-x[i-nb]) - (y[i]-y[i-1])/(x[i+na]-x[i-nb*1]);
u[i]=(6.0*u[i]/(x[i+na*1]-x[i-nb*1])-sig*u[i-1])/p;
}
}
if (ypn > 0.99e30) //The upper boundary condition is set either to be "natural"
qn=un=0.0;
else { //or else to have a specified first derivative.
qn=0.5;
un=(3.0/(x[n]-x[n-1]))*(ypn-(y[n]-y[n-1])/(x[n]-x[n-1]));
}
y2[n]=(un-qn*u[n-1])/(qn*y2[n-1]+1.0);
for (k=n-1;k>=1;k--) { //This is the backsubstitution loop of the tridiagonal
y2[k]=y2[k]*y2[k+1]+u[k]; //algorithm.
}
free_vector(u,1,n-1);
}
void splint(float xa[], float ya[], float y2a[], int n, float x, float *y)
/*Given the arrays xa[1..n] and ya[1..n], which tabulate a function (with the xai's in order),
and given the array y2a[1..n], which is the output from spline above, and given a value of
x, this routine returns a cubic-spline interpolated value y.*/
{
void nrerror(char error_text[]);
int klo,khi,k;
float h,b,a;
klo=1; // We will find the right place in the table by means of
khi=n; //bisection. This is optimal if sequential calls to this
while (khi-klo > 1) { //routine are at random values of x. If sequential calls
k=(khi+klo) >> 1; //are in order, and closely spaced, one would do better
if (xa[k] > x) khi=k; //to store previous values of klo and khi and test if
else klo=k; //they remain appropriate on the next call.
} // klo and khi now bracket the input value of x.
h=xa[khi]-xa[klo];
if (h == 0.0) nrerror("Bad xa input to routine splint"); //The xa's must be distinct.
a=(xa[khi]-x)/h;
b=(x-xa[klo])/h; //Cubic spline polynomial is now evaluated.
*y=a*ya[klo]+b*ya[khi]+((a*a*a-a)*y2a[klo]+(b*b*b-b)*y2a[khi])*(h*h)/6.0;
}
unsigned long *lvector(long nl, long nh)
/* allocate an unsigned long vector with subscript range v[nl..nh] */
{
unsigned long *v;
v = (unsigned long *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(long)));
if(!v) nrerror("allocation failure in lvector()");
return v - nl + NR_END;
}
void free_lvector(unsigned long *v, long nl, long nh)
/* free an unsigned long vector allocated with lvector() */
{
free((FREE_ARG) (v+nl-NR_END));
}
double FgtrlnM_general(double lnM, void *params) {
struct parameters_gsl_int_ vals = *(struct parameters_gsl_int_ *)params;
float z = vals.z_obs;
float M2 = vals.Mval;
float MFeedback = vals.M_Feed;
float alpha = vals.alpha_pl;
float delta1 = vals.del_traj_1;
float delta2 = vals.del_traj_2;
return FgtrConditionalM_second(z,lnM,M2,MFeedback,alpha,delta1,delta2);
}
double FgtrM_general(float z, float M1, float M_Max, float M2, float MFeedback, float alpha, float delta1, float delta2) {
double result, error, lower_limit, upper_limit;
double rel_tol = 0.01;
int size;
size = 1000;
// printf("delta1 = %e Deltac = %e\n",delta1,Deltac);
if((float)delta1==(float)Deltac) {
gsl_function Fx;
gsl_integration_workspace * w = gsl_integration_workspace_alloc (size);
Fx.function = &FgtrlnM_general;
struct parameters_gsl_int_ parameters_gsl_int = {
.z_obs = z,
.Mval = M2,
.M_Feed = MFeedback,
.alpha_pl = alpha,
.del_traj_1 = delta1,
.del_traj_2 = delta2
};
Fx.params = ¶meters_gsl_int;
lower_limit = M1;
upper_limit = M_Max;
// gsl_integration_qag (&Fx, lower_limit, upper_limit, 0, rel_tol, size, GSL_INTEG_GAUSS15, w, &result, &error);
gsl_integration_qag (&Fx, lower_limit, upper_limit, 0, rel_tol, size, GSL_INTEG_GAUSS61, w, &result, &error);
gsl_integration_workspace_free (w);
if(delta2 > delta1) {
return 1.;
}
else {
return result;
}
}
}
float FgtrConditionallnM(float M1, struct parameters_gsl_int_ parameters_gsl_int) {
float z = parameters_gsl_int.z_obs;
float M2 = parameters_gsl_int.Mval;
float MFeedback = parameters_gsl_int.M_Feed;
float alpha = parameters_gsl_int.alpha_pl;
float delta1 = parameters_gsl_int.del_traj_1;
float delta2 = parameters_gsl_int.del_traj_2;
return exp(M1)*pow(exp(M1)/MFeedback,alpha)*dNdM_conditional_second(z,M1,M2,delta1,delta2)/sqrt(2.*PI);
}
float GaussLegengreQuad_Fcoll(int n, float z, float M2, float MFeedback, float alpha, float delta1, float delta2)
{
//Performs the Gauss-Legendre quadrature.
int i;
float integrand,x;
integrand = 0.0;
struct parameters_gsl_int_ parameters_gsl_int = {
.z_obs = z,
.Mval = M2,
.M_Feed = MFeedback,
.alpha_pl = alpha,
.del_traj_1 = delta1,
.del_traj_2 = delta2
};
if(delta2>delta1) {
return 1.;
}
else {
for(i=1;i<(n+1);i++) {
x = xi_low[i];
integrand += wi_low[i]*FgtrConditionallnM(x,parameters_gsl_int);
}
return integrand;
}
}
/*
FUNCTION FgtrM_st(z, M)
Computes the fraction of mass contained in haloes with mass > M at redshift z
Uses Sheth-Torman correction
*/
double dFdlnM_st_PL (double lnM, void *params){
struct parameters_gsl_ST_int_ vals = *(struct parameters_gsl_ST_int_ *)params;
double M = exp(lnM);
float z = vals.z_obs;
float MFeedback = vals.M_Feed;
float alpha = vals.alpha_pl;
return dNdM_st(z, M) * M * M * pow((M/MFeedback),alpha);
}
double FgtrM_st_PL(double z, double Mmin, double MFeedback, double alpha_pl){
double result_lower, result_upper, error, lower_limit, upper_limit;
gsl_function F;
double rel_tol = 0.01; //<- relative tolerance
gsl_integration_workspace * w_lower
= gsl_integration_workspace_alloc (1000);
gsl_integration_workspace * w_upper
= gsl_integration_workspace_alloc (1000);
struct parameters_gsl_ST_int_ parameters_gsl_ST_lower = {
.z_obs = z,
.M_Feed = MFeedback,
.alpha_pl = alpha_pl,
};
F.function = &dFdlnM_st_PL;
F.params = ¶meters_gsl_ST_lower;
lower_limit = log(Mmin);
upper_limit = log(1e16);
gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,
1000, GSL_INTEG_GAUSS61, w_lower, &result_lower, &error);
gsl_integration_workspace_free (w_lower);
return (result_lower) / (OMm*RHOcrit);
}
void initialiseSplinedSigmaM(float M_Min, float M_Max)
{
int i;
float Mass;
Mass_Spline = calloc(NMass,sizeof(float));
Sigma_Spline = calloc(NMass,sizeof(float));
dSigmadm_Spline = calloc(NMass,sizeof(float));
second_derivs_sigma = calloc(NMass,sizeof(float));
second_derivs_dsigma = calloc(NMass,sizeof(float));
printf("Initializing mass spline \n");
for(i=0;i<NMass;i++) {
Mass_Spline[i] = pow(10., log10(M_Min) + (float)i/(NMass-1)*( log10(M_Max) - log10(M_Min) ) );
Sigma_Spline[i] = sigma_z0(Mass_Spline[i]);
dSigmadm_Spline[i] = log10(-dsigmasqdm_z0(Mass_Spline[i]));
}
spline(Mass_Spline-1,Sigma_Spline-1,NMass,0,0,second_derivs_sigma-1);
spline(Mass_Spline-1,dSigmadm_Spline-1,NMass,0,0,second_derivs_dsigma-1);
}
void initialiseGL_Fcoll(int n_low, int n_high, float M_Min, float M_Max)
{
//calculates the weightings and the positions for Gauss-Legendre quadrature.
gauleg(log(M_Min),log(M_Max),xi_low,wi_low,n_low);
gauleg(log(M_Min),log(M_Max),xi_high,wi_high,n_high);
}
void initialiseFcoll_spline(float z, float Mmin, float Mmax, float Mval, float MFeedback, float alphapl)
{
double overdense_val,overdense_small_low,overdense_small_high,overdense_large_low,overdense_large_high;
int i;
overdense_large_high = Deltac;
overdense_large_low = 1.5;
overdense_small_high = 1.5;
overdense_small_low = -1. + 9.e-8;
Fcoll_spline_acc = gsl_interp_accel_alloc ();
Fcoll_spline = gsl_spline_alloc (gsl_interp_cspline, SPLINE_NPTS);
for (i=0;i<SPLINE_NPTS;i++){
overdense_val = log10(1.+overdense_small_low) + (float)i/(SPLINE_NPTS-1.)*(log10(1.+overdense_small_high) - log10(1.+overdense_small_low));
log_Fcoll_spline_table[i] = log10(GaussLegengreQuad_Fcoll(NGLlow,z,log(Mval),MFeedback,alphapl,Deltac,pow(10.,overdense_val)-1.));
Fcoll_spline_params[i] = overdense_val;
if(log_Fcoll_spline_table[i]<-40.) {
log_Fcoll_spline_table[i] = -40.;
}
}
gsl_spline_init(Fcoll_spline, Fcoll_spline_params, log_Fcoll_spline_table, SPLINE_NPTS);
for(i=0;i<Nhigh;i++) {
Overdense_spline_GL_high[i] = overdense_large_low + (float)i/((float)Nhigh-1.)*(overdense_large_high - overdense_large_low);
Fcoll_spline_GL_high[i] = FgtrM_general(z,log(Mmin),log(Mmax),log(Mval),MFeedback,alphapl,Deltac,Overdense_spline_GL_high[i]);
if(Fcoll_spline_GL_high[i]<0.) {
Fcoll_spline_GL_high[i]=pow(10.,-40.0);
}
}
spline(Overdense_spline_GL_high-1,Fcoll_spline_GL_high-1,Nhigh,0,0,second_derivs_high_GL-1);
}
void FcollSpline(float Overdensity, float *splined_value)
{
int i;
float returned_value;
if(Overdensity<1.5) {
if(Overdensity<-1.) {
returned_value = 0;
}
else {
returned_value = gsl_spline_eval(Fcoll_spline, log10(Overdensity+1.), Fcoll_spline_acc);
returned_value = pow(10.,returned_value);
}
}
else {
if(Overdensity<Deltac) {
splint(Overdense_spline_GL_high-1,Fcoll_spline_GL_high-1,second_derivs_high_GL-1,(int)Nhigh,Overdensity,&(returned_value));
}
else {
returned_value = 1.;
}
}
*splined_value = returned_value;
}
#endif
| {
"alphanum_fraction": 0.6357531007,
"avg_line_length": 34.8371069182,
"ext": "c",
"hexsha": "38bb9b2f8a04e9bc4060d300282b7b180a9060e2",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-12-08T17:16:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-11-14T13:54:46.000Z",
"max_forks_repo_head_hexsha": "14c053c301a7f10081071e815281f9c3879efa6b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JulianBMunoz/21cmvFAST",
"max_forks_repo_path": "public_21CMvFAST_MC/Cosmo_c_files/ps.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "14c053c301a7f10081071e815281f9c3879efa6b",
"max_issues_repo_issues_event_max_datetime": "2019-12-18T19:59:55.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-17T05:27:25.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "JulianBMunoz/21cmvFAST",
"max_issues_repo_path": "public_21CMvFAST_MC/Cosmo_c_files/ps.c",
"max_line_length": 238,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "14c053c301a7f10081071e815281f9c3879efa6b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JulianBMunoz/21cmvFAST",
"max_stars_repo_path": "public_21CMvFAST_MC/Cosmo_c_files/ps.c",
"max_stars_repo_stars_event_max_datetime": "2020-11-15T03:29:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-04-18T11:31:34.000Z",
"num_tokens": 18928,
"size": 55391
} |
#include <petsc/private/pcimpl.h> /*I "petscpc.h" I*/
#include <petsc.h>
#include <petsc/private/hashmapi.h>
#include <petscsf.h>
#include <libssc.h>
PetscLogEvent PC_Patch_CreatePatches, PC_Patch_ComputeOp, PC_Patch_Solve, PC_Patch_Scatter, PC_Patch_Apply, PC_Patch_Prealloc;
static PetscBool PCPatchPackageInitialized = PETSC_FALSE;
PETSC_EXTERN PetscErrorCode PCPatchInitializePackage(void)
{
PetscErrorCode ierr;
PetscFunctionBegin;
if (PCPatchPackageInitialized) PetscFunctionReturn(0);
PCPatchPackageInitialized = PETSC_TRUE;
ierr = PCRegister("patch", PCCreate_PATCH); CHKERRQ(ierr);
ierr = PetscLogEventRegister("PCPATCHCreate", PC_CLASSID, &PC_Patch_CreatePatches); CHKERRQ(ierr);
ierr = PetscLogEventRegister("PCPATCHComputeOp", PC_CLASSID, &PC_Patch_ComputeOp); CHKERRQ(ierr);
ierr = PetscLogEventRegister("PCPATCHSolve", PC_CLASSID, &PC_Patch_Solve); CHKERRQ(ierr);
ierr = PetscLogEventRegister("PCPATCHApply", PC_CLASSID, &PC_Patch_Apply); CHKERRQ(ierr);
ierr = PetscLogEventRegister("PCPATCHScatter", PC_CLASSID, &PC_Patch_Scatter); CHKERRQ(ierr);
ierr = PetscLogEventRegister("PCPATCHPrealloc", PC_CLASSID, &PC_Patch_Prealloc); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
typedef struct {
PetscSF defaultSF;
PetscSection *dofSection;
PetscSection cellCounts;
PetscSection cellNumbering; /* Numbering of cells in DM */
PetscSection gtolCounts; /* Indices to extract from local to
* patch vectors */
PetscInt nsubspaces; /* for mixed problems */
PetscInt *subspaceOffsets; /* offsets for calculating concatenated numbering for mixed spaces */
PetscSection bcCounts;
IS cells;
IS dofs;
IS ghostBcNodes;
IS globalBcNodes;
IS gtol;
PetscBool save_operators; /* Save all operators (or create/destroy one at a time?) */
PetscBool partition_of_unity; /* Weight updates by dof multiplicity? */
PetscBool multiplicative; /* Gauss-Seidel or Jacobi? */
PetscInt npatch; /* Number of patches */
PetscInt *bs; /* block size (can come from global
* operators?) */
PetscInt *nodesPerCell;
PetscInt totalDofsPerCell;
const PetscInt **cellNodeMap; /* Map from cells to nodes */
KSP *ksp; /* Solvers for each patch */
Vec localX, localY;
Vec dof_weights; /* In how many patches does each dof lie? */
Vec *patchX, *patchY; /* Work vectors for patches */
Vec *patch_dof_weights;
Mat *mat; /* Operators */
MatType sub_mat_type;
PetscErrorCode (*usercomputeop)(PC, Mat, PetscInt, const PetscInt *, PetscInt, const PetscInt *, void *);
void *usercomputectx;
PetscErrorCode (*patchconstructop)(void*, DM, PetscInt, PetscHMapI); /* patch construction */
PetscInt codim; /* dimension or codimension of entities to loop over; */
PetscInt dim; /* only one of them can be set */
PetscInt exclude_subspace; /* If you don't want any other dofs from a particular subspace you can exclude them with this.
Used for Vanka in Stokes, for example, to eliminate all pressure dofs not on the vertex
you're building the patch around */
PetscInt vankadim; /* In Vanka construction, should we eliminate any entities of a certain dimension? */
PetscBool print_patches; /* Should we print out information about patch construction? */
PetscBool symmetrise_sweep; /* Should we sweep forwards->backwards, backwards->forwards? */
IS *userIS;
IS iterationSet; /* Index set specifying how we iterate over patches */
PetscInt nuserIS; /* user-specified index sets to specify the patches */
PetscBool user_patches;
PetscErrorCode (*userpatchconstructionop)(PC, PetscInt*, IS**, IS*, void* ctx);
void *userpatchconstructctx;
} PC_PATCH;
PETSC_EXTERN PetscErrorCode PCPatchSetSaveOperators(PC pc, PetscBool flg)
{
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscFunctionBegin;
patch->save_operators = flg;
PetscFunctionReturn(0);
}
PETSC_EXTERN PetscErrorCode PCPatchSetPartitionOfUnity(PC pc, PetscBool flg)
{
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscFunctionBegin;
patch->partition_of_unity = flg;
PetscFunctionReturn(0);
}
static PetscErrorCode PCPatchCreateDefaultSF_Private(PC pc, PetscInt n, const PetscSF *sf, const PetscInt *bs)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscFunctionBegin;
if (n == 1 && bs[0] == 1) {
patch->defaultSF = sf[0];
ierr = PetscObjectReference((PetscObject)patch->defaultSF); CHKERRQ(ierr);
} else {
PetscInt allRoots = 0, allLeaves = 0;
PetscInt leafOffset = 0;
PetscInt *ilocal = NULL;
PetscSFNode *iremote = NULL;
PetscInt *remoteOffsets = NULL;
PetscInt index = 0;
PetscHMapI rankToIndex;
PetscInt numRanks = 0;
PetscSFNode *remote = NULL;
PetscSF rankSF;
PetscInt *ranks = NULL;
PetscInt *offsets = NULL;
MPI_Datatype contig;
PetscHMapI ht;
/* First figure out how many dofs there are in the concatenated numbering.
* allRoots: number of owned global dofs;
* allLeaves: number of visible dofs (global + ghosted).
*/
for ( PetscInt i = 0; i < n; i++ ) {
PetscInt nroots, nleaves;
ierr = PetscSFGetGraph(sf[i], &nroots, &nleaves, NULL, NULL); CHKERRQ(ierr);
allRoots += nroots * bs[i];
allLeaves += nleaves * bs[i];
}
ierr = PetscMalloc1(allLeaves, &ilocal); CHKERRQ(ierr);
ierr = PetscMalloc1(allLeaves, &iremote); CHKERRQ(ierr);
/* Now build an SF that just contains process connectivity. */
PetscHMapICreate(&ht);
for (PetscInt i = 0; i < n; i++ ) {
PetscInt nranks;
const PetscMPIInt *ranks = NULL;
ierr = PetscSFSetUp(sf[i]); CHKERRQ(ierr);
ierr = PetscSFGetRanks(sf[i], &nranks, &ranks, NULL, NULL, NULL); CHKERRQ(ierr);
/* These are all the ranks who communicate with me. */
for (PetscInt j = 0; j < nranks; j++) {
PetscHMapISet(ht, (PetscInt)ranks[j], 0);
}
}
PetscHMapIGetSize(ht, &numRanks); CHKERRQ(ierr);
ierr = PetscMalloc1(numRanks, &remote); CHKERRQ(ierr);
ierr = PetscMalloc1(numRanks, &ranks); CHKERRQ(ierr);
ierr = PetscHMapIGetKeys(ht, &index, ranks); CHKERRQ(ierr);
PetscHMapICreate(&rankToIndex);
for (PetscInt i = 0; i < numRanks; i++) {
remote[i].rank = ranks[i];
remote[i].index = 0;
PetscHMapISet(rankToIndex, ranks[i], i);
}
ierr = PetscFree(ranks); CHKERRQ(ierr);
PetscHMapIDestroy(&ht);
ierr = PetscSFCreate(PetscObjectComm((PetscObject)pc), &rankSF); CHKERRQ(ierr);
ierr = PetscSFSetGraph(rankSF, 1, numRanks, NULL, PETSC_OWN_POINTER, remote, PETSC_OWN_POINTER); CHKERRQ(ierr);
ierr = PetscSFSetUp(rankSF); CHKERRQ(ierr);
/* OK, use it to communicate the root offset on the remote
* processes for each subspace. */
ierr = PetscMalloc1(n, &offsets); CHKERRQ(ierr);
ierr = PetscMalloc1(n*numRanks, &remoteOffsets); CHKERRQ(ierr);
offsets[0] = 0;
for (PetscInt i = 1; i < n; i++) {
PetscInt nroots;
ierr = PetscSFGetGraph(sf[i-1], &nroots, NULL, NULL, NULL); CHKERRQ(ierr);
offsets[i] = offsets[i-1] + nroots*bs[i-1];
}
/* Offsets are the offsets on the current process of the
* global dof numbering for the subspaces. */
ierr = MPI_Type_contiguous(n, MPIU_INT, &contig); CHKERRQ(ierr);
ierr = MPI_Type_commit(&contig); CHKERRQ(ierr);
ierr = PetscSFBcastBegin(rankSF, contig, offsets, remoteOffsets); CHKERRQ(ierr);
ierr = PetscSFBcastEnd(rankSF, contig, offsets, remoteOffsets); CHKERRQ(ierr);
ierr = MPI_Type_free(&contig); CHKERRQ(ierr);
ierr = PetscFree(offsets); CHKERRQ(ierr);
ierr = PetscSFDestroy(&rankSF); CHKERRQ(ierr);
/* Now remoteOffsets contains the offsets on the remote
* processes who communicate with me. So now we can
* concatenate the list of SFs into a single one. */
index = 0;
for ( PetscInt i = 0; i < n; i++ ) {
PetscInt nroots, nleaves;
const PetscInt *local = NULL;
const PetscSFNode *remote = NULL;
ierr = PetscSFGetGraph(sf[i], &nroots, &nleaves, &local, &remote); CHKERRQ(ierr);
for ( PetscInt j = 0; j < nleaves; j++ ) {
PetscInt rank = remote[j].rank;
PetscInt idx, rootOffset;
PetscHMapIGet(rankToIndex, rank, &idx);
if (idx == -1) {
SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Didn't find rank, huh?");
}
/* Offset on given rank for ith subspace */
rootOffset = remoteOffsets[n*idx + i];
for ( PetscInt k = 0; k < bs[i]; k++ ) {
ilocal[index] = (local ? local[j] : j)*bs[i] + k + leafOffset;
iremote[index].rank = remote[j].rank;
iremote[index].index = remote[j].index*bs[i] + k + rootOffset;
++index;
}
}
leafOffset += nleaves * bs[i];
}
PetscHMapIDestroy(&rankToIndex);
ierr = PetscFree(remoteOffsets); CHKERRQ(ierr);
ierr = PetscSFCreate(PetscObjectComm((PetscObject)pc), &patch->defaultSF); CHKERRQ(ierr);
ierr = PetscSFSetGraph(patch->defaultSF, allRoots, allLeaves, ilocal, PETSC_OWN_POINTER, iremote, PETSC_OWN_POINTER); CHKERRQ(ierr);
}
PetscFunctionReturn(0);
}
PETSC_EXTERN PetscErrorCode PCPatchSetCellNumbering(PC pc, PetscSection cellNumbering)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscFunctionBegin;
patch->cellNumbering = cellNumbering;
ierr = PetscObjectReference((PetscObject)cellNumbering); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PETSC_EXTERN PetscErrorCode PCPatchSetDiscretisationInfo(PC pc, PetscInt nsubspaces,
DM *dms,
PetscInt *bs,
PetscInt *nodesPerCell,
const PetscInt **cellNodeMap,
const PetscInt *subspaceOffsets,
PetscInt numGhostBcs,
const PetscInt *ghostBcNodes,
PetscInt numGlobalBcs,
const PetscInt *globalBcNodes)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscSF *sfs;
PetscFunctionBegin;
ierr = PetscMalloc1(nsubspaces, &sfs); CHKERRQ(ierr);
ierr = PetscMalloc1(nsubspaces, &patch->dofSection); CHKERRQ(ierr);
ierr = PetscMalloc1(nsubspaces, &patch->bs); CHKERRQ(ierr);
ierr = PetscMalloc1(nsubspaces, &patch->nodesPerCell); CHKERRQ(ierr);
ierr = PetscMalloc1(nsubspaces, &patch->cellNodeMap); CHKERRQ(ierr);
ierr = PetscMalloc1(nsubspaces+1, &patch->subspaceOffsets); CHKERRQ(ierr);
patch->nsubspaces = nsubspaces;
patch->totalDofsPerCell = 0;
for (int i = 0; i < nsubspaces; i++) {
ierr = DMGetDefaultSection(dms[i], &patch->dofSection[i]); CHKERRQ(ierr);
ierr = PetscObjectReference((PetscObject)patch->dofSection[i]); CHKERRQ(ierr);
patch->bs[i] = bs[i];
patch->nodesPerCell[i] = nodesPerCell[i];
patch->totalDofsPerCell += nodesPerCell[i]*bs[i];
patch->cellNodeMap[i] = cellNodeMap[i];
patch->subspaceOffsets[i] = subspaceOffsets[i];
ierr = DMGetDefaultSF(dms[i], &sfs[i]); CHKERRQ(ierr);
}
ierr = PCPatchCreateDefaultSF_Private(pc, nsubspaces, sfs, patch->bs); CHKERRQ(ierr);
ierr = PetscFree(sfs); CHKERRQ(ierr);
patch->subspaceOffsets[nsubspaces] = subspaceOffsets[nsubspaces];
ierr = ISCreateGeneral(PETSC_COMM_SELF, numGhostBcs, ghostBcNodes, PETSC_COPY_VALUES, &patch->ghostBcNodes); CHKERRQ(ierr);
ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalBcs, globalBcNodes, PETSC_COPY_VALUES, &patch->globalBcNodes); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PETSC_EXTERN PetscErrorCode PCPatchSetSubMatType(PC pc, MatType sub_mat_type)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscFunctionBegin;
if (patch->sub_mat_type) {
ierr = PetscFree(patch->sub_mat_type); CHKERRQ(ierr);
}
ierr = PetscStrallocpy(sub_mat_type, (char **)&patch->sub_mat_type); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PETSC_EXTERN PetscErrorCode PCPatchSetComputeOperator(PC pc, PetscErrorCode (*func)(PC, Mat, PetscInt,
const PetscInt *,
PetscInt,
const PetscInt *,
void *),
void *ctx)
{
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscFunctionBegin;
/* User op can assume matrix is zeroed */
patch->usercomputeop = func;
patch->usercomputectx = ctx;
PetscFunctionReturn(0);
}
PETSC_EXTERN PetscErrorCode PCPatchSetUserPatchConstructionOperator(PC pc, PetscErrorCode (*func)(PC, PetscInt*, IS**, IS*, void*), void* ctx)
{
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscFunctionBegin;
patch->userpatchconstructionop = func;
patch->userpatchconstructctx = ctx;
PetscFunctionReturn(0);
}
/* On entry, ht contains the topological entities whose dofs we are responsible for solving for;
on exit, cht contains all the topological entities we need to compute their residuals.
In full generality this should incorporate knowledge of the sparsity pattern of the matrix;
here we assume a standard FE sparsity pattern.*/
static PetscErrorCode PCPatchCompleteCellPatch(DM dm, PetscHMapI ht, PetscHMapI cht)
{
PetscErrorCode ierr;
PetscHashIter hi;
PetscInt entity;
PetscInt *star = NULL, *closure = NULL;
PetscFunctionBegin;
PetscHMapIClear(cht);
PetscHashIterBegin(ht, hi);
while (!PetscHashIterAtEnd(ht, hi)) {
PetscInt starSize, closureSize;
PetscHashIterGetKey(ht, hi, entity);
PetscHashIterNext(ht, hi);
/* Loop over all the cells that this entity connects to */
ierr = DMPlexGetTransitiveClosure(dm, entity, PETSC_FALSE, &starSize, &star); CHKERRQ(ierr);
for ( PetscInt si = 0; si < starSize; si++ ) {
PetscInt ownedentity = star[2*si];
/* now loop over all entities in the closure of that cell */
ierr = DMPlexGetTransitiveClosure(dm, ownedentity, PETSC_TRUE, &closureSize, &closure); CHKERRQ(ierr);
for ( PetscInt ci = 0; ci < closureSize; ci++ ) {
PetscInt seenentity = closure[2*ci];
PetscHMapISet(cht, seenentity, 0);
}
}
}
/* Only restore work arrays at very end. */
if (closure) {
ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_TRUE, NULL, &closure); CHKERRQ(ierr);
}
if (star) {
ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_FALSE, NULL, &star); CHKERRQ(ierr);
}
PetscFunctionReturn(0);
}
/* Given a hash table with a set of topological entities (pts), compute the degrees of
freedom in global concatenated numbering on those entities.
For Vanka smoothing, this needs to do something special: ignore dofs of the
constraint subspace on entities that aren't the base entity we're building the patch
around. */
static PetscErrorCode PCPatchGetPointDofs(PC_PATCH *patch, PetscHMapI pts, PetscHMapI dofs, PetscInt base, PetscInt exclude_subspace)
{
PetscErrorCode ierr;
PetscInt ldof, loff;
PetscHashIter hi;
PetscInt p;
PetscFunctionBegin;
PetscHMapIClear(dofs);
for ( PetscInt k = 0; k < patch->nsubspaces; k++ ) {
PetscSection dofSection = patch->dofSection[k];
PetscInt bs = patch->bs[k];
PetscInt subspaceOffset = patch->subspaceOffsets[k];
if (k == exclude_subspace) {
/* only get this subspace dofs at the base entity, not any others */
ierr = PetscSectionGetDof(dofSection, base, &ldof); CHKERRQ(ierr);
ierr = PetscSectionGetOffset(dofSection, base, &loff); CHKERRQ(ierr);
if (0 == ldof) continue;
for ( PetscInt j = loff; j < ldof + loff; j++ ) {
for ( PetscInt l = 0; l < bs; l++ ) {
PetscInt dof = bs*j + l + subspaceOffset;
PetscHMapISet(dofs, dof, 0);
}
}
continue; /* skip the other dofs of this subspace */
}
PetscHashIterBegin(pts, hi);
while (!PetscHashIterAtEnd(pts, hi)) {
PetscHashIterGetKey(pts, hi, p);
PetscHashIterNext(pts, hi);
ierr = PetscSectionGetDof(dofSection, p, &ldof); CHKERRQ(ierr);
ierr = PetscSectionGetOffset(dofSection, p, &loff); CHKERRQ(ierr);
if (0 == ldof) continue;
for ( PetscInt j = loff; j < ldof + loff; j++ ) {
for ( PetscInt l = 0; l < bs; l++ ) {
PetscInt dof = bs*j + l + subspaceOffset;
PetscHMapISet(dofs, dof, 0);
}
}
}
}
PetscFunctionReturn(0);
}
/* Given two hash tables A and B, compute the keys in B that are not in A, and
put them in C */
static PetscErrorCode PCPatchComputeSetDifference(PetscHMapI A, PetscHMapI B, PetscHMapI C)
{
PetscHashIter hi;
PetscInt key;
PetscBool flg;
PetscFunctionBegin;
PetscHMapIClear(C);
PetscHashIterBegin(B, hi);
while (!PetscHashIterAtEnd(B, hi)) {
PetscHashIterGetKey(B, hi, key);
PetscHashIterNext(B, hi);
PetscHMapIHas(A, key, &flg);
if (!flg) {
PetscHMapISet(C, key, 0);
}
}
PetscFunctionReturn(0);
}
/*
* PCPatchCreateCellPatches - create patches.
*
* Input Parameters:
* + dm - The DMPlex object defining the mesh
*
* Output Parameters:
* + cellCounts - Section with counts of cells around each vertex
* - cells - IS of the cell point indices of cells in each patch
*/
static PetscErrorCode PCPatchCreateCellPatches(PC pc)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
DM dm;
DMLabel ghost;
PetscInt pStart, pEnd, vStart, vEnd, cStart, cEnd;
PetscBool flg;
PetscInt *cellsArray = NULL;
PetscInt numCells;
PetscSection cellCounts;
PetscHMapI ht;
PetscHMapI cht;
PetscFunctionBegin;
/* Used to keep track of the cells in the patch. */
PetscHMapICreate(&ht);
PetscHMapICreate(&cht);
ierr = PCGetDM(pc, &dm); CHKERRQ(ierr);
if (!dm) {
SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, "DM not yet set on patch PC\n");
}
ierr = PetscObjectTypeCompare((PetscObject)dm, DMPLEX, &flg); CHKERRQ(ierr);
if (!flg) {
SETERRQ(PetscObjectComm((PetscObject)pc), PETSC_ERR_ARG_WRONGSTATE, "DM on patch PC must be DMPlex\n");
}
ierr = DMPlexGetChart(dm, &pStart, &pEnd); CHKERRQ(ierr);
ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd); CHKERRQ(ierr);
if (patch->user_patches) {
/* compute patch->nuserIS, patch->userIS here */
ierr = patch->userpatchconstructionop(pc, &patch->nuserIS, &patch->userIS, &patch->iterationSet, patch->userpatchconstructctx); CHKERRQ(ierr);
vStart = 0;
vEnd = patch->nuserIS;
} else if (patch->codim < 0) { /* codim unset */
if (patch->dim < 0) { /* dim unset */
ierr = DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd); CHKERRQ(ierr);
} else { /* dim set */
ierr = DMPlexGetDepthStratum(dm, patch->dim, &vStart, &vEnd); CHKERRQ(ierr);
}
} else { /* codim set */
ierr = DMPlexGetHeightStratum(dm, patch->codim, &vStart, &vEnd); CHKERRQ(ierr);
}
/* These labels mark the owned points. We only create patches
* around points that this process owns. */
ierr = DMGetLabel(dm, "pyop2_ghost", &ghost); CHKERRQ(ierr);
ierr = DMLabelCreateIndex(ghost, pStart, pEnd); CHKERRQ(ierr);
ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->cellCounts); CHKERRQ(ierr);
cellCounts = patch->cellCounts;
ierr = PetscSectionSetChart(cellCounts, vStart, vEnd); CHKERRQ(ierr);
/* Count cells in the patch surrounding each entity */
for ( PetscInt v = vStart; v < vEnd; v++ ) {
PetscHashIter hi;
PetscInt chtSize;
if (!patch->user_patches) {
ierr = DMLabelHasPoint(ghost, v, &flg); CHKERRQ(ierr);
/* Not an owned entity, don't make a cell patch. */
if (flg) {
continue;
}
}
ierr = patch->patchconstructop((void*)patch, dm, v, ht); CHKERRQ(ierr);
ierr = PCPatchCompleteCellPatch(dm, ht, cht);
PetscHMapIGetSize(cht, &chtSize);
if (chtSize == 0) {
/* empty patch, continue */
continue;
}
PetscHashIterBegin(cht, hi); /* safe because size(cht) > 0 from above */
while (!PetscHashIterAtEnd(cht, hi)) {
PetscInt entity;
PetscHashIterGetKey(cht, hi, entity);
if (cStart <= entity && entity < cEnd) {
ierr = PetscSectionAddDof(cellCounts, v, 1); CHKERRQ(ierr);
}
PetscHashIterNext(cht, hi);
}
}
ierr = DMLabelDestroyIndex(ghost); CHKERRQ(ierr);
ierr = PetscSectionSetUp(cellCounts); CHKERRQ(ierr);
ierr = PetscSectionGetStorageSize(cellCounts, &numCells); CHKERRQ(ierr);
ierr = PetscMalloc1(numCells, &cellsArray); CHKERRQ(ierr);
/* Now that we know how much space we need, run through again and
* actually remember the cells. */
for ( PetscInt v = vStart; v < vEnd; v++ ) {
PetscInt ndof, off;
PetscHashIter hi;
ierr = PetscSectionGetDof(cellCounts, v, &ndof); CHKERRQ(ierr);
ierr = PetscSectionGetOffset(cellCounts, v, &off); CHKERRQ(ierr);
if ( ndof <= 0 ) {
continue;
}
ierr = patch->patchconstructop((void*)patch, dm, v, ht); CHKERRQ(ierr);
ierr = PCPatchCompleteCellPatch(dm, ht, cht);
ndof = 0;
PetscHashIterBegin(cht, hi);
while (!PetscHashIterAtEnd(cht, hi)) {
PetscInt entity;
PetscHashIterGetKey(cht, hi, entity);
if (cStart <= entity && entity < cEnd) {
cellsArray[ndof + off] = entity;
ndof++;
}
PetscHashIterNext(cht, hi);
}
}
ierr = ISCreateGeneral(PETSC_COMM_SELF, numCells, cellsArray, PETSC_OWN_POINTER, &patch->cells); CHKERRQ(ierr);
ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd); CHKERRQ(ierr);
patch->npatch = pEnd - pStart;
PetscHMapIDestroy(&ht);
PetscHMapIDestroy(&cht);
PetscFunctionReturn(0);
}
/*
* PCPatchCreateCellPatchDiscretisationInfo - Build the dof maps for cell patches
*
* Input Parameters:
* + dm - The DMPlex object defining the mesh
* . cellCounts - Section with counts of cells around each vertex
* . cells - IS of the cell point indices of cells in each patch
* . cellNumbering - Section mapping plex cell points to Firedrake cell indices.
* . nodesPerCell - number of nodes per cell.
* - cellNodeMap - map from cells to node indices (nodesPerCell * numCells)
*
* Output Parameters:
* + dofs - IS of local dof numbers of each cell in the patch
* . gtolCounts - Section with counts of dofs per cell patch
* - gtol - IS mapping from global dofs to local dofs for each patch.
*/
static PetscErrorCode PCPatchCreateCellPatchDiscretisationInfo(PC pc)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscSection cellCounts = patch->cellCounts;
PetscSection gtolCounts;
IS cells = patch->cells;
PetscSection cellNumbering = patch->cellNumbering;
PetscInt numCells;
PetscInt numDofs;
PetscInt numGlobalDofs;
PetscInt totalDofsPerCell = patch->totalDofsPerCell;
PetscInt vStart, vEnd;
const PetscInt *cellsArray;
PetscInt *newCellsArray = NULL;
PetscInt *dofsArray = NULL;
PetscInt *asmArray = NULL;
PetscInt *globalDofsArray = NULL;
PetscInt globalIndex = 0;
PetscHMapI ht;
PetscHMapI globalBcs;
DM dm = NULL;
const PetscInt *bcNodes = NULL;
PetscInt numBcs;
PetscHMapI ownedpts, seenpts, owneddofs, seendofs, artificialbcs;
PetscHashIter hi;
PetscFunctionBegin;
ierr = PCGetDM(pc, &dm); CHKERRQ(ierr);
/* dofcounts section is cellcounts section * dofPerCell */
ierr = PetscSectionGetStorageSize(cellCounts, &numCells); CHKERRQ(ierr);
numDofs = numCells * totalDofsPerCell;
ierr = PetscMalloc1(numDofs, &dofsArray); CHKERRQ(ierr);
ierr = PetscMalloc1(numDofs, &asmArray); CHKERRQ(ierr);
ierr = PetscMalloc1(numCells, &newCellsArray); CHKERRQ(ierr);
ierr = PetscSectionGetChart(cellCounts, &vStart, &vEnd); CHKERRQ(ierr);
ierr = PetscSectionCreate(PETSC_COMM_SELF, &patch->gtolCounts); CHKERRQ(ierr);
gtolCounts = patch->gtolCounts;
ierr = PetscSectionSetChart(gtolCounts, vStart, vEnd); CHKERRQ(ierr);
/* Outside the patch loop, get the dofs that are globally-enforced Dirichlet
conditions */
PetscHMapICreate(&globalBcs);
ierr = ISGetIndices(patch->ghostBcNodes, &bcNodes); CHKERRQ(ierr);
ierr = ISGetSize(patch->ghostBcNodes, &numBcs); CHKERRQ(ierr);
for ( PetscInt i = 0; i < numBcs; i++ ) {
PetscHMapISet(globalBcs, bcNodes[i], 0); /* these are already in concatenated numbering */
}
ierr = ISRestoreIndices(patch->ghostBcNodes, &bcNodes); CHKERRQ(ierr);
/* HMap tables for artificial BC construction */
PetscHMapICreate(&ownedpts);
PetscHMapICreate(&seenpts);
PetscHMapICreate(&owneddofs);
PetscHMapICreate(&seendofs);
PetscHMapICreate(&artificialbcs);
ierr = ISGetIndices(cells, &cellsArray); CHKERRQ(ierr);
PetscHMapICreate(&ht);
for ( PetscInt v = vStart; v < vEnd; v++ ) {
PetscInt dof, off;
PetscInt localIndex = 0;
PetscHMapIClear(ht);
ierr = PetscSectionGetDof(cellCounts, v, &dof); CHKERRQ(ierr);
ierr = PetscSectionGetOffset(cellCounts, v, &off); CHKERRQ(ierr);
if ( dof <= 0 ) continue;
/* Calculate the global numbers of the artificial BC dofs here first */
ierr = patch->patchconstructop((void*)patch, dm, v, ownedpts); CHKERRQ(ierr);
ierr = PCPatchCompleteCellPatch(dm, ownedpts, seenpts); CHKERRQ(ierr);
ierr = PCPatchGetPointDofs(patch, ownedpts, owneddofs, v, patch->exclude_subspace); CHKERRQ(ierr);
ierr = PCPatchGetPointDofs(patch, seenpts, seendofs, v, -1); CHKERRQ(ierr);
ierr = PCPatchComputeSetDifference(owneddofs, seendofs, artificialbcs); CHKERRQ(ierr);
if (patch->print_patches) {
PetscHMapI globalbcdofs;
PetscHMapICreate(&globalbcdofs);
MPI_Comm comm = PetscObjectComm((PetscObject)pc);
ierr = PetscSynchronizedPrintf(comm, "Patch %d: owned dofs:\n", v); CHKERRQ(ierr);
PetscHashIterBegin(owneddofs, hi);
while (!PetscHashIterAtEnd(owneddofs, hi)) {
PetscInt globalDof;
PetscHashIterGetKey(owneddofs, hi, globalDof);
PetscHashIterNext(owneddofs, hi);
ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
}
ierr = PetscSynchronizedPrintf(comm, "\n"); CHKERRQ(ierr);
ierr = PetscSynchronizedPrintf(comm, "Patch %d: seen dofs:\n", v); CHKERRQ(ierr);
PetscHashIterBegin(seendofs, hi);
while (!PetscHashIterAtEnd(seendofs, hi)) {
PetscInt globalDof;
PetscBool flg;
PetscHashIterGetKey(seendofs, hi, globalDof);
PetscHashIterNext(seendofs, hi);
ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
PetscHMapIHas(globalBcs, globalDof, &flg);
if (flg) {
PetscHMapISet(globalbcdofs, globalDof, 0);
}
}
ierr = PetscSynchronizedPrintf(comm, "\n"); CHKERRQ(ierr);
ierr = PetscSynchronizedPrintf(comm, "Patch %d: global BCs:\n", v); CHKERRQ(ierr);
PetscHMapIGetSize(globalbcdofs, &numBcs);
if (numBcs > 0) {
PetscHashIterBegin(globalbcdofs, hi);
while (!PetscHashIterAtEnd(globalbcdofs, hi)) {
PetscInt globalDof;
PetscHashIterGetKey(globalbcdofs, hi, globalDof);
PetscHashIterNext(globalbcdofs, hi);
ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
}
}
ierr = PetscSynchronizedPrintf(comm, "\n"); CHKERRQ(ierr);
ierr = PetscSynchronizedPrintf(comm, "Patch %d: artificial BCs:\n", v); CHKERRQ(ierr);
PetscHMapIGetSize(artificialbcs, &numBcs);
if (numBcs > 0) {
PetscHashIterBegin(artificialbcs, hi);
while (!PetscHashIterAtEnd(artificialbcs, hi)) {
PetscInt globalDof;
PetscHashIterGetKey(artificialbcs, hi, globalDof);
PetscHashIterNext(artificialbcs, hi);
ierr = PetscSynchronizedPrintf(comm, "%d ", globalDof); CHKERRQ(ierr);
}
}
ierr = PetscSynchronizedPrintf(comm, "\n\n"); CHKERRQ(ierr);
PetscHMapIDestroy(&globalbcdofs);
}
for ( PetscInt k = 0; k < patch->nsubspaces; k++ ) {
PetscInt nodesPerCell = patch->nodesPerCell[k];
PetscInt subspaceOffset = patch->subspaceOffsets[k];
const PetscInt *cellNodeMap = patch->cellNodeMap[k];
PetscInt bs = patch->bs[k];
for ( PetscInt i = off; i < off + dof; i++ ) {
/* Walk over the cells in this patch. */
const PetscInt c = cellsArray[i];
PetscInt cell;
ierr = PetscSectionGetDof(cellNumbering, c, &cell); CHKERRQ(ierr);
if ( cell <= 0 ) {
SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
"Cell doesn't appear in cell numbering map");
}
ierr = PetscSectionGetOffset(cellNumbering, c, &cell); CHKERRQ(ierr);
newCellsArray[i] = cell;
for ( PetscInt j = 0; j < nodesPerCell; j++ ) {
/* For each global dof, map it into contiguous local storage. */
const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + subspaceOffset;
/* finally, loop over block size */
for ( PetscInt l = 0; l < bs; l++ ) {
PetscInt localDof, isGlobalBcDof, isArtificialBcDof;
/* first, check if this is either a globally enforced or locally enforced BC dof */
PetscHMapIGet(globalBcs, globalDof + l, &isGlobalBcDof);
PetscHMapIGet(artificialbcs, globalDof + l, &isArtificialBcDof);
/* if it's either, don't ever give it a local dof number */
if (isGlobalBcDof >= 0 || isArtificialBcDof >= 0) {
dofsArray[globalIndex++] = -1; /* don't use this in assembly in this patch */
} else {
PetscHMapIGet(ht, globalDof + l, &localDof);
if (localDof == -1) {
localDof = localIndex++;
PetscHMapISet(ht, globalDof + l, localDof);
}
if ( globalIndex >= numDofs ) {
SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
"Found more dofs than expected");
}
/* And store. */
dofsArray[globalIndex++] = localDof;
}
}
}
}
}
PetscHMapIGetSize(ht, &dof);
/* How many local dofs in this patch? */
ierr = PetscSectionSetDof(gtolCounts, v, dof); CHKERRQ(ierr);
}
if (globalIndex != numDofs) {
SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
"Expected number of dofs (%d) doesn't match found number (%d)",
numDofs, globalIndex);
}
ierr = PetscSectionSetUp(gtolCounts); CHKERRQ(ierr);
ierr = PetscSectionGetStorageSize(gtolCounts, &numGlobalDofs); CHKERRQ(ierr);
ierr = PetscMalloc1(numGlobalDofs, &globalDofsArray); CHKERRQ(ierr);
/* Now populate the global to local map. This could be merged
* into the above loop if we were willing to deal with reallocs. */
PetscInt key = 0;
PetscInt asmKey = 0;
for ( PetscInt v = vStart; v < vEnd; v++ ) {
PetscInt dof, off;
PetscHashIter hi;
PetscHMapIClear(ht);
ierr = PetscSectionGetDof(cellCounts, v, &dof); CHKERRQ(ierr);
ierr = PetscSectionGetOffset(cellCounts, v, &off); CHKERRQ(ierr);
if ( dof <= 0 ) continue;
for ( PetscInt k = 0; k < patch->nsubspaces; k++ ) {
PetscInt nodesPerCell = patch->nodesPerCell[k];
PetscInt subspaceOffset = patch->subspaceOffsets[k];
const PetscInt *cellNodeMap = patch->cellNodeMap[k];
PetscInt bs = patch->bs[k];
for ( PetscInt i = off; i < off + dof; i++ ) {
/* Reconstruct mapping of global-to-local on this patch. */
const PetscInt c = cellsArray[i];
PetscInt cell;
ierr = PetscSectionGetOffset(cellNumbering, c, &cell); CHKERRQ(ierr);
for ( PetscInt j = 0; j < nodesPerCell; j++ ) {
for ( PetscInt l = 0; l < bs; l++ ) {
const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + subspaceOffset + l;
const PetscInt localDof = dofsArray[key++];
if (localDof >= 0) PetscHMapISet(ht, globalDof, localDof);
}
}
}
/* Shove it in the output data structure. */
PetscInt goff;
ierr = PetscSectionGetOffset(gtolCounts, v, &goff); CHKERRQ(ierr);
PetscHashIterBegin(ht, hi);
while (!PetscHashIterAtEnd(ht, hi)) {
PetscInt globalDof, localDof;
PetscHashIterGetKey(ht, hi, globalDof);
PetscHashIterGetVal(ht, hi, localDof);
if (globalDof >= 0) {
globalDofsArray[goff + localDof] = globalDof;
}
PetscHashIterNext(ht, hi);
}
}
/* At this point, we have a hash table ht built that maps globalDof -> localDof.
We need to create the dof table laid out cellwise first, then by subspace,
as the assembler assembles cell-wise and we need to stuff the different
contributions of the different function spaces to the right places. So we loop
over cells, then over subspaces. */
if (patch->nsubspaces > 1) { /* for nsubspaces = 1, data we need is already in dofsArray */
for (PetscInt i = off; i < off + dof; i++ ) {
const PetscInt c = cellsArray[i];
PetscInt cell;
ierr = PetscSectionGetOffset(cellNumbering, c, &cell); CHKERRQ(ierr);
for ( PetscInt k = 0; k < patch->nsubspaces; k++ ) {
PetscInt nodesPerCell = patch->nodesPerCell[k];
PetscInt subspaceOffset = patch->subspaceOffsets[k];
const PetscInt *cellNodeMap = patch->cellNodeMap[k];
PetscInt bs = patch->bs[k];
for ( PetscInt j = 0; j < nodesPerCell; j++ ) {
for ( PetscInt l = 0; l < bs; l++ ) {
const PetscInt globalDof = cellNodeMap[cell*nodesPerCell + j]*bs + subspaceOffset + l;
PetscInt localDof;
PetscHMapIGet(ht, globalDof, &localDof);
/* If it's not in the hash table, i.e. is a BC dof,
then the PetscHMapIGet above gives -1, which matches
exactly the convention for PETSc's matrix assembly to
ignore the dof. So we don't need to do anything here */
asmArray[asmKey++] = localDof;
}
}
}
}
}
}
if (1 == patch->nsubspaces) { /* replace with memcpy? */
for (PetscInt i = 0; i < numDofs; i++) {
asmArray[i] = dofsArray[i];
}
}
PetscHMapIDestroy(&ht);
ierr = ISRestoreIndices(cells, &cellsArray);
ierr = PetscFree(dofsArray); CHKERRQ(ierr);
/* Replace cell indices with firedrake-numbered ones. */
ierr = ISGeneralSetIndices(cells, numCells, (const PetscInt *)newCellsArray, PETSC_OWN_POINTER); CHKERRQ(ierr);
ierr = ISCreateGeneral(PETSC_COMM_SELF, numGlobalDofs, globalDofsArray, PETSC_OWN_POINTER, &patch->gtol); CHKERRQ(ierr);
ierr = ISCreateGeneral(PETSC_COMM_SELF, numDofs, asmArray, PETSC_OWN_POINTER, &patch->dofs); CHKERRQ(ierr);
PetscHMapIDestroy(&artificialbcs);
PetscHMapIDestroy(&seendofs);
PetscHMapIDestroy(&owneddofs);
PetscHMapIDestroy(&seenpts);
PetscHMapIDestroy(&ownedpts);
PetscHMapIDestroy(&globalBcs);
ierr = ISDestroy(&patch->ghostBcNodes); CHKERRQ(ierr); /* memory optimisation */
PetscFunctionReturn(0);
}
static PetscErrorCode PCReset_PATCH(PC pc)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscInt i;
PetscFunctionBegin;
ierr = PetscSFDestroy(&patch->defaultSF); CHKERRQ(ierr);
ierr = PetscSectionDestroy(&patch->cellCounts); CHKERRQ(ierr);
ierr = PetscSectionDestroy(&patch->cellNumbering); CHKERRQ(ierr);
ierr = PetscSectionDestroy(&patch->gtolCounts); CHKERRQ(ierr);
ierr = PetscSectionDestroy(&patch->bcCounts); CHKERRQ(ierr);
ierr = ISDestroy(&patch->gtol); CHKERRQ(ierr);
ierr = ISDestroy(&patch->cells); CHKERRQ(ierr);
ierr = ISDestroy(&patch->dofs); CHKERRQ(ierr);
ierr = ISDestroy(&patch->ghostBcNodes); CHKERRQ(ierr);
ierr = ISDestroy(&patch->globalBcNodes); CHKERRQ(ierr);
if (patch->dofSection) {
for (i = 0; i < patch->nsubspaces; i++) {
ierr = PetscSectionDestroy(&patch->dofSection[i]); CHKERRQ(ierr);
}
}
ierr = PetscFree(patch->dofSection); CHKERRQ(ierr);
ierr = PetscFree(patch->bs); CHKERRQ(ierr);
ierr = PetscFree(patch->nodesPerCell); CHKERRQ(ierr);
ierr = PetscFree(patch->cellNodeMap); CHKERRQ(ierr);
ierr = PetscFree(patch->subspaceOffsets); CHKERRQ(ierr);
if (patch->ksp) {
for ( i = 0; i < patch->npatch; i++ ) {
ierr = KSPReset(patch->ksp[i]); CHKERRQ(ierr);
}
}
ierr = VecDestroy(&patch->localX); CHKERRQ(ierr);
ierr = VecDestroy(&patch->localY); CHKERRQ(ierr);
if (patch->patchX) {
for ( i = 0; i < patch->npatch; i++ ) {
ierr = VecDestroy(patch->patchX + i); CHKERRQ(ierr);
}
ierr = PetscFree(patch->patchX); CHKERRQ(ierr);
}
if (patch->patchY) {
for ( i = 0; i < patch->npatch; i++ ) {
ierr = VecDestroy(patch->patchY + i); CHKERRQ(ierr);
}
ierr = PetscFree(patch->patchY); CHKERRQ(ierr);
}
if (patch->partition_of_unity) {
ierr = VecDestroy(&patch->dof_weights); CHKERRQ(ierr);
}
if (patch->patch_dof_weights) {
for ( i = 0; i < patch->npatch; i++ ) {
ierr = VecDestroy(patch->patch_dof_weights + i); CHKERRQ(ierr);
}
ierr = PetscFree(patch->patch_dof_weights); CHKERRQ(ierr);
}
if (patch->mat) {
for ( i = 0; i < patch->npatch; i++ ) {
ierr = MatDestroy(patch->mat + i); CHKERRQ(ierr);
}
ierr = PetscFree(patch->mat); CHKERRQ(ierr);
}
ierr = PetscFree(patch->sub_mat_type); CHKERRQ(ierr);
patch->bs = 0;
patch->cellNodeMap = NULL;
if (patch->user_patches) {
for ( PetscInt i = 0; i < patch->nuserIS; i++ ) {
ierr = ISDestroy(&patch->userIS[i]); CHKERRQ(ierr);
}
PetscFree(patch->userIS);
patch->nuserIS = 0;
}
if (patch->iterationSet) {
ierr = ISDestroy(&patch->iterationSet); CHKERRQ(ierr);
}
PetscFunctionReturn(0);
}
static PetscErrorCode PCDestroy_PATCH(PC pc)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscInt i;
PetscFunctionBegin;
ierr = PCReset_PATCH(pc); CHKERRQ(ierr);
if (patch->ksp) {
for ( i = 0; i < patch->npatch; i++ ) {
ierr = KSPDestroy(&patch->ksp[i]); CHKERRQ(ierr);
}
ierr = PetscFree(patch->ksp); CHKERRQ(ierr);
}
ierr = PetscFree(pc->data); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static PetscErrorCode PCPatchZeroMatrix_Private(Mat mat, const PetscInt ncell,
const PetscInt ndof,
const PetscInt *dof)
{
const PetscScalar *values = NULL;
PetscInt rows;
PetscErrorCode ierr;
PetscFunctionBegin;
ierr = PetscCalloc1(ndof*ndof, &values); CHKERRQ(ierr);
for (PetscInt c = 0; c < ncell; c++) {
const PetscInt *idx = &dof[ndof*c];
ierr = MatSetValues(mat, ndof, idx, ndof, idx, values, INSERT_VALUES); CHKERRQ(ierr);
}
ierr = MatGetLocalSize(mat, &rows, NULL); CHKERRQ(ierr);
for (PetscInt i = 0; i < rows; i++) {
ierr = MatSetValues(mat, 1, &i, 1, &i, values, INSERT_VALUES); CHKERRQ(ierr);
}
ierr = MatAssemblyBegin(mat, MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = MatAssemblyEnd(mat, MAT_FINAL_ASSEMBLY); CHKERRQ(ierr);
ierr = PetscFree(values); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static PetscErrorCode PCPatchCreateMatrix(PC pc, PetscInt which, Mat *mat)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscInt csize, rsize;
Vec x, y;
PetscBool flg;
const char *prefix = NULL;
PetscFunctionBegin;
x = patch->patchX[which];
y = patch->patchY[which];
ierr = VecGetSize(x, &csize); CHKERRQ(ierr);
ierr = VecGetSize(y, &rsize); CHKERRQ(ierr);
ierr = MatCreate(PETSC_COMM_SELF, mat); CHKERRQ(ierr);
ierr = PCGetOptionsPrefix(pc, &prefix); CHKERRQ(ierr);
ierr = MatSetOptionsPrefix(*mat, prefix); CHKERRQ(ierr);
ierr = MatAppendOptionsPrefix(*mat, "sub_"); CHKERRQ(ierr);
if (patch->sub_mat_type) {
ierr = MatSetType(*mat, patch->sub_mat_type); CHKERRQ(ierr);
}
ierr = MatSetSizes(*mat, rsize, csize, rsize, csize); CHKERRQ(ierr);
ierr = PetscObjectTypeCompare((PetscObject)*mat, MATDENSE, &flg); CHKERRQ(ierr);
if (!flg) {
ierr = PetscObjectTypeCompare((PetscObject)*mat, MATSEQDENSE, &flg); CHKERRQ(ierr);
}
if (!flg) {
PetscBT bt;
PetscInt *dnnz = NULL;
const PetscInt *dofsArray = NULL;
PetscInt pStart, pEnd, ncell, offset;
ierr = ISGetIndices(patch->dofs, &dofsArray); CHKERRQ(ierr);
ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd); CHKERRQ(ierr);
which += pStart;
if (which >= pEnd) {
SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Asked for operator index is invalid\n"); CHKERRQ(ierr);
}
ierr = PetscSectionGetDof(patch->cellCounts, which, &ncell); CHKERRQ(ierr);
ierr = PetscSectionGetOffset(patch->cellCounts, which, &offset); CHKERRQ(ierr);
ierr = PetscMalloc1(rsize, &dnnz); CHKERRQ(ierr);
for (PetscInt i = 0; i < rsize; i++) {
dnnz[i] = 0;
}
ierr = PetscLogEventBegin(PC_Patch_Prealloc, pc, 0, 0, 0); CHKERRQ(ierr);
/* XXX: This uses N^2 bits to store the sparsity pattern on a
* patch. This is probably OK if the patches are not too big,
* but could use quite a bit of memory for planes in 3D.
* Should we switch based on the value of rsize to a
* hash-table (slower, but more memory efficient) approach? */
ierr = PetscBTCreate(rsize*rsize, &bt); CHKERRQ(ierr);
for (PetscInt c = 0; c < ncell; c++) {
const PetscInt *idx = dofsArray + (offset + c)*patch->totalDofsPerCell;
for (PetscInt i = 0; i < patch->totalDofsPerCell; i++) {
const PetscInt row = idx[i];
if (row < 0) continue;
for (PetscInt j = 0; j < patch->totalDofsPerCell; j++) {
const PetscInt col = idx[j];
const PetscInt key = row*rsize + col;
if (col < 0) continue;
if (!PetscBTLookupSet(bt, key)) {
++dnnz[row];
}
}
}
}
PetscBTDestroy(&bt);
ierr = MatXAIJSetPreallocation(*mat, 1, dnnz, NULL, NULL, NULL); CHKERRQ(ierr);
ierr = PetscFree(dnnz); CHKERRQ(ierr);
ierr = PCPatchZeroMatrix_Private(*mat, ncell, patch->totalDofsPerCell,
&dofsArray[offset*patch->totalDofsPerCell]); CHKERRQ(ierr);
ierr = PetscLogEventEnd(PC_Patch_Prealloc, pc, 0, 0, 0); CHKERRQ(ierr);
ierr = ISRestoreIndices(patch->dofs, &dofsArray); CHKERRQ(ierr);
}
ierr = MatSetUp(*mat); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static PetscErrorCode PCPatchComputeOperator(PC pc, Mat mat, Mat multMat, PetscInt which)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
const PetscInt *dofsArray;
const PetscInt *cellsArray;
PetscInt ncell, offset, pStart, pEnd;
PetscFunctionBegin;
ierr = PetscLogEventBegin(PC_Patch_ComputeOp, pc, 0, 0, 0); CHKERRQ(ierr);
if (!patch->usercomputeop) {
SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call PCPatchSetComputeOperator() to set user callback\n");
}
ierr = ISGetIndices(patch->dofs, &dofsArray); CHKERRQ(ierr);
ierr = ISGetIndices(patch->cells, &cellsArray); CHKERRQ(ierr);
ierr = PetscSectionGetChart(patch->cellCounts, &pStart, &pEnd); CHKERRQ(ierr);
which += pStart;
if (which >= pEnd) {
SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Asked for operator index is invalid\n"); CHKERRQ(ierr);
}
ierr = PetscSectionGetDof(patch->cellCounts, which, &ncell); CHKERRQ(ierr);
ierr = PetscSectionGetOffset(patch->cellCounts, which, &offset); CHKERRQ(ierr);
if ( ncell <= 0 ) {
ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PetscStackPush("PCPatch user callback");
ierr = patch->usercomputeop(pc, mat, ncell, cellsArray + offset, ncell*patch->totalDofsPerCell, dofsArray + offset*patch->totalDofsPerCell, patch->usercomputectx); CHKERRQ(ierr);
PetscStackPop;
ierr = ISRestoreIndices(patch->dofs, &dofsArray); CHKERRQ(ierr);
ierr = ISRestoreIndices(patch->cells, &cellsArray); CHKERRQ(ierr);
ierr = PetscLogEventEnd(PC_Patch_ComputeOp, pc, 0, 0, 0); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static PetscErrorCode PCPatch_ScatterLocal_Private(PC pc, PetscInt p,
Vec x, Vec y,
InsertMode mode,
ScatterMode scat)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
const PetscScalar *xArray = NULL;
PetscScalar *yArray = NULL;
const PetscInt *gtolArray = NULL;
PetscInt offset, size;
PetscFunctionBeginHot;
ierr = PetscLogEventBegin(PC_Patch_Scatter, pc, 0, 0, 0); CHKERRQ(ierr);
ierr = VecGetArrayRead(x, &xArray); CHKERRQ(ierr);
ierr = VecGetArray(y, &yArray); CHKERRQ(ierr);
ierr = PetscSectionGetDof(patch->gtolCounts, p, &size); CHKERRQ(ierr);
ierr = PetscSectionGetOffset(patch->gtolCounts, p, &offset); CHKERRQ(ierr);
ierr = ISGetIndices(patch->gtol, >olArray); CHKERRQ(ierr);
if (mode == INSERT_VALUES && scat != SCATTER_FORWARD) {
SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Can't insert if not scattering forward\n");
}
if (mode == ADD_VALUES && scat != SCATTER_REVERSE) {
SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Can't add if not scattering reverse\n");
}
for ( PetscInt lidx = 0; lidx < size; lidx++ ) {
const PetscInt gidx = gtolArray[lidx + offset];
if (mode == INSERT_VALUES) {
yArray[lidx] = xArray[gidx];
} else {
yArray[gidx] += xArray[lidx];
}
}
ierr = VecRestoreArrayRead(x, &xArray); CHKERRQ(ierr);
ierr = VecRestoreArray(y, &yArray); CHKERRQ(ierr);
ierr = ISRestoreIndices(patch->gtol, >olArray); CHKERRQ(ierr);
ierr = PetscLogEventEnd(PC_Patch_Scatter, pc, 0, 0, 0); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static PetscErrorCode PCSetUp_PATCH(PC pc)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
const char *prefix;
PetscInt pStart;
PetscFunctionBegin;
if (!pc->setupcalled) {
PetscInt pStart, pEnd;
PetscInt localSize;
ierr = PetscLogEventBegin(PC_Patch_CreatePatches, pc, 0, 0, 0); CHKERRQ(ierr);
localSize = patch->subspaceOffsets[patch->nsubspaces];
ierr = VecCreateSeq(PETSC_COMM_SELF, localSize, &patch->localX); CHKERRQ(ierr);
ierr = VecSetUp(patch->localX); CHKERRQ(ierr);
ierr = VecDuplicate(patch->localX, &patch->localY); CHKERRQ(ierr);
ierr = PCPatchCreateCellPatches(pc); CHKERRQ(ierr);
ierr = PCPatchCreateCellPatchDiscretisationInfo(pc); CHKERRQ(ierr);
/* OK, now build the work vectors */
ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, &pEnd); CHKERRQ(ierr);
ierr = PetscMalloc1(patch->npatch, &patch->patchX); CHKERRQ(ierr);
ierr = PetscMalloc1(patch->npatch, &patch->patchY); CHKERRQ(ierr);
for ( PetscInt i = pStart; i < pEnd; i++ ) {
PetscInt dof;
ierr = PetscSectionGetDof(patch->gtolCounts, i, &dof); CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchX[i - pStart]); CHKERRQ(ierr);
ierr = VecSetUp(patch->patchX[i - pStart]); CHKERRQ(ierr);
ierr = VecCreateSeq(PETSC_COMM_SELF, dof, &patch->patchY[i - pStart]); CHKERRQ(ierr);
ierr = VecSetUp(patch->patchY[i - pStart]); CHKERRQ(ierr);
}
ierr = PetscMalloc1(patch->npatch, &patch->ksp); CHKERRQ(ierr);
ierr = PCGetOptionsPrefix(pc, &prefix); CHKERRQ(ierr);
for ( PetscInt i = 0; i < patch->npatch; i++ ) {
ierr = KSPCreate(PETSC_COMM_SELF, patch->ksp + i); CHKERRQ(ierr);
ierr = PetscObjectIncrementTabLevel((PetscObject)patch->ksp[i], (PetscObject)pc, 1); CHKERRQ(ierr);
ierr = KSPSetOptionsPrefix(patch->ksp[i], prefix); CHKERRQ(ierr);
ierr = KSPAppendOptionsPrefix(patch->ksp[i], "sub_"); CHKERRQ(ierr);
}
if (patch->save_operators) {
ierr = PetscMalloc1(patch->npatch, &patch->mat); CHKERRQ(ierr);
for ( PetscInt i = 0; i < patch->npatch; i++ ) {
ierr = PCPatchCreateMatrix(pc, i, patch->mat + i); CHKERRQ(ierr);
}
}
ierr = PetscLogEventEnd(PC_Patch_CreatePatches, pc, 0, 0, 0); CHKERRQ(ierr);
}
/* If desired, calculate weights for dof multiplicity */
if (!pc->setupcalled && patch->partition_of_unity) {
Mat P;
Vec local;
const PetscScalar *input = NULL;
PetscScalar *output = NULL;
ierr = PCGetOperators(pc, NULL, &P); CHKERRQ(ierr);
ierr = MatCreateVecs(P, NULL, &patch->dof_weights);
ierr = VecDuplicate(patch->localX, &local); CHKERRQ(ierr);
ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, NULL); CHKERRQ(ierr);
for ( PetscInt i = 0; i < patch->npatch; i++ ) {
PetscInt dof;
ierr = PetscSectionGetDof(patch->gtolCounts, i + pStart, &dof); CHKERRQ(ierr);
if ( dof <= 0 ) continue;
ierr = VecSet(patch->patchX[i], 1.0); CHKERRQ(ierr);
/* TODO: Do we need different scatters for X and Y? */
ierr = PCPatch_ScatterLocal_Private(pc, i + pStart,
patch->patchX[i], local,
ADD_VALUES, SCATTER_REVERSE); CHKERRQ(ierr);
}
/* Local to Global */
ierr = VecGetArrayRead(local, &input); CHKERRQ(ierr);
ierr = VecGetArray(patch->dof_weights, &output); CHKERRQ(ierr);
ierr = PetscSFReduceBegin(patch->defaultSF, MPIU_SCALAR, input, output, MPI_SUM); CHKERRQ(ierr);
ierr = PetscSFReduceEnd(patch->defaultSF, MPIU_SCALAR, input, output, MPI_SUM); CHKERRQ(ierr);
ierr = VecRestoreArray(patch->dof_weights, &output); CHKERRQ(ierr);
ierr = VecRestoreArrayRead(local, &input); CHKERRQ(ierr);
ierr = VecReciprocal(patch->dof_weights); CHKERRQ(ierr);
ierr = VecDestroy(&local); CHKERRQ(ierr);
}
if (patch->save_operators) {
for ( PetscInt i = 0; i < patch->npatch; i++ ) {
ierr = MatZeroEntries(patch->mat[i]); CHKERRQ(ierr);
ierr = PCPatchComputeOperator(pc, patch->mat[i], NULL, i); CHKERRQ(ierr);
ierr = KSPSetOperators(patch->ksp[i], patch->mat[i], patch->mat[i]); CHKERRQ(ierr);
}
}
if (!pc->setupcalled) {
for ( PetscInt i = 0; i < patch->npatch; i++ ) {
ierr = KSPSetFromOptions(patch->ksp[i]); CHKERRQ(ierr);
}
}
PetscFunctionReturn(0);
}
static PetscErrorCode PCApply_PATCH(PC pc, Vec x, Vec y)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH *)pc->data;
const PetscScalar *globalX = NULL;
PetscScalar *localX = NULL;
PetscScalar *localY = NULL;
PetscScalar *globalY = NULL;
const PetscInt *bcNodes = NULL;
PetscInt pStart, numBcs, size;
PetscInt nsweep = 1;
PetscInt start[2] = {0, patch->npatch-1};
PetscInt end[2] = {patch->npatch, -1};
const PetscInt inc[2] = {1, -1};
const PetscInt *iterationSet;
PetscFunctionBegin;
ierr = PetscLogEventBegin(PC_Patch_Apply, pc, 0, 0, 0); CHKERRQ(ierr);
ierr = PetscOptionsPushGetViewerOff(PETSC_TRUE); CHKERRQ(ierr);
/* Scatter from global space into overlapped local spaces */
ierr = VecGetArrayRead(x, &globalX); CHKERRQ(ierr);
ierr = VecGetArray(patch->localX, &localX); CHKERRQ(ierr);
ierr = PetscSFBcastBegin(patch->defaultSF, MPIU_SCALAR, globalX, localX); CHKERRQ(ierr);
ierr = PetscSFBcastEnd(patch->defaultSF, MPIU_SCALAR, globalX, localX); CHKERRQ(ierr);
ierr = VecRestoreArrayRead(x, &globalX); CHKERRQ(ierr);
ierr = VecRestoreArray(patch->localX, &localX); CHKERRQ(ierr);
if (patch->user_patches) {
ierr = ISGetLocalSize(patch->iterationSet, &end[0]); CHKERRQ(ierr);
start[1] = end[0] - 1;
ierr = ISGetIndices(patch->iterationSet, &iterationSet); CHKERRQ(ierr);
}
ierr = VecSet(patch->localY, 0.0); CHKERRQ(ierr);
ierr = PetscSectionGetChart(patch->gtolCounts, &pStart, NULL); CHKERRQ(ierr);
if (patch->symmetrise_sweep) {
nsweep = 2;
} else {
nsweep = 1;
}
for (PetscInt sweep = 0; sweep < nsweep; sweep++) {
for ( PetscInt j = start[sweep]; j*inc[sweep] < end[sweep]*inc[sweep]; j += inc[sweep] ) {
PetscInt start, len, i;
Mat multMat = NULL;
if (patch->user_patches) {
i = iterationSet[j];
} else {
i = j;
}
ierr = PetscSectionGetDof(patch->gtolCounts, i + pStart, &len); CHKERRQ(ierr);
ierr = PetscSectionGetOffset(patch->gtolCounts, i + pStart, &start); CHKERRQ(ierr);
if ( len <= 0 ) {
/* TODO: Squash out these guys in the setup as well. */
continue;
}
ierr = PCPatch_ScatterLocal_Private(pc, i + pStart,
patch->localX, patch->patchX[i],
INSERT_VALUES,
SCATTER_FORWARD); CHKERRQ(ierr);
if (!patch->save_operators) {
Mat mat;
ierr = PCPatchCreateMatrix(pc, i, &mat); CHKERRQ(ierr);
/* Populate operator here. */
ierr = PCPatchComputeOperator(pc, mat, multMat, i); CHKERRQ(ierr);
ierr = KSPSetOperators(patch->ksp[i], mat, mat);
/* Drop reference so the KSPSetOperators below will blow it away. */
ierr = MatDestroy(&mat); CHKERRQ(ierr);
}
ierr = PetscLogEventBegin(PC_Patch_Solve, pc, 0, 0, 0); CHKERRQ(ierr);
ierr = KSPSolve(patch->ksp[i], patch->patchX[i], patch->patchY[i]); CHKERRQ(ierr);
ierr = PetscLogEventEnd(PC_Patch_Solve, pc, 0, 0, 0); CHKERRQ(ierr);
if (!patch->save_operators) {
PC pc;
ierr = KSPSetOperators(patch->ksp[i], NULL, NULL); CHKERRQ(ierr);
ierr = KSPGetPC(patch->ksp[i], &pc); CHKERRQ(ierr);
/* Destroy PC context too, otherwise the factored matrix hangs around. */
ierr = PCReset(pc); CHKERRQ(ierr);
}
ierr = PCPatch_ScatterLocal_Private(pc, i + pStart,
patch->patchY[i], patch->localY,
ADD_VALUES, SCATTER_REVERSE); CHKERRQ(ierr);
}
}
if (patch->user_patches) {
ierr = ISRestoreIndices(patch->iterationSet, &iterationSet); CHKERRQ(ierr);
}
/* Now patch->localY contains the solution of the patch solves, so
* we need to combine them all. */
ierr = VecSet(y, 0.0); CHKERRQ(ierr);
ierr = VecGetArray(y, &globalY); CHKERRQ(ierr);
ierr = VecGetArrayRead(patch->localY, (const PetscScalar **)&localY); CHKERRQ(ierr);
ierr = PetscSFReduceBegin(patch->defaultSF, MPIU_SCALAR, localY, globalY, MPI_SUM); CHKERRQ(ierr);
ierr = PetscSFReduceEnd(patch->defaultSF, MPIU_SCALAR, localY, globalY, MPI_SUM); CHKERRQ(ierr);
ierr = VecRestoreArrayRead(patch->localY, (const PetscScalar **)&localY); CHKERRQ(ierr);
/* Now we need to send the global BC values through */
ierr = VecGetArrayRead(x, &globalX); CHKERRQ(ierr);
ierr = ISGetSize(patch->globalBcNodes, &numBcs); CHKERRQ(ierr);
ierr = ISGetIndices(patch->globalBcNodes, &bcNodes); CHKERRQ(ierr);
ierr = VecGetLocalSize(x, &size); CHKERRQ(ierr);
for ( PetscInt i = 0; i < numBcs; i++ ) {
const PetscInt idx = bcNodes[i];
if (idx < size) {
globalY[idx] = globalX[idx];
}
}
ierr = ISRestoreIndices(patch->globalBcNodes, &bcNodes); CHKERRQ(ierr);
ierr = VecRestoreArrayRead(x, &globalX); CHKERRQ(ierr);
ierr = VecRestoreArray(y, &globalY); CHKERRQ(ierr);
if (patch->partition_of_unity) {
/* Now apply partition of unity */
ierr = VecPointwiseMult(y, y, patch->dof_weights); CHKERRQ(ierr);
}
ierr = PetscOptionsPopGetViewerOff(); CHKERRQ(ierr);
ierr = PetscLogEventEnd(PC_Patch_Apply, pc, 0, 0, 0); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static PetscErrorCode PCSetUpOnBlocks_PATCH(PC pc)
{
PC_PATCH *patch = (PC_PATCH*)pc->data;
PetscErrorCode ierr;
PetscInt i;
KSPConvergedReason reason;
PetscFunctionBegin;
PetscFunctionReturn(0);
for (i=0; i<patch->npatch; i++) {
ierr = KSPSetUp(patch->ksp[i]); CHKERRQ(ierr);
ierr = KSPGetConvergedReason(patch->ksp[i], &reason); CHKERRQ(ierr);
if (reason == KSP_DIVERGED_PCSETUP_FAILED) {
pc->failedreason = PC_SUBPC_ERROR;
}
}
PetscFunctionReturn(0);
}
PETSC_EXTERN PetscErrorCode PCPatchConstruct_Star(void *vpatch, DM dm, PetscInt entity, PetscHMapI ht)
{
PetscErrorCode ierr;
PetscInt starSize;
PetscInt *star = NULL;
PetscFunctionBegin;
PetscHMapIClear(ht);
/* To start with, add the entity we care about */
PetscHMapISet(ht, entity, 0);
/* Loop over all the points that this entity connects to */
ierr = DMPlexGetTransitiveClosure(dm, entity, PETSC_FALSE, &starSize, &star); CHKERRQ(ierr);
for ( PetscInt si = 0; si < starSize; si++ ) {
PetscInt pt = star[2*si];
PetscHMapISet(ht, pt, 0);
}
if (star) {
ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_FALSE, NULL, &star); CHKERRQ(ierr);
}
PetscFunctionReturn(0);
}
PETSC_EXTERN PetscErrorCode PCPatchConstruct_Vanka(void *vpatch, DM dm, PetscInt entity, PetscHMapI ht)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH*) vpatch;
PetscInt starSize, closureSize;
PetscInt *star = NULL, *closure = NULL;
PetscInt iStart, iEnd;
PetscInt cStart, cEnd;
PetscBool shouldIgnore;
PetscFunctionBegin;
PetscHMapIClear(ht);
/* To start with, add the entity we care about */
PetscHMapISet(ht, entity, 0);
/* Should we ignore any topological entities of a certain dimension? */
if (patch->vankadim >= 0) {
shouldIgnore = PETSC_TRUE;
ierr = DMPlexGetDepthStratum(dm, patch->vankadim, &iStart, &iEnd); CHKERRQ(ierr);
} else {
shouldIgnore = PETSC_FALSE;
}
ierr = DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd); CHKERRQ(ierr);
/* Loop over all the cells that this entity connects to */
ierr = DMPlexGetTransitiveClosure(dm, entity, PETSC_FALSE, &starSize, &star); CHKERRQ(ierr);
for ( PetscInt si = 0; si < starSize; si++ ) {
PetscInt cell = star[2*si];
if ( cell < cStart || cell >= cEnd) continue;
/* now loop over all entities in the closure of that cell */
ierr = DMPlexGetTransitiveClosure(dm, cell, PETSC_TRUE, &closureSize, &closure); CHKERRQ(ierr);
for ( PetscInt ci = 0; ci < closureSize; ci++ ) {
PetscInt newentity = closure[2*ci];
if (shouldIgnore && iStart <= newentity && newentity < iEnd) {
/* We've been told to ignore entities of this type.*/
continue;
}
PetscHMapISet(ht, newentity, 0);
}
}
if (closure) {
ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_TRUE, NULL, &closure); CHKERRQ(ierr);
}
if (star) {
ierr = DMPlexRestoreTransitiveClosure(dm, 0, PETSC_FALSE, NULL, &star); CHKERRQ(ierr);
}
PetscFunctionReturn(0);
}
/* The user's already set the patches in patch->userIS. Build the hash tables */
PETSC_EXTERN PetscErrorCode PCPatchConstruct_User(void *vpatch, DM dm, PetscInt entity, PetscHMapI ht)
{
PetscErrorCode ierr;
PC_PATCH *patch = (PC_PATCH*) vpatch;
IS patchis = patch->userIS[entity];
PetscInt size;
PetscInt pStart, pEnd;
const PetscInt *patchdata;
PetscFunctionBegin;
PetscHMapIClear(ht);
ierr = DMPlexGetChart(dm, &pStart, &pEnd);
ierr = ISGetLocalSize(patchis, &size); CHKERRQ(ierr);
ierr = ISGetIndices(patchis, &patchdata); CHKERRQ(ierr);
for ( PetscInt i = 0; i < size; i++ ) {
PetscInt ownedentity = patchdata[i];
if (ownedentity < pStart || ownedentity >= pEnd) {
SETERRQ(PetscObjectComm((PetscObject)dm),PETSC_ERR_USER,"Entities need to be between the bounds of DMPlexGetChart()");
}
PetscHMapISet(ht, patchdata[i], 0);
}
ierr = ISRestoreIndices(patchis, &patchdata); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
const char *const PCPatchConstructTypes[] = {"star","vanka","user","python",0};
static PetscErrorCode PCSetFromOptions_PATCH(PetscOptionItems *PetscOptionsObject, PC pc)
{
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscErrorCode ierr;
PetscBool flg, dimflg, codimflg;
char sub_mat_type[256];
PCPatchConstructType patchConstructionType = PC_PATCH_STAR;
PetscFunctionBegin;
ierr = PetscOptionsHead(PetscOptionsObject, "Vertex-patch Additive Schwarz options"); CHKERRQ(ierr);
ierr = PetscOptionsBool("-pc_patch_save_operators", "Store all patch operators for lifetime of PC?",
"PCPatchSetSaveOperators", patch->save_operators, &patch->save_operators, &flg); CHKERRQ(ierr);
ierr = PetscOptionsBool("-pc_patch_partition_of_unity", "Weight contributions by dof multiplicity?",
"PCPatchSetPartitionOfUnity", patch->partition_of_unity, &patch->partition_of_unity, &flg); CHKERRQ(ierr);
ierr = PetscOptionsBool("-pc_patch_multiplicative", "Gauss-Seidel instead of Jacobi?",
"PCPatchSetMultiplicative", patch->multiplicative, &patch->multiplicative, &flg); CHKERRQ(ierr);
if (patch->multiplicative) {
SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_USER,"We've removed multiplicative to do BC condensation (for now)");
}
ierr = PetscOptionsInt("-pc_patch_construction_dim", "What dimension of entity to construct patches by? (0 = vertices)", "PCSetFromOptions_PATCH", patch->dim, &patch->dim, &dimflg);
ierr = PetscOptionsInt("-pc_patch_construction_codim", "What co-dimension of entity to construct patches by? (0 = cells)", "PCSetFromOptions_PATCH", patch->codim, &patch->codim, &codimflg);
if (dimflg && codimflg) {
SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_USER,"Can only set one of dimension or co-dimension");
}
/* XXX: This should be PetscOptionsEnum */
ierr = PetscOptionsEList("-pc_patch_construction_type", "How should the patches be constructed?", "PCSetFromOptions_PATCH", PCPatchConstructTypes, 4, PCPatchConstructTypes[patchConstructionType], (PetscInt *)&patchConstructionType, &flg);
if (flg) {
switch (patchConstructionType) {
case PC_PATCH_STAR:
patch->patchconstructop = PCPatchConstruct_Star;
break;
case PC_PATCH_VANKA:
patch->patchconstructop = PCPatchConstruct_Vanka;
ierr = PetscOptionsInt("-pc_patch_vanka_dim", "Topological dimension of entities for Vanka to ignore", "PCSetFromOptions_PATCH", patch->vankadim, &patch->vankadim, &flg);
ierr = PetscOptionsInt("-pc_patch_vanka_space", "What subspace is the constraint space for Vanka?", "PCSetFromOptions_PATCH", patch->exclude_subspace, &patch->exclude_subspace, &flg);
if (flg) {
SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_USER, "-pc_patch_vanka_space has been renamed to -pc_patch_exclude_subspace");
}
break;
case PC_PATCH_USER:
case PC_PATCH_PYTHON:
patch->user_patches = PETSC_TRUE;
patch->patchconstructop = PCPatchConstruct_User;
break;
default:
SETERRQ(PetscObjectComm((PetscObject)pc),PETSC_ERR_USER,"Unknown patch construction type");
break;
}
}
ierr = PetscOptionsFList("-pc_patch_sub_mat_type", "Matrix type for patch solves", "PCPatchSetSubMatType",MatList, NULL, sub_mat_type, 256, &flg); CHKERRQ(ierr);
if (flg) {
ierr = PCPatchSetSubMatType(pc, sub_mat_type); CHKERRQ(ierr);
}
ierr = PetscOptionsBool("-pc_patch_print_patches", "Print out information during patch construction?",
"PCSetFromOptions_PATCH", patch->print_patches, &patch->print_patches, &flg); CHKERRQ(ierr);
ierr = PetscOptionsBool("-pc_patch_symmetrise_sweep", "Go start->end, end->start?",
"PCSetFromOptions_PATCH", patch->symmetrise_sweep, &patch->symmetrise_sweep, &flg); CHKERRQ(ierr);
ierr = PetscOptionsInt("-pc_patch_exclude_subspace", "What subspace (if any) to exclude in construction?", "PCSetFromOptions_PATCH", patch->exclude_subspace, &patch->exclude_subspace, &flg);
ierr = PetscOptionsTail(); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
static PetscErrorCode PCView_PATCH(PC pc, PetscViewer viewer)
{
PC_PATCH *patch = (PC_PATCH *)pc->data;
PetscErrorCode ierr;
PetscMPIInt rank;
PetscBool isascii;
PetscViewer sviewer;
PetscFunctionBegin;
ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&isascii);CHKERRQ(ierr);
ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)pc),&rank);CHKERRQ(ierr);
if (!isascii) {
PetscFunctionReturn(0);
}
ierr = PetscViewerASCIIPushTab(viewer); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, "Subspace Correction preconditioner with %d patches\n", patch->npatch); CHKERRQ(ierr);
if (patch->multiplicative) {
ierr = PetscViewerASCIIPrintf(viewer, "Schwarz type: multiplicative\n"); CHKERRQ(ierr);
} else {
ierr = PetscViewerASCIIPrintf(viewer, "Schwarz type: additive\n"); CHKERRQ(ierr);
}
if (patch->partition_of_unity) {
ierr = PetscViewerASCIIPrintf(viewer, "Weighting by partition of unity\n"); CHKERRQ(ierr);
} else {
ierr = PetscViewerASCIIPrintf(viewer, "Not weighting by partition of unity\n"); CHKERRQ(ierr);
}
if (patch->symmetrise_sweep) {
ierr = PetscViewerASCIIPrintf(viewer, "Symmetrising sweep (start->end, then end->start)\n"); CHKERRQ(ierr);
} else {
ierr = PetscViewerASCIIPrintf(viewer, "Not symmetrising sweep\n"); CHKERRQ(ierr);
}
if (!patch->save_operators) {
ierr = PetscViewerASCIIPrintf(viewer, "Not saving patch operators (rebuilt every PCApply)\n"); CHKERRQ(ierr);
} else {
ierr = PetscViewerASCIIPrintf(viewer, "Saving patch operators (rebuilt every PCSetUp)\n"); CHKERRQ(ierr);
}
if (patch->patchconstructop == PCPatchConstruct_Star) {
ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: star\n"); CHKERRQ(ierr);
} else if (patch->patchconstructop == PCPatchConstruct_Vanka) {
ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: Vanka\n"); CHKERRQ(ierr);
} else if (patch->patchconstructop == PCPatchConstruct_User) {
ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: user-specified\n"); CHKERRQ(ierr);
} else {
ierr = PetscViewerASCIIPrintf(viewer, "Patch construction operator: unknown\n"); CHKERRQ(ierr);
}
ierr = PetscViewerASCIIPrintf(viewer, "KSP on patches (all same):\n"); CHKERRQ(ierr);
if (patch->ksp) {
ierr = PetscViewerGetSubViewer(viewer, PETSC_COMM_SELF, &sviewer); CHKERRQ(ierr);
if (!rank) {
ierr = PetscViewerASCIIPushTab(sviewer); CHKERRQ(ierr);
ierr = KSPView(patch->ksp[0], sviewer); CHKERRQ(ierr);
ierr = PetscViewerASCIIPopTab(sviewer); CHKERRQ(ierr);
}
ierr = PetscViewerRestoreSubViewer(viewer, PETSC_COMM_SELF, &sviewer); CHKERRQ(ierr);
} else {
ierr = PetscViewerASCIIPushTab(viewer); CHKERRQ(ierr);
ierr = PetscViewerASCIIPrintf(viewer, "KSP not yet set.\n"); CHKERRQ(ierr);
ierr = PetscViewerASCIIPopTab(viewer); CHKERRQ(ierr);
}
ierr = PetscViewerASCIIPopTab(viewer); CHKERRQ(ierr);
PetscFunctionReturn(0);
}
PETSC_EXTERN PetscErrorCode PCCreate_PATCH(PC pc)
{
PetscErrorCode ierr;
PC_PATCH *patch;
PetscFunctionBegin;
ierr = PetscNewLog(pc, &patch); CHKERRQ(ierr);
/* Set some defaults */
patch->sub_mat_type = NULL;
patch->save_operators = PETSC_TRUE;
patch->partition_of_unity = PETSC_FALSE;
patch->multiplicative = PETSC_FALSE;
patch->codim = -1;
patch->dim = -1;
patch->exclude_subspace = -1;
patch->vankadim = -1;
patch->patchconstructop = PCPatchConstruct_Star;
patch->print_patches = PETSC_FALSE;
patch->symmetrise_sweep = PETSC_FALSE;
patch->nuserIS = 0;
patch->userIS = NULL;
patch->iterationSet = NULL;
patch->user_patches = PETSC_FALSE;
pc->data = (void *)patch;
pc->ops->apply = PCApply_PATCH;
pc->ops->applytranspose = 0; /* PCApplyTranspose_PATCH; */
pc->ops->setup = PCSetUp_PATCH;
pc->ops->reset = PCReset_PATCH;
pc->ops->destroy = PCDestroy_PATCH;
pc->ops->setfromoptions = PCSetFromOptions_PATCH;
pc->ops->setuponblocks = PCSetUpOnBlocks_PATCH;
pc->ops->view = PCView_PATCH;
pc->ops->applyrichardson = 0;
PetscFunctionReturn(0);
}
| {
"alphanum_fraction": 0.6019111681,
"avg_line_length": 43.4113557358,
"ext": "c",
"hexsha": "a2294b421bc2c89b2e3cf3b7df3e1b193aa393f1",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2018-01-23T15:21:31.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-01-23T15:21:31.000Z",
"max_forks_repo_head_hexsha": "c56af51286a7dd7f3d98a8087903e3d18ca937cb",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "wence-/ssc",
"max_forks_repo_path": "ssc/libssc.c",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "c56af51286a7dd7f3d98a8087903e3d18ca937cb",
"max_issues_repo_issues_event_max_datetime": "2018-09-27T10:54:59.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-03-05T12:22:54.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "wence-/ssc",
"max_issues_repo_path": "ssc/libssc.c",
"max_line_length": 242,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c56af51286a7dd7f3d98a8087903e3d18ca937cb",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "wence-/ssc",
"max_stars_repo_path": "ssc/libssc.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 19556,
"size": 74928
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#ifdef GSL_FOUND
#include <gsl/gsl_integration.h>
#endif
#include "core_allvars.h"
#include "core_init.h"
#include "core_mymalloc.h"
#include "core_cool_func.h"
/* These functions do not need to be exposed externally */
double integrand_time_to_present(const double a, void *param);
void set_units(struct params *run_params);
void read_snap_list(const int ThisTask, struct params *run_params);
double time_to_present(const double z, struct params *run_params);
#ifdef HDF5
#include "io/io_save_hdf5.h"
#endif
void init(const int ThisTask, struct params *run_params)
{
run_params->Age = mymalloc(ABSOLUTEMAXSNAPS*sizeof(run_params->Age[0]));
set_units(run_params);
read_snap_list(ThisTask, run_params);
//Hack to fix deltaT for snapshot 0
//This way, galsnapnum = -1 will not segfault.
run_params->Age[0] = time_to_present(1000.0, run_params);//lookback time from z=1000
run_params->Age++;
for(int i = 0; i < run_params->Snaplistlen; i++) {
run_params->ZZ[i] = 1 / run_params->AA[i] - 1;
run_params->Age[i] = time_to_present(run_params->ZZ[i], run_params);
}
run_params->a0 = 1.0 / (1.0 + run_params->Reionization_z0);
run_params->ar = 1.0 / (1.0 + run_params->Reionization_zr);
read_cooling_functions();
if(ThisTask == 0) {
printf("cooling functions read\n\n");
}
#if 0
#ifdef HDF5
if(HDF5Output) {
calc_hdf5_props();
}
#endif
#endif
}
void set_units(struct params *run_params)
{
run_params->UnitTime_in_s = run_params->UnitLength_in_cm / run_params->UnitVelocity_in_cm_per_s;
run_params->UnitTime_in_Megayears = run_params->UnitTime_in_s / SEC_PER_MEGAYEAR;
run_params->G = GRAVITY / pow(run_params->UnitLength_in_cm, 3) * run_params->UnitMass_in_g * pow(run_params->UnitTime_in_s, 2);
run_params->UnitDensity_in_cgs = run_params->UnitMass_in_g / pow(run_params->UnitLength_in_cm, 3);
run_params->UnitPressure_in_cgs = run_params->UnitMass_in_g / run_params->UnitLength_in_cm / pow(run_params->UnitTime_in_s, 2);
run_params->UnitCoolingRate_in_cgs = run_params->UnitPressure_in_cgs / run_params->UnitTime_in_s;
run_params->UnitEnergy_in_cgs = run_params->UnitMass_in_g * pow(run_params->UnitLength_in_cm, 2) / pow(run_params->UnitTime_in_s, 2);
run_params->EnergySNcode = run_params->EnergySN / run_params->UnitEnergy_in_cgs * run_params->Hubble_h;
run_params->EtaSNcode = run_params->EtaSN * (run_params->UnitMass_in_g / SOLAR_MASS) / run_params->Hubble_h;
// convert some physical input parameters to internal units
run_params->Hubble = HUBBLE * run_params->UnitTime_in_s;
// compute a few quantitites
run_params->RhoCrit = 3.0 * run_params->Hubble * run_params->Hubble / (8 * M_PI * run_params->G);
}
void read_snap_list(const int ThisTask, struct params *run_params)
{
char fname[MAX_STRING_LEN+1];
snprintf(fname, MAX_STRING_LEN, "%s", run_params->FileWithSnapList);
FILE *fd = fopen(fname, "r");
if(fd == NULL) {
printf("can't read output list in file '%s'\n", fname);
ABORT(0);
}
run_params->Snaplistlen = 0;
do {
if(fscanf(fd, " %lg ", &(run_params->AA[run_params->Snaplistlen])) == 1) {
run_params->Snaplistlen++;
} else {
break;
}
} while(run_params->Snaplistlen < run_params->MAXSNAPS);
fclose(fd);
if(ThisTask == 0) {
printf("found %d defined times in snaplist\n", run_params->Snaplistlen);
}
}
double time_to_present(const double z, struct params *run_params)
{
const double end_limit = 1.0;
const double start_limit = 1.0/(1 + z);
double result=0.0;
#ifdef GSL_FOUND
#define WORKSIZE 1000
gsl_function F;
gsl_integration_workspace *workspace;
double abserr;
workspace = gsl_integration_workspace_alloc(WORKSIZE);
F.function = &integrand_time_to_present;
F.params = run_params;
gsl_integration_qag(&F, start_limit, end_limit, 1.0 / run_params->Hubble,
1.0e-9, WORKSIZE, GSL_INTEG_GAUSS21, workspace, &result, &abserr);
gsl_integration_workspace_free(workspace);
#undef WORKSIZE
#else
/* Do not have GSL - let's integrate numerically ourselves */
const double step = 1e-7;
const int64_t nsteps = (end_limit - start_limit)/step;
result = 0.0;
const double y0 = integrand_time_to_present(start_limit + 0*step, run_params);
const double yn = integrand_time_to_present(start_limit + nsteps*step, run_params);
for(int64_t i=1; i<nsteps; i++) {
result += integrand_time_to_present(start_limit + i*step, run_params);
}
result = (step*0.5)*(y0 + yn + 2.0*result);
#endif
/* convert into Myrs/h (I think -> MS 23/6/2018) */
const double time = 1.0 / run_params->Hubble * result;
// return time to present as a function of redshift
return time;
}
double integrand_time_to_present(const double a, void *param)
{
const struct params *run_params = (struct params *) param;
return 1.0 / sqrt(run_params->Omega / a + (1.0 - run_params->Omega - run_params->OmegaLambda) + run_params->OmegaLambda * a * a);
}
| {
"alphanum_fraction": 0.689810471,
"avg_line_length": 31.1637426901,
"ext": "c",
"hexsha": "c12b90728245858026c266c7cddd3ef1905a4120",
"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": "de7040b9eee3c437fc129828bb64bd835be64ae2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "manodeep/lfs_sage",
"max_forks_repo_path": "src/core_init.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "de7040b9eee3c437fc129828bb64bd835be64ae2",
"max_issues_repo_issues_event_max_datetime": "2021-06-23T02:16:53.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-02-13T10:57:27.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "manodeep/lfs_sage",
"max_issues_repo_path": "src/core_init.c",
"max_line_length": 137,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "de7040b9eee3c437fc129828bb64bd835be64ae2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "manodeep/lfs_sage",
"max_stars_repo_path": "src/core_init.c",
"max_stars_repo_stars_event_max_datetime": "2021-04-22T03:19:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-22T03:19:14.000Z",
"num_tokens": 1506,
"size": 5329
} |
#ifndef COMUTILS_H
#define COMUTILS_H
#include "HypCommands.h" // RECORD_LENGTH
#include <gsl/gsl-lite.hpp> // gsl::span
#include <array>
#include <functional>
#include <memory>
#include <stdint.h>
#include <string>
#include <vector>
#include <QObject>
#include <QString>
QT_USE_NAMESPACE
class SerialPort;
#define val const auto
//------------------------------------------------------------------------------
class DeviceLink : public QObject
{
Q_OBJECT
DeviceLink() = delete;
DeviceLink (const DeviceLink&) = delete;
DeviceLink& operator =(const DeviceLink&) = delete;
public:
//enum class DeviceType {
// UNKNOWN = 0,
// LDU, RDU, MDU,
// NUM_TYPES // the last
//};
typedef std::function<void(const QString&)> MsgToDisplayCbk;
typedef std::function<void(const gsl::span<uint8_t>&)> PacketRecvdCbk;
typedef std::function<void()> SeriesEndCbk;
typedef std::function<void(bool)> FinishedCbk;
DeviceLink(MsgToDisplayCbk msgCbk, PacketRecvdCbk packetCbk,
SeriesEndCbk seriesEndCbk, FinishedCbk finishCbk);
void DownloadRecorded(); // returns packets via PacketRecvdCbk
void ClearRecordings();
void UploadToDevice(const std::vector<uint8_t>& data);
Hyperion::DeviceType GetDeviceType() const { return m_deviceType; }
int GetFirmwareVersionX100() const { return m_firmwareVersionX100; }
private:
void DownloadThreadFn();
void ClearThreadFn();
void UploadThreadFn();
std::unique_ptr<SerialPort> EstablishConnection(size_t& port_idx, uint8_t& handshakeReply);
void SendMessage (const QString& msg) const { if (m_messageCbk) m_messageCbk(msg); }
void ReceivePacket(const gsl::span<uint8_t>& p)const { if (m_packetRecvdCbk) m_packetRecvdCbk(p); }
void SendFinished (bool ok) const { if (m_finishCbk) m_finishCbk(ok); }
typedef std::vector<uint8_t> dataVec_t;
template<size_t N> static bool ChecksumOk(const std::array<uint8_t, N>& data) {
size_t sum = 0;
for (size_t i=0; i+1 < N; sum += data[i++]);
return ((sum & 0xFF) == data[N - 1]);
}
//data:
MsgToDisplayCbk m_messageCbk;
PacketRecvdCbk m_packetRecvdCbk;
SeriesEndCbk m_seriesEndCbk;
FinishedCbk m_finishCbk;
std::vector<QString> m_portNames;
Hyperion::DeviceType m_deviceType = Hyperion::UNKNOWN_DEVICE;
int m_firmwareVersionX100 = 0; // unknown
//statics const:
static const std::array<uint8_t,2> HANDSHAKE; // "DZ"
static const std::array<uint8_t,2> START_DOWNLOAD; // "DK"
static const std::array<uint8_t,1> CONTINUE_DOWNLOAD; // 0x01
static const std::array<uint8_t,2> CLEAR_VALUES; // "DE" - not sure what it does...
static const std::array<uint8_t,2> CLEAR_MEMORY; // "DB"
static const std::array<uint8_t,2> GET_FW_VERSION; // "DV"
static const std::array<uint8_t,5> HANDSHAKE_REPLY;
};
//------------------------------------------------------------------------------
#endif // COMUTILS_H
| {
"alphanum_fraction": 0.6027018729,
"avg_line_length": 33.5773195876,
"ext": "h",
"hexsha": "586e83225298149d5207160f3a757e5a8fa688fe",
"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": "105124530364cdf9f625a03046b5edba140c9114",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bsergeev/HyperionEmeter2",
"max_forks_repo_path": "src/ComUtils.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114",
"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": "bsergeev/HyperionEmeter2",
"max_issues_repo_path": "src/ComUtils.h",
"max_line_length": 104,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "105124530364cdf9f625a03046b5edba140c9114",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bsergeev/HyperionEmeter2",
"max_stars_repo_path": "src/ComUtils.h",
"max_stars_repo_stars_event_max_datetime": "2021-04-01T08:01:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-04-01T08:01:08.000Z",
"num_tokens": 825,
"size": 3257
} |
#pragma once
#include <memory>
#include <string>
#include <unordered_map>
#include <DirectXMath.h>
#include <gsl/span>
struct Ray3d;
namespace gfx {
struct Light3d;
struct MdfRenderOverrides;
enum class MaterialPlaceholderSlot;
struct AnimatedModelParams;
using AnimatedModelPtr = std::shared_ptr<class AnimatedModel>;
using MdfRenderMaterialPtr = std::shared_ptr<class MdfRenderMaterial>;
enum class WeaponAnim : int {
None = 0,
RightAttack,
RightAttack2,
RightAttack3,
LeftAttack,
LeftAttack2,
LeftAttack3,
Walk,
Run,
Idle,
FrontHit,
FrontHit2,
FrontHit3,
LeftHit,
LeftHit2,
LeftHit3,
RightHit,
RightHit2,
RightHit3,
BackHit,
BackHit2,
BackHit3,
RightCriticalSwing,
LeftCriticalSwing,
Fidget,
Fidget2,
Fidget3,
Sneak,
Panic,
RightCombatStart,
LeftCombatStart,
CombatIdle,
CombatFidget,
Special1,
Special2,
Special3,
FrontDodge,
RightDodge,
LeftDodge,
BackDodge,
RightThrow,
LeftThrow,
LeftSnatch,
RightSnatch,
LeftTurn,
RightTurn
};
enum class WeaponAnimType : int {
Unarmed = 0,
Dagger,
Sword,
Mace,
Hammer,
Axe,
Club,
Battleaxe,
Greatsword,
Greataxe,
Greathammer,
Spear,
Staff,
Polearm,
Bow,
Crossbow,
Sling,
Shield,
Flail,
Chain,
TwoHandedFlail,
Shuriken,
Monk
};
enum class BardInstrumentType : int {
Flute = 0,
Drum,
Mandolin,
Trumpet,
Harp,
Lute,
Pipers,
Recorder
};
enum class NormalAnimType : int {
Falldown = 0,
ProneIdle,
ProneFidget,
Getup,
Magichands,
Picklock,
PicklockConcentrated,
Examine,
Throw,
Death,
Death2,
Death3,
DeadIdle,
DeadFidget,
DeathProneIdle,
DeathProneFidget,
AbjurationCasting,
AbjurationConjuring,
ConjurationCasting,
ConjurationConjuring,
DivinationCasting,
DivinationConjuring,
EnchantmentCasting,
EnchantmentConjuring,
EvocationCasting,
EvocationConjuring,
IllusionCasting,
IllusionConjuring,
NecromancyCasting,
NecromancyConjuring,
TransmutationCasting,
TransmutationConjuring,
Conceal,
ConcealIdle,
Unconceal,
ItemIdle,
ItemFidget,
Open,
Close,
SkillAnimalEmpathy,
SkillDisableDevice,
SkillHeal,
SkillHealConcentrated,
SkillHide,
SkillHideIdle,
SkillHideFidget,
SkillUnhide,
SkillPickpocket,
SkillSearch,
SkillSpot,
FeatTrack,
Trip,
Bullrush,
Flurry,
Kistrike,
Tumble,
Special1,
Special2,
Special3,
Special4,
Throw2,
WandAbjurationCasting,
WandAbjurationConjuring,
WandConjurationCasting,
WandConjurationConjuring,
WandDivinationCasting,
WandDivinationConjuring,
WandEnchantmentCasting,
WandEnchantmentConjuring,
WandEvocationCasting,
WandEvocationConjuring,
WandIllusionCasting,
WandIllusionConjuring,
WandNecromancyCasting,
WandNecromancyConjuring,
WandTransmutationCasting,
WandTransmutationConjuring,
SkillBarbarianRage,
OpenIdle
};
/*
Represents an encoded animation id.
*/
class EncodedAnimId {
public:
explicit EncodedAnimId(int id) : mId(id) {
}
explicit EncodedAnimId(WeaponAnim anim,
WeaponAnimType leftHand = WeaponAnimType::Unarmed,
WeaponAnimType rightHand = WeaponAnimType::Unarmed) : mId(sWeaponAnimFlag) {
auto animId = (int)anim;
auto leftHandId = (int)leftHand;
auto rightHandId = (int)rightHand;
mId |= animId & 0xFFFFF;
mId |= leftHandId << 20;
mId |= rightHandId << 25;
}
explicit EncodedAnimId(BardInstrumentType instrumentType) : mId(sBardInstrumentAnimFlag) {
mId |= (int)instrumentType;
}
explicit EncodedAnimId(NormalAnimType animType) : mId((int) animType) {
}
operator int() const {
return mId;
}
bool IsConjuireAnimation() const;
bool IsSpecialAnim() const {
return (mId & (sWeaponAnimFlag | sBardInstrumentAnimFlag)) != 0;
}
// Not for weapon/bard anims
NormalAnimType GetNormalAnimType() const {
return (NormalAnimType)mId;
}
bool IsWeaponAnim() const {
return (mId & sWeaponAnimFlag) != 0;
}
// Only valid for weapon animations
WeaponAnimType GetWeaponLeftHand() const {
return (WeaponAnimType)((mId >> 20) & 0x1F);
}
// Only valid for weapon animations
WeaponAnimType GetWeaponRightHand() const {
return (WeaponAnimType)((mId >> 25) & 0x1F);
}
// Only valid for weapon animations
WeaponAnim GetWeaponAnim() const {
return (WeaponAnim)(mId & 0xFFFFF);
}
bool IsBardInstrumentAnim() const {
return (mId & sBardInstrumentAnimFlag) != 0;
}
// Only valid for bard instrument anim
BardInstrumentType GetBardInstrumentType() const {
return (BardInstrumentType)(mId & 7);
}
std::string GetName() const;
bool ToFallback();
private:
// Indicates that an animation id uses the encoded format
static constexpr int sWeaponAnimFlag = 1 << 30;
static constexpr int sBardInstrumentAnimFlag = 1 << 31;
int mId;
};
/*
Represents the events that can trigger when the animation
of an animated model is advanced.
*/
class AnimatedModelEvents {
public:
AnimatedModelEvents(bool isEnd, bool isAction)
: mIsEnd(isEnd),
mIsAction(isAction) {
}
bool IsEnd() const {
return mIsEnd;
}
bool IsAction() const {
return mIsAction;
}
private:
const bool mIsEnd : 1;
const bool mIsAction : 1;
};
class Submesh {
public:
virtual ~Submesh() {
}
virtual int GetVertexCount() = 0;
virtual int GetPrimitiveCount() = 0;
virtual gsl::span<DirectX::XMFLOAT4> GetPositions() = 0;
virtual gsl::span<DirectX::XMFLOAT4> GetNormals() = 0;
virtual gsl::span<DirectX::XMFLOAT2> GetUV() = 0;
virtual gsl::span<uint16_t> GetIndices() = 0;
};
class IRenderState {
public:
virtual ~IRenderState() = default;
};
class AnimatedModel {
public:
virtual ~AnimatedModel() {
}
virtual uint32_t GetHandle() const = 0;
virtual bool AddAddMesh(const std::string& filename) = 0;
virtual bool ClearAddMeshes() = 0;
virtual AnimatedModelEvents Advance(float deltaTime,
float deltaDistance,
float deltaRotation,
const AnimatedModelParams& params) = 0;
virtual EncodedAnimId GetAnimId() const = 0;
virtual int GetBoneCount() const = 0;
virtual std::string GetBoneName(int boneId) = 0;
virtual int GetBoneParentId(int boneId) = 0;
virtual bool GetBoneWorldMatrixByName(
const AnimatedModelParams& params,
const std::string& boneName,
DirectX::XMFLOAT4X4* worldMatrixOut) = 0;
virtual bool GetBoneWorldMatrixByNameForChild(const AnimatedModelPtr& child,
const AnimatedModelParams& params,
const std::string& boneName,
DirectX::XMFLOAT4X4* worldMatrixOut) = 0;
virtual float GetDistPerSec() const = 0;
virtual float GetRotationPerSec() const = 0;
virtual bool HasAnim(EncodedAnimId animId) const = 0;
virtual void SetTime(const AnimatedModelParams& params, float timeInSecs) = 0;
virtual bool HasBone(const std::string& boneName) const = 0;
virtual void AddReplacementMaterial(gfx::MaterialPlaceholderSlot slot,
const gfx::MdfRenderMaterialPtr &material) = 0;
virtual void SetAnimId(EncodedAnimId animId) = 0;
// This seems to reset cloth simulation state
virtual void SetClothFlag() = 0;
virtual std::vector<int> GetSubmeshes() = 0;
virtual std::unique_ptr<Submesh> GetSubmesh(const AnimatedModelParams& params, int submeshIdx) = 0;
virtual std::unique_ptr<Submesh> GetSubmeshForParticles(const AnimatedModelParams& params, int submeshIdx) = 0;
bool HitTestRay(const AnimatedModelParams& params, const Ray3d &ray, float &hitDistance);
/**
* Find the closest distance that the given point is away from the surface of this mesh.
*/
float GetDistanceToMesh(const AnimatedModelParams ¶ms, DirectX::XMFLOAT3 pos);
/**
This calculates the effective height in world coordinate units of the model in its current
state. Scale is the model scale in percent.
*/
virtual float GetHeight(int scale = 100) = 0;
/**
This calculates the visible radius of the model in its current state.
The radius is the maximum distance of any vertex on the x,z plane from the models origin.
If the model has no vertices, 0 is returned.
Scale is model scale in percent.
*/
virtual float GetRadius(int scale = 100) = 0;
/**
* Sets a custom render state pointer that will be freed when this model is freed.
*/
virtual void SetRenderState(std::unique_ptr<IRenderState> renderState) = 0;
/**
* Returns the currently assigned render state or null.
*/
virtual IRenderState *GetRenderState() const = 0;
template<typename T>
T &GetOrCreateRenderState() {
auto current = GetRenderState();
if (!current) {
auto newState = std::make_unique<T>();
current = newState.get();
SetRenderState(std::move(newState));
}
return (T&) *current;
}
};
struct AnimatedModelParams { // see: objects.GetAnimParams(handle)
uint32_t x = 0;
uint32_t y = 0;
float offsetX = 0;
float offsetY = 0;
float offsetZ = 0;
float rotation = 0;
float scale = 1;
float rotationRoll = 0;
float rotationPitch = 0;
float rotationYaw = 0;
AnimatedModelPtr parentAnim;
std::string attachedBoneName;
bool rotation3d = false; // Enables use of rotationRoll/rotationPitch/rotationYaw
};
class AnimatedModelFactory {
public:
virtual ~AnimatedModelFactory() {
}
virtual AnimatedModelPtr FromIds(
int meshId,
int skeletonId,
EncodedAnimId idleAnimId,
const AnimatedModelParams& params,
bool borrow = false) = 0;
virtual AnimatedModelPtr FromFilenames(
const std::string& meshFilename,
const std::string& skeletonFilename,
EncodedAnimId idleAnimId,
const AnimatedModelParams& params) = 0;
virtual std::unique_ptr<gfx::AnimatedModel> BorrowByHandle(uint32_t handle) = 0;
virtual void FreeHandle(uint32_t handle) = 0;
virtual void FreeAll() = 0;
};
class AnimatedModelRenderer {
public:
virtual ~AnimatedModelRenderer() {}
virtual void Render(AnimatedModel *model,
const AnimatedModelParams& params,
gsl::span<Light3d> lights,
const MdfRenderOverrides *materialOverrides = nullptr) = 0;
};
}
| {
"alphanum_fraction": 0.701327648,
"avg_line_length": 21.9087048832,
"ext": "h",
"hexsha": "131db9f30dfa54e41f49d646195d57d45ec35216",
"lang": "C",
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "edoipi/TemplePlus",
"max_forks_repo_path": "Infrastructure/include/infrastructure/meshes.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "edoipi/TemplePlus",
"max_issues_repo_path": "Infrastructure/include/infrastructure/meshes.h",
"max_line_length": 113,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f0e552289822fea908f16daa379fa568b1bd286d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "edoipi/TemplePlus",
"max_stars_repo_path": "Infrastructure/include/infrastructure/meshes.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3094,
"size": 10319
} |
#include "../include/matrix.h"
#ifndef MATREX_NO_BLAS
#include <cblas.h>
void
matrix_dot(const float alpha, const Matrix first, const Matrix second, Matrix result) {
MX_SET_ROWS(result, MX_ROWS(first));
MX_SET_COLS(result, MX_COLS(second));
cblas_sgemm(
CblasRowMajor,
CblasNoTrans,
CblasNoTrans,
MX_ROWS(first),
MX_COLS(second),
MX_COLS(first),
alpha,
first + 2,
MX_COLS(first),
second + 2,
MX_COLS(second),
0.0,
result + 2,
MX_COLS(result)
);
}
void
matrix_dot_and_add(
const float alpha, const Matrix first, const Matrix second, const Matrix third, Matrix result
) {
const uint64_t data_size = MX_ROWS(first) * MX_COLS(second) + 2;
MX_SET_ROWS(result, MX_ROWS(first));
MX_SET_COLS(result, MX_COLS(second));
cblas_sgemm(
CblasRowMajor,
CblasNoTrans,
CblasNoTrans,
MX_ROWS(first),
MX_COLS(second),
MX_COLS(first),
alpha,
first + 2,
MX_COLS(first),
second + 2,
MX_COLS(second),
0.0,
result + 2,
MX_COLS(result)
);
for(uint64_t index = 2; index < data_size; index += 1) {
result[index] += third[index];
}
}
void
matrix_dot_and_apply(
const float alpha, const Matrix first, const Matrix second, const char *function_name, Matrix result
) {
const math_func_ptr_t func = math_func_from_name(function_name);
const uint64_t data_size = MX_ROWS(first) * MX_COLS(second) + 2;
MX_SET_ROWS(result, MX_ROWS(first));
MX_SET_COLS(result, MX_COLS(second));
cblas_sgemm(
CblasRowMajor,
CblasNoTrans,
CblasNoTrans,
MX_ROWS(first),
MX_COLS(second),
MX_COLS(first),
alpha,
first + 2,
MX_COLS(first),
second + 2,
MX_COLS(second),
0.0,
result + 2,
MX_COLS(result)
);
for(uint64_t index = 2; index < data_size; index += 1) {
result[index] = func(result[index]);
}
}
void
matrix_dot_nt(const float alpha, const Matrix first, const Matrix second, Matrix result) {
MX_SET_ROWS(result, MX_ROWS(first));
MX_SET_COLS(result, MX_ROWS(second));
cblas_sgemm(
CblasRowMajor,
CblasNoTrans,
CblasTrans,
MX_ROWS(first),
MX_ROWS(second),
MX_COLS(first),
alpha,
first + 2,
MX_COLS(first),
second + 2,
MX_COLS(second),
0.0,
result + 2,
MX_COLS(result)
);
}
void
matrix_dot_tn(const float alpha, const Matrix first, const Matrix second, Matrix result) {
MX_SET_ROWS(result, MX_COLS(first));
MX_SET_COLS(result, MX_COLS(second));
cblas_sgemm(
CblasRowMajor,
CblasTrans,
CblasNoTrans,
MX_COLS(first),
MX_COLS(second),
MX_ROWS(first),
alpha,
first + 2,
MX_COLS(first),
second + 2,
MX_COLS(second),
0.0,
result + 2,
MX_COLS(result)
);
}
#else
void
matrix_dot(const float alpha, const Matrix first, const Matrix second, Matrix result) {
const int64_t rows = MX_ROWS(first);
const int64_t cols = MX_COLS(second);
MX_SET_ROWS(result, rows);
MX_SET_COLS(result, cols);
for (int64_t r = 0; r < rows; r++)
for (int64_t c = 0; c < cols; c++) {
const int64_t elem_offset = 2 + r*cols + c;
result[elem_offset] = 0.0;
for (int64_t k = 0; k < MX_COLS(first); k++)
result[elem_offset] += first[2 + r*MX_COLS(first) + k] * second[2 + k*MX_COLS(second) + c];
result[elem_offset] *= alpha;
}
}
void
matrix_dot_and_add(
const float alpha, const Matrix first, const Matrix second, const Matrix third, Matrix result
) {
const int64_t rows = MX_ROWS(first);
const int64_t cols = MX_COLS(second);
MX_SET_ROWS(result, rows);
MX_SET_COLS(result, cols);
for (int64_t r = 0; r < rows; r++)
for (int64_t c = 0; c < cols; c++) {
const int64_t elem_offset = 2 + r*cols + c;
result[elem_offset] = third[elem_offset];
for (int64_t k = 0; k < MX_COLS(first); k++)
result[elem_offset] += first[2 + r*MX_COLS(first) + k] * second[2 + k*MX_COLS(second) + c];
result[elem_offset] *= alpha;
}
}
void
matrix_dot_and_apply(
const float alpha, const Matrix first, const Matrix second, const char *function_name, Matrix result
) {
const math_func_ptr_t func = math_func_from_name(function_name);
const int64_t rows = MX_ROWS(first);
const int64_t cols = MX_COLS(second);
MX_SET_ROWS(result, rows);
MX_SET_COLS(result, cols);
for (int64_t r = 0; r < rows; r++)
for (int64_t c = 0; c < cols; c++) {
const int64_t elem_offset = 2 + r*cols + c;
result[elem_offset] = 0.0;
for (int64_t k = 0; k < MX_COLS(first); k++)
result[elem_offset] += first[2 + r*MX_COLS(first) + k] * second[2 + k*MX_COLS(second) + c];
result[elem_offset] = func(alpha * result[elem_offset]);
}
}
void
matrix_dot_nt(const float alpha, const Matrix first, const Matrix second, Matrix result) {
const int64_t rows = MX_ROWS(first);
const int64_t cols = MX_ROWS(second);
MX_SET_ROWS(result, rows);
MX_SET_COLS(result, cols);
for (int64_t r = 0; r < rows; r++)
for (int64_t c = 0; c < cols; c++) {
const int64_t elem_offset = 2 + r*cols + c;
result[elem_offset] = 0.0;
for (int64_t k = 0; k < MX_COLS(first); k++)
result[elem_offset] += first[2 + r*MX_COLS(first) + k] * second[2 + c*MX_COLS(second) + k];
result[elem_offset] *= alpha;
}
}
void
matrix_dot_tn(const float alpha, const Matrix first, const Matrix second, Matrix result) {
const int64_t rows = MX_COLS(first);
const int64_t cols = MX_COLS(second);
MX_SET_ROWS(result, rows);
MX_SET_COLS(result, cols);
for (int64_t r = 0; r < rows; r++)
for (int64_t c = 0; c < cols; c++) {
const int64_t elem_offset = 2 + r*cols + c;
result[elem_offset] = 0.0;
for (int64_t k = 0; k < MX_ROWS(first); k++)
result[elem_offset] += first[2 + r + k*rows]*second[2 + c + k*cols];
result[elem_offset] *= alpha;
}
}
#endif
| {
"alphanum_fraction": 0.6405028882,
"avg_line_length": 24.4232365145,
"ext": "c",
"hexsha": "4e3fb9c945bd9723bde8ef0dc03c89edd21e773f",
"lang": "C",
"max_forks_count": 34,
"max_forks_repo_forks_event_max_datetime": "2021-03-29T07:30:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-05-21T15:40:11.000Z",
"max_forks_repo_head_hexsha": "9a080311836a151ef9f2b780c3cd751a0fa0df22",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "scripbox/matrex",
"max_forks_repo_path": "native/src/matrix_dot.c",
"max_issues_count": 30,
"max_issues_repo_head_hexsha": "9a080311836a151ef9f2b780c3cd751a0fa0df22",
"max_issues_repo_issues_event_max_datetime": "2021-12-09T11:38:28.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-05-28T11:00:37.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "scripbox/matrex",
"max_issues_repo_path": "native/src/matrix_dot.c",
"max_line_length": 102,
"max_stars_count": 464,
"max_stars_repo_head_hexsha": "9a080311836a151ef9f2b780c3cd751a0fa0df22",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "scripbox/matrex",
"max_stars_repo_path": "native/src/matrix_dot.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-01T18:29:38.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-05-13T00:48:25.000Z",
"num_tokens": 1763,
"size": 5886
} |
//Include guard
#ifndef MISC_H
#define MISC_H
//Forward declared dependencies
//Included dependencies
#include <vector>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_matrix.h>
#include "sequence.h"
#include "diploidSequence.h"
#include "modelMR.hpp"
#include "model.hpp"
#include "simParamPH.h"
#include "anaParam.h"
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
void rescale(std::vector<double> &vec);
void rescaleZeroAccepted(std::vector<double> &vec);
void rescaleMin(std::vector<double> &vec, double min);
void printDoubleVector(std:: vector<double> &vec);
std::string printDoubleVectorToString(std:: vector<double> &vec);
void printIntVector(std:: vector<int> &vec);
std::string printIntVectorToString(std:: vector<int> &vec);
std::vector<int> multinomialSampling(int N, std::vector<double> p, const gsl_rng *r);
int sumOfVector(std::vector<int> intVec);
double sumOfVector(std::vector<double> doubleVec);
std::vector<double> subtractVectorsDouble(std::vector<double> &a, std::vector<double> &b);
std::vector<double> addVectorsDouble(std::vector<double> &a, std::vector<double> &b);
double my_gsl_linalg_LU_det (gsl_matrix * LU, int signum);
double determinant(gsl_matrix *A);
double logMultivariateNormalPDF(std::vector<double> &x, std::vector<double> &mu, gsl_matrix *sigma);
double logMultivariateNormalPDFPrint(std::vector<double> &x, std::vector<double> &mu, gsl_matrix *sigma);
void printMatrix(gsl_matrix *A);
void printMatrixMathematica(gsl_matrix *A);
std::string printMatrixMathematicaToString(gsl_matrix* A);
Sequence randomSequence(int length, gsl_rng *r);
std::vector<Sequence> generateRandomFullHaplotypes(int length, int number, gsl_rng *r);
std::vector<Sequence> generateMajorMinorFullHaplotypes(int length, int number, gsl_rng *r);
bool identicalSeqs(Sequence & a, Sequence & b);
bool identicalIntVectors(std::vector<int> & a, std::vector<int> & b);
bool nonZeroIntVector(std::vector<int> & a);
bool nonZeroDoubleVector(std::vector<double> & a);
void setupRNG(gsl_rng *r, unsigned long int seed);
DiploidSequence generateRandomDiploidSequence(int length, gsl_rng *r);
DiploidSequence generateRandomSemiConstrainedDiploidSequence(Sequence constraint, gsl_rng *r);
DiploidSequence generateRandomSemiConstrainedDiploidSequence(DiploidSequence constraint, gsl_rng *r);
std::vector<Sequence> generateFullHapsFromAlleles(DiploidSequence &fullHapAlleles);
void randomiseSequenceVector(std::vector<Sequence> & s, gsl_rng *r);
std::vector<int> pickRandomInts(gsl_rng *r, int max, int length);
void addRandom(std::vector<double>& oldVec, std::vector<double>& newVec, double delta, gsl_rng *r);
void addRandomMin(std::vector<double>& oldVec, std::vector<double>& newVec, double delta, gsl_rng *r, double min);
void addRandom(std::vector<double>& vec, double delta, gsl_rng *r);
double logMultinomialProb(std::vector<double> &freq, std::vector<int> & obs);
void findLogFactorial(std::vector<double> & fact_store, int N);
double logDirMultProbC(double C, std::vector<int> &obs, std::vector<double> &inf, std::vector<double> &fact_store);
double logDirMultProb(std::vector<double>& alpha, std::vector<int> &x, int& n);
double logBetaBinProb(double alpha, double beta, int x, int n);
double BetaBinCDF(double alpha, double beta, double threshold, int n);
bool fileExists(std::string &fileName);
std::vector<int> DirMultSampling(int N, std::vector<double> & freqs, double C, const gsl_rng *r);
//Mean, no var
double computeLSelection(std::vector<int> &obsB, std::vector<int> &obsA, int Nt, AnaParam* ap, std::vector<double> &qBfhFreqs, std::vector<double> &hapFit, std::vector<std::vector<int> >* contribs, bool print);
double computeLNeutral(std::vector<int>& obsB, std::vector<int>& obsA, int Nt, AnaParam* ap, std::vector<double>& qBfhFreqs, std::vector<std::vector<int> >* contribs, bool print);
//Mean and var
double computeLSelTVar(std::vector<int>& obsA, int Nt, AnaParam* ap, std::vector<double>& qBfhFreqs, gsl_matrix* var, std::vector<double>& hapFitT, std::vector<std::vector<int> >* contribs, bool print);
double computeLSelTVarOld(std::vector<int>& obsA, int Nt, AnaParam* ap, std::vector<double>& qBfhFreqs, gsl_matrix* var, std::vector<double>& hapFitT, std::vector<std::vector<int> >* contribs, bool print);
double computeLSelTSelGVar(std::vector<int>& obsA, int Nt, AnaParam* ap, std::vector<double>& qBfhFreqs, gsl_matrix* var, std::vector<double>& hapFitT, std::vector<double> &hapFitG, std::vector<std::vector<int> >* contribs, bool print);
double computeLSelTSelGVarOld(std::vector<int>& obsA, int Nt, AnaParam* ap, std::vector<double>& qBfhFreqs, gsl_matrix* var, std::vector<double>& hapFitT, std::vector<double> &hapFitG, std::vector<std::vector<int> >* contribs, bool print);
double computeLNeutralVar(std::vector<int>& obsA, int Nt, AnaParam* ap, std::vector<double>& qBfhFreqs, gsl_matrix* var, std::vector<std::vector<int> >* contribs, bool print);
double computeLNeutralVarAdvanced(std::vector<int>& obsA, int& deltaDays, int Nt, AnaParam* ap, std::vector<double>& qBfhFreqs, gsl_matrix* var, std::vector<std::vector<int> >* contribs, bool print);
double computeLNeutralVarReduced(std::vector<int>& obsA, int Nt, AnaParam* ap, std::vector<double>& qBfhFreqs, gsl_matrix* var, std::vector<std::vector<int> >* contribs, bool print);
double computeLNeutralSelGVar(std::vector<int>& obsA, int Nt, AnaParam* ap, std::vector<double>& qBfhFreqs, gsl_matrix* var, std::vector<double>& hapFitG, std::vector<std::vector<int> >* contribs, bool print);
double computeLNeutralSelGVarOld(std::vector<int>& obsA, int Nt, AnaParam* ap, std::vector<double>& qBfhFreqs, gsl_matrix* var, std::vector<double>& hapFitG, std::vector<std::vector<int> >* contribs, bool print);
void constructMatrixM(std::vector<double> x, gsl_matrix *M);
void constructMatrixMoriginal(std::vector<double> x, gsl_matrix *M);
std::vector<double> computeHapFit(std::vector<Sequence> &fullHaps, Sequence &selModel, std::vector<double> &selCoefsNew);
std::vector<double> computeSimulationHapFitT(std::vector<Sequence> &fullHaps, SimParamPH *spPH);
std::vector<double> computeSimulationHapFitG(std::vector<Sequence> &fullHaps, SimParamPH *spPH);
std::vector<DiploidSequence> createOneLocusCollapsed(std::vector<std::vector<DiploidSequence> > &oneLocusModels);
std::vector<Model> generateModelsFromPreviousBest(std::vector<DiploidSequence> &collapsedFullHaps, Model &bestModelBefore);
std::vector<ModelMR> generateModelsFromPreviousBest(std::vector<DiploidSequence> &collapsedFullHaps, ModelMR &bestModelBefore);
int binomialCoeff(int n, int k);
int logBinCoeffStirling(int n, int k);
int getNextLeft(std::vector<int> alreadyPicked, int max);
std::vector<Sequence> findRemainingSeqs(std::vector<Sequence> subset, std::vector<Sequence> set);
DiploidSequence constructDiploidFromFullHap(std::vector<Sequence> &fhs, std::vector<double> &freqs);
DiploidSequence constructDiploidFromFullHap(std::vector<Sequence> &fhs);
bool noEntryTheSameExceptZero(std::vector<double> &v);
std::vector<std::vector<int> > getAllCombs(int N, int k);
std::vector<std::vector<int> > getLinkedPairs(std::vector<Sequence> &haps);
std::vector<std::string> split(const std::string& s, char delim);
//Related to gaining information on memory usage
int parseLine(char* line);
int getValue();
bool stringToBool(std::string& s);
bool compareBySize(const std::vector<int>& a, const std::vector<int>& b);
//gamma and delta functions for compound solutions
double gamma_n(int n, double lambda, int Nt);
double delta_n(int n, double lambda, int Nt);
double qPochhammer(double a, double q, int n);
#endif
| {
"alphanum_fraction": 0.7628852459,
"avg_line_length": 57.7651515152,
"ext": "h",
"hexsha": "f95b27ae1e899f6494ff11c7c772e00ec7a6d9e0",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-06-12T13:25:36.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-06-12T13:25:36.000Z",
"max_forks_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "CasperLumby/Bottleneck_Size_Estimation",
"max_forks_repo_path": "Codes/Codes_for_xStar/misc.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "CasperLumby/Bottleneck_Size_Estimation",
"max_issues_repo_path": "Codes/Codes_for_xStar/misc.h",
"max_line_length": 239,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "9f9d81e35c1ac9dc74541401e8da70d428be1ad1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "CasperLumby/Bottleneck_Size_Estimation",
"max_stars_repo_path": "Codes/Codes_for_xStar/misc.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2151,
"size": 7625
} |
/* specfunc/gsl_sf_coupling.h
*
* Copyright (C) 1996,1997,1998,1999,2000,2001,2002 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_COUPLING_H__
#define __GSL_SF_COUPLING_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
/* 3j Symbols: / ja jb jc \
* \ ma mb mc /
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
int gsl_sf_coupling_3j_e(int two_ja, int two_jb, int two_jc,
int two_ma, int two_mb, int two_mc,
gsl_sf_result * result
);
double gsl_sf_coupling_3j(int two_ja, int two_jb, int two_jc,
int two_ma, int two_mb, int two_mc
);
/* 6j Symbols: / ja jb jc \
* \ jd je jf /
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
int gsl_sf_coupling_6j_e(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
gsl_sf_result * result
);
double gsl_sf_coupling_6j(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf
);
/* Racah W coefficients:
*
* W(a b c d; e f) = (-1)^{a+b+c+d} / a b e \
* \ d c f /
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
int gsl_sf_coupling_RacahW_e(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
gsl_sf_result * result
);
double gsl_sf_coupling_RacahW(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf
);
/* 9j Symbols: / ja jb jc \
* | jd je jf |
* \ jg jh ji /
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
int gsl_sf_coupling_9j_e(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
int two_jg, int two_jh, int two_ji,
gsl_sf_result * result
);
double gsl_sf_coupling_9j(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
int two_jg, int two_jh, int two_ji
);
/* INCORRECT version of 6j Symbols:
* This function actually calculates
* / ja jb je \
* \ jd jc jf /
* It represents the original implementation,
* which had the above permutation of the
* arguments. This was wrong and confusing,
* and I had to fix it. Sorry for the trouble.
* [GJ] Tue Nov 26 12:53:39 MST 2002
*
* exceptions: GSL_EDOM, GSL_EOVRFLW
*/
#ifndef GSL_DISABLE_DEPRECATED
int gsl_sf_coupling_6j_INCORRECT_e(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf,
gsl_sf_result * result
);
double gsl_sf_coupling_6j_INCORRECT(int two_ja, int two_jb, int two_jc,
int two_jd, int two_je, int two_jf
);
#endif /* !GSL_DISABLE_DEPRECATED */
__END_DECLS
#endif /* __GSL_SF_COUPLING_H__ */
| {
"alphanum_fraction": 0.5740696279,
"avg_line_length": 33.0555555556,
"ext": "h",
"hexsha": "bd6b58372302cbfee5da490258797dd62234cda9",
"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_coupling.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_coupling.h",
"max_line_length": 81,
"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_coupling.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": 1096,
"size": 4165
} |
/******************************************************************************
** Copyright (C) 2014 by CEA
*******************************************************************************
**
** UNIT
**
** Version: 1.0
**
** Author: Fred Ngole
**
** Date: 24/09/2014
**
** File: sr_util.h
**
*******************************************************************************
**
** DESCRIPTION
** -----------
** Tools used in sprite.cc and useful beyond the scope of super-resolution
**
**
******************************************************************************/
#ifndef SR_UTIL_H
#define SR_UTIL_H
#include <stdio.h>
#include <stdlib.h>
#include "TempArray.h"
#include <cmath>
#include "IM_Obj.h"
#include "IM_IO.h"
#include "MR_Obj.h"
#include "MR_Sigma.h"
#include "CoaddCorrel.h"
#include "IM_Deconv.h"
#include "OptMedian.h"
//#include <random>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
const double Pi = 3.14159265358979323846;
const int LR_DENOISING = 0;
const int MR_SUPP_DENOISING=1;
const int ONE_STEP_ANALYSIS=1;
const int ACCURATE_ANALYSIS=0;
const int MODEL_SINC_INTERP=0;
const int MODEL_NON_LIN_INTERP=1;
const int MODEL_GAUSS_FIT=2;
const int FISTA = 1;
const int GEN_FWBW = 0;
//gsl_rng *rng;
//const gsl_rng_type * T;
//T = gsl_rng_default;
//rng = gsl_rng_alloc (T);
typedef struct{
type_transform transf;
int nb_sc;
int nb_usc;
sb_type_norm Norm;
type_undec_filter U_Filter;
type_sb_filter SB_Filter;
type_border Bord;
FilterAnaSynt *FAS ;
}mr_opt;
int compute_centroid(Ifloat *img,double sig,double *cent,int niter=10);
int compute_centroid_arr(fltarray *data,double sig,double **cent,int niter=10);
double gauss2d(double amp,double x,double y,double theta,double sigx,double sigy);
void gauss2darray(double amp,double theta,double sigx,double sigy, double xcen,double ycen,Ifloat &im_out);
void gauss2D_fitting_first_guess(Ifloat im,double*sigx,double*sigy,double*xcen,double*ycen,double*amp,int smooth_ker);
void gauss2d_fit(Ifloat im,double *xcen,double *ycen,double* amp,double sig0,double *sig,int nb_iter_alter=20,int nb_subiter=10,double *mse=NULL,int max_test=10);
void gauss2d_fit_2(Ifloat im,double *xcen,double *ycen,double *amp,double *sigx,double *sigy,int nb_iter_alter=20,int nb_subiter=10,double *mse=NULL,int max_test=10);
double gauss2d_der1sig(Ifloat res,Ifloat gauss_approx,Ifloat distances_map,double sig);
double gauss2d_der1sigx(Ifloat res, Ifloat gauss_approx, double sigx, double xcen);
double gauss2d_der1sigy(Ifloat res, Ifloat gauss_approx, double sigy, double ycen);
double gauss2d_der2sig(Ifloat res,Ifloat gauss_approx,Ifloat distances_map,double sig);
double gauss2d_der2sigx(Ifloat res, Ifloat gauss_approx, double sigx, double xcen);
double gauss2d_der2sigy(Ifloat res, Ifloat gauss_approx, double sigy, double ycen);
double gauss2d_der1xcen(Ifloat res, Ifloat gauss_approx, double sig, double xcen);
double gauss2d_der1ycen(Ifloat res, Ifloat gauss_approx, double sig, double ycen);
double gauss2d_der2xcen(Ifloat res, Ifloat gauss_approx, double sig,double xcen);
double gauss2d_der2ycen(Ifloat res, Ifloat gauss_approx, double sig,double ycen);
double gauss2d_der2xcenycen(Ifloat res, Ifloat gauss_approx, double sig, double xcen, double ycen);
void dist_map(Ifloat &map,double xcen,double ycen);
void thresholding(Ifloat *data_in,Ifloat *data_out,double thresh,bool thresh_type=0);
void thresholding(Ifloat *data,Ifloat *data_out,Ifloat *thresh,bool thresh_type=0);
void thresholding(fltarray *data_in,fltarray *data_out,fltarray *thresh,bool thresh_type=0);
void circ_thresh(Ifloat *data_in,Ifloat *data_out,double r,double *cen);
void circ_thresh(fltarray *data_in,fltarray *data_out,double r,double **cen);
int sign_num (double a);
int wl_trans(Ifloat *Dat,mr_opt opt,MultiResol* MR_Data);
void wl_thresholding(MultiResol*wav_coeff,fltarray *thresh,bool thresh_type=0);
void wl_filter(Ifloat *img,Ifloat*img_filt,mr_opt opt,double nsig=4,bool thresh_type=0,fltarray* noise_map=NULL,fltarray *coeff_thresh=NULL,Ifloat *coarse_scale=NULL);
void wl_filter_analysis(Ifloat img,Ifloat &img_filt,mr_opt opt,double nsig,bool thresh_type,fltarray std_map,MultiResol &coeff_init,int nb_iter=100,double mu=0.5,double *mse=NULL);
int wl_gnoise_est(MultiResol* wav_coeff,fltarray* noise_arr);
mr_opt mr_opt_init(int Nx,type_transform transf = TO_UNDECIMATED_MALLAT,int nb_sc=-1,int nb_usc=-1,sb_type_norm Norm=NORM_L1,type_undec_filter U_Filter=DEF_UNDER_FILTER,type_sb_filter SB_Filter=F_MALLAT_7_9,type_border Bord=I_CONT,Bool Verbose =False);
int noise_est(fltarray* data,fltarray* noise_arr);
void wl_arr_filter(fltarray *data,fltarray*data_filt,mr_opt opt,double nsig=4,bool thresh_type=0);
void coadd_frames(fltarray Data, Ifloat &Ima,Bool GetMedian=False);
void coadd_frames(fltarray Dat, Ifloat &Ima,float Zoom,
Bool GetMedian=True,int MaxDist=4,
int Surface=10, type_interp_corr TypeInterp=ICF_TANH,Bool OptNoOffset=False,Bool MeanSub=False,Bool Verbose=False);
void flux_est(Ifloat *data, double r,double *cent,double*flux);
void flux_est(fltarray *data, double r,double **cent,double*flux,int ref_im_ind=0);
void shift_est(fltarray *data, double sig_gfit, double *sig_vec,double **cent,double **shift,int ref_im_ind=0,double nsig=4);
double sinc(double x);
void lanczos(double u,double*mask,int mask_rad=10);
void lanczos(double u[],double**mask,int mask_rad=10);
void lanczos_upsamp(Ifloat &im,int upfact,Ifloat &im_out, double *u=NULL,int kern_rad=5);
void lanczos_stacking(fltarray &data,Ifloat &im_upsamp,int upfact,double **u,int kern_rad=5,Bool mean_en=False);
void im_stacking(fltarray &data,Ifloat &im_stack,Bool mean_en=False);
void decim(Ifloat *img,Ifloat *img_filt,Ifloat *img_dec,int D,Ifloat* mask,Bool filt_en=True,Bool fft_en=True );
void rotate(Ifloat *input,Ifloat *output,int dir);
void transpose_decim(Ifloat*im_in,Ifloat*im_out,int D);
void power_meth(void(*opname)(double*,double*),int size_input,int *nb_iter,double *spec_rad,int nb_iter_max=100,double tol=0.01);
double norm2 (double * x,int siz);
void scale (double * x,double siz,double a);
double dot(Ifloat Im1,Ifloat Im2);
void hadamard(Ifloat Im1,Ifloat Im2,Ifloat &Im_out);
void ineq_cons(Ifloat &A, Ifloat B,double b=1);
void reverse(double*u,int length,double*ur);
void holes(double*h,int sc_nb,int length,double*hout);
void convol1D(double*in,double*out,double*h,int length,int filt_length);
void convol1D_cent(double*in,double*out,double*h,int length,int filt_length);
void correl2D(Ifloat im1,Ifloat im2, Ifloat &im_correl);
void sep_filt2d(Ifloat* im_in,Ifloat*im_out,double *h,double *g,int lh,int lg);
void transp_sep_filt2d(Ifloat* im_in,Ifloat*im_out,double *h,double *g,int lh,int lg);
void grad(Ifloat im,Ifloat &im_gradx,Ifloat &im_grady,double* hx,double* hy,int lhx,int lhy);
void grad_cons_noise_est(Ifloat im_in,Ifloat& im_out,Ifloat &res,double * sig,double gamma,int nb_iter=5,double * mse_iter=NULL,double mu=0.5, double *hx=NULL,double *hy=NULL,int lhx=-1,int lhy=-1);
void mad_res_noise_est(Ifloat im_in,Ifloat& im_out,Ifloat &res,double * sig,int nb_iter=5,double * mse_iter=NULL,double*sig_iter=NULL,double mu=1, int nsig=5,Bool sig_up=True,int thresh_type=0);
//void randomn(double *x,double sig=1,int length=1,double mean=0);
void randomngsl(double *x,double sig,int length,double mean=0);
//void randomn(Ifloat *mat,double sig=1,double mean=0);
void randomngsl(Ifloat *mat,double sig=1,double mean=0);
//void randomn(fltarray *mat,double *sig,double mean=0);
void randomngsl(fltarray *mat,double *sig,double mean=0);
//void randomn(fltarray *mat,double *sig,double*mean);
void randomngsl(fltarray *mat,double *sig,double*mean);
double var_iter(double x,int n,double *mean,double*M);
void check_ineq(Ifloat dat,double thresh,Bool abs_en,Ifloat &flag);
void mr_support_filt(Ifloat img,Ifloat &img_filt, mr_opt opt,double nsig=5,int nb_iter=1,double*mse=NULL,Bool Pos_coeff=True,double lambda=1,Bool coarse_cons=False,Bool pos_cons=True, Bool drop_coarse=True,Bool iso_cons=False, double sig=89.108911);
inline void mod_denoise_usage(void)
{
fprintf(OUTMAN, " [-m type_of_model_denoising]\n");
fprintf(OUTMAN, " %d: %s \n",0,
"Wavelet denoising of LR images before coaddition");
fprintf(OUTMAN, " %d: %s \n",1,
"Iterative multiresolution support denoising after coaddition");
fprintf(OUTMAN, " default is %s.\n", "Iterative multiresolution support denoising after coaddition");
}
inline void mod_comp_usage(void)
{
fprintf(OUTMAN, " [-M model_computing_method]\n");
fprintf(OUTMAN, " %d: %s \n",0,
"Sinc Interpolation");
fprintf(OUTMAN, " %d: %s \n",1,
"Non linear interpolation");
fprintf(OUTMAN, " %d: %s \n",2,
"Gaussian fitting after sinc interpolation (no denoising)");
fprintf(OUTMAN, " default is %s.\n", "Sinc Interpolation");
}
inline void min_id_usage(void)
{
fprintf(OUTMAN, " [-A Minimisation algorithm]\n");
fprintf(OUTMAN, " %d: %s \n",0,
"Generalized forward-backard (analysis+positivity)");
fprintf(OUTMAN, " %d: %s \n",1,
"FISTA");
fprintf(OUTMAN, " default is %s.\n", "Generalized forward-backard (analysis+positivity)");
}
inline void sparse_const_type_usage(void)
{
fprintf(OUTMAN, " [-D sparse_constraint_implementation (if FISTA is chosen for the minimisation)]\n");
fprintf(OUTMAN, " %d: %s \n",0,
"Accurate analysis constraint with subiteration");
fprintf(OUTMAN, " %d: %s \n",1,
"One step approximation of analysis constraint implementation");
fprintf(OUTMAN, " default is %s.\n", "Accurate analysis constraint with subiteration");
}
inline void noise_est_usage(void)
{
fprintf(OUTMAN, " [-e Noise_est_meth]\n");
fprintf(OUTMAN, " %d: %s \n",0,
"Estimation on backprojected residual using a MAD");
fprintf(OUTMAN, " %d: %s \n",1,
"Noise simulation");
//fprintf(OUTMAN, " %d: %s \n",2,
// "Direct calculation of noise standard deviation per pixel (option under development)");
fprintf(OUTMAN, " default is %s.\n", "Estimation on backprojected residual using a MAD");
}
inline void thresh_type_usage(void)
{
fprintf(OUTMAN, " [-c Thresh_type]\n");
fprintf(OUTMAN, " %d: %s \n",0,
"Hard Thresholding");
fprintf(OUTMAN, " %d: %s \n",1,
"Soft Thresholding");
//fprintf(OUTMAN, " %d: %s \n",2,
// "Direct calculation of noise standard deviation per pixel (option under development)");
fprintf(OUTMAN, " default is %s.\n", "Soft Thresholding");
}
void decim_conv_mat(Ifloat conv_mat,int im_siz[],int decim_fact,Ifloat &output,double flux=1,double sig=1);
void convmask_shift_extend(Ifloat mask,int im_siz[],int shift[],Ifloat &output);
void noise_map_comp(double **shifts, double *sig, double *flux,int nb_im,int lancrad, int im_siz[],mr_opt opt, int decim_fact,fltarray &output);
int renewSeed();
void mr_norm(mr_opt opt,double*nrm,int nb_band,int Nx,int Ny=-1);
void wl_gnoise_est_dat(Ifloat data,mr_opt opt,fltarray* noise_arr);
void shell(unsigned long n,double *a);
double median(double *arr,int n);
#endif
| {
"alphanum_fraction": 0.6724767596,
"avg_line_length": 52.8421052632,
"ext": "h",
"hexsha": "062f43c092a5e167ce05f7387fe5f7286c7e11d9",
"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": "a475315cda06dca346095a1e83cb6ad23979acae",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sfarrens/cosmostat",
"max_forks_repo_path": "src/cxx/mrgsl/libmrgsl/sr_util.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae",
"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": "sfarrens/cosmostat",
"max_issues_repo_path": "src/cxx/mrgsl/libmrgsl/sr_util.h",
"max_line_length": 252,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a475315cda06dca346095a1e83cb6ad23979acae",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sfarrens/cosmostat",
"max_stars_repo_path": "src/cxx/mrgsl/libmrgsl/sr_util.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3255,
"size": 12048
} |
// The MIT License (MIT)
//
// Copyright (c) 2008 - 2015 Stefan Faußer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
/**
* \file mlpLib.c
* \brief Multi-layer perceptron (MLP) libary
*
* This MLP library supports Online, Batch, Batch with Momentumterm, RPROP-, RPROP+ and Quickprop learning.
* Further, it can be used for learning state-action value functions (reinforcement learning)
* when used in combination with the tdlLib.
*
* \author Stefan Fausser
*
* Modification history:
*
* 2008-04-01, S. Fausser - written
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <errno.h>
#include <string.h> /*memset */
#include "mlpLib.h"
#include "matrixLib.h"
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_blas.h>
#define MAX_WEIGHT_ONLINE_MODE 99999999
#define ZERO_PRECISION 0.001
/**
* structure including all mlp parameters for one mlp network
*/
struct mlp_vars
{
/**
* weights for neurons in hidden layer
*/
double ***w;
double ***w_prime;
/**
* bias for neurons in hidden layer
*/
double **theta;
double **theta_prime;
/**
* modifyable eta values for supersab / resilient weight udpate mode in hidden layer
*/
double ***eta_w;
/**
* last gradient (t-1) in hidden layer
*/
double ***desc_w;
/**
* last weight-delta in hidden layer
*/
double ***delta_w1;
/**
* dendrit potential in hidden layer
*/
double ***u;
/**
* axon potential in hidden layer
*/
double ***y;
double ***y_tsignal;
/**
* delta values in hidden layer
*/
double ***delta;
double ****gradvec;
double ****gradvec_tsignal;
double ****grad2vec;
double ****gradientTrace;
/**
* weights for neurons in output layer
*/
double **w2;
double **w2_prime;
/**
* bias for neurons in output layer
*/
double *theta2;
double *theta2_prime;
/**
* modifyable eta values for supersab / resilient weight udpate mode in output layer
*/
double **eta_w2;
/**
* last gradient in output layer
*/
double **desc_w2;
/**
* last weight-delta in output layer
*/
double **delta_w2;
/**
* dendrit potential in output layer
*/
double *u2;
/**
* axon potential in output layer
*/
double **y2;
double **y2_prime;
/**
* delta values in output layer
*/
double **delta2;
double **gradvec2;
double **gradvec2_tsignal;
double **grad2vec2;
double **gradientTrace2;
/**
* mlp_param structure
*/
struct mlp_param mlpP;
/**
* mlp_init_values structure
*/
struct mlp_init_values mlpIv;
/**
* maximum number of training samples in one epoche
*/
uint32_t micro_max;
/**
* floating point value that will be used to random initialize the weights
*/
double a;
double aOut;
int weightNormalizedInitialization;
int thresholdZeroInitialization;
};
/**
* Gradient factor
*/
#define GRADIENT_FACTOR (-1.0)
/*Calculate S = summed gradient information (weight specific) over all patterns of the pattern set*/
#define CALC_GRADIENT_WEIGHTS_OUTPUT(_S) \
_S = 0; \
for (muster=0;muster<micro_max;muster++) { \
_S += pMlpVA[mlpfd]->y[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers-1][muster][i] * pMlpVA[mlpfd]->delta2[muster][j]; \
} \
_S *= GRADIENT_FACTOR;
#define CALC_GRADIENT_BIAS_OUTPUT(_S) \
_S = 0; \
for (muster=0;muster<micro_max;muster++) { \
_S += pMlpVA[mlpfd]->delta2[muster][j]; \
}
#define CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER(_S) \
_S = 0; \
for (muster=0;muster<micro_max;muster++) { \
_S += pData->x[muster][k] * pMlpVA[mlpfd]->delta[l][muster][i]; \
} \
_S *= GRADIENT_FACTOR;
#define CALC_GRADIENT_WEIGHTS_HIDDEN(_S) \
_S = 0; \
for (muster=0;muster<micro_max;muster++) { \
_S += pMlpVA[mlpfd]->y[l-1][muster][i2] * pMlpVA[mlpfd]->delta[l][muster][i]; \
} \
_S *= GRADIENT_FACTOR;
#define CALC_GRADIENT_BIAS_HIDDEN(_S) \
_S = 0; \
for (muster=0;muster<micro_max;muster++) { \
_S += pMlpVA[mlpfd]->delta[l][muster][i]; \
}
#define CALC_RESILIENT_UPDATE_WEIGHT(_S,_weight,_delta) \
/*Berechnung der aktuellen Gewichtsaenderung*/ \
if ( _S > 0 ) { \
/*S(t)>0*/ \
_weight = _weight - _delta; \
} \
else if ( _S < 0 ) { \
/*S(t-1)<0*/ \
_weight = _weight + _delta; \
} \
else { \
/*S(t-1)*S(t)=0*/ \
}
#define CALC_RESILIENT_DELTA_WEIGHT(_S,_delta_weight,_delta) \
/*Berechnung der aktuellen Gewichtsaenderung*/ \
if ( _S > 0 ) { \
/*S(t)>0*/ \
_delta_weight = - _delta; \
} \
else if ( _S < 0 ) { \
/*S(t-1)<0*/ \
_delta_weight = + _delta; \
} \
else { \
_delta_weight = 0; \
}
#define CALC_RESILIENT_DELTA_INCREASE(_delta,_eta_pos,_max_delta) \
_delta = _eta_pos * _delta; \
if ( _delta > _max_delta ) \
_delta = _max_delta;
#define CALC_RESILIENT_DELTA_DECREASE(_delta,_eta_neg,_min_delta) \
_delta = _eta_neg * _delta; \
if ( _delta < _min_delta ) \
_delta = _min_delta;
#define CALC_RESILIENT_DS(_dS,_S,_desc_w) \
_dS = sign(_S) * sign(_desc_w);
/* locals */
static int maxMlps = -1;
static struct mlp_vars **pMlpVA = NULL;
static int nRegisteredMlps = -1;
static int *mlpRegistered = NULL;
int mlpLibInit (
uint16_t nrMlps)
{
int i;
maxMlps = nrMlps;
mlpRegistered = malloc (sizeof (*mlpRegistered) * maxMlps);
pMlpVA = malloc (sizeof (**pMlpVA) * maxMlps);
nRegisteredMlps = 0;
for (i = 0; i < maxMlps; i++)
{
mlpRegistered[i] = 0;
}
return 0;
}
int mlpLibDeinit (
)
{
free (mlpRegistered);
free (pMlpVA);
return 0;
}
/*local function prototypes*/
static int allocateWeights (
struct mlp_vars *pMlpV);
static int initializeWeights (
struct mlp_vars *pMlpV,
int verbose,
unsigned int seed);
static double randomVal (
double min,
double max);
/*implementation*/
#define TRANSFKT(Y,X,TYPE,BETA) \
/*Transferfunktion*/ \
if (TYPE==0) { \
/*Logistische Funktion*/ \
Y = 1.0 / (1.0 + exp(-X)); \
} \
else if (TYPE==1) { \
/*Fermi Funktion*/ \
Y = 1.0 / (1.0 + exp(-BETA*X)); \
} \
else if (TYPE==2) { \
/*Tangens hyperbolicus*/ \
Y = tanh(X); \
} \
else { \
Y = X; \
}
#define TRANSFKT_DERIVATIVE(Y,FX,TYPE,BETA) \
/*1. Ableitung der Transferfunktion*/ \
if (TYPE==0) { \
/*1. Ableitung Logistische Funktion*/ \
Y = FX * (1.0 - FX); \
} \
else if (TYPE==1) { \
/*1. Ableitung Fermi Funktion*/ \
Y = BETA * FX * (1.0 - FX); \
} \
else if (TYPE==2) { \
/*1. Ableitung Tangens hyperbolicus*/ \
Y = 1.0 - (FX * FX); \
} \
else { \
Y = 1; \
}
#define TRANSFKT_DERIVATIVE_2(Y,FX,TYPE,BETA) \
/*2. Ableitung der Transferfunktion*/ \
if (TYPE==0) { \
/*2. Ableitung Logistische Funktion*/ \
Y = FX * ((1.0 - FX) * ((1.0 - FX) - FX)); \
} \
else if (TYPE==1) { \
/*2. Ableitung Fermi Funktion*/ \
Y = BETA * FX * ((1.0 - FX) * ((1.0 - FX) - FX)); \
} \
else if (TYPE==2) { \
/*2. Ableitung Tangens hyperbolicus*/ \
Y = -2.0 * (FX - pow(FX, 3.0)); \
} \
else { \
Y = 0; \
}
static int allocateWeights (
struct mlp_vars *pMlpV)
{
uint16_t l;
int ret;
if (pMlpV == NULL)
return -1;
/*Speicher allozieren fuer w[pMlpV->mlpIv.nrHiddenLayers][pMlpV->mlpIv.m][pMlpV->mlpIv.h] */
pMlpV->w = (double ***) malloc (pMlpV->mlpIv.nrHiddenLayers * sizeof (double **));
if (pMlpV->w == NULL)
{
printf ("### not enough memory to allocate w.\n");
return -2;
}
pMlpV->w_prime = (double ***) malloc (pMlpV->mlpIv.nrHiddenLayers * sizeof (double **));
if (pMlpV->w_prime == NULL)
{
printf ("### not enough memory to allocate w_prime.\n");
return -2;
}
/*Speicher allozieren fuer theta[pMlpV->mlpIv.nrHiddenLayers][zeile] */
pMlpV->theta = (double **) malloc (pMlpV->mlpIv.nrHiddenLayers * sizeof (double *));
if (pMlpV->theta == NULL)
{
printf ("### not enough memory to allocate theta1.\n");
return -3;
}
pMlpV->theta_prime = (double **) malloc (pMlpV->mlpIv.nrHiddenLayers * sizeof (double *));
if (pMlpV->theta_prime == NULL)
{
printf ("### not enough memory to allocate theta1_prime.\n");
return -3;
}
for (l = 0; l < pMlpV->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
ret = allocateMatrix2 (&pMlpV->w[l], pMlpV->mlpIv.m, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->w_prime[l], pMlpV->mlpIv.m, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
}
else
{
ret = allocateMatrix2 (&pMlpV->w[l], pMlpV->mlpIv.h[l - 1], pMlpV->mlpIv.h[l]);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->w_prime[l], pMlpV->mlpIv.h[l - 1], pMlpV->mlpIv.h[l]);
if (ret)
return -2;
}
ret = allocateVector (&pMlpV->theta[l], pMlpV->mlpIv.h[l]);
if (ret)
return -2;
ret = allocateVector (&pMlpV->theta_prime[l], pMlpV->mlpIv.h[l]);
if (ret)
return -2;
}
/*Speicher allozieren fuer w2[zeile][spalte] */
ret = allocateMatrix2 (&pMlpV->w2, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1], pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->w2_prime, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1], pMlpV->mlpIv.n);
if (ret)
return -2;
/*Speicher allozieren fuer theta2[zeile] */
ret = allocateVector (&pMlpV->theta2, pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateVector (&pMlpV->theta2_prime, pMlpV->mlpIv.n);
if (ret)
return -2;
return 0;
}
static int initializeWeights (
struct mlp_vars *pMlpV,
int verbose,
unsigned int seed)
{
uint16_t k, i, i2, j, l;
int ret;
if (pMlpV == NULL)
return -1;
/*Allocate weights first */
ret = allocateWeights (pMlpV);
if (ret)
return -2;
/*Schritt 1: Initialisierung */
srandom (seed);
// Attention: The _prime weights are only used for TDC_MODE and they are just set to zero
/* Hidden Layer */
for (l = 0; l < pMlpV->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
for (k = 0; k < pMlpV->mlpIv.m; k++)
{
for (i = 0; i < pMlpV->mlpIv.h[l]; i++)
{
double val = pMlpV->a;
if(pMlpV->weightNormalizedInitialization == 1)
val *= 1.0 / sqrt(pMlpV->mlpIv.m);
else if(pMlpV->weightNormalizedInitialization == 2)
val *= sqrt(6.0 / (pMlpV->mlpIv.m + pMlpV->mlpIv.h[l]));
pMlpV->w[l][k][i] = randomVal (-val, val);
pMlpV->w_prime[l][k][i] = 0;
}
}
}
else
{
for (i = 0; i < pMlpV->mlpIv.h[l - 1]; i++)
{
for (i2 = 0; i2 < pMlpV->mlpIv.h[l]; i2++)
{
double val = pMlpV->a;
if(pMlpV->weightNormalizedInitialization == 1)
val *= 1.0 / sqrt(pMlpV->mlpIv.h[l - 1]);
else if(pMlpV->weightNormalizedInitialization == 2)
val *= sqrt(6.0 / (pMlpV->mlpIv.h[l - 1] + pMlpV->mlpIv.h[l]));
pMlpV->w[l][i][i2] = randomVal (-val, val);
pMlpV->w_prime[l][i][i2] = 0;
}
}
}
for (i = 0; i < pMlpV->mlpIv.h[l]; i++)
{
if(pMlpV->thresholdZeroInitialization)
pMlpV->theta[l][i] = 0;
else
{
double val = pMlpV->a;
if(pMlpV->weightNormalizedInitialization == 1)
{
if(l == 0)
val *= 1.0 / sqrt(pMlpV->mlpIv.m);
else
val *= 1.0 / sqrt(pMlpV->mlpIv.h[l - 1]);
}
else if(pMlpV->weightNormalizedInitialization == 2)
{
if(l == 0)
val *= sqrt(6.0 / (pMlpV->mlpIv.m + pMlpV->mlpIv.h[l]));
else
val *= sqrt(6.0 / (pMlpV->mlpIv.h[l - 1] + pMlpV->mlpIv.h[l]));
}
pMlpV->theta[l][i] = randomVal (-val, val);
}
pMlpV->theta_prime[l][i] = 0;
}
}
/* output layer */
for (i = 0; i < pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1]; i++)
{
for (j = 0; j < pMlpV->mlpIv.n; j++)
{
double val = pMlpV->a;
if(pMlpV->aOut > 0)
val = pMlpV->aOut;
if(pMlpV->weightNormalizedInitialization == 1)
val *= 1.0 / sqrt(pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1]);
else if(pMlpV->weightNormalizedInitialization == 2)
val *= sqrt(6.0 / (pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + pMlpV->mlpIv.n));
pMlpV->w2[i][j] = randomVal (-val, val);
pMlpV->w2_prime[i][j] = 0;
}
}
for (j = 0; j < pMlpV->mlpIv.n; j++)
{
if(pMlpV->thresholdZeroInitialization)
pMlpV->theta2[j] = 0;
else
{
double val = pMlpV->a;
if(pMlpV->aOut > 0)
val = pMlpV->aOut;
if(pMlpV->weightNormalizedInitialization == 1)
val *= 1.0 / sqrt(pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1]);
else if(pMlpV->weightNormalizedInitialization == 2)
val *= sqrt(6.0 / (pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + pMlpV->mlpIv.n));
pMlpV->theta2[j] = randomVal (-val, val);
}
pMlpV->theta2_prime[j] = 0;
}
return 0;
}
static int mlp_reset_specialvars (
int mlpfd)
{
uint16_t k, i, i2, j;
int32_t l; /*wegen for Schleife => Fehlerrückvermittlung... */
if (pMlpVA[mlpfd] == NULL)
return -1;
double eta = pMlpVA[mlpfd]->mlpP.eta_start;
if(pMlpVA[mlpfd]->mlpP.etaNormalize)
eta /= (double) pMlpVA[mlpfd]->micro_max;
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
pMlpVA[mlpfd]->delta_w1[l][k][i] = 0;
pMlpVA[mlpfd]->eta_w[l][k][i] = eta;
pMlpVA[mlpfd]->desc_w[l][k][i] = 0;
}
}
}
else
{
for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
pMlpVA[mlpfd]->delta_w1[l][i2][i] = 0;
pMlpVA[mlpfd]->eta_w[l][i2][i] = eta;
pMlpVA[mlpfd]->desc_w[l][i2][i] = 0;
}
}
}
}
for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)
{ /*h+1 */
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
pMlpVA[mlpfd]->delta_w2[i][j] = 0;
pMlpVA[mlpfd]->eta_w2[i][j] = eta;
pMlpVA[mlpfd]->desc_w2[i][j] = 0;
}
}
return 0;
}
static double randomVal (
double min,
double max)
{
if(min == 0 && max == 0)
return 0;
double val = min + ((max - min) * random () / (RAND_MAX + 1.0));
return val;
}
int openMlpParameterFile (
const char *filename,
struct mlp_init_values *pMlpInitVals,
struct mlp_param *pMlpP,
uint32_t *seed,
double *a,
double *aOut,
int *weightNormalizedInitialization,
int *thresholdZeroInitialization)
{
FILE *fp;
char var[512], value[512], line[512];
int i = 0;
char str[1000];
if (pMlpP == NULL)
return -1;
if (pMlpInitVals == NULL)
return -2;
/* Set defaults (all zero) */
memset(pMlpP, 0, sizeof(struct mlp_param));
fp = fopen (filename, "r");
if (fp)
{
while (fgets (line, sizeof (line), fp))
{
memset (var, 0, sizeof (var));
memset (value, 0, sizeof (value));
if (sscanf (line, "%[^ \t=]%*[\t ]=%*[\t ]%[^\n]", var, value) == 2)
{
if (strcmp (var, "seed") == 0)
*seed = atoi (value);
if (strcmp (var, "a") == 0)
*a = atof (value);
if (strcmp (var, "aOut") == 0)
*aOut = atof (value);
if (strcmp (var, "weightNormalizedInitialization") == 0)
*weightNormalizedInitialization = atoi (value);
if (strcmp (var, "thresholdZeroInitialization") == 0)
*thresholdZeroInitialization = atoi (value);
if (strcmp (var, "nrHiddenLayers") == 0)
pMlpInitVals->nrHiddenLayers = atoi (value);
for (i = 0; i < pMlpInitVals->nrHiddenLayers; i++)
{
sprintf (str, "h%i", i);
if (strcmp (var, str) == 0)
pMlpInitVals->h[i] = atoi (value);
}
if (strcmp (var, "m") == 0)
pMlpInitVals->m = atoi (value);
if (strcmp (var, "n") == 0)
pMlpInitVals->n = atoi (value);
if (strcmp (var, "maxIterations") == 0)
pMlpP->maxIterations = atoi (value);
if (strcmp (var, "eta1") == 0)
pMlpP->eta1 = atof (value);
if (strcmp (var, "eta2") == 0)
pMlpP->eta2 = atof (value);
if (strcmp (var, "etaNormalize") == 0)
pMlpP->etaNormalize = atoi (value);
if (strcmp (var, "epsilon") == 0)
pMlpP->epsilon = atof (value);
if (strcmp (var, "transFktTypeHidden") == 0)
pMlpInitVals->transFktTypeHidden = atoi (value);
if (strcmp (var, "transFktTypeOutput") == 0)
pMlpInitVals->transFktTypeOutput = atoi (value);
if (strcmp (var, "hasThresholdOutput") == 0)
pMlpInitVals->hasThresholdOutput = atoi (value);
if (strcmp (var, "beta") == 0)
pMlpP->beta = atof (value);
if (strcmp (var, "eta_pos") == 0)
pMlpP->eta_pos = atof (value);
if (strcmp (var, "eta_neg") == 0)
pMlpP->eta_neg = atof (value);
if (strcmp (var, "eta_start") == 0)
pMlpP->eta_start = atof (value);
if (strcmp (var, "eta_max") == 0)
pMlpP->eta_max = atof (value);
if (strcmp (var, "eta_min") == 0)
pMlpP->eta_min = atof (value);
if (strcmp (var, "beta_max") == 0)
pMlpP->beta_max = atof (value);
if (strcmp (var, "alpha") == 0)
pMlpP->alpha = atof (value);
if (strcmp (var, "trainingMode") == 0)
pMlpP->trainingMode = atoi (value);
if (strcmp (var, "verboseOutput") == 0)
pMlpP->verboseOutput = atoi (value);
}
} /*while */
fclose (fp);
} /*if */
else
{
return -2;
}
return 0;
}
int initializeMlpNet (
struct mlp_init_values *pMlpInitVals,
struct mlp_param *pMlpParam,
double a,
double aOut,
int weightNormalizedInitialization,
int thresholdZeroInitialization,
uint32_t micro_max,
unsigned int seed)
{
int ret;
uint16_t i, l;
struct mlp_vars *pMlpV = NULL;
if ((!pMlpInitVals->m) || (!pMlpInitVals->h) || (!pMlpInitVals->n) || (!pMlpInitVals->nrHiddenLayers))
return -2;
pMlpV = malloc (sizeof (*pMlpV));
if (pMlpV == NULL)
{
printf ("### not enough memory to allocate pMlpV.\n");
return -3;
}
pMlpV->mlpIv.m = pMlpInitVals->m;
pMlpV->mlpIv.nrHiddenLayers = pMlpInitVals->nrHiddenLayers;
for (l = 0; l < pMlpV->mlpIv.nrHiddenLayers; l++)
pMlpV->mlpIv.h[l] = pMlpInitVals->h[l];
pMlpV->mlpIv.n = pMlpInitVals->n;
pMlpV->mlpIv.transFktTypeHidden = pMlpInitVals->transFktTypeHidden;
pMlpV->mlpIv.transFktTypeOutput = pMlpInitVals->transFktTypeOutput;
pMlpV->mlpIv.hasThresholdOutput = pMlpInitVals->hasThresholdOutput;
pMlpV->a = a;
pMlpV->aOut = aOut;
pMlpV->weightNormalizedInitialization = weightNormalizedInitialization;
pMlpV->thresholdZeroInitialization = thresholdZeroInitialization;
pMlpV->micro_max = micro_max;
ret = initializeWeights (pMlpV, 0, seed);
if (ret)
{
free (pMlpV);
return -4;
}
/*Speicher allozieren fuer eta[pMlpV->mlpIv.nrHiddenLayers][pMlpV->mlpIv.m+1][pMlpV->mlpIv.h[l]] */
pMlpV->eta_w = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));
if (pMlpV->eta_w == NULL)
{
printf ("### not enough memory to allocate eta_w.\n");
return -5;
}
/*Speicher allozieren fuer desc_w[pMlpV->mlpIv.nrHiddenLayers][pMlpV->mlpIv.m+1][pMlpV->mlpIv.h[l]] */
pMlpV->desc_w = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));
if (pMlpV->desc_w == NULL)
{
printf ("### not enough memory to allocate desc_w.\n");
return -6;
}
/*Speicher allozieren fuer delta_w1[pMlpV->mlpIv.nrHiddenLayers][pMlpV->mlpIv.m+1][pMlpV->mlpIv.h[l]] */
pMlpV->delta_w1 = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));
if (pMlpV->delta_w1 == NULL)
{
printf ("### not enough memory to allocate delta_w1.\n");
return -7;
}
/*Speicher allozieeren fuer u[pMlpV->mlpIv.nrHiddenLayers][pMlpV->mlpIv.h[l]] */
pMlpV->u = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));
if (pMlpV->u == NULL)
{
printf ("### not enough memory to allocate u.\n");
return -8;
}
/*Speicher allozieren fuer pData->y[pMlpV->mlpIv.nrHiddenLayers][micro_max][pMlpV->mlpIv.h[l]] */
pMlpV->y = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));
if (pMlpV->y == NULL)
{
printf ("### not enough memory to allocate y.\n");
return -9;
}
pMlpV->y_tsignal = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));
if (pMlpV->y_tsignal == NULL)
{
printf ("### not enough memory to allocate y_tsignal.\n");
return -9;
}
/*Speicher allozieeren fuer delta[pMlpV->mlpIv.nrHiddenLayers][micro_max][pMlpV->mlpIv.h[l]] */
pMlpV->delta = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));
if (pMlpV->delta == NULL)
{
printf ("### not enough memory to allocate delta.\n");
return -10;
}
/*Speicher allozieeren fuer delta[pMlpV->mlpIv.nrHiddenLayers][micro_max][pMlpV->mlpIv.h[l]] */
pMlpV->gradvec = (double ****) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double ***));
if (pMlpV->gradvec == NULL)
{
printf ("### not enough memory to allocate gradvec.\n");
return -10;
}
pMlpV->gradvec_tsignal = (double ****) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double ***));
if (pMlpV->gradvec_tsignal == NULL)
{
printf ("### not enough memory to allocate gradvec_tsignal.\n");
return -10;
}
pMlpV->grad2vec = (double ****) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double ***));
if (pMlpV->grad2vec == NULL)
{
printf ("### not enough memory to allocate grad2vec.\n");
return -10;
}
pMlpV->gradientTrace = (double ****) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double ***));
if (pMlpV->gradientTrace == NULL)
{
printf ("### not enough memory to allocate gradientTrace.\n");
return -10;
}
for (l = 0; l < pMlpV->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
ret = allocateMatrix2 (&pMlpV->eta_w[l], pMlpV->mlpIv.m + 1, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->desc_w[l], pMlpV->mlpIv.m + 1, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->delta_w1[l], pMlpV->mlpIv.m + 1, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
}
else
{
ret = allocateMatrix2 (&pMlpV->eta_w[l], pMlpV->mlpIv.h[l - 1] + 1, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->desc_w[l], pMlpV->mlpIv.h[l - 1] + 1, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->delta_w1[l], pMlpV->mlpIv.h[l - 1] + 1, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
}
if(l == 0)
{
if(l == pMlpV->mlpIv.nrHiddenLayers - 1)
{
// Naechste Schicht ist die Ausgabeschicht
ret = allocateArray3 (&pMlpV->gradvec[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateArray3 (&pMlpV->gradvec_tsignal[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateArray3 (&pMlpV->gradientTrace[l], pMlpV->mlpIv.h[l], pMlpV->mlpIv.n, pMlpV->mlpIv.m + 1);
if (ret)
return -2;
}
else
{
// Naechste Schicht ist die naechste Zwischenschicht
ret = allocateArray3 (&pMlpV->gradvec[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1]);
if (ret)
return -2;
ret = allocateArray3 (&pMlpV->gradvec_tsignal[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1]);
if (ret)
return -2;
ret = allocateArray3 (&pMlpV->gradientTrace[l], pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1], pMlpV->mlpIv.m + 1);
if (ret)
return -2;
}
}
else
{
if(l == pMlpV->mlpIv.nrHiddenLayers - 1)
{
// Naechste Schicht ist die Ausgabeschicht
ret = allocateArray3 (&pMlpV->gradvec[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateArray3 (&pMlpV->gradvec_tsignal[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateArray3 (&pMlpV->gradientTrace[l], pMlpV->mlpIv.h[l], pMlpV->mlpIv.n, pMlpV->mlpIv.h[l - 1] + 1);
if (ret)
return -2;
}
else
{
// Naechste Schicht ist die naechste Zwischenschicht
ret = allocateArray3 (&pMlpV->gradvec[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1]);
if (ret)
return -2;
ret = allocateArray3 (&pMlpV->gradvec_tsignal[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1]);
if (ret)
return -2;
ret = allocateArray3 (&pMlpV->gradientTrace[l], pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1], pMlpV->mlpIv.h[l - 1] + 1);
if (ret)
return -2;
}
}
ret = allocateMatrix2 (&pMlpV->u[l], micro_max, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->y[l], micro_max, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->y_tsignal[l], micro_max, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->delta[l], micro_max, pMlpV->mlpIv.h[l]);
if (ret)
return -2;
ret = allocateArray3 (&pMlpV->grad2vec[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.n);
if (ret)
return -2;
} /* for l */
ret = allocateMatrix2 (&pMlpV->gradientTrace2, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + 1, pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->eta_w2, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + 1, pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->desc_w2, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + 1, pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->delta_w2, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + 1, pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateVector (&pMlpV->u2, pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->y2, micro_max, pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->y2_prime, micro_max, pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->delta2, micro_max, pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->gradvec2, micro_max, pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->gradvec2_tsignal, micro_max, pMlpV->mlpIv.n);
if (ret)
return -2;
ret = allocateMatrix2 (&pMlpV->grad2vec2, micro_max, pMlpV->mlpIv.n);
if (ret)
return -2;
if (nRegisteredMlps < maxMlps)
{
nRegisteredMlps++;
for (i = 0; i < maxMlps; i++)
{
if (mlpRegistered[i] == 0)
{
pMlpVA[i] = pMlpV;
mlpRegistered[i] = 1;
break;
}
}
}
else
{
printf ("### maximum number of mlps exceeded.\n");
return -33;
}
setMlpParam(i, pMlpParam);
mlp_reset_specialvars (i);
clearGradientTrace(i);
return i;
}
int cleanupMlpNet (
int mlpfd)
{
uint16_t l;
if (pMlpVA[mlpfd] == NULL)
return -1;
/*Free everything for the hidden layer... */
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
freeMatrix2 (pMlpVA[mlpfd]->w[l], pMlpVA[mlpfd]->mlpIv.m);
freeMatrix2 (pMlpVA[mlpfd]->w_prime[l], pMlpVA[mlpfd]->mlpIv.m);
}
else
{
freeMatrix2 (pMlpVA[mlpfd]->w[l], pMlpVA[mlpfd]->mlpIv.h[l - 1]);
freeMatrix2 (pMlpVA[mlpfd]->w_prime[l], pMlpVA[mlpfd]->mlpIv.h[l - 1]);
}
freeVector (pMlpVA[mlpfd]->theta[l]);
freeVector (pMlpVA[mlpfd]->theta_prime[l]);
}
freeMatrix2 (pMlpVA[mlpfd]->w2, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]);
freeMatrix2 (pMlpVA[mlpfd]->w2_prime, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]);
freeVector (pMlpVA[mlpfd]->theta2);
freeVector (pMlpVA[mlpfd]->theta2_prime);
free (pMlpVA[mlpfd]->w);
free (pMlpVA[mlpfd]->w_prime);
free (pMlpVA[mlpfd]->theta);
free (pMlpVA[mlpfd]->theta_prime);
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
freeMatrix2 (pMlpVA[mlpfd]->eta_w[l], pMlpVA[mlpfd]->mlpIv.m + 1);
freeMatrix2 (pMlpVA[mlpfd]->desc_w[l], pMlpVA[mlpfd]->mlpIv.m + 1);
freeMatrix2 (pMlpVA[mlpfd]->delta_w1[l], pMlpVA[mlpfd]->mlpIv.m + 1);
}
else
{
freeMatrix2 (pMlpVA[mlpfd]->eta_w[l], pMlpVA[mlpfd]->mlpIv.h[l - 1] + 1);
freeMatrix2 (pMlpVA[mlpfd]->desc_w[l], pMlpVA[mlpfd]->mlpIv.h[l - 1] + 1);
freeMatrix2 (pMlpVA[mlpfd]->delta_w1[l], pMlpVA[mlpfd]->mlpIv.h[l - 1] + 1);
}
if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1)
{
freeArray3 (pMlpVA[mlpfd]->gradientTrace[l], pMlpVA[mlpfd]->mlpIv.h[l], pMlpVA[mlpfd]->mlpIv.n);
}
else
{
freeArray3 (pMlpVA[mlpfd]->gradientTrace[l], pMlpVA[mlpfd]->mlpIv.h[l], pMlpVA[mlpfd]->mlpIv.h[l + 1]);
}
freeMatrix2 (pMlpVA[mlpfd]->u[l], pMlpVA[mlpfd]->micro_max);
freeMatrix2 (pMlpVA[mlpfd]->y[l], pMlpVA[mlpfd]->micro_max);
freeMatrix2 (pMlpVA[mlpfd]->y_tsignal[l], pMlpVA[mlpfd]->micro_max);
freeMatrix2 (pMlpVA[mlpfd]->delta[l], pMlpVA[mlpfd]->micro_max);
freeArray3 (pMlpVA[mlpfd]->gradvec[l], pMlpVA[mlpfd]->micro_max, pMlpVA[mlpfd]->mlpIv.h[l]);
freeArray3 (pMlpVA[mlpfd]->gradvec_tsignal[l], pMlpVA[mlpfd]->micro_max, pMlpVA[mlpfd]->mlpIv.h[l]);
freeArray3 (pMlpVA[mlpfd]->grad2vec[l], pMlpVA[mlpfd]->micro_max, pMlpVA[mlpfd]->mlpIv.h[l]);
}
freeMatrix2 (pMlpVA[mlpfd]->gradientTrace2, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1] + 1);
freeMatrix2 (pMlpVA[mlpfd]->eta_w2, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1] + 1);
freeMatrix2 (pMlpVA[mlpfd]->desc_w2, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1] + 1);
freeMatrix2 (pMlpVA[mlpfd]->delta_w2, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1] + 1);
freeVector (pMlpVA[mlpfd]->u2);
freeMatrix2 (pMlpVA[mlpfd]->y2, pMlpVA[mlpfd]->micro_max);
freeMatrix2 (pMlpVA[mlpfd]->y2_prime, pMlpVA[mlpfd]->micro_max);
freeMatrix2 (pMlpVA[mlpfd]->delta2, pMlpVA[mlpfd]->micro_max);
freeMatrix2 (pMlpVA[mlpfd]->gradvec2, pMlpVA[mlpfd]->micro_max);
freeMatrix2 (pMlpVA[mlpfd]->gradvec2_tsignal, pMlpVA[mlpfd]->micro_max);
freeMatrix2 (pMlpVA[mlpfd]->grad2vec2, pMlpVA[mlpfd]->micro_max);
free (pMlpVA[mlpfd]->eta_w);
free (pMlpVA[mlpfd]->desc_w);
free (pMlpVA[mlpfd]->delta_w1);
free (pMlpVA[mlpfd]->u);
free (pMlpVA[mlpfd]->y);
free (pMlpVA[mlpfd]->y_tsignal);
free (pMlpVA[mlpfd]->delta);
free (pMlpVA[mlpfd]->gradvec);
free (pMlpVA[mlpfd]->gradvec_tsignal);
free (pMlpVA[mlpfd]->grad2vec);
free (pMlpVA[mlpfd]->gradientTrace);
mlpRegistered[mlpfd] = 0;
nRegisteredMlps--;
free (pMlpVA[mlpfd]);
return 0;
}
int outputWeightsStatistics (
int mlpfd)
{
uint16_t k, i, i2, j, l;
uint32_t index;
double *vals;
double mean, variance;
if (pMlpVA[mlpfd] == NULL)
return -1;
printf("'Zero' weights are in interval [-%lf,%lf]\n", ZERO_PRECISION, ZERO_PRECISION);
unsigned long nZeroWeights;
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
printf ("weights hidden layer (%i):\n", l);
if (l == 0)
{
index = 0;
vals = malloc (sizeof (double) * pMlpVA[mlpfd]->mlpIv.m * pMlpVA[mlpfd]->mlpIv.h[l]);
nZeroWeights = 0;
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)
{
vals[index] = pMlpVA[mlpfd]->w[l][k][i];
index++;
if(pMlpVA[mlpfd]->w[l][k][i] >= - ZERO_PRECISION && pMlpVA[mlpfd]->w[l][k][i] <= ZERO_PRECISION)
nZeroWeights++;
}
}
mean = gsl_stats_mean (vals, 1, index);
variance = gsl_stats_variance (vals, 1, index);
printf ("The sample mean is %g\n", mean);
printf ("The estimated variance is %g\n", variance);
free (vals);
index = 0;
}
else
{
vals = malloc (sizeof (double) * pMlpVA[mlpfd]->mlpIv.h[l - 1] * pMlpVA[mlpfd]->mlpIv.h[l]);
nZeroWeights = 0;
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
vals[index] = pMlpVA[mlpfd]->w[l][i2][i];
index++;
if(pMlpVA[mlpfd]->w[l][i2][i] >= - ZERO_PRECISION && pMlpVA[mlpfd]->w[l][i2][i] <= ZERO_PRECISION)
nZeroWeights++;
}
}
mean = gsl_stats_mean (vals, 1, index);
variance = gsl_stats_variance (vals, 1, index);
printf ("The sample mean is %g\n", mean);
printf ("The estimated variance is %g\n", variance);
free (vals);
index = 0;
}
printf ("bias hidden layer (%i):\n", l);
vals = malloc (sizeof (double) * pMlpVA[mlpfd]->mlpIv.h[l]);
nZeroWeights = 0;
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
vals[index] = pMlpVA[mlpfd]->theta[l][i];
index++;
if(pMlpVA[mlpfd]->theta[l][i] >= - ZERO_PRECISION && pMlpVA[mlpfd]->theta[l][i] <= ZERO_PRECISION)
nZeroWeights++;
}
mean = gsl_stats_mean (vals, 1, index);
variance = gsl_stats_variance (vals, 1, index);
printf ("The sample mean is %g\n", mean);
printf ("The estimated variance is %g\n", variance);
free (vals);
index = 0;
}
printf ("weights output layer:\n");
vals = malloc (sizeof (double) * pMlpVA[mlpfd]->mlpIv.n * pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]);
nZeroWeights = 0;
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)
{
vals[index] = pMlpVA[mlpfd]->w2[i][j];
index++;
if(pMlpVA[mlpfd]->w2[i][j] >= - ZERO_PRECISION && pMlpVA[mlpfd]->w2[i][j] <= ZERO_PRECISION)
nZeroWeights++;
}
}
mean = gsl_stats_mean (vals, 1, index);
variance = gsl_stats_variance (vals, 1, index);
printf ("The sample mean is %g\n", mean);
printf ("The estimated variance is %g\n", variance);
free (vals);
index = 0;
printf ("bias output layer:\n");
vals = malloc (sizeof (double) * pMlpVA[mlpfd]->mlpIv.n);
nZeroWeights = 0;
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
vals[index] = pMlpVA[mlpfd]->theta2[j];
index++;
if(pMlpVA[mlpfd]->theta2[j] >= - ZERO_PRECISION && pMlpVA[mlpfd]->theta2[j] <= ZERO_PRECISION)
nZeroWeights++;
}
mean = gsl_stats_mean (vals, 1, index);
variance = gsl_stats_variance (vals, 1, index);
printf ("The sample mean is %g\n", mean);
printf ("The estimated variance is %g\n", variance);
free (vals);
index = 0;
return 0;
}
int outputWeights (
int mlpfd)
{
uint16_t k, i, i2, j, l;
if (pMlpVA[mlpfd] == NULL)
return -1;
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
printf ("weights hidden layer (%i)\n", l);
if (l == 0)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)
{
printf ("%lf ", pMlpVA[mlpfd]->w[l][k][i]);
}
printf ("\n");
}
}
else
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
printf ("%lf ", pMlpVA[mlpfd]->w[l][i2][i]);
}
printf ("\n");
}
}
printf ("bias hidden layer\n");
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
printf ("%lf ", pMlpVA[mlpfd]->theta[l][i]);
}
printf ("\n");
}
printf ("weights output layer\n");
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)
{
printf ("%lf ", pMlpVA[mlpfd]->w2[i][j]);
}
printf ("\n");
}
printf ("bias output layer\n");
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
printf ("%lf ", pMlpVA[mlpfd]->theta2[j]);
}
printf ("\n");
return 0;
}
int setMlpParam (
int mlpfd,
struct mlp_param *pMlpP)
{
if (pMlpVA[mlpfd] == NULL)
return -1;
if (pMlpP == NULL)
return -2;
pMlpVA[mlpfd]->mlpP.maxIterations = pMlpP->maxIterations;
pMlpVA[mlpfd]->mlpP.eta1 = pMlpP->eta1;
pMlpVA[mlpfd]->mlpP.eta2 = pMlpP->eta2;
pMlpVA[mlpfd]->mlpP.etaNormalize = pMlpP->etaNormalize;
pMlpVA[mlpfd]->mlpP.epsilon = pMlpP->epsilon;
pMlpVA[mlpfd]->mlpP.beta = pMlpP->beta;
pMlpVA[mlpfd]->mlpP.eta_pos = pMlpP->eta_pos;
pMlpVA[mlpfd]->mlpP.eta_neg = pMlpP->eta_neg;
pMlpVA[mlpfd]->mlpP.eta_start = pMlpP->eta_start;
pMlpVA[mlpfd]->mlpP.eta_max = pMlpP->eta_max;
pMlpVA[mlpfd]->mlpP.eta_min = pMlpP->eta_min;
pMlpVA[mlpfd]->mlpP.alpha = pMlpP->alpha;
pMlpVA[mlpfd]->mlpP.beta_max = pMlpP->beta_max;
pMlpVA[mlpfd]->mlpP.trainingMode = pMlpP->trainingMode;
pMlpVA[mlpfd]->mlpP.verboseOutput = pMlpP->verboseOutput;
return 0;
}
int getMlpParam (
int mlpfd,
struct mlp_param *pMlpP)
{
if (pMlpVA[mlpfd] == NULL)
return -1;
if (pMlpP == NULL)
return -2;
pMlpP->maxIterations = pMlpVA[mlpfd]->mlpP.maxIterations;
pMlpP->eta1 = pMlpVA[mlpfd]->mlpP.eta1;
pMlpP->eta2 = pMlpVA[mlpfd]->mlpP.eta2;
pMlpP->etaNormalize = pMlpVA[mlpfd]->mlpP.etaNormalize;
pMlpP->epsilon = pMlpVA[mlpfd]->mlpP.epsilon;
pMlpP->beta = pMlpVA[mlpfd]->mlpP.beta;
pMlpP->eta_pos = pMlpVA[mlpfd]->mlpP.eta_pos;
pMlpP->eta_neg = pMlpVA[mlpfd]->mlpP.eta_neg;
pMlpP->eta_start = pMlpVA[mlpfd]->mlpP.eta_start;
pMlpP->eta_max = pMlpVA[mlpfd]->mlpP.eta_max;
pMlpP->eta_min = pMlpVA[mlpfd]->mlpP.eta_min;
pMlpP->alpha = pMlpVA[mlpfd]->mlpP.alpha;
pMlpP->beta_max = pMlpVA[mlpfd]->mlpP.beta_max;
pMlpP->trainingMode = pMlpVA[mlpfd]->mlpP.trainingMode;
pMlpP->verboseOutput = pMlpVA[mlpfd]->mlpP.verboseOutput;
return 0;
}
int getMlpInitValues (
int mlpfd,
struct mlp_init_values *pMlpInitVals)
{
uint16_t l;
if (pMlpVA[mlpfd] == NULL)
return -1;
if (pMlpInitVals == NULL)
return -2;
pMlpInitVals->m = pMlpVA[mlpfd]->mlpIv.m;
pMlpInitVals->nrHiddenLayers = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers;
for (l = 0; l < pMlpInitVals->nrHiddenLayers; l++)
pMlpInitVals->h[l] = pMlpVA[mlpfd]->mlpIv.h[l];
pMlpInitVals->n = pMlpVA[mlpfd]->mlpIv.n;
pMlpInitVals->transFktTypeHidden = pMlpVA[mlpfd]->mlpIv.transFktTypeHidden;
pMlpInitVals->transFktTypeOutput = pMlpVA[mlpfd]->mlpIv.transFktTypeOutput;
pMlpInitVals->hasThresholdOutput = pMlpVA[mlpfd]->mlpIv.hasThresholdOutput;
return 0;
}
int clearGradientTrace (
int mlpfd)
{
uint16_t k, i, i2, j;
int32_t l; /*wegen for Schleife => Fehlerrückvermittlung... */
if (pMlpVA[mlpfd] == NULL)
return -1;
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)
{ /*m+1 */
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
int maxJ;
if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1)
maxJ = pMlpVA[mlpfd]->mlpIv.n;
else
maxJ = pMlpVA[mlpfd]->mlpIv.h[l + 1];
for (j = 0; j < maxJ; j++)
pMlpVA[mlpfd]->gradientTrace[l][i][j][k] = 0;
}
}
}
else
{
for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{ /*h+1 */
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
int maxJ;
if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1)
maxJ = pMlpVA[mlpfd]->mlpIv.n;
else
maxJ = pMlpVA[mlpfd]->mlpIv.h[l + 1];
for (j = 0; j < maxJ; j++)
pMlpVA[mlpfd]->gradientTrace[l][i][j][i2] = 0;
}
}
}
}
for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)
{ /*h+1 */
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
pMlpVA[mlpfd]->gradientTrace2[i][j] = 0;
}
return 0;
}
int mlpSave (
int mlpfd,
const char *filename)
{
FILE *fp;
uint16_t i, i2, j, k, l;
if (pMlpVA[mlpfd] == NULL)
return -1;
fp = fopen (filename, "w");
if (fp == NULL)
return -2;
if (fwrite (&pMlpVA[mlpfd]->mlpIv.m, sizeof (pMlpVA[mlpfd]->mlpIv.m), 1, fp) != 1)
{
fclose (fp);
return -15;
}
if (fwrite (&pMlpVA[mlpfd]->mlpIv.n, sizeof (pMlpVA[mlpfd]->mlpIv.n), 1, fp) != 1)
{
fclose (fp);
return -17;
}
if (fwrite (&pMlpVA[mlpfd]->mlpIv.nrHiddenLayers, sizeof (pMlpVA[mlpfd]->mlpIv.nrHiddenLayers), 1, fp) != 1)
{
fclose (fp);
return -17;
}
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (fwrite (&pMlpVA[mlpfd]->mlpIv.h[l], sizeof (pMlpVA[mlpfd]->mlpIv.h[l]), 1, fp) != 1)
{
fclose (fp);
return -16;
}
}
if (fwrite (&pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, sizeof (pMlpVA[mlpfd]->mlpIv.transFktTypeHidden), 1, fp) != 1)
{
fclose (fp);
return -7;
}
if (fwrite (&pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, sizeof (pMlpVA[mlpfd]->mlpIv.transFktTypeOutput), 1, fp) != 1)
{
fclose (fp);
return -7;
}
if (fwrite (&pMlpVA[mlpfd]->a, sizeof (pMlpVA[mlpfd]->a), 1, fp) != 1)
{
fclose (fp);
return -6;
}
if (fwrite (&pMlpVA[mlpfd]->mlpIv.hasThresholdOutput, sizeof (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput), 1, fp) != 1)
{
fclose (fp);
return -7;
}
/* TODO: Remove me (kept for compatibility reasons) */
int junksize = sizeof (pMlpVA[mlpfd]->mlpP.maxIterations) +
sizeof (pMlpVA[mlpfd]->mlpP.eta1) +
sizeof (pMlpVA[mlpfd]->mlpP.eta2) +
sizeof (pMlpVA[mlpfd]->mlpP.epsilon) +
sizeof (pMlpVA[mlpfd]->mlpP.beta) +
sizeof (pMlpVA[mlpfd]->mlpP.eta_pos) +
sizeof (pMlpVA[mlpfd]->mlpP.eta_neg) +
sizeof (pMlpVA[mlpfd]->mlpP.eta_start) +
sizeof (pMlpVA[mlpfd]->mlpP.eta_max) +
sizeof (pMlpVA[mlpfd]->mlpP.alpha) +
sizeof (pMlpVA[mlpfd]->mlpP.trainingMode);
uint8_t junk[junksize];
memset(junk, 0, sizeof(uint8_t) * junksize);
if (fwrite (&junk, junksize, 1, fp) != 1)
{
fclose (fp);
return -18;
}
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (fwrite (&pMlpVA[mlpfd]->w[l][k][i], sizeof (pMlpVA[mlpfd]->w[l][k][i]), 1, fp) != 1)
{
fclose (fp);
return -19;
}
if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
if (fwrite (&pMlpVA[mlpfd]->w_prime[l][k][i], sizeof (pMlpVA[mlpfd]->w_prime[l][k][i]), 1, fp) != 1)
{
fclose (fp);
return -19;
}
}
}
}
}
else
{
for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (fwrite (&pMlpVA[mlpfd]->w[l][i2][i], sizeof (pMlpVA[mlpfd]->w[l][i2][i]), 1, fp) != 1)
{
fclose (fp);
return -19;
}
if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
if (fwrite (&pMlpVA[mlpfd]->w_prime[l][i2][i], sizeof (pMlpVA[mlpfd]->w_prime[l][i2][i]), 1, fp) != 1)
{
fclose (fp);
return -19;
}
}
}
}
}
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (fwrite (&pMlpVA[mlpfd]->theta[l][i], sizeof (pMlpVA[mlpfd]->theta[l][i]), 1, fp) != 1)
{
fclose (fp);
return -20;
}
if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
if (fwrite (&pMlpVA[mlpfd]->theta_prime[l][i], sizeof (pMlpVA[mlpfd]->theta_prime[l][i]), 1, fp) != 1)
{
fclose (fp);
return -20;
}
}
}
}
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)
{
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
if (fwrite (&pMlpVA[mlpfd]->w2[i][j], sizeof (pMlpVA[mlpfd]->w2[i][j]), 1, fp) != 1)
{
fclose (fp);
return -21;
}
if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
if (fwrite (&pMlpVA[mlpfd]->w2_prime[i][j], sizeof (pMlpVA[mlpfd]->w2_prime[i][j]), 1, fp) != 1)
{
fclose (fp);
return -21;
}
}
}
}
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
if (fwrite (&pMlpVA[mlpfd]->theta2[j], sizeof (pMlpVA[mlpfd]->theta2[j]), 1, fp) != 1)
{
fclose (fp);
return -22;
}
if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
if (fwrite (&pMlpVA[mlpfd]->theta2_prime[j], sizeof (pMlpVA[mlpfd]->theta2_prime[j]), 1, fp) != 1)
{
fclose (fp);
return -22;
}
}
}
fclose (fp);
return 0;
}
int mlpRestore (
struct mlp_param *pMlpParam,
const char *filename,
uint32_t micro_max,
unsigned int seed)
{
FILE *fp;
uint16_t i, i2, j, k, l;
struct mlp_init_values mlpInitVals;
double a;
int mlpfd;
fp = fopen (filename, "r");
if (fp == NULL)
return -2;
if (fread (&mlpInitVals.m, sizeof (mlpInitVals.m), 1, fp) != 1)
{
fclose (fp);
return -15;
}
if (fread (&mlpInitVals.n, sizeof (mlpInitVals.n), 1, fp) != 1)
{
fclose (fp);
return -17;
}
if (fread (&mlpInitVals.nrHiddenLayers, sizeof (mlpInitVals.nrHiddenLayers), 1, fp) != 1)
{
fclose (fp);
return -18;
}
for (l = 0; l < mlpInitVals.nrHiddenLayers; l++)
{
if (fread (&mlpInitVals.h[l], sizeof (mlpInitVals.h[l]), 1, fp) != 1)
{
fclose (fp);
return -16;
}
}
if (fread (&mlpInitVals.transFktTypeHidden, sizeof (mlpInitVals.transFktTypeHidden), 1, fp) != 1)
{
fclose (fp);
return -7;
}
if (fread (&mlpInitVals.transFktTypeOutput, sizeof (mlpInitVals.transFktTypeOutput), 1, fp) != 1)
{
fclose (fp);
return -7;
}
if (fread (&a, sizeof (a), 1, fp) != 1)
{
fclose (fp);
return -6;
}
if (fread (&mlpInitVals.hasThresholdOutput, sizeof (mlpInitVals.hasThresholdOutput), 1, fp) != 1)
{
fclose (fp);
return -7;
}
/* TODO: Remove the following line in case the output layer should have a configurable
* threshold. Currently this is done to be able to use the old mlp saves (compatibility reasons) */
mlpInitVals.hasThresholdOutput = 0;
/* TODO: Remove me (compatibility reasons) */
int junksize = sizeof (pMlpVA[mlpfd]->mlpP.maxIterations) +
sizeof (pMlpVA[mlpfd]->mlpP.eta1) +
sizeof (pMlpVA[mlpfd]->mlpP.eta2) +
sizeof (pMlpVA[mlpfd]->mlpP.epsilon) +
sizeof (pMlpVA[mlpfd]->mlpP.beta) +
sizeof (pMlpVA[mlpfd]->mlpP.eta_pos) +
sizeof (pMlpVA[mlpfd]->mlpP.eta_neg) +
sizeof (pMlpVA[mlpfd]->mlpP.eta_start) +
sizeof (pMlpVA[mlpfd]->mlpP.eta_max) +
sizeof (pMlpVA[mlpfd]->mlpP.alpha) +
sizeof (pMlpVA[mlpfd]->mlpP.trainingMode);
uint8_t junk[junksize];
if (fread (&junk, junksize, 1, fp) != 1)
{
fclose (fp);
return -7;
}
mlpfd = initializeMlpNet (&mlpInitVals, pMlpParam, a, 0, 0, 0, micro_max, seed);
if (mlpfd < 0)
return -1;
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (fread (&pMlpVA[mlpfd]->w[l][k][i], sizeof (pMlpVA[mlpfd]->w[l][k][i]), 1, fp) != 1)
{
fclose (fp);
return -20;
}
if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
if (fread (&pMlpVA[mlpfd]->w_prime[l][k][i], sizeof (pMlpVA[mlpfd]->w_prime[l][k][i]), 1, fp) != 1)
{
fclose (fp);
return -20;
}
}
}
}
}
else
{
for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (fread (&pMlpVA[mlpfd]->w[l][i2][i], sizeof (pMlpVA[mlpfd]->w[l][i2][i]), 1, fp) != 1)
{
fclose (fp);
return -21;
}
if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
if (fread (&pMlpVA[mlpfd]->w_prime[l][i2][i], sizeof (pMlpVA[mlpfd]->w_prime[l][i2][i]), 1, fp) != 1)
{
fclose (fp);
return -21;
}
}
}
}
}
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (fread (&pMlpVA[mlpfd]->theta[l][i], sizeof (pMlpVA[mlpfd]->theta[l][i]), 1, fp) != 1)
{
fclose (fp);
return -22;
}
if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
if (fread (&pMlpVA[mlpfd]->theta_prime[l][i], sizeof (pMlpVA[mlpfd]->theta_prime[l][i]), 1, fp) != 1)
{
fclose (fp);
return -22;
}
}
}
}
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)
{
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
if (fread (&pMlpVA[mlpfd]->w2[i][j], sizeof (pMlpVA[mlpfd]->w2[i][j]), 1, fp) != 1)
{
fclose (fp);
return -23;
}
if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
if (fread (&pMlpVA[mlpfd]->w2_prime[i][j], sizeof (pMlpVA[mlpfd]->w2_prime[i][j]), 1, fp) != 1)
{
fclose (fp);
return -23;
}
}
}
}
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
if (fread (&pMlpVA[mlpfd]->theta2[j], sizeof (pMlpVA[mlpfd]->theta2[j]), 1, fp) != 1)
{
fclose (fp);
return -24;
}
if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
if (fread (&pMlpVA[mlpfd]->theta2_prime[j], sizeof (pMlpVA[mlpfd]->theta2_prime[j]), 1, fp) != 1)
{
fclose (fp);
return -24;
}
}
}
fclose (fp);
return mlpfd;
}
int mlpOutput (
int mlpfd,
unsigned long micro_max,
uint32_t offset,
struct train_data *pData)
{
unsigned long micro;
uint16_t k, i, i2, j, l;
double fkt;
if (pMlpVA[mlpfd] == NULL)
return -1;
if ((pData->x == NULL) || (pData->y == NULL))
return -2;
for (micro = 0; micro < micro_max; micro++)
{
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
pMlpVA[mlpfd]->u[l][0][i] = 0;
if (l == 0)
{
for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)
pMlpVA[mlpfd]->u[l][0][i] += pData->x[micro + offset][k] * pMlpVA[mlpfd]->w[l][k][i];
}
else
{
for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
pMlpVA[mlpfd]->u[l][0][i] += pMlpVA[mlpfd]->y[l - 1][0][i2] * pMlpVA[mlpfd]->w[l][i2][i];
}
pMlpVA[mlpfd]->u[l][0][i] -= pMlpVA[mlpfd]->theta[l][i];
TRANSFKT (fkt, pMlpVA[mlpfd]->u[l][0][i], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);
pMlpVA[mlpfd]->y[l][0][i] = fkt;
}
}
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
pMlpVA[mlpfd]->u2[j] = 0;
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)
pMlpVA[mlpfd]->u2[j] += pMlpVA[mlpfd]->y[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][0][i] * pMlpVA[mlpfd]->w2[i][j];
/* don't subtract the threshold of the neuron if the neuron has a linear transfer function */
if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
pMlpVA[mlpfd]->u2[j] -= pMlpVA[mlpfd]->theta2[j];
TRANSFKT (fkt, pMlpVA[mlpfd]->u2[j], pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, pMlpVA[mlpfd]->mlpP.beta);
pData->y[micro + offset][j] = fkt;
}
}
return 0;
}
double mlp (
int mlpfd,
uint32_t micro_max,
struct train_data *pData,
// Attention: Following arguments are only used in combination with Reinforcement Learning.
// Currently, this is for the learning modes: RG_MODE, TDC_MODE
double alpha,
double alpha2,
double gamma,
double lambda,
bool updateFirstLayer,
bool updateSecondLayer,
double *sampleAlphaDiscount,
double gradientPrimeFactor,
double normFactor,
bool checkGradients,
bool tdcOwnSummedGradient,
bool replacingTraces)
{
double E = 0, Emin = 999999999, Elast, Emax = 0;
double fkt;
uint32_t k, i, i2, j;
int32_t l; /*wegen for Schleife => Fehlerrückvermittlung... */
uint32_t micro;
uint32_t muster;
double S, deltaW, dS, beta;
uint32_t numIterations = 0;
int end = 0;
int ouch = 0;
double deltaWeight;
if (pMlpVA[mlpfd] == NULL)
return -1;
if (micro_max > pMlpVA[mlpfd]->micro_max)
return -2;
if ((pData->x == NULL) || (pData->y == NULL))
return -3;
if (!pMlpVA[mlpfd]->mlpP.maxIterations)
end = 1;
if(pMlpVA[mlpfd]->mlpP.trainingMode == RG_MODE ||
pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
// Must be a nonlinear transfer function in hidden layer
if(pMlpVA[mlpfd]->mlpIv.transFktTypeHidden > 2)
return -7;
// Must be a single output neuron
if(pMlpVA[mlpfd]->mlpIv.n != 1)
return -8;
}
// Additional restrictions with TDC
if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
// Must be one hidden layer
if(pMlpVA[mlpfd]->mlpIv.nrHiddenLayers != 1)
return -4;
// Must be a single sample
if(micro_max != 1)
return -5;
}
while (!end)
{
Elast = E;
E = 0;
Emax = 0;
double Evals[micro_max];
long z, maxz;
if((pMlpVA[mlpfd]->mlpP.trainingMode == RG_MODE) ||
(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE))
maxz = 2;
else
maxz = 1;
for(z = maxz - 1; z >=0; z--)
{
for (micro = 0; micro < micro_max; micro++)
{
if(z && (!pData->hasXPrime[micro]))
continue;
/*Schritt 2: Berechnung der Netzausgabe y2 (Vorwärtsphase) */
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
pMlpVA[mlpfd]->u[l][micro][i] = 0;
if(l == 0)
{
for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)
{
if(!z)
pMlpVA[mlpfd]->u[l][micro][i] += pData->x[micro][k] * pMlpVA[mlpfd]->w[l][k][i];
else
pMlpVA[mlpfd]->u[l][micro][i] += pData->x_prime[micro][k] * pMlpVA[mlpfd]->w[l][k][i];
}
}
else
{
for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
if(!z)
pMlpVA[mlpfd]->u[l][micro][i] += pMlpVA[mlpfd]->y[l - 1][micro][i2] * pMlpVA[mlpfd]->w[l][i2][i];
else
pMlpVA[mlpfd]->u[l][micro][i] += pMlpVA[mlpfd]->y_tsignal[l - 1][micro][i2] * pMlpVA[mlpfd]->w[l][i2][i];
}
}
pMlpVA[mlpfd]->u[l][micro][i] -= pMlpVA[mlpfd]->theta[l][i];
TRANSFKT (fkt, pMlpVA[mlpfd]->u[l][micro][i], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);
if(!z)
pMlpVA[mlpfd]->y[l][micro][i] = fkt;
else
pMlpVA[mlpfd]->y_tsignal[l][micro][i] = fkt;
} /* for i */
} /* for l */
/* from output layer to last hidden layer */
double E_single_sample = 0;
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
pMlpVA[mlpfd]->u2[j] = 0;
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)
{
if(!z)
pMlpVA[mlpfd]->u2[j] += pMlpVA[mlpfd]->y[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][micro][i] * pMlpVA[mlpfd]->w2[i][j];
else
pMlpVA[mlpfd]->u2[j] += pMlpVA[mlpfd]->y_tsignal[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][micro][i] * pMlpVA[mlpfd]->w2[i][j];
}
/* don't subtract the threshold of the neuron if the neuron has a linear transfer function */
if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
pMlpVA[mlpfd]->u2[j] -= pMlpVA[mlpfd]->theta2[j];
TRANSFKT (fkt, pMlpVA[mlpfd]->u2[j], pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, pMlpVA[mlpfd]->mlpP.beta);
if ((pMlpVA[mlpfd]->mlpP.trainingMode == RG_MODE || pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE) && z)
{
pMlpVA[mlpfd]->y2_prime[micro][j] = fkt;
/*Schritt 3: Bestimmung des Fehlers am Netzausgang */
TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y2_prime[micro][j], pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, pMlpVA[mlpfd]->mlpP.beta);
}
else
{
pMlpVA[mlpfd]->y2[micro][j] = fkt;
/*Schritt 3: Bestimmung des Fehlers am Netzausgang */
TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y2[micro][j], pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, pMlpVA[mlpfd]->mlpP.beta);
}
/* gradient vector for bias output layer
* iff multiplied by pMlpVA[mlpfd]->y[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][micro][i] then it is
* the gradient vector for the weights output layer */
if(!z)
{
double fkt2;
TRANSFKT_DERIVATIVE_2 (fkt2, pMlpVA[mlpfd]->y2[micro][j], pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, pMlpVA[mlpfd]->mlpP.beta);
pMlpVA[mlpfd]->grad2vec2[micro][j] = fkt2;
pMlpVA[mlpfd]->gradvec2[micro][j] = fkt;
pMlpVA[mlpfd]->delta2[micro][j] = (pData->y[micro][j] - pMlpVA[mlpfd]->y2[micro][j]) * fkt;
double diff = 0;
if((pMlpVA[mlpfd]->mlpP.trainingMode != RG_MODE &&
pMlpVA[mlpfd]->mlpP.trainingMode != TDC_MODE))
diff = (pData->y[micro][j] - pMlpVA[mlpfd]->y2[micro][j]);
else
{
if(!pData->hasXPrime[micro])
diff = (pData->reward[micro] - pMlpVA[mlpfd]->y2[micro][j]);
else
diff = (pData->reward[micro] + gamma * normFactor * pMlpVA[mlpfd]->y2_prime[micro][j] + pData->y2[micro][j] - pMlpVA[mlpfd]->y2[micro][j]);
}
E_single_sample += pow (diff, 2.0);
if(E_single_sample > Emax)
Emax = E_single_sample;
Evals[micro] = E_single_sample;
}
else
pMlpVA[mlpfd]->gradvec2_tsignal[micro][j] = fkt;
} /* for j */
if(!z)
E += E_single_sample;
/*Schritt 4: Fehlerrückvermittlung (Rückwärtsphase) */
/* from output layer to last hidden layer l */
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if(!z)
{
pMlpVA[mlpfd]->delta[l][micro][i] = 0;
TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y[l][micro][i], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);
}
else
{
TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y_tsignal[l][micro][i], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);
}
double fkt2;
TRANSFKT_DERIVATIVE_2 (fkt2, pMlpVA[mlpfd]->y[l][micro][i], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
if(!z)
{
pMlpVA[mlpfd]->delta[l][micro][i] += fkt * pMlpVA[mlpfd]->w2[i][j] * pMlpVA[mlpfd]->delta2[micro][j];
pMlpVA[mlpfd]->gradvec[l][micro][i][j] = fkt * pMlpVA[mlpfd]->w2[i][j] * pMlpVA[mlpfd]->gradvec2[micro][j];
// TODO: Verify the following line
pMlpVA[mlpfd]->grad2vec[l][micro][i][j] = pMlpVA[mlpfd]->w2[i][j] * (fkt2 * pMlpVA[mlpfd]->gradvec2[micro][j] + 2.0 * pMlpVA[mlpfd]->grad2vec2[micro][j] * pow(fkt, 2.0) * pMlpVA[mlpfd]->w2[i][j]);
}
else
pMlpVA[mlpfd]->gradvec_tsignal[l][micro][i][j] = fkt * pMlpVA[mlpfd]->w2[i][j] * pMlpVA[mlpfd]->gradvec2_tsignal[micro][j];
}
} /* for i */
/* from hidden layer l to hidden layer l-1 */
for (l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 2; l >= 0; l--)
{
for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l]; i2++)
{
if(!z)
{
pMlpVA[mlpfd]->delta[l][micro][i2] = 0;
TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y[l][micro][i2], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);
}
else
{
TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y_tsignal[l][micro][i2], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);
}
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l + 1]; i++)
{
int maxJ;
if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 2)
{
// Naechste Schicht ist Ausgabeschicht
maxJ = pMlpVA[mlpfd]->mlpIv.n;
}
else
{
// Naechste Schicht ist naechste Zwischenschicht
maxJ = pMlpVA[mlpfd]->mlpIv.h[l + 2];
}
if(!z)
{
pMlpVA[mlpfd]->delta[l][micro][i2] += fkt * pMlpVA[mlpfd]->w[l + 1][i2][i] * pMlpVA[mlpfd]->delta[l + 1][micro][i];
pMlpVA[mlpfd]->gradvec[l][micro][i2][i] = 0;
for (j = 0; j < maxJ; j++)
pMlpVA[mlpfd]->gradvec[l][micro][i2][i] += fkt * pMlpVA[mlpfd]->w[l + 1][i2][i] * pMlpVA[mlpfd]->gradvec[l + 1][micro][i][j];
}
else
{
pMlpVA[mlpfd]->gradvec_tsignal[l][micro][i2][i] = 0;
for (j = 0; j < maxJ; j++)
pMlpVA[mlpfd]->gradvec_tsignal[l][micro][i2][i] += fkt * pMlpVA[mlpfd]->w[l + 1][i2][i] * pMlpVA[mlpfd]->gradvec_tsignal[l + 1][micro][i][j];
}
}
}
} /* for l */
if(checkGradients)
{
if(pMlpVA[mlpfd]->mlpP.trainingMode != ONLINE_MODE)
{
printf("### checkGradients: Must be run in online mode, check trainingMode in configuration file\n");
return -4;
}
/* Compares the gradients (gradvec and gradvec2) with the delta values (delta and delta2)
* This is only for debugging / verifying the internal works of this function.
* Normally checkGradients shall be false */
for (l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l >= 0; l--)
{
if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1)
{
// Output layer
for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
double val = pMlpVA[mlpfd]->gradvec2[micro][j] * (pData->y[micro][j] - pMlpVA[mlpfd]->y2[micro][j]);
if((float) val != (float) pMlpVA[mlpfd]->delta2[micro][j])
{
printf("### checkGradients: output layer, (%lf) != (%lf)\n", val, pMlpVA[mlpfd]->delta2[micro][j]);
return -4;
}
}
}
// Last hidden layer
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
double sum = 0;
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
sum += pMlpVA[mlpfd]->gradvec[l][micro][i][j] * (pData->y[micro][j] - pMlpVA[mlpfd]->y2[micro][j]);
if((float) sum != (float)pMlpVA[mlpfd]->delta[l][micro][i])
{
printf("### checkGradients: hidden layer (%i), i (%i), (%lf) != (%lf)\n", l, i, sum, pMlpVA[mlpfd]->delta[l][micro][i]);
return -4;
}
}
}
else
{
// Hidden layer before last hidden layer
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
double sum = 0;
for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l + 1]; i2++)
{
for(j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
sum += pMlpVA[mlpfd]->gradvec[l][micro][i][i2] * (pData->y[micro][j] - pMlpVA[mlpfd]->y2[micro][j]);
}
if((float) sum != (float)pMlpVA[mlpfd]->delta[l][micro][i])
{
printf("### checkGradients: hidden layer (%i), i (%i), (%lf) != (%lf)\n", l, i, sum, pMlpVA[mlpfd]->delta[l][micro][i]);
return -4;
}
}
}
}
}
/*Schritt 5: Lernen */
if (pMlpVA[mlpfd]->mlpP.trainingMode == ONLINE_MODE)
{
/*Error Backpropagation: Online Mode */
/*Adaptiere Gewichte nach Praesentation eines einzelnen Musters micro */
/*Adaptiere Schwellwerte nach Praesentation eines einzelnen Musters micro */
/*Adaptiere Gewichte der Ausgangsschicht */
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
if (i < pMlpVA[mlpfd]->mlpIv.h[l])
{
deltaWeight = pMlpVA[mlpfd]->w2[i][j] + pMlpVA[mlpfd]->mlpP.eta2 * pMlpVA[mlpfd]->y[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][micro][i] * pMlpVA[mlpfd]->delta2[micro][j];
if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]))
deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]) * sign (deltaWeight);
pMlpVA[mlpfd]->w2[i][j] = deltaWeight;
}
else
{
/* neurons with linear activation function don't have a threshold */
if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
{
/*Adaptiere Schwellwerte der Ausgangsschicht */
deltaWeight = pMlpVA[mlpfd]->theta2[j] - (pMlpVA[mlpfd]->mlpP.eta2 * pMlpVA[mlpfd]->delta2[micro][j]);
if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]))
deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]) * sign (deltaWeight);
pMlpVA[mlpfd]->theta2[j] = deltaWeight;
}
}
}
}
/*Adaptiere Gewichte der Zwischenschichten */
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (k < pMlpVA[mlpfd]->mlpIv.m)
{
deltaWeight = pMlpVA[mlpfd]->w[l][k][i] + pMlpVA[mlpfd]->mlpP.eta1 * pData->x[micro][k] * pMlpVA[mlpfd]->delta[l][micro][i];
if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.m))
deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.m) * sign (deltaWeight);
pMlpVA[mlpfd]->w[l][k][i] = deltaWeight;
}
else
{
/*Adaptiere Schwellwerte der Zwischenschichten */
deltaWeight = pMlpVA[mlpfd]->theta[l][i] - (pMlpVA[mlpfd]->mlpP.eta1 * pMlpVA[mlpfd]->delta[l][micro][i]);
if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.m))
deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.m) * sign (deltaWeight);
pMlpVA[mlpfd]->theta[l][i] = deltaWeight;
}
}
}
}
else
{
for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1])
{
deltaWeight = pMlpVA[mlpfd]->w[l][i2][i] + pMlpVA[mlpfd]->mlpP.eta1 * pMlpVA[mlpfd]->y[l - 1][micro][i2] * pMlpVA[mlpfd]->delta[l][micro][i];
if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]))
deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]) * sign (deltaWeight);
pMlpVA[mlpfd]->w[l][i2][i] = deltaWeight;
}
else
{
/*Adaptiere Schwellwerte der Zwischenschichten */
deltaWeight = pMlpVA[mlpfd]->theta[l][i] - (pMlpVA[mlpfd]->mlpP.eta1 * pMlpVA[mlpfd]->delta[l][micro][i]);
if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]))
deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]) * sign (deltaWeight);
pMlpVA[mlpfd]->theta[l][i] = deltaWeight;
}
}
}
}
}
} /* ONLINE_MODE */
} /* for micro */ /*Schritt 6: Ende Epoche, naechstes Muster, falls noch weitere vorhanden */
} /* for z */
if (pMlpVA[mlpfd]->mlpP.trainingMode == BATCH_MODE)
{
/*Error Backpropagation: Batch Mode */
/*Adaptiere Gewichte nach Praesentation aller Muster micro */
/*Adaptiere Gewichte der Ausgangsschicht */
/*Adaptiere Schwellwerte nach Praesentation aller Muster micro */
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
double eta = pMlpVA[mlpfd]->mlpP.eta2;
if(pMlpVA[mlpfd]->mlpP.etaNormalize)
eta /= (double) micro_max;
for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
if (i < pMlpVA[mlpfd]->mlpIv.h[l])
{
CALC_GRADIENT_WEIGHTS_OUTPUT (S);
deltaW = -eta * S;
pMlpVA[mlpfd]->w2[i][j] = pMlpVA[mlpfd]->w2[i][j] + deltaW;
}
else
{
/* neurons with linear activation function don't have a threshold */
if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
{
/*Adaptiere Schwellwerte der Ausgangsschicht */
CALC_GRADIENT_BIAS_OUTPUT (S);
deltaW = -eta * S;
pMlpVA[mlpfd]->theta2[j] = pMlpVA[mlpfd]->theta2[j] + deltaW;
}
}
}
}
eta = pMlpVA[mlpfd]->mlpP.eta1;
if(pMlpVA[mlpfd]->mlpP.etaNormalize)
eta /= (double) micro_max;
/*Adaptiere Gewichte der Zwischenschichten */
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (k < pMlpVA[mlpfd]->mlpIv.m)
{
CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER (S);
deltaW = -eta * S;
pMlpVA[mlpfd]->w[l][k][i] = pMlpVA[mlpfd]->w[l][k][i] + deltaW;
}
else
{
CALC_GRADIENT_BIAS_HIDDEN (S);
deltaW = -eta * S;
pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + deltaW;
}
}
}
}
else
{
for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1])
{
CALC_GRADIENT_WEIGHTS_HIDDEN (S);
deltaW = -eta * S;
pMlpVA[mlpfd]->w[l][i2][i] = pMlpVA[mlpfd]->w[l][i2][i] + deltaW;
}
else
{
/*Adaptiere Schwellwerte der Zwischenschichten */
CALC_GRADIENT_BIAS_HIDDEN (S);
deltaW = -eta * S;
pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + deltaW;
}
}
}
}
}
} /* BATCH_MODE */
else if (pMlpVA[mlpfd]->mlpP.trainingMode == RG_MODE)
{
double gradient_prime, gradient;
if(updateSecondLayer)
{
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
/* output neurons with linear activation function don't have a threshold */
if (i < pMlpVA[mlpfd]->mlpIv.h[l] || pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
{
S = 0;
for (muster = 0; muster < micro_max; muster++)
{
double diff;
if(!pData->hasXPrime[muster])
{
diff = (pData->reward[muster] - pMlpVA[mlpfd]->y2[muster][j]);
gradient_prime = 0;
}
else
{
diff = (pData->reward[muster] + gamma * normFactor * pMlpVA[mlpfd]->y2_prime[muster][j] + pData->y2[muster][j] - pMlpVA[mlpfd]->y2[muster][j]);
double tmp = -1.0;
if (i < pMlpVA[mlpfd]->mlpIv.h[l])
tmp = pMlpVA[mlpfd]->y_tsignal[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][muster][i];
gradient_prime = pMlpVA[mlpfd]->gradvec2_tsignal[muster][j] * tmp;
}
if(sampleAlphaDiscount != NULL)
diff *= sampleAlphaDiscount[muster];
double tmp = -1.0;
if(i < pMlpVA[mlpfd]->mlpIv.h[l])
tmp = pMlpVA[mlpfd]->y[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][muster][i];
gradient = pMlpVA[mlpfd]->gradvec2[muster][j] * tmp;
if(replacingTraces)
{
// Replacing traces
if(gradient == 0)
pMlpVA[mlpfd]->gradientTrace2[i][j] = gamma * lambda * pMlpVA[mlpfd]->gradientTrace2[i][j];
else
pMlpVA[mlpfd]->gradientTrace2[i][j] = gradient;
}
else
{
// Accumulating traces
pMlpVA[mlpfd]->gradientTrace2[i][j] = gamma * lambda * pMlpVA[mlpfd]->gradientTrace2[i][j] + gradient;
}
S += (pMlpVA[mlpfd]->gradientTrace2[i][j] - gradientPrimeFactor * gamma * gradient_prime) * diff;
/* Clear gradient traces upon observing a terminal state */
if(!pData->hasXPrime[muster])
pMlpVA[mlpfd]->gradientTrace2[i][j] = 0;
} /* for muster */
deltaW = alpha * S;
if (i < pMlpVA[mlpfd]->mlpIv.h[l])
pMlpVA[mlpfd]->w2[i][j] += deltaW;
else
pMlpVA[mlpfd]->theta2[j] += deltaW;
}
}
}
}
if(updateFirstLayer)
{
/*Adaptiere Gewichte der Zwischenschichten */
for (l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1; l >= 0; l--)
{
int maxK;
if(l == 0)
maxK = pMlpVA[mlpfd]->mlpIv.m;
else
maxK = pMlpVA[mlpfd]->mlpIv.h[l - 1];
for (k = 0; k <= maxK; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
S = 0;
for (muster = 0; muster < micro_max; muster++)
{
int maxJ;
if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1)
maxJ = pMlpVA[mlpfd]->mlpIv.n;
else
maxJ = pMlpVA[mlpfd]->mlpIv.h[l + 1];
for (j = 0; j < maxJ; j++)
{
double diff;
if(!pData->hasXPrime[muster])
{
diff = (pData->reward[muster] - pMlpVA[mlpfd]->y2[muster][0]);
gradient_prime = 0;
}
else
{
diff = (pData->reward[muster] + gamma * normFactor * pMlpVA[mlpfd]->y2_prime[muster][0] + pData->y2[muster][0] - pMlpVA[mlpfd]->y2[muster][0]);
double tmp = -1.0;
if(l == 0)
{
if(k < pMlpVA[mlpfd]->mlpIv.m)
tmp = pData->x_prime[muster][k];
}
else
{
if (k < pMlpVA[mlpfd]->mlpIv.h[l - 1])
tmp = pMlpVA[mlpfd]->y_tsignal[l - 1][muster][k];
}
gradient_prime = pMlpVA[mlpfd]->gradvec_tsignal[l][muster][i][j] * tmp;
}
if(sampleAlphaDiscount != NULL)
diff *= sampleAlphaDiscount[muster];
double tmp = -1.0;
if(l == 0)
{
if(k < pMlpVA[mlpfd]->mlpIv.m)
tmp = pData->x[muster][k];
}
else
{
if (k < pMlpVA[mlpfd]->mlpIv.h[l - 1])
tmp = pMlpVA[mlpfd]->y[l - 1][muster][k];
}
gradient = pMlpVA[mlpfd]->gradvec[l][muster][i][j] * tmp;
if(replacingTraces)
{
// Replacing traces
if(gradient == 0)
pMlpVA[mlpfd]->gradientTrace[l][i][j][k] = gamma * lambda * pMlpVA[mlpfd]->gradientTrace[l][i][j][k];
else
pMlpVA[mlpfd]->gradientTrace[l][i][j][k] = gradient;
}
else
{
// Accumulating traces
pMlpVA[mlpfd]->gradientTrace[l][i][j][k] = gamma * lambda * pMlpVA[mlpfd]->gradientTrace[l][i][j][k] + gradient;
}
S += (pMlpVA[mlpfd]->gradientTrace[l][i][j][k] - gradientPrimeFactor * gamma * gradient_prime) * diff;
/* Clear gradient traces upon observing a terminal state */
if(!pData->hasXPrime[muster])
pMlpVA[mlpfd]->gradientTrace[l][i][j][k] = 0;
} /* for j */
} /* for muster */
deltaW = alpha2 * S;
if((l == 0 && k < pMlpVA[mlpfd]->mlpIv.m) || (l > 0 && k < pMlpVA[mlpfd]->mlpIv.h[l - 1]))
pMlpVA[mlpfd]->w[l][k][i] += deltaW;
else
pMlpVA[mlpfd]->theta[l][i] += deltaW;
} /* for i */
} /* for k */
} /* for l */
} /* updateFirstLayer */
} /* RG_MODE */
else if (pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)
{
muster = 0; /* We assume that there is only one state transition (sample) */
// Calculate \theta^T w
double summed_W_Gradient_outputLayer = 0;
double summed_W_Gradient_outputLayerBias = 0;
double summed_W_Gradient_hiddenLayer = 0;
double summed_W_Gradient_hiddenLayerBias = 0;
if(tdcOwnSummedGradient)
{
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
summed_W_Gradient_outputLayer += pMlpVA[mlpfd]->gradvec2[muster][0] * pMlpVA[mlpfd]->y[l][muster][i] * pMlpVA[mlpfd]->w2_prime[i][0];
if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
summed_W_Gradient_outputLayerBias += pMlpVA[mlpfd]->gradvec2[muster][0] * -1.0 * pMlpVA[mlpfd]->theta2_prime[0];
l = 0;
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)
summed_W_Gradient_hiddenLayer += pMlpVA[mlpfd]->gradvec[l][muster][i][0] * pData->x[muster][k] * pMlpVA[mlpfd]->w_prime[l][k][i];
summed_W_Gradient_hiddenLayerBias += pMlpVA[mlpfd]->gradvec[l][muster][i][0] * -1.0 * pMlpVA[mlpfd]->theta_prime[l][i];
}
}
else
{
double summed_W_Gradient = 0;
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
summed_W_Gradient += pMlpVA[mlpfd]->gradvec2[muster][0] * pMlpVA[mlpfd]->y[l][muster][i] * pMlpVA[mlpfd]->w2_prime[i][0];
if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
summed_W_Gradient += pMlpVA[mlpfd]->gradvec2[muster][0] * -1.0 * pMlpVA[mlpfd]->theta2_prime[0];
l = 0;
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)
summed_W_Gradient += pMlpVA[mlpfd]->gradvec[l][muster][i][0] * pData->x[muster][k] * pMlpVA[mlpfd]->w_prime[l][k][i];
summed_W_Gradient += pMlpVA[mlpfd]->gradvec[l][muster][i][0] * -1.0 * pMlpVA[mlpfd]->theta_prime[l][i];
}
summed_W_Gradient_outputLayer = summed_W_Gradient_outputLayerBias = summed_W_Gradient_hiddenLayer = summed_W_Gradient_hiddenLayerBias = summed_W_Gradient;
}
double diff;
if(!pData->hasXPrime[muster])
diff = (pData->reward[muster] - pMlpVA[mlpfd]->y2[muster][0]);
else
diff = (pData->reward[muster] + gamma * normFactor * pMlpVA[mlpfd]->y2_prime[muster][0] + pData->y2[muster][0] - pMlpVA[mlpfd]->y2[muster][0]);
// Adapt the first weights theta
// Output layer
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (i < pMlpVA[mlpfd]->mlpIv.h[l])
{
double gradient = pMlpVA[mlpfd]->gradvec2[muster][0] * pMlpVA[mlpfd]->y[l][muster][i];
double gradient2 = pMlpVA[mlpfd]->grad2vec2[muster][0] * pow(pMlpVA[mlpfd]->y[l][muster][i], 2.0);
double h = (diff - summed_W_Gradient_outputLayer) * gradient2 * pMlpVA[mlpfd]->w2_prime[i][0];
double gradient_prime = 0;
if(pData->hasXPrime[muster])
gradient_prime = pMlpVA[mlpfd]->gradvec2_tsignal[muster][0] * pMlpVA[mlpfd]->y_tsignal[l][muster][i];
S = diff * gradient - gamma * gradient_prime * summed_W_Gradient_outputLayer - h;
deltaW = alpha * S;
pMlpVA[mlpfd]->w2[i][0] += deltaW;
}
else if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
{
/*Adaptiere Schwellwerte der Ausgangsschicht */
double gradient = pMlpVA[mlpfd]->gradvec2[muster][0] * -1.0;
double gradient2 = pMlpVA[mlpfd]->grad2vec2[muster][0];
double h = (diff - summed_W_Gradient_outputLayerBias) * gradient2 * pMlpVA[mlpfd]->theta2_prime[0];
double gradient_prime = 0;
if(pData->hasXPrime[muster])
gradient_prime = pMlpVA[mlpfd]->gradvec2_tsignal[muster][0] * -1.0;
S = diff * gradient - gamma * gradient_prime * summed_W_Gradient_outputLayerBias - h;
deltaW = alpha * S;
pMlpVA[mlpfd]->theta2[0] += deltaW;
}
}
// Hidden layer
l = 0;
for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (k < pMlpVA[mlpfd]->mlpIv.m)
{
double gradient = pMlpVA[mlpfd]->gradvec[l][muster][i][0] * pData->x[muster][k];
double gradient2 = pMlpVA[mlpfd]->grad2vec[l][muster][i][0] * pow(pData->x[muster][k], 2.0);
double h = (diff - summed_W_Gradient_hiddenLayer) * gradient2 * pMlpVA[mlpfd]->w_prime[l][k][i];
double gradient_prime = 0;
if(pData->hasXPrime[muster])
gradient_prime = pMlpVA[mlpfd]->gradvec_tsignal[l][muster][i][0] * pData->x_prime[muster][k];
S = diff * gradient - gamma * gradient_prime * summed_W_Gradient_hiddenLayer - h;
deltaW = alpha * S;
pMlpVA[mlpfd]->w[l][k][i] += deltaW;
}
else
{
/*Adaptiere Schwellwerte der Zwischenschichten */
double gradient = pMlpVA[mlpfd]->gradvec[l][muster][i][0] * -1.0;
double gradient2 = pMlpVA[mlpfd]->grad2vec[l][muster][i][0];
double h = (diff - summed_W_Gradient_hiddenLayerBias) * gradient2 * pMlpVA[mlpfd]->theta_prime[l][i];
double gradient_prime = 0;
if(pData->hasXPrime[muster])
gradient_prime = pMlpVA[mlpfd]->gradvec_tsignal[l][muster][i][0] * -1.0;
S = diff * gradient - gamma * gradient_prime * summed_W_Gradient_hiddenLayerBias - h;
deltaW = alpha * S;
pMlpVA[mlpfd]->theta[l][i] += deltaW;
}
} /* for i */
} /* for k */
// Update the second weights
// Output layer
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
double gradient = pMlpVA[mlpfd]->gradvec2[muster][0];
if (i < pMlpVA[mlpfd]->mlpIv.h[l])
{
gradient *= pMlpVA[mlpfd]->y[l][muster][i];
pMlpVA[mlpfd]->w2_prime[i][0] += alpha2 * (diff - summed_W_Gradient_outputLayer) * gradient;
}
else if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
{
gradient *= -1.0;
pMlpVA[mlpfd]->theta2_prime[0] += alpha2 * (diff - summed_W_Gradient_outputLayerBias) * gradient;
}
}
// Hidden layer
l = 0;
for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
double gradient = pMlpVA[mlpfd]->gradvec[l][muster][i][0];
if (k < pMlpVA[mlpfd]->mlpIv.m)
{
gradient *= pData->x[muster][k];
pMlpVA[mlpfd]->w_prime[l][k][i] += alpha2 * (diff - summed_W_Gradient_hiddenLayer) * gradient;
}
else
{
gradient *= -1.0;
pMlpVA[mlpfd]->theta_prime[l][i] += alpha2 * (diff - summed_W_Gradient_hiddenLayerBias) * gradient;
}
}
}
} /* TDC_MODE */
else if (pMlpVA[mlpfd]->mlpP.trainingMode == MOMENTUMTERM_MODE)
{
/*Error Backpropagation mit Momentumterm: Batch Mode */
/*Adaptiere Gewichte nach Praesentation aller Muster micro */
/*Adaptiere Schwellwerte nach Praesentation aller Muster micro */
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
if (i < pMlpVA[mlpfd]->mlpIv.h[l])
{
CALC_GRADIENT_WEIGHTS_OUTPUT (S);
deltaW = -pMlpVA[mlpfd]->mlpP.eta2 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w2[i][j];
pMlpVA[mlpfd]->w2[i][j] += deltaW;
pMlpVA[mlpfd]->delta_w2[i][j] = deltaW;
}
else
{
/* neurons with linear activation function don't have a threshold */
if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
{
/*Adaptiere Schwellwerte der Ausgangsschicht */
CALC_GRADIENT_BIAS_OUTPUT (S);
deltaW = -pMlpVA[mlpfd]->mlpP.eta2 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w2[i][j];
pMlpVA[mlpfd]->theta2[j] += deltaW;
pMlpVA[mlpfd]->delta_w2[i][j] = deltaW;
}
}
}
}
/*Adaptiere Gewichte der Zwischenschichten */
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (k < pMlpVA[mlpfd]->mlpIv.m)
{
CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER (S);
deltaW = -pMlpVA[mlpfd]->mlpP.eta1 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w1[l][k][i];
pMlpVA[mlpfd]->w[l][k][i] += deltaW;
pMlpVA[mlpfd]->delta_w1[l][k][i] = deltaW;
}
else
{
/*Adaptiere Schwellwerte der Zwischenschichten */
CALC_GRADIENT_BIAS_HIDDEN (S);
deltaW = -pMlpVA[mlpfd]->mlpP.eta1 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w1[l][k][i];
pMlpVA[mlpfd]->theta[l][i] += deltaW;
pMlpVA[mlpfd]->delta_w1[l][k][i] = deltaW;
}
}
}
}
else
{
for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1])
{
CALC_GRADIENT_WEIGHTS_HIDDEN (S);
deltaW = -pMlpVA[mlpfd]->mlpP.eta1 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w1[l][i2][i];
pMlpVA[mlpfd]->w[l][i2][i] += deltaW;
pMlpVA[mlpfd]->delta_w1[l][i2][i] = deltaW;
}
else
{
/*Adaptiere Schwellwerte der Zwischenschichten */
CALC_GRADIENT_BIAS_HIDDEN (S);
deltaW = -pMlpVA[mlpfd]->mlpP.eta1 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w1[l][i2][i];
pMlpVA[mlpfd]->theta[l][i] += deltaW;
pMlpVA[mlpfd]->delta_w1[l][i2][i] = deltaW;
}
}
}
}
}
}
else if (pMlpVA[mlpfd]->mlpP.trainingMode == QUICKPROP_MODE)
{
/*Quickpropagation Mode */
/*Adaptiere Gewichte nach Praesentation aller Muster micro */
/*Adaptiere Schwellwerte nach Praesentation aller Muster micro */
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
if (i < pMlpVA[mlpfd]->mlpIv.h[l])
{
CALC_GRADIENT_WEIGHTS_OUTPUT (S);
if ((pMlpVA[mlpfd]->delta_w2[i][j] == 0) || (S > pMlpVA[mlpfd]->desc_w2[i][j]))
{
/*Standard Error Backpropagation Lernregel */
deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta2 * S;
}
else
{
/* printf("Yes, Quickprop like...\n"); */
if (S > pMlpVA[mlpfd]->desc_w2[i][j])
{
printf ("### Quickprop: S(t) = %f, S(t-1) = %f\n", S, pMlpVA[mlpfd]->desc_w2[i][j]);
return -2;
}
beta = S / (pMlpVA[mlpfd]->desc_w2[i][j] - S);
if (fabs (beta * pMlpVA[mlpfd]->delta_w2[i][j]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w2[i][j]))
deltaW = beta * pMlpVA[mlpfd]->delta_w2[i][j];
else
{
if (beta < 0)
deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w2[i][j];
else
deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w2[i][j];
}
}
pMlpVA[mlpfd]->desc_w2[i][j] = S;
pMlpVA[mlpfd]->delta_w2[i][j] = deltaW;
pMlpVA[mlpfd]->w2[i][j] = pMlpVA[mlpfd]->w2[i][j] + deltaW;
}
else
{
/* neurons with linear activation function don't have a threshold */
if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
{
/*Adaptiere Schwellwerte der Ausgangsschicht */
CALC_GRADIENT_BIAS_OUTPUT (S);
if ((pMlpVA[mlpfd]->delta_w2[i][j] == 0) || (S > pMlpVA[mlpfd]->desc_w2[i][j]))
{
/*Standard Error Backpropagation Lernregel */
deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta2 * S;
}
else
{
if (S > pMlpVA[mlpfd]->desc_w2[i][j])
{
printf ("### Quickprop: S(t) = %f, S(t-1) = %f\n", S, pMlpVA[mlpfd]->desc_w2[i][j]);
return -2;
}
beta = S / (pMlpVA[mlpfd]->desc_w2[i][j] - S);
if (fabs (beta * pMlpVA[mlpfd]->delta_w2[i][j]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w2[i][j]))
deltaW = beta * pMlpVA[mlpfd]->delta_w2[i][j];
else
{
if (beta < 0)
deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w2[i][j];
else
deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w2[i][j];
}
}
pMlpVA[mlpfd]->desc_w2[i][j] = S;
pMlpVA[mlpfd]->delta_w2[i][j] = deltaW;
pMlpVA[mlpfd]->theta2[j] = pMlpVA[mlpfd]->theta2[j] + deltaW;
}
}
}
}
/*Adaptiere Gewichte der Zwischenschichten */
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (k < pMlpVA[mlpfd]->mlpIv.m)
{
CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER (S);
if ((pMlpVA[mlpfd]->delta_w1[l][k][i] == 0) || (S > pMlpVA[mlpfd]->desc_w[l][k][i]))
{
/*Standard Error Backpropagation Lernregel */
deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta1 * S;
}
else
{
if (S > pMlpVA[mlpfd]->desc_w[l][k][i])
{
printf ("### Quickprop: S(t) = %f, S(t-1) = %f\n", S, pMlpVA[mlpfd]->desc_w[l][k][i]);
return -2;
}
beta = S / (pMlpVA[mlpfd]->desc_w[l][k][i] - S);
if (fabs (beta * pMlpVA[mlpfd]->delta_w1[l][k][i]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w1[l][k][i]))
deltaW = beta * pMlpVA[mlpfd]->delta_w1[l][k][i];
else
{
if (beta < 0)
deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][k][i];
else
deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][k][i];
}
}
pMlpVA[mlpfd]->desc_w[l][k][i] = S;
pMlpVA[mlpfd]->delta_w1[l][k][i] = deltaW;
pMlpVA[mlpfd]->w[l][k][i] = pMlpVA[mlpfd]->w[l][k][i] + deltaW;
}
else
{
/*Adaptiere Schwellwerte der Zwischenschichten */
CALC_GRADIENT_BIAS_HIDDEN (S);
if ((pMlpVA[mlpfd]->delta_w1[l][k][i] == 0) || (S > pMlpVA[mlpfd]->desc_w[l][k][i]))
{
/*Standard Error Backpropagation Lernregel */
deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta1 * S;
}
else
{
if (S > pMlpVA[mlpfd]->desc_w[l][k][i])
{
printf ("### Quickprop: S(t) = %f, S(t-1) = %f\n", S, pMlpVA[mlpfd]->desc_w[l][k][i]);
return -2;
}
beta = S / (pMlpVA[mlpfd]->desc_w[l][k][i] - S);
if (fabs (beta * pMlpVA[mlpfd]->delta_w1[l][k][i]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w1[l][k][i]))
deltaW = beta * pMlpVA[mlpfd]->delta_w1[l][k][i];
else
{
if (beta < 0)
deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][k][i];
else
deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][k][i];
}
}
pMlpVA[mlpfd]->desc_w[l][k][i] = S;
pMlpVA[mlpfd]->delta_w1[l][k][i] = deltaW;
pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + deltaW;
}
}
}
}
else
{
for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1])
{
CALC_GRADIENT_WEIGHTS_HIDDEN (S);
if ((pMlpVA[mlpfd]->delta_w1[l][i2][i] == 0) || (S > pMlpVA[mlpfd]->desc_w[l][i2][i]))
{
/*Standard Error Backpropagation Lernregel */
deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta1 * S;
}
else
{
if (S > pMlpVA[mlpfd]->desc_w[l][i2][i])
{
printf ("### Quickprop: S(t) = %f, S(t-1) = %f\n", S, pMlpVA[mlpfd]->desc_w[l][i2][i]);
return -2;
}
beta = S / (pMlpVA[mlpfd]->desc_w[l][i2][i] - S);
if (fabs (beta * pMlpVA[mlpfd]->delta_w1[l][i2][i]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w1[l][i2][i]))
deltaW = beta * pMlpVA[mlpfd]->delta_w1[l][i2][i];
else
{
if (beta < 0)
deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][i2][i];
else
deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][i2][i];
}
}
pMlpVA[mlpfd]->desc_w[l][i2][i] = S;
pMlpVA[mlpfd]->delta_w1[l][i2][i] = deltaW;
pMlpVA[mlpfd]->w[l][i2][i] = pMlpVA[mlpfd]->w[l][i2][i] + deltaW;
}
else
{
/*Adaptiere Schwellwerte der Zwischenschichten */
CALC_GRADIENT_BIAS_HIDDEN (S);
if ((pMlpVA[mlpfd]->delta_w1[l][i2][i] == 0) || (S > pMlpVA[mlpfd]->desc_w[l][i2][i]))
{
/*Standard Error Backpropagation Lernregel */
deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta1 * S;
}
else
{
if (S > pMlpVA[mlpfd]->desc_w[l][i2][i])
{
printf ("### Quickprop: S(t) = %f, S(t-1) = %f\n", S, pMlpVA[mlpfd]->desc_w[l][i2][i]);
return -2;
}
beta = S / (pMlpVA[mlpfd]->desc_w[l][i2][i] - S);
if (fabs (beta * pMlpVA[mlpfd]->delta_w1[l][i2][i]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w1[l][i2][i]))
deltaW = beta * pMlpVA[mlpfd]->delta_w1[l][i2][i];
else
{
if (beta < 0)
deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][i2][i];
else
deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][i2][i];
}
}
pMlpVA[mlpfd]->desc_w[l][i2][i] = S;
pMlpVA[mlpfd]->delta_w1[l][i2][i] = deltaW;
pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + deltaW;
}
}
}
}
}
} /* MOMENTUMTERM_MODE */
else if (pMlpVA[mlpfd]->mlpP.trainingMode == RPROPM_MODE)
{
/*Resilient Propagation Minus (RPROP-) Mode */
/*Adaptiere Gewichte nach Praesentation aller Muster micro */
/*Adaptiere Schwellwerte nach Praesentation aller Muster micro */
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
if (i < pMlpVA[mlpfd]->mlpIv.h[l])
{
CALC_GRADIENT_WEIGHTS_OUTPUT (S);
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w2[i][j]);
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
}
else
{
/*S(t-1)*S(t)=0 */
}
CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->w2[i][j], pMlpVA[mlpfd]->eta_w2[i][j]);
pMlpVA[mlpfd]->desc_w2[i][j] = S;
}
else
{
/* neurons with linear activation function don't have a threshold */
if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
{
/*Adaptiere Schwellwerte der Ausgangsschicht */
CALC_GRADIENT_BIAS_OUTPUT (S)
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w2[i][j]);
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
/* S = 0; */
}
else
{
/*S(t-1)*S(t)=0 */
}
CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->theta2[j], pMlpVA[mlpfd]->eta_w2[i][j]);
pMlpVA[mlpfd]->desc_w2[i][j] = S;
}
}
}
}
/*Adaptiere Gewichte der Zwischenschichten */
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (k < pMlpVA[mlpfd]->mlpIv.m)
{
CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER (S);
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][k][i]);
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
/* S = 0; */
}
else
{
/*S(t-1)*S(t)=0 */
}
CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->w[l][k][i], pMlpVA[mlpfd]->eta_w[l][k][i]);
pMlpVA[mlpfd]->desc_w[l][k][i] = S;
}
else
{
/*Adaptiere Schwellwerte der Zwischenschichten */
CALC_GRADIENT_BIAS_HIDDEN (S);
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][k][i]);
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
/* S = 0; */
}
else
{
/*S(t-1)*S(t)=0 */
}
CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->theta[l][i], pMlpVA[mlpfd]->eta_w[l][k][i]);
pMlpVA[mlpfd]->desc_w[l][k][i] = S;
}
}
}
}
else
{
for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
if (i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1])
{
CALC_GRADIENT_WEIGHTS_HIDDEN (S);
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][i2][i]);
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
/* S = 0; */
}
else
{
/*S(t-1)*S(t)=0 */
}
CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->w[l][i2][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);
pMlpVA[mlpfd]->desc_w[l][i2][i] = S;
}
else
{
/*Adaptiere Schwellwerte der Zwischenschichten */
CALC_GRADIENT_BIAS_HIDDEN (S);
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][i2][i]);
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
/* S = 0; */
}
else
{
/*S(t-1)*S(t)=0 */
}
CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->theta[l][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);
pMlpVA[mlpfd]->desc_w[l][i2][i] = S;
}
}
}
}
}
} /* RPROPM_MODE */
else if (pMlpVA[mlpfd]->mlpP.trainingMode == RPROPP_MODE)
{
/*Resilient Propagation Plus (RPROP+) Mode */
/*Adaptiere Gewichte nach Praesentation aller Muster micro */
l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;
/*Adaptiere Gewichte der Ausgangsschicht */
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
CALC_GRADIENT_WEIGHTS_OUTPUT (S);
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w2[i][j]);
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w2[i][j], pMlpVA[mlpfd]->eta_w2[i][j]);
pMlpVA[mlpfd]->w2[i][j] = pMlpVA[mlpfd]->w2[i][j] + pMlpVA[mlpfd]->delta_w2[i][j];
pMlpVA[mlpfd]->desc_w2[i][j] = S;
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
if (E > Elast)
pMlpVA[mlpfd]->w2[i][j] = pMlpVA[mlpfd]->w2[i][j] - pMlpVA[mlpfd]->delta_w2[i][j];
pMlpVA[mlpfd]->desc_w2[i][j] = 0;
}
else
{
/*S(t-1)*S(t)=0 */
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w2[i][j], pMlpVA[mlpfd]->eta_w2[i][j]);
pMlpVA[mlpfd]->w2[i][j] = pMlpVA[mlpfd]->w2[i][j] + pMlpVA[mlpfd]->delta_w2[i][j];
pMlpVA[mlpfd]->desc_w2[i][j] = S;
}
}
}
/*Adaptiere Schwellwerte nach Praesentation aller Muster micro */
/* neurons with linear activation function don't have a threshold */
if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)
{
/*Adaptiere Schwellwerte der Ausgangsschicht */
for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)
{
CALC_GRADIENT_BIAS_OUTPUT (S);
i = pMlpVA[mlpfd]->mlpIv.h[l];
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w2[i][j]);
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w2[i][j], pMlpVA[mlpfd]->eta_w2[i][j]);
pMlpVA[mlpfd]->theta2[j] = pMlpVA[mlpfd]->theta2[j] + pMlpVA[mlpfd]->delta_w2[i][j];
pMlpVA[mlpfd]->desc_w2[i][j] = S;
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
if (E > Elast)
pMlpVA[mlpfd]->theta2[j] = pMlpVA[mlpfd]->theta2[j] - pMlpVA[mlpfd]->delta_w2[i][j];
pMlpVA[mlpfd]->desc_w2[i][j] = 0;
}
else
{
/*S(t-1)*S(t)=0 */
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w2[i][j], pMlpVA[mlpfd]->eta_w2[i][j]);
pMlpVA[mlpfd]->theta2[j] = pMlpVA[mlpfd]->theta2[j] + pMlpVA[mlpfd]->delta_w2[i][j];
pMlpVA[mlpfd]->desc_w2[i][j] = S;
}
}
}
/*Adaptiere Gewichte der Zwischenschichten */
for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)
{
if (l == 0)
{
for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER (S);
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][k][i]);
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][k][i], pMlpVA[mlpfd]->eta_w[l][k][i]);
pMlpVA[mlpfd]->w[l][k][i] = pMlpVA[mlpfd]->w[l][k][i] + pMlpVA[mlpfd]->delta_w1[l][k][i];
pMlpVA[mlpfd]->desc_w[l][k][i] = S;
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
if (E > Elast)
pMlpVA[mlpfd]->w[l][k][i] = pMlpVA[mlpfd]->w[l][k][i] - pMlpVA[mlpfd]->delta_w1[l][k][i];
pMlpVA[mlpfd]->desc_w[l][k][i] = 0;
}
else
{
/*S(t-1)*S(t)=0 */
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][k][i], pMlpVA[mlpfd]->eta_w[l][k][i]);
pMlpVA[mlpfd]->w[l][k][i] = pMlpVA[mlpfd]->w[l][k][i] + pMlpVA[mlpfd]->delta_w1[l][k][i];
pMlpVA[mlpfd]->desc_w[l][k][i] = S;
}
}
}
/*Adaptiere Schwellwerte der Zwischenschichten */
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
CALC_GRADIENT_BIAS_HIDDEN (S);
k = pMlpVA[mlpfd]->mlpIv.m;
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][k][i])
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][k][i], pMlpVA[mlpfd]->eta_w[l][k][i]);
pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + pMlpVA[mlpfd]->delta_w1[l][k][i];
pMlpVA[mlpfd]->desc_w[l][k][i] = S;
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
if (E > Elast)
pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] - pMlpVA[mlpfd]->delta_w1[l][k][i];
pMlpVA[mlpfd]->desc_w[l][k][i] = 0;
}
else
{
/*S(t-1)*S(t)=0 */
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][k][i], pMlpVA[mlpfd]->eta_w[l][k][i]);
pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + pMlpVA[mlpfd]->delta_w1[l][k][i];
pMlpVA[mlpfd]->desc_w[l][k][i] = S;
}
}
}
else
{
for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)
{
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
CALC_GRADIENT_WEIGHTS_HIDDEN (S);
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][i2][i]);
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][i2][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);
pMlpVA[mlpfd]->w[l][i2][i] = pMlpVA[mlpfd]->w[l][i2][i] + pMlpVA[mlpfd]->delta_w1[l][i2][i];
pMlpVA[mlpfd]->desc_w[l][i2][i] = S;
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
if (E > Elast)
pMlpVA[mlpfd]->w[l][i2][i] = pMlpVA[mlpfd]->w[l][i2][i] - pMlpVA[mlpfd]->delta_w1[l][i2][i];
pMlpVA[mlpfd]->desc_w[l][i2][i] = 0;
}
else
{
/*S(t-1)*S(t)=0 */
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][i2][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);
pMlpVA[mlpfd]->w[l][i2][i] = pMlpVA[mlpfd]->w[l][i2][i] + pMlpVA[mlpfd]->delta_w1[l][i2][i];
pMlpVA[mlpfd]->desc_w[l][i2][i] = S;
}
}
}
/*Adaptiere Schwellwerte der Zwischenschichten */
for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)
{
CALC_GRADIENT_BIAS_HIDDEN (S);
i2 = pMlpVA[mlpfd]->mlpIv.h[l - 1];
/*Berechnung von delta ij */
CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][i2][i]);
if (dS > 0)
{
/*S(t-1)*S(t)>0 */
CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][i2][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);
pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + pMlpVA[mlpfd]->delta_w1[l][i2][i];
pMlpVA[mlpfd]->desc_w[l][i2][i] = S;
}
else if (dS < 0)
{
/*S(t-1)*S(t)<0 */
CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);
if (E > Elast)
pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] - pMlpVA[mlpfd]->delta_w1[l][i2][i];
pMlpVA[mlpfd]->desc_w[l][i2][i] = 0;
}
else
{
/*S(t-1)*S(t)=0 */
CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][i2][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);
pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + pMlpVA[mlpfd]->delta_w1[l][i2][i];
pMlpVA[mlpfd]->desc_w[l][i2][i] = S;
}
}
}
}
} /* RPROPP_MODE */
/*Schritt 7: Ende Training */
numIterations++;
if (E < Emin)
Emin = E;
if ((E <= pMlpVA[mlpfd]->mlpP.epsilon) || (numIterations >= pMlpVA[mlpfd]->mlpP.maxIterations))
end = 1;
if(pMlpVA[mlpfd]->mlpP.trainingMode != RG_MODE &&
pMlpVA[mlpfd]->mlpP.trainingMode != TDC_MODE)
{
if(E <= Elast)
ouch = 0;
else if(E > Elast)
{
ouch++;
if (ouch > 10)
{
ouch = 0;
printf ("### Algorithm does not converge (E > Elast), lower the learning rate or stop earlier\n");
}
}
}
if (pMlpVA[mlpfd]->mlpP.verboseOutput)
{
double mean = gsl_stats_mean (Evals, 1, micro_max);
double largest = gsl_stats_max (Evals, 1, micro_max);
gsl_sort (Evals, 1, micro_max);
double median = gsl_stats_median_from_sorted_data (Evals, 1, micro_max);
double upperq = gsl_stats_quantile_from_sorted_data (Evals, 1, micro_max, 0.75);
printf ("number of iterations: %i, E: %lf. Max: %lf, Mean: %lf, Median: %lf, uQuart: %lf\n", numIterations, E, largest, mean, median, upperq);
}
if (pMlpVA[mlpfd]->mlpP.verboseOutput >= 2)
outputWeights (mlpfd);
} /* while */
if (pMlpVA[mlpfd]->mlpP.verboseOutput)
outputWeights (mlpfd);
return E;
}
| {
"alphanum_fraction": 0.4158764435,
"avg_line_length": 41.4781641168,
"ext": "c",
"hexsha": "4c8f47f6232fae9d6b6dff658d2dfaabd4f486ac",
"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": "2f5bd9bf7a8fa0ff2b7458facd941dc9cb77b904",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "stefanfausser/neural-network-ensembles-rl",
"max_forks_repo_path": "rlLib/mlpLib.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2f5bd9bf7a8fa0ff2b7458facd941dc9cb77b904",
"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": "stefanfausser/neural-network-ensembles-rl",
"max_issues_repo_path": "rlLib/mlpLib.c",
"max_line_length": 224,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "2f5bd9bf7a8fa0ff2b7458facd941dc9cb77b904",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "stefanfausser/neural-network-ensembles-rl",
"max_stars_repo_path": "rlLib/mlpLib.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 43306,
"size": 149114
} |
#include <stdio.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_odeiv2.h>
// y' = 2y + x
// https://www.wolframalpha.com/input/?i=y%27+%3D+2y+%2B+x%2C+y%280%29+%3D+1%2C+y%281%29
// https://www.wolframalpha.com/input/?i=1%2F4+*+%285+*+e%5E2+-+3%29
// 저항값: 1Kohm
// 인덕턴스: 300uH
// DC 전원: 5V
// ---DC---R---L---GND---
// 직렬 회로의 특성상 전류값이 일정함 i(t)
// V = i(t) * R + L * [di(t) / dt]
// 5 = y * R + L * y'
// 미분 방정식의 표준형은 무조건 y'의 계수가 1이어야 합니다!!!
// 5 / L = (R / L) * y + y'
// 5 / 0.0003 = (1000 / 0.0003) * y + y'
// y' = 5 / 0.0003 - (1000 / 0.0003) * y <<<=== 표준형
int odefunc (double x, const double y[], double f[], void *params)
{
// f[0] = x+2*y[0];
//f[0] = pow(M_E, x);
//f[0] = -(1000 / 0.0003) * x - (5 / 0.0003);
f[0] = -(1000 / 0.0003) * y[0] + (5 / 0.0003);
return GSL_SUCCESS;
}
int * jac;
int main(void)
{
int dim = 1;
// 미방을 풀기 위한 데이터 타입
gsl_odeiv2_system sys = {odefunc, NULL, dim, NULL};
// 드라이버는 미방을 쉽게 풀 수 있도록 시간에 따른 변화, 제어, 스텝에 대한 래퍼
// gsl_odeiv2_step_rkf45는 룬게쿠타 4-5차를 의미함
// 다음 인자는 미분방정식의 시작지점
// 절대적인 에러 바운드와 상대적인 에러 바운드
gsl_odeiv2_driver * d = gsl_odeiv2_driver_alloc_y_new (&sys, gsl_odeiv2_step_rkf45, 1e-6, 1e-6, 0.0);
int i;
double x0 = 0.0, xf = 10.0; /* start and end of integration interval */
double x = x0;
double y[1] = { 0.5 }; /* initial value */
double tmp = 0.0;
int cnt = 0;
for (i = 0; tmp <= xf; tmp += 0.0000001)
{
double xi = x0 + tmp * (xf-x0) / xf;
int status = gsl_odeiv2_driver_apply (d, &x, xi, y);
if (status != GSL_SUCCESS)
{
printf ("error, return value=%d\n", status);
break;
}
if (cnt++ < 101)
{
printf ("%.8e %.8e\n", x, y[0]);
}
}
gsl_odeiv2_driver_free (d);
return 0;
}
| {
"alphanum_fraction": 0.5315217391,
"avg_line_length": 24.8648648649,
"ext": "c",
"hexsha": "521529a6fa59bbef3551f915f04769f2f7739c78",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-03-19T01:22:06.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-19T01:22:06.000Z",
"max_forks_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_forks_repo_path": "ch4/src/main/rl_test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_issues_repo_path": "ch4/src/main/rl_test.c",
"max_line_length": 105,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "245385b79807c25081dfe2014c72843226716f92",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "EDDI-RobotAcademy/E4DS-DSP-Basic-Mathematics",
"max_stars_repo_path": "ch4/src/main/rl_test.c",
"max_stars_repo_stars_event_max_datetime": "2021-10-22T00:39:04.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-10-22T00:39:04.000Z",
"num_tokens": 899,
"size": 1840
} |
/* complex/test.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 <stdio.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_test.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
struct f
{
char *name;
double (*f) (gsl_complex z);
double x;
double y;
double fx;
double fy;
};
struct fz
{
char *name;
gsl_complex (*f) (gsl_complex z);
double x;
double y;
double fx;
double fy;
};
#define FN(x) "gsl_complex_" #x, gsl_complex_ ## x
#define ARG(x,y) x, y
#define RES(x,y) x, y
struct f list[] =
{
#include "results1.h"
{"", 0, 0, 0, 0, 0}
};
struct fz listz[] =
{
#include "results.h"
{"", 0, 0, 0, 0, 0}
};
int
main (void)
{
size_t i = 0;
gsl_ieee_env_setup();
for (i = 0 ; i < 10; i++)
{
double r = (i - 5.0) * 0.3 ;
double t = 2.0 * M_PI * i / 5 ;
double x = r * cos(t), y = r * sin(t) ;
gsl_complex z = gsl_complex_polar (r, t) ;
gsl_test_rel (GSL_REAL(z), x, 10 * GSL_DBL_EPSILON, "gsl_complex_polar real part at (r=%g,t=%g)", r, t);
gsl_test_rel (GSL_IMAG(z), y, 10 * GSL_DBL_EPSILON, "gsl_complex_polar imag part at (r=%g,t=%g)", r, t);
}
i = 0;
while (list[i].f)
{
struct f t = list[i];
gsl_complex z = gsl_complex_rect (t.x, t.y);
double f = (t.f) (z);
gsl_test_rel (f, t.fx, 10 * GSL_DBL_EPSILON, "%s at (%g,%g)", t.name, t.x, t.y);
i++;
}
i = 0;
while (listz[i].f)
{
struct fz t = listz[i];
gsl_complex z = gsl_complex_rect (t.x, t.y);
gsl_complex fz = (t.f) (z);
double fx = GSL_REAL (fz), fy = GSL_IMAG (fz);
#ifdef DEBUG
printf("x = "); gsl_ieee_fprintf_double (stdout, &t.x); printf("\n");
printf("y = "); gsl_ieee_fprintf_double (stdout, &t.y); printf("\n");
printf("fx = "); gsl_ieee_fprintf_double (stdout, &fx); printf("\n");
printf("ex = "); gsl_ieee_fprintf_double (stdout, &t.fx); printf("\n");
printf("fy = "); gsl_ieee_fprintf_double (stdout, &fy); printf("\n");
printf("ey = "); gsl_ieee_fprintf_double (stdout, &t.fy); printf("\n");
#endif
gsl_test_rel (fx, t.fx, 10 * GSL_DBL_EPSILON, "%s real part at (%g,%g)", t.name, t.x, t.y);
gsl_test_rel (fy, t.fy, 10 * GSL_DBL_EPSILON, "%s imag part at (%g,%g)", t.name, t.x, t.y);
i++;
}
exit (gsl_test_summary ());
}
| {
"alphanum_fraction": 0.60598345,
"avg_line_length": 25.9669421488,
"ext": "c",
"hexsha": "c257df6a24b8752129060d5c3851dc8fe14e7e77",
"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/complex/test.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "91e70bc88726ee680ec6e8cbc609977db3fdcff9",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "ICML14MoMCompare/spectral-learn",
"max_issues_repo_path": "code/em/treba/gsl-1.0/complex/test.c",
"max_line_length": 110,
"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/complex/test.c",
"max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z",
"num_tokens": 1024,
"size": 3142
} |
/* [response orientation nms filterBank] = steerableDetector3D(image, filterOrder, sigma);
*
* (c) Francois Aguet, 30/08/2012 (last modified 09/02/2012).
*
* Compilation:
* Mac/Linux: mex -I/usr/local/include -I../../mex/include /usr/local/lib/libgsl.a /usr/local/lib/libgslcblas.a steerableDetector3D.cpp
* Windows: mex COMPFLAGS="$COMPFLAGS /TP /MT" -I"..\..\..\extern\mex\include\gsl-1.14" -I"..\..\mex\include" "..\..\..\extern\mex\lib\gsl.lib" "..\..\..\extern\mex\lib\cblas.lib" -output steerableDetector3D steerableDetector3D.cpp
*/
#include <cstring>
#include <gsl_include/gsl_poly.h>
#include <gsl_include/gsl_math.h>
#include <gsl_include/gsl_eigen.h>
#include <gsl_include/gsl_cblas.h>
#include <algorithm>
#include <vector>
#include <fstream>
#include <string>
#include <math.h>
#include "stackutil.h"
#include "../../../v3d_main/jba/newmat11/newmatap.h"
#include "../../../v3d_main/jba/newmat11/newmatio.h"
#include "convolver3D.h"
double zhi_abs(double num);
int swapthree(double& dummya, double& dummyb, double& dummyc);
class Filter {
public:
Filter(const double voxels[], const int nx, const int ny, const int nz, const int M, const double sigma);
Filter(const double voxels[], const int nx, const int ny, const int nz, const int M, const double sigma, const double zxRatio);
~Filter();
void init();
double* getResponse();
double** getOrientation();
double* getNMS();
private:
const double* voxels_;
double* response_;
double** orientation_;
double* nms_;
int nx_, ny_, nz_;
int M_;
double sigma_, sigmaZ_;
int N_;
double alpha_, sign_, c_;
double *gxx_, *gxy_, *gxz_, *gyy_, *gyz_, *gzz_;
void calculateTemplates();
double interpResponse(const double x, const double y, const double z);
static int mirror(const int x, const int nx);
void normalize(double v[], const int k);
void cross(const double v1[], const double v2[], double r[]);
void computeCurveNMS();
void computeSurfaceNMS();
void run();
};
| {
"alphanum_fraction": 0.6726479146,
"avg_line_length": 31.2424242424,
"ext": "h",
"hexsha": "826f8a3f5558e107767312db8e547b9e1992b23a",
"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": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zzhmark/vaa3d_tools",
"max_forks_repo_path": "hackathon/liyad/steerablefilter3D/steerableDetector3D.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"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": "zzhmark/vaa3d_tools",
"max_issues_repo_path": "hackathon/liyad/steerablefilter3D/steerableDetector3D.h",
"max_line_length": 231,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzhmark/vaa3d_tools",
"max_stars_repo_path": "hackathon/liyad/steerablefilter3D/steerableDetector3D.h",
"max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z",
"num_tokens": 578,
"size": 2062
} |
#ifndef __EMULATOR_INC_
#define __EMULATOR_INC_
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_sf.h>
/**
* the fn ptr to the covariance function, this is the most called function in libEmu
* you can change this when you setup the optstruct.
*/
double (*covariance_fn)(gsl_vector*, gsl_vector*, gsl_vector*, int, int) ;
void print_matrix(gsl_matrix* m, int nx, int ny);
double covariance_fn_gaussian(gsl_vector *xm, gsl_vector* xn, gsl_vector* thetas, int nthetas, int nparams);
void derivative_l_gauss(gsl_matrix *dCdTheta, gsl_matrix* xmodel,
double thetaLength, int index, int nmodel_points, int nparams);
// same as above but without clamping on small values
double covariance_fn_gaussian_exact(gsl_vector *xm, gsl_vector* xn, gsl_vector* thetas, int nthetas, int nparams);
double covariance_fn_matern_three(gsl_vector *xm, gsl_vector* xn, gsl_vector* thetas, int nthetas, int nparams);
void derivative_l_matern_three(gsl_matrix *dCdTheta, gsl_matrix* xmodel, double thetaLength,
int index, int nmodel_points, int nparams);
double covariance_fn_matern_five(gsl_vector *xm, gsl_vector* xn, gsl_vector* thetas, int nthetas, int nparams);
void derivative_l_matern_five(gsl_matrix *dCdTheta, gsl_matrix* xmodel, double thetaLength,
int index, int nmodel_points, int nparams);
void makeKVector(gsl_vector* kvector, gsl_matrix *xmodel, gsl_vector *xnew, gsl_vector* thetas, int nmodel_points, int nthetas, int nparams);
void makeKVector_fnptr(gsl_vector* kvector, gsl_matrix *xmodel, gsl_vector *xnew, gsl_vector* thetas, int nmodel_points, int nthetas, int nparams,
double (*covariance_fn_ptr)(gsl_vector*, gsl_vector*, gsl_vector*, int, int));
void makeCovMatrix(gsl_matrix *cov_matrix, gsl_matrix *xmodel, gsl_vector* thetas, int nmodel_points, int nthetas, int nparams);
void makeCovMatrix_fnptr(gsl_matrix *cov_matrix, gsl_matrix *xmodel, gsl_vector* thetas, int nmodel_points, int nthetas, int nparams,
double (*covariance_fn_ptr)(gsl_vector*, gsl_vector*, gsl_vector*, int, int));
double makeEmulatedMean(gsl_matrix *inverse_cov_matrix, gsl_vector *training_vector, gsl_vector *kplus_vector, gsl_vector* h_vector, gsl_matrix* h_matrix, gsl_vector* beta_vector, int nmodel_points);
double makeEmulatedVariance(gsl_matrix *inverse_cov_matrix, gsl_vector *kplus_vector, gsl_vector *h_vector, gsl_matrix *h_matrix, double kappa, int nmodel_points, int nregression_fns);
void initialise_new_x(gsl_matrix* new_x, int nparams, int nemulate_points, double emulate_min, double emulate_max);
/* deprecated */
/* double covariance_fn_gaussian_nondiag(gsl_vector* xm, gsl_vector*xn, gsl_vector*thetas, int nthetas, int nparams); */
/* double covariance_fn_matern(gsl_vector *xm, gsl_vector* xn, gsl_vector* thetas, int nthetas, int nparams); */
#endif
| {
"alphanum_fraction": 0.7759751467,
"avg_line_length": 47.4918032787,
"ext": "h",
"hexsha": "18c623e303a9d6dffc4dc437404c3eae19c11103",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-30T16:43:33.000Z",
"max_forks_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MADAI/MADAIEmulator",
"max_forks_repo_path": "src/libEmu/emulator.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7d926ad04a791c7694defd88db41c13f7ee4e6aa",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "MADAI/MADAIEmulator",
"max_issues_repo_path": "src/libEmu/emulator.h",
"max_line_length": 200,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "1c11f69c535acef8159ef0e780cca343785ea004",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jackdawjackdaw/emulator",
"max_stars_repo_path": "src/libEmu/emulator.h",
"max_stars_repo_stars_event_max_datetime": "2017-06-02T00:34:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-02T17:37:42.000Z",
"num_tokens": 774,
"size": 2897
} |
/*
* vbHmmPc.c
* Model-specific core functions for VB-HMM-PC.
*
* Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN
* Copyright 2011-2015
* Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.
* All rights reserved.
*
* Ver. 1.1.0
* Last modified on 2015.09.17
*/
#include <math.h>
#include <string.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_psi.h>
#include <gsl/gsl_sf_pow_int.h>
#include <string.h>
#include "vbHmmPc.h"
#include "rand.h"
#ifdef _OPENMP
#include "omp.h"
#endif
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
//static int isGlobalAnalysis = 0;
void setFunctions_pc(){
commonFunctions funcs;
funcs.newModelParameters = newModelParameters_pc;
funcs.freeModelParameters = freeModelParameters_pc;
funcs.newModelStats = newModelStats_pc;
funcs.freeModelStats = freeModelStats_pc;
funcs.initializeVbHmm = initializeVbHmm_pc;
funcs.pTilde_z1 = pTilde_z1_pc;
funcs.pTilde_zn_zn1 = pTilde_zn_zn1_pc;
funcs.pTilde_xn_zn = pTilde_xn_zn_pc;
funcs.calcStatsVars = calcStatsVars_pc;
funcs.maximization = maximization_pc;
funcs.varLowerBound = varLowerBound_pc;
funcs.reorderParameters = reorderParameters_pc;
funcs.outputResults = outputResults_pc;
setFunctions( funcs );
}
//void setGFunctions_pc(){
// gCommonFunctions funcs;
// funcs.newModelParameters = newModelParameters_pc;
// funcs.freeModelParameters = freeModelParameters_pc;
// funcs.newModelStats = newModelStats_pc;
// funcs.freeModelStats = freeModelStats_pc;
// funcs.newModelStatsG = newModelStatsG_pc;
// funcs.freeModelStatsG = freeModelStatsG_pc;
// funcs.initializeVbHmmG = initializeVbHmmG_pc;
// funcs.pTilde_z1 = pTilde_z1_pc;
// funcs.pTilde_zn_zn1 = pTilde_zn_zn1_pc;
// funcs.pTilde_xn_zn = pTilde_xn_zn_pc;
// funcs.calcStatsVarsG = calcStatsVarsG_pc;
// funcs.maximizationG = maximizationG_pc;
// funcs.varLowerBoundG = varLowerBoundG_pc;
// funcs.reorderParametersG = reorderParametersG_pc;
// funcs.outputResultsG = outputResultsG_pc;
// setGFunctions( funcs );
// isGlobalAnalysis = 1;
//}
void outputResults_pc( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
outputPcResults( xn, gv, iv, logFP );
}
//void outputResultsG_pc( xns, gv, ivs, logFP )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//FILE *logFP;
//{
// outputPcResultsG( xns, gv, ivs, logFP );
//}
void *newModelParameters_pc( xn, sNo )
xnDataSet *xn;
int sNo;
{
int i;
pcParameters *p = (void*)malloc( sizeof(pcParameters) );
p->uPiArr = (double*)malloc( sNo * sizeof(double) );
p->sumUPi = 0.0;
p->uAMat = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->uAMat[i] = (double*)malloc( sNo * sizeof(double) );
}
p->sumUAArr = (double*)malloc( sNo * sizeof(double) );
p->avgPi = (double *)malloc( sNo * sizeof(double) );
p->avgLnPi = (double *)malloc( sNo * sizeof(double) );
p->avgA = (double **)malloc( sNo * sizeof(double*) );
p->avgLnA = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ ){
p->avgA[i] = (double *)malloc( sNo * sizeof(double) );
p->avgLnA[i] = (double *)malloc( sNo * sizeof(double) );
}
p->avgI = (double *)malloc( sNo * sizeof(double) );
p->avgLnI = (double *)malloc( sNo * sizeof(double) );
p->aIArr = (double*)malloc( sNo * sizeof(double) );
p->bIArr = (double*)malloc( sNo * sizeof(double) );
return p;
}
void freeModelParameters_pc( p, xn, sNo )
void **p;
xnDataSet *xn;
int sNo;
{
pcParameters *gp = *p;
int i;
free( gp->uPiArr );
for( i = 0 ; i < sNo ; i++ ){
free( gp->uAMat[i] );
}
free( gp->uAMat );
free( gp->sumUAArr );
free( gp->avgPi );
free( gp->avgLnPi );
for( i = 0 ; i < sNo ; i++ ){
free( gp->avgA[i] );
free( gp->avgLnA[i] );
}
free( gp->avgA );
free( gp->avgLnA );
free( gp->avgI );
free( gp->avgLnI );
free( gp->aIArr );
free( gp->bIArr );
free( *p );
*p = NULL;
}
void *newModelStats_pc( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
pcStats *s = (pcStats*)malloc( sizeof(pcStats) );
int i;
s->Ni = (double *)malloc( sNo * sizeof(double) );
s->Nij = (double **)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s->Nij[i] = (double *)malloc( sNo * sizeof(double) ); }
s->Ci = (double *)malloc( sNo * sizeof(double) );
s->Mi = (double *)malloc( sNo * sizeof(double) );
return s;
// } else {
//
// return NULL;
//
// }
}
void freeModelStats_pc( s, xn, gv, iv )
void **s;
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
// if( isGlobalAnalysis == 0 ){
int sNo = gv->sNo;
pcStats *gs = *s;
int i;
free( gs->Ni );
for( i = 0 ; i < sNo ; i++ )
{ free( gs->Nij[i] ); }
free( gs->Nij );
free( gs->Ci );
free( gs->Mi );
free( gs );
*s = NULL;
// }
}
//void *newModelStatsG_pc( xns, gv, ivs)
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
// int sNo = gv->sNo;
// pcGlobalStats *gs = (pcGlobalStats*)malloc( sizeof(pcGlobalStats) );
//
// return gs;
//}
//void freeModelStatsG_pc( gs, xns, gv, ivs )
//void **gs;
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
// int sNo = gv->sNo;
// pcGlobalStats *ggs = *gs;
//
// free( *gs );
// *gs = NULL;
//}
void initializeVbHmm_pc( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcData *d = xn->data;
size_t dLen = xn->N;
int sNo = gv->sNo;
pcParameters *p = gv->params;
int i, j;
size_t totalC = 0;
for( i = 0 ; i < dLen ; i++ ){
totalC += d->counts[i];
}
double meanI = (double)totalC / (double)dLen;
// hyperparameter for p( pi(k) )
p->sumUPi = 0.0;
for( i = 0 ; i < sNo ; i++ ){
p->uPiArr[i] = 1.0;
p->sumUPi += p->uPiArr[i];
}
// hyperparameter for p( A(i,j) )
for( i = 0 ; i < sNo ; i++ ){
p->sumUAArr[i] = 0.0;
for( j = 0 ; j < sNo ; j++ ){
if( j == i ){
p->uAMat[i][j] = 100.0;
} else {
p->uAMat[i][j] = 1.0;
}
p->sumUAArr[i] += p->uAMat[i][j];
}
}
// hyperparameter for p( I(k) )
for( i = 0 ; i < sNo ; i++ ){
p->aIArr[i] = 1.0;
p->bIArr[i] = 1.0 / meanI;
}
initialize_indVars_pc( xn, gv, iv );
calcStatsVars_pc( xn, gv, iv );
maximization_pc( xn, gv, iv );
}
//void initializeVbHmmG_pc( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void initialize_indVars_pc( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
int i;
size_t n;
double sumPar;
for( n = 0 ; n < dLen ; n++ ){
sumPar = 0.0;
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] = enoise(1.0) + 1.0;
sumPar += gmMat[n][i];
}
for( i = 0 ; i < sNo ; i++ ){
gmMat[n][i] /= sumPar;
}
}
}
xnDataSet *newXnDataSet_pc( filename )
const char *filename;
{
xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );
xn->name = (char*)malloc( strlen(filename) + 2 );
strncpy( xn->name, filename, strlen(filename)+1 );
xn->data = (pcData*)malloc( sizeof(pcData) );
pcData *d = (pcData*)xn->data;
d->binSize = 0.0;
d->counts = NULL;
return xn;
}
void freeXnDataSet_pc( xn )
xnDataSet **xn;
{
pcData *d = (pcData*)(*xn)->data;
free( d->counts );
free( (*xn)->data );
free( (*xn)->name );
free( *xn );
*xn = NULL;
}
double pTilde_z1_pc( i, params )
int i;
void *params;
{
pcParameters *p = (pcParameters*)params;
return exp( p->avgLnPi[i] );
}
double pTilde_zn_zn1_pc( i, j, params )
int i, j;
void *params;
{
pcParameters *p = (pcParameters*)params;
return exp( p->avgLnA[i][j] );
}
double pTilde_xn_zn_pc( xnWv, n, i, params )
xnDataSet *xnWv;
size_t n;
int i;
void *params;
{
pcParameters *p = (pcParameters*)params;
pcData *xn = (pcData*)xnWv->data;
return exp( p->avgLnI[i] * (double)xn->counts[n] - p->avgI[i] ) / gsl_sf_fact( xn->counts[n] );
}
void calcStatsVars_pc( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcData *d = (pcData*)xn->data;
pcStats *s = (pcStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *Ni = s->Ni, **Nij = s->Nij;
double *Mi = s->Mi, *Ci = s->Ci;
size_t n;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
Ni[i] = 1e-10;
Ci[i] = 1e-10;
Mi[i] = 1e-10;
for( j = 0 ; j < sNo ; j++ ){
Nij[i][j] = 1e-10;
}
}
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){
Ni[i] += gmMat[n][i];
Ci[i] += gmMat[n][i] * (double)d->counts[n];
for( j = 0 ; j < sNo ; j++ ){
Mi[i] += xiMat[n][i][j];
Nij[i][j] += xiMat[n][i][j];
}
}
}
}
//void calcStatsVarsG_pc( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void maximization_pc( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcParameters *p = (pcParameters*)gv->params;
pcStats *s = (pcStats*)iv->stats;
int sNo = gv->sNo;
double **gmMat = iv->gmMat;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgI = p->avgI, *avgLnI = p->avgLnI;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *Ni = s->Ni, **Nij = s->Nij;
double *Mi = s->Mi, *Ci = s->Ci;
int i, j;
for( i = 0 ; i < sNo ; i++ ){
avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );
avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );
for( j = 0 ; j < sNo ; j++ ){
avgA[i][j] = ( uAMat[i][j] + Nij[i][j] ) / ( sumUAArr[i] + Mi[i] );
avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Mi[i] );
}
avgI[i] = (Ci[i] + aIArr[i]) / (Ni[i] + bIArr[i]);
avgLnI[i] = gsl_sf_psi( Ci[i] + aIArr[i] ) - log( Ni[i] + bIArr[i] );
#ifdef INTENSITY_CAP
size_t n, totalC = 0;
pcData *pc = xnWv->data;
for( n = 0 ; n < xnWv->N ; n++ ){
totalC += pc->counts[n];
}
double meanI = (double)totalC / (double)xnWv->N;
avgI[i] = MIN( avgI[i], maxIntensityRatio * meanI );
avgLnI[i] = MIN( avgLnI[i], log(maxIntensityRatio * meanI) );
#endif
}
}
//void maximizationG_pc( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
double varLowerBound_pc( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcParameters *p = (pcParameters*)gv->params;
pcStats *s = (pcStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, *cn = iv->cn;
double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;
double *avgI = p->avgI, *avgLnI = p->avgLnI;
double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;
double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;
double *Ni = s->Ni, **Nij = s->Nij;
double *Mi = s->Mi, *Ci = s->Ci;
size_t n;
int i, j;
double lnpPi = gsl_sf_lngamma(sumUPi);
double lnpA = 0.0;
double lnpI = 0.0;
double lnqPi = gsl_sf_lngamma(sumUPi + 1.0);
double lnqA = 0.0;
double lnqI = 0.0;
for( i = 0 ; i < sNo ; i++ ){
lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);
lnpI += aIArr[i] * log(bIArr[i]) - gsl_sf_lngamma(aIArr[i]);
lnpI += (aIArr[i] - 1.0) * avgLnI[i] - bIArr[i] * avgI[i];
lnqPi += (uPiArr[i]+gmMat[0][i]-1.0) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1.0));
lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);
lnqI += (Ci[i] + aIArr[i]) * log(Ni[i] + bIArr[i]) - gsl_sf_lngamma(Ci[i] + aIArr[i]);
lnqI += (Ci[i] + aIArr[i] - 1.0) * avgLnI[i] - (Ni[i] + bIArr[i]) * avgI[i];
lnpA += gsl_sf_lngamma(sumUAArr[i]);
lnqA += gsl_sf_lngamma(sumUAArr[i] + Mi[i]);
for( j = 0 ; j < sNo ; j++ ){
lnpA += (uAMat[i][j]-1.0) * avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);
lnqA += (uAMat[i][j] + Nij[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+Nij[i][j]) - gsl_sf_psi( sumUAArr[i]+Mi[i]) );
lnqA -= gsl_sf_lngamma( uAMat[i][j] + Nij[i][j] );
}
}
double lnpX = 0.0;
for( n = 0 ; n < dLen ; n++ ){
lnpX += log( cn[n] );
}
double val;
val = lnpPi + lnpA + lnpI;
val -= lnqPi + lnqA + lnqI;
val += lnpX;
val += log(gsl_sf_fact(sNo));
return val;
}
//double varLowerBoundG_pc( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void reorderParameters_pc( xn, gv, iv )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
{
pcParameters *p = (pcParameters*)gv->params;
pcStats *s = (pcStats*)iv->stats;
size_t dLen = xn->N;
int sNo = gv->sNo;
double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;
double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;
double *avgI = p->avgI, *avgLnI = p->avgLnI;
double *Ni = s->Ni, *Ci = s->Ci;
size_t n;
int i, j;
int *index = (int*)malloc( sNo * sizeof(int) );
double *store = (double*)malloc( sNo * sizeof(double) );
double **s2D = (double**)malloc( sNo * sizeof(double*) );
for( i = 0 ; i < sNo ; i++ )
{ s2D[i] = (double*)malloc( sNo * sizeof(double) ); }
// index indicates order of avgI values (0=biggest avgI -- sNo=smallest avgI).
for( i = 0 ; i < sNo ; i++ ){
index[i] = sNo - 1;
for( j = 0 ; j < sNo ; j++ ){
if( j != i ){
if( avgI[i] < avgI[j] ){
index[i]--;
} else if( avgI[i] == avgI[j] ){
if( i < j )
{ index[i]--; }
}
}
}
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgI[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnI[i]; }
for( i = 0 ; i < sNo ; i++ ){ avgLnI[i] = store[i]; }
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgA[i][j] = s2D[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnA[i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ avgLnA[i][j] = s2D[i][j]; }
}
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ni[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ni[i] = store[i]; }
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ci[i]; }
for( i = 0 ; i < sNo ; i++ ){ Ci[i] = store[i]; }
for( n = 0 ; n < dLen ; n++ ){
for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }
for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }
}
for( n = 0 ; n < dLen ; n++ ){
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }
}
for( j = 0 ; j < sNo ; j++ ){
for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }
}
}
for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }
free( s2D );
free( store );
free( index );
}
//void reorderParametersG_pc( xns, gv, ivs )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//{
//}
void outputPcResults( xn, gv, iv, logFP )
xnDataSet *xn;
globalVars *gv;
indVars *iv;
FILE *logFP;
{
pcParameters *p = (pcParameters*)gv->params;
int sNo = gv->sNo;
int i, j;
fprintf(logFP, " results: K = %d \n", sNo);
fprintf(logFP, " intensity: ( %g", p->avgI[0]);
for( i = 1 ; i < sNo ; i++ )
{ fprintf(logFP, ", %g", p->avgI[i]); }
fprintf(logFP, " ) \n");
fprintf(logFP, " pi: ( %g", p->avgPi[0]);
for( i = 1 ; i < sNo ; i++ ){
fprintf(logFP, ", %g", p->avgPi[i]);
}
fprintf(logFP, " ) \n");
fprintf(logFP, " A_matrix: [");
for( i = 0 ; i < sNo ; i++ ){
fprintf(logFP, " ( %g", p->avgA[i][0]);
for( j = 1 ; j < sNo ; j++ )
{ fprintf(logFP, ", %g", p->avgA[i][j]); }
fprintf(logFP, ")");
}
fprintf(logFP, " ] \n\n");
char fn[256];
FILE *fp;
size_t n;
sprintf( fn, "%s.param%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
fprintf(fp, "I, pi");
for( i = 0 ; i < sNo ; i++ )
{ fprintf(fp, ", A%dx", i); }
fprintf(fp, "\n");
for( i = 0 ; i < sNo ; i++ ){
fprintf(fp, "%g, %g", p->avgI[i], p->avgPi[i]);
for( j = 0 ; j < sNo ; j++ )
{ fprintf(fp, ", %g", p->avgA[j][i]); }
fprintf(fp, "\n");
}
fclose(fp);
}
sprintf( fn, "%s.Lq%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < gv->iteration ; n++ ){
fprintf( fp, "%24.20e\n", gv->LqArr[n] );
}
fclose(fp);
}
sprintf( fn, "%s.maxS%03d", xn->name, sNo );
if( (fp = fopen( fn, "w")) != NULL ){
for( n = 0 ; n < xn->N ; n++ ){
fprintf( fp, "%d\n", iv->stateTraj[n] );
}
fclose(fp);
}
}
//void outputPcResultsG( xns, gv, ivs, logFP )
//xnDataBundle *xns;
//globalVars *gv;
//indVarBundle *ivs;
//FILE *logFP;
//{
//}
//
| {
"alphanum_fraction": 0.497372193,
"avg_line_length": 26.7571022727,
"ext": "c",
"hexsha": "579c1e03b3fc9e8ab5a708a67ad2e5aa866680d1",
"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": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "okamoto-kenji/varBayes-HMM",
"max_forks_repo_path": "C/vbHmmPc.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"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": "okamoto-kenji/varBayes-HMM",
"max_issues_repo_path": "C/vbHmmPc.c",
"max_line_length": 124,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "okamoto-kenji/varBayes-HMM",
"max_stars_repo_path": "C/vbHmmPc.c",
"max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z",
"num_tokens": 6860,
"size": 18837
} |
static char help[] = "Newton's method for arctan x = 0. Run with -snes_fd or -snes_mf.\n\n";
#include <petsc.h>
extern PetscErrorCode FormFunction(SNES, Vec, Vec, void*);
int main(int argc,char **argv) {
PetscErrorCode ierr;
SNES snes; // nonlinear solver
Vec x, r; // solution, residual vectors
PetscReal x0 = 2.0;
PetscInitialize(&argc,&argv,(char*)0,help);
ierr = PetscOptionsBegin(PETSC_COMM_WORLD,"","options to atan","");CHKERRQ(ierr);
ierr = PetscOptionsReal("-x0","initial value","atan.c",x0,&x0,NULL); CHKERRQ(ierr);
ierr = PetscOptionsEnd();CHKERRQ(ierr);
ierr = VecCreate(PETSC_COMM_WORLD,&x); CHKERRQ(ierr);
ierr = VecSetSizes(x,PETSC_DECIDE,1); CHKERRQ(ierr);
ierr = VecSetFromOptions(x); CHKERRQ(ierr);
ierr = VecSet(x,x0); CHKERRQ(ierr);
ierr = VecDuplicate(x,&r); CHKERRQ(ierr);
ierr = SNESCreate(PETSC_COMM_WORLD,&snes); CHKERRQ(ierr);
ierr = SNESSetFunction(snes,r,FormFunction,NULL); CHKERRQ(ierr);
ierr = SNESSetFromOptions(snes); CHKERRQ(ierr);
ierr = SNESSolve(snes,NULL,x); CHKERRQ(ierr);
ierr = VecView(x,PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
VecDestroy(&x); VecDestroy(&r); SNESDestroy(&snes);
PetscFinalize();
return 0;
}
PetscErrorCode FormFunction(SNES snes, Vec x, Vec F, void *ctx) {
PetscErrorCode ierr;
const PetscReal *ax;
PetscReal *aF;
ierr = VecGetArrayRead(x,&ax);CHKERRQ(ierr);
ierr = VecGetArray(F,&aF);CHKERRQ(ierr);
aF[0] = atan(ax[0]);
ierr = VecRestoreArrayRead(x,&ax);CHKERRQ(ierr);
ierr = VecRestoreArray(F,&aF);CHKERRQ(ierr);
return 0;
}
| {
"alphanum_fraction": 0.6554216867,
"avg_line_length": 33.8775510204,
"ext": "c",
"hexsha": "865e2b4898950ae084ece0bcfe81c649f338a8c3",
"lang": "C",
"max_forks_count": 46,
"max_forks_repo_forks_event_max_datetime": "2022-03-22T07:43:17.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-07-23T09:26:58.000Z",
"max_forks_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "thw1021/p4pdes",
"max_forks_repo_path": "c/ch4/solns/atan.c",
"max_issues_count": 52,
"max_issues_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_issues_repo_issues_event_max_datetime": "2021-11-29T12:36:20.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-09-24T17:42:48.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "thw1021/p4pdes",
"max_issues_repo_path": "c/ch4/solns/atan.c",
"max_line_length": 93,
"max_stars_count": 115,
"max_stars_repo_head_hexsha": "421fd3d809b1e23e5a6f3c3e51252cb275a76140",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "thw1021/p4pdes",
"max_stars_repo_path": "c/ch4/solns/atan.c",
"max_stars_repo_stars_event_max_datetime": "2022-03-05T23:12:02.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-03-13T04:35:40.000Z",
"num_tokens": 487,
"size": 1660
} |
/* wavelet/gsl_wavelet.h
*
* Copyright (C) 2004 Ivo Alxneit
*
* 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_WAVELET2D_H__
#define __GSL_WAVELET2D_H__
#include <stdlib.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_vector_double.h>
#include <gsl/gsl_matrix_double.h>
#include <gsl/gsl_wavelet.h>
#include <gsl/gsl_types.h>
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
# define __BEGIN_DECLS extern "C" {
# define __END_DECLS }
#else
# define __BEGIN_DECLS /* empty */
# define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
GSL_EXPORT int gsl_wavelet2d_transform (const gsl_wavelet * w,
double *data,
size_t tda, size_t size1, size_t size2,
gsl_wavelet_direction dir,
gsl_wavelet_workspace * work);
GSL_EXPORT int gsl_wavelet2d_transform_forward (const gsl_wavelet * w,
double *data,
size_t tda, size_t size1, size_t size2,
gsl_wavelet_workspace * work);
GSL_EXPORT int gsl_wavelet2d_transform_inverse (const gsl_wavelet * w,
double *data,
size_t tda, size_t size1, size_t size2,
gsl_wavelet_workspace * work);
GSL_EXPORT int gsl_wavelet2d_nstransform (const gsl_wavelet * w,
double *data,
size_t tda, size_t size1, size_t size2,
gsl_wavelet_direction dir,
gsl_wavelet_workspace * work);
GSL_EXPORT int gsl_wavelet2d_nstransform_forward (const gsl_wavelet * w,
double *data,
size_t tda, size_t size1, size_t size2,
gsl_wavelet_workspace * work);
GSL_EXPORT int gsl_wavelet2d_nstransform_inverse (const gsl_wavelet * w,
double *data,
size_t tda, size_t size1, size_t size2,
gsl_wavelet_workspace * work);
GSL_EXPORT
int
gsl_wavelet2d_transform_matrix (const gsl_wavelet * w,
gsl_matrix * a,
gsl_wavelet_direction dir,
gsl_wavelet_workspace * work);
GSL_EXPORT
int
gsl_wavelet2d_transform_matrix_forward (const gsl_wavelet * w,
gsl_matrix * a,
gsl_wavelet_workspace * work);
GSL_EXPORT
int
gsl_wavelet2d_transform_matrix_inverse (const gsl_wavelet * w,
gsl_matrix * a,
gsl_wavelet_workspace * work);
GSL_EXPORT
int
gsl_wavelet2d_nstransform_matrix (const gsl_wavelet * w,
gsl_matrix * a,
gsl_wavelet_direction dir,
gsl_wavelet_workspace * work);
GSL_EXPORT
int
gsl_wavelet2d_nstransform_matrix_forward (const gsl_wavelet * w,
gsl_matrix * a,
gsl_wavelet_workspace * work);
GSL_EXPORT
int
gsl_wavelet2d_nstransform_matrix_inverse (const gsl_wavelet * w,
gsl_matrix * a,
gsl_wavelet_workspace * work);
__END_DECLS
#endif /* __GSL_WAVELET2D_H__ */
| {
"alphanum_fraction": 0.535422644,
"avg_line_length": 39.7456140351,
"ext": "h",
"hexsha": "ecb84be0515368cb28b091881cf7a4738e0951d2",
"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_wavelet2d.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_wavelet2d.h",
"max_line_length": 89,
"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_wavelet2d.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 893,
"size": 4531
} |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the program */
/* GCG --- Generic Column Generation */
/* a Dantzig-Wolfe decomposition based extension */
/* of the branch-cut-and-price framework */
/* SCIP --- Solving Constraint Integer Programs */
/* */
/* Copyright (C) 2010-2018 Operations Research, RWTH Aachen University */
/* Zuse Institute Berlin (ZIB) */
/* */
/* This program is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public License */
/* as published by the Free Software Foundation; either version 3 */
/* of the License, or (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU Lesser General Public License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with this program; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.*/
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**@file sepa_basis.c
* @brief basis separator
* @author Jonas Witt
*/
/*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/
/*#define SCIP_DEBUG*/
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "scip/scip.h"
#include "scip/scipdefplugins.h"
#include "sepa_basis.h"
#include "sepa_master.h"
#include "gcg.h"
#include "relax_gcg.h"
#include "pricer_gcg.h"
#include "pub_gcgvar.h"
#ifdef GSL
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_linalg.h>
#endif
#define SEPA_NAME "basis"
#define SEPA_DESC "separator calculates a basis of the orig problem to generate cuts, which cut off the master lp sol"
#define SEPA_PRIORITY 100
#define SEPA_FREQ 0
#define SEPA_MAXBOUNDDIST 1.0
#define SEPA_USESSUBSCIP FALSE /**< does the separator use a secondary SCIP instance? */
#define SEPA_DELAY FALSE /**< should separation method be delayed, if other separators found cuts? */
#define STARTMAXCUTS 50 /**< maximal cuts used at the beginning */
#define MAXCUTSINC 20 /**< increase of allowed number of cuts */
/*
* Data structures
*/
/** separator data */
struct SCIP_SepaData
{
SCIP_ROW** mastercuts; /**< cuts in the master problem */
SCIP_ROW** origcuts; /**< cuts in the original problem */
int norigcuts; /**< number of cuts in the original problem */
int nmastercuts; /**< number of cuts in the master problem */
int maxcuts; /**< maximal number of allowed cuts */
SCIP_ROW** newcuts; /**< new cuts to tighten original problem */
int nnewcuts; /**< number of new cuts */
int maxnewcuts; /**< maximal number of allowed new cuts */
SCIP_ROW* objrow; /**< row with obj coefficients */
SCIP_Bool enable; /**< parameter returns if basis separator is enabled */
SCIP_Bool enableobj; /**< parameter returns if objective constraint is enabled */
SCIP_Bool enableobjround; /**< parameter returns if rhs/lhs of objective constraint is rounded, when obj is int */
SCIP_Bool enableppcuts; /**< parameter returns if cuts generated during pricing are added to newconss array */
SCIP_Bool enableppobjconss; /**< parameter returns if objective constraint for each redcost of pp is enabled */
SCIP_Bool enableppobjcg; /**< parameter returns if objective constraint for each redcost of pp is enabled during pricing */
int separationsetting; /**< parameter returns which parameter setting is used for separation */
SCIP_Bool chgobj; /**< parameter returns if basis is searched with different objective */
SCIP_Bool chgobjallways; /**< parameter returns if obj is not only changed in first iteration */
SCIP_Bool genobjconvex; /**< parameter returns if objconvex is generated dynamically */
SCIP_Bool enableposslack; /**< parameter returns if positive slack should influence the probing objective function */
SCIP_Bool forcecuts; /**< parameter returns if cuts are forced to enter the LP */
int posslackexp; /**< parameter returns exponent of usage of positive slack */
SCIP_Bool posslackexpgen; /**< parameter returns if exponent should be automatically generated */
SCIP_Real posslackexpgenfactor; /**< parameter returns factor for automatically generated exponent */
int iterations; /**< parameter returns number of new rows adding iterations (rows just cut off probing lp sol) */
int mincuts; /**< parameter returns number of minimum cuts needed to return *result = SCIP_Separated */
SCIP_Real objconvex; /**< parameter return convex combination factor */
};
/*
* Local methods
*/
/** allocates enough memory to hold more cuts */
static
SCIP_RETCODE ensureSizeCuts(
SCIP* scip, /**< SCIP data structure */
SCIP_SEPADATA* sepadata, /**< separator data data structure */
int size /**< new size of cut arrays */
)
{
assert(scip != NULL);
assert(sepadata != NULL);
assert(sepadata->mastercuts != NULL);
assert(sepadata->origcuts != NULL);
assert(sepadata->norigcuts <= sepadata->maxcuts);
assert(sepadata->norigcuts >= 0);
assert(sepadata->nmastercuts <= sepadata->maxcuts);
assert(sepadata->nmastercuts >= 0);
if( sepadata->maxcuts < size )
{
while ( sepadata->maxcuts < size )
{
sepadata->maxcuts += MAXCUTSINC;
}
SCIP_CALL( SCIPreallocMemoryArray(scip, &(sepadata->mastercuts), sepadata->maxcuts) );
SCIP_CALL( SCIPreallocMemoryArray(scip, &(sepadata->origcuts), sepadata->maxcuts) );
}
assert(sepadata->maxcuts >= size);
return SCIP_OKAY;
}
/** allocates enough memory to hold more new cuts */
static
SCIP_RETCODE ensureSizeNewCuts(
SCIP* scip, /**< SCIP data structure */
SCIP_SEPADATA* sepadata, /**< separator data data structure */
int size /**< new size of cut arrays */
)
{
assert(scip != NULL);
assert(sepadata != NULL);
assert(sepadata->newcuts != NULL);
assert(sepadata->nnewcuts <= sepadata->maxnewcuts);
assert(sepadata->nnewcuts >= 0);
if( sepadata->maxnewcuts < size )
{
while ( sepadata->maxnewcuts < size )
{
sepadata->maxnewcuts += MAXCUTSINC;
}
SCIP_CALL( SCIPreallocMemoryArray(scip, &(sepadata->newcuts), sepadata->maxnewcuts) );
}
assert(sepadata->maxnewcuts >= size);
return SCIP_OKAY;
}
/** returns the result of the exponentiation for given exponent and basis (basis^exponent) */
static
SCIP_Real exponentiate(
SCIP_Real basis, /**< basis for exponentiation */
int exponent /**< exponent for exponentiation */
)
{
SCIP_Real result;
int i;
assert(exponent >= 0);
result = 1.0;
for( i = 0; i < exponent; ++i )
{
result *= basis;
}
return result;
}
/**< Initialize probing objective coefficient for each variable with original objective. */
static
SCIP_RETCODE initProbingObjWithOrigObj(
SCIP* origscip, /**< orig scip problem */
SCIP_Bool enableobj, /**< returns if objective row was added to the lp */
SCIP_Real objfactor /**< factor, the objective is multiplied with */
)
{
SCIP_VAR** origvars;
int norigvars;
SCIP_VAR* origvar;
SCIP_Real newobj;
int i;
assert(SCIPinProbing(origscip));
origvars = SCIPgetVars(origscip);
norigvars = SCIPgetNVars(origscip);
/** loop over original variables */
for( i = 0; i < norigvars; ++i )
{
/* get variable information */
origvar = origvars[i];
newobj = 0.0;
/* if objective row is enabled consider also the original objective value */
if( enableobj )
newobj = objfactor * SCIPvarGetObj(origvar);
SCIP_CALL( SCIPchgVarObjProbing(origscip, origvar, newobj) );
}
return SCIP_OKAY;
}
/**< Change probing objective coefficient for each variable by adding original objective
* to the probing objective.
*/
static
SCIP_RETCODE chgProbingObjAddingOrigObj(
SCIP* origscip, /**< orig scip problem */
SCIP_Real objfactor, /**< factor the additional part of the objective is multiplied with */
SCIP_Real objdivisor /**< factor the additional part of the objective is divided with */
)
{
SCIP_VAR** origvars;
int norigvars;
SCIP_VAR* origvar;
SCIP_Real newobj;
int i;
assert(SCIPinProbing(origscip));
origvars = SCIPgetVars(origscip);
norigvars = SCIPgetNVars(origscip);
/** loop over original variables */
for( i = 0; i < norigvars; ++i )
{
/* get variable information */
origvar = origvars[i];
newobj = SCIPgetVarObjProbing(origscip, origvar) + (objfactor * SCIPvarGetObj(origvar))/ objdivisor ;
SCIP_CALL( SCIPchgVarObjProbing(origscip, origvar, newobj) );
}
return SCIP_OKAY;
}
/**< Initialize probing objective coefficient for each variable depending on the current origsol.
*
* If variable is at upper bound set objective to -1, if variable is at lower bound set obj to 1,
* else set obj to 0.
* Additionally, add original objective to the probing objective if this is enabled.
*/
static
SCIP_RETCODE initProbingObjUsingVarBounds(
SCIP* origscip, /**< orig scip problem */
SCIP_SEPADATA* sepadata, /**< separator specific data */
SCIP_SOL* origsol, /**< orig solution */
SCIP_Bool enableobj, /**< returns if objective row was added to the lp */
SCIP_Real objfactor /**< factor the objective is multiplied with */
)
{
SCIP_Bool enableposslack;
int posslackexp;
SCIP_VAR** origvars;
int norigvars;
SCIP_VAR* origvar;
SCIP_Real lb;
SCIP_Real ub;
SCIP_Real solval;
SCIP_Real newobj;
SCIP_Real distance;
int i;
origvars = SCIPgetVars(origscip);
norigvars = SCIPgetNVars(origscip);
enableposslack = sepadata->enableposslack;
posslackexp = sepadata->posslackexp;
/** loop over original variables */
for( i = 0; i < norigvars; ++i )
{
/* get variable information */
origvar = origvars[i];
lb = SCIPvarGetLbLocal(origvar);
ub = SCIPvarGetUbLocal(origvar);
solval = SCIPgetSolVal(origscip, origsol, origvar);
assert(SCIPisFeasLE(origscip, solval, ub));
assert(SCIPisFeasGE(origscip, solval, lb));
/* if solution value of variable is at ub or lb initialize objective value of the variable
* such that the difference to this bound is minimized
*/
if( SCIPisFeasEQ(origscip, lb, ub) )
{
newobj = 0.0;
}
else if( SCIPisLT(origscip, ub, SCIPinfinity(origscip)) && SCIPisFeasLE(origscip, ub, solval) )
{
newobj = -1.0;
}
else if( SCIPisGT(origscip, lb, -SCIPinfinity(origscip)) && SCIPisFeasGE(origscip, lb, solval) )
{
newobj = 1.0;
}
else if( enableposslack )
{
/* compute distance from solution to variable bound */
distance = MIN(solval - lb, ub - solval);
assert(SCIPisFeasPositive(origscip, distance));
/* check if distance is lower than 1 and compute factor */
if( SCIPisLT(origscip, distance, 1.0) )
{
newobj = exponentiate(MAX(0.0, 1.0 - distance), posslackexp);
/* check if algebraic sign has to be changed */
if( SCIPisLT(origscip, distance, solval - lb) )
newobj = -newobj;
}
else
{
newobj = 0.0;
}
}
else
{
newobj = 0.0;
}
newobj = newobj * (int) SCIPgetObjsense(origscip);
/* if objective row is enabled consider also the original objective value */
if( enableobj )
newobj = newobj + SCIPvarGetObj(origvar);
SCIP_CALL( SCIPchgVarObjProbing(origscip, origvar, objfactor*newobj) );
}
return SCIP_OKAY;
}
/**< Change probing objective depending on the current origsol.
*
* Loop over all constraints lhs <= sum a_i*x_i <= rhs. If lhs == sum a_i*x_i^* add a_i to objective
* of variable i and if rhs == sum a_i*x_i^* add -a_i to objective of variable i.
*/
static
SCIP_RETCODE chgProbingObjUsingRows(
SCIP* origscip, /**< orig scip problem */
SCIP_SEPADATA* sepadata, /**< separator data */
SCIP_SOL* origsol, /**< orig solution */
SCIP_Real objfactor, /**< factor the objective is multiplied with */
SCIP_Real objdivisor /**< factor the objective is divided with */
)
{
SCIP_Bool enableposslack;
int posslackexp;
SCIP_ROW** rows;
int nrows;
SCIP_ROW* row;
SCIP_Real* vals;
SCIP_VAR** vars;
SCIP_COL** cols;
int nvars;
SCIP_Real lhs;
SCIP_Real rhs;
SCIP_Real* solvals;
SCIP_Real activity;
SCIP_Real factor;
SCIP_Real objadd;
SCIP_Real obj;
SCIP_Real norm;
SCIP_Real distance;
int i;
int j;
rows = SCIPgetLPRows(origscip);
nrows = SCIPgetNLPRows(origscip);
enableposslack = sepadata->enableposslack;
posslackexp = sepadata->posslackexp;
assert(SCIPinProbing(origscip));
SCIP_CALL( SCIPallocBufferArray(origscip, &solvals, SCIPgetNVars(origscip)) );
SCIP_CALL( SCIPallocBufferArray(origscip, &vars, SCIPgetNVars(origscip)) );
/** loop over constraint and check activity */
for( i = 0; i < nrows; ++i )
{
row = rows[i];
lhs = SCIProwGetLhs(row);
rhs = SCIProwGetRhs(row);
nvars = SCIProwGetNNonz(row);
if( nvars == 0 || (sepadata->objrow != NULL && strcmp(SCIProwGetName(row),SCIProwGetName(sepadata->objrow)) == 0 ) )
continue;
/* get values, variables and solution values */
vals = SCIProwGetVals(row);
cols = SCIProwGetCols(row);
for( j = 0; j < nvars; ++j )
{
vars[j] = SCIPcolGetVar(cols[j]);
}
activity = SCIPgetRowSolActivity(origscip, row, origsol);
if( SCIPisFeasEQ(origscip, rhs, lhs) )
{
continue;
}
if( SCIPisLT(origscip, rhs, SCIPinfinity(origscip)) && SCIPisFeasLE(origscip, rhs, activity) )
{
factor = -1.0;
}
else if( SCIPisGT(origscip, lhs, -SCIPinfinity(origscip)) && SCIPisFeasGE(origscip, lhs, activity) )
{
factor = 1.0;
}
else if( enableposslack )
{
assert(!(SCIPisInfinity(origscip, rhs) && SCIPisInfinity(origscip, lhs)));
assert(!(SCIPisInfinity(origscip, activity) && SCIPisInfinity(origscip, -activity)));
/* compute distance from solution to row */
if( SCIPisInfinity(origscip, rhs) && SCIPisGT(origscip, lhs, -SCIPinfinity(origscip)) )
distance = activity - lhs;
else if( SCIPisInfinity(origscip, lhs) && SCIPisLT(origscip, rhs, SCIPinfinity(origscip)) )
distance = rhs - activity;
else
distance = MIN(activity - lhs, rhs - activity);
assert(SCIPisFeasPositive(origscip, distance) || !SCIPisCutEfficacious(origscip, origsol, row));
/* check if distance is lower than 1 and compute factor */
if( SCIPisLT(origscip, distance, 1.0) )
{
factor = exponentiate(MAX(0.0, 1.0 - distance), posslackexp);
/* check if algebraic sign has to be changed */
if( SCIPisLT(origscip, distance, activity - lhs) )
factor = -1.0*factor;
}
else
{
continue;
}
}
else
{
continue;
}
norm = SCIProwGetNorm(row);
/** loop over variables of the constraint and change objective */
for( j = 0; j < nvars; ++j )
{
obj = SCIPgetVarObjProbing(origscip, vars[j]);
objadd = (factor * vals[j]) / norm;
objadd = objadd * (int) SCIPgetObjsense(origscip);
SCIP_CALL( SCIPchgVarObjProbing(origscip, vars[j], obj + (objfactor * objadd) / objdivisor) );
}
}
SCIPfreeBufferArray(origscip, &solvals);
SCIPfreeBufferArray(origscip, &vars);
return SCIP_OKAY;
}
#ifdef GSL
/**< Get matrix (including nrows and ncols) of rows that are satisfied with equality by sol */
static
SCIP_RETCODE getEqualityMatrixGsl(
SCIP* scip, /**< SCIP data structure */
SCIP_SOL* sol, /**< solution */
gsl_matrix** matrix, /**< pointer to store equality matrix */
int* nrows, /**< pointer to store number of rows */
int* ncols, /**< pointer to store number of columns */
int* prerank /**< pointer to store preprocessed rank */
)
{
int* var2col;
int* delvars;
int nvar2col;
int ndelvars;
SCIP_ROW** lprows;
int nlprows;
SCIP_COL** lpcols;
int nlpcols;
int i;
int j;
*ncols = SCIPgetNLPCols(scip);
nlprows = SCIPgetNLPRows(scip);
lprows = SCIPgetLPRows(scip);
nlpcols = SCIPgetNLPCols(scip);
lpcols = SCIPgetLPCols(scip);
*nrows = 0;
ndelvars = 0;
nvar2col = 0;
SCIP_CALL( SCIPallocBufferArray(scip, &var2col, nlpcols) );
SCIP_CALL( SCIPallocBufferArray(scip, &delvars, nlpcols) );
/* loop over lp cols and check if it is at one of its bounds */
for( i = 0; i < nlpcols; ++i )
{
SCIP_COL* lpcol;
SCIP_VAR* lpvar;
lpcol = lpcols[i];
lpvar = SCIPcolGetVar(lpcol);
if( SCIPisEQ(scip, SCIPgetSolVal(scip, sol, lpvar), SCIPcolGetUb(lpcol) )
|| SCIPisEQ(scip, SCIPgetSolVal(scip, sol, lpvar), SCIPcolGetLb(lpcol)) )
{
int ind;
ind = SCIPcolGetIndex(lpcol);
delvars[ndelvars] = ind;
++ndelvars;
var2col[ind] = -1;
}
else
{
int ind;
ind = SCIPcolGetIndex(lpcol);
var2col[ind] = nvar2col;
++nvar2col;
}
}
SCIPsortInt(delvars, ndelvars);
*matrix = gsl_matrix_calloc(nlprows, nvar2col);
*ncols = nvar2col;
/* loop over lp rows and check if solution feasibility is equal to zero */
for( i = 0; i < nlprows; ++i )
{
SCIP_ROW* lprow;
lprow = lprows[i];
/* if solution feasiblity is equal to zero, add row to matrix */
if( SCIPisEQ(scip, SCIPgetRowSolFeasibility(scip, lprow, sol), 0.0) )
{
SCIP_COL** cols;
SCIP_Real* vals;
int nnonz;
cols = SCIProwGetCols(lprow);
vals = SCIProwGetVals(lprow);
nnonz = SCIProwGetNNonz(lprow);
/* get nonzero coefficients of row */
for( j = 0; j < nnonz; ++j )
{
int ind;
int pos;
ind = SCIPcolGetIndex(cols[j]);
assert(ind >= 0 && ind < nlpcols);
if( !SCIPsortedvecFindInt(delvars, ind, ndelvars, &pos) )
{
gsl_matrix_set(*matrix, *nrows, var2col[ind], vals[j]);
}
}
++(*nrows);
}
}
*nrows = nlprows;
*prerank = ndelvars;
SCIPfreeBufferArray(scip, &delvars);
SCIPfreeBufferArray(scip, &var2col);
return SCIP_OKAY;
}
/**< get the rank of a given matrix */
static
SCIP_RETCODE getRank(
SCIP* scip,
gsl_matrix* matrix,
int nrows,
int ncols,
int* rank
)
{
gsl_matrix* matrixq;
gsl_matrix* matrixr;
gsl_vector* tau;
gsl_vector* norm;
gsl_permutation* permutation;
int ranktmp;
int signum;
int i;
matrixq = gsl_matrix_alloc(nrows, nrows);
matrixr = gsl_matrix_alloc(nrows, ncols);
norm = gsl_vector_alloc(ncols);
tau = gsl_vector_alloc(MIN(nrows, ncols));
permutation = gsl_permutation_alloc(ncols);
gsl_linalg_QRPT_decomp(matrix, tau, permutation, &signum, norm);
gsl_linalg_QR_unpack(matrix, tau, matrixq, matrixr);
ranktmp = 0;
for( i = 0; i < MIN(nrows, ncols); ++i )
{
SCIP_Real val;
val = gsl_matrix_get(matrixr, i, i);
if( SCIPisZero(scip, val) )
{
break;
}
++(ranktmp);
}
*rank = ranktmp;
gsl_matrix_free(matrixq);
gsl_matrix_free(matrixr);
gsl_vector_free(tau);
gsl_vector_free(norm);
gsl_permutation_free(permutation);
return SCIP_OKAY;
}
/**< Get rank (number of linear independent rows) of rows that are satisfied
* with equality by solution sol */
static
SCIP_RETCODE getEqualityRankGsl(
SCIP* scip, /**< SCIP data structure */
SCIP_SOL* sol, /**< solution */
int* equalityrank /**< pointer to store rank of rows with equality */
)
{
gsl_matrix* matrix;
int nrows;
int ncols;
int prerank;
int rowrank;
SCIP_CALL( getEqualityMatrixGsl(scip, sol, &matrix, &nrows, &ncols, &prerank) );
SCIP_CALL( getRank(scip, matrix, nrows, ncols, &rowrank) );
gsl_matrix_free(matrix);
*equalityrank = rowrank + prerank;
return SCIP_OKAY;
}
#endif
/** add cuts which are due to the latest objective function of the pricing problems
* (reduced cost non-negative) */
static
SCIP_RETCODE addPPObjConss(
SCIP* scip, /**< SCIP data structure */
SCIP_SEPA* sepa, /**< separator basis */
int ppnumber, /**< number of pricing problem */
SCIP_Real dualsolconv, /**< dual solution corresponding to convexity constraint */
SCIP_Bool newcuts, /**< add cut to newcuts in sepadata? (otherwise add it just to the cutpool) */
SCIP_Bool probing /**< add cut to probing LP? */
)
{
SCIP_SEPADATA* sepadata;
SCIP* pricingscip;
SCIP_VAR** pricingvars;
SCIP_VAR* var;
int npricingvars;
int nvars;
char name[SCIP_MAXSTRLEN];
int j;
int k;
SCIP_OBJSENSE objsense;
SCIP_Real lhs;
SCIP_Real rhs;
sepadata = SCIPsepaGetData(sepa);
nvars = 0;
pricingscip = GCGgetPricingprob(scip, ppnumber);
pricingvars = SCIPgetOrigVars(pricingscip);
npricingvars = SCIPgetNOrigVars(pricingscip);
if( !GCGisPricingprobRelevant(scip, ppnumber) || pricingscip == NULL )
return SCIP_OKAY;
objsense = SCIPgetObjsense(pricingscip);
if( objsense == SCIP_OBJSENSE_MINIMIZE )
{
lhs = dualsolconv;
rhs = SCIPinfinity(scip);
}
else
{
rhs = dualsolconv;
lhs = -SCIPinfinity(scip);
}
for( k = 0; k < GCGgetNIdenticalBlocks(scip, ppnumber); ++k )
{
SCIP_ROW* origcut;
(void) SCIPsnprintf(name, SCIP_MAXSTRLEN, "newconstraint_%d_%d_%d", SCIPsepaGetNCalls(sepa), ppnumber, k);
SCIP_CALL( SCIPcreateEmptyRowUnspec(scip, &origcut, name, lhs, rhs, FALSE, FALSE, TRUE) );
nvars = 0;
for( j = 0; j < npricingvars ; ++j )
{
assert(GCGvarIsPricing(pricingvars[j]));
if( !SCIPisEQ(scip, SCIPvarGetObj(pricingvars[j]), 0.0) )
{
var = GCGpricingVarGetOrigvars(pricingvars[j])[k];
assert(var != NULL);
SCIP_CALL( SCIPaddVarToRow(scip, origcut, var, SCIPvarGetObj(pricingvars[j])) );
++nvars;
}
}
if( nvars > 0 )
{
if( newcuts )
{
SCIP_CALL( ensureSizeNewCuts(scip, sepadata, sepadata->nnewcuts + 1) );
sepadata->newcuts[sepadata->nnewcuts] = origcut;
SCIP_CALL( SCIPcaptureRow(scip, sepadata->newcuts[sepadata->nnewcuts]) );
++(sepadata->nnewcuts);
SCIPdebugMessage("cut added to new cuts in relaxdata\n");
}
else
{
SCIP_CALL( SCIPaddPoolCut(scip, origcut) );
SCIPdebugMessage("cut added to orig cut pool\n");
}
if( probing )
{
SCIP_CALL( SCIPaddRowProbing(scip, origcut) );
SCIPdebugMessage("cut added to probing\n");
}
}
SCIP_CALL( SCIPreleaseRow(scip, &origcut) );
}
return SCIP_OKAY;
}
/*
* Callback methods of separator
*/
/** copy method for separator plugins (called when SCIP copies plugins) */
#if 0
static
SCIP_DECL_SEPACOPY(sepaCopyBasis)
{ /*lint --e{715}*/
SCIPerrorMessage("method of basis separator not implemented yet\n");
SCIPABORT(); /*lint --e{527}*/
return SCIP_OKAY;
}
#else
#define sepaCopyBasis NULL
#endif
/** destructor of separator to free user data (called when SCIP is exiting) */
static
SCIP_DECL_SEPAFREE(sepaFreeBasis)
{ /*lint --e{715}*/
SCIP_SEPADATA* sepadata;
sepadata = SCIPsepaGetData(sepa);
assert(sepadata != NULL);
SCIPfreeMemory(scip, &sepadata);
return SCIP_OKAY;
}
/** initialization method of separator (called after problem was transformed) */
static
SCIP_DECL_SEPAINIT(sepaInitBasis)
{ /*lint --e{715}*/
SCIP* origscip;
SCIP_SEPADATA* sepadata;
SCIP_VAR** origvars;
int norigvars;
char name[SCIP_MAXSTRLEN];
SCIP_Real obj;
int i;
SCIP_Bool enable;
SCIP_Bool enableobj;
assert(scip != NULL);
origscip = GCGmasterGetOrigprob(scip);
assert(origscip != NULL);
sepadata = SCIPsepaGetData(sepa);
assert(sepadata != NULL);
origvars = SCIPgetVars(origscip);
norigvars = SCIPgetNVars(origscip);
SCIPdebugMessage("sepaInitBasis\n");
enable = sepadata->enable;
enableobj = sepadata->enableobj;
sepadata->maxcuts = STARTMAXCUTS;
sepadata->norigcuts = 0;
sepadata->maxnewcuts = 0;
sepadata->nnewcuts = 0;
sepadata->objrow = NULL;
/* if separator is disabled do nothing */
if( !enable )
{
return SCIP_OKAY;
}
SCIP_CALL( SCIPallocMemoryArray(scip, &(sepadata->origcuts), STARTMAXCUTS) ); /*lint !e506*/
SCIP_CALL( SCIPallocMemoryArray(scip, &(sepadata->mastercuts), STARTMAXCUTS) ); /*lint !e506*/
SCIP_CALL( SCIPallocMemoryArray(scip, &(sepadata->newcuts), STARTMAXCUTS) ); /*lint !e506*/
/* if objective row is enabled create row with objective coefficients */
if( enableobj )
{
(void) SCIPsnprintf(name, SCIP_MAXSTRLEN, "objrow");
SCIP_CALL( SCIPcreateEmptyRowUnspec(origscip, &(sepadata->objrow), name, -SCIPinfinity(origscip), SCIPinfinity(origscip), TRUE, FALSE, TRUE) );
for( i = 0; i < norigvars; ++i )
{
obj = SCIPvarGetObj(origvars[i]);
SCIP_CALL( SCIPaddVarToRow(origscip, sepadata->objrow, origvars[i], obj) );
}
}
return SCIP_OKAY;
}
/** deinitialization method of separator (called before transformed problem is freed) */
static
SCIP_DECL_SEPAEXIT(sepaExitBasis)
{ /*lint --e{715}*/
SCIP* origscip;
SCIP_SEPADATA* sepadata;
SCIP_Bool enableobj;
int i;
sepadata = SCIPsepaGetData(sepa);
assert(sepadata != NULL);
enableobj = sepadata->enableobj;
assert(sepadata->nmastercuts == sepadata->norigcuts);
origscip = GCGmasterGetOrigprob(scip);
assert(origscip != NULL);
for( i = 0; i < sepadata->norigcuts; i++ )
{
SCIP_CALL( SCIPreleaseRow(origscip, &(sepadata->origcuts[i])) );
}
for( i = 0; i < sepadata->nnewcuts; ++i )
{
if( sepadata->newcuts[i] != NULL )
SCIP_CALL( SCIPreleaseRow(origscip, &(sepadata->newcuts[i])) );
}
if( enableobj )
SCIP_CALL( SCIPreleaseRow(origscip, &(sepadata->objrow)) );
SCIPfreeMemoryArrayNull(scip, &(sepadata->origcuts));
SCIPfreeMemoryArrayNull(scip, &(sepadata->mastercuts));
SCIPfreeMemoryArrayNull(scip, &(sepadata->newcuts));
return SCIP_OKAY;
}
/** solving process initialization method of separator (called when branch and bound process is about to begin) */
static
SCIP_DECL_SEPAINITSOL(sepaInitsolBasis)
{ /*lint --e{715}*/
SCIP_SEPADATA* sepadata;
sepadata = SCIPsepaGetData(sepa);
assert(sepadata != NULL);
sepadata->nmastercuts = 0;
return SCIP_OKAY;
}
/** solving process deinitialization method of separator (called before branch and bound process data is freed) */
static
SCIP_DECL_SEPAEXITSOL(sepaExitsolBasis)
{ /*lint --e{715}*/
SCIP_SEPADATA* sepadata;
int i;
sepadata = SCIPsepaGetData(sepa);
assert(sepadata != NULL);
assert(sepadata->nmastercuts == sepadata->norigcuts);
assert(GCGmasterGetOrigprob(scip) != NULL);
for( i = 0; i < sepadata->nmastercuts; i++ )
{
SCIP_CALL( SCIPreleaseRow(scip, &(sepadata->mastercuts[i])) );
}
return SCIP_OKAY;
}
/**< Initialize objective due to generation of convex combination */
static
SCIP_RETCODE initGenconv(
SCIP* origscip, /**< original SCIP data structure */
SCIP_SEPADATA* sepadata, /**< separator data structure */
SCIP_SOL* origsol, /**< current original solution */
int nbasis, /**< rank of constraint matrix */
SCIP_Real* convex /**< pointer to store convex combination coefficient */
)
{ /*lint --e{715}*/
#ifdef GSL
int rank;
SCIP_CALL( getEqualityRankGsl(origscip, origsol, &rank) );
*convex = 1.0* rank/nbasis;
SCIPdebugMessage("use generic coefficient %d/%d = %f\n", rank, nbasis, *convex);
#else
SCIPwarningMessage(origscip, "Gnu Scientific Library is not enabled! \n"
"either set sepa/basis/genobjconvex = FALSE sepa/basis/posslackexpgen = FALSE \n"
"or compile with GSL=true and include Gnu Scientific Library\n");
*convex = sepadata->objconvex;
#endif
return SCIP_OKAY;
}
/**< Initialize objective due to generation of convex combination */
static
SCIP_RETCODE initConvObj(
SCIP* origscip, /**< original SCIP data structure */
SCIP_SEPADATA* sepadata, /**< separator data structure */
SCIP_SOL* origsol, /**< current original solution */
SCIP_Real convex, /**< convex coefficient to initialize objective */
SCIP_Bool genericconv /**< was convex coefficient calculated generically? */
)
{
SCIP_Real objnormnull;
SCIP_Real objnormcurrent;
objnormnull = 1.0;
objnormcurrent = 1.0;
if( SCIPisEQ(origscip, convex, 0.0) )
{
SCIP_CALL( initProbingObjWithOrigObj(origscip, TRUE, 1.0) );
}
else if( SCIPisLT(origscip, convex, 1.0) )
{
SCIP_CALL( initProbingObjWithOrigObj(origscip, TRUE, 1.0) );
objnormnull = SCIPgetObjNorm(origscip);
SCIP_CALL( initProbingObjUsingVarBounds(origscip, sepadata, origsol, FALSE, convex) );
SCIP_CALL( chgProbingObjUsingRows(origscip, sepadata, origsol, convex, 1.0) );
objnormcurrent = SCIPgetObjNorm(origscip)/(convex);
if( SCIPisEQ(origscip, objnormcurrent, 0.0) )
SCIP_CALL( initProbingObjWithOrigObj(origscip, TRUE, 1.0) );
else if( SCIPisGT(origscip, objnormnull, 0.0) )
SCIP_CALL( chgProbingObjAddingOrigObj(origscip, (1.0 - convex) * objnormcurrent, objnormnull) );
}
else if( SCIPisEQ(origscip, convex, 1.0) )
{
SCIP_CALL( initProbingObjUsingVarBounds(origscip, sepadata, origsol, !genericconv && sepadata->enableobj, 1.0) );
SCIP_CALL( chgProbingObjUsingRows(origscip, sepadata, origsol, 1.0, 1.0) );
}
return SCIP_OKAY;
}
/** LP solution separation method of separator */
static
SCIP_DECL_SEPAEXECLP(sepaExeclpBasis)
{ /*lint --e{715}*/
SCIP* origscip;
SCIP_SEPADATA* sepadata;
SCIP_SEPA** sepas;
int nsepas;
SCIP_ROW** cuts;
SCIP_ROW* mastercut;
SCIP_ROW* origcut;
SCIP_COL** cols;
SCIP_VAR** roworigvars;
SCIP_VAR** mastervars;
SCIP_Real* mastervals;
int ncols;
int ncuts;
SCIP_Real* vals;
int nmastervars;
SCIP_RESULT resultdummy;
SCIP_OBJSENSE objsense;
SCIP_SOL* origsol;
SCIP_Bool lperror;
SCIP_Bool delayed;
SCIP_Bool cutoff;
SCIP_Bool infeasible;
SCIP_Real obj;
SCIP_Bool enable;
SCIP_Bool enableobj;
SCIP_Bool enableobjround;
SCIP_Bool enableppobjconss;
char name[SCIP_MAXSTRLEN];
int i;
int j;
int iteration;
int nbasis;
int nlprowsstart;
int nlprows;
SCIP_ROW** lprows;
assert(scip != NULL);
assert(result != NULL);
origscip = GCGmasterGetOrigprob(scip);
assert(origscip != NULL);
sepadata = SCIPsepaGetData(sepa);
assert(sepadata != NULL);
SCIPdebugMessage("calling sepaExeclpBasis\n");
*result = SCIP_DIDNOTFIND;
enable = sepadata->enable;
enableobj = sepadata->enableobj;
enableobjround = sepadata->enableobjround;
enableppobjconss = sepadata->enableppobjconss;
/* if separator is disabled do nothing */
if( !enable )
{
SCIPdebugMessage("separator is not enabled\n");
*result = SCIP_DIDNOTRUN;
return SCIP_OKAY;
}
/* ensure master LP is solved to optimality */
if( SCIPgetLPSolstat(scip) != SCIP_LPSOLSTAT_OPTIMAL )
{
SCIPdebugMessage("master LP not solved to optimality, do no separation!\n");
*result = SCIP_DIDNOTRUN;
return SCIP_OKAY;
}
if( GCGgetNRelPricingprobs(origscip) < GCGgetNPricingprobs(origscip) )
{
SCIPdebugMessage("aggregated pricing problems, do no separation!\n");
*result = SCIP_DIDNOTRUN;
return SCIP_OKAY;
}
if( GCGrelaxIsOrigSolFeasible(origscip) )
{
SCIPdebugMessage("Current solution is feasible, no separation necessary!\n");
*result = SCIP_DIDNOTRUN;
return SCIP_OKAY;
}
/* get current original solution */
origsol = GCGrelaxGetCurrentOrigSol(origscip);
/* get obj and objsense */
objsense = SCIPgetObjsense(origscip);
obj = SCIPgetSolOrigObj(origscip, origsol);
/** get number of linearly independent rows needed for basis */
nbasis = SCIPgetNLPCols(origscip);
*result = SCIP_DIDNOTFIND;
/* init iteration counter */
iteration = 0;
/* set parameter setting for separation */
SCIP_CALL( SCIPsetSeparating(origscip, (SCIP_PARAMSETTING) sepadata->separationsetting, TRUE) );
/* start diving */
SCIP_CALL( SCIPstartProbing(origscip) );
SCIP_CALL( SCIPnewProbingNode(origscip) );
SCIP_CALL( SCIPconstructLP(origscip, &cutoff) );
/** add origcuts to probing lp */
for( i = 0; i < GCGsepaGetNCuts(scip); ++i )
{
if( SCIProwGetLPPos(GCGsepaGetOrigcuts(scip)[i]) == -1 )
SCIP_CALL( SCIPaddRowProbing(origscip, GCGsepaGetOrigcuts(scip)[i]) );
}
/** add new cuts which did not cut off master sol to probing lp */
for( i = 0; i < sepadata->nnewcuts; ++i )
{
if( SCIProwGetLPPos(sepadata->newcuts[i]) == -1 )
SCIP_CALL( SCIPaddRowProbing(origscip, sepadata->newcuts[i]) );
}
/* store number of lp rows in the beginning */
nlprowsstart = SCIPgetNLPRows(origscip);
/* while the counter is smaller than the number of allowed iterations,
* try to separate origsol via probing lp sol */
/* TODO: while z*(T) = 0 like Range suggests? But then we have to adjust which cuts are added */
while( iteration < sepadata->iterations )
{
SCIPdebugMessage("iteration %d of at most %d iterations\n", iteration + 1, sepadata->iterations);
SCIP_CALL( SCIPapplyCutsProbing(origscip, &cutoff) );
/* add new constraints if this is enabled */
if( enableppobjconss && iteration == 0 )
{
SCIP_Real* dualsolconv;
SCIPdebugMessage("add reduced cost cut for relevant pricing problems\n");
SCIP_CALL( SCIPallocMemoryArray(scip, &dualsolconv, GCGgetNPricingprobs(origscip)) );
SCIP_CALL( GCGsetPricingObjs(scip, dualsolconv) );
for( i = 0; i < GCGgetNPricingprobs(origscip); ++i )
{
SCIP_CALL( addPPObjConss(origscip, sepa, i, dualsolconv[i], FALSE, TRUE) );
}
SCIPfreeMemoryArray(scip, &dualsolconv);
}
/* init objective */
if( sepadata->chgobj && (iteration == 0 || sepadata->chgobjallways) )
{
SCIPdebugMessage("initialize objective function\n");
if( sepadata->genobjconvex )
{
SCIP_Real genconvex;
SCIP_CALL( initGenconv(origscip, sepadata, origsol, nbasis, &genconvex) );
SCIP_CALL( initConvObj(origscip, sepadata, origsol, genconvex, TRUE) );
}
else
{
SCIPdebugMessage("use given coefficient %g\n", sepadata->objconvex);
if( sepadata->enableposslack && sepadata->posslackexpgen )
{
SCIP_Real genconvex;
SCIP_Real factor;
factor = sepadata->posslackexpgenfactor;
SCIP_CALL( initGenconv(origscip, sepadata, origsol, nbasis, &genconvex) );
sepadata->posslackexp = (int) (SCIPceil(origscip, factor/(1.0 - genconvex)) + 0.5);
SCIPdebugMessage("exponent = %d\n", sepadata->posslackexp);
}
SCIP_CALL( initConvObj(origscip, sepadata, origsol, sepadata->objconvex, FALSE) );
}
}
/* update rhs/lhs of objective constraint and add it to probing LP, if it exists (only in first iteration) */
if( enableobj && iteration == 0 )
{
SCIPdebugMessage("initialize original objective cut\n");
/* round rhs/lhs of objective constraint, if it exists, obj is integral and this is enabled */
if( SCIPisObjIntegral(origscip) && enableobjround )
{
if( objsense == SCIP_OBJSENSE_MAXIMIZE )
{
SCIPdebugMessage("round rhs down\n");
obj = SCIPfloor(origscip, obj);
}
else
{
SCIPdebugMessage("round lhs up\n");
obj = SCIPceil(origscip, obj);
}
}
/* update rhs/lhs of objective constraint */
if( objsense == SCIP_OBJSENSE_MAXIMIZE )
{
SCIP_CALL( SCIPchgRowRhs(origscip, sepadata->objrow, obj) );
SCIP_CALL( SCIPchgRowLhs(origscip, sepadata->objrow, -1.0*SCIPinfinity(origscip)) );
}
else
{
SCIP_CALL( SCIPchgRowLhs(origscip, sepadata->objrow, obj) );
SCIP_CALL( SCIPchgRowRhs(origscip, sepadata->objrow, SCIPinfinity(origscip)) );
}
SCIPdebugMessage("add original objective cut to probing LP\n");
/** add row to probing lp */
SCIP_CALL( SCIPaddRowProbing(origscip, sepadata->objrow) );
}
SCIPdebugMessage("solve probing LP\n");
/* solve probing lp */
SCIP_CALL( SCIPsolveProbingLP(origscip, -1, &lperror, &cutoff) );
assert(!lperror);
/* get separators of origscip */
sepas = SCIPgetSepas(origscip);
nsepas = SCIPgetNSepas(origscip);
SCIPdebugMessage("set parameters of separators\n");
/* loop over sepas and enable/disable sepa */
for( i = 0; i < nsepas; ++i )
{
const char* sepaname;
char paramname[SCIP_MAXSTRLEN];
sepaname = SCIPsepaGetName(sepas[i]);
(void) SCIPsnprintf(paramname, SCIP_MAXSTRLEN, "separating/%s/freq", sepaname);
/* disable intobj, closecuts, rapidlearning and cgmip separator*/
if( strcmp(sepaname, "intobj") == 0 || strcmp(sepaname, "closecuts") == 0
|| strcmp(sepaname, "rapidlearning") == 0
|| (strcmp(sepaname, "cgmip") == 0))
{
SCIP_CALL( SCIPsetIntParam(origscip, paramname, -1) );
}
else
{
SCIP_CALL( SCIPsetIntParam(origscip, paramname, 0) );
}
}
SCIPdebugMessage("separate current LP solution\n");
/** separate current probing lp sol of origscip */
SCIP_CALL( SCIPseparateSol(origscip, NULL, TRUE, FALSE, TRUE, &delayed, &cutoff) );
if( delayed && !cutoff )
{
SCIPdebugMessage("call delayed separators\n");
SCIP_CALL( SCIPseparateSol(origscip, NULL, TRUE, TRUE, TRUE, &delayed, &cutoff) );
}
/* if cut off is detected set result pointer and return SCIP_OKAY */
if( cutoff )
{
*result = SCIP_CUTOFF;
SCIP_CALL( SCIPendProbing(origscip) );
/* disable separating again */
SCIP_CALL( SCIPsetSeparating(origscip, SCIP_PARAMSETTING_OFF, TRUE) );
return SCIP_OKAY;
}
SCIPdebugMessage("separate current LP solution and current original solution in cutpool\n");
/* separate cuts in cutpool */
SCIP_CALL( SCIPseparateSolCutpool(origscip, SCIPgetGlobalCutpool(origscip), NULL, &resultdummy) );
SCIP_CALL( SCIPseparateSolCutpool(origscip, SCIPgetDelayedGlobalCutpool(origscip), NULL, &resultdummy) );
/* separate cuts in cutpool */
SCIP_CALL( SCIPseparateSolCutpool(origscip, SCIPgetGlobalCutpool(origscip), origsol, &resultdummy) );
SCIP_CALL( SCIPseparateSolCutpool(origscip, SCIPgetDelayedGlobalCutpool(origscip), origsol, &resultdummy) );
assert(sepadata->norigcuts == sepadata->nmastercuts);
SCIPdebugMessage("%d cuts are in the original sepastore!\n", SCIPgetNCuts(origscip));
/* get separated cuts */
cuts = SCIPgetCuts(origscip);
ncuts = SCIPgetNCuts(origscip);
SCIP_CALL( ensureSizeCuts(scip, sepadata, sepadata->norigcuts + ncuts) );
mastervars = SCIPgetVars(scip);
nmastervars = SCIPgetNVars(scip);
SCIP_CALL( SCIPallocBufferArray(scip, &mastervals, nmastervars) );
/** loop over cuts and transform cut to master problem (and safe cuts) if it seperates origsol */
for( i = 0; i < ncuts; i++ )
{
SCIP_Bool colvarused;
colvarused = FALSE;
origcut = cuts[i];
/* get columns and vals of the cut */
ncols = SCIProwGetNNonz(origcut);
cols = SCIProwGetCols(origcut);
vals = SCIProwGetVals(origcut);
/* get the variables corresponding to the columns in the cut */
SCIP_CALL( SCIPallocBufferArray(scip, &roworigvars, ncols) );
for( j = 0; j < ncols; j++ )
{
roworigvars[j] = SCIPcolGetVar(cols[j]);
assert(roworigvars[j] != NULL);
if( !GCGvarIsOriginal(roworigvars[j]) )
{
colvarused = TRUE;
break;
}
}
if( colvarused )
{
SCIPwarningMessage(origscip, "colvar used in original cut %s\n", SCIProwGetName(origcut));
SCIPfreeBufferArray(scip, &roworigvars);
continue;
}
if( !SCIPisCutEfficacious(origscip, origsol, origcut) )
{
if( !SCIProwIsLocal(origcut) )
SCIP_CALL( SCIPaddPoolCut(origscip, origcut) );
SCIPfreeBufferArray(scip, &roworigvars);
continue;
}
/* add the cut to the original cut storage */
sepadata->origcuts[sepadata->norigcuts] = origcut;
SCIP_CALL( SCIPcaptureRow(origscip, sepadata->origcuts[sepadata->norigcuts]) );
sepadata->norigcuts++;
/* create new cut in the master problem */
(void) SCIPsnprintf(name, SCIP_MAXSTRLEN, "mc_basis_%s", SCIProwGetName(origcut));
SCIP_CALL( SCIPcreateEmptyRowSepa(scip, &mastercut, sepa, name,
( SCIPisInfinity(scip, -SCIProwGetLhs(origcut)) ?
SCIProwGetLhs(origcut) : SCIProwGetLhs(origcut) - SCIProwGetConstant(origcut)),
( SCIPisInfinity(scip, SCIProwGetRhs(origcut)) ?
SCIProwGetRhs(origcut) : SCIProwGetRhs(origcut) - SCIProwGetConstant(origcut)),
SCIProwIsLocal(origcut), TRUE, FALSE) );
/* transform the original variables to master variables and add them to the cut */
GCGtransformOrigvalsToMastervals(origscip, roworigvars, vals, ncols, mastervars, mastervals, nmastervars);
SCIP_CALL( SCIPaddVarsToRow(scip, mastercut, nmastervars, mastervars, mastervals) );
/* add the cut to the master problem and to the master cut storage */
SCIP_CALL( SCIPaddRow(scip, mastercut, sepadata->forcecuts, &infeasible) );
sepadata->mastercuts[sepadata->nmastercuts] = mastercut;
SCIP_CALL( SCIPcaptureRow(scip, sepadata->mastercuts[sepadata->nmastercuts]) );
sepadata->nmastercuts++;
SCIP_CALL( GCGsepaAddMastercuts(scip, origcut, mastercut) );
SCIP_CALL( SCIPreleaseRow(scip, &mastercut) );
SCIPfreeBufferArray(scip, &roworigvars);
}
if( SCIPgetNCuts(scip) >= sepadata->mincuts )
{
*result = SCIP_SEPARATED;
iteration = sepadata->iterations;
}
else if( SCIPgetNCuts(origscip) == 0 )
{
iteration = sepadata->iterations;
}
else
{
++iteration;
}
SCIPdebugMessage("%d cuts are in the master sepastore!\n", SCIPgetNCuts(scip));
SCIPfreeBufferArray(scip, &mastervals);
assert(sepadata->norigcuts == sepadata->nmastercuts );
}
SCIP_CALL( SCIPclearCuts(origscip) );
lprows = SCIPgetLPRows(origscip);
nlprows = SCIPgetNLPRows(origscip);
assert(nlprowsstart <= nlprows);
SCIP_CALL( ensureSizeNewCuts(scip, sepadata, sepadata->nnewcuts + nlprows - nlprowsstart) );
for( i = nlprowsstart; i < nlprows; ++i )
{
if( SCIProwGetOrigintype(lprows[i]) == SCIP_ROWORIGINTYPE_SEPA )
{
sepadata->newcuts[sepadata->nnewcuts] = lprows[i];
SCIP_CALL( SCIPcaptureRow(origscip, sepadata->newcuts[sepadata->nnewcuts]) );
++(sepadata->nnewcuts);
}
}
/* end diving */
SCIP_CALL( SCIPendProbing(origscip) );
if( SCIPgetNCuts(scip) > 0 )
{
*result = SCIP_SEPARATED;
}
/* disable separating again */
SCIP_CALL( SCIPsetSeparating(origscip, SCIP_PARAMSETTING_OFF, TRUE) );
SCIPdebugMessage("exiting sepaExeclpBasis\n");
return SCIP_OKAY;
}
/** arbitrary primal solution separation method of separator */
#if 0
static
SCIP_DECL_SEPAEXECSOL(sepaExecsolBasis)
{ /*lint --e{715}*/
SCIPerrorMessage("method of basis separator not implemented yet\n");
SCIPABORT(); /*lint --e{527}*/
return SCIP_OKAY;
}
#else
#define sepaExecsolBasis NULL
#endif
/*
* separator specific interface methods
*/
/** creates the basis separator and includes it in SCIP */
SCIP_RETCODE SCIPincludeSepaBasis(
SCIP* scip /**< SCIP data structure */
)
{
SCIP_SEPADATA* sepadata;
/* create master separator data */
SCIP_CALL( SCIPallocMemory(scip, &sepadata) );
sepadata->mastercuts = NULL;
sepadata->origcuts = NULL;
sepadata->norigcuts = 0;
sepadata->nmastercuts = 0;
sepadata->maxcuts = 0;
sepadata->newcuts = NULL;
sepadata->nnewcuts = 0;
sepadata->maxnewcuts = 0;
sepadata->objrow = NULL;
/* include separator */
SCIP_CALL( SCIPincludeSepa(scip, SEPA_NAME, SEPA_DESC, SEPA_PRIORITY, SEPA_FREQ, SEPA_MAXBOUNDDIST,
SEPA_USESSUBSCIP, SEPA_DELAY,
sepaCopyBasis, sepaFreeBasis, sepaInitBasis, sepaExitBasis, sepaInitsolBasis, sepaExitsolBasis, sepaExeclpBasis, sepaExecsolBasis,
sepadata) );
/* add basis separator parameters */
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/enable", "is basis separator enabled?",
&(sepadata->enable), FALSE, TRUE, NULL, NULL) );
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/enableobj", "is objective constraint of separator enabled?",
&(sepadata->enableobj), FALSE, FALSE, NULL, NULL) );
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/enableobjround", "round obj rhs/lhs of obj constraint if obj is int?",
&(sepadata->enableobjround), FALSE, FALSE, NULL, NULL) );
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/enableppcuts", "add cuts generated during pricing to newconss array?",
&(sepadata->enableppcuts), FALSE, FALSE, NULL, NULL) );
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/enableppobjconss", "is objective constraint for redcost of each pp of "
"separator enabled?", &(sepadata->enableppobjconss), FALSE, FALSE, NULL, NULL) );
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/enableppobjcg", "is objective constraint for redcost of each pp during "
"pricing of separator enabled?", &(sepadata->enableppobjcg), FALSE, FALSE, NULL, NULL) );
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/genobjconvex", "generated obj convex dynamically",
&(sepadata->genobjconvex), FALSE, FALSE, NULL, NULL) );
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/enableposslack", "should positive slack influence the probing objective "
"function?", &(sepadata->enableposslack), FALSE, FALSE, NULL, NULL) );
SCIP_CALL( SCIPaddIntParam(GCGmasterGetOrigprob(scip), "sepa/basis/posslackexp", "exponent of positive slack usage",
&(sepadata->posslackexp), FALSE, 1, 1, INT_MAX, NULL, NULL) );
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/posslackexpgen", "automatically generated exponent?",
&(sepadata->posslackexpgen), FALSE, FALSE, NULL, NULL) );
SCIP_CALL( SCIPaddRealParam(GCGmasterGetOrigprob(scip), "sepa/basis/posslackexpgenfactor", "factor for automatically generated exponent",
&(sepadata->posslackexpgenfactor), FALSE, 0.1, SCIPepsilon(GCGmasterGetOrigprob(scip)),
SCIPinfinity(GCGmasterGetOrigprob(scip)), NULL, NULL) );
SCIP_CALL( SCIPaddRealParam(GCGmasterGetOrigprob(scip), "sepa/basis/objconvex", "convex combination factor",
&(sepadata->objconvex), FALSE, 1.0, 0.0, 1.0, NULL, NULL) );
SCIP_CALL( SCIPaddIntParam(GCGmasterGetOrigprob(scip), "sepa/basis/paramsetting", "parameter returns which parameter setting is used for "
"separation (default = 0, aggressive = 1, fast = 2", &(sepadata->separationsetting), FALSE, 1, 0, 2, NULL, NULL) );
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/chgobj", "parameter returns if basis is searched with different objective",
&(sepadata->chgobj), FALSE, TRUE, NULL, NULL) );
SCIP_CALL( SCIPaddIntParam(GCGmasterGetOrigprob(scip), "sepa/basis/iterations", "parameter returns if number new rows adding"
"iterations (rows just cut off probing lp sol)", &(sepadata->iterations), FALSE, 100, 1, 10000000 , NULL, NULL) );
SCIP_CALL( SCIPaddIntParam(GCGmasterGetOrigprob(scip), "sepa/basis/mincuts", "parameter returns number of minimum cuts needed to "
"return *result = SCIP_Separated", &(sepadata->mincuts), FALSE, 1, 1, 100, NULL, NULL) );
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/chgobjallways", "parameter returns if obj is changed not only in the "
"first iteration", &(sepadata->chgobjallways), FALSE, FALSE, NULL, NULL) );
SCIP_CALL( SCIPaddBoolParam(GCGmasterGetOrigprob(scip), "sepa/basis/forcecuts", "parameter returns if cuts are forced to enter the LP ",
&(sepadata->forcecuts), FALSE, FALSE, NULL, NULL) );
return SCIP_OKAY;
}
/** returns the array of original cuts saved in the separator data */
SCIP_ROW** GCGsepaBasisGetOrigcuts(
SCIP* scip /**< SCIP data structure */
)
{
SCIP_SEPA* sepa;
SCIP_SEPADATA* sepadata;
assert(scip != NULL);
sepa = SCIPfindSepa(scip, SEPA_NAME);
assert(sepa != NULL);
sepadata = SCIPsepaGetData(sepa);
assert(sepadata != NULL);
return sepadata->origcuts;
}
/** returns the number of original cuts saved in the separator data */
int GCGsepaBasisGetNOrigcuts(
SCIP* scip /**< SCIP data structure */
)
{
SCIP_SEPA* sepa;
SCIP_SEPADATA* sepadata;
assert(scip != NULL);
sepa = SCIPfindSepa(scip, SEPA_NAME);
assert(sepa != NULL);
sepadata = SCIPsepaGetData(sepa);
assert(sepadata != NULL);
return sepadata->norigcuts;
}
/** returns the array of master cuts saved in the separator data */
SCIP_ROW** GCGsepaBasisGetMastercuts(
SCIP* scip /**< SCIP data structure */
)
{
SCIP_SEPA* sepa;
SCIP_SEPADATA* sepadata;
assert(scip != NULL);
sepa = SCIPfindSepa(scip, SEPA_NAME);
assert(sepa != NULL);
sepadata = SCIPsepaGetData(sepa);
assert(sepadata != NULL);
return sepadata->mastercuts;
}
/** returns the number of master cuts saved in the separator data */
int GCGsepaBasisGetNMastercuts(
SCIP* scip /**< SCIP data structure */
)
{
SCIP_SEPA* sepa;
SCIP_SEPADATA* sepadata;
assert(scip != NULL);
sepa = SCIPfindSepa(scip, SEPA_NAME);
assert(sepa != NULL);
sepadata = SCIPsepaGetData(sepa);
assert(sepadata != NULL);
return sepadata->nmastercuts;
}
/** transforms cut in pricing variables to cut in original variables and adds it to newcuts array */
SCIP_RETCODE GCGsepaBasisAddPricingCut(
SCIP* scip,
int ppnumber,
SCIP_ROW* cut
)
{
SCIP* origscip;
SCIP_SEPA* sepa;
SCIP_SEPADATA* sepadata;
SCIP* pricingprob;
SCIP_Real* vals;
SCIP_COL** cols;
SCIP_VAR** pricingvars;
int nvars;
int i;
int j;
int k;
char name[SCIP_MAXSTRLEN];
assert(GCGisMaster(scip));
sepa = SCIPfindSepa(scip, SEPA_NAME);
if( sepa == NULL )
{
SCIPerrorMessage("sepa basis not found\n");
return SCIP_OKAY;
}
sepadata = SCIPsepaGetData(sepa);
origscip = GCGmasterGetOrigprob(scip);
pricingprob = GCGgetPricingprob(origscip, ppnumber);
if( !sepadata->enableppcuts )
{
return SCIP_OKAY;
}
assert(!SCIProwIsLocal(cut));
nvars = SCIProwGetNNonz(cut);
cols = SCIProwGetCols(cut);
vals = SCIProwGetVals(cut);
if( nvars == 0 )
{
return SCIP_OKAY;
}
SCIP_CALL( SCIPallocMemoryArray(scip, &pricingvars, nvars) );
for( i = 0; i < nvars; ++i )
{
pricingvars[i] = SCIPcolGetVar(cols[i]);
assert(pricingvars[i] != NULL);
}
for( k = 0; k < GCGgetNIdenticalBlocks(origscip, ppnumber); ++k )
{
SCIP_ROW* origcut;
(void) SCIPsnprintf(name, SCIP_MAXSTRLEN, "ppcut_%d_%d_%d", SCIPsepaGetNCalls(sepa), ppnumber, k);
SCIP_CALL( SCIPcreateEmptyRowUnspec(origscip, &origcut, name,
( SCIPisInfinity(pricingprob, -SCIProwGetLhs(cut)) ?
-SCIPinfinity(origscip) : SCIProwGetLhs(cut) - SCIProwGetConstant(cut)),
( SCIPisInfinity(pricingprob, SCIProwGetRhs(cut)) ?
SCIPinfinity(origscip) : SCIProwGetRhs(cut) - SCIProwGetConstant(cut)),
FALSE, FALSE, TRUE) );
for( j = 0; j < nvars ; ++j )
{
SCIP_VAR* var;
if( !GCGvarIsPricing(pricingvars[j]) )
{
nvars = 0;
break;
}
assert(GCGvarIsPricing(pricingvars[j]));
var = GCGpricingVarGetOrigvars(pricingvars[j])[k];
assert(var != NULL);
SCIP_CALL( SCIPaddVarToRow(origscip, origcut, var, vals[j]) );
}
if( nvars > 0 )
{
SCIP_CALL( ensureSizeNewCuts(scip, sepadata, sepadata->nnewcuts + 1) );
sepadata->newcuts[sepadata->nnewcuts] = origcut;
SCIP_CALL( SCIPcaptureRow(scip, sepadata->newcuts[sepadata->nnewcuts]) );
++(sepadata->nnewcuts);
SCIPdebugMessage("cut added to orig cut pool\n");
}
SCIP_CALL( SCIPreleaseRow(origscip, &origcut) );
}
SCIPfreeMemoryArray(scip, &pricingvars);
return SCIP_OKAY;
}
/** add cuts which are due to the latest objective function of the pricing problems
* (reduced cost non-negative) */
SCIP_RETCODE SCIPsepaBasisAddPPObjConss(
SCIP* scip, /**< SCIP data structure */
int ppnumber, /**< number of pricing problem */
SCIP_Real dualsolconv, /**< dual solution corresponding to convexity constraint */
SCIP_Bool newcuts /**< add cut to newcuts in sepadata? (otherwise add it just to the cutpool) */
)
{
SCIP_SEPA* sepa;
assert(GCGisMaster(scip));
sepa = SCIPfindSepa(scip, SEPA_NAME);
if( sepa == NULL )
{
SCIPerrorMessage("sepa basis not found\n");
return SCIP_OKAY;
}
SCIP_CALL( addPPObjConss(GCGmasterGetOrigprob(scip), sepa, ppnumber, dualsolconv, newcuts, FALSE) );
return SCIP_OKAY;
}
| {
"alphanum_fraction": 0.6158557567,
"avg_line_length": 31.9889928453,
"ext": "c",
"hexsha": "8adc30080a29fdedeaa77550e91be81b527cb1a2",
"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": "a90ce2229108197fd48f956310ae2929e0fa5d9a",
"max_forks_repo_licenses": [
"AFL-1.1"
],
"max_forks_repo_name": "npwebste/UPS_Controller",
"max_forks_repo_path": "lib/scipoptsuite-5.0.1/gcg/src/sepa_basis.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a90ce2229108197fd48f956310ae2929e0fa5d9a",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"AFL-1.1"
],
"max_issues_repo_name": "npwebste/UPS_Controller",
"max_issues_repo_path": "lib/scipoptsuite-5.0.1/gcg/src/sepa_basis.c",
"max_line_length": 149,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a90ce2229108197fd48f956310ae2929e0fa5d9a",
"max_stars_repo_licenses": [
"AFL-1.1"
],
"max_stars_repo_name": "npwebste/UPS_Controller",
"max_stars_repo_path": "lib/scipoptsuite-5.0.1/gcg/src/sepa_basis.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 15430,
"size": 58124
} |
#include <gsl/gsl_math.h>
#include <gsl/gsl_cblas.h>
#include "cblas.h"
#include "error_cblas_l2.h"
void
cblas_zgbmv (const enum CBLAS_ORDER order, const enum CBLAS_TRANSPOSE TransA,
const int M, const int N, const int KL, const int KU,
const void *alpha, const void *A, const int lda, const void *X,
const int incX, const void *beta, void *Y, const int incY)
{
#define BASE double
#include "source_gbmv_c.h"
#undef BASE
}
| {
"alphanum_fraction": 0.6803455724,
"avg_line_length": 28.9375,
"ext": "c",
"hexsha": "2c0c1308a9aad6705b3f7dded8d715dc54678661",
"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/cblas/zgbmv.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/cblas/zgbmv.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/cblas/zgbmv.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": 135,
"size": 463
} |
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <math.h>
#include "cconfigspace_internal.h"
#include "distribution_internal.h"
struct _ccs_distribution_roulette_data_s {
_ccs_distribution_common_data_t common_data;
size_t num_areas;
ccs_float_t *areas;
};
typedef struct _ccs_distribution_roulette_data_s _ccs_distribution_roulette_data_t;
static ccs_result_t
_ccs_distribution_del(ccs_object_t o) {
(void)o;
return CCS_SUCCESS;
}
static ccs_result_t
_ccs_distribution_roulette_get_bounds(_ccs_distribution_data_t *data,
ccs_interval_t *interval_ret);
static ccs_result_t
_ccs_distribution_roulette_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
ccs_numeric_t *values);
static ccs_result_t
_ccs_distribution_roulette_strided_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
size_t stride,
ccs_numeric_t *values);
static ccs_result_t
_ccs_distribution_roulette_soa_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
ccs_numeric_t **values);
static _ccs_distribution_ops_t _ccs_distribution_roulette_ops = {
{ &_ccs_distribution_del },
&_ccs_distribution_roulette_samples,
&_ccs_distribution_roulette_get_bounds,
&_ccs_distribution_roulette_strided_samples,
&_ccs_distribution_roulette_soa_samples
};
static ccs_result_t
_ccs_distribution_roulette_get_bounds(_ccs_distribution_data_t *data,
ccs_interval_t *interval_ret) {
_ccs_distribution_roulette_data_t *d = (_ccs_distribution_roulette_data_t *)data;
interval_ret->type = CCS_NUM_INTEGER;
interval_ret->lower = CCSI(INT64_C(0));
interval_ret->upper = CCSI((ccs_int_t)(d->num_areas));
interval_ret->lower_included = CCS_TRUE;
interval_ret->upper_included = CCS_FALSE;
return CCS_SUCCESS;
}
static ccs_result_t
_ccs_distribution_roulette_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
ccs_numeric_t *values) {
_ccs_distribution_roulette_data_t *d = (_ccs_distribution_roulette_data_t *)data;
gsl_rng *grng;
CCS_VALIDATE(ccs_rng_get_gsl_rng(rng, &grng));
for (size_t i = 0; i < num_values; i++) {
ccs_float_t rnd = gsl_rng_uniform(grng);
ccs_int_t index = ccs_dichotomic_search(d->num_areas, d->areas, rnd);
values[i].i = index;
}
return CCS_SUCCESS;
}
static ccs_result_t
_ccs_distribution_roulette_strided_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
size_t stride,
ccs_numeric_t *values) {
_ccs_distribution_roulette_data_t *d = (_ccs_distribution_roulette_data_t *)data;
gsl_rng *grng;
CCS_VALIDATE(ccs_rng_get_gsl_rng(rng, &grng));
for (size_t i = 0; i < num_values; i++) {
ccs_float_t rnd = gsl_rng_uniform(grng);
ccs_int_t index = ccs_dichotomic_search(d->num_areas, d->areas, rnd);
values[i*stride].i = index;
}
return CCS_SUCCESS;
}
static ccs_result_t
_ccs_distribution_roulette_soa_samples(_ccs_distribution_data_t *data,
ccs_rng_t rng,
size_t num_values,
ccs_numeric_t **values) {
if (*values)
return _ccs_distribution_roulette_samples(data, rng, num_values, *values);
return CCS_SUCCESS;
}
ccs_result_t
ccs_create_roulette_distribution(size_t num_areas,
ccs_float_t *areas,
ccs_distribution_t *distribution_ret) {
CCS_CHECK_ARY(num_areas, areas);
CCS_CHECK_PTR(distribution_ret);
if (!num_areas || num_areas > INT64_MAX)
return -CCS_INVALID_VALUE;
ccs_float_t sum = 0.0;
for(size_t i = 0; i < num_areas; i++) {
if (areas[i] < 0.0)
return -CCS_INVALID_VALUE;
sum += areas[i];
}
if (sum == 0.0)
return -CCS_INVALID_VALUE;
ccs_float_t inv_sum = 1.0/sum;
if (isnan(inv_sum) || !isfinite(inv_sum))
return -CCS_INVALID_VALUE;
uintptr_t mem = (uintptr_t)calloc(1, sizeof(struct _ccs_distribution_s) + sizeof(_ccs_distribution_roulette_data_t) + sizeof(ccs_float_t)*(num_areas + 1) + sizeof(ccs_numeric_type_t));
if (!mem)
return -CCS_OUT_OF_MEMORY;
ccs_distribution_t distrib = (ccs_distribution_t)mem;
_ccs_object_init(&(distrib->obj), CCS_DISTRIBUTION, (_ccs_object_ops_t *)&_ccs_distribution_roulette_ops);
_ccs_distribution_roulette_data_t * distrib_data = (_ccs_distribution_roulette_data_t *)(mem + sizeof(struct _ccs_distribution_s));
distrib_data->common_data.data_types = (ccs_numeric_type_t *)(mem + sizeof(struct _ccs_distribution_s) + sizeof(_ccs_distribution_roulette_data_t) + sizeof(ccs_float_t)*(num_areas + 1));
distrib_data->common_data.type = CCS_ROULETTE;
distrib_data->common_data.dimension = 1;
distrib_data->common_data.data_types[0] = CCS_NUM_INTEGER;
distrib_data->num_areas = num_areas;
distrib_data->areas = (ccs_float_t *)(mem + sizeof(struct _ccs_distribution_s) + sizeof(_ccs_distribution_roulette_data_t));
distrib_data->areas[0] = 0.0;
for(size_t i = 1; i <= num_areas; i++) {
distrib_data->areas[i] = distrib_data->areas[i-1] + areas[i-1] * inv_sum;
}
distrib_data->areas[num_areas] = 1.0;
if (distrib_data->areas[num_areas] < distrib_data->areas[num_areas-1]) {
free((void *)mem);
return -CCS_INVALID_VALUE;
}
distrib->data = (_ccs_distribution_data_t *)distrib_data;
*distribution_ret = distrib;
return CCS_SUCCESS;
}
ccs_result_t
ccs_roulette_distribution_get_num_areas(ccs_distribution_t distribution,
size_t *num_areas_ret) {
CCS_CHECK_DISTRIBUTION(distribution, CCS_ROULETTE);
CCS_CHECK_PTR(num_areas_ret);
_ccs_distribution_roulette_data_t * data = (_ccs_distribution_roulette_data_t *)distribution->data;
*num_areas_ret = data->num_areas;
return CCS_SUCCESS;
}
ccs_result_t
ccs_roulette_distribution_get_areas(ccs_distribution_t distribution,
size_t num_areas,
ccs_float_t *areas,
size_t *num_areas_ret) {
CCS_CHECK_DISTRIBUTION(distribution, CCS_ROULETTE);
CCS_CHECK_ARY(num_areas, areas);
if (!areas && !num_areas_ret)
return -CCS_INVALID_VALUE;
_ccs_distribution_roulette_data_t * data = (_ccs_distribution_roulette_data_t *)distribution->data;
if (areas) {
if (num_areas < data->num_areas)
return -CCS_INVALID_VALUE;
for (size_t i = 0; i < data->num_areas; i++)
areas[i] = data->areas[i+1] - data->areas[i];
for (size_t i = data->num_areas; i < num_areas; i++)
areas[i] = 0.0;
}
if (num_areas_ret)
*num_areas_ret = data->num_areas;
return CCS_SUCCESS;
}
| {
"alphanum_fraction": 0.6299171843,
"avg_line_length": 40.0414507772,
"ext": "c",
"hexsha": "5667a35c85016007ace5068ed4fd0e5442d224d1",
"lang": "C",
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2021-12-07T17:54:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-16T18:20:47.000Z",
"max_forks_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "deephyper/CCS",
"max_forks_repo_path": "src/distribution_roulette.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_issues_repo_issues_event_max_datetime": "2021-12-15T10:48:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-12-15T10:37:41.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "deephyper/CCS",
"max_issues_repo_path": "src/distribution_roulette.c",
"max_line_length": 190,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "dd8c976eca2a510c995862cc5c871e81932f3ff4",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "deephyper/CCS",
"max_stars_repo_path": "src/distribution_roulette.c",
"max_stars_repo_stars_event_max_datetime": "2021-11-29T16:31:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-29T16:31:28.000Z",
"num_tokens": 1817,
"size": 7728
} |
/* wavelet/gsl_wavelet.h
*
* Copyright (C) 2004 Ivo Alxneit
*
* 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_WAVELET_H__
#define __GSL_WAVELET_H__
#include <stdlib.h>
#include <gsl/gsl_types.h>
#include <gsl/gsl_errno.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
#ifndef GSL_DISABLE_DEPRECATED
typedef enum {
forward = 1, backward = -1,
gsl_wavelet_forward = 1, gsl_wavelet_backward = -1
}
gsl_wavelet_direction;
#else
typedef enum {
gsl_wavelet_forward = 1, gsl_wavelet_backward = -1
}
gsl_wavelet_direction;
#endif
typedef struct
{
const char *name;
int (*init) (const double **h1, const double **g1,
const double **h2, const double **g2, size_t * nc,
size_t * offset, size_t member);
}
gsl_wavelet_type;
typedef struct
{
const gsl_wavelet_type *type;
const double *h1;
const double *g1;
const double *h2;
const double *g2;
size_t nc;
size_t offset;
}
gsl_wavelet;
typedef struct
{
double *scratch;
size_t n;
}
gsl_wavelet_workspace;
GSL_VAR const gsl_wavelet_type *gsl_wavelet_daubechies;
GSL_VAR const gsl_wavelet_type *gsl_wavelet_daubechies_centered;
GSL_VAR const gsl_wavelet_type *gsl_wavelet_haar;
GSL_VAR const gsl_wavelet_type *gsl_wavelet_haar_centered;
GSL_VAR const gsl_wavelet_type *gsl_wavelet_bspline;
GSL_VAR const gsl_wavelet_type *gsl_wavelet_bspline_centered;
gsl_wavelet *gsl_wavelet_alloc (const gsl_wavelet_type * T, size_t k);
void gsl_wavelet_free (gsl_wavelet * w);
const char *gsl_wavelet_name (const gsl_wavelet * w);
gsl_wavelet_workspace *gsl_wavelet_workspace_alloc (size_t n);
void gsl_wavelet_workspace_free (gsl_wavelet_workspace * work);
int gsl_wavelet_transform (const gsl_wavelet * w,
double *data, size_t stride, size_t n,
gsl_wavelet_direction dir,
gsl_wavelet_workspace * work);
int gsl_wavelet_transform_forward (const gsl_wavelet * w,
double *data, size_t stride, size_t n,
gsl_wavelet_workspace * work);
int gsl_wavelet_transform_inverse (const gsl_wavelet * w,
double *data, size_t stride, size_t n,
gsl_wavelet_workspace * work);
__END_DECLS
#endif /* __GSL_WAVELET_H__ */
| {
"alphanum_fraction": 0.7047648708,
"avg_line_length": 29.4587155963,
"ext": "h",
"hexsha": "fde012cd30107997ad6eecf7aca32493871d991c",
"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/wavelet/gsl_wavelet.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/wavelet/gsl_wavelet.h",
"max_line_length": 81,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/wavelet/gsl_wavelet.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": 829,
"size": 3211
} |
#include <bindings.cmacros.h>
#include <gsl/gsl_version.h>
BC_GLOBALARRAY(GSL_VERSION,char)
BC_GLOBALARRAY(gsl_version,char)
| {
"alphanum_fraction": 0.8174603175,
"avg_line_length": 21,
"ext": "c",
"hexsha": "c77faaf380851ddb1ef25f37e37e4d1fd5efcc9d",
"lang": "C",
"max_forks_count": 19,
"max_forks_repo_forks_event_max_datetime": "2021-09-10T19:31:38.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-03T20:43:08.000Z",
"max_forks_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "flip111/bindings-dsl",
"max_forks_repo_path": "bindings-gsl/src/Bindings/Gsl/Version.c",
"max_issues_count": 23,
"max_issues_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb",
"max_issues_repo_issues_event_max_datetime": "2021-04-07T09:49:12.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-01-04T06:32:10.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "flip111/bindings-dsl",
"max_issues_repo_path": "bindings-gsl/src/Bindings/Gsl/Version.c",
"max_line_length": 32,
"max_stars_count": 25,
"max_stars_repo_head_hexsha": "6ed49c4eb089e63e4e25d84e7cad75c96116affb",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "flip111/bindings-dsl",
"max_stars_repo_path": "bindings-gsl/src/Bindings/Gsl/Version.c",
"max_stars_repo_stars_event_max_datetime": "2022-02-06T09:29:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-04-29T00:31:20.000Z",
"num_tokens": 32,
"size": 126
} |
/* These functions compute linear preprocessing for
the UE using LAPACKE and CBLAS modules of
LAPACK libraries.
MMSE and MMSE whitening filters are available.
Functions are using RowMajor storage of the
matrices, like in conventional C. Traditional
Fortran functions of LAPACK employ ColumnMajor
data storage. */
#include<stdio.h>
#include<math.h>
#include<complex.h>
#include <stdlib.h>
#include <cblas.h>
#include <string.h>
#include <linux/version.h>
#if RHEL_RELEASE_CODE >= 1796
#include <lapacke/lapacke_utils.h>
#include <lapacke/lapacke.h>
#else
#include <lapacke_utils.h>
#include <lapacke.h>
#endif
//#define DEBUG_PREPROC
void transpose (int N, float complex *A, float complex *Result)
{
// COnputes C := alpha*op(A)*op(B) + beta*C,
enum CBLAS_TRANSPOSE transa = CblasTrans;
enum CBLAS_TRANSPOSE transb = CblasNoTrans;
int rows_opA = N; // number of rows in op(A) and in C
int col_opB = N; //number of columns of op(B) and in C
int col_opA = N; //number of columns in op(A) and rows in op(B)
int col_B; //number of columns in B
float complex alpha = 1.0+I*0;
int lda = rows_opA;
float complex beta = 0.0+I*0;
int ldc = rows_opA;
int i;
float complex* B;
int ldb = col_opB;
if (transb == CblasNoTrans) {
B = (float complex*)calloc(ldb*col_opB,sizeof(float complex));
col_B= col_opB;
}
else {
B = (float complex*)calloc(ldb*col_opA, sizeof(float complex));
col_B = col_opA;
}
float complex* C = (float complex*)malloc(ldc*col_opB*sizeof(float complex));
for (i=0; i<lda*col_B; i+=N+1)
B[i]=1.0+I*0;
cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, A, lda, B, ldb, &beta, C, ldc);
memcpy(Result, C, N*N*sizeof(float complex));
free(B);
free(C);
}
void conjugate_transpose (int N, float complex *A, float complex *Result)
{
// Computes C := alpha*op(A)*op(B) + beta*C,
enum CBLAS_TRANSPOSE transa = CblasConjTrans;
enum CBLAS_TRANSPOSE transb = CblasNoTrans;
int rows_opA = N; // number of rows in op(A) and in C
int col_opB = N; //number of columns of op(B) and in C
int col_opA = N; //number of columns in op(A) and rows in op(B)
int col_B; //number of columns in B
float complex alpha = 1.0+I*0;
int lda = rows_opA;
float complex beta = 0.0+I*0;
int ldc = rows_opA;
int i;
float complex* B;
int ldb = col_opB;
if (transb == CblasNoTrans) {
B = (float complex*)calloc(ldb*col_opB,sizeof(float complex));
col_B= col_opB;
}
else {
B = (float complex*)calloc(ldb*col_opA, sizeof(float complex));
col_B = col_opA;
}
float complex* C = (float complex*)malloc(ldc*col_opB*sizeof(float complex));
for (i=0; i<lda*col_B; i+=N+1)
B[i]=1.0+I*0;
cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, A, lda, B, ldb, &beta, C, ldc);
memcpy(Result, C, N*N*sizeof(float complex));
free(B);
free(C);
}
void H_hermH_plus_sigma2I (int N, int M, float complex *A, float sigma2, float complex *Result)
{
//C := alpha*op(A)*op(B) + beta*C,
enum CBLAS_TRANSPOSE transa = CblasConjTrans;
enum CBLAS_TRANSPOSE transb = CblasNoTrans;
int rows_opA = N; // number of rows in op(A) and in C
int col_opB = N; //number of columns of op(B) and in C
int col_opA = N; //number of columns in op(A) and rows in op(B)
int col_C = N; //number of columns in B
float complex alpha = 1.0+I*0;
int lda = col_opA;
float complex beta = 1.0 + I*0;
int ldc = col_opA;
int i;
float complex* C = (float complex*)calloc(ldc*col_opB, sizeof(float complex));
for (i=0; i<lda*col_C; i+=N+1)
C[i]=sigma2*(1.0+I*0);
cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, A, lda, A, lda, &beta, C, ldc);
memcpy(Result, C, N*M*sizeof(float complex));
free(C);
}
void HH_herm_plus_sigma2I (int M, int N, float complex *A, float sigma2, float complex *Result)
{
//C := alpha*op(A)*op(B) + beta*C,
enum CBLAS_TRANSPOSE transa = CblasNoTrans;
enum CBLAS_TRANSPOSE transb = CblasConjTrans;
int k = N; //number of columns in op(A) and rows in op(B),k
float complex alpha = 1.0+I*0;
int lda = N;
int ldb = N;
int ldc = M;
int i;
float complex* C = (float complex*)calloc(M*M, sizeof(float complex));
for (i=0; i<M*M; i+=M+1)
C[i]=1.0+I*0;
cblas_cgemm(CblasRowMajor, transa, transb, M, M, k, &alpha, A, lda, A, ldb, &sigma2, C, ldc);
memcpy(Result, C, M*M*sizeof(float complex));
free(C);
}
void eigen_vectors_values (int N, float complex *A, float complex *Vectors, float *Values_Matrix)
{
// This function computes ORTHONORMAL eigenvectors and eigenvalues of matrix A,
// where Values_Matrix is a diagonal matrix of eigenvalues.
// A=Vectors*Values_Matrix*Vectors'
char jobz = 'V';
char uplo = 'U';
int order_A = N;
int lda = N;
int i;
float* Values = (float*)malloc(sizeof(float)*1*N);
LAPACKE_cheev(LAPACK_ROW_MAJOR, jobz, uplo, order_A, A, lda, Values);
memcpy(Vectors, A, N*N*sizeof(float complex));
for (i=0; i<lda; i+=1)
Values_Matrix[i*(lda+1)]=Values[i];
free(Values);
}
void lin_eq_solver (int N, float complex* A, float complex* B, float complex* Result)
{
int n = N;
int lda = N;
int ldb = N;
int nrhs = N;
char transa = 'N';
int* IPIV = malloc(N*N*sizeof(int));
// Compute LU-factorization
LAPACKE_cgetrf(LAPACK_ROW_MAJOR, n, nrhs, A, lda, IPIV);
// Solve AX=B
LAPACKE_cgetrs(LAPACK_ROW_MAJOR, transa, n, nrhs, A, lda, IPIV, B, ldb);
// cgetrs( "N", N, 4, A, lda, IPIV, B, ldb, INFO )
memcpy(Result, B, N*N*sizeof(float complex));
free(IPIV);
}
void mutl_matrix_matrix_row_based(float complex* M0, float complex* M1, int rows_M0, int col_M0, int rows_M1, int col_M1, float complex* Result ){
enum CBLAS_TRANSPOSE transa = CblasNoTrans;
enum CBLAS_TRANSPOSE transb = CblasNoTrans;
int rows_opA = rows_M0; // number of rows in op(A) and in C
int col_opB = col_M1; //number of columns of op(B) and in C
int col_opA = col_M0; //number of columns in op(A) and rows in op(B)
float complex alpha =1.0;
int lda = col_M0;
float complex beta = 0.0;
int ldc = col_M1;
int ldb = col_M1;
#ifdef DEBUG_PREPROC
int i=0;
printf("rows_M0 %d, col_M0 %d, rows_M1 %d, col_M1 %d\n", rows_M0, col_M0, rows_M1, col_M1);
for(i=0; i<rows_M0*col_M0; ++i)
printf(" rows_opA = %d, col_opB = %d, W_MMSE[%d] = (%f + i%f)\n", rows_opA, col_opB, i , creal(M0[i]), cimag(M0[i]));
for(i=0; i<rows_M1*col_M1; ++i)
printf(" M1[%d] = (%f + i%f)\n", i , creal(M1[i]), cimag(M1[i]));
#endif
cblas_cgemm(CblasRowMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, M0, lda, M1, ldb, &beta, Result, ldc);
#ifdef DEBUG_PREPROC
for(i=0; i<rows_opA*col_opB; ++i)
printf(" result[%d] = (%f + i%f)\n", i , creal(Result[i]), cimag(Result[i]));
#endif
}
void mutl_matrix_matrix_col_based(float complex* M0, float complex* M1, int rows_M0, int col_M0, int rows_M1, int col_M1, float complex* Result ){
enum CBLAS_TRANSPOSE transa = CblasNoTrans;
enum CBLAS_TRANSPOSE transb = CblasNoTrans;
int rows_opA = rows_M0; // number of rows in op(A) and in C
int col_opB = col_M1; //number of columns of op(B) and in C
int col_opA = col_M0; //number of columns in op(A) and rows in op(B)
float complex alpha =1.0;
int lda = col_M0;
float complex beta = 0.0;
int ldc = rows_M1;
int ldb = rows_M1;
#ifdef DEBUG_PREPROC
int i = 0;
printf("rows_M0 %d, col_M0 %d, rows_M1 %d, col_M1 %d\n", rows_M0, col_M0, rows_M1, col_M1);
for(i=0; i<rows_M0*col_M0; ++i)
printf(" rows_opA = %d, col_opB = %d, W_MMSE[%d] = (%f + i%f)\n", rows_opA, col_opB, i , creal(M0[i]), cimag(M0[i]));
for(i=0; i<rows_M1*col_M1; ++i)
printf(" M1[%d] = (%f + i%f)\n", i , creal(M1[i]), cimag(M1[i]));
#endif
cblas_cgemm(CblasColMajor, transa, transb, rows_opA, col_opB, col_opA, &alpha, M0, lda, M1, ldb, &beta, Result, ldc);
#ifdef DEBUG_PREPROC
for(i=0; i<rows_opA*col_opB; ++i)
printf(" result[%d] = (%f + i%f)\n", i , creal(Result[i]), cimag(Result[i]));
#endif
}
/*FILTERS */
void compute_MMSE(float complex* H, int order_H, float sigma2, float complex* W_MMSE)
{
int N = order_H;
float complex* H_hermH_sigmaI = malloc(N*N*sizeof(float complex));
float complex* H_herm = malloc(N*N*sizeof(float complex));
H_hermH_plus_sigma2I(N, N, H, sigma2, H_hermH_sigmaI);
#ifdef DEBUG_PREPROC
int i =0;
for(i=0;i<N*N;i++)
printf(" H_hermH_sigmaI[%d] = (%f + i%f)\n", i , creal(H_hermH_sigmaI[i]), cimag(H_hermH_sigmaI[i]));
#endif
conjugate_transpose (N, H, H_herm); //equals H_herm
#ifdef DEBUG_PREPROC
for(i=0;i<N*N;i++)
printf(" H_herm[%d] = (%f + i%f)\n", i , creal(H_herm[i]), cimag(H_herm[i]));
#endif
lin_eq_solver(N, H_hermH_sigmaI, H_herm, W_MMSE);
#ifdef DEBUG_PREPROC
for(i=0;i<N*N;i++)
printf(" W_MMSE[%d] = (%f + i%f)\n", i , creal(W_MMSE[i]), cimag(W_MMSE[i]));
#endif
free(H_hermH_sigmaI);
free(H_herm);
}
#if 0
void compute_white_filter(float complex* H_re,
int order_H,
float sigma2,
float complex* W_Wh_0_re,
float complex* W_Wh_1_re){
int aatx, aarx, re;
int i,j;
int M =n_rx;
int N = n_tx;
int sigma2=noise_power;
float complex *H0_re = malloc(n_rx*(n_tx>>2)*sizeof(float complex));
float complex *H1_re = malloc(n_rx*(n_tx>>2)*sizeof(float complex));
float complex *R_corr_col_n_0_re = malloc(n_rx*n_tx*sizeof(float complex));
float complex *R_corr_col_n_1_re = malloc(n_rx*n_tx*sizeof(float complex));
float complex *U_0_re = malloc(n_rx*n_tx*sizeof(float complex));
float complex *U_1_re = malloc(n_rx*n_tx*sizeof(float complex));
float complex *U_0_herm_re = malloc(n_rx*n_tx*sizeof(float complex));
float complex *U_1_herm_re = malloc(n_rx*n_tx*sizeof(float complex));
float complex *D_0_re = malloc(n_rx*n_tx*sizeof(float complex));
float complex *D_1_re = malloc(n_rx*n_tx*sizeof(float complex));
float complex *W_Wh_0_re = malloc(n_rx*n_tx*sizeof(float complex));
float complex *W_Wh_1_re = malloc(n_rx*n_tx*sizeof(float complex));
for (aatx=0; aatx<n_tx/2; aatx++){
for (aarx=0; aarx<n_rx; aarx++) {
H0_re[aatx*n_rx + aarx] = H_re[aatx*n_rx + aarx][re]; // H0 gets [0 1 2 3; 4,5,6,7].' coefficients of H
H1_re[aatx*n_rx + aarx] = H_re[aatx*n_rx + aarx + 8][re]; // H1 gets [8 9 10 11; 12, 13, 14, 15].' coefficients of H
if (re == 0)
printf("ant %d, H_re = (%f + i%f) \n", aatx*n_rx + aarx, creal(H[aatx*n_rx + aarx][re]), cimag(H[aatx*n_rx + aarx][re]));
}
}
//HH_herm_plus_sigma2I(n_rx, (n_tx>>2), H1_re, sigma2, R_corr_col_n_0_re);
HH_herm_plus_sigma2I(n_rx, (n_tx>>2), H0_re, sigma2, R_corr_col_n_1_re);
eigen_vectors_values(n_rx, R_corr_col_n_0_re, U_0_re, D_0_re);
eigen_vectors_values(n_rx, R_corr_col_n_1_re, U_1_re, D_1_re);
transpose (n_rx, U_0_re, U_0_herm_re);
transpose (n_rx, U_1_re, U_1_herm_re);
sigma = (float)(sqrt((double)(sigma2)));
/*The inverse of a diagonal matrix is obtained by replacing each element in the diagonal with its reciprocal.
A square root of a diagonal matrix is given by the diagonal matrix, whose diagonal entries are just the square
roots of the original matrix.*/
D_0_re_inv_sqrt[0] = sqrt_float(1/D_0_re_inv[0]);
D_0_re_inv_sqrt[5] = sqrt_float(1/D_0_re_inv[5]);
D_0_re_inv_sqrt[10] = sqrt_float(1/D_0_re_inv[10]);
D_0_re_inv_sqrt[15] = sqrt_float(1/D_0_re_inv[15]);
D_1_re_inv[0] = sqrt_float(1/D_1_re_inv[0]);
D_1_re_inv[5] = sqrt_float(1/D_1_re_inv[5]);
D_1_re_inv[10] = sqrt_float(1/D_1_re_inv[10]);
D_1_re_inv[15] = sqrt_float(1/D_1_re_inv[15]);
now only to multiply
free(H0);
free(H1);
free(R_corr_col_n_0);
free(R_corr_col_n_1);
}
#endif
float sqrt_float(float x, float sqrt_x)
{
sqrt_x = (float)(sqrt((double)(x)));
return sqrt_x;
}
| {
"alphanum_fraction": 0.6617140938,
"avg_line_length": 31.768,
"ext": "c",
"hexsha": "7d063e326effc919180e5ebe12c02fa19d85b6a2",
"lang": "C",
"max_forks_count": 15,
"max_forks_repo_forks_event_max_datetime": "2022-03-28T02:13:45.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-12-27T00:55:51.000Z",
"max_forks_repo_head_hexsha": "16cbf4828bd11e4c7319e7a009a26b6f39fde628",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "shadansari/onos-cu-cp",
"max_forks_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "16cbf4828bd11e4c7319e7a009a26b6f39fde628",
"max_issues_repo_issues_event_max_datetime": "2021-11-24T14:23:54.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-06-17T05:01:55.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "shadansari/onos-cu-cp",
"max_issues_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c",
"max_line_length": 146,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "16cbf4828bd11e4c7319e7a009a26b6f39fde628",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "shadansari/onos-cu-cp",
"max_stars_repo_path": "openair1/PHY/LTE_UE_TRANSPORT/linear_preprocessing_rec.c",
"max_stars_repo_stars_event_max_datetime": "2021-01-24T07:04:29.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-11T17:03:35.000Z",
"num_tokens": 4176,
"size": 11913
} |
/*
* Copyright (c) 2011-2013 University of Texas at Austin. All rights reserved.
*
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* This file is part of PerfExpert.
*
* PerfExpert is free software: you can redistribute it and/or modify it under
* the terms of the The University of Texas at Austin Research License
*
* PerfExpert 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.
*
* Authors: Leonardo Fialho and Ashay Rane
*
* $HEADER$
*/
#ifndef ANALYSIS_DEFS_H_
#define ANALYSIS_DEFS_H_
#include <vector>
#include <gsl/gsl_histogram.h>
#include "tools/macpo/common/avl_tree.h"
#include "tools/macpo/common/generic_defs.h"
#include "tools/macpo/common/macpo_record.h"
#include "tools/macpo/common/macpo_record_cxx.h"
typedef gsl_histogram histogram_t;
typedef std::vector<mem_info_list_t> mem_info_bucket_t;
typedef std::vector<trace_info_list_t> trace_info_bucket_t;
typedef std::vector<vector_stride_info_list_t> vector_stride_info_bucket_t;
typedef std::vector<histogram_t*> histogram_list_t;
typedef std::vector<histogram_list_t> histogram_matrix_t;
typedef std::vector<avl_tree*> avl_tree_list_t;
typedef std::pair<size_t, size_t> pair_t;
typedef std::vector<pair_t> pair_list_t;
typedef std::vector<double> double_list_t;
typedef std::vector<int> int_list_t;
typedef struct {
size_t size, line_size, associativity, count;
} cache_data_t;
typedef struct {
cache_data_t l1_data, l2_data, l3_data;
name_list_t stream_list;
mem_info_bucket_t mem_info_bucket;
trace_info_bucket_t trace_info_bucket;
vector_stride_info_bucket_t vector_stride_info_bucket;
} global_data_t;
typedef struct {
size_t count, l1_conflicts, l2_conflicts;
} stream_list_t;
/* Different kinds of analyses options. */
#define ANALYSIS_REUSE_DISTANCE (1 << 0)
#define ANALYSIS_CACHE_CONFLICTS (1 << 1)
#define ANALYSIS_PREFETCH_STREAMS (1 << 2)
#define ANALYSIS_STRIDES (1 << 3)
#define ANALYSIS_VECTOR_STRIDES (1 << 4)
#define ANALYSIS_ALL (~0)
/* Number of reuse distance entries to display for each stream. */
#define REUSE_DISTANCE_COUNT 3
#define ADDR_TO_CACHE_LINE(x) (x >> 6)
#endif /* ANALYSIS_DEFS_H_ */
| {
"alphanum_fraction": 0.7569772435,
"avg_line_length": 28.7530864198,
"ext": "h",
"hexsha": "989ba4a7447da620313ecb753ca3f01e474bc8d8",
"lang": "C",
"max_forks_count": 11,
"max_forks_repo_forks_event_max_datetime": "2020-08-18T03:53:19.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-01-23T15:41:40.000Z",
"max_forks_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30",
"max_forks_repo_licenses": [
"BSD-4-Clause-UC"
],
"max_forks_repo_name": "roystgnr/perfexpert",
"max_forks_repo_path": "tools/macpo/analyze/include/analysis_defs.h",
"max_issues_count": 15,
"max_issues_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30",
"max_issues_repo_issues_event_max_datetime": "2018-04-18T16:08:41.000Z",
"max_issues_repo_issues_event_min_datetime": "2015-10-07T20:52:05.000Z",
"max_issues_repo_licenses": [
"BSD-4-Clause-UC"
],
"max_issues_repo_name": "roystgnr/perfexpert",
"max_issues_repo_path": "tools/macpo/analyze/include/analysis_defs.h",
"max_line_length": 80,
"max_stars_count": 28,
"max_stars_repo_head_hexsha": "a03b13db9ac83e992e1c5cc3b6e45e52c266fe30",
"max_stars_repo_licenses": [
"BSD-4-Clause-UC"
],
"max_stars_repo_name": "roystgnr/perfexpert",
"max_stars_repo_path": "tools/macpo/analyze/include/analysis_defs.h",
"max_stars_repo_stars_event_max_datetime": "2021-09-27T16:23:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-05-05T15:54:25.000Z",
"num_tokens": 576,
"size": 2329
} |
#include <linux/types.h>
#include "sweeny_uf.h"
#include "extract_args.h"
#include "timeseries.h"
#include <stdio.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_rng.h> //Verwendung von Mersenne-Twister Pseudozufallszahlengenerator
#define TS_FILE_D "../time_series/uf/simulation_l%u_q%.4f_b%.4f_c%.4f_s%u.hdf5"
#define BUF_LEN 512
char fn[BUF_LEN];
char impl_title[] = "Union-Find implementation";
char verbose=0;
__u64 *four_cs_moment ;
__u64 *sec_cs_moment ;
__u32 *size_giant;
__u32 *num_bonds;
__u32 *num_cluster;
__u32 DX;
__u32 N;
__u32 seed=123456;
double q=2;
double coupling;
double beta;
double v;
double K;
__u32 steps;
__u32 cutoff;
int main(int argc, char *argv[])
{
if(!extractArgs(argc, argv,impl_title))
return EXIT_FAILURE;
snprintf(fn,BUF_LEN,TS_FILE_D,DX,q,beta,coupling,seed);
if(!init_observables())
return EXIT_FAILURE;
if(!init_sweeny_uf( q,DX,beta,coupling,cutoff,steps,seed,num_bonds,num_cluster,size_giant,sec_cs_moment,four_cs_moment))
return EXIT_FAILURE;
if(!simulate_sweeny_uf())
return EXIT_FAILURE;
destroy_sweeny_uf();
save_timeseries();
destroy_observables();
return EXIT_SUCCESS;
}
/******************************************************************************
*****************************************************************************/
| {
"alphanum_fraction": 0.6254442075,
"avg_line_length": 28.14,
"ext": "c",
"hexsha": "d840baa8419cf3a7b9cddc68283094b468c3b576",
"lang": "C",
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2017-04-10T14:18:57.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-04-10T14:18:57.000Z",
"max_forks_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ermeel86/sweeny",
"max_forks_repo_path": "src/sy_uf_mc.c",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_issues_repo_issues_event_max_datetime": "2018-08-20T09:32:03.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-08-19T09:29:25.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "ernmeel/sweeny",
"max_issues_repo_path": "src/sy_uf_mc.c",
"max_line_length": 125,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ae6dc73d9a6c793c797453f4d05724b1210bb1be",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ernmeel/sweeny",
"max_stars_repo_path": "src/sy_uf_mc.c",
"max_stars_repo_stars_event_max_datetime": "2017-04-10T14:18:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-03-03T10:57:43.000Z",
"num_tokens": 371,
"size": 1407
} |
/* roots/utility.c
*
* Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Reid Priedhorsky, 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.
*/
/* utility.c -- various root finding utility routines */
/* config headers */
#include <config.h>
/* standard headers */
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
/* gsl headers */
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
/* roots headers */
#include "roots.h"
/* Validate arguments common to gsl_root_bisection and gsl_root_falsepos.
Return GSL_SUCCESS if all arguments are okay, complain appropriately (i.e.
call GSL_ERROR and return GSL_FAILURE) otherwise. */
int
_gsl_root_validate_bfp_args (double *root, double (*f) (double),
double *lower_bound,
double *upper_bound, double epsrel,
double epsabs, unsigned int max_iterations,
double max_deltay)
{
/* Is the maximum delta-y too small? */
if (max_deltay < GSL_ROOT_MIN_MAX_DELTAY)
GSL_ERROR ("maximum delta-y negative, zero, or too small", GSL_EBADTOL);
/* Did the user give a lower bound that not less than the upper bound? */
if (*lower_bound >= *upper_bound)
GSL_ERROR ("lower bound larger than upper_bound", GSL_EINVAL);
/* The rest of the arguments are common. */
return _gsl_root_validate_args (root, f, lower_bound, upper_bound,
epsrel, epsabs, max_iterations);
}
/* Validate arguments commond to gsl_root_secant and gsl_root_newtons. Return
GSL_SUCCESS if all arguments are okay, complain appropriately (i.e. call
GSL_ERROR and return GSL_FAILURE) otherwise. */
int
_gsl_root_validate_sn_args (double *root, double (*f) (double),
double *guess1,
double *guess2, double epsrel,
double epsabs, unsigned int max_iterations,
double max_step_size)
{
/* Is the maximum step size ridiculous? */
if (max_step_size <= 0.0)
GSL_ERROR ("maximum step size <= 0", GSL_EBADTOL);
/* The rest of the arguments are common. */
return _gsl_root_validate_args (root, f, guess1, guess2, epsrel,
epsabs, max_iterations);
}
/* Validate the arguments common to all four low level functions. Return
GSL_SUCCESS if all of the following arguments hold true, call GSL_ERROR and
return GSL_FAILURE otherwise.
* No pointer arguments are null.
* The maximum number of iterations is non-zero.
* Relative and absolute error are non-negative.
* The relative error is not too small. */
int
_gsl_root_validate_args (double *root, double (*f) (double), double *where1,
double *where2, double epsrel,
double epsabs, unsigned int max_iterations)
{
/* Are any pointers null? */
if ((root == NULL) || (f == NULL) || (where1 == NULL)
|| (where2 == NULL))
GSL_ERROR ("pointer argument null", GSL_EINVAL);
/* Did the user tell us to do no iterations? */
if (max_iterations == 0)
GSL_ERROR ("maximum iterations 0", GSL_EINVAL);
/* Did the user try to pawn a negative tolerance off on us? */
if (epsrel < 0.0 || epsabs < 0.0)
GSL_ERROR ("relative or absolute tolerance negative", GSL_EBADTOL);
/* Is the relative error too small? */
if (epsrel < GSL_DBL_EPSILON * GSL_ROOT_EPSILON_BUFFER)
GSL_ERROR ("relative tolerance too small", GSL_EBADTOL);
/* All is well. */
return GSL_SUCCESS;
}
/* Verify that the supplied interval is guaranteed by the Intermediate Value
Theorem to contain a root and complain appropriately if it is not. (It
might actually be a discontinuity, but we check for that elsewhere.) Return
GSL_SUCCESS if all is well, otherwise, call GSL_ERROR and return
GSL_FAILURE. */
int
_gsl_root_ivt_guar (double (*f) (double), double lower_bound,
double upper_bound)
{
double fl, fu;
_BARF_FPCALL (f, lower_bound, fl);
_BARF_FPCALL (f, upper_bound, fu);
if (fl * fu > 0.0)
{
GSL_ERROR ("interval not guaranteed to contain a root", GSL_EINVAL);
}
else
{
return GSL_SUCCESS;
}
}
/* Check if the user has the root but doesn't know it. If lower_bound or
upper_bound is a root of f, or the interval [upper_bound, lower_bound] is
within tolerance, return 1 and set *root appropriately. Otherwise, return
0. On error, call GSL_ERROR and return GSL_FAILURE. Only worry about
max_deltay if it is greater than 0 (which implies that you should validate
arguments _before_ calling this function). */
int
_gsl_root_silly_user (double *root, double (*f) (double), double lower_bound,
double upper_bound, double epsrel,
double epsabs, double max_deltay)
{
double fl, fu;
/* Is lower_bound the root? */
_BARF_FPCALL (f, lower_bound, fl);
if (fl == 0.0)
{
*root = lower_bound;
return 1;
}
/* Is upper_bound the root? */
_BARF_FPCALL (f, upper_bound, fu);
if (fu == 0.0)
{
*root = upper_bound;
return 1;
}
/* Are lower_bound and upper_bound within tolerance? */
_BARF_TOLS (lower_bound, upper_bound, 2 * epsrel, 2 * epsabs);
if (max_deltay > 0.0)
_BARF_DELTAY (fl, fu, max_deltay);
if (_WITHIN_TOL (lower_bound, upper_bound, 2 * epsrel,
2 * epsabs))
{
*root = (lower_bound + upper_bound) / 2.0;
return 1;
}
/* No? Bummer. */
return 0;
}
| {
"alphanum_fraction": 0.659421448,
"avg_line_length": 34.7611111111,
"ext": "c",
"hexsha": "57442a3e3d7d91cda9b174b57b72cb71e9ecf085",
"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/roots/utility.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/roots/utility.c",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim",
"max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/roots/utility.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": 1583,
"size": 6257
} |
/**
* \author Sylvain Marsat, University of Maryland - NASA GSFC
*
* \brief C header for functions windowing and computing FFT/IFFT of time/frequency series.
*
*/
#ifndef __GENERATELLVFD_H__
#define __GENERATELLVFD_H__ 1
#ifdef __GNUC__
#define UNUSED __attribute__ ((unused))
#else
#define UNUSED
#endif
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <complex.h>
#include <time.h>
#include <unistd.h>
#include <getopt.h>
#include <stdbool.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_blas.h>
#include <gsl/gsl_min.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_complex.h>
#include "constants.h"
#include "struct.h"
#include "waveform.h"
#include "fft.h"
#include "LLVgeometry.h"
#include "LLVFDresponse.h"
/********************************** Structures ******************************************/
typedef enum GenLLVFDtag {
LLVFD,
LLVhlm
} GenLLVFDtag;
/* Parameters for the generation of a LLV waveform (in the form of a list of modes) */
typedef struct tagGenLLVFDparams {
double tRef; /* reference time (s) - GPS time at the frequency representing coalescence */
double phiRef; /* reference phase (rad) - phase at the frequency representing coalescence (or at fRef if specified) */
double fRef; /* reference frequency at which phiRef is set (Hz, default 0 which is interpreted as Mf=0.14) */
double m1; /* mass of companion 1 (solar masses, default 2e6) */
double m2; /* mass of companion 2 (solar masses, default 1e6) */
double distance; /* distance of source (Mpc, default 1e3) */
double inclination; /* inclination of source (rad, default pi/3) */
double ra; /* first angle for the position in the sky (rad, default 0) */
double dec; /* second angle for the position in the sky (rad, default 0) */
double polarization; /* polarization angle (rad, default 0) */
int nbmode; /* number of modes to generate (starting with 22) - defaults to 5 (all modes) */
double minf; /* Minimal frequency, ignore if 0 (Hz, default=0) - will use first frequency covered by the ROM if higher */
double maxf; /* Maximal frequency, ignore if 0 (Hz, default=0) - will use last frequency covered by the ROM if lower */
double deltaf; /* When generating frequency series from the mode contributions, deltaf for the output (0 to set automatically at 1/2*1/(2T)) */
int tagnetwork; /* Tag selecting the desired output format */
int taggenwave; /* Tag selecting the desired output format */
int fromLLVtdfile; /* Tag for loading time series for LLV detectors and FFTing */
int nsamplesinfile; /* Number of lines of input file */
int binaryin; /* Tag for loading the data in gsl binary form instead of text (default false) */
int binaryout; /* Tag for outputting the data in gsl binary form instead of text (default false) */
char indir[256]; /* Path for the input directory */
char infile[256]; /* Path for the input file */
char outdir[256]; /* Path for the output directory */
char outfileprefix[256]; /* Path for the output file */
} GenLLVFDparams;
#if 0
{ /* so that editors will match succeeding brace */
#elif defined(__cplusplus)
}
#endif
#endif /* _GENERATELLVFD_H */
| {
"alphanum_fraction": 0.6461846242,
"avg_line_length": 40.2183908046,
"ext": "h",
"hexsha": "b2929c76d6810ab8903fcdf9dedc4c994acdf042",
"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": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "titodalcanton/flare",
"max_forks_repo_path": "LLVsim/GenerateLLVFD.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "titodalcanton/flare",
"max_issues_repo_path": "LLVsim/GenerateLLVFD.h",
"max_line_length": 157,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "4ffb02977d19786ab8c1a767cc495a799d9575ae",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "titodalcanton/flare",
"max_stars_repo_path": "LLVsim/GenerateLLVFD.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 869,
"size": 3499
} |
#ifndef BN
#define BN
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdbool.h>
#include <getopt.h>
#include <assert.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_multimin.h>
#include <gsl/gsl_matrix.h>
#include <omp.h>
#include <math.h>
#include "matrix.h"
#include "model.h"
#include "data.h"
#include "vector.h"
#include "a-queue.h"
bool verbose = false;
bool debug = false;
int** GENOTYPE; // GENOTYPE[i] stores the binary expansion of i.
int NUM_SAMPLES_READ; // total number of samples read in from dataset.
// set initial parameter values (seeimingly arbitrary, but makes it easier to tweak them since they're all here)
void initialize_MH_params(unsigned int* seed, int* number_samples, int* record_ith, int* burn_in, char* reg_scheme) {
*seed = time(NULL); // random seed using time
*number_samples = 100000;
*record_ith = 1;
*burn_in = 0;
strcpy(reg_scheme, "bic");
}
/*
* Check file inputs to bn. If no .poset file supplied (f flag), prints error message and exits.
* Flags:
*
*
*
*/
void check_file_inputs(int argc, char** argv, char* filestem, char* output, int* number_samples, unsigned int* seed, char* reg_scheme) {
int c = 0;
bool input_flag = false;
bool output_flag = false;
bool help_flag = false;
static struct option long_options[] =
{
{"dataset", required_argument, 0, 'd'},
{"output", required_argument, 0, 'o'},
{"number_samples", required_argument, 0, 'n'},
{"seed", required_argument, 0, 's'},
{"reg", required_argument, 0, 'r'},
{"help", no_argument, 0, 'h'},
{NULL, 0, NULL,0,}
};
while ((c = getopt_long(argc, argv, "d:o:n:s:r:hvt:e:", long_options, NULL)) != -1 ) {
switch(c) {
case 'd': // get input filename, satisfy boolean check for provided input.
strcpy(filestem, optarg);
input_flag = true;
break;
case 'o':
strcpy(output, optarg);
output_flag = true;
break;
case 'n':
*number_samples = atoi(optarg);
break;
case 's':
*seed = atoi(optarg);
break;
case 'r':
strcpy(reg_scheme, optarg);
break;
case 'h':
help_flag = true;
break;
case 'v':
verbose = true;
break;
}
}
if (help_flag) {
printf("Usage: ./cbn (-(option) (argument) )*\n");
printf("where dataset input option (-d or --dataset) is required.\n");
printf("Options include:\n");
printf("-d | --dataset \tPath to input file with sample data. Please include file extension as well. ex: test1.txt\n");
printf("-o | --output \tPath to output file to write results to. If not specified, then results not written to file.\n");
printf("-n | --number_samples \tSet the number of iterations for Metropolis-Hastings to be run. Default value set to 500,000.\n");
printf("-s | --seed \tSet the seed for random number generators in the program. Time used as default seed.\n");
printf("-r | --reg \tSet the likelihood regularization scheme for the MCMC algorithm. Valid choices are bic, aic, and loglik.\n");
printf("-h | --help \tPrint help information for program.\n");
exit(1);
}
if (!input_flag) {
fprintf(stderr, "Error: No input file specified. Please provide the filename (without filetype) of a file containing formatted sample data using the \"-d\" or \"--dataset\" options.\n");
exit(1);
}
if (!output_flag) {
strcpy(output, "");
}
if (strcmp(reg_scheme, "bic") && strcmp(reg_scheme, "aic") && strcmp(reg_scheme, "loglik")) {
fprintf(stderr, "Error: Invalid regularization scheme. Please choose from bic (default), aic, or loglik.\n");
exit(1);
}
}
/*
* Standard open_file helper. Throws error if error while opening file.
*/
FILE* open_file(char* filename, char* option) {
FILE* input = fopen(filename, option);
if (input == NULL) {
fprintf(stderr, "Error: Could not read %s\n", filename);
exit(1);
}
return input;
}
/*
* Base 2 power function. Computes 2^n, for n >= 0
*/
static inline int pow2(int n) {
assert(n >= 0);
return 1 << n;
}
// Basic power function implementation. Only accepts integral power values.
double power(double base, int power) {
double result = 1.0;
for (int i = 0; i < power; i++) {
result *= base;
}
return result;
}
/*
* Generates a binary compression of pattern data, which is
* used as a means of quickly determining whether two samples have
* the same pattern. Presumably, this is faster (as opposed to
* comparisons without such a compression scheme), since we compress
* all samples once, and then compare the "hash" values.
* Parallels index_of in TS code.
*/
int binary_compression(int* pat_i, int num_events) {
int index = 0;
for (int i = 0; i < num_events; i++) {
if (pat_i[i] ==1)
index += pow2(num_events - 1 - i);
}
return index;
}
// Used to generate binary expansions of genotypes, for easier access later on.
void precompute_binary(const int n) {
int m = pow2(n);
GENOTYPE = get_int_matrix(m, n);
for (int i = 0; i < m; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if ( ((1 << j) & i) > 0) {
GENOTYPE[i][n - 1 - j] = 1;
count++;
} else {
GENOTYPE[i][n - 1 - j] = 0;
}
}
}
}
int count_edges(int** poset, int n) {
int count = 0;
for (int i=0; i< n; i++) {
for (int j = 0; j< n; j++) {
if (poset[i][j])
count++;
}
}
return count;
}
// TODO: reconsider the use of int* ptr vector here. We've changed the idea, and we're no longer looking
// at the probability of combined events. Instead, using the current poset to determine how children
// are valid or not in find_children_extended.
/*
* Helper function for process_patterns function. Reads pattern data
* from .txt file. Only 0/1 expected, but places negative values where
* any deviations occur. Exits if any error is encountered.
*/
int** read_patterns(FILE *input, model* M, char* filename, int* num_samples, int* num_events) {
size_t temp = 0;
int n;
char* line = NULL;
int len = getline(&line, &temp, input);
if (len != -1) {
n = len / 2;
free(line);
line = NULL;
rewind(input);
} else {
fprintf(stderr, "Error reading sample data.\n");
exit(1);
}
M->n = n;
*num_events = n;
ptr_vector* v = new_ptr_vector(); // vector takes ints, hopefully won't get mutilated?
while (getline(&line, &temp, input) != -1) {
int line_index = 0;
int* genotype = get_int_array(n);
for (int i = 0; i< n; i++) { // fill in each event with genotype.
if (line[line_index] == '0') genotype[i] = 0;
if (line[line_index] == '1') genotype[i] = 1;
line_index += 2;
}
push_back_ptr(v, genotype);
free(line);
line = NULL;
temp = 0;
}
free(line);
*num_samples = v->size;
if (debug) {
printf("Finished reading patterns.\nPatterns matrix: \n");
print_int_matrix(v->elems, v->size, n);
}
return free_ptr_vector(v, false);
}
// counts uniq patterns among samples.
// It seems that pat_idx counts the number of unique samples
// up to that last unique sample.
// ----- variables -----
// index stores the "hashed" patterns
// count stores the number of samples with the same pattern
// Removed pat_idx necessity, since the same information is stored in index.
// Note: The binary compression places a limit on the number of loci that can be observed (32 for int, 64 for long int).
// For a completely scalable implementation, should re-work this scheme, use a hashset for speed.
void count_uniq_patterns(int* index, int* count, int num_samples, int num_events, int* N_u, int** pat) {
//binary compression that "hashes" genotypes
for (int i = 0; i< num_samples; i++)
index[i] = binary_compression(pat[i], num_events);
// count unique patterns. Runs in worst case O(n^2) time. can be optimized to O(nlgn) using sort -> iterate, or linear time using a hashtable/set.
bool skips; // true if another sample has same pattern ("index" value)
int num_unique = 0; // counts number of unique patterns
for (int i = 0; i < num_samples; i++) {
skips = false;
for (int j = 0; j < i; j++) {
if (index[i] == index[j]) { //samples have the same pattern
count[j]++; //increment the count at first index
skips = true;
break;
}
}
if (!skips) { // unique pattern --> NOT previously observed
count[i]++;
num_unique++;
}
}
*N_u = num_unique;
if (verbose) {
printf("Number of samples processed = %d\n", num_samples);
printf("Number of gene loci considered = %d\n", num_events);
printf("Number of unique genotypes observed = %d\n", num_unique);
}
if (debug) {
printf("num_samples = %d\n", num_samples);
printf("count array: \n");
print_int_array(count, num_samples);
printf("index array: \n");
print_int_array(index, num_samples);
}
}
data* construct_data_set(int num_unique, int* count, int* index, int num_samples, int num_events, int** pat) {
data* D = calloc(num_unique, sizeof(data));
if (D == NULL) {
fprintf(stderr, "Error: calloc failure - out of memory.\n");
exit(1);
}
int d_index = 0;
for (int i = 0; i < num_samples; i++) {
if (count[i] > 0) {//if was not a repeat
D[d_index].count = count[i];
D[d_index].g = get_int_array(num_events);
for (int j = 0; j < num_events; j++)
D[d_index].g[j] = pat[i][j];
d_index++;
}
}
if (debug) {
print_data_array(D, num_unique, num_events);
}
return D;
}
// N_u = number of unique genotypes in dataset
// n = number of events
int process_patterns(char* filename, model* M, int* N_u, data** D) {
FILE* input = open_file(filename, "r");
int num_samples, num_events;
int** pat = read_patterns(input, M, filename, &num_samples, &num_events);
fclose(input);
//Count unique patterns, construct data set.
int* index = get_int_array(num_samples);
int* count = get_int_array(num_samples);
count_uniq_patterns(index, count, num_samples, num_events, N_u, pat);
*D = construct_data_set(*N_u, count, index, num_samples, num_events, pat);
NUM_SAMPLES_READ = num_samples;
free_int_matrix(pat, num_samples);
free_int_array(index);
free_int_array(count);
return 0;
}
// Suppes condition
// Confirm that the proposed modification (move) is supported by event probabilities in the data set, taking into account
// current theta types.
bool cumulative_probs_maintained(model* M, data* D, int* theta_types, int num_unique) {
int n = M->n;
for (int i = 0; i< n; i++) { // loop through each event
int num_parents = M->num_pa[i];
int* parents = M->pa[i];
int type = theta_types[i];
int count_parents = 0;
int count_child = 0;
int count_parents_child = 0;
for (int j = 0; j< num_unique; j++) { // loop through all observed genotypes
int* g = D[j].g;
int found = 0;
// get child present bool value
bool child_present = false;
if (g[i]) child_present = true;
// get parent set satisfied bool value
bool parents_present = true;
switch (type) { // 0 or 1 parents, conjunctive
case -1 ... 0:
for (int k = 0; k < num_parents; k++) {
if (!g[parents[k]]) parents_present = false;
}
break;
case 1: // or
for (int k = 0; k < num_parents; k++) {
if (g[parents[k]]) found++;
}
if (!found) parents_present = false;
break;
case 2: // xor
for (int k = 0; k < num_parents; k++) {
if (g[parents[k]]) found++;
}
if (found != 1) parents_present = false;
break;
}
if (child_present && parents_present) {
count_parents_child += D[j].count;
}
if (child_present) {
count_child += D[j].count;
}
if (parents_present) {
count_parents += D[j].count;
}
}
// check that the checks and additions are correct.
if (num_parents > 0) {
if (count_parents <= count_child || count_parents_child * NUM_SAMPLES_READ <= count_parents * count_child) {
return false;
}
}
}
return true;
}
// Initializes the parent fields in the model so that they can be used to find children more efficiently.
void set_theta_types(model* M, int* theta_types, int* theta_types_p) {
int num_events = M->n;
int** poset = M->P;
free_parents(M);
M->num_pa = get_int_array(num_events); // create an array that stores the sizes of parents.
M->pa = (int**) malloc(num_events * sizeof(int*)); // create an array to hold arrays of integers
// for all events, create a vector of all other events that relate to them, according to the current poset.
// Then, determine theta type if an event has > 1 parent events.
for (int i = 0; i< num_events; i++) {
vector* v = new_vector();
for (int j = 0; j< num_events; j++) {
if (poset[j][i]) {
push_back(v, j);
}
}
int num_parents = v->size;
M->num_pa[i] = num_parents;
M->pa[i] = free_vector(v, false);
if (num_parents <= 1) { // if 1 parent at most, no need for special care.
theta_types_p[i] = -1;
} else {
if (theta_types[i] < 0) { // event goes from 0/1 parents to 2+ parents
theta_types_p[i] = rand() % 3; // randomly pick between 0, 1, and 2.
} else { // carry over formula from previous iteration.
theta_types_p[i] = theta_types[i];
}
}
}
}
// imposes a total ordering on the events. Use Fisher-Yates shuffling algorithm to randomize ordering
void new_total_ordering(model* M, int* theta_types, data* D, int num_unique) {
int num_events = M->n;
// initialize new array to use.
int rand_arr[num_events];
for (int i = 0; i < num_events; i++) {
rand_arr[i] = i;
}
// establish total ordering
for (int i = num_events - 1; i >= 0; i--) {
int randy = rand() % (i + 1);
int temp = rand_arr[i];
rand_arr[i] = rand_arr[randy];
rand_arr[randy] = temp;
}
int** initial_poset = get_int_matrix(num_events, num_events);
// mark in poset.
for (int i = 0; i < num_events - 1; i++) {
initial_poset[rand_arr[i]][rand_arr[i+1]] = 1;
}
// transitive closure & theta types
int** T = get_int_matrix(num_events, num_events);
transitive_closure(initial_poset, T, num_events);
for (int i = 0; i < num_events; i++) {
int num_parents = 0;
for (int j = 0; j < num_events; j++) {
if (T[j][i]) num_parents++;
}
if (num_parents == 0) continue; // don't bother checking if there are no parents, since we're only going to remove excess edges.
int reduce = num_parents - (rand() % (num_parents + 1));
for (int j = 0; j < reduce; j++) { // delete a random relation reduce number of times.
int ith_event = rand() % num_parents;
int counted = 0;
for (int k = 0; k < num_events; k++) {
if (counted == ith_event && T[k][i]) {
T[k][i] = 0; // delete event
num_parents--; // decrement number of parents.
break;
}
if (T[k][i]) counted++;
}
}
}
free_int_matrix(initial_poset, num_events);
free_int_matrix(M->P, num_events);
M->P = T;
int* theta_types_p = get_int_array(num_events);
for (int i = 0; i < num_events; i++) {
theta_types_p[i] = -1;
}
set_theta_types(M, theta_types_p, theta_types);
model M_p;
M_p.n = num_events;
M_p.pa = M->pa;
M_p.P = T;
M_p.num_pa = get_int_array(num_events); // initializes each to 0.
// do suppes checking for each events' parent set.
for (int i = 0; i < num_events; i++) {
// determine suppes prob condition for this event and its parent set.
// copy the parent set of this event into a new poset.
theta_types_p[i] = theta_types[i];
M_p.num_pa[i] = M->num_pa[i];
if (!cumulative_probs_maintained(&M_p, D, theta_types, num_unique)) {// reject entire parent set.
for (int j = 0; j < num_events; j++) {
M->P[j][i] = 0;
}
M->num_pa[i] = 0;
theta_types[i] = -1;
}
theta_types_p[i] = -1; // push to conjunctive so that it doesn't go to 'or' and 'xor' cases.
M_p.num_pa[i] = 0; // set back to 0.
}
free_int_array(M_p.num_pa);
free_int_array(theta_types_p);
}
// returns the total number of events associated with a given genotype.
// ex. For n= 4, 0101 returns 2.
int total_events(const int genotype, const int n) {
int* binary = GENOTYPE[genotype];
int num_events = 0;
for (int i=0; i< n; i++)
num_events += binary[i];
return num_events;
}
// Given two integers, returns the number of bitwise differences between the two.
// If hamming distance > 1, returns index of last (largest) bit.
int hamming_distance(unsigned int x, unsigned int y, const int num_events, int* diff_index) {
unsigned int dist = 0;
unsigned int diff = x ^ y;
for (int i= 0; i < num_events; i++) {
if ( (1 << i) & diff ) {
dist++;
if (diff_index != NULL) *diff_index = num_events - 1 - i;
}
}
return dist;
}
// Checks that the parent conditions of the ith event are satisfied in provided genotype g.
// Returns true if parent conditions (according to poset and theta_types) are fulfilled, false otherwise.
bool check_parent_set(model* M, int* theta_types, int* g, int i) {
int num_parents = M->num_pa[i];
int type = theta_types[i]; // relationship between parents.
bool compatible = false;
int found = 0;
switch (type) { // will only go into one case for each, so this may be faster.
case -1 ... 0: // 0/1 parents, or and case if > 1 parents. loop through all parents, confirm that all are present.
for (int j = 0; j< num_parents; j++) {
if (!g[M->pa[i][j]]) return false;
}
break;
case 1: // or.
for (int j = 0; j< num_parents; j++) {
if (g[M->pa[i][j]]) {
compatible = true;
break;
}
}
if (!compatible) return false;
break;
case 2: // xor. loop through all parents, confirm that only one present at a time.
for (int j = 0; j< num_parents; j++) {
if (g[M->pa[i][j]]) { // another event observed that isn't the current
found++;
}
}
if (found != 1) return false;
break;
}
return true;
}
// Theta types gives the relationship between "parent events", if an event has more than one direct parent.
// If check_parent_set returns true for all events, then returns true.
bool compatible_with_poset(int genotype, model* M, int* theta_types) {
int num_events = M->n;
int* g = GENOTYPE[genotype];
for (int i = 0; i< num_events; i++) { // for each event
if (g[i]) { // if event is observed
if (!check_parent_set(M, theta_types, g, i)) return false;
}
}
return true;
}
#endif
| {
"alphanum_fraction": 0.6456762261,
"avg_line_length": 30.3795986622,
"ext": "h",
"hexsha": "7738e22465a1e6d7d54fbf9d24252a99c133a95e",
"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": "836575a6a5ac7d3e0cb13eea9ac5e20b8e33c2a6",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "BIMIB-DISCo/PMCE",
"max_forks_repo_path": "HESBCN/h-esbcn.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "836575a6a5ac7d3e0cb13eea9ac5e20b8e33c2a6",
"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": "BIMIB-DISCo/PMCE",
"max_issues_repo_path": "HESBCN/h-esbcn.h",
"max_line_length": 188,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "836575a6a5ac7d3e0cb13eea9ac5e20b8e33c2a6",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "BIMIB-DISCo/PMCE",
"max_stars_repo_path": "HESBCN/h-esbcn.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5326,
"size": 18167
} |
#ifndef RAYS_H
#define RAYS_H
#include <complex.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include "tsvread.h"
// A ray.
typedef struct {
double p0[3]; // position
double e0[3]; // direction
complex double pol[3]; // polarization
double OPL; // optical path length
double lambda; // wavelength
double intensity; // intensity of this paricular ray
double g; // apodisation factor
} ray_t;
ray_t *readrays(char *filename, unsigned int *nrays);
void movefocus(ray_t *ray, unsigned int nrays);
#endif // RAYS_H
| {
"alphanum_fraction": 0.6420454545,
"avg_line_length": 23.4666666667,
"ext": "h",
"hexsha": "db1de68fffd772d20d960189e1699f7fa93809e6",
"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": "ddc61f250ed2c7ad185dcaf78def714231328ef4",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "AaronWebster/directdebye",
"max_forks_repo_path": "rays.h",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4",
"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": "AaronWebster/directdebye",
"max_issues_repo_path": "rays.h",
"max_line_length": 60,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "AaronWebster/directdebye",
"max_stars_repo_path": "rays.h",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 189,
"size": 704
} |
/*
Template for applications of single array GSL functions
*/
#include <stdio.h>
#ifdef SINGLE_ARG
# include <stdlib.h>
#endif
#include <gsl/gsl_statistics_double.h>
#ifdef SORT_DATA
# include <gsl/gsl_sort.h>
#endif
#include "y.tab.h"
#include "double_matrix.h"
#define SINGLE_STEP 1
Double_Matrix *data = NULL;
int
main(int argc, char *argv[]) {
size_t i = 0;
#ifdef SINGLE_ARG
char *endptr = NULL;
double arg;
#endif
#ifdef SINGLE_ARG
if (2 != argc) {
fprintf(stderr, "Argument required.\n");
return 1;
}
arg = strtod(argv[1], &endptr);
if (0 == arg && endptr == argv[ 1 ]) {
fprintf(stderr, "Argument (%s) is not a valid number\n", argv[1]);
return 1;
}
#endif
data = double_matrix_new();
yyparse();
for (i = 0; i < double_matrix_width(data); i++) {
#ifdef SORT_DATA
gsl_sort(double_matrix_col_mut_data(data, i), SINGLE_STEP, double_matrix_depth(data));
#endif
if (0 != i)
printf( " " );
printf("%.10g",
FUNC_NAME(double_matrix_col_data(data, i), SINGLE_STEP, double_matrix_depth(data)
#ifdef SINGLE_ARG
, arg
#endif
)
);
}
printf("\n");
double_matrix_free(data);
return 0;
}
| {
"alphanum_fraction": 0.6628919861,
"avg_line_length": 15.5135135135,
"ext": "c",
"hexsha": "ccca28df1fe6f55984fac364b3e71f77a21d7482",
"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": "3686e1c674845fd9679ed02c25b8d3e0fad73373",
"max_forks_repo_licenses": [
"CC0-1.0"
],
"max_forks_repo_name": "blindsay7/gsl-tools",
"max_forks_repo_path": "gsl-template.c",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3686e1c674845fd9679ed02c25b8d3e0fad73373",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC0-1.0"
],
"max_issues_repo_name": "blindsay7/gsl-tools",
"max_issues_repo_path": "gsl-template.c",
"max_line_length": 88,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3686e1c674845fd9679ed02c25b8d3e0fad73373",
"max_stars_repo_licenses": [
"CC0-1.0"
],
"max_stars_repo_name": "blindsay7/gsl-tools",
"max_stars_repo_path": "gsl-template.c",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 323,
"size": 1148
} |
/***************************************************************************
integration.h - description
-------------------
copyright : (C) 2005 by MOUSSA
email : mmousa@liris.cnrs.fr
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef INTEGRATIONFILE
#define INTEGRATIONFILE
#include "config.h"
#include "misc.h"
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_plain.h>
#include <gsl/gsl_sf.h>
#include <gsl/gsl_complex.h>
#include <gsl/gsl_complex_math.h>
void Integrate(int , int , double , Tetrahedron_3 , gsl_complex *, gsl_complex *);
#endif
| {
"alphanum_fraction": 0.3941220799,
"avg_line_length": 40.2121212121,
"ext": "h",
"hexsha": "9ca66d8a84e3668b46db50fb40f9570fff2dd4d0",
"lang": "C",
"max_forks_count": 77,
"max_forks_repo_forks_event_max_datetime": "2022-03-24T01:03:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-10-24T22:36:29.000Z",
"max_forks_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kyeonghopark/jgt-code",
"max_forks_repo_path": "Volume_11/Number_2/Mousa2006/integration.h",
"max_issues_count": 8,
"max_issues_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73",
"max_issues_repo_issues_event_max_datetime": "2021-05-27T01:49:50.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-01-15T13:23:16.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "kyeonghopark/jgt-code",
"max_issues_repo_path": "Volume_11/Number_2/Mousa2006/integration.h",
"max_line_length": 83,
"max_stars_count": 415,
"max_stars_repo_head_hexsha": "08bbcc298e12582e32cb56a52e70344c57689d73",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kyeonghopark/jgt-code",
"max_stars_repo_path": "Volume_11/Number_2/Mousa2006/integration.h",
"max_stars_repo_stars_event_max_datetime": "2022-02-18T04:09:07.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-10-24T17:37:12.000Z",
"num_tokens": 224,
"size": 1327
} |
/* cdf/fdistinv.c
*
* Copyright (C) 2002 Przemyslaw Sliwa and Jason H. Stover.
* Copyright (C) 2006 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
#include <config.h>
#include <gsl/gsl_cdf.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_errno.h>
#include "error.h"
double
gsl_cdf_fdist_Pinv (const double P, const double nu1, const double nu2)
{
double result;
double y;
if (P < 0.0)
{
CDF_ERROR ("P < 0.0", GSL_EDOM);
}
if (P > 1.0)
{
CDF_ERROR ("P > 1.0", GSL_EDOM);
}
if (nu1 < 1.0)
{
CDF_ERROR ("nu1 < 1", GSL_EDOM);
}
if (nu2 < 1.0)
{
CDF_ERROR ("nu2 < 1", GSL_EDOM);
}
if (P < 0.5)
{
y = gsl_cdf_beta_Pinv (P, nu1 / 2.0, nu2 / 2.0);
result = nu2 * y / (nu1 * (1.0 - y));
}
else
{
y = gsl_cdf_beta_Qinv (P, nu2 / 2.0, nu1 / 2.0);
result = nu2 * (1 - y) / (nu1 * y);
}
return result;
}
double
gsl_cdf_fdist_Qinv (const double Q, const double nu1, const double nu2)
{
double result;
double y;
if (Q < 0.0)
{
CDF_ERROR ("Q < 0.0", GSL_EDOM);
}
if (Q > 1.0)
{
CDF_ERROR ("Q > 1.0", GSL_EDOM);
}
if (nu1 < 1.0)
{
CDF_ERROR ("nu1 < 1", GSL_EDOM);
}
if (nu2 < 1.0)
{
CDF_ERROR ("nu2 < 1", GSL_EDOM);
}
if (Q > 0.5)
{
y = gsl_cdf_beta_Qinv (Q, nu1 / 2.0, nu2 / 2.0);
result = nu2 * y / (nu1 * (1.0 - y));
}
else
{
y = gsl_cdf_beta_Pinv (Q, nu2 / 2.0, nu1 / 2.0);
result = nu2 * (1 - y) / (nu1 * y);
}
return result;
}
| {
"alphanum_fraction": 0.579064588,
"avg_line_length": 21.380952381,
"ext": "c",
"hexsha": "231f5c1259cd60b182e909cc39d4b93bdc2acc94",
"lang": "C",
"max_forks_count": 40,
"max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z",
"max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "manggoguy/parsec-modified",
"max_forks_repo_path": "pkgs/libs/gsl/src/cdf/fdistinv.c",
"max_issues_count": 12,
"max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "manggoguy/parsec-modified",
"max_issues_repo_path": "pkgs/libs/gsl/src/cdf/fdistinv.c",
"max_line_length": 77,
"max_stars_count": 64,
"max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "manggoguy/parsec-modified",
"max_stars_repo_path": "pkgs/libs/gsl/src/cdf/fdistinv.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": 793,
"size": 2245
} |
/*
** use median of trials
**
** G.Lohmann, May 2016
*/
#include <viaio/Vlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_statistics.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_permutation.h>
#include <gsl/gsl_sort_vector.h>
extern void VNormalize(float *data,int nt,VBoolean stddev);
extern void GetRank(float *data,gsl_vector *v,gsl_permutation *perm,gsl_permutation *rank);
void GetMedian(gsl_matrix_float **X1,gsl_matrix_float **X2,int *table,int n,gsl_matrix_float *SNR,int metric)
{
long j,nvox=X1[0]->size1;
long k,s,nt=X1[0]->size2;
double *data = (double *) VCalloc(n,sizeof(double));
double median = 0;
gsl_vector *vec = NULL;
gsl_permutation *perm = NULL;
gsl_permutation *rank = NULL;
if (metric == 1) {
vec = gsl_vector_calloc(nt);
perm = gsl_permutation_alloc(nt);
rank = gsl_permutation_alloc(nt);
}
/* for each voxel ... */
for (j=0; j<nvox; j++) {
for (k=0; k<nt; k++) {
for (s=0; s<n; s++) {
if (table[s] == 0)
data[s] = (double)gsl_matrix_float_get(X1[s],j,k);
else
data[s] = (double)gsl_matrix_float_get(X2[s],j,k);
}
gsl_sort(data,1,n);
median = gsl_stats_median_from_sorted_data (data,1,(size_t) n);
gsl_matrix_float_set(SNR,j,k,(float)median);
}
if (metric == 0) { /* pearson correlation */
float *qq = gsl_matrix_float_ptr(SNR,j,0);
VNormalize(qq,nt,TRUE);
}
if (metric == 1) { /* spearman ranks */
float *qq = gsl_matrix_float_ptr(SNR,j,0);
GetRank(qq,vec,perm,rank);
}
}
VFree(data);
if (metric == 1) {
gsl_permutation_free (perm);
gsl_permutation_free (rank);
gsl_vector_free(vec);
}
}
| {
"alphanum_fraction": 0.642699115,
"avg_line_length": 25.1111111111,
"ext": "c",
"hexsha": "3f1ed3e5b13669d83f91700659d48adadf5b4f9d",
"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/ted/vted/Median.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/ted/vted/Median.c",
"max_line_length": 109,
"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/ted/vted/Median.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": 569,
"size": 1808
} |
#pragma once
#include "movie_writer.h"
#include <boost/math/tools/roots.hpp>
#include <cxxopts.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/string_cast.hpp>
#include <gsl/gsl_integration.h>
#include <omp.h>
#include <opencv2/opencv.hpp>
#include <QApplication>
#include <QCheckBox>
#include <QGraphicsView>
#include <QGuiApplication>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QMainWindow>
#include <QMenuBar>
#include <QPushButton>
#include <QVBoxLayout>
#include <QFileDialog>
#include <QGraphicsPixmapItem>
#include <QPixmap>
#include <array>
#include <chrono>
#include <cmath>
#include <filesystem>
#include <iostream>
#include <random>
#include <thread>
#include <vector> | {
"alphanum_fraction": 0.7620286086,
"avg_line_length": 21.3611111111,
"ext": "h",
"hexsha": "1e80951a566317cbe2c81c4106a9c3466581b031",
"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": "d0187d17d5fee01a754fd3bc19353a53caacc1b0",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "evopen/blackness",
"max_forks_repo_path": "src/pch.h",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "d0187d17d5fee01a754fd3bc19353a53caacc1b0",
"max_issues_repo_issues_event_max_datetime": "2020-04-27T17:56:50.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-04-27T00:28:17.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "evopen/blackness",
"max_issues_repo_path": "src/pch.h",
"max_line_length": 39,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "d0187d17d5fee01a754fd3bc19353a53caacc1b0",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "evopen/blackness",
"max_stars_repo_path": "src/pch.h",
"max_stars_repo_stars_event_max_datetime": "2021-07-27T06:50:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-04-26T12:35:30.000Z",
"num_tokens": 182,
"size": 769
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.